code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
# -*- coding: utf-8 -*- # # yara documentation build configuration file, created by # sphinx-quickstart on Tue Jul 8 11:04:03 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'yara' copyright = u'2014-2019, VirusTotal' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '3.9' # The full version, including alpha/beta/rc tags. release = '3.9.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. try: import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except: html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'yaradoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'yara.tex', u'yara Documentation', u'Victor M. Alvarez', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'yara', u'yara Documentation', [u'Victor M. Alvarez'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'yara', u'yara Documentation', u'Victor M. Alvarez', 'yara', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
Masood-M/yalih
req/yara-3.9.0/docs/conf.py
Python
apache-2.0
8,265
/** * 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. */ package org.apache.hadoop.hive.ql.exec.spark.status.impl; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.JavaSparkListener; import org.apache.spark.executor.TaskMetrics; import org.apache.spark.scheduler.SparkListenerJobStart; import org.apache.spark.scheduler.SparkListenerTaskEnd; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class JobMetricsListener extends JavaSparkListener { private static final Logger LOG = LoggerFactory.getLogger(JobMetricsListener.class); private final Map<Integer, int[]> jobIdToStageId = Maps.newHashMap(); private final Map<Integer, Integer> stageIdToJobId = Maps.newHashMap(); private final Map<Integer, Map<String, List<TaskMetrics>>> allJobMetrics = Maps.newHashMap(); @Override public synchronized void onTaskEnd(SparkListenerTaskEnd taskEnd) { int stageId = taskEnd.stageId(); int stageAttemptId = taskEnd.stageAttemptId(); String stageIdentifier = stageId + "_" + stageAttemptId; Integer jobId = stageIdToJobId.get(stageId); if (jobId == null) { LOG.warn("Can not find job id for stage[" + stageId + "]."); } else { Map<String, List<TaskMetrics>> jobMetrics = allJobMetrics.get(jobId); if (jobMetrics == null) { jobMetrics = Maps.newHashMap(); allJobMetrics.put(jobId, jobMetrics); } List<TaskMetrics> stageMetrics = jobMetrics.get(stageIdentifier); if (stageMetrics == null) { stageMetrics = Lists.newLinkedList(); jobMetrics.put(stageIdentifier, stageMetrics); } stageMetrics.add(taskEnd.taskMetrics()); } } @Override public synchronized void onJobStart(SparkListenerJobStart jobStart) { int jobId = jobStart.jobId(); int size = jobStart.stageIds().size(); int[] intStageIds = new int[size]; for (int i = 0; i < size; i++) { Integer stageId = (Integer) jobStart.stageIds().apply(i); intStageIds[i] = stageId; stageIdToJobId.put(stageId, jobId); } jobIdToStageId.put(jobId, intStageIds); } public synchronized Map<String, List<TaskMetrics>> getJobMetric(int jobId) { return allJobMetrics.get(jobId); } public synchronized void cleanup(int jobId) { allJobMetrics.remove(jobId); jobIdToStageId.remove(jobId); Iterator<Map.Entry<Integer, Integer>> iterator = stageIdToJobId.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, Integer> entry = iterator.next(); if (entry.getValue() == jobId) { iterator.remove(); } } } }
BUPTAnderson/apache-hive-2.1.1-src
ql/src/java/org/apache/hadoop/hive/ql/exec/spark/status/impl/JobMetricsListener.java
Java
apache-2.0
3,467
package servicios.validacion; public final class RegexValidation { public static final class ValidaNombres { private ValidaNombres() { } // public static final String INICIALES = "[a-z,A-Z,ñ,Ñ]{2}$+"; public static final String NOMBRE = "[A-Z]+[a-z,ñ]*+[ ]+[A-Z]+[a-z,ñ]*"; } public static final class ValidaTel { private ValidaTel() { } public static final String NUMEROTEL = "[+]?[0-9]{3}+[-]+[0-9]{7}"; } public static final class ValidaMail { private ValidaMail() { } public static final String EMAIL = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; } public static final class ValidaDireccion{ private ValidaDireccion() { } public static final String DIRECCION = "^[_A-Za-z-\\+]+(\\ [0-9-]+)$"; } public static final class ValidaPalabra{ private ValidaPalabra() { } public static final String PALABRA = "[a-zA-Z]*$"; public static final String PALABRAINICIALMAYUSCULA = "[A-Z]+[a-z]*$"; } }
TesisTarjetasMejorar/TarjetasISIS
dom/src/main/java/servicios/validacion/RegexValidation.java
Java
apache-2.0
1,016
#!/usr/bin/env node /** * Copyright IBM Corp. 2019, 2019 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable no-console */ 'use strict'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', (error) => { console.error(error); }); var chalk = require('chalk'); var currentNodeVersion = process.versions.node; var semver = currentNodeVersion.split('.'); var major = semver[0]; if (major < 14) { console.error( chalk.red( `You are running Node ${currentNodeVersion}.\n` + `carbon-upgrade requires Node 14 or higher, please update your ` + `version of Node.` ) ); process.exit(1); } var main = require('../src/cli'); main(process).catch((error) => { console.error(error); process.exit(1); });
carbon-design-system/carbon-components
packages/upgrade/bin/carbon-upgrade.js
JavaScript
apache-2.0
1,034
var studio_locale = {lc:{"ar":function(n){ if (n === 0) { return 'zero'; } if (n == 1) { return 'one'; } if (n == 2) { return 'two'; } if ((n % 100) >= 3 && (n % 100) <= 10 && n == Math.floor(n)) { return 'few'; } if ((n % 100) >= 11 && (n % 100) <= 99 && n == Math.floor(n)) { return 'many'; } return 'other'; },"en":function(n){return n===1?"one":"other"},"bg":function(n){return n===1?"one":"other"},"bn":function(n){return n===1?"one":"other"},"ca":function(n){return n===1?"one":"other"},"cs":function(n){ if (n == 1) { return 'one'; } if (n == 2 || n == 3 || n == 4) { return 'few'; } return 'other'; },"da":function(n){return n===1?"one":"other"},"de":function(n){return n===1?"one":"other"},"el":function(n){return n===1?"one":"other"},"es":function(n){return n===1?"one":"other"},"et":function(n){return n===1?"one":"other"},"eu":function(n){return n===1?"one":"other"},"fa":function(n){return "other"},"fi":function(n){return n===1?"one":"other"},"fil":function(n){return n===0||n==1?"one":"other"},"fr":function(n){return Math.floor(n)===0||Math.floor(n)==1?"one":"other"},"ga":function(n){return n==1?"one":(n==2?"two":"other")},"gl":function(n){return n===1?"one":"other"},"he":function(n){return n===1?"one":"other"},"hi":function(n){return n===0||n==1?"one":"other"},"hr":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"hu":function(n){return "other"},"id":function(n){return "other"},"is":function(n){ return ((n%10) === 1 && (n%100) !== 11) ? 'one' : 'other'; },"it":function(n){return n===1?"one":"other"},"ja":function(n){return "other"},"ko":function(n){return "other"},"lt":function(n){ if ((n % 10) == 1 && ((n % 100) < 11 || (n % 100) > 19)) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 9 && ((n % 100) < 11 || (n % 100) > 19) && n == Math.floor(n)) { return 'few'; } return 'other'; },"lv":function(n){ if (n === 0) { return 'zero'; } if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } return 'other'; },"mk":function(n){return (n%10)==1&&n!=11?"one":"other"},"mr":function(n){return n===1?"one":"other"},"ms":function(n){return "other"},"mt":function(n){ if (n == 1) { return 'one'; } if (n === 0 || ((n % 100) >= 2 && (n % 100) <= 4 && n == Math.floor(n))) { return 'few'; } if ((n % 100) >= 11 && (n % 100) <= 19 && n == Math.floor(n)) { return 'many'; } return 'other'; },"nl":function(n){return n===1?"one":"other"},"no":function(n){return n===1?"one":"other"},"pl":function(n){ if (n == 1) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || n != 1 && (n % 10) == 1 || ((n % 10) >= 5 && (n % 10) <= 9 || (n % 100) >= 12 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"pt":function(n){return n===1?"one":"other"},"ro":function(n){ if (n == 1) { return 'one'; } if (n === 0 || n != 1 && (n % 100) >= 1 && (n % 100) <= 19 && n == Math.floor(n)) { return 'few'; } return 'other'; },"ru":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"sk":function(n){ if (n == 1) { return 'one'; } if (n == 2 || n == 3 || n == 4) { return 'few'; } return 'other'; },"sl":function(n){ if ((n % 100) == 1) { return 'one'; } if ((n % 100) == 2) { return 'two'; } if ((n % 100) == 3 || (n % 100) == 4) { return 'few'; } return 'other'; },"sq":function(n){return n===1?"one":"other"},"sr":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"sv":function(n){return n===1?"one":"other"},"ta":function(n){return n===1?"one":"other"},"th":function(n){return "other"},"tr":function(n){return n===1?"one":"other"},"uk":function(n){ if ((n % 10) == 1 && (n % 100) != 11) { return 'one'; } if ((n % 10) >= 2 && (n % 10) <= 4 && ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) { return 'few'; } if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) || ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) { return 'many'; } return 'other'; },"ur":function(n){return n===1?"one":"other"},"vi":function(n){return "other"},"zh":function(n){return "other"}}, c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")}, n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)}, v:function(d,k){studio_locale.c(d,k);return d[k]}, p:function(d,k,o,l,p){studio_locale.c(d,k);return d[k] in p?p[d[k]]:(k=studio_locale.lc[l](d[k]-o),k in p?p[k]:p.other)}, s:function(d,k,p){studio_locale.c(d,k);return d[k] in p?p[d[k]]:p.other}}; (window.blockly = window.blockly || {}).studio_locale = { "actor":function(d){return "herec"}, "addItems1":function(d){return "přidat 1 položku typu"}, "addItems2":function(d){return "přidat 2 položky typu"}, "addItems3":function(d){return "přidat 3 položky typu"}, "addItems5":function(d){return "přidat 5 položek typu"}, "addItems10":function(d){return "přidat 10 položek typu"}, "addItemsRandom":function(d){return "přidat náhodné položky typu"}, "addItemsTooltip":function(d){return "Přidat položky na scénu."}, "alienInvasion":function(d){return "Mimozemská invaze!"}, "backgroundBlack":function(d){return "černý"}, "backgroundCave":function(d){return "jeskyně"}, "backgroundCloudy":function(d){return "zataženo"}, "backgroundHardcourt":function(d){return "tvrdé hřiště"}, "backgroundNight":function(d){return "noc"}, "backgroundUnderwater":function(d){return "pod vodou"}, "backgroundCity":function(d){return "město"}, "backgroundDesert":function(d){return "poušť"}, "backgroundRainbow":function(d){return "duha"}, "backgroundSoccer":function(d){return "fotbal"}, "backgroundSpace":function(d){return "vesmír"}, "backgroundTennis":function(d){return "tenis"}, "backgroundWinter":function(d){return "zima"}, "catActions":function(d){return "Akce"}, "catControl":function(d){return "Smyčky"}, "catEvents":function(d){return "Události"}, "catLogic":function(d){return "Logika"}, "catMath":function(d){return "Matematika"}, "catProcedures":function(d){return "Funkce"}, "catText":function(d){return "text"}, "catVariables":function(d){return "Proměnné"}, "changeScoreTooltip":function(d){return "Přidat nebo odebrat bod ze skóre."}, "changeScoreTooltipK1":function(d){return "Přidat bod."}, "continue":function(d){return "Pokračovat"}, "decrementPlayerScore":function(d){return "Odebrat bod"}, "defaultSayText":function(d){return "Piš zde"}, "dropletBlock_changeScore_description":function(d){return "Přidat nebo odebrat bod ze skóre."}, "dropletBlock_penColour_description":function(d){return "Sets the color of the line drawn behind the turtle as it moves"}, "dropletBlock_penColour_param0":function(d){return "color"}, "dropletBlock_setBackground_description":function(d){return "Nastavit obrázek pozadí"}, "dropletBlock_setSpriteEmotion_description":function(d){return "Nastaví náladu herce"}, "dropletBlock_setSpritePosition_description":function(d){return "Okamžitě přesune herce na zadané místo."}, "dropletBlock_setSpriteSpeed_description":function(d){return "Nastaví rychlost herce"}, "dropletBlock_setSprite_description":function(d){return "Nastaví obrázek herce"}, "dropletBlock_throw_description":function(d){return "Hodí střelu od zadaného herce."}, "dropletBlock_vanish_description":function(d){return "Herec zmizí."}, "emotion":function(d){return "nálada"}, "finalLevel":function(d){return "Dobrá práce! Vyřešil si poslední hádanku."}, "for":function(d){return "pro"}, "hello":function(d){return "ahoj"}, "helloWorld":function(d){return "Ahoj světe!"}, "incrementPlayerScore":function(d){return "Bod"}, "itemBlueFireball":function(d){return "modrá ohnivá koule"}, "itemPurpleFireball":function(d){return "fialová ohnivá koule"}, "itemRedFireball":function(d){return "červená ohnivá koule"}, "itemYellowHearts":function(d){return "žlutá srdce"}, "itemPurpleHearts":function(d){return "fialová srdce"}, "itemRedHearts":function(d){return "červená srdce"}, "itemRandom":function(d){return "náhodně"}, "itemAnna":function(d){return "hák"}, "itemElsa":function(d){return "jiskra"}, "itemHiro":function(d){return "mikroboti"}, "itemBaymax":function(d){return "raketa"}, "itemRapunzel":function(d){return "pánev"}, "itemCherry":function(d){return "třešeň"}, "itemIce":function(d){return "led"}, "itemDuck":function(d){return "kachna"}, "makeProjectileDisappear":function(d){return "zmizet"}, "makeProjectileBounce":function(d){return "odrazit"}, "makeProjectileBlueFireball":function(d){return "udělej modrou ohnivou kouli"}, "makeProjectilePurpleFireball":function(d){return "udělej fialovou ohnivou kouli"}, "makeProjectileRedFireball":function(d){return "udělej červenou ohnivou kouli"}, "makeProjectileYellowHearts":function(d){return "udělej žlutá srdce"}, "makeProjectilePurpleHearts":function(d){return "udělej fialová srdce"}, "makeProjectileRedHearts":function(d){return "udělej červená srdce"}, "makeProjectileTooltip":function(d){return "Nechat střelu narazit a zmizet nebo odrazit."}, "makeYourOwn":function(d){return "Vytvořit si vlastní hru v Hravé laboratoři"}, "moveDirectionDown":function(d){return "dolů"}, "moveDirectionLeft":function(d){return "vlevo"}, "moveDirectionRight":function(d){return "vpravo"}, "moveDirectionUp":function(d){return "nahoru"}, "moveDirectionRandom":function(d){return "náhodně"}, "moveDistance25":function(d){return "25 pixelů"}, "moveDistance50":function(d){return "50 pixelů"}, "moveDistance100":function(d){return "100 pixelů"}, "moveDistance200":function(d){return "200 pixelů"}, "moveDistance400":function(d){return "400 pixelů"}, "moveDistancePixels":function(d){return "pixely"}, "moveDistanceRandom":function(d){return "náhodné pixely"}, "moveDistanceTooltip":function(d){return "Přemístit herce určenou vzdálenost ve specifickém směru."}, "moveSprite":function(d){return "pohyb"}, "moveSpriteN":function(d){return "pohnout hercem "+studio_locale.v(d,"spriteIndex")}, "toXY":function(d){return "do x,y"}, "moveDown":function(d){return "pohyb dolů"}, "moveDownTooltip":function(d){return "pohnout hercem dolů."}, "moveLeft":function(d){return "pohnout vlevo"}, "moveLeftTooltip":function(d){return "pohnout hercem vlevo."}, "moveRight":function(d){return "pohnout vpravo"}, "moveRightTooltip":function(d){return "pohnout hercem vpravo."}, "moveUp":function(d){return "pohnout nahoru"}, "moveUpTooltip":function(d){return "pohnout hercem nahoru."}, "moveTooltip":function(d){return "pohnout hercem."}, "nextLevel":function(d){return "Dobrá práce! Dokončil jsi tuto hádanku."}, "no":function(d){return "Ne"}, "numBlocksNeeded":function(d){return "Tato hádanka může být vyřešena pomocí %1 bloků."}, "onEventTooltip":function(d){return "Spustit kód v reakci na konkrétní událost."}, "ouchExclamation":function(d){return "Au!"}, "playSoundCrunch":function(d){return "přehrát zvuk křupání"}, "playSoundGoal1":function(d){return "přehrát zvuk cíl 1"}, "playSoundGoal2":function(d){return "přehrát zvuk cíl 2"}, "playSoundHit":function(d){return "přehrát zvuk zásah"}, "playSoundLosePoint":function(d){return "přehrát zvuk ztráta bodu"}, "playSoundLosePoint2":function(d){return "přehrát zvuk ztráta bodu 2"}, "playSoundRetro":function(d){return "přehrát zvuk \"retro\""}, "playSoundRubber":function(d){return "přehrát zvuk guma"}, "playSoundSlap":function(d){return "přehrát zvuk plácnutí"}, "playSoundTooltip":function(d){return "Přehraj vybraný zvuk."}, "playSoundWinPoint":function(d){return "přehrát zvuk získaný bod"}, "playSoundWinPoint2":function(d){return "přehrát zvuk získaný bod 2"}, "playSoundWood":function(d){return "přehrát zvuk dřevo"}, "positionOutTopLeft":function(d){return "na pozici nad horní levou pozicí"}, "positionOutTopRight":function(d){return "na pozici nad horní pravou pozicí"}, "positionTopOutLeft":function(d){return "na horní vnější levou pozici"}, "positionTopLeft":function(d){return "na horní levou pozici"}, "positionTopCenter":function(d){return "na horní středovou pozici"}, "positionTopRight":function(d){return "na horní pravou pozici"}, "positionTopOutRight":function(d){return "na horní vnější pravou pozici"}, "positionMiddleLeft":function(d){return "na střední levou pozici"}, "positionMiddleCenter":function(d){return "na prostřední středovou pozici"}, "positionMiddleRight":function(d){return "na prostřední pravou pozici"}, "positionBottomOutLeft":function(d){return "na spodní vnější levou pozici"}, "positionBottomLeft":function(d){return "na spodní levou pozici"}, "positionBottomCenter":function(d){return "na spodní středovou pozici"}, "positionBottomRight":function(d){return "na spodní pravou pozici"}, "positionBottomOutRight":function(d){return "na spodní vnější pravou pozici"}, "positionOutBottomLeft":function(d){return "na pozici pod spodní levou pozicí"}, "positionOutBottomRight":function(d){return "na pozici pod spodní pravou pozicí"}, "positionRandom":function(d){return "na náhodnou pozici"}, "projectileBlueFireball":function(d){return "modrá ohnivá koule"}, "projectilePurpleFireball":function(d){return "fialová ohnivá koule"}, "projectileRedFireball":function(d){return "červená ohnivá koule"}, "projectileYellowHearts":function(d){return "žlutá srdce"}, "projectilePurpleHearts":function(d){return "fialová srdce"}, "projectileRedHearts":function(d){return "červená srdce"}, "projectileRandom":function(d){return "náhodně"}, "projectileAnna":function(d){return "hák"}, "projectileElsa":function(d){return "jiskra"}, "projectileHiro":function(d){return "mikroboti"}, "projectileBaymax":function(d){return "raketa"}, "projectileRapunzel":function(d){return "pánev"}, "projectileCherry":function(d){return "třešeň"}, "projectileIce":function(d){return "led"}, "projectileDuck":function(d){return "kachna"}, "reinfFeedbackMsg":function(d){return "Můžeš stisknout tlačítko \"Pokračovat v hraní\" pro návrat do hraní tvé historie."}, "repeatForever":function(d){return "opakujte navždy"}, "repeatDo":function(d){return "dělej"}, "repeatForeverTooltip":function(d){return "Provést akce v tomto bloku opakovaně dokud je spuštěn příběh."}, "saySprite":function(d){return "řekni"}, "saySpriteN":function(d){return "herec "+studio_locale.v(d,"spriteIndex")+" říká"}, "saySpriteTooltip":function(d){return "Zobrazit komiksovou bublinu s přidruženým textem od zvoleného herece."}, "saySpriteChoices_0":function(d){return "Ahoj."}, "saySpriteChoices_1":function(d){return "Ahoj všichni."}, "saySpriteChoices_2":function(d){return "Jak se máš?"}, "saySpriteChoices_3":function(d){return "Dobré ráno"}, "saySpriteChoices_4":function(d){return "Dobré odpoledne"}, "saySpriteChoices_5":function(d){return "Dobrou noc"}, "saySpriteChoices_6":function(d){return "Dobrý večer"}, "saySpriteChoices_7":function(d){return "Co je nového?"}, "saySpriteChoices_8":function(d){return "Co?"}, "saySpriteChoices_9":function(d){return "Kde?"}, "saySpriteChoices_10":function(d){return "Kdy?"}, "saySpriteChoices_11":function(d){return "Dobře."}, "saySpriteChoices_12":function(d){return "Skvělé!"}, "saySpriteChoices_13":function(d){return "Dobře."}, "saySpriteChoices_14":function(d){return "Není to zlé."}, "saySpriteChoices_15":function(d){return "Hodně štěstí."}, "saySpriteChoices_16":function(d){return "Ano"}, "saySpriteChoices_17":function(d){return "Ne"}, "saySpriteChoices_18":function(d){return "Dobře"}, "saySpriteChoices_19":function(d){return "Pěkný hod!"}, "saySpriteChoices_20":function(d){return "Hezký den."}, "saySpriteChoices_21":function(d){return "Ahoj."}, "saySpriteChoices_22":function(d){return "Hned jsem zpátky."}, "saySpriteChoices_23":function(d){return "Zítra ahoj!"}, "saySpriteChoices_24":function(d){return "Zatím se měj!"}, "saySpriteChoices_25":function(d){return "Opatruj se!"}, "saySpriteChoices_26":function(d){return "Užijte si!"}, "saySpriteChoices_27":function(d){return "Musím jít."}, "saySpriteChoices_28":function(d){return "Chcete být přátelé?"}, "saySpriteChoices_29":function(d){return "Skvělá práce!"}, "saySpriteChoices_30":function(d){return "Pane jo!"}, "saySpriteChoices_31":function(d){return "Jaj!"}, "saySpriteChoices_32":function(d){return "Těší mě."}, "saySpriteChoices_33":function(d){return "Dobře!"}, "saySpriteChoices_34":function(d){return "Děkuji"}, "saySpriteChoices_35":function(d){return "Ne, děkuji"}, "saySpriteChoices_36":function(d){return "Aaaaaah!"}, "saySpriteChoices_37":function(d){return "Nevadí"}, "saySpriteChoices_38":function(d){return "Dnes"}, "saySpriteChoices_39":function(d){return "Zítra"}, "saySpriteChoices_40":function(d){return "Včera"}, "saySpriteChoices_41":function(d){return "Našel jsem tě!"}, "saySpriteChoices_42":function(d){return "Našel si mě!"}, "saySpriteChoices_43":function(d){return "10, 9, 8, 7, 6, 5, 4, 3, 2, 1!"}, "saySpriteChoices_44":function(d){return "Jsi skvělý!"}, "saySpriteChoices_45":function(d){return "Jsi vtipný!"}, "saySpriteChoices_46":function(d){return "Jsi pošetilý! "}, "saySpriteChoices_47":function(d){return "Jsi dobrý přítel!"}, "saySpriteChoices_48":function(d){return "Dávej pozor!"}, "saySpriteChoices_49":function(d){return "Kachna!"}, "saySpriteChoices_50":function(d){return "Mám tě!"}, "saySpriteChoices_51":function(d){return "Au!"}, "saySpriteChoices_52":function(d){return "Promiň!"}, "saySpriteChoices_53":function(d){return "Opatrně!"}, "saySpriteChoices_54":function(d){return "Uau!"}, "saySpriteChoices_55":function(d){return "Ups!"}, "saySpriteChoices_56":function(d){return "Skoro si mě dostal!"}, "saySpriteChoices_57":function(d){return "Dobrý pokus!"}, "saySpriteChoices_58":function(d){return "Nemůžeš mě chytit!"}, "scoreText":function(d){return "Body: "+studio_locale.v(d,"playerScore")}, "setBackground":function(d){return "nastavit pozadí"}, "setBackgroundRandom":function(d){return "nastavit náhodné pozadí"}, "setBackgroundBlack":function(d){return "nastavit černé pozadí"}, "setBackgroundCave":function(d){return "nastavit pozadí jeskyně"}, "setBackgroundCloudy":function(d){return "nastavit pozadí mraky"}, "setBackgroundHardcourt":function(d){return "nastavit pozadí tvrdé hřiště"}, "setBackgroundNight":function(d){return "nastavit pozadí noc"}, "setBackgroundUnderwater":function(d){return "nastavit pozadí pod vodou"}, "setBackgroundCity":function(d){return "nastavit pozadí město"}, "setBackgroundDesert":function(d){return "nastavit pozadí poušť"}, "setBackgroundRainbow":function(d){return "nastavit pozadí duha"}, "setBackgroundSoccer":function(d){return "nastavit pozadí fotbal"}, "setBackgroundSpace":function(d){return "nastavit pozadí vesmír"}, "setBackgroundTennis":function(d){return "nastavit pozadí tenis"}, "setBackgroundWinter":function(d){return "nastavit pozadí zima"}, "setBackgroundLeafy":function(d){return "nastavit listnaté pozadí"}, "setBackgroundGrassy":function(d){return "nastavit travnaté pozadí"}, "setBackgroundFlower":function(d){return "nastavit květinové pozadí"}, "setBackgroundTile":function(d){return "nastavit dlaždicové pozadí"}, "setBackgroundIcy":function(d){return "nastavit ledové pozadí"}, "setBackgroundSnowy":function(d){return "nastavit zasněžené pozadí"}, "setBackgroundTooltip":function(d){return "Nastavit obrázek pozadí"}, "setEnemySpeed":function(d){return "nastavit rychlost protivníka"}, "setPlayerSpeed":function(d){return "nastavit rychlost hráče"}, "setScoreText":function(d){return "nastavit body"}, "setScoreTextTooltip":function(d){return "Nastaví text, který se má zobrazit v oblasti pro výsledek."}, "setSpriteEmotionAngry":function(d){return "na nahněvanou náladu"}, "setSpriteEmotionHappy":function(d){return "na šťastnou náladu"}, "setSpriteEmotionNormal":function(d){return "na normální náladu"}, "setSpriteEmotionRandom":function(d){return "na náhodnou náladu"}, "setSpriteEmotionSad":function(d){return "na smutnou náladu"}, "setSpriteEmotionTooltip":function(d){return "Nastaví náladu herce"}, "setSpriteAlien":function(d){return "na obrázek mimozemšťana"}, "setSpriteBat":function(d){return "na obrázek netopýra"}, "setSpriteBird":function(d){return "na obrázek ptáka"}, "setSpriteCat":function(d){return "na obrázek kočky"}, "setSpriteCaveBoy":function(d){return "na obrázek jeskynního chlapece"}, "setSpriteCaveGirl":function(d){return "na obrázek jeskynní dívky"}, "setSpriteDinosaur":function(d){return "na obrázek dinosaura"}, "setSpriteDog":function(d){return "na obrázek psa"}, "setSpriteDragon":function(d){return "na obrázek draka"}, "setSpriteGhost":function(d){return "na obrázek ducha"}, "setSpriteHidden":function(d){return "na skrytý obrázek"}, "setSpriteHideK1":function(d){return "skrýt"}, "setSpriteAnna":function(d){return "na Anin obrázek"}, "setSpriteElsa":function(d){return "na Elsin obrázek"}, "setSpriteHiro":function(d){return "na obrázek Hira"}, "setSpriteBaymax":function(d){return "na obrázek Baymaxe"}, "setSpriteRapunzel":function(d){return "na obrázek Rapunzela"}, "setSpriteKnight":function(d){return "na obrázek rytíře"}, "setSpriteMonster":function(d){return "na obrázek příšery"}, "setSpriteNinja":function(d){return "na obrázek maskovaného ninjy"}, "setSpriteOctopus":function(d){return "na obrázek chobotnice"}, "setSpritePenguin":function(d){return "na obrázek tučňáka"}, "setSpritePirate":function(d){return "na obrázek piráta"}, "setSpritePrincess":function(d){return "na obrázek princezny"}, "setSpriteRandom":function(d){return "na náhodný obrázek"}, "setSpriteRobot":function(d){return "na obrázek robota"}, "setSpriteShowK1":function(d){return "zobrazit"}, "setSpriteSpacebot":function(d){return "na obrázek vesmírného robota"}, "setSpriteSoccerGirl":function(d){return "na obrázek fotbalistky"}, "setSpriteSoccerBoy":function(d){return "na obrázek fotbalisty"}, "setSpriteSquirrel":function(d){return "na obrázek veverky"}, "setSpriteTennisGirl":function(d){return "na obrázek tenistky"}, "setSpriteTennisBoy":function(d){return "na obrázek tenisty"}, "setSpriteUnicorn":function(d){return "na obrázek jednorožce"}, "setSpriteWitch":function(d){return "na obrázek čarodějnice"}, "setSpriteWizard":function(d){return "na obrázek čaroděje"}, "setSpritePositionTooltip":function(d){return "Okamžitě přesune herce na zadané místo."}, "setSpriteK1Tooltip":function(d){return "Zobrazí nebo skryje zadaného herce."}, "setSpriteTooltip":function(d){return "Nastaví obrázek herce"}, "setSpriteSizeRandom":function(d){return "na náhodnou velikost"}, "setSpriteSizeVerySmall":function(d){return "na velmi malou velikost"}, "setSpriteSizeSmall":function(d){return "na malou velikost"}, "setSpriteSizeNormal":function(d){return "na normální velikost"}, "setSpriteSizeLarge":function(d){return "na velkou velikost"}, "setSpriteSizeVeryLarge":function(d){return "na velmi velkou velikost"}, "setSpriteSizeTooltip":function(d){return "Nastaví velikost herce"}, "setSpriteSpeedRandom":function(d){return "na náhodnou rychlost"}, "setSpriteSpeedVerySlow":function(d){return "na velmi pomalou rychlost"}, "setSpriteSpeedSlow":function(d){return "na pomalou rychlost"}, "setSpriteSpeedNormal":function(d){return "na normální rychlost"}, "setSpriteSpeedFast":function(d){return "na rychlou rychlost"}, "setSpriteSpeedVeryFast":function(d){return "na velmi rychlou rychlost"}, "setSpriteSpeedTooltip":function(d){return "Nastaví rychlost herce"}, "setSpriteZombie":function(d){return "na obrázek zombie"}, "shareStudioTwitter":function(d){return "Podívejte se na aplikaci, kterou jsem udělal. Napsal jsem to sám s @codeorg"}, "shareGame":function(d){return "Sdílej svůj příběh:"}, "showCoordinates":function(d){return "Zobrazit souřadnice"}, "showCoordinatesTooltip":function(d){return "zobrazí souřadnice hlavní postavy na obrazovce"}, "showTitleScreen":function(d){return "zobrazit úvodní obrazovku"}, "showTitleScreenTitle":function(d){return "nadpis"}, "showTitleScreenText":function(d){return "text"}, "showTSDefTitle":function(d){return "zde napiš nadpis"}, "showTSDefText":function(d){return "zde napiš text"}, "showTitleScreenTooltip":function(d){return "Zobrazit úvodní obrazovka k přidruženému názvu a textu."}, "size":function(d){return "velikost"}, "setSprite":function(d){return "nastavit"}, "setSpriteN":function(d){return "nastavit herece "+studio_locale.v(d,"spriteIndex")}, "soundCrunch":function(d){return "křupnutí"}, "soundGoal1":function(d){return "cíl 1"}, "soundGoal2":function(d){return "cíl 2"}, "soundHit":function(d){return "zásah"}, "soundLosePoint":function(d){return "ztracený bod"}, "soundLosePoint2":function(d){return "ztracený bod 2"}, "soundRetro":function(d){return "retro"}, "soundRubber":function(d){return "guma"}, "soundSlap":function(d){return "facka"}, "soundWinPoint":function(d){return "vyhraný bod"}, "soundWinPoint2":function(d){return "vyhraný bod 2"}, "soundWood":function(d){return "dřevo"}, "speed":function(d){return "rychlost"}, "startSetValue":function(d){return "start (funkce)"}, "startSetVars":function(d){return "game_vars (nadpis, podnadpis, pozadí, cíl, nebezpečí, hráč)"}, "startSetFuncs":function(d){return "game_funcs (aktualizuj-cíl, aktualizuj-nebezpečí, aktualizuj-hráče, kolize?, na-obrazovce?)"}, "stopSprite":function(d){return "zastavit"}, "stopSpriteN":function(d){return "zastavit herce "+studio_locale.v(d,"spriteIndex")}, "stopTooltip":function(d){return "Zastaví pohyb herce."}, "throwSprite":function(d){return "hoď"}, "throwSpriteN":function(d){return "herec "+studio_locale.v(d,"spriteIndex")+" hodí"}, "throwTooltip":function(d){return "Hodí střelu od zadaného herce."}, "vanish":function(d){return "zmiz"}, "vanishActorN":function(d){return "zmiz herec "+studio_locale.v(d,"spriteIndex")}, "vanishTooltip":function(d){return "Herec zmizí."}, "waitFor":function(d){return "čekat na"}, "waitSeconds":function(d){return "sekund"}, "waitForClick":function(d){return "čekat na kliknutí"}, "waitForRandom":function(d){return "čekat na náhodně"}, "waitForHalfSecond":function(d){return "čekat půl sekundy"}, "waitFor1Second":function(d){return "čekat 1 sekundu"}, "waitFor2Seconds":function(d){return "čekat 2 sekundy"}, "waitFor5Seconds":function(d){return "čekat 5 sekund"}, "waitFor10Seconds":function(d){return "čekat 10 sekund"}, "waitParamsTooltip":function(d){return "Čeká zadaný počet sekund. Použijte nulu pro čekání na kliknutí."}, "waitTooltip":function(d){return "Čeká zadané množství času nebo dokud nedojde ke kliknutí."}, "whenArrowDown":function(d){return "šipka dolů"}, "whenArrowLeft":function(d){return "šipka vlevo"}, "whenArrowRight":function(d){return "šipka vpravo"}, "whenArrowUp":function(d){return "šipka nahoru"}, "whenArrowTooltip":function(d){return "Provést zadané akce po stisknutí klávesy se šipkou."}, "whenDown":function(d){return "když šipka dolů"}, "whenDownTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"dolů\"."}, "whenGameStarts":function(d){return "když se příběh začne"}, "whenGameStartsTooltip":function(d){return "Provést uvedené akce, když příběh začne."}, "whenLeft":function(d){return "když šipka vlevo"}, "whenLeftTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"vlevo\"."}, "whenRight":function(d){return "když šipka vpravo"}, "whenRightTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"vpravo\"."}, "whenSpriteClicked":function(d){return "po kliknutí na herce"}, "whenSpriteClickedN":function(d){return "po kliknutí na herce "+studio_locale.v(d,"spriteIndex")}, "whenSpriteClickedTooltip":function(d){return "Provést uvedené akce po kliknutí na herce."}, "whenSpriteCollidedN":function(d){return "když se herec "+studio_locale.v(d,"spriteIndex")}, "whenSpriteCollidedTooltip":function(d){return "Provést uvedené akce když se herec dotkne jiného herce."}, "whenSpriteCollidedWith":function(d){return "dotkne"}, "whenSpriteCollidedWithAnyActor":function(d){return "dotkne jiného herce"}, "whenSpriteCollidedWithAnyEdge":function(d){return "dotkne okraje"}, "whenSpriteCollidedWithAnyProjectile":function(d){return "dotkne střely"}, "whenSpriteCollidedWithAnything":function(d){return "dotkne čehokoliv"}, "whenSpriteCollidedWithN":function(d){return "dotkne herce "+studio_locale.v(d,"spriteIndex")}, "whenSpriteCollidedWithBlueFireball":function(d){return "dotkne modré ohnivé koule"}, "whenSpriteCollidedWithPurpleFireball":function(d){return "dotkne fialové ohnivé koule"}, "whenSpriteCollidedWithRedFireball":function(d){return "dotkne červené ohnivé koule"}, "whenSpriteCollidedWithYellowHearts":function(d){return "dotkne žlutých srdcí"}, "whenSpriteCollidedWithPurpleHearts":function(d){return "dotkne fialových srdcí"}, "whenSpriteCollidedWithRedHearts":function(d){return "dotkne červených srdcí"}, "whenSpriteCollidedWithBottomEdge":function(d){return "dotkne dolního okraje"}, "whenSpriteCollidedWithLeftEdge":function(d){return "dotkne levého okraje"}, "whenSpriteCollidedWithRightEdge":function(d){return "dotkne pravého okraje"}, "whenSpriteCollidedWithTopEdge":function(d){return "dotkne horního okraje"}, "whenUp":function(d){return "když šipka nahoru"}, "whenUpTooltip":function(d){return "Spusť uvedené akce když je stisknutá klávesa \"nahoru\"."}, "yes":function(d){return "Ano"}};
ty-po/code-dot-org
dashboard/public/apps-package/js/cs_cz/studio_locale-bfd0c94141f74417a2ff3e69569591ae.js
JavaScript
apache-2.0
30,817
/* * Copyright 2011 The Apache Software Foundation * * 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. */ package org.apache.hadoop.hbase.io.hfile; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.KeyValue.KeyComparator; import org.apache.hadoop.hbase.io.hfile.HFile.Writer; import org.apache.hadoop.hbase.io.hfile.HFileBlock.BlockWritable; import org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics; import org.apache.hadoop.hbase.util.ChecksumType; import org.apache.hadoop.hbase.util.BloomFilterWriter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; /** * Writes HFile format version 2. */ public class HFileWriterV2 extends AbstractHFileWriter { static final Log LOG = LogFactory.getLog(HFileWriterV2.class); /** Max memstore (mvcc) timestamp in FileInfo */ public static final byte [] MAX_MEMSTORE_TS_KEY = Bytes.toBytes("MAX_MEMSTORE_TS_KEY"); /** KeyValue version in FileInfo */ public static final byte [] KEY_VALUE_VERSION = Bytes.toBytes("KEY_VALUE_VERSION"); /** Version for KeyValue which includes memstore timestamp */ public static final int KEY_VALUE_VER_WITH_MEMSTORE = 1; /** Inline block writers for multi-level block index and compound Blooms. */ private List<InlineBlockWriter> inlineBlockWriters = new ArrayList<InlineBlockWriter>(); /** Unified version 2 block writer */ private HFileBlock.Writer fsBlockWriter; private HFileBlockIndex.BlockIndexWriter dataBlockIndexWriter; private HFileBlockIndex.BlockIndexWriter metaBlockIndexWriter; /** The offset of the first data block or -1 if the file is empty. */ private long firstDataBlockOffset = -1; /** The offset of the last data block or 0 if the file is empty. */ private long lastDataBlockOffset; /** Additional data items to be written to the "load-on-open" section. */ private List<BlockWritable> additionalLoadOnOpenData = new ArrayList<BlockWritable>(); /** Checksum related settings */ private ChecksumType checksumType = HFile.DEFAULT_CHECKSUM_TYPE; private int bytesPerChecksum = HFile.DEFAULT_BYTES_PER_CHECKSUM; private final boolean includeMemstoreTS = true; private long maxMemstoreTS = 0; static class WriterFactoryV2 extends HFile.WriterFactory { WriterFactoryV2(Configuration conf, CacheConfig cacheConf) { super(conf, cacheConf); } @Override public Writer createWriter(FileSystem fs, Path path, FSDataOutputStream ostream, int blockSize, Compression.Algorithm compress, HFileDataBlockEncoder blockEncoder, final KeyComparator comparator, final ChecksumType checksumType, final int bytesPerChecksum) throws IOException { return new HFileWriterV2(conf, cacheConf, fs, path, ostream, blockSize, compress, blockEncoder, comparator, checksumType, bytesPerChecksum); } } /** Constructor that takes a path, creates and closes the output stream. */ public HFileWriterV2(Configuration conf, CacheConfig cacheConf, FileSystem fs, Path path, FSDataOutputStream ostream, int blockSize, Compression.Algorithm compressAlgo, HFileDataBlockEncoder blockEncoder, final KeyComparator comparator, final ChecksumType checksumType, final int bytesPerChecksum) throws IOException { super(cacheConf, ostream == null ? createOutputStream(conf, fs, path) : ostream, path, blockSize, compressAlgo, blockEncoder, comparator); SchemaMetrics.configureGlobally(conf); this.checksumType = checksumType; this.bytesPerChecksum = bytesPerChecksum; finishInit(conf); } /** Additional initialization steps */ private void finishInit(final Configuration conf) { if (fsBlockWriter != null) throw new IllegalStateException("finishInit called twice"); // HFile filesystem-level (non-caching) block writer fsBlockWriter = new HFileBlock.Writer(compressAlgo, blockEncoder, includeMemstoreTS, checksumType, bytesPerChecksum); // Data block index writer boolean cacheIndexesOnWrite = cacheConf.shouldCacheIndexesOnWrite(); dataBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(fsBlockWriter, cacheIndexesOnWrite ? cacheConf.getBlockCache(): null, cacheIndexesOnWrite ? name : null); dataBlockIndexWriter.setMaxChunkSize( HFileBlockIndex.getMaxChunkSize(conf)); inlineBlockWriters.add(dataBlockIndexWriter); // Meta data block index writer metaBlockIndexWriter = new HFileBlockIndex.BlockIndexWriter(); LOG.debug("Initialized with " + cacheConf); if (isSchemaConfigured()) { schemaConfigurationChanged(); } } @Override protected void schemaConfigurationChanged() { passSchemaMetricsTo(dataBlockIndexWriter); passSchemaMetricsTo(metaBlockIndexWriter); } /** * At a block boundary, write all the inline blocks and opens new block. * * @throws IOException */ private void checkBlockBoundary() throws IOException { if (fsBlockWriter.blockSizeWritten() < blockSize) return; finishBlock(); writeInlineBlocks(false); newBlock(); } /** Clean up the current block */ private void finishBlock() throws IOException { if (!fsBlockWriter.isWriting() || fsBlockWriter.blockSizeWritten() == 0) return; long startTimeNs = System.nanoTime(); // Update the first data block offset for scanning. if (firstDataBlockOffset == -1) { firstDataBlockOffset = outputStream.getPos(); } // Update the last data block offset lastDataBlockOffset = outputStream.getPos(); fsBlockWriter.writeHeaderAndData(outputStream); int onDiskSize = fsBlockWriter.getOnDiskSizeWithHeader(); dataBlockIndexWriter.addEntry(firstKeyInBlock, lastDataBlockOffset, onDiskSize); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); HFile.offerWriteLatency(System.nanoTime() - startTimeNs); if (cacheConf.shouldCacheDataOnWrite()) { doCacheOnWrite(lastDataBlockOffset); } } /** Gives inline block writers an opportunity to contribute blocks. */ private void writeInlineBlocks(boolean closing) throws IOException { for (InlineBlockWriter ibw : inlineBlockWriters) { while (ibw.shouldWriteBlock(closing)) { long offset = outputStream.getPos(); boolean cacheThisBlock = ibw.cacheOnWrite(); ibw.writeInlineBlock(fsBlockWriter.startWriting( ibw.getInlineBlockType())); fsBlockWriter.writeHeaderAndData(outputStream); ibw.blockWritten(offset, fsBlockWriter.getOnDiskSizeWithHeader(), fsBlockWriter.getUncompressedSizeWithoutHeader()); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); if (cacheThisBlock) { doCacheOnWrite(offset); } } } } /** * Caches the last written HFile block. * @param offset the offset of the block we want to cache. Used to determine * the cache key. */ private void doCacheOnWrite(long offset) { // We don't cache-on-write data blocks on compaction, so assume this is not // a compaction. final boolean isCompaction = false; HFileBlock cacheFormatBlock = blockEncoder.diskToCacheFormat( fsBlockWriter.getBlockForCaching(), isCompaction); passSchemaMetricsTo(cacheFormatBlock); cacheConf.getBlockCache().cacheBlock( new BlockCacheKey(name, offset, blockEncoder.getEncodingInCache(), cacheFormatBlock.getBlockType()), cacheFormatBlock); } /** * Ready a new block for writing. * * @throws IOException */ private void newBlock() throws IOException { // This is where the next block begins. fsBlockWriter.startWriting(BlockType.DATA); firstKeyInBlock = null; } /** * Add a meta block to the end of the file. Call before close(). Metadata * blocks are expensive. Fill one with a bunch of serialized data rather than * do a metadata block per metadata instance. If metadata is small, consider * adding to file info using {@link #appendFileInfo(byte[], byte[])} * * @param metaBlockName * name of the block * @param content * will call readFields to get data later (DO NOT REUSE) */ @Override public void appendMetaBlock(String metaBlockName, Writable content) { byte[] key = Bytes.toBytes(metaBlockName); int i; for (i = 0; i < metaNames.size(); ++i) { // stop when the current key is greater than our own byte[] cur = metaNames.get(i); if (Bytes.BYTES_RAWCOMPARATOR.compare(cur, 0, cur.length, key, 0, key.length) > 0) { break; } } metaNames.add(i, key); metaData.add(i, content); } /** * Add key/value to file. Keys must be added in an order that agrees with the * Comparator passed on construction. * * @param kv * KeyValue to add. Cannot be empty nor null. * @throws IOException */ @Override public void append(final KeyValue kv) throws IOException { append(kv.getMemstoreTS(), kv.getBuffer(), kv.getKeyOffset(), kv.getKeyLength(), kv.getBuffer(), kv.getValueOffset(), kv.getValueLength()); this.maxMemstoreTS = Math.max(this.maxMemstoreTS, kv.getMemstoreTS()); } /** * Add key/value to file. Keys must be added in an order that agrees with the * Comparator passed on construction. * * @param key * Key to add. Cannot be empty nor null. * @param value * Value to add. Cannot be empty nor null. * @throws IOException */ @Override public void append(final byte[] key, final byte[] value) throws IOException { append(0, key, 0, key.length, value, 0, value.length); } /** * Add key/value to file. Keys must be added in an order that agrees with the * Comparator passed on construction. * * @param key * @param koffset * @param klength * @param value * @param voffset * @param vlength * @throws IOException */ private void append(final long memstoreTS, final byte[] key, final int koffset, final int klength, final byte[] value, final int voffset, final int vlength) throws IOException { boolean dupKey = checkKey(key, koffset, klength); checkValue(value, voffset, vlength); if (!dupKey) { checkBlockBoundary(); } if (!fsBlockWriter.isWriting()) newBlock(); // Write length of key and value and then actual key and value bytes. // Additionally, we may also write down the memstoreTS. { DataOutputStream out = fsBlockWriter.getUserDataStream(); out.writeInt(klength); totalKeyLength += klength; out.writeInt(vlength); totalValueLength += vlength; out.write(key, koffset, klength); out.write(value, voffset, vlength); if (this.includeMemstoreTS) { WritableUtils.writeVLong(out, memstoreTS); } } // Are we the first key in this block? if (firstKeyInBlock == null) { // Copy the key. firstKeyInBlock = new byte[klength]; System.arraycopy(key, koffset, firstKeyInBlock, 0, klength); } lastKeyBuffer = key; lastKeyOffset = koffset; lastKeyLength = klength; entryCount++; } @Override public void close() throws IOException { if (outputStream == null) { return; } // Write out the end of the data blocks, then write meta data blocks. // followed by fileinfo, data block index and meta block index. finishBlock(); writeInlineBlocks(true); FixedFileTrailer trailer = new FixedFileTrailer(2, HFileReaderV2.MAX_MINOR_VERSION); // Write out the metadata blocks if any. if (!metaNames.isEmpty()) { for (int i = 0; i < metaNames.size(); ++i) { // store the beginning offset long offset = outputStream.getPos(); // write the metadata content DataOutputStream dos = fsBlockWriter.startWriting(BlockType.META); metaData.get(i).write(dos); fsBlockWriter.writeHeaderAndData(outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); // Add the new meta block to the meta index. metaBlockIndexWriter.addEntry(metaNames.get(i), offset, fsBlockWriter.getOnDiskSizeWithHeader()); } } // Load-on-open section. // Data block index. // // In version 2, this section of the file starts with the root level data // block index. We call a function that writes intermediate-level blocks // first, then root level, and returns the offset of the root level block // index. long rootIndexOffset = dataBlockIndexWriter.writeIndexBlocks(outputStream); trailer.setLoadOnOpenOffset(rootIndexOffset); // Meta block index. metaBlockIndexWriter.writeSingleLevelIndex(fsBlockWriter.startWriting( BlockType.ROOT_INDEX), "meta"); fsBlockWriter.writeHeaderAndData(outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); if (this.includeMemstoreTS) { appendFileInfo(MAX_MEMSTORE_TS_KEY, Bytes.toBytes(maxMemstoreTS)); appendFileInfo(KEY_VALUE_VERSION, Bytes.toBytes(KEY_VALUE_VER_WITH_MEMSTORE)); } // File info writeFileInfo(trailer, fsBlockWriter.startWriting(BlockType.FILE_INFO)); fsBlockWriter.writeHeaderAndData(outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); // Load-on-open data supplied by higher levels, e.g. Bloom filters. for (BlockWritable w : additionalLoadOnOpenData){ fsBlockWriter.writeBlock(w, outputStream); totalUncompressedBytes += fsBlockWriter.getUncompressedSizeWithHeader(); } // Now finish off the trailer. trailer.setNumDataIndexLevels(dataBlockIndexWriter.getNumLevels()); trailer.setUncompressedDataIndexSize( dataBlockIndexWriter.getTotalUncompressedSize()); trailer.setFirstDataBlockOffset(firstDataBlockOffset); trailer.setLastDataBlockOffset(lastDataBlockOffset); trailer.setComparatorClass(comparator.getClass()); trailer.setDataIndexCount(dataBlockIndexWriter.getNumRootEntries()); finishClose(trailer); fsBlockWriter.releaseCompressor(); } @Override public void addInlineBlockWriter(InlineBlockWriter ibw) { inlineBlockWriters.add(ibw); } @Override public void addGeneralBloomFilter(final BloomFilterWriter bfw) { this.addBloomFilter(bfw, BlockType.GENERAL_BLOOM_META); } @Override public void addDeleteFamilyBloomFilter(final BloomFilterWriter bfw) { this.addBloomFilter(bfw, BlockType.DELETE_FAMILY_BLOOM_META); } private void addBloomFilter(final BloomFilterWriter bfw, final BlockType blockType) { if (bfw.getKeyCount() <= 0) return; if (blockType != BlockType.GENERAL_BLOOM_META && blockType != BlockType.DELETE_FAMILY_BLOOM_META) { throw new RuntimeException("Block Type: " + blockType.toString() + "is not supported"); } additionalLoadOnOpenData.add(new BlockWritable() { @Override public BlockType getBlockType() { return blockType; } @Override public void writeToBlock(DataOutput out) throws IOException { bfw.getMetaWriter().write(out); Writable dataWriter = bfw.getDataWriter(); if (dataWriter != null) dataWriter.write(out); } }); } }
ay65535/hbase-0.94.0
src/main/java/org/apache/hadoop/hbase/io/hfile/HFileWriterV2.java
Java
apache-2.0
16,662
<?php include dirname(__FILE__) . '/cache/top-cache.php'; include(dirname(__FILE__) . "/TwitterAPIExchange.php"); //get it from https://github.com/J7mbo/twitter-api-php include(dirname(__FILE__) . "/apiKeys.php"); $twitterHandleSuffixes = array('x', 'mtl', 'sf', 'bos', 'to', 'kw', 'van', 'nyc', 'xnews'); $followers_count_array = array('twitterFollowersCount' => array()); $totalFollowers = 0; /** Set access tokens here - see: https://dev.twitter.com/apps/ **/ $settings = array( 'oauth_access_token' => $twitter_keys_and_tokens["token"], 'oauth_access_token_secret' => $twitter_keys_and_tokens["token_secret"], 'consumer_key' => $twitter_keys_and_tokens["key"], 'consumer_secret' => $twitter_keys_and_tokens["key_secret"] ); $url = 'https://api.twitter.com/1.1/followers/ids.json'; $requestMethod = 'GET'; //Get number of followers of each twitter account and add them to an array foreach ($twitterHandleSuffixes as $suffix) { $getfield = '?screen_name=Neurotech' . $suffix; $twitter = new TwitterAPIExchange($settings); $follow_count = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); $data = json_decode($follow_count, true); $followers_count = count($data['ids']); $totalFollowers += $followers_count; $twitter_count_array['twitterFollowersCount']['neurotech' . ucfirst($suffix)] = $followers_count; $twitter_count_array['twitterFollowersCount']['total'] = $totalFollowers; }; // This JSON object will stored in cache echo json_encode($twitter_count_array); include dirname(__FILE__) . '/cache/bottom-cache.php'; ?>
curiositry/neurotechx.github.io
public_html/social_media_apis/twitter-count.php
PHP
apache-2.0
1,693
/* * Copyright (c) 2010-2013 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.notifications.impl.helpers; import com.evolveum.midpoint.notifications.api.events.Event; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.EventHandlerType; import com.evolveum.midpoint.xml.ns._public.common.common_3.EventOperationType; import org.springframework.stereotype.Component; /** * @author mederly */ @Component public class OperationFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(OperationFilterHelper.class); public boolean processEvent(Event event, EventHandlerType eventHandlerType) { if (eventHandlerType.getOperation().isEmpty()) { return true; } logStart(LOGGER, event, eventHandlerType, eventHandlerType.getOperation()); boolean retval = false; for (EventOperationType eventOperationType : eventHandlerType.getOperation()) { if (eventOperationType == null) { LOGGER.warn("Filtering on null eventOperationType; filter = " + eventHandlerType); } else if (event.isOperationType(eventOperationType)) { retval = true; break; } } logEnd(LOGGER, event, eventHandlerType, retval); return retval; } }
bshp/midPoint
model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/OperationFilterHelper.java
Java
apache-2.0
1,574
/* * 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. */ package org.apache.hyracks.storage.am.lsm.rtree.dataflow; import java.util.Map; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.ILinearizeComparatorFactory; import org.apache.hyracks.api.dataflow.value.ITypeTraits; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.storage.am.common.api.IPrimitiveValueProviderFactory; import org.apache.hyracks.storage.am.common.dataflow.IIndexOperatorDescriptor; import org.apache.hyracks.storage.am.common.dataflow.IndexDataflowHelper; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory; import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationSchedulerProvider; import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicyFactory; import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTrackerFactory; import org.apache.hyracks.storage.am.lsm.common.api.IVirtualBufferCacheProvider; import org.apache.hyracks.storage.am.lsm.common.dataflow.AbstractLSMIndexDataflowHelperFactory; import org.apache.hyracks.storage.am.rtree.frames.RTreePolicyType; public class LSMRTreeWithAntiMatterTuplesDataflowHelperFactory extends AbstractLSMIndexDataflowHelperFactory { private static final long serialVersionUID = 1L; private final IBinaryComparatorFactory[] btreeComparatorFactories; private final IPrimitiveValueProviderFactory[] valueProviderFactories; private final RTreePolicyType rtreePolicyType; private final ILinearizeComparatorFactory linearizeCmpFactory; private final int[] rtreeFields; protected final boolean isPointMBR; public LSMRTreeWithAntiMatterTuplesDataflowHelperFactory(IPrimitiveValueProviderFactory[] valueProviderFactories, RTreePolicyType rtreePolicyType, IBinaryComparatorFactory[] btreeComparatorFactories, IVirtualBufferCacheProvider virtualBufferCacheProvider, ILSMMergePolicyFactory mergePolicyFactory, Map<String, String> mergePolicyProperties, ILSMOperationTrackerFactory opTrackerFactory, ILSMIOOperationSchedulerProvider ioSchedulerProvider, ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILinearizeComparatorFactory linearizeCmpFactory, int[] rtreeFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories, int[] filterFields, boolean durable, boolean isPointMBR) { super(virtualBufferCacheProvider, mergePolicyFactory, mergePolicyProperties, opTrackerFactory, ioSchedulerProvider, ioOpCallbackFactory, 1.0, filterTypeTraits, filterCmpFactories, filterFields, durable); this.btreeComparatorFactories = btreeComparatorFactories; this.valueProviderFactories = valueProviderFactories; this.rtreePolicyType = rtreePolicyType; this.linearizeCmpFactory = linearizeCmpFactory; this.rtreeFields = rtreeFields; this.isPointMBR = isPointMBR; } @Override public IndexDataflowHelper createIndexDataflowHelper(IIndexOperatorDescriptor opDesc, IHyracksTaskContext ctx, int partition) throws HyracksDataException { return new LSMRTreeWithAntiMatterTuplesDataflowHelper(opDesc, ctx, partition, virtualBufferCacheProvider.getVirtualBufferCaches(ctx, opDesc.getFileSplitProvider()), btreeComparatorFactories, valueProviderFactories, rtreePolicyType, mergePolicyFactory.createMergePolicy(mergePolicyProperties, ctx), opTrackerFactory, ioSchedulerProvider.getIOScheduler(ctx), ioOpCallbackFactory, linearizeCmpFactory, rtreeFields, filterTypeTraits, filterCmpFactories, filterFields, durable, isPointMBR); } }
waans11/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-storage-am-lsm-rtree/src/main/java/org/apache/hyracks/storage/am/lsm/rtree/dataflow/LSMRTreeWithAntiMatterTuplesDataflowHelperFactory.java
Java
apache-2.0
4,634
package sk.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sk.mmap.Constants; import sk.mmap.IUnsafeAllocator; import java.util.Map; import java.util.HashMap; // Memory mapped hash set of Long public class MUHSetLong { private static final Logger logger = LoggerFactory.getLogger(MUHSetLong.class); private final int numBuckets; private final IUnsafeAllocator allocator; private final MBUArrayListL buckets; // TODO: Implement rehashing when table is full to avoid adding lots of elements in list public MUHSetLong(final IUnsafeAllocator allocator, final int numBuckets) { this.allocator = allocator; this.numBuckets = numBuckets; buckets = new MBUArrayListL(allocator, numBuckets); // Initialize all buckets with NULL for (int i = 0; i < numBuckets; i++) { buckets.add(Constants.NULL); } } public void debug() { logger.debug("Printing details of Hash table"); final Map<Integer, Integer> elems2buckets = new HashMap<>(); for (int i = 0; i < buckets.size(); i++) { final long list = buckets.get(i); int elems = 0; if (list != Constants.NULL) { long node = MULinkedListL.getFirst(allocator, list); // If list is non-NULL, search in the MULinkedListL while (node != Constants.NULL) { ++elems; node = MULinkedListL.getNext(allocator, node); } /* if (elems > 1) { logger.debug("Bucket " + i + " has " + elems + " elements"); } */ } if (elems2buckets.containsKey(elems)) { elems2buckets.put(elems, elems2buckets.get(elems) + 1); } else { elems2buckets.put(elems, 1); } } elems2buckets.forEach((key, val) -> { logger.debug(val + " buckets have " + key + " elements"); }); logger.debug("End printing details of Hash table"); } private long getBucket(final long key, final boolean create) { final long hash = JenkinsHash.hash64(key); final int index = (int)(hash % numBuckets); if (create) { // logger.debug("Key " + key + " : Hash " + hash + " : index " + index); } long list = buckets.get(index); if (create && list == Constants.NULL) { list = MULinkedListL.create(allocator); buckets.put(index, list); } return list; } public void put(final long value) { long list = getBucket(value, true); MULinkedListL.add(allocator, list, value); } public long get(final long key) { long value = Constants.NULL; final long list = getBucket(key, false); if (list != Constants.NULL) { long node = MULinkedListL.getFirst(allocator, list); // If list is non-NULL, search in the MULinkedListL while (node != Constants.NULL) { final long tmp = MULinkedListL.getL(allocator, node); if (tmp == key) { value = tmp; break; } node = MULinkedListL.getNext(allocator, node); } } return value; } }
soumitrak/mmap-ds
src/main/java/sk/util/MUHSetLong.java
Java
apache-2.0
3,408
/* * Copyright 2017 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 example.sos.monolith; import example.sos.monolith.catalog.Catalog; import example.sos.monolith.catalog.Product; import example.sos.monolith.inventory.Inventory; import example.sos.monolith.orders.OrderManager; import java.math.BigDecimal; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; /** * @author Oliver Gierke */ @SpringBootApplication public class MonolithApplication { public static void main(String... args) { SpringApplication.run(MonolithApplication.class, args); } @Bean CommandLineRunner onStartup(Catalog catalog, Inventory inventory, OrderManager orders) { return args -> { Product iPad = catalog.save(new Product("iPad", new BigDecimal(699.99))); Product iPhone = catalog.save(new Product("iPhone", new BigDecimal(899.99))); inventory.addItemFor(iPad, 10); inventory.addItemFor(iPhone, 15); }; } }
olivergierke/sos
00-monolith/src/main/java/example/sos/monolith/MonolithApplication.java
Java
apache-2.0
1,646
/* * Copyright 2014 University of Zürich, SIB, and others. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. 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. */ package org.string_db.psicquic; import org.hupo.psi.calimocho.model.Row; /** * @author Milan Simonovic <milan.simonovic@imls.uzh.ch> */ public interface SearchServer { /** * Add a new interaction to the index; might not be visible for search * before {@link #commit(boolean)} is called. * * @param row * @throws RuntimeException */ void add(Row row) throws RuntimeException; /** * Write all previously added interactions to the index. * * @param reopenSearcher true to wait to reopen searcher * @throws RuntimeException */ void commit(boolean reopenSearcher) throws RuntimeException; /** * @return number of indexed documents */ Long countIndexedDocuments(); /** * remove all documents from the index * * @throws RuntimeException */ void deleteAll() throws RuntimeException; }
meringlab/stringdb-psicquic
src/main/java/org/string_db/psicquic/SearchServer.java
Java
apache-2.0
1,651
package com.example.denizalp.thefirst; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import com.bounswe.group7.model.Topics; import org.w3c.dom.Text; import java.util.List; /** * Created by denizalp on 18/12/16. */ public class TopicAdapter extends BaseAdapter { private LayoutInflater mInflater; private List<Topics> mTopicList; private String currentToken; private Activity activity; public TopicAdapter(Activity activity, List<Topics> topicList, String currentToken){ this.activity = activity; mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mTopicList = topicList; this.currentToken = currentToken; } @Override public int getCount() { return mTopicList.size(); } @Override public Object getItem(int position) { return mTopicList.get(position); } @Override public long getItemId(int position) { return mTopicList.get(position).getTopicId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View singleTopicView = mInflater.inflate(R.layout.activity_single_topic, null); Topics topic = mTopicList.get(position); TextView textView = (TextView) singleTopicView.findViewById(R.id.textView8); Button button = (Button) singleTopicView.findViewById(R.id.button38); Intent toTopic = new Intent(activity, ShowTopicPage.class); textView.setText(topic.getHeader()); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toTopic.putExtra("topicId",topic.getTopicId()); activity.startActivity(toTopic); } }); return singleTopicView; } }
bounswe/bounswe2016group7
TheFirst/app/src/main/java/com/example/denizalp/thefirst/TopicAdapter.java
Java
apache-2.0
2,061
/// <reference path="types.ts"/> module ts { export interface Map<T> { [index: string]: T; } export interface StringSet extends Map<any> { } export function forEach<T, U>(array: T[], callback: (element: T) => U): U { var result: U; if (array) { for (var i = 0, len = array.length; i < len; i++) { if (result = callback(array[i])) { break; } } } return result; } export function contains<T>(array: T[], value: T): boolean { if (array) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return true; } } } return false; } export function indexOf<T>(array: T[], value: T): number { if (array) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } } return -1; } export function countWhere<T>(array: T[], predicate: (x: T) => boolean): number { var count = 0; if (array) { for (var i = 0, len = array.length; i < len; i++) { if (predicate(array[i])) { count++; } } } return count; } export function filter<T>(array: T[], f: (x: T) => boolean): T[] { if (array) { var result: T[] = []; for (var i = 0, len = array.length; i < len; i++) { var item = array[i]; if (f(item)) { result.push(item); } } } return result; } export function map<T, U>(array: T[], f: (x: T) => U): U[] { if (array) { var result: U[] = []; for (var i = 0, len = array.length; i < len; i++) { result.push(f(array[i])); } } return result; } export function concatenate<T>(array1: T[], array2: T[]): T[] { if (!array2 || !array2.length) return array1; if (!array1 || !array1.length) return array2; return array1.concat(array2); } export function uniqueElements<T>(array: T[]): T[] { if (array) { var result: T[] = []; for (var i = 0, len = array.length; i < len; i++) { var item = array[i]; if (!contains(result, item)) result.push(item); } } return result; } export function sum(array: any[], prop: string): number { var result = 0; for (var i = 0; i < array.length; i++) { result += array[i][prop]; } return result; } export function binarySearch(array: number[], value: number): number { var low = 0; var high = array.length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; if (midValue === value) { return middle; } else if (midValue > value) { high = middle - 1; } else { low = middle + 1; } } return ~low; } var hasOwnProperty = Object.prototype.hasOwnProperty; export function hasProperty<T>(map: Map<T>, key: string): boolean { return hasOwnProperty.call(map, key); } export function getProperty<T>(map: Map<T>, key: string): T { return hasOwnProperty.call(map, key) ? map[key] : undefined; } export function isEmpty<T>(map: Map<T>) { for (var id in map) { if (hasProperty(map, id)) { return false; } } return true; } export function clone<T>(object: T): T { var result: any = {}; for (var id in object) { result[id] = (<any>object)[id]; } return <T>result; } export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U { var result: U; for (var id in map) { if (result = callback(map[id])) break; } return result; } export function forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U { var result: U; for (var id in map) { if (result = callback(id)) break; } return result; } export function lookUp<T>(map: Map<T>, key: string): T { return hasProperty(map, key) ? map[key] : undefined; } export function mapToArray<T>(map: Map<T>): T[] { var result: T[] = []; for (var id in map) { result.push(map[id]); } return result; } /** * Creates a map from the elements of an array. * * @param array the array of input elements. * @param makeKey a function that produces a key for a given element. * * This function makes no effort to avoid collisions; if any two elements produce * the same key with the given 'makeKey' function, then the element with the higher * index in the array will be the one associated with the produced key. */ export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T> { var result: Map<T> = {}; forEach(array, value => { result[makeKey(value)] = value; }); return result; } function formatStringFromArgs(text: string, args: { [index: number]: any; }, baseIndex?: number): string { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, (match, index?) => args[+index + baseIndex]); } export var localizedDiagnosticMessages: Map<string> = undefined; export function getLocaleSpecificMessage(message: string) { return localizedDiagnosticMessages && localizedDiagnosticMessages[message] ? localizedDiagnosticMessages[message] : message; } export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): Diagnostic { Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); var text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); } return { file: file, start: start, length: length, messageText: text, category: message.category, code: message.code }; } export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { var text = getLocaleSpecificMessage(message.key); if (arguments.length > 1) { text = formatStringFromArgs(text, arguments, 1); } return { file: undefined, start: undefined, length: undefined, messageText: text, category: message.category, code: message.code }; } export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage): DiagnosticMessageChain { var text = getLocaleSpecificMessage(message.key); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); } return { messageText: text, category: message.category, code: message.code, next: details }; } export function flattenDiagnosticChain(file: SourceFile, start: number, length: number, diagnosticChain: DiagnosticMessageChain, newLine: string): Diagnostic { Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); var code = diagnosticChain.code; var category = diagnosticChain.category; var messageText = ""; var indent = 0; while (diagnosticChain) { if (indent) { messageText += newLine; for (var i = 0; i < indent; i++) { messageText += " "; } } messageText += diagnosticChain.messageText; indent++; diagnosticChain = diagnosticChain.next; } return { file: file, start: start, length: length, code: code, category: category, messageText: messageText }; } export function compareValues<T>(a: T, b: T): number { if (a === b) return 0; if (a === undefined) return -1; if (b === undefined) return 1; return a < b ? -1 : 1; } function getDiagnosticFilename(diagnostic: Diagnostic): string { return diagnostic.file ? diagnostic.file.filename : undefined; } export function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): number { return compareValues(getDiagnosticFilename(d1), getDiagnosticFilename(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || compareValues(d1.messageText, d2.messageText) || 0; } export function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] { if (diagnostics.length < 2) { return diagnostics; } var newDiagnostics = [diagnostics[0]]; var previousDiagnostic = diagnostics[0]; for (var i = 1; i < diagnostics.length; i++) { var currentDiagnostic = diagnostics[i]; var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0; if (!isDupe) { newDiagnostics.push(currentDiagnostic); previousDiagnostic = currentDiagnostic; } } return newDiagnostics; } export function normalizeSlashes(path: string): string { return path.replace(/\\/g, "/"); } // Returns length of path root (i.e. length of "/", "x:/", "//server/share/") export function getRootLength(path: string): number { if (path.charCodeAt(0) === CharacterCodes.slash) { if (path.charCodeAt(1) !== CharacterCodes.slash) return 1; var p1 = path.indexOf("/", 2); if (p1 < 0) return 2; var p2 = path.indexOf("/", p1 + 1); if (p2 < 0) return p1 + 1; return p2 + 1; } if (path.charCodeAt(1) === CharacterCodes.colon) { if (path.charCodeAt(2) === CharacterCodes.slash) return 3; return 2; } return 0; } export var directorySeparator = "/"; function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { var parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); var normalized: string[] = []; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { normalized.pop(); } else { normalized.push(part); } } } return normalized; } export function normalizePath(path: string): string { var path = normalizeSlashes(path); var rootLength = getRootLength(path); var normalized = getNormalizedParts(path, rootLength); return path.substr(0, rootLength) + normalized.join(directorySeparator); } export function getDirectoryPath(path: string) { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))); } export function isUrl(path: string) { return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } export function isRootedDiskPath(path: string) { return getRootLength(path) !== 0; } function normalizedPathComponents(path: string, rootLength: number) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); } export function getNormalizedPathComponents(path: string, currentDirectory: string) { var path = normalizeSlashes(path); var rootLength = getRootLength(path); if (rootLength == 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); rootLength = getRootLength(path); } return normalizedPathComponents(path, rootLength); } export function getNormalizedPathFromPathComponents(pathComponents: string[]) { if (pathComponents && pathComponents.length) { return pathComponents[0] + pathComponents.slice(1).join(directorySeparator); } } function getNormalizedPathComponentsOfUrl(url: string) { // Get root length of http://www.website.com/folder1/foler2/ // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part var rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { // Consume all immediate slashes in the protocol // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// if (url.charCodeAt(rootLength) === CharacterCodes.slash) { rootLength++; } else { // non slash character means we continue proceeding to next component of root search break; } } // there are no parts after http:// just return current string as the pathComponent if (rootLength === urlLength) { return [url]; } // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) var indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ // and get components afetr the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } else { // Can't find the host assume the rest of the string as component // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + directorySeparator]; } } function getNormalizedPathOrUrlComponents(pathOrUrl: string, currentDirectory: string) { if (isUrl(pathOrUrl)) { return getNormalizedPathComponentsOfUrl(pathOrUrl); } else { return getNormalizedPathComponents(pathOrUrl, currentDirectory); } } export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean) { var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.length--; } // Find the component that differs for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } } // Get the relative path if (joinStartIndex) { var relativePath = ""; var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { if (directoryComponents[joinStartIndex] !== "") { relativePath = relativePath + ".." + directorySeparator; } } return relativePath + relativePathComponents.join(directorySeparator); } // Cant find the relative path, get the absolute path var absolutePath = getNormalizedPathFromPathComponents(pathComponents); if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { absolutePath = "file:///" + absolutePath; } return absolutePath; } export function getBaseFilename(path: string) { var i = path.lastIndexOf(directorySeparator); return i < 0 ? path : path.substring(i + 1); } export function combinePaths(path1: string, path2: string) { if (!(path1 && path1.length)) return path2; if (!(path2 && path2.length)) return path1; if (path2.charAt(0) === directorySeparator) return path2; if (path1.charAt(path1.length - 1) === directorySeparator) return path1 + path2; return path1 + directorySeparator + path2; } export function fileExtensionIs(path: string, extension: string): boolean { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } var supportedExtensions = [".d.ts", ".ts", ".js"]; export function removeFileExtension(path: string): string { for (var i = 0; i < supportedExtensions.length; i++) { var ext = supportedExtensions[i]; if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } } return path; } var escapedCharsRegExp = /[\t\v\f\b\0\r\n\"\\\u2028\u2029\u0085]/g; var escapedCharsMap: Map<string> = { "\t": "\\t", "\v": "\\v", "\f": "\\f", "\b": "\\b", "\0": "\\0", "\r": "\\r", "\n": "\\n", "\"": "\\\"", "\u2028": "\\u2028", // lineSeparator "\u2029": "\\u2029", // paragraphSeparator "\u0085": "\\u0085" // nextLine }; /** NOTE: This *does not* support the full escape characters, it only supports the subset that can be used in file names * or string literals. If the information encoded in the map changes, this needs to be revisited. */ export function escapeString(s: string): string { return escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, c => { return escapedCharsMap[c] || c; }) : s; } export interface ObjectAllocator { getNodeConstructor(kind: SyntaxKind): new () => Node; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; getSignatureConstructor(): new (checker: TypeChecker) => Signature; } function Symbol(flags: SymbolFlags, name: string) { this.flags = flags; this.name = name; this.declarations = undefined; } function Type(checker: TypeChecker, flags: TypeFlags) { this.flags = flags; } function Signature(checker: TypeChecker) { } export var objectAllocator: ObjectAllocator = { getNodeConstructor: kind => { function Node() { } Node.prototype = { kind: kind, pos: 0, end: 0, flags: 0, parent: undefined, }; return <any>Node; }, getSymbolConstructor: () => <any>Symbol, getTypeConstructor: () => <any>Type, getSignatureConstructor: () => <any>Signature } export enum AssertionLevel { None = 0, Normal = 1, Aggressive = 2, VeryAggressive = 3, } export module Debug { var currentAssertionLevel = AssertionLevel.None; export function shouldAssert(level: AssertionLevel): boolean { return currentAssertionLevel >= level; } export function assert(expression: any, message?: string, verboseDebugInfo?: () => string): void { if (!expression) { var verboseDebugString = ""; if (verboseDebugInfo) { verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); } throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); } } export function fail(message?: string): void { Debug.assert(false, message); } } }
jnetterf/typescript-react-jsx
src/compiler/core.ts
TypeScript
apache-2.0
22,924
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // //------------------------------------------------------------------------------ // // Example: HTTP flex server (plain and SSL), asynchronous // //------------------------------------------------------------------------------ #include "example/common/detect_ssl.hpp" #include "example/common/server_certificate.hpp" #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ssl/stream.hpp> #include <boost/asio/strand.hpp> #include <boost/config.hpp> #include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <memory> #include <string> #include <thread> using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> namespace http = boost::beast::http; // from <boost/beast/http.hpp> // Return a reasonable mime type based on the extension of a file. boost::beast::string_view mime_type(boost::beast::string_view path) { using boost::beast::iequals; auto const ext = [&path] { auto const pos = path.rfind("."); if(pos == boost::beast::string_view::npos) return boost::beast::string_view{}; return path.substr(pos); }(); if(iequals(ext, ".htm")) return "text/html"; if(iequals(ext, ".html")) return "text/html"; if(iequals(ext, ".php")) return "text/html"; if(iequals(ext, ".css")) return "text/css"; if(iequals(ext, ".txt")) return "text/plain"; if(iequals(ext, ".js")) return "application/javascript"; if(iequals(ext, ".json")) return "application/json"; if(iequals(ext, ".xml")) return "application/xml"; if(iequals(ext, ".swf")) return "application/x-shockwave-flash"; if(iequals(ext, ".flv")) return "video/x-flv"; if(iequals(ext, ".png")) return "image/png"; if(iequals(ext, ".jpe")) return "image/jpeg"; if(iequals(ext, ".jpeg")) return "image/jpeg"; if(iequals(ext, ".jpg")) return "image/jpeg"; if(iequals(ext, ".gif")) return "image/gif"; if(iequals(ext, ".bmp")) return "image/bmp"; if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon"; if(iequals(ext, ".tiff")) return "image/tiff"; if(iequals(ext, ".tif")) return "image/tiff"; if(iequals(ext, ".svg")) return "image/svg+xml"; if(iequals(ext, ".svgz")) return "image/svg+xml"; return "application/text"; } // Append an HTTP rel-path to a local filesystem path. // The returned path is normalized for the platform. std::string path_cat( boost::beast::string_view base, boost::beast::string_view path) { if(base.empty()) return path.to_string(); std::string result = base.to_string(); #if BOOST_MSVC char constexpr path_separator = '\\'; if(result.back() == path_separator) result.resize(result.size() - 1); result.append(path.data(), path.size()); for(auto& c : result) if(c == '/') c = path_separator; #else char constexpr path_separator = '/'; if(result.back() == path_separator) result.resize(result.size() - 1); result.append(path.data(), path.size()); #endif return result; } // This function produces an HTTP response for the given // request. The type of the response object depends on the // contents of the request, so the interface requires the // caller to pass a generic lambda for receiving the response. template< class Body, class Allocator, class Send> void handle_request( boost::beast::string_view doc_root, http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send) { // Returns a bad request response auto const bad_request = [&req](boost::beast::string_view why) { http::response<http::string_body> res{http::status::bad_request, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html"); res.keep_alive(req.keep_alive()); res.body() = why.to_string(); res.prepare_payload(); return res; }; // Returns a not found response auto const not_found = [&req](boost::beast::string_view target) { http::response<http::string_body> res{http::status::not_found, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html"); res.keep_alive(req.keep_alive()); res.body() = "The resource '" + target.to_string() + "' was not found."; res.prepare_payload(); return res; }; // Returns a server error response auto const server_error = [&req](boost::beast::string_view what) { http::response<http::string_body> res{http::status::internal_server_error, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, "text/html"); res.keep_alive(req.keep_alive()); res.body() = "An error occurred: '" + what.to_string() + "'"; res.prepare_payload(); return res; }; // Make sure we can handle the method if( req.method() != http::verb::get && req.method() != http::verb::head) return send(bad_request("Unknown HTTP-method")); // Request path must be absolute and not contain "..". if( req.target().empty() || req.target()[0] != '/' || req.target().find("..") != boost::beast::string_view::npos) return send(bad_request("Illegal request-target")); // Build the path to the requested file std::string path = path_cat(doc_root, req.target()); if(req.target().back() == '/') path.append("index.html"); // Attempt to open the file boost::beast::error_code ec; http::file_body::value_type body; body.open(path.c_str(), boost::beast::file_mode::scan, ec); // Handle the case where the file doesn't exist if(ec == boost::system::errc::no_such_file_or_directory) return send(not_found(req.target())); // Handle an unknown error if(ec) return send(server_error(ec.message())); // Respond to HEAD request if(req.method() == http::verb::head) { http::response<http::empty_body> res{http::status::ok, req.version()}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, mime_type(path)); res.content_length(body.size()); res.keep_alive(req.keep_alive()); return send(std::move(res)); } // Respond to GET request http::response<http::file_body> res{ std::piecewise_construct, std::make_tuple(std::move(body)), std::make_tuple(http::status::ok, req.version())}; res.set(http::field::server, BOOST_BEAST_VERSION_STRING); res.set(http::field::content_type, mime_type(path)); res.content_length(body.size()); res.keep_alive(req.keep_alive()); return send(std::move(res)); } //------------------------------------------------------------------------------ // Report a failure void fail(boost::system::error_code ec, char const* what) { std::cerr << what << ": " << ec.message() << "\n"; } // Handles an HTTP server connection. // This uses the Curiously Recurring Template Pattern so that // the same code works with both SSL streams and regular sockets. template<class Derived> class session { // Access the derived class, this is part of // the Curiously Recurring Template Pattern idiom. Derived& derived() { return static_cast<Derived&>(*this); } // This is the C++11 equivalent of a generic lambda. // The function object is used to send an HTTP message. struct send_lambda { session& self_; explicit send_lambda(session& self) : self_(self) { } template<bool isRequest, class Body, class Fields> void operator()(http::message<isRequest, Body, Fields>&& msg) const { // The lifetime of the message has to extend // for the duration of the async operation so // we use a shared_ptr to manage it. auto sp = std::make_shared< http::message<isRequest, Body, Fields>>(std::move(msg)); // Store a type-erased version of the shared // pointer in the class to keep it alive. self_.res_ = sp; // Write the response http::async_write( self_.derived().stream(), *sp, self_.strand_.wrap(std::bind( &session::on_write, self_.derived().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } }; std::string const& doc_root_; http::request<http::string_body> req_; std::shared_ptr<void> res_; send_lambda lambda_; protected: boost::asio::io_service::strand strand_; boost::beast::flat_buffer buffer_; public: // Take ownership of the buffer explicit session( boost::asio::io_service& ios, boost::beast::flat_buffer buffer, std::string const& doc_root) : doc_root_(doc_root) , lambda_(*this) , strand_(ios) , buffer_(std::move(buffer)) { } void do_read() { // Read a request http::async_read( derived().stream(), buffer_, req_, strand_.wrap(std::bind( &session::on_read, derived().shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_read( boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); // This means they closed the connection if(ec == http::error::end_of_stream) return derived().do_eof(); if(ec) return fail(ec, "read"); // Send the response handle_request(doc_root_, std::move(req_), lambda_); } void on_write( boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if(ec == http::error::end_of_stream) { // This means we should close the connection, usually because // the response indicated the "Connection: close" semantic. return derived().do_eof(); } if(ec) return fail(ec, "write"); // We're done with the response so delete it res_ = nullptr; // Read another request do_read(); } }; // Handles a plain HTTP connection class plain_session : public session<plain_session> , public std::enable_shared_from_this<plain_session> { tcp::socket socket_; boost::asio::io_service::strand strand_; public: // Create the session plain_session( tcp::socket socket, boost::beast::flat_buffer buffer, std::string const& doc_root) : session<plain_session>( socket.get_io_service(), std::move(buffer), doc_root) , socket_(std::move(socket)) , strand_(socket_.get_io_service()) { } // Called by the base class tcp::socket& stream() { return socket_; } // Start the asynchronous operation void run() { do_read(); } void do_eof() { // Send a TCP shutdown boost::system::error_code ec; socket_.shutdown(tcp::socket::shutdown_send, ec); // At this point the connection is closed gracefully } }; // Handles an SSL HTTP connection class ssl_session : public session<ssl_session> , public std::enable_shared_from_this<ssl_session> { tcp::socket socket_; ssl::stream<tcp::socket&> stream_; boost::asio::io_service::strand strand_; public: // Create the session ssl_session( tcp::socket socket, ssl::context& ctx, boost::beast::flat_buffer buffer, std::string const& doc_root) : session<ssl_session>( socket.get_io_service(), std::move(buffer), doc_root) , socket_(std::move(socket)) , stream_(socket_, ctx) , strand_(stream_.get_io_service()) { } // Called by the base class ssl::stream<tcp::socket&>& stream() { return stream_; } // Start the asynchronous operation void run() { // Perform the SSL handshake // Note, this is the buffered version of the handshake. stream_.async_handshake( ssl::stream_base::server, buffer_.data(), strand_.wrap(std::bind( &ssl_session::on_handshake, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_handshake( boost::system::error_code ec, std::size_t bytes_used) { if(ec) return fail(ec, "handshake"); // Consume the portion of the buffer used by the handshake buffer_.consume(bytes_used); do_read(); } void do_eof() { // Perform the SSL shutdown stream_.async_shutdown( strand_.wrap(std::bind( &ssl_session::on_shutdown, shared_from_this(), std::placeholders::_1))); } void on_shutdown(boost::system::error_code ec) { if(ec) return fail(ec, "shutdown"); // At this point the connection is closed gracefully } }; //------------------------------------------------------------------------------ // Detects SSL handshakes class detect_session : public std::enable_shared_from_this<detect_session> { tcp::socket socket_; ssl::context& ctx_; boost::asio::io_service::strand strand_; std::string const& doc_root_; boost::beast::flat_buffer buffer_; public: explicit detect_session( tcp::socket socket, ssl::context& ctx, std::string const& doc_root) : socket_(std::move(socket)) , ctx_(ctx) , strand_(socket_.get_io_service()) , doc_root_(doc_root) { } // Launch the detector void run() { async_detect_ssl( socket_, buffer_, strand_.wrap(std::bind( &detect_session::on_detect, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void on_detect(boost::system::error_code ec, boost::tribool result) { if(ec) return fail(ec, "detect"); if(result) { // Launch SSL session std::make_shared<ssl_session>( std::move(socket_), ctx_, std::move(buffer_), doc_root_)->run(); return; } // Launch plain session std::make_shared<plain_session>( std::move(socket_), std::move(buffer_), doc_root_)->run(); } }; // Accepts incoming connections and launches the sessions class listener : public std::enable_shared_from_this<listener> { ssl::context& ctx_; boost::asio::io_service::strand strand_; tcp::acceptor acceptor_; tcp::socket socket_; std::string const& doc_root_; public: listener( boost::asio::io_service& ios, ssl::context& ctx, tcp::endpoint endpoint, std::string const& doc_root) : ctx_(ctx) , strand_(ios) , acceptor_(ios) , socket_(ios) , doc_root_(doc_root) { boost::system::error_code ec; // Open the acceptor acceptor_.open(endpoint.protocol(), ec); if(ec) { fail(ec, "open"); return; } // Bind to the server address acceptor_.bind(endpoint, ec); if(ec) { fail(ec, "bind"); return; } // Start listening for connections acceptor_.listen( boost::asio::socket_base::max_connections, ec); if(ec) { fail(ec, "listen"); return; } } // Start accepting incoming connections void run() { if(! acceptor_.is_open()) return; do_accept(); } void do_accept() { acceptor_.async_accept( socket_, std::bind( &listener::on_accept, shared_from_this(), std::placeholders::_1)); } void on_accept(boost::system::error_code ec) { if(ec) { fail(ec, "accept"); } else { // Create the detector session and run it std::make_shared<detect_session>( std::move(socket_), ctx_, doc_root_)->run(); } // Accept another connection do_accept(); } }; //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { // Check command line arguments. if (argc != 5) { std::cerr << "Usage: http-server-sync <address> <port> <doc_root> <threads>\n" << "Example:\n" << " http-server-sync 0.0.0.0 8080 .\n"; return EXIT_FAILURE; } auto const address = boost::asio::ip::address::from_string(argv[1]); auto const port = static_cast<unsigned short>(std::atoi(argv[2])); std::string const doc_root = argv[3]; auto const threads = std::max<std::size_t>(1, std::atoi(argv[4])); // The io_service is required for all I/O boost::asio::io_service ios{threads}; // The SSL context is required, and holds certificates ssl::context ctx{ssl::context::sslv23}; // This holds the self-signed certificate used by the server load_server_certificate(ctx); // Create and launch a listening port std::make_shared<listener>( ios, ctx, tcp::endpoint{address, port}, doc_root)->run(); // Run the I/O service on the requested number of threads std::vector<std::thread> v; v.reserve(threads - 1); for(auto i = threads - 1; i > 0; --i) v.emplace_back( [&ios] { ios.run(); }); ios.run(); return EXIT_SUCCESS; }
Voultapher/Presentations
old/cppcon-2017-web-service/example/server/beast/lib/beast/example/http/server/flex/http_server_flex.cpp
C++
apache-2.0
19,006
package utils; import java.util.ArrayList; import java.util.List; /** * Utility tree class, where the children are not necessarily ordered in any * particular way besides their locations. * * @author tetigi * * @param <T> * Type of the data node */ public class UnorderedTree<T> implements Tree<T> { private final ArrayList<Tree<T>> children = new ArrayList<Tree<T>>(); private T value; @SafeVarargs public UnorderedTree(final T val, final Tree<T>... trees) { value = val; for (final Tree<T> t : trees) { children.add(t); } } public UnorderedTree(final T val) { value = val; } public UnorderedTree() { value = null; } @Override public void map(final utils.Tree.TreeFunc<T> f) { for (final Tree<T> t : children) { t.setValue(f.mapFunction(t.getValue())); t.map(f); } } @Override public Tree<T> getChild(final int index) { return children.get(index); } @Override public void printTree() { System.out.println(value); for (final Tree<T> t : children) { t.printTree(); } } @Override public <U> Tree<U> transform(final utils.Tree.TreeTFunc<T, U> f) { final UnorderedTree<U> ret = new UnorderedTree<U>(); for (final Tree<T> t : children) { ret.setValue(f.transform(t.getValue())); ret.addChild(t.transform(f)); } return ret; } @Override public void addChild(final Tree<T> t) { children.add(t); } @Override public T getValue() { return value; } @Override public void setValue(final T t) { value = t; } @Override public boolean isLeaf() { return (children.size() == 0); } @Override public <U> Tree<U> depthFirstTransform(utils.Tree.TreeNodeTFunc<T, U> f) { return f.transformTree(this); } @Override public List<Tree<T>> getChildren() { return children; } @Override public void setChildren(List<Tree<T>> children) { this.children.clear(); this.children.addAll(children); } /* * (non-Javadoc) * * @see utils.Tree#setChildren(java.util.List) */ @Override public void addChildren(List<Tree<T>> children) { this.children.addAll(children); } }
tetigi/toucan
java/src/utils/UnorderedTree.java
Java
apache-2.0
2,232
/* * Copyright 2020 Google LLC * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datastream/v1alpha1/datastream.proto package com.google.cloud.datastream.v1alpha1; /** Protobuf type {@code google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest} */ public final class DeleteConnectionProfileRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) DeleteConnectionProfileRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteConnectionProfileRequest.newBuilder() to construct. private DeleteConnectionProfileRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteConnectionProfileRequest() { name_ = ""; requestId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteConnectionProfileRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private DeleteConnectionProfileRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); requestId_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto .internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto .internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.class, com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUEST_ID_FIELD_NUMBER = 2; private volatile java.lang.Object requestId_; /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The requestId. */ @java.lang.Override public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } } /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for requestId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requestId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requestId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest)) { return super.equals(obj); } com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest other = (com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) obj; if (!getName().equals(other.getName())) return false; if (!getRequestId().equals(other.getRequestId())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** Protobuf type {@code google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto .internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto .internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.class, com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.Builder.class); } // Construct using // com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; requestId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datastream.v1alpha1.CloudDatastreamServiceProto .internal_static_google_cloud_datastream_v1alpha1_DeleteConnectionProfileRequest_descriptor; } @java.lang.Override public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest getDefaultInstanceForType() { return com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest build() { com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest buildPartial() { com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest result = new com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest(this); result.name_ = name_; result.requestId_ = requestId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) { return mergeFrom( (com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest other) { if (other == com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest .getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getRequestId().isEmpty()) { requestId_ = other.requestId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * * * <pre> * Required. The name of the connection profile resource to delete. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object requestId_ = ""; /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The requestId. */ public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for requestId. */ public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The requestId to set. * @return This builder for chaining. */ public Builder setRequestId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearRequestId() { requestId_ = getDefaultInstance().getRequestId(); onChanged(); return this; } /** * * * <pre> * Optional. A request ID to identify requests. Specify a unique request ID * so that if you must retry your request, the server will know to ignore * the request if it has already been completed. The server will guarantee * that for at least 60 minutes after the first request. * For example, consider a situation where you make an initial request and the * request times out. If you make the request again with the same request ID, * the server can check if original operation with the same request ID was * received, and if so, will ignore the second request. This prevents clients * from accidentally creating duplicate commitments. * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for requestId to set. * @return This builder for chaining. */ public Builder setRequestIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest) private static final com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest(); } public static com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteConnectionProfileRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteConnectionProfileRequest>() { @java.lang.Override public DeleteConnectionProfileRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DeleteConnectionProfileRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DeleteConnectionProfileRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteConnectionProfileRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datastream.v1alpha1.DeleteConnectionProfileRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-datastream
proto-google-cloud-datastream-v1alpha1/src/main/java/com/google/cloud/datastream/v1alpha1/DeleteConnectionProfileRequest.java
Java
apache-2.0
32,578
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.sena.mavenproject2.model.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Enrique */ @Entity @Table(name = "instructor_ficha") @XmlRootElement @NamedQueries({ @NamedQuery(name = "InstructorFicha.findAll", query = "SELECT i FROM InstructorFicha i") , @NamedQuery(name = "InstructorFicha.findByTipoDocumento", query = "SELECT i FROM InstructorFicha i WHERE i.instructorFichaPK.tipoDocumento = :tipoDocumento") , @NamedQuery(name = "InstructorFicha.findByNumeroDocumento", query = "SELECT i FROM InstructorFicha i WHERE i.instructorFichaPK.numeroDocumento = :numeroDocumento") , @NamedQuery(name = "InstructorFicha.findByFicha", query = "SELECT i FROM InstructorFicha i WHERE i.instructorFichaPK.ficha = :ficha")}) public class InstructorFicha implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected InstructorFichaPK instructorFichaPK; @JoinColumns({ @JoinColumn(name = "tipo_documento", referencedColumnName = "tipo_documento", nullable = false, insertable = false, updatable = false) , @JoinColumn(name = "numero_documento", referencedColumnName = "numero_documento", nullable = false, insertable = false, updatable = false)}) @ManyToOne(optional = false, fetch = FetchType.LAZY) private Cliente cliente; @JoinColumn(name = "ficha", referencedColumnName = "numero_ficha", nullable = false, insertable = false, updatable = false) @ManyToOne(optional = false, fetch = FetchType.LAZY) private Ficha ficha1; @OneToMany(cascade = CascadeType.ALL, mappedBy = "instructorFicha", fetch = FetchType.LAZY) private Collection<InstructorHasTrimestre> instructorHasTrimestreCollection; public InstructorFicha() { } public InstructorFicha(InstructorFichaPK instructorFichaPK) { this.instructorFichaPK = instructorFichaPK; } public InstructorFicha(String tipoDocumento, String numeroDocumento, String ficha) { this.instructorFichaPK = new InstructorFichaPK(tipoDocumento, numeroDocumento, ficha); } public InstructorFichaPK getInstructorFichaPK() { return instructorFichaPK; } public void setInstructorFichaPK(InstructorFichaPK instructorFichaPK) { this.instructorFichaPK = instructorFichaPK; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Ficha getFicha1() { return ficha1; } public void setFicha1(Ficha ficha1) { this.ficha1 = ficha1; } @XmlTransient public Collection<InstructorHasTrimestre> getInstructorHasTrimestreCollection() { return instructorHasTrimestreCollection; } public void setInstructorHasTrimestreCollection(Collection<InstructorHasTrimestre> instructorHasTrimestreCollection) { this.instructorHasTrimestreCollection = instructorHasTrimestreCollection; } @Override public int hashCode() { int hash = 0; hash += (instructorFichaPK != null ? instructorFichaPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof InstructorFicha)) { return false; } InstructorFicha other = (InstructorFicha) object; if ((this.instructorFichaPK == null && other.instructorFichaPK != null) || (this.instructorFichaPK != null && !this.instructorFichaPK.equals(other.instructorFichaPK))) { return false; } return true; } @Override public String toString() { return "co.edu.sena.mavenproject2.model.entities.InstructorFicha[ instructorFichaPK=" + instructorFichaPK + " ]"; } }
SENA-CEET/1349397-Trimestre-4
java/JSF/mavenproject2/src/main/java/co/edu/sena/mavenproject2/model/entities/InstructorFicha.java
Java
apache-2.0
4,558
// "use strict"; var AppDispatcher = require('../dispatcher/AppDispatcher'); var StationEquipmentAlarmConstants = require('../constants/StationEquipmentAlarmConstants'); var StationEquipmentAlarmsWebApiUtils = require('../webapiutils/StationEquipmentAlarmsWebApiUtils') var Station = require('../domain/Station'); var StationEquipmentAlarmActionCreators = { loadDefectData: function(station){ console.assert(station instanceof Station); AppDispatcher.dispatch({ action: StationEquipmentAlarmConstants.ActionTypes.GET_EQUIPMENT_ALARMS, payload: station }); StationEquipmentAlarmsWebApiUtils.getEquipmentAlarms(station); } }; module.exports = StationEquipmentAlarmActionCreators;
DForshner/ReactFluxDashboardProto
ReactFluxDashboardProto.Web/Scripts/App/actions/StationEquipmentAlarmActionCreators.js
JavaScript
apache-2.0
733
// Copyright 2017 Yahoo Inc. // Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms. package com.yahoo.bard.webservice.table; import com.yahoo.bard.webservice.data.time.Granularity; import com.yahoo.bard.webservice.util.Utils; import java.util.LinkedHashSet; import java.util.Optional; import java.util.Set; /** * An interface describing a table or table-like entity composed of sets of columns. */ public interface Schema { /** * Get all the columns underlying this Schema. * * @return The columns of this schema */ Set<Column> getColumns(); /** * Get the time granularity for this Schema. * * @return The time granularity of this schema */ Granularity getGranularity(); /** * Getter for set of columns by sub-type. * * @param columnClass The class of columns to to search * @param <T> sub-type of Column to return * * @return Set of Columns */ default <T extends Column> LinkedHashSet<T> getColumns(Class<T> columnClass) { return Utils.getSubsetByType(getColumns(), columnClass); } /** * Given a column type and name, return the column of the expected type. * * @param name The name on the column * @param columnClass The class of the column being retrieved * @param <T> The type of the subclass of the column being retrieved * * @return The an optional containing the column of the name and type specified, if any */ default <T extends Column> Optional<T> getColumn(String name, Class<T> columnClass) { return getColumns(columnClass).stream() .filter(column -> column.getName().equals(name)) .findFirst(); } }
yahoo/fili
fili-core/src/main/java/com/yahoo/bard/webservice/table/Schema.java
Java
apache-2.0
1,788
/* * Copyright 2014-2016 Samsung Research America, Inc. * * 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. */ /* * String literal * * @author colin.gordon */ package com.samsung.sjs.backend.asts.ir; public class Str extends Expression { private String s; public Str(String s) { super(Tag.Str); this.s = s; } public String getValue() { return s; } @Override public String toSource(int x) { return "\""+s+"\""; } @Override public <R> R accept(IRVisitor<R> v) { return v.visitStr(this); } @Override public boolean isPure() { return true; } @Override public boolean isConst() { return true; } @Override public boolean mustSaveIntermediates() { return false; } }
csgordon/SJS
sjsc/src/main/java/com/samsung/sjs/backend/asts/ir/Str.java
Java
apache-2.0
1,266
/* * 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. */ package org.apache.activemq.transport.amqp.client.transport; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketVersion; /** * Transport for communicating over WebSockets */ public class NettyWSTransport extends NettyTcpTransport { private static final Logger LOG = LoggerFactory.getLogger(NettyWSTransport.class); private static final String AMQP_SUB_PROTOCOL = "amqp"; /** * Create a new transport instance * * @param remoteLocation * the URI that defines the remote resource to connect to. * @param options * the transport options used to configure the socket connection. */ public NettyWSTransport(URI remoteLocation, NettyTransportOptions options) { this(null, remoteLocation, options); } /** * Create a new transport instance * * @param listener * the TransportListener that will receive events from this Transport. * @param remoteLocation * the URI that defines the remote resource to connect to. * @param options * the transport options used to configure the socket connection. */ public NettyWSTransport(NettyTransportListener listener, URI remoteLocation, NettyTransportOptions options) { super(listener, remoteLocation, options); } @Override public void send(ByteBuf output) throws IOException { checkConnected(); int length = output.readableBytes(); if (length == 0) { return; } LOG.trace("Attempted write of: {} bytes", length); channel.writeAndFlush(new BinaryWebSocketFrame(output)); } @Override protected ChannelInboundHandlerAdapter createChannelHandler() { return new NettyWebSocketTransportHandler(); } @Override protected void addAdditionalHandlers(ChannelPipeline pipeline) { pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(8192)); } @Override protected void handleConnected(Channel channel) throws Exception { LOG.trace("Channel has become active, awaiting WebSocket handshake! Channel is {}", channel); } // ----- Handle connection events -----------------------------------------// private class NettyWebSocketTransportHandler extends NettyDefaultHandler<Object> { private final WebSocketClientHandshaker handshaker; NettyWebSocketTransportHandler() { handshaker = WebSocketClientHandshakerFactory.newHandshaker( getRemoteLocation(), WebSocketVersion.V13, AMQP_SUB_PROTOCOL, true, new DefaultHttpHeaders(), getMaxFrameSize()); } @Override public void channelActive(ChannelHandlerContext context) throws Exception { handshaker.handshake(context.channel()); super.channelActive(context); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception { LOG.trace("New data read: incoming: {}", message); Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) message); LOG.trace("WebSocket Client connected! {}", ctx.channel()); // Now trigger super processing as we are really connected. NettyWSTransport.super.handleConnected(ch); return; } // We shouldn't get this since we handle the handshake previously. if (message instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) message; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) message; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; LOG.warn("WebSocket Client received message: " + textFrame.text()); ctx.fireExceptionCaught(new IOException("Received invalid frame over WebSocket.")); } else if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame; LOG.trace("WebSocket Client received data: {} bytes", binaryFrame.content().readableBytes()); listener.onData(binaryFrame.content()); } else if (frame instanceof PingWebSocketFrame) { LOG.trace("WebSocket Client received ping, response with pong"); ch.write(new PongWebSocketFrame(frame.content())); } else if (frame instanceof CloseWebSocketFrame) { LOG.trace("WebSocket Client received closing"); ch.close(); } } } }
cshannon/activemq-artemis
tests/artemis-test-support/src/main/java/org/apache/activemq/transport/amqp/client/transport/NettyWSTransport.java
Java
apache-2.0
6,723
var expect = require('chai').expect describe('Pane', function () { describe('# Show pane', function () { it('should show a lateral pane when requested (click on data feature)', function () { const pane = require('../src/pane') expect(pane.show).to.be.a('function') pane.show() expect(document.getElementById('pane')).not.to.be.null }) }) describe('# Close pane', function () { it('should empty lateral pane when requested (click on map or click on close button)', function () { const pane = require('../src/pane') expect(pane.close).to.be.a('function') pane.close() expect(document.getElementById('pane').hasChildNodes()).to.be.false }) }) describe('# Show feature in pane', function () { const pane = require('../src/pane') const parcelFeature = require('./fixtures').getGoogleMapsParcelFeature() it('should have a hero header section with an image button', function () { pane.show(parcelFeature) var sectionsHeroHeader = document.getElementById('pane').getElementsByClassName('section-hero-header') expect(sectionsHeroHeader).to.not.be.null expect(sectionsHeroHeader.length).to.be.equal(1, '1 and only 1 section hero header') var sectionHeroHeader = sectionsHeroHeader[0] expect(sectionHeroHeader.getElementsByTagName('button')).to.not.be.null expect(sectionHeroHeader.getElementsByTagName('button').length).to.be.least(1, 'Almost a button in section-hero-header') var imageButton = sectionHeroHeader.getElementsByTagName('button')[0] expect(imageButton.getElementsByTagName('img')).to.not.be.null expect(imageButton.getElementsByTagName('img').length).to.be.least(1, 'Almost an image in the button of section-hero-header') }) it('and with a description in the hero header section', function () { pane.show(parcelFeature) var sectionHeroHeader = document.getElementById('pane').getElementsByClassName('section-hero-header')[0] expect(sectionHeroHeader.getElementsByClassName('section-hero-header-description')).to.not.be.null expect(sectionHeroHeader.getElementsByClassName('section-hero-header-description').length).to.be.least(1, 'Almost a description in section-hero-header') var description = sectionHeroHeader.getElementsByClassName('section-hero-header-description')[0] expect(description.getElementsByClassName('section-hero-header-title')).to.not.be.null expect(description.getElementsByClassName('section-hero-header-title').length).to.be.least(1, 'Almost a title in section-hero-header') expect(description.getElementsByTagName('h1').length).to.be.least(1, 'Almost a title in section-hero-header') expect(description.getElementsByTagName('h1')[0].textContent).to.be.equal(parcelFeature.properties.nationalCadastralReference, 'Title with the national cadastral reference of the selected parcel') expect(description.getElementsByClassName('section-hero-header-container')).to.not.be.null expect(description.getElementsByClassName('section-hero-header-description-container').length).to.be.least(1, 'Almost a description container in section-hero-header') }) it('should have an action section', function () { pane.show(parcelFeature) var sectionsAction = document.getElementById('pane').getElementsByClassName('section-action') expect(sectionsAction).to.not.be.null expect(sectionsAction.length).to.be.equal(1, '1 and only 1 action section') var sectionAction = sectionsAction[0] var buttons = sectionAction.getElementsByTagName('button') expect(buttons).to.not.be.null expect(buttons.length).to.be.equal(4, 'Four action buttons in the action section') }) }) })
ilice/OSCWeb
test/pane.test.js
JavaScript
apache-2.0
3,763
/***************************************************************************** * Copyright 2016 Aurora Solutions * * http://www.aurorasolutions.io * * Aurora Solutions is an innovative services and product company at * the forefront of the software industry, with processes and practices * involving Domain Driven Design(DDD), Agile methodologies to build * scalable, secure, reliable and high performance products. * * TradeSharp is a C# based data feed and broker neutral Algorithmic * Trading Platform that lets trading firms or individuals automate * any rules based trading strategies in stocks, forex and ETFs. * TradeSharp allows users to connect to providers like Tradier Brokerage, * IQFeed, FXCM, Blackwood, Forexware, Integral, HotSpot, Currenex, * Interactive Brokers and more. * Key features: Place and Manage Orders, Risk Management, * Generate Customized Reports etc * * 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. *****************************************************************************/ using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TradeHub.UserInterface.BootStrap")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TradeHub.UserInterface.BootStrap")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
trade-nexus/tradesharp-core
Backend/TradeHubUserInterface/TradeHub.UserInterface.BootStrap/Properties/AssemblyInfo.cs
C#
apache-2.0
3,813
package br.com.caelum.designpatterns.decorator.imposto; import br.com.caelum.designpatterns.modelo.Orcamento; public class ICMS extends Imposto{ public ICMS(Imposto outroImposto) { super(outroImposto); } public ICMS() { } public double calcula(Orcamento orcamento){ return orcamento.getValor() * 0.1 + calculoDoOutroImposto(orcamento); } }
sedesdev/design-patterns
src/br/com/caelum/designpatterns/decorator/imposto/ICMS.java
Java
apache-2.0
358
package com.xinqihd.sns.gameserver.admin.i18n; import java.util.HashMap; public class ColumnNames { private static HashMap<String, String> map = new HashMap<String, String>(); static { map.put("profile" , "profile"); map.put("vip" , "vip"); map.put("ability" , "ability"); map.put("login" , "登陆"); map.put("config" , "配置"); map.put("wealth" , "wealth"); map.put("loc" , "位置"); map.put("tools" , "便携道具"); map.put("wears" , "wears"); map.put("count" , "count"); map.put("items" , "items"); map.put("class" , "class"); map.put("name" , "名称"); map.put("type" , "类型"); map.put("reqlv" , "reqlv"); map.put("scrollAreaX" , "scrollAreaX"); map.put("scrollAreaY" , "scrollAreaY"); map.put("scrollAreaWidth" , "scrollAreaWidth"); map.put("scrollAreaHeight" , "scrollAreaHeight"); map.put("layers" , "layers"); map.put("bgm" , "bgm"); map.put("damage" , "damage"); map.put("bosses" , "bosses"); map.put("enemies" , "enemies"); map.put("startPoints" , "startPoints"); map.put("index" , "index"); map.put("quality" , "品质"); map.put("qualityColor" , "品质颜色"); map.put("sName" , "名称"); map.put("equipType" , "装备类型"); map.put("addAttack" , "加攻击"); map.put("addDefend" , "加防御"); map.put("addAgility" , "加敏捷"); map.put("addLuck" , "加幸运"); map.put("addBlood" , "加血量"); map.put("addBloodPercent" , "加血量比例"); map.put("addThew" , "加体力"); map.put("addDamage" , "加伤害"); map.put("addSkin" , "加护甲"); map.put("sex" , "性别"); map.put("unused1" , "unused1"); map.put("unused2" , "unused2"); map.put("unused3" , "unused3"); map.put("indate1" , "indate1"); map.put("indate2" , "indate2"); map.put("indate3" , "indate3"); map.put("sign" , "sign"); map.put("lv" , "lv"); map.put("autoDirection" , "自动定位"); map.put("sAutoDirection" , "大招定位"); map.put("specialAction" , "特殊攻击"); map.put("radius" , "攻击半径"); map.put("sRadius" , "大招攻击半径"); map.put("expBlend" , "混合(不用)"); map.put("expSe" , "音效"); map.put("power" , "战斗力(未使用)"); map.put("autoDestory" , "自动伤害"); map.put("bullet" , "子弹标识"); map.put("icon" , "图标"); map.put("info" , "描述"); map.put("bubble" , "bubble"); map.put("slot" , "卡槽"); map.put("avatar" , "形象"); map.put("propInfoId" , "propInfoId"); map.put("level" , "level"); map.put("moneyType" , "货币类型"); map.put("buyPrices" , "购买价格"); map.put("banded" , "是否绑定"); map.put("discount" , "折扣"); map.put("sell" , "出售"); map.put("limitCount" , "limitCount"); map.put("limitGroup" , "limitGroup"); map.put("shopId" , "shopId"); map.put("isItem" , "isItem"); map.put("catalogs" , "商品目录"); map.put("desc" , "描述"); map.put("taskTarget" , "taskTarget"); map.put("step" , "步骤(step)"); map.put("exp" , "经验"); map.put("gold" , "金币"); map.put("ticket" , "礼券"); map.put("gongxun" , "功勋"); map.put("caifu" , "财富"); map.put("seq" , "顺序(seq)"); map.put("userLevel" , "用户等级"); map.put("script" , "脚本"); map.put("awards" , "奖励"); map.put("rival" , "rival"); map.put("typeId" , "typeId"); map.put("q" , "概率q"); map.put("rewards" , "奖励"); map.put("conditions" , "开启条件"); map.put("dayNum" , "天数"); map.put("price" , "价格"); map.put("currency" , "货币"); map.put("yuanbao" , "元宝"); map.put("isHotSale" , "是否热卖"); map.put("month" , "月"); map.put("yuanbaoPrice" , "元宝价格"); map.put("voucherPrice" , "礼券价格"); map.put("medalPrice" , "勋章价格"); } public static String translate(String columnName) { String name = map.get(columnName); if ( name != null ) { return name; } return columnName; } }
wangqi/gameserver
admin/src/main/java/com/xinqihd/sns/gameserver/admin/i18n/ColumnNames.java
Java
apache-2.0
3,924
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <?php echo "{\"Relay0\":"; echo apc_fetch('Relay0'); echo "}"; ?> </body> </html>
SpenceKonde/MagicMirror
php/test2.php
PHP
apache-2.0
201
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP export default { 'People Finder': 'Localizador de Pessoas', 'Groups Finder': 'Localizador de Grupos', 'Locations Finder': 'Localizador de Locais', 'People': 'Pessoas', 'Groups': 'Grupos', 'Locations': 'Locais', 'Organization': 'Organização', 'Details': 'Detalhes', 'Owners': 'Proprietários', 'Search': 'Buscar', 'No matching people': 'Nenhuma pessoa encontrada', 'No matching groups': 'Nenhum grupo encontrado', 'No matching locations': 'Nenhuma localização encontrada', 'People matching': 'Pessoas correspondentes {search}', 'Groups matching': 'Grupos correspondentes {search}', 'Locations matching': 'Locais correspondentes {search}', 'Refine search to find more': 'Refinar a pesquisa para encontrar mais.', };
grommet/grommet-people-finder
src/messages/pt-BR.js
JavaScript
apache-2.0
822
require 'spec_helper' require 'gitlab/build/image' RSpec.describe Build::Image do ComponentImage = Class.new do extend Build::Image def self.gitlab_registry_image_name 'my-project/my-image' end def self.dockerhub_image_name 'my-image' end end before do allow(ENV).to receive(:[]).and_call_original allow(ENV).to receive(:[]).with('CI_JOB_TOKEN').and_return('1234') allow(ENV).to receive(:[]).with('CI_REGISTRY').and_return('registry.com') allow(ENV).to receive(:[]).with('CI_REGISTRY_IMAGE').and_return('registry.com/group/repo') allow(ENV).to receive(:[]).with('DOCKERHUB_USERNAME').and_return('john') allow(ENV).to receive(:[]).with('DOCKERHUB_PASSWORD').and_return('secret') allow(Build::Info).to receive(:docker_tag).and_return('9.0.0') end describe '.pull' do it 'creates an image from the local one' do expect(Docker::Image).to receive(:create).with( 'fromImage' => "#{ComponentImage.gitlab_registry_image_address}:9.0.0" ) ComponentImage.pull end end describe '.gitlab_registry_image_address' do it 'returns a correct image name' do expect(ComponentImage.gitlab_registry_image_address).to eq('registry.com/group/repo/my-project/my-image') end context 'with a tag given' do it 'returns a correct image name' do expect(ComponentImage.gitlab_registry_image_address(tag: 'mytag')).to eq('registry.com/group/repo/my-project/my-image:mytag') end end end describe '.tag_and_push_to_gitlab_registry' do it 'calls DockerOperations.authenticate and DockerOperations.tag_and_push' do expect(DockerOperations).to receive(:authenticate).with('gitlab-ci-token', '1234', 'registry.com') expect(DockerOperations).to receive(:tag_and_push).with( ComponentImage.gitlab_registry_image_address, ComponentImage.gitlab_registry_image_address, 'latest', 'foo' ) ComponentImage.tag_and_push_to_gitlab_registry('foo') end end describe '.tag_and_push_to_dockerhub' do it 'calls DockerOperations.authenticate and DockerOperations.tag_and_push' do expect(DockerOperations).to receive(:authenticate).with('john', 'secret') expect(DockerOperations).to receive(:tag_and_push).with( ComponentImage.gitlab_registry_image_address, ComponentImage.dockerhub_image_name, '9.0.0', 'foo' ) ComponentImage.tag_and_push_to_dockerhub('foo') end context 'with a initial_tag given' do it 'calls DockerOperations.authenticate and DockerOperations.tag_and_push' do expect(DockerOperations).to receive(:authenticate).with('john', 'secret') expect(DockerOperations).to receive(:tag_and_push).with( ComponentImage.gitlab_registry_image_address, ComponentImage.dockerhub_image_name, 'latest', 'foo' ) ComponentImage.tag_and_push_to_dockerhub('foo', initial_tag: 'latest') end end end describe '.write_release_file' do describe 'with triggered build' do let(:release_file) do [ "PACKAGECLOUD_REPO=download-package", "RELEASE_VERSION=12.121.12-ce.1", "DOWNLOAD_URL=https://gitlab.com/api/v4/projects/1/jobs/1/artifacts/pkg/ubuntu-focal/gitlab.deb", "TRIGGER_PRIVATE_TOKEN=NOT-PRIVATE-TOKEN\n" ] end before do stub_env_var('PACKAGECLOUD_REPO', 'download-package') stub_env_var('TRIGGER_PRIVATE_TOKEN', 'NOT-PRIVATE-TOKEN') stub_env_var('CI_PROJECT_ID', '1') stub_env_var('CI_PIPELINE_ID', '2') allow(Build::Info).to receive(:release_version).and_return('12.121.12-ce.1') allow(Build::Info).to receive(:fetch_artifact_url).with('1', '2').and_return('1') end describe 'for CE' do before do allow(Build::Info).to receive(:package).and_return('gitlab-ce') end it 'returns build version and iteration with env variable' do release_file_content = release_file.insert(1, 'RELEASE_PACKAGE=gitlab-ce').join("\n") expect(ComponentImage.write_release_file).to eq(release_file_content) end end describe 'for EE' do before do allow(Build::Info).to receive(:package).and_return('gitlab-ee') end it 'returns build version and iteration with env variable' do release_file_content = release_file.insert(1, 'RELEASE_PACKAGE=gitlab-ee').join("\n") expect(ComponentImage.write_release_file).to eq(release_file_content) end end describe 'with regular build' do let(:s3_download_link) { 'https://downloads-packages.s3.amazonaws.com/ubuntu-focal/gitlab-ee_12.121.12-ce.1_amd64.deb' } let(:release_file) do [ "RELEASE_VERSION=12.121.12-ce.1", "DOWNLOAD_URL=#{s3_download_link}\n", ] end before do stub_env_var('PACKAGECLOUD_REPO', '') stub_env_var('TRIGGER_PRIVATE_TOKEN', '') stub_env_var('CI_PROJECT_ID', '') stub_env_var('CI_PIPELINE_ID', '') allow(Build::Check).to receive(:on_tag?).and_return(true) allow(Build::Info).to receive(:package).and_return('gitlab-ee') allow(ComponentImage).to receive(:release_version).and_return('12.121.12-ce.1') end it 'returns build version and iteration with env variable' do release_file_content = release_file.insert(0, 'RELEASE_PACKAGE=gitlab-ee').join("\n") expect(ComponentImage.write_release_file).to eq(release_file_content) end end end end end
gitlabhq/omnibus-gitlab
spec/gitlab/build/image_spec.rb
Ruby
apache-2.0
5,717
package com.anteoy.coreJava.reflect; import java.lang.reflect.Method; public class BeanUtil { /** * ���ݱ�׼javaBean�������������ȡ������ֵ * * @param obj * @param propertyName * @return */ public static Object getValueByPropertyName(Object obj, String propertyName) { // 1.�����������ƾͿ��Ի�ȡ��get���� String getMethodName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); //2.��ȡ�������� Class c = obj.getClass(); try { //get��������public�����޲��� Method m = c.getMethod(getMethodName); //3 ͨ�������ķ���������� Object value = m.invoke(obj); return value; } catch (Exception e) { e.printStackTrace(); return null; } } }
Anteoy/jottings
src/main/java/com/anteoy/coreJava/reflect/BeanUtil.java
Java
apache-2.0
1,049
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EENamedTypeSymbol : NamedTypeSymbol { internal readonly NamedTypeSymbol SubstitutedSourceType; internal readonly ImmutableArray<TypeParameterSymbol> SourceTypeParameters; private readonly NamespaceSymbol _container; private readonly NamedTypeSymbol _baseType; private readonly string _name; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<MethodSymbol> _methods; internal EENamedTypeSymbol( NamespaceSymbol container, NamedTypeSymbol baseType, CSharpSyntaxNode syntax, MethodSymbol currentFrame, string typeName, string methodName, CompilationContext context, GenerateMethodBody generateMethodBody) : this(container, baseType, currentFrame, typeName, (m, t) => ImmutableArray.Create<MethodSymbol>(context.CreateMethod(t, methodName, syntax, generateMethodBody))) { } internal EENamedTypeSymbol( NamespaceSymbol container, NamedTypeSymbol baseType, MethodSymbol currentFrame, string typeName, Func<MethodSymbol, EENamedTypeSymbol, ImmutableArray<MethodSymbol>> getMethods, ImmutableArray<TypeParameterSymbol> sourceTypeParameters, Func<NamedTypeSymbol, EENamedTypeSymbol, ImmutableArray<TypeParameterSymbol>> getTypeParameters) { _container = container; _baseType = baseType; _name = typeName; this.SourceTypeParameters = sourceTypeParameters; _typeParameters = getTypeParameters(currentFrame.ContainingType, this); VerifyTypeParameters(this, _typeParameters); _methods = getMethods(currentFrame, this); } internal EENamedTypeSymbol( NamespaceSymbol container, NamedTypeSymbol baseType, MethodSymbol currentFrame, string typeName, Func<MethodSymbol, EENamedTypeSymbol, ImmutableArray<MethodSymbol>> getMethods) { _container = container; _baseType = baseType; _name = typeName; // What we want is to map all original type parameters to the corresponding new type parameters // (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: // 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. // 2) The map cannot be constructed until all new type parameters exist. // Our solution is to pass each new type parameter a lazy reference to the type map. We then // initialize the map as soon as the new type parameters are available - and before they are // handed out - so that there is never a period where they can require the type map and find // it uninitialized. var sourceType = currentFrame.ContainingType; this.SourceTypeParameters = sourceType.GetAllTypeParameters(); TypeMap typeMap = null; var getTypeMap = new Func<TypeMap>(() => typeMap); _typeParameters = this.SourceTypeParameters.SelectAsArray( (tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap), (object)null); typeMap = new TypeMap(this.SourceTypeParameters, _typeParameters); VerifyTypeParameters(this, _typeParameters); this.SubstitutedSourceType = typeMap.SubstituteNamedType(sourceType); TypeParameterChecker.Check(this.SubstitutedSourceType, _typeParameters); _methods = getMethods(currentFrame, this); } internal ImmutableArray<MethodSymbol> Methods { get { return _methods; } } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { return SpecializedCollections.EmptyEnumerable<FieldSymbol>(); } internal override IEnumerable<MethodSymbol> GetMethodsToEmit() { return _methods; } internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return ImmutableArray<NamedTypeSymbol>.Empty; } public override int Arity { get { return _typeParameters.Length; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } internal override ImmutableArray<TypeSymbolWithAnnotations> TypeArgumentsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public override bool MightContainExtensionMethods { get { return false; } } internal override AttributeUsageInfo GetAttributeUsageInfo() { throw ExceptionUtilities.Unreachable; } public override string Name { get { return _name; } } // No additional name mangling since CompileExpression // is providing an explicit type name. internal override bool MangleName { get { return false; } } public override IEnumerable<string> MemberNames { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<Symbol> GetMembers() { return _methods.Cast<MethodSymbol, Symbol>(); } public override ImmutableArray<Symbol> GetMembers(string name) { // Should not be requesting generated members // by name other than constructors. Debug.Assert((name == WellKnownMemberNames.InstanceConstructorName) || (name == WellKnownMemberNames.StaticConstructorName)); return this.GetMembers().WhereAsArray(m => m.Name == name); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { throw ExceptionUtilities.Unreachable; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { throw ExceptionUtilities.Unreachable; } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { throw ExceptionUtilities.Unreachable; } internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<Symbol> basesBeingResolved) { return _baseType; } internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<Symbol> basesBeingResolved) { throw ExceptionUtilities.Unreachable; } internal override bool HasSpecialName { get { return true; } } internal override bool IsComImport { get { return false; } } internal override bool IsWindowsRuntimeImport { get { return false; } } internal override bool ShouldAddWinRTMembers { get { return false; } } public override bool IsSerializable { get { return false; } } internal override TypeLayout Layout { get { return default(TypeLayout); } } internal override System.Runtime.InteropServices.CharSet MarshallingCharSet { get { return System.Runtime.InteropServices.CharSet.Ansi; } } internal override bool HasDeclarativeSecurity { get { return false; } } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable; } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get { return _baseType; } } internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<Symbol> basesBeingResolved) { throw ExceptionUtilities.Unreachable; } public override TypeKind TypeKind { get { return TypeKind.Class; } } public override NamedTypeSymbol ContainingType { get { return null; } } public override Symbol ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsStatic { get { return true; } } public override bool IsAbstract { get { return false; } } internal sealed override bool IsByRefLikeType { get { return false; } } internal sealed override bool IsReadOnly { get { return false; } } public override bool IsSealed { get { return true; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } internal override bool IsInterface { get { return false; } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; [Conditional("DEBUG")] internal static void VerifyTypeParameters(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters) { for (int i = 0; i < typeParameters.Length; i++) { var typeParameter = typeParameters[i]; Debug.Assert((object)typeParameter.ContainingSymbol == (object)container); Debug.Assert(typeParameter.Ordinal == i); } } } }
xasx/roslyn
src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EENamedTypeSymbol.cs
C#
apache-2.0
11,286
package com.adobe.aem.scf.extensions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.jcr.Session; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceUtil; import com.adobe.cq.social.forum.client.api.Post; import com.adobe.cq.social.forum.client.endpoints.ForumOperationExtension; import com.adobe.cq.social.scf.Operation; import com.adobe.cq.social.scf.OperationException; @Component(name = "Ideation Status Extension", immediate = true, metatype = true) @Service public class IdeationStatusExtension implements ForumOperationExtension { @Override public void afterAction(Operation op, Session sessionUsed, Post post, Map<String, Object> props) throws OperationException { // TODO Auto-generated method stub } @Override public void beforeAction(Operation op, Session sessionUsed, Resource requestResource, Map<String, Object> props) throws OperationException { if (ResourceUtil.isA(requestResource, "acme/components/ideation/forum")) { List<String> tags = new ArrayList<String>(); if (props.containsKey("tags")) { final Object v = props.get("tags"); if (!(v instanceof String[])) { if (v instanceof String) { tags.add((String) v); } } else { for (String t : (String[]) v) { tags.add(t); } } } tags.add("acmeideas:new"); props.put("tags", tags.toArray(new String[]{})); } } @Override public String getName() { return "ideation status"; } @Override public int getOrder() { return 1; } @Override public List<ForumOperation> getOperationsToHookInto() { return Arrays.asList(ForumOperation.CREATE); } }
Adobe-Marketing-Cloud/aem-scf-sample-components-extension
bundles/aem-scf-extensions/src/main/java/com/adobe/aem/scf/extensions/IdeationStatusExtension.java
Java
apache-2.0
2,104
import 'mocha'; import { EventRecorder, expect } from '@integration/testing-tools'; import { Ensure, equals } from '@serenity-js/assertions'; import { actorCalled, Question, Serenity } from '@serenity-js/core'; import { ActivityFinished, ActivityRelatedArtifactGenerated, ActivityStarts, ArtifactGenerated } from '@serenity-js/core/lib/events'; import { TextData } from '@serenity-js/core/lib/model'; import { Clock } from '@serenity-js/core/lib/stage'; import { by, ExecuteScript, Navigate, Target, Value } from '../../../../src'; import { Actors } from '../../Actors'; /** @test {ExecuteScript} */ describe('ExecuteAsynchronousScript', function () { class Sandbox { static Input = Target.the('input field').located(by.id('name')); } /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ it('allows the actor to execute an asynchronous script', () => actorCalled('Joe').attemptsTo( Navigate.to('/screenplay/interactions/execute-script/input_field.html'), ExecuteScript.async(` var callback = arguments[arguments.length - 1]; setTimeout(function () { document.getElementById('name').value = 'Joe'; callback(); }, 100); `), Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)), )); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ it('allows the actor to execute an asynchronous script with a static argument', () => actorCalled('Joe').attemptsTo( Navigate.to('/screenplay/interactions/execute-script/input_field.html'), ExecuteScript.async(` var name = arguments[0]; var callback = arguments[arguments.length - 1]; setTimeout(function () { document.getElementById('name').value = name; callback(); }, 100); `).withArguments(actorCalled('Joe').name), Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)), )); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ it('allows the actor to execute an asynchronous script with a promised argument', () => actorCalled('Joe').attemptsTo( Navigate.to('/screenplay/interactions/execute-script/input_field.html'), ExecuteScript.async(` var name = arguments[0]; var callback = arguments[arguments.length - 1]; setTimeout(function () { document.getElementById('name').value = name; callback(); }, 100); `).withArguments(Promise.resolve(actorCalled('Joe').name)), Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)), )); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ it('allows the actor to execute an asynchronous script with a Target argument', () => actorCalled('Joe').attemptsTo( Navigate.to('/screenplay/interactions/execute-script/input_field.html'), ExecuteScript.async(` var name = arguments[0]; var field = arguments[1]; var callback = arguments[arguments.length - 1]; setTimeout(function () { field.value = name; callback(); }, 100); `).withArguments(actorCalled('Joe').name, Sandbox.Input), Ensure.that(Value.of(Sandbox.Input), equals(actorCalled('Joe').name)), )); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ /** @test {ExecuteAsynchronousScript#toString} */ it('provides a sensible description of the interaction being performed when invoked without arguments', () => { expect(ExecuteScript.async(` arguments[arguments.length - 1](); `).toString()).to.equal(`#actor executes an asynchronous script`); }); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript#toString} */ it('provides a sensible description of the interaction being performed when invoked with arguments', () => { const arg3 = Question.about('arg number 3', actor => void 0); expect(ExecuteScript.async(`arguments[arguments.length - 1]();`) .withArguments(Promise.resolve('arg1'), 'arg2', arg3).toString(), ).to.equal(`#actor executes an asynchronous script with arguments: [ a Promise, 'arg2', arg number 3 ]`); }); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ it('complains if the script has failed', () => expect(actorCalled('Joe').attemptsTo( Navigate.to('/screenplay/interactions/execute-script/input_field.html'), ExecuteScript.async(` var callback = arguments[arguments.length - 1]; throw new Error("something's not quite right here"); `), )).to.be.rejectedWith(Error, `something's not quite right here`)); /** @test {ExecuteScript.async} */ /** @test {ExecuteAsynchronousScript} */ it('emits the events so that the details of the script being executed can be reported', () => { const frozenClock = new Clock(() => new Date('1970-01-01')); const serenity = new Serenity(frozenClock); const recorder = new EventRecorder(); serenity.configure({ actors: new Actors(), crew: [ recorder ], }); return serenity.theActorCalled('Ashwin').attemptsTo( ExecuteScript.async(`arguments[arguments.length - 1]();`), ).then(() => { const events = recorder.events; expect(events).to.have.lengthOf(3); expect(events[ 0 ]).to.be.instanceOf(ActivityStarts); expect(events[ 1 ]).to.be.instanceOf(ArtifactGenerated); expect(events[ 2 ]).to.be.instanceOf(ActivityFinished); const artifactGenerated = events[ 1 ] as ActivityRelatedArtifactGenerated; expect(artifactGenerated.name.value).to.equal(`Script source`); expect(artifactGenerated.artifact.equals(TextData.fromJSON({ contentType: 'text/javascript;charset=UTF-8', data: 'arguments[arguments.length - 1]();', }))).to.equal(true, JSON.stringify(artifactGenerated.artifact.toJSON())); expect(artifactGenerated.timestamp.equals(frozenClock.now())).to.equal(true, artifactGenerated.timestamp.toString()); }); }); });
jan-molak/serenity-js
packages/webdriverio/spec/screenplay/interactions/execute-script/ExecuteAsynchronousScript.spec.ts
TypeScript
apache-2.0
6,757
<?php declare(strict_types = 1); namespace ctr; use sys\Ctr; class middle extends Ctr { public function _load() { if (PATH !== 'test/middle') { return true; } return '_action: ' . $this->_action . '<br><br>In fact, the middle method does not exist in the test controller, which uses Mutton\'s middle structure to preprocess requests.'; } }
yunbookf/Chameleon
ctr/middle.php
PHP
apache-2.0
390
module.exports = LocalTransport; function LocalTransport(incoming, options) { options = options || {}; this.name = "local"; this.outgoing = function(destination, message, sender, callback) { setImmediate(incoming(destination, message, callback)); //to make function async, just like other transports? //incoming(destination, message, callback) } }
RemcoTukker/eve-nodejs-remco
services/localTransport.js
JavaScript
apache-2.0
364
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.gml; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.FeatureMap; import org.w3._1999.xlink.ActuateType; import org.w3._1999.xlink.ShowType; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Feature Property Type</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * Container for a feature - follow gml:AssociationType pattern. * <!-- end-model-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link net.opengis.gml.FeaturePropertyType#getFeatureGroup <em>Feature Group</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getFeature <em>Feature</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getArcrole <em>Arcrole</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getHref <em>Href</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getRemoteSchema <em>Remote Schema</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getRole <em>Role</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getTitle <em>Title</em>}</li> * <li>{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}</li> * </ul> * </p> * * @see net.opengis.gml.GmlPackage#getFeaturePropertyType() * @model extendedMetaData="name='FeaturePropertyType' kind='elementOnly'" * @generated */ public interface FeaturePropertyType extends EObject { /** * Returns the value of the '<em><b>Feature Group</b></em>' attribute list. * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Feature Group</em>' attribute list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Feature Group</em>' attribute list. * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_FeatureGroup() * @model dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="false" * extendedMetaData="kind='group' name='_Feature:group' namespace='##targetNamespace'" * @generated */ FeatureMap getFeatureGroup(); /** * Returns the value of the '<em><b>Feature</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Feature</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Feature</em>' containment reference. * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Feature() * @model containment="true" transient="true" changeable="false" volatile="true" derived="true" * extendedMetaData="kind='element' name='_Feature' namespace='##targetNamespace' group='_Feature:group'" * @generated */ AbstractFeatureType getFeature(); /** * Returns the value of the '<em><b>Actuate</b></em>' attribute. * The literals are from the enumeration {@link org.w3._1999.xlink.ActuateType}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * * The 'actuate' attribute is used to communicate the desired timing * of traversal from the starting resource to the ending resource; * it's value should be treated as follows: * onLoad - traverse to the ending resource immediately on loading * the starting resource * onRequest - traverse from the starting resource to the ending * resource only on a post-loading event triggered for * this purpose * other - behavior is unconstrained; examine other markup in link * for hints * none - behavior is unconstrained * * <!-- end-model-doc --> * @return the value of the '<em>Actuate</em>' attribute. * @see org.w3._1999.xlink.ActuateType * @see #isSetActuate() * @see #unsetActuate() * @see #setActuate(ActuateType) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Actuate() * @model unsettable="true" * extendedMetaData="kind='attribute' name='actuate' namespace='http://www.w3.org/1999/xlink'" * @generated */ ActuateType getActuate(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Actuate</em>' attribute. * @see org.w3._1999.xlink.ActuateType * @see #isSetActuate() * @see #unsetActuate() * @see #getActuate() * @generated */ void setActuate(ActuateType value); /** * Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetActuate() * @see #getActuate() * @see #setActuate(ActuateType) * @generated */ void unsetActuate(); /** * Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getActuate <em>Actuate</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Actuate</em>' attribute is set. * @see #unsetActuate() * @see #getActuate() * @see #setActuate(ActuateType) * @generated */ boolean isSetActuate(); /** * Returns the value of the '<em><b>Arcrole</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Arcrole</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Arcrole</em>' attribute. * @see #setArcrole(String) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Arcrole() * @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI" * extendedMetaData="kind='attribute' name='arcrole' namespace='http://www.w3.org/1999/xlink'" * @generated */ String getArcrole(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getArcrole <em>Arcrole</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Arcrole</em>' attribute. * @see #getArcrole() * @generated */ void setArcrole(String value); /** * Returns the value of the '<em><b>Href</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Href</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Href</em>' attribute. * @see #setHref(String) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Href() * @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI" * extendedMetaData="kind='attribute' name='href' namespace='http://www.w3.org/1999/xlink'" * @generated */ String getHref(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getHref <em>Href</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Href</em>' attribute. * @see #getHref() * @generated */ void setHref(String value); /** * Returns the value of the '<em><b>Remote Schema</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Reference to an XML Schema fragment that specifies the content model of the propertys value. This is in conformance with the XML Schema Section 4.14 Referencing Schemas from Elsewhere. * <!-- end-model-doc --> * @return the value of the '<em>Remote Schema</em>' attribute. * @see #setRemoteSchema(String) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_RemoteSchema() * @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI" * extendedMetaData="kind='attribute' name='remoteSchema' namespace='##targetNamespace'" * @generated */ String getRemoteSchema(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getRemoteSchema <em>Remote Schema</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Remote Schema</em>' attribute. * @see #getRemoteSchema() * @generated */ void setRemoteSchema(String value); /** * Returns the value of the '<em><b>Role</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Role</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Role</em>' attribute. * @see #setRole(String) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Role() * @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI" * extendedMetaData="kind='attribute' name='role' namespace='http://www.w3.org/1999/xlink'" * @generated */ String getRole(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getRole <em>Role</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Role</em>' attribute. * @see #getRole() * @generated */ void setRole(String value); /** * Returns the value of the '<em><b>Show</b></em>' attribute. * The literals are from the enumeration {@link org.w3._1999.xlink.ShowType}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * * The 'show' attribute is used to communicate the desired presentation * of the ending resource on traversal from the starting resource; it's * value should be treated as follows: * new - load ending resource in a new window, frame, pane, or other * presentation context * replace - load the resource in the same window, frame, pane, or * other presentation context * embed - load ending resource in place of the presentation of the * starting resource * other - behavior is unconstrained; examine other markup in the * link for hints * none - behavior is unconstrained * * <!-- end-model-doc --> * @return the value of the '<em>Show</em>' attribute. * @see org.w3._1999.xlink.ShowType * @see #isSetShow() * @see #unsetShow() * @see #setShow(ShowType) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Show() * @model unsettable="true" * extendedMetaData="kind='attribute' name='show' namespace='http://www.w3.org/1999/xlink'" * @generated */ ShowType getShow(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Show</em>' attribute. * @see org.w3._1999.xlink.ShowType * @see #isSetShow() * @see #unsetShow() * @see #getShow() * @generated */ void setShow(ShowType value); /** * Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetShow() * @see #getShow() * @see #setShow(ShowType) * @generated */ void unsetShow(); /** * Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getShow <em>Show</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Show</em>' attribute is set. * @see #unsetShow() * @see #getShow() * @see #setShow(ShowType) * @generated */ boolean isSetShow(); /** * Returns the value of the '<em><b>Title</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Title</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Title</em>' attribute. * @see #setTitle(String) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Title() * @model dataType="org.eclipse.emf.ecore.xml.type.String" * extendedMetaData="kind='attribute' name='title' namespace='http://www.w3.org/1999/xlink'" * @generated */ String getTitle(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getTitle <em>Title</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Title</em>' attribute. * @see #getTitle() * @generated */ void setTitle(String value); /** * Returns the value of the '<em><b>Type</b></em>' attribute. * The default value is <code>"simple"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' attribute. * @see #isSetType() * @see #unsetType() * @see #setType(String) * @see net.opengis.gml.GmlPackage#getFeaturePropertyType_Type() * @model default="simple" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.String" * extendedMetaData="kind='attribute' name='type' namespace='http://www.w3.org/1999/xlink'" * @generated */ String getType(); /** * Sets the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' attribute. * @see #isSetType() * @see #unsetType() * @see #getType() * @generated */ void setType(String value); /** * Unsets the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetType() * @see #getType() * @see #setType(String) * @generated */ void unsetType(); /** * Returns whether the value of the '{@link net.opengis.gml.FeaturePropertyType#getType <em>Type</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Type</em>' attribute is set. * @see #unsetType() * @see #getType() * @see #setType(String) * @generated */ boolean isSetType(); } // FeaturePropertyType
markus1978/citygml4emf
de.hub.citygml.emf.ecore/src/net/opengis/gml/FeaturePropertyType.java
Java
apache-2.0
14,502
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.iit.sat.itmd4515.yzhan214.fp.web.hospital; import edu.iit.sat.itmd4515.yzhan214.fp.web.hospital.AbstractJSFBean; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.inject.Named; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author ln1878 */ @Named @RequestScoped public class LoginBean extends AbstractJSFBean{ private static final Logger LOG = Logger.getLogger(LoginBean.class.getName()); @NotNull(message = "You shall not pass without a username!") private String username; @NotNull(message = "You shall not pass without a password!") @Size(min = 5, message = "Password must be at least 5 characters in length.") private String password; /** * */ public LoginBean() { } @PostConstruct private void postConstruct() { super.postContruct(); } /** * * @return */ public boolean isAdmin() { return facesContext.getExternalContext().isUserInRole("admin"); } /** * * @return */ public boolean isDoctor() { return facesContext.getExternalContext().isUserInRole("doctor"); } /** * * @return */ public boolean isAssistant() { return facesContext.getExternalContext().isUserInRole("vetassistant"); } /** * * @return */ public boolean isPetOwner() { return facesContext.getExternalContext().isUserInRole("petowner"); } /** * * @param path * @return */ public String getPortalPathByRole(String path) { LOG.info("Inside LoginBean getPortal"); if (isAdmin()) { return "/admin" + path; } else if (isDoctor()) { return "/doctorPortal" + path; } else if (isAssistant()) { return "/assistantPortal" + path; } else if(isPetOwner()) { return "/petownerPortal" + path; } else { return path ; } } /** * * @return */ public String doLogin() { HttpServletRequest req = (HttpServletRequest) facesContext.getExternalContext().getRequest(); try { req.login(username, password); } catch (ServletException ex) { LOG.log(Level.SEVERE, null, ex); facesContext.addMessage(null, new FacesMessage("Bad Login", "Detail: You made a bad login!")); return "/login.xhtml"; } return getPortalPathByRole("/welcome.xhtml"); } /** * * @return */ public String doLogout() { HttpServletRequest req = (HttpServletRequest) facesContext.getExternalContext().getRequest(); try { req.logout(); } catch (ServletException ex) { LOG.log(Level.SEVERE,"There has been a problem invoking HttpServletRequest.logout",ex); facesContext.addMessage(null, new FacesMessage("Bad Logout", "Detail:There was a problem with the logout")); return "/error.xhtml"; } return "/index.xhtml"; } /** * * @return */ public String getRemoteUser() { return facesContext.getExternalContext().getRemoteUser(); } /** * Get the value of password * * @return the value of password */ public String getPassword() { return password; } /** * Set the value of password * * @param password new value of password */ public void setPassword(String password) { this.password = password; } /** * Get the value of username * * @return the value of username */ public String getUsername() { return username; } /** * Set the value of username * * @param username new value of username */ public void setUsername(String username) { this.username = username; } }
Langenoir1878/vet_web
src/main/java/web/hospital/LoginBean.java
Java
apache-2.0
4,588
export const GET = 'GET'; export const PUT = 'PUT'; export const POST = 'POST'; export const DELETE = 'DELETE';
adioss/MyWebAppBootstrap
src/main/resources/static/js/apis/ApiConstants.js
JavaScript
apache-2.0
111
package com.twopillar.jiba.activity; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.FragmentTabHost; import android.view.KeyEvent; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Toast; import com.twopillar.jiba.R; import com.twopillar.jiba.fragment.ActionFragment; import com.twopillar.jiba.fragment.BBSFragment; import com.twopillar.jiba.fragment.MeFragment; import com.twopillar.jiba.fragment.PlanFragment; public class MainActivity extends BaseActivity{ private FragmentTabHost mTabHost; private RadioGroup radioGroup; private RadioButton plan;//计划 private RadioButton action;//动作 private RadioButton bbs;//论坛 private RadioButton me;//我 private long exitTime = 0; String tabs[] = {"Tab1","Tab2","Tab3","Tab4"}; Class cls[] = {PlanFragment.class,ActionFragment.class,BBSFragment.class,MeFragment.class}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_fragment_tabs); initView(); } private void initView() { plan = (RadioButton)findViewById(R.id.plan); action = (RadioButton)findViewById(R.id.action); bbs = (RadioButton)findViewById(R.id.bbs); me = (RadioButton)findViewById(R.id.me); mTabHost = (FragmentTabHost)this.findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); mTabHost.getTabWidget().setVisibility(View.GONE); for(int i=0;i<tabs.length;i++){ mTabHost.addTab(mTabHost.newTabSpec(tabs[i]).setIndicator(tabs[i]),cls[i], null); } radioGroup = (RadioGroup) findViewById(R.id.main_radiogroup); radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch(checkedId){ case R.id.plan: changeSeletedButton(0); mTabHost.setCurrentTabByTag(tabs[0]); break; case R.id.action: changeSeletedButton(1); mTabHost.setCurrentTabByTag(tabs[1]); break; case R.id.bbs: changeSeletedButton(2); mTabHost.setCurrentTabByTag(tabs[2]); break; case R.id.me: changeSeletedButton(3); mTabHost.setCurrentTabByTag(tabs[3]); break; } } }); ((RadioButton)radioGroup.getChildAt(0)).toggle(); } private void changeSeletedButton(int type) { Drawable drawable = null; switch (type) { case 0: drawable = getResources().getDrawable(R.drawable.icon_plan_selected); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); plan.setCompoundDrawables(null, drawable, null, null); plan.setTextColor(Color.parseColor("#FFDA44")); drawable = getResources().getDrawable(R.drawable.icon_action); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); action.setCompoundDrawables(null, drawable, null, null); action.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_bbs); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); bbs.setCompoundDrawables(null, drawable, null, null); bbs.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_me); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); me.setCompoundDrawables(null, drawable, null, null); me.setTextColor(Color.parseColor("#595959")); break; case 1: drawable = getResources().getDrawable(R.drawable.icon_action_selected); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); action.setCompoundDrawables(null, drawable, null, null); action.setTextColor(Color.parseColor("#FFDA44")); drawable = getResources().getDrawable(R.drawable.icon_plan); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); plan.setCompoundDrawables(null, drawable, null, null); plan.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_bbs); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); bbs.setCompoundDrawables(null, drawable, null, null); bbs.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_me); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); me.setCompoundDrawables(null, drawable, null, null); me.setTextColor(Color.parseColor("#595959")); break; case 2: drawable = getResources().getDrawable(R.drawable.icon_bbs_selected); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); bbs.setCompoundDrawables(null, drawable, null, null); bbs.setTextColor(Color.parseColor("#FFDA44")); drawable = getResources().getDrawable(R.drawable.icon_plan); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); plan.setCompoundDrawables(null, drawable, null, null); plan.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_action); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); action.setCompoundDrawables(null, drawable, null, null); action.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_me); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); me.setCompoundDrawables(null, drawable, null, null); me.setTextColor(Color.parseColor("#595959")); break; case 3: drawable = getResources().getDrawable(R.drawable.icon_me_selected); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); me.setCompoundDrawables(null, drawable, null, null); me.setTextColor(Color.parseColor("#FFDA44")); drawable = getResources().getDrawable(R.drawable.icon_plan); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); plan.setCompoundDrawables(null, drawable, null, null); plan.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_action); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); action.setCompoundDrawables(null, drawable, null, null); action.setTextColor(Color.parseColor("#595959")); drawable = getResources().getDrawable(R.drawable.icon_bbs); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); bbs.setCompoundDrawables(null, drawable, null, null); bbs.setTextColor(Color.parseColor("#595959")); break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); } else { ExitApp(); } } return false; } // 返回键双击退出APP public void ExitApp() { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); } } }
TwoPillar/jiba
src/com/twopillar/jiba/activity/MainActivity.java
Java
apache-2.0
8,696
# Copyright 2017 CareerBuilder, LLC # 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. Rails.application.routes.draw do mount RoutesRevealer::Engine => "/" end
careerbuilder/routes-revealer
test/dummy/config/routes.rb
Ruby
apache-2.0
653
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// KoubeiCateringPosPaymodeQueryModel Data Structure. /// </summary> [Serializable] public class KoubeiCateringPosPaymodeQueryModel : AopObject { /// <summary> /// 门店id /// </summary> [XmlElement("shop_id")] public string ShopId { get; set; } } }
329277920/Snail
Snail.Pay.Ali.Sdk/Domain/KoubeiCateringPosPaymodeQueryModel.cs
C#
apache-2.0
408
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. 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 {ColorOption, ColumnStats, DataPoint, DataProto, DataSet, PointAccessors3D, PointMetadata, Projection, SpriteAndMetadataInfo, State, stateGetAccessorDimensions} from './data'; import {DataProvider, EmbeddingInfo, ServingMode} from './data-provider'; import {DemoDataProvider} from './data-provider-demo'; import {ProtoDataProvider} from './data-provider-proto'; import {ServerDataProvider} from './data-provider-server'; import {HoverContext, HoverListener} from './hoverContext'; import * as knn from './knn'; import * as logging from './logging'; import {ProjectorScatterPlotAdapter} from './projectorScatterPlotAdapter'; import {Mode, ScatterPlot} from './scatterPlot'; import {ScatterPlotVisualizer3DLabels} from './scatterPlotVisualizer3DLabels'; import {ScatterPlotVisualizerCanvasLabels} from './scatterPlotVisualizerCanvasLabels'; import {ScatterPlotVisualizerSprites} from './scatterPlotVisualizerSprites'; import {ScatterPlotVisualizerTraces} from './scatterPlotVisualizerTraces'; import {SelectionChangedListener, SelectionContext} from './selectionContext'; import {BookmarkPanel} from './vz-projector-bookmark-panel'; import {DataPanel} from './vz-projector-data-panel'; import {InspectorPanel} from './vz-projector-inspector-panel'; import {MetadataCard} from './vz-projector-metadata-card'; import {ProjectionsPanel} from './vz-projector-projections-panel'; // tslint:disable-next-line:no-unused-variable import {PolymerElement, PolymerHTMLElement} from './vz-projector-util'; /** * The minimum number of dimensions the data should have to automatically * decide to normalize the data. */ const THRESHOLD_DIM_NORMALIZE = 50; const POINT_COLOR_MISSING = 'black'; export let ProjectorPolymer = PolymerElement({ is: 'vz-projector', properties: { routePrefix: String, dataProto: {type: String, observer: '_dataProtoChanged'}, servingMode: String, projectorConfigJsonPath: String } }); const INDEX_METADATA_FIELD = '__index__'; export class Projector extends ProjectorPolymer implements SelectionContext, HoverContext { // The working subset of the data source's original data set. dataSet: DataSet; servingMode: ServingMode; // The path to the projector config JSON file for demo mode. projectorConfigJsonPath: string; private selectionChangedListeners: SelectionChangedListener[]; private hoverListeners: HoverListener[]; private originalDataSet: DataSet; private dom: d3.Selection<any>; private projectorScatterPlotAdapter: ProjectorScatterPlotAdapter; private scatterPlot: ScatterPlot; private dim: number; private selectedPointIndices: number[]; private neighborsOfFirstPoint: knn.NearestEntry[]; private hoverPointIndex: number; private dataProvider: DataProvider; private inspectorPanel: InspectorPanel; private selectedColorOption: ColorOption; private selectedLabelOption: string; private routePrefix: string; private normalizeData: boolean; private selectedProjection: Projection; private selectedProjectionPointAccessors: PointAccessors3D; /** Polymer component panels */ private dataPanel: DataPanel; private bookmarkPanel: BookmarkPanel; private projectionsPanel: ProjectionsPanel; private metadataCard: MetadataCard; private statusBar: d3.Selection<HTMLElement>; ready() { this.selectionChangedListeners = []; this.hoverListeners = []; this.selectedPointIndices = []; this.neighborsOfFirstPoint = []; this.dom = d3.select(this); logging.setDomContainer(this); this.dataPanel = this.$['data-panel'] as DataPanel; this.inspectorPanel = this.$['inspector-panel'] as InspectorPanel; this.inspectorPanel.initialize(this); this.projectionsPanel = this.$['projections-panel'] as ProjectionsPanel; this.projectionsPanel.initialize(this); this.metadataCard = this.$['metadata-card'] as MetadataCard; this.statusBar = this.dom.select('#status-bar'); this.bookmarkPanel = this.$['bookmark-panel'] as BookmarkPanel; this.scopeSubtree(this.$$('#wrapper-notify-msg'), true); this.setupUIControls(); this.initializeDataProvider(); } setSelectedLabelOption(labelOption: string) { this.selectedLabelOption = labelOption; let labelAccessor = (i: number): string => { return this.dataSet.points[i] .metadata[this.selectedLabelOption] as string; }; this.metadataCard.setLabelOption(this.selectedLabelOption); this.scatterPlot.setLabelAccessor(labelAccessor); this.scatterPlot.render(); } setSelectedColorOption(colorOption: ColorOption) { this.selectedColorOption = colorOption; this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setNormalizeData(normalizeData: boolean) { this.normalizeData = normalizeData; this.setCurrentDataSet(this.originalDataSet.getSubset()); } updateDataSet( ds: DataSet, spriteAndMetadata?: SpriteAndMetadataInfo, metadataFile?: string) { this.originalDataSet = ds; if (this.scatterPlot == null || this.originalDataSet == null) { // We are not ready yet. return; } this.normalizeData = this.originalDataSet.dim[1] >= THRESHOLD_DIM_NORMALIZE; spriteAndMetadata = spriteAndMetadata || {}; if (spriteAndMetadata.pointsInfo == null) { let [pointsInfo, stats] = this.makeDefaultPointsInfoAndStats(ds.points); spriteAndMetadata.pointsInfo = pointsInfo; spriteAndMetadata.stats = stats; } ds.mergeMetadata(spriteAndMetadata); this.dataPanel.setNormalizeData(this.normalizeData); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.inspectorPanel.datasetChanged(); this.inspectorPanel.metadataChanged(spriteAndMetadata); this.projectionsPanel.metadataChanged(spriteAndMetadata); this.dataPanel.metadataChanged(spriteAndMetadata, metadataFile); // Set the container to a fixed height, otherwise in Colab the // height can grow indefinitely. let container = this.dom.select('#container'); container.style('height', container.property('clientHeight') + 'px'); } setSelectedTensor(run: string, tensorInfo: EmbeddingInfo) { this.bookmarkPanel.setSelectedTensor(run, tensorInfo); } /** * Registers a listener to be called any time the selected point set changes. */ registerSelectionChangedListener(listener: SelectionChangedListener) { this.selectionChangedListeners.push(listener); } filterDataset() { let indices = this.selectedPointIndices.concat( this.neighborsOfFirstPoint.map(n => n.index)); let selectionSize = this.selectedPointIndices.length; this.setCurrentDataSet(this.dataSet.getSubset(indices)); this.adjustSelectionAndHover(d3.range(selectionSize)); } resetFilterDataset() { let originalPointIndices = this.selectedPointIndices.map(localIndex => { return this.dataSet.points[localIndex].index; }); this.setCurrentDataSet(this.originalDataSet.getSubset()); this.updateScatterPlotPositions(); this.adjustSelectionAndHover(originalPointIndices); } /** * Used by clients to indicate that a selection has occurred. */ notifySelectionChanged(newSelectedPointIndices: number[]) { this.selectedPointIndices = newSelectedPointIndices; let neighbors: knn.NearestEntry[] = []; if (newSelectedPointIndices.length === 1) { neighbors = this.dataSet.findNeighbors( newSelectedPointIndices[0], this.inspectorPanel.distFunc, this.inspectorPanel.numNN); this.metadataCard.updateMetadata( this.dataSet.points[newSelectedPointIndices[0]].metadata); } else { this.metadataCard.updateMetadata(null); } this.selectionChangedListeners.forEach( l => l(this.selectedPointIndices, neighbors)); } /** * Registers a listener to be called any time the mouse hovers over a point. */ registerHoverListener(listener: HoverListener) { this.hoverListeners.push(listener); } /** * Used by clients to indicate that a hover is occurring. */ notifyHoverOverPoint(pointIndex: number) { this.hoverListeners.forEach(l => l(pointIndex)); } _dataProtoChanged(dataProtoString: string) { let dataProto = dataProtoString ? JSON.parse(dataProtoString) as DataProto : null; this.initializeDataProvider(dataProto); } private makeDefaultPointsInfoAndStats(points: DataPoint[]): [PointMetadata[], ColumnStats[]] { let pointsInfo: PointMetadata[] = []; points.forEach(p => { let pointInfo: PointMetadata = {}; pointInfo[INDEX_METADATA_FIELD] = p.index; pointsInfo.push(pointInfo); }); let stats: ColumnStats[] = [{ name: INDEX_METADATA_FIELD, isNumeric: false, tooManyUniqueValues: true, min: 0, max: pointsInfo.length - 1 }]; return [pointsInfo, stats]; } private initializeDataProvider(dataProto?: DataProto) { if (this.servingMode === 'demo') { this.dataProvider = new DemoDataProvider(this.projectorConfigJsonPath); } else if (this.servingMode === 'server') { if (!this.routePrefix) { throw 'route-prefix is a required parameter'; } this.dataProvider = new ServerDataProvider(this.routePrefix); } else if (this.servingMode === 'proto' && dataProto != null) { this.dataProvider = new ProtoDataProvider(dataProto); } this.dataPanel.initialize(this, this.dataProvider); this.bookmarkPanel.initialize(this, this.dataProvider); } private getLegendPointColorer(colorOption: ColorOption): (index: number) => string { if ((colorOption == null) || (colorOption.map == null)) { return null; } const colorer = (i: number) => { let value = this.dataSet.points[i].metadata[this.selectedColorOption.name]; if (value == null) { return POINT_COLOR_MISSING; } return colorOption.map(value); }; return colorer; } private get3DLabelModeButton(): any { return this.querySelector('#labels3DMode'); } private get3DLabelMode(): boolean { const label3DModeButton = this.get3DLabelModeButton(); return (label3DModeButton as any).active; } private getSpriteImageMode(): boolean { return this.dataSet && this.dataSet.spriteAndMetadataInfo && this.dataSet.spriteAndMetadataInfo.spriteImage != null; } adjustSelectionAndHover(selectedPointIndices: number[], hoverIndex?: number) { this.notifySelectionChanged(selectedPointIndices); this.notifyHoverOverPoint(hoverIndex); this.scatterPlot.setMode(Mode.HOVER); } private unsetCurrentDataSet() { this.dataSet.stopTSNE(); } private setCurrentDataSet(ds: DataSet) { this.adjustSelectionAndHover([]); if (this.dataSet != null) { this.unsetCurrentDataSet(); } this.dataSet = ds; if (this.normalizeData) { this.dataSet.normalize(); } this.dim = this.dataSet.dim[1]; this.dom.select('span.numDataPoints').text(this.dataSet.dim[0]); this.dom.select('span.dim').text(this.dataSet.dim[1]); this.selectedProjectionPointAccessors = null; this.projectionsPanel.dataSetUpdated( this.dataSet, this.originalDataSet, this.dim); this.scatterPlot.setCameraParametersForNextCameraCreation(null, true); } private setupUIControls() { // View controls this.querySelector('#reset-zoom').addEventListener('click', () => { this.scatterPlot.resetZoom(); this.scatterPlot.startOrbitAnimation(); }); let selectModeButton = this.querySelector('#selectMode'); selectModeButton.addEventListener('click', (event) => { this.scatterPlot.setMode( (selectModeButton as any).active ? Mode.SELECT : Mode.HOVER); }); let nightModeButton = this.querySelector('#nightDayMode'); nightModeButton.addEventListener('click', () => { this.scatterPlot.setDayNightMode((nightModeButton as any).active); }); const labels3DModeButton = this.get3DLabelModeButton(); labels3DModeButton.addEventListener('click', () => { this.createVisualizers(this.get3DLabelMode()); this.updateScatterPlotAttributes(); this.scatterPlot.render(); }); window.addEventListener('resize', () => { let container = this.dom.select('#container'); let parentHeight = (container.node().parentNode as HTMLElement).clientHeight; container.style('height', parentHeight + 'px'); this.scatterPlot.resize(); }); this.projectorScatterPlotAdapter = new ProjectorScatterPlotAdapter(); this.scatterPlot = new ScatterPlot( this.getScatterContainer(), i => '' + this.dataSet.points[i].metadata[this.selectedLabelOption], this, this); this.createVisualizers(false); this.scatterPlot.onCameraMove( (cameraPosition: THREE.Vector3, cameraTarget: THREE.Vector3) => this.bookmarkPanel.clearStateSelection()); this.registerHoverListener( (hoverIndex: number) => this.onHover(hoverIndex)); this.registerSelectionChangedListener( (selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) => this.onSelectionChanged( selectedPointIndices, neighborsOfFirstPoint)); this.scatterPlot.resize(); this.scatterPlot.render(); } private onHover(hoverIndex: number) { this.hoverPointIndex = hoverIndex; let hoverText = null; if (hoverIndex != null) { const point = this.dataSet.points[hoverIndex]; if (point.metadata[this.selectedLabelOption]) { hoverText = point.metadata[this.selectedLabelOption].toString(); } } this.updateScatterPlotAttributes(); this.scatterPlot.render(); if (this.selectedPointIndices.length === 0) { this.statusBar.style('display', hoverText ? null : 'none'); this.statusBar.text(hoverText); } } private updateScatterPlotPositions() { if (this.dataSet == null) { return; } if (this.selectedProjectionPointAccessors == null) { return; } const newPositions = this.projectorScatterPlotAdapter.generatePointPositionArray( this.dataSet, this.selectedProjectionPointAccessors); this.scatterPlot.setPointPositions(this.dataSet, newPositions); } private updateScatterPlotAttributes() { const dataSet = this.dataSet; const selectedSet = this.selectedPointIndices; const hoverIndex = this.hoverPointIndex; const neighbors = this.neighborsOfFirstPoint; const pointColorer = this.getLegendPointColorer(this.selectedColorOption); const adapter = this.projectorScatterPlotAdapter; const pointColors = adapter.generatePointColorArray( dataSet, pointColorer, selectedSet, neighbors, hoverIndex, this.get3DLabelMode(), this.getSpriteImageMode()); const pointScaleFactors = adapter.generatePointScaleFactorArray( dataSet, selectedSet, neighbors, hoverIndex); const labels = adapter.generateVisibleLabelRenderParams( dataSet, selectedSet, neighbors, hoverIndex); const traceColors = adapter.generateLineSegmentColorMap(dataSet, pointColorer); const traceOpacities = adapter.generateLineSegmentOpacityArray(dataSet, selectedSet); const traceWidths = adapter.generateLineSegmentWidthArray(dataSet, selectedSet); this.scatterPlot.setPointColors(pointColors); this.scatterPlot.setPointScaleFactors(pointScaleFactors); this.scatterPlot.setLabels(labels); this.scatterPlot.setTraceColors(traceColors); this.scatterPlot.setTraceOpacities(traceOpacities); this.scatterPlot.setTraceWidths(traceWidths); } private getScatterContainer(): d3.Selection<any> { return this.dom.select('#scatter'); } private createVisualizers(inLabels3DMode: boolean) { const scatterPlot = this.scatterPlot; scatterPlot.removeAllVisualizers(); if (inLabels3DMode) { scatterPlot.addVisualizer(new ScatterPlotVisualizer3DLabels()); } else { scatterPlot.addVisualizer(new ScatterPlotVisualizerSprites()); scatterPlot.addVisualizer( new ScatterPlotVisualizerCanvasLabels(this.getScatterContainer())); } scatterPlot.addVisualizer(new ScatterPlotVisualizerTraces()); } private onSelectionChanged( selectedPointIndices: number[], neighborsOfFirstPoint: knn.NearestEntry[]) { this.selectedPointIndices = selectedPointIndices; this.neighborsOfFirstPoint = neighborsOfFirstPoint; let totalNumPoints = this.selectedPointIndices.length + neighborsOfFirstPoint.length; this.statusBar.text(`Selected ${totalNumPoints} points`) .style('display', totalNumPoints > 0 ? null : 'none'); this.inspectorPanel.updateInspectorPane( selectedPointIndices, neighborsOfFirstPoint); this.updateScatterPlotAttributes(); this.scatterPlot.render(); } setProjection( projection: Projection, dimensionality: number, pointAccessors: PointAccessors3D) { this.selectedProjection = projection; this.selectedProjectionPointAccessors = pointAccessors; this.scatterPlot.setDimensions(dimensionality); if (this.dataSet.projectionCanBeRendered(projection)) { this.updateScatterPlotAttributes(); this.notifyProjectionsUpdated(); } this.scatterPlot.setCameraParametersForNextCameraCreation(null, false); } notifyProjectionsUpdated() { this.updateScatterPlotPositions(); this.scatterPlot.render(); } /** * Gets the current view of the embedding and saves it as a State object. */ getCurrentState(): State { const state = new State(); // Save the individual datapoint projections. state.projections = []; for (let i = 0; i < this.dataSet.points.length; i++) { const point = this.dataSet.points[i]; const projections: {[key: string]: number} = {}; const keys = Object.keys(point.projections); for (let j = 0; j < keys.length; ++j) { projections[keys[j]] = point.projections[keys[j]]; } state.projections.push(projections); } state.selectedProjection = this.selectedProjection; state.dataSetDimensions = this.dataSet.dim; state.tSNEIteration = this.dataSet.tSNEIteration; state.selectedPoints = this.selectedPointIndices; state.cameraDef = this.scatterPlot.getCameraDef(); state.selectedColorOptionName = this.dataPanel.selectedColorOptionName; state.selectedLabelOption = this.selectedLabelOption; this.projectionsPanel.populateBookmarkFromUI(state); return state; } /** Loads a State object into the world. */ loadState(state: State) { for (let i = 0; i < state.projections.length; i++) { const point = this.dataSet.points[i]; const projection = state.projections[i]; const keys = Object.keys(projection); for (let j = 0; j < keys.length; ++j) { point.projections[keys[j]] = projection[keys[j]]; } } this.dataSet.hasTSNERun = (state.selectedProjection === 'tsne'); this.dataSet.tSNEIteration = state.tSNEIteration; this.projectionsPanel.restoreUIFromBookmark(state); this.dataPanel.selectedColorOptionName = state.selectedColorOptionName; this.selectedLabelOption = state.selectedLabelOption; this.scatterPlot.setCameraParametersForNextCameraCreation( state.cameraDef, false); { const dimensions = stateGetAccessorDimensions(state); const accessors = this.dataSet.getPointAccessors(state.selectedProjection, dimensions); this.setProjection( state.selectedProjection, dimensions.length, accessors); } this.notifySelectionChanged(state.selectedPoints); } } document.registerElement(Projector.prototype.is, Projector);
nanditav/15712-TensorFlow
tensorflow/tensorboard/components/vz_projector/vz-projector.ts
TypeScript
apache-2.0
20,485
/******************************************************************************* * Copyright 2013 SAP AG * * 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.sap.core.odata.core.uri.expression; import com.sap.core.odata.api.edm.EdmType; import com.sap.core.odata.api.exception.ODataApplicationException; import com.sap.core.odata.api.uri.expression.CommonExpression; import com.sap.core.odata.api.uri.expression.ExceptionVisitExpression; import com.sap.core.odata.api.uri.expression.ExpressionKind; import com.sap.core.odata.api.uri.expression.ExpressionVisitor; import com.sap.core.odata.api.uri.expression.OrderExpression; import com.sap.core.odata.api.uri.expression.SortOrder; /** * @author SAP AG */ public class OrderExpressionImpl implements OrderExpression { SortOrder orderType = SortOrder.asc; CommonExpression expression; OrderExpressionImpl(final CommonExpression expression) { this.expression = expression; } @Override public SortOrder getSortOrder() { return orderType; } @Override public CommonExpression getExpression() { return expression; } void setSortOrder(final SortOrder orderType) { this.orderType = orderType; } @Override public ExpressionKind getKind() { return ExpressionKind.ORDER; } @Override public EdmType getEdmType() { return null; } @Override public CommonExpression setEdmType(final EdmType edmType) { return this; } @Override public String getUriLiteral() { return ""; } @Override public Object accept(final ExpressionVisitor visitor) throws ExceptionVisitExpression, ODataApplicationException { Object obj = expression.accept(visitor); Object ret = visitor.visitOrder(this, obj, orderType); return ret; } }
SAP/cloud-odata-java
odata-core/src/main/java/com/sap/core/odata/core/uri/expression/OrderExpressionImpl.java
Java
apache-2.0
2,356
package httpseverywhere import ( "bytes" "encoding/gob" "encoding/xml" "io/ioutil" "path/filepath" "regexp" "github.com/getlantern/golog" ) // Preprocessor is a struct for preprocessing rules into a GOB file. var Preprocessor = &preprocessor{ log: golog.LoggerFor("httpseverywhere-preprocessor"), } type preprocessor struct { log golog.Logger } // Preprocess adds all of the rules in the specified directory. func (p *preprocessor) Preprocess(dir string) { p.preprocess(dir, gobrules) } // preprocess adds all of the rules in the specified directory and writes to // the specified file. func (p *preprocessor) preprocess(dir string, outFile string) { rules := make([]*Ruleset, 0) files, err := ioutil.ReadDir(dir) if err != nil { p.log.Fatal(err) } var num int var errors int for _, file := range files { b, errr := ioutil.ReadFile(filepath.Join(dir, file.Name())) if errr != nil { //log.Errorf("Error reading file: %v", err) } else { rs, processed := p.VetRuleSet(b) if !processed { errors++ } else { rules = append(rules, rs) } } num++ } p.log.Debugf("Total rule set files: %v", num) p.log.Debugf("Loaded rules with %v rulesets and %v errors", len(rules), errors) var buf bytes.Buffer enc := gob.NewEncoder(&buf) // Encode (send) the value. err = enc.Encode(rules) if err != nil { p.log.Fatalf("encode error: %v", err) } ioutil.WriteFile(outFile, buf.Bytes(), 0644) } // VetRuleSet just checks to make sure all the regular expressions compile for // a given rule set. If any fail, we just ignore it. func (p *preprocessor) VetRuleSet(rules []byte) (*Ruleset, bool) { var ruleset Ruleset xml.Unmarshal(rules, &ruleset) // If the rule is turned off, ignore it. if len(ruleset.Off) > 0 { return nil, false } // We don't run on any platforms (aka Tor) that support mixed content, so // ignore any rule that is mixedcontent-only. if ruleset.Platform == "mixedcontent" { return nil, false } for _, rule := range ruleset.Rule { _, err := regexp.Compile(rule.From) if err != nil { p.log.Debugf("Could not compile From rule %v - got error %v", rule.From, err) return nil, false } rule.To = p.normalizeTo(rule.To) } for _, e := range ruleset.Exclusion { _, err := regexp.Compile(e.Pattern) if err != nil { p.log.Debugf("Could not compile Exclusion pattern %v - got error %v", e.Pattern, err) return nil, false } } return &ruleset, true } func (p *preprocessor) normalizeTo(to string) string { // Go handles references to matching groups in the replacement text // differently from PCRE. PCRE considers $1xxx to be the first match // followed by xxx, whereas in Go that's considered to be the named group // "$1xxx". // See: https://golang.org/pkg/regexp/#Regexp.Expand re := regexp.MustCompile("\\$(\\d+)") return re.ReplaceAllString(to, "${$1}") }
getlantern/httpseverywhere
preprocessor.go
GO
apache-2.0
2,872
/* * 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 specic language governing permissions and * limitations under the License. */ package app.metatron.discovery.common.geospatial.geojson; public class PointGeometry implements GeoJsonGeometry { private double[] coordinates; private double[] bbox; public PointGeometry() { } public PointGeometry(double[] coordinates) { this.coordinates = coordinates; } public double[] getCoordinates() { return coordinates; } public double[] getBbox() { return bbox; } }
metatron-app/metatron-discovery
discovery-server/src/main/java/app/metatron/discovery/common/geospatial/geojson/PointGeometry.java
Java
apache-2.0
975
/** * Copyright 2011-2016 GatlingCorp (http://gatling.io) * * 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 io.gatling.liferay.model.impl; import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.ProxyUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import com.liferay.portal.model.impl.BaseModelImpl; import com.liferay.portal.service.ServiceContext; import com.liferay.portlet.expando.model.ExpandoBridge; import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil; import io.gatling.liferay.model.Process; import io.gatling.liferay.model.ProcessModel; import java.io.Serializable; import java.sql.Types; import java.util.HashMap; import java.util.Map; /** * The base model implementation for the Process service. Represents a row in the &quot;StressTool_Process&quot; database table, with each column mapped to a property of this class. * * <p> * This implementation and its corresponding interface {@link io.gatling.liferay.model.ProcessModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link ProcessImpl}. * </p> * * @author Brian Wing Shun Chan * @see ProcessImpl * @see io.gatling.liferay.model.Process * @see io.gatling.liferay.model.ProcessModel * @generated */ public class ProcessModelImpl extends BaseModelImpl<Process> implements ProcessModel { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this class directly. All methods that expect a process model instance should use the {@link io.gatling.liferay.model.Process} interface instead. */ public static final String TABLE_NAME = "StressTool_Process"; public static final Object[][] TABLE_COLUMNS = { { "process_id", Types.BIGINT }, { "name", Types.VARCHAR }, { "type_", Types.VARCHAR }, { "feederId", Types.BIGINT } }; public static final String TABLE_SQL_CREATE = "create table StressTool_Process (process_id LONG not null primary key,name VARCHAR(75) null,type_ VARCHAR(75) null,feederId LONG)"; public static final String TABLE_SQL_DROP = "drop table StressTool_Process"; public static final String ORDER_BY_JPQL = " ORDER BY process.process_id ASC"; public static final String ORDER_BY_SQL = " ORDER BY StressTool_Process.process_id ASC"; public static final String DATA_SOURCE = "liferayDataSource"; public static final String SESSION_FACTORY = "liferaySessionFactory"; public static final String TX_MANAGER = "liferayTransactionManager"; public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get( "value.object.entity.cache.enabled.io.gatling.liferay.model.Process"), true); public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get( "value.object.finder.cache.enabled.io.gatling.liferay.model.Process"), true); public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get( "value.object.column.bitmask.enabled.io.gatling.liferay.model.Process"), true); public static long NAME_COLUMN_BITMASK = 1L; public static long PROCESS_ID_COLUMN_BITMASK = 2L; public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get( "lock.expiration.time.io.gatling.liferay.model.Process")); private static ClassLoader _classLoader = Process.class.getClassLoader(); private static Class<?>[] _escapedModelInterfaces = new Class[] { Process.class }; private long _process_id; private String _name; private String _originalName; private String _type; private Long _feederId; private long _columnBitmask; private Process _escapedModel; public ProcessModelImpl() { } @Override public long getPrimaryKey() { return _process_id; } @Override public void setPrimaryKey(long primaryKey) { setProcess_id(primaryKey); } @Override public Serializable getPrimaryKeyObj() { return _process_id; } @Override public void setPrimaryKeyObj(Serializable primaryKeyObj) { setPrimaryKey(((Long) primaryKeyObj).longValue()); } @Override public Class<?> getModelClass() { return Process.class; } @Override public String getModelClassName() { return Process.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("process_id", getProcess_id()); attributes.put("name", getName()); attributes.put("type", getType()); attributes.put("feederId", getFeederId()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long process_id = (Long) attributes.get("process_id"); if (process_id != null) { setProcess_id(process_id); } String name = (String) attributes.get("name"); if (name != null) { setName(name); } String type = (String) attributes.get("type"); if (type != null) { setType(type); } Long feederId = (Long) attributes.get("feederId"); if (feederId != null) { setFeederId(feederId); } } @Override public long getProcess_id() { return _process_id; } @Override public void setProcess_id(long process_id) { _process_id = process_id; } @Override public String getName() { if (_name == null) { return StringPool.BLANK; } else { return _name; } } @Override public void setName(String name) { _columnBitmask |= NAME_COLUMN_BITMASK; if (_originalName == null) { _originalName = _name; } _name = name; } public String getOriginalName() { return GetterUtil.getString(_originalName); } @Override public String getType() { if (_type == null) { return StringPool.BLANK; } else { return _type; } } @Override public void setType(String type) { _type = type; } @Override public Long getFeederId() { return _feederId; } @Override public void setFeederId(Long feederId) { _feederId = feederId; } public long getColumnBitmask() { return _columnBitmask; } @Override public ExpandoBridge getExpandoBridge() { return ExpandoBridgeFactoryUtil.getExpandoBridge(0, Process.class.getName(), getPrimaryKey()); } @Override public void setExpandoBridgeAttributes(ServiceContext serviceContext) { ExpandoBridge expandoBridge = getExpandoBridge(); expandoBridge.setAttributes(serviceContext); } @Override public Process toEscapedModel() { if (_escapedModel == null) { _escapedModel = (Process) ProxyUtil.newProxyInstance(_classLoader, _escapedModelInterfaces, new AutoEscapeBeanHandler(this)); } return _escapedModel; } @Override public Object clone() { ProcessImpl processImpl = new ProcessImpl(); processImpl.setProcess_id(getProcess_id()); processImpl.setName(getName()); processImpl.setType(getType()); processImpl.setFeederId(getFeederId()); processImpl.resetOriginalValues(); return processImpl; } @Override public int compareTo(Process process) { long primaryKey = process.getPrimaryKey(); if (getPrimaryKey() < primaryKey) { return -1; } else if (getPrimaryKey() > primaryKey) { return 1; } else { return 0; } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Process)) { return false; } Process process = (Process) obj; long primaryKey = process.getPrimaryKey(); if (getPrimaryKey() == primaryKey) { return true; } else { return false; } } @Override public int hashCode() { return (int) getPrimaryKey(); } @Override public void resetOriginalValues() { ProcessModelImpl processModelImpl = this; processModelImpl._originalName = processModelImpl._name; processModelImpl._columnBitmask = 0; } @Override public CacheModel<Process> toCacheModel() { ProcessCacheModel processCacheModel = new ProcessCacheModel(); processCacheModel.process_id = getProcess_id(); processCacheModel.name = getName(); String name = processCacheModel.name; if ((name != null) && (name.length() == 0)) { processCacheModel.name = null; } processCacheModel.type = getType(); String type = processCacheModel.type; if ((type != null) && (type.length() == 0)) { processCacheModel.type = null; } processCacheModel.feederId = getFeederId(); return processCacheModel; } @Override public String toString() { StringBundler sb = new StringBundler(9); sb.append("{process_id="); sb.append(getProcess_id()); sb.append(", name="); sb.append(getName()); sb.append(", type="); sb.append(getType()); sb.append(", feederId="); sb.append(getFeederId()); sb.append("}"); return sb.toString(); } @Override public String toXmlString() { StringBundler sb = new StringBundler(16); sb.append("<model><model-name>"); sb.append("io.gatling.liferay.model.Process"); sb.append("</model-name>"); sb.append( "<column><column-name>process_id</column-name><column-value><![CDATA["); sb.append(getProcess_id()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>name</column-name><column-value><![CDATA["); sb.append(getName()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>type</column-name><column-value><![CDATA["); sb.append(getType()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>feederId</column-name><column-value><![CDATA["); sb.append(getFeederId()); sb.append("]]></column-value></column>"); sb.append("</model>"); return sb.toString(); } }
e-biz/gatling-liferay
src/main/java/io/gatling/liferay/model/impl/ProcessModelImpl.java
Java
apache-2.0
11,680
/* ------ IOS ------ */ if(OS_IOS){ // NappSlideMenu var NappSlideMenu = require('dk.napp.slidemenu'); var drawerIphone = NappSlideMenu.createSlideMenuWindow({ centerWindow: $.navWindow, leftWindow: Alloy.createController('menu').getView(), leftLedge: 50 }); // Configure navigation and init app Alloy.Globals.nav.setIphoneDrawer(drawerIphone); Alloy.Globals.nav.setParentWindow($.firstWindow); Alloy.Globals.nav.openCenter('Feed', 'feed', false); Alloy.Globals.nav.init(); function openMenu(){ drawerIphone.toggleLeftView(); } } /* ------ ANDROID ------ */ else if(OS_ANDROID){ // Ti.DrawerLayout var TiDrawerLayout = require('com.tripvi.drawerlayout'); var drawer = TiDrawerLayout.createDrawer({ leftView: Alloy.createController('menu').getView(), leftDrawerWidth: "280dp", width: Ti.UI.FILL, height: Ti.UI.FILL }); // Configure navigation and init app Alloy.Globals.nav.setAppName('My App Name'); Alloy.Globals.nav.setAndroidDrawer(drawer); Alloy.Globals.nav.setParentWindow($.index); Alloy.Globals.nav.openCenter('Feed', 'feed', false); Alloy.Globals.nav.init(); }
netoramalho/ti.slidemenu
app/controllers/index.js
JavaScript
apache-2.0
1,119
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Mvc.RazorPages; namespace RazorPagesWebSite { public class PageWithModel : PageModel { } }
aspnet/AspNetCore
src/Mvc/test/WebSites/RazorPagesWebSite/Pages/CustomBaseType/PageWithModel.cs
C#
apache-2.0
268
module.exports = function (process, manifest, actionCallback) { var program = require('commander'); program .version(manifest.version) .option('-v, --verbose', 'Enable verbose output') .command('*') .action(function (args) { actionCallback(process, args); }); program.parse(process.argv); };
blegros/TestBoxCLI
lib/cli.js
JavaScript
apache-2.0
357
# Copyright 2019 DeepMind Technologies Limited and Google LLC # # 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. """Training script.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags from absl import logging import tensorflow.compat.v1 as tf from cs_gan import file_utils from cs_gan import gan from cs_gan import image_metrics from cs_gan import utils flags.DEFINE_integer( 'num_training_iterations', 1200000, 'Number of training iterations.') flags.DEFINE_string( 'ode_mode', 'rk4', 'Integration method.') flags.DEFINE_integer( 'batch_size', 64, 'Training batch size.') flags.DEFINE_float( 'grad_reg_weight', 0.02, 'Step size for latent optimisation.') flags.DEFINE_string( 'opt_name', 'gd', 'Name of the optimiser (gd|adam).') flags.DEFINE_bool( 'schedule_lr', True, 'The method to project z.') flags.DEFINE_bool( 'reg_first_grad_only', True, 'Whether only to regularise the first grad.') flags.DEFINE_integer( 'num_latents', 128, 'The number of latents') flags.DEFINE_integer( 'summary_every_step', 1000, 'The interval at which to log debug ops.') flags.DEFINE_integer( 'image_metrics_every_step', 1000, 'The interval at which to log (expensive) image metrics.') flags.DEFINE_integer( 'export_every', 10, 'The interval at which to export samples.') # Use 50k to reproduce scores from the paper. Default to 10k here to avoid the # runtime error caused by too large graph with 50k samples on some machines. flags.DEFINE_integer( 'num_eval_samples', 10000, 'The number of samples used to evaluate FID/IS.') flags.DEFINE_string( 'dataset', 'cifar', 'The dataset used for learning (cifar|mnist).') flags.DEFINE_string( 'output_dir', '/tmp/ode_gan/gan', 'Location where to save output files.') flags.DEFINE_float('disc_lr', 4e-2, 'Discriminator Learning rate.') flags.DEFINE_float('gen_lr', 4e-2, 'Generator Learning rate.') flags.DEFINE_bool( 'run_real_data_metrics', False, 'Whether or not to run image metrics on real data.') flags.DEFINE_bool( 'run_sample_metrics', True, 'Whether or not to run image metrics on samples.') FLAGS = flags.FLAGS # Log info level (for Hooks). tf.logging.set_verbosity(tf.logging.INFO) def _copy_vars(v_list): """Copy variables in v_list.""" t_list = [] for v in v_list: t_list.append(tf.identity(v)) return t_list def _restore_vars(v_list, t_list): """Restore variables in v_list from t_list.""" ops = [] for v, t in zip(v_list, t_list): ops.append(v.assign(t)) return ops def _scale_vars(s, v_list): """Scale all variables in v_list by s.""" return [s * v for v in v_list] def _acc_grads(g_sum, g_w, g): """Accumulate gradients in g, weighted by g_w.""" return [g_sum_i + g_w * g_i for g_sum_i, g_i in zip(g_sum, g)] def _compute_reg_grads(gen_grads, disc_vars): """Compute gradients norm (this is an upper-bpund of the full-batch norm).""" gen_norm = tf.accumulate_n([tf.reduce_sum(u * u) for u in gen_grads]) disc_reg_grads = tf.gradients(gen_norm, disc_vars) return disc_reg_grads def run_model(prior, images, model, disc_reg_weight): """Run the model with new data and samples. Args: prior: the noise source as the generator input. images: images sampled from dataset. model: a GAN model defined in gan.py. disc_reg_weight: regularisation weight for discrmininator gradients. Returns: debug_ops: statistics from the model, see gan.py for more detials. disc_grads: discriminator gradients. gen_grads: generator gradients. """ generator_inputs = prior.sample(FLAGS.batch_size) model_output = model.connect(images, generator_inputs) optimization_components = model_output.optimization_components disc_grads = tf.gradients( optimization_components['disc'].loss, optimization_components['disc'].vars) gen_grads = tf.gradients( optimization_components['gen'].loss, optimization_components['gen'].vars) if disc_reg_weight > 0.0: reg_grads = _compute_reg_grads(gen_grads, optimization_components['disc'].vars) disc_grads = _acc_grads(disc_grads, disc_reg_weight, reg_grads) debug_ops = model_output.debug_ops return debug_ops, disc_grads, gen_grads def update_model(model, disc_grads, gen_grads, disc_opt, gen_opt, global_step, update_scale): """Update model with gradients.""" disc_vars, gen_vars = model.get_variables() with tf.control_dependencies(gen_grads + disc_grads): disc_update_op = disc_opt.apply_gradients( zip(_scale_vars(update_scale, disc_grads), disc_vars)) gen_update_op = gen_opt.apply_gradients( zip(_scale_vars(update_scale, gen_grads), gen_vars), global_step=global_step) update_op = tf.group([disc_update_op, gen_update_op]) return update_op def main(argv): del argv utils.make_output_dir(FLAGS.output_dir) data_processor = utils.DataProcessor() # Compute the batch-size multiplier if FLAGS.ode_mode == 'rk2': batch_mul = 2 elif FLAGS.ode_mode == 'rk4': batch_mul = 4 else: batch_mul = 1 images = utils.get_train_dataset(data_processor, FLAGS.dataset, int(FLAGS.batch_size * batch_mul)) image_splits = tf.split(images, batch_mul) logging.info('Generator learning rate: %d', FLAGS.gen_lr) logging.info('Discriminator learning rate: %d', FLAGS.disc_lr) global_step = tf.train.get_or_create_global_step() # Construct optimizers. if FLAGS.opt_name == 'adam': disc_opt = tf.train.AdamOptimizer(FLAGS.disc_lr, beta1=0.5, beta2=0.999) gen_opt = tf.train.AdamOptimizer(FLAGS.gen_lr, beta1=0.5, beta2=0.999) elif FLAGS.opt_name == 'gd': if FLAGS.schedule_lr: gd_disc_lr = tf.train.piecewise_constant( global_step, values=[FLAGS.disc_lr / 4., FLAGS.disc_lr, FLAGS.disc_lr / 2.], boundaries=[500, 400000]) gd_gen_lr = tf.train.piecewise_constant( global_step, values=[FLAGS.gen_lr / 4., FLAGS.gen_lr, FLAGS.gen_lr / 2.], boundaries=[500, 400000]) else: gd_disc_lr = FLAGS.disc_lr gd_gen_lr = FLAGS.gen_lr disc_opt = tf.train.GradientDescentOptimizer(gd_disc_lr) gen_opt = tf.train.GradientDescentOptimizer(gd_gen_lr) else: raise ValueError('Unknown ODE mode!') # Create the networks and models. generator = utils.get_generator(FLAGS.dataset) metric_net = utils.get_metric_net(FLAGS.dataset, use_sn=False) model = gan.GAN(metric_net, generator) prior = utils.make_prior(FLAGS.num_latents) # Setup ODE parameters. if FLAGS.ode_mode == 'rk2': ode_grad_weights = [0.5, 0.5] step_scale = [1.0] elif FLAGS.ode_mode == 'rk4': ode_grad_weights = [1. / 6., 1. / 3., 1. / 3., 1. / 6.] step_scale = [0.5, 0.5, 1.] elif FLAGS.ode_mode == 'euler': # Euler update ode_grad_weights = [1.0] step_scale = [] else: raise ValueError('Unknown ODE mode!') # Extra steps for RK updates. num_extra_steps = len(step_scale) if FLAGS.reg_first_grad_only: first_reg_weight = FLAGS.grad_reg_weight / ode_grad_weights[0] other_reg_weight = 0.0 else: first_reg_weight = FLAGS.grad_reg_weight other_reg_weight = FLAGS.grad_reg_weight debug_ops, disc_grads, gen_grads = run_model(prior, image_splits[0], model, first_reg_weight) disc_vars, gen_vars = model.get_variables() final_disc_grads = _scale_vars(ode_grad_weights[0], disc_grads) final_gen_grads = _scale_vars(ode_grad_weights[0], gen_grads) restore_ops = [] # Preparing for further RK steps. if num_extra_steps > 0: # copy the variables before they are changed by update_op saved_disc_vars = _copy_vars(disc_vars) saved_gen_vars = _copy_vars(gen_vars) # Enter RK loop. with tf.control_dependencies(saved_disc_vars + saved_gen_vars): step_deps = [] for i_step in range(num_extra_steps): with tf.control_dependencies(step_deps): # Compute gradient steps for intermediate updates. update_op = update_model( model, disc_grads, gen_grads, disc_opt, gen_opt, None, step_scale[i_step]) with tf.control_dependencies([update_op]): _, disc_grads, gen_grads = run_model( prior, image_splits[i_step + 1], model, other_reg_weight) # Accumlate gradients for final update. final_disc_grads = _acc_grads(final_disc_grads, ode_grad_weights[i_step + 1], disc_grads) final_gen_grads = _acc_grads(final_gen_grads, ode_grad_weights[i_step + 1], gen_grads) # Make new restore_op for each step. restore_ops = [] restore_ops += _restore_vars(disc_vars, saved_disc_vars) restore_ops += _restore_vars(gen_vars, saved_gen_vars) step_deps = restore_ops with tf.control_dependencies(restore_ops): update_op = update_model( model, final_disc_grads, final_gen_grads, disc_opt, gen_opt, global_step, 1.0) samples = generator(prior.sample(FLAGS.batch_size), is_training=False) # Get data needed to compute FID. We also compute metrics on # real data as a sanity check and as a reference point. eval_real_data = utils.get_real_data_for_eval(FLAGS.num_eval_samples, FLAGS.dataset, split='train') def sample_fn(x): return utils.optimise_and_sample(x, module=model, data=None, is_training=False)[0] if FLAGS.run_sample_metrics: sample_metrics = image_metrics.get_image_metrics_for_samples( eval_real_data, sample_fn, prior, data_processor, num_eval_samples=FLAGS.num_eval_samples) else: sample_metrics = {} if FLAGS.run_real_data_metrics: data_metrics = image_metrics.get_image_metrics( eval_real_data, eval_real_data) else: data_metrics = {} sample_exporter = file_utils.FileExporter( os.path.join(FLAGS.output_dir, 'samples')) # Hooks. debug_ops['it'] = global_step # Abort training on Nans. nan_disc_hook = tf.train.NanTensorHook(debug_ops['disc_loss']) nan_gen_hook = tf.train.NanTensorHook(debug_ops['gen_loss']) # Step counter. step_conter_hook = tf.train.StepCounterHook() checkpoint_saver_hook = tf.train.CheckpointSaverHook( checkpoint_dir=utils.get_ckpt_dir(FLAGS.output_dir), save_secs=10 * 60) loss_summary_saver_hook = tf.train.SummarySaverHook( save_steps=FLAGS.summary_every_step, output_dir=os.path.join(FLAGS.output_dir, 'summaries'), summary_op=utils.get_summaries(debug_ops)) metrics_summary_saver_hook = tf.train.SummarySaverHook( save_steps=FLAGS.image_metrics_every_step, output_dir=os.path.join(FLAGS.output_dir, 'summaries'), summary_op=utils.get_summaries(sample_metrics)) hooks = [checkpoint_saver_hook, metrics_summary_saver_hook, nan_disc_hook, nan_gen_hook, step_conter_hook, loss_summary_saver_hook] # Start training. with tf.train.MonitoredSession(hooks=hooks) as sess: logging.info('starting training') for key, value in sess.run(data_metrics).items(): logging.info('%s: %d', key, value) for i in range(FLAGS.num_training_iterations): sess.run(update_op) if i % FLAGS.export_every == 0: samples_np, data_np = sess.run([samples, image_splits[0]]) # Create an object which gets data and does the processing. data_np = data_processor.postprocess(data_np) samples_np = data_processor.postprocess(samples_np) sample_exporter.save(samples_np, 'samples') sample_exporter.save(data_np, 'data') if __name__ == '__main__': tf.enable_resource_variables() app.run(main)
deepmind/deepmind-research
cs_gan/main_ode.py
Python
apache-2.0
12,654
# Copyright (c) 2014 Alcatel-Lucent Enterprise # All Rights Reserved. # # 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. from facette.utils import * from facette.v1.plotserie import PlotSerie import json PLOT_ID = "id" PLOT_NAME = "name" PLOT_DESCRIPTION = "description" PLOT_TYPE = "type" PLOT_SERIES = "series" PLOT_STACK_MODE = "stack_mode" PLOT_START = "start" PLOT_END = "end" PLOT_STEP = "step" PLOT_MODIFIED = "modified" PLOT_UNIT_LABEL = "unit_label" PLOT_UNIT_TYPE = "unit_type" GRAPH_TYPE_AREA = 1 GRAPH_TYPE_LINE = 2 STACK_MODE_NONE = 1 STACK_MODE_NORMAL = 2 STACK_MODE_PERCENT = 3 class Plot: def __init__(self, js=""): self.plot = {} self.id = facette_to_json(PLOT_ID, js, self.plot) self.name = facette_to_json(PLOT_NAME, js, self.plot) self.description = facette_to_json(PLOT_DESCRIPTION, js, self.plot) self.type = facette_to_json(PLOT_TYPE, js, self.plot) self.stack_mode = facette_to_json(PLOT_STACK_MODE, js, self.plot) self.start = facette_to_json(PLOT_START, js, self.plot) self.end = facette_to_json(PLOT_END, js, self.plot) self.step = facette_to_json(PLOT_STEP, js, self.plot) self.modified = facette_to_json(PLOT_MODIFIED, js, self.plot) self.unit_label = facette_to_json(PLOT_UNIT_LABEL, js, self.plot) self.unit_type = facette_to_json(PLOT_UNIT_TYPE, js, self.plot) self.series = [] if js.get(PLOT_SERIES): for x in js[PLOT_SERIES]: e = PlotSerie(x) self.series.append(e) self.plot[PLOT_SERIES] = self.series def __str__(self): js = self.plot series = [] for s in self.series: series.append(json.loads(str(s))) js[PLOT_SERIES] = series return json.dumps(js) def __repr__(self): return str(self)
OpenTouch/python-facette
src/facette/v1/plot.py
Python
apache-2.0
2,559
#include "gen-cpp/LogSender.h" #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/server/TNonblockingServer.h> #include <thrift/transport/TServerSocket.h> #include <thrift/transport/TBufferTransports.h> #include <thrift/concurrency/PosixThreadFactory.h> using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::transport; using namespace ::apache::thrift::server; using namespace ::apache::thrift::concurrency; using boost::shared_ptr; #define THREAD_NUM 5 std::map<std::string, std::string> logMap; class LogSenderHandler : virtual public LogSenderIf { public: LogSenderHandler() { // Your initialization goes here } void SendLog(const std::vector<LogInfo> & loglist) { // Your implementation goes here sleep(5); time_t now = time(NULL); printf("SendLog, now = %s\n", ctime(&now)); for (size_t i = 0; i < loglist.size(); ++i) { if (logMap.find(loglist[i].name) == logMap.end()) { logMap.insert(std::make_pair(loglist[i].name, loglist[i].content)); } } } void GetLog(std::string& _return, const std::string& logname) { // Your implementation goes here std::map<std::string,std::string>::iterator iter = logMap.find(logname); if (iter != logMap.end()) { _return = iter->second; } else { _return = "Not Found!"; } } }; int main(int argc, char **argv) { int port = 9090; shared_ptr<LogSenderHandler> handler(new LogSenderHandler()); shared_ptr<TProcessor> processor(new LogSenderProcessor(handler)); shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(THREAD_NUM); shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory> (new PosixThreadFactory()); threadManager->threadFactory(threadFactory); threadManager->start(); TNonblockingServer server(processor, protocolFactory, port, threadManager); server.serve(); return 0; }
opensource000/cnblogs
log_thrift/nonblock_server.cpp
C++
apache-2.0
2,062
package gov.va.med.imaging.exceptions; public class StudyURNFormatException extends URNFormatException { private static final long serialVersionUID = 6271193731031546478L; public StudyURNFormatException() { super(); } public StudyURNFormatException(String message) { super(message); } public StudyURNFormatException(Throwable cause) { super(cause); } public StudyURNFormatException(String message, Throwable cause) { super(message, cause); } }
VHAINNOVATIONS/Telepathology
Source/Java/ImagingCommon/main/src/java/gov/va/med/imaging/exceptions/StudyURNFormatException.java
Java
apache-2.0
472
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.session.state; import java.io.IOException; import org.jsmpp.bean.Command; import org.jsmpp.session.ResponseHandler; import org.jsmpp.session.SMPPSessionContext; /** * This class provides the interface to response to every incoming SMPP Command. * How the response behavior is, depends on its state, or the * implementation of this class. * * @author uudashr * @version 1.0 * @since 2.0 */ public interface SMPPSessionState extends GenericSMPPSessionState { SMPPSessionState OPEN = new SMPPSessionOpen(); SMPPSessionState BOUND_RX = new SMPPSessionBoundRX(); SMPPSessionState BOUND_TX = new SMPPSessionBoundTX(); SMPPSessionState BOUND_TRX = new SMPPSessionBoundTRX(); SMPPSessionState UNBOUND = new SMPPSessionUnbound(); SMPPSessionState CLOSED = new SMPPSessionClosed(); /** * Process the bind response command. * * @param sessionContext the session context. * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException if an input or output error occurred. */ void processBindResp(SMPPSessionContext sessionContext, Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the submit short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the response handler. * @throws IOException if there is an I/O error found. */ void processSubmitSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process a submit multiple message response. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the response handler. * @throws IOException if there is an I/O error found. */ void processSubmitMultiResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the query short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processQuerySmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the deliver short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processDeliverSm(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the cancel short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processCancelSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the replace short message request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processReplaceSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the alert notification request command. * * @param pduHeader is the PDU header. * @param pdu is the complete PDU. * @param responseHandler is the session handler. */ void processAlertNotification(Command pduHeader, byte[] pdu, ResponseHandler responseHandler); /** * Process the broadcast short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete broadcast_sm PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processBroadcastSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the cancel broadcast short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete cancel_broadcast_sm PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processCancelBroadcastSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; /** * Process the query broadcast short message response command. * * @param pduHeader is the PDU header. * @param pdu is the complete query_broadcast_sm PDU. * @param responseHandler is the session handler. * @throws IOException throw if there is an IO error occur. */ void processQueryBroadcastSmResp(Command pduHeader, byte[] pdu, ResponseHandler responseHandler) throws IOException; }
opentelecoms-org/jsmpp
jsmpp/src/main/java/org/jsmpp/session/state/SMPPSessionState.java
Java
apache-2.0
6,024
/* * Licensed to David Pilato (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author 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 fr.pilato.spring.elasticsearch.it.annotation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; import static fr.pilato.spring.elasticsearch.ElasticsearchAbstractFactoryBean.XPACK_USER; import static fr.pilato.spring.elasticsearch.it.BaseTest.testCredentials; @Configuration public class SecurityOptionalConfig { @Bean("esProperties") public Properties properties() { Properties properties = new Properties(); properties.setProperty(XPACK_USER, testCredentials); return properties; } }
dadoonet/spring-elasticsearch
src/test/java/fr/pilato/spring/elasticsearch/it/annotation/SecurityOptionalConfig.java
Java
apache-2.0
1,399
// vim: et sw=4 sts=4 tabstop=4 /* * 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.issc.widget; import com.issc.R; import android.app.DialogFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class LoadingFragment extends DialogFragment { public LoadingFragment() { super(); setStyle(DialogFragment.STYLE_NO_FRAME, 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.progressdialog, container, false); return v; } }
ISSC/Bluebit
src/com/issc/widget/LoadingFragment.java
Java
apache-2.0
1,195
#!/usr/bin/env python """ Set up the logging """ import logging import tempfile import os def initialize_logging(): """ Set up the screen and file logging. :return: The log filename """ # set up DEBUG logging to file, INFO logging to STDERR log_file = os.path.join(tempfile.gettempdir(), 'spfy.log') formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=log_file, filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setFormatter(formatter) console.setLevel(logging.INFO) # add the handler to the root logger logging.getLogger('').addHandler(console) return log_file
superphy/backend
app/modules/loggingFunctions.py
Python
apache-2.0
1,056
package io.particle.android.sdk.cloud; import android.annotation.SuppressLint; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.MainThread; import android.support.annotation.Nullable; import android.support.annotation.WorkerThread; import org.greenrobot.eventbus.EventBus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import javax.annotation.ParametersAreNonnullByDefault; import io.particle.android.sdk.cloud.Responses.ReadDoubleVariableResponse; import io.particle.android.sdk.cloud.Responses.ReadIntVariableResponse; import io.particle.android.sdk.cloud.Responses.ReadObjectVariableResponse; import io.particle.android.sdk.cloud.Responses.ReadStringVariableResponse; import io.particle.android.sdk.cloud.Responses.ReadVariableResponse; import io.particle.android.sdk.cloud.exceptions.ParticleCloudException; import io.particle.android.sdk.cloud.models.DeviceStateChange; import io.particle.android.sdk.utils.ParticleInternalStringUtils; import io.particle.android.sdk.utils.Preconditions; import io.particle.android.sdk.utils.TLog; import okio.Okio; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.mime.TypedByteArray; import retrofit.mime.TypedFile; import static io.particle.android.sdk.utils.Py.list; // don't warn about public APIs not being referenced inside this module, or about // the _default locale_ in a bunch of backend code @SuppressLint("DefaultLocale") @SuppressWarnings({"UnusedDeclaration"}) @ParametersAreNonnullByDefault public class ParticleDevice implements Parcelable { public enum ParticleDeviceType { CORE, PHOTON, P1, RASPBERRY_PI, RED_BEAR_DUO, BLUZ, DIGISTUMP_OAK, ELECTRON, ARGON, BORON, XENON; // FIXME: ADD MESH TYPES BELOW public static ParticleDeviceType fromInt(int intValue) { switch (intValue) { case 0: return CORE; case 8: return P1; case 10: return ELECTRON; case 31: return RASPBERRY_PI; case 82: return DIGISTUMP_OAK; case 88: return RED_BEAR_DUO; case 103: return BLUZ; case 6: default: return PHOTON; } } } public enum ParticleDeviceState { CAME_ONLINE, FLASH_STARTED, FLASH_SUCCEEDED, FLASH_FAILED, APP_HASH_UPDATED, ENTERED_SAFE_MODE, SAFE_MODE_UPDATER, WENT_OFFLINE, UNKNOWN } public enum VariableType { INT, DOUBLE, STRING } public static class FunctionDoesNotExistException extends Exception { public FunctionDoesNotExistException(String functionName) { super("Function " + functionName + " does not exist on this device"); } } public static class VariableDoesNotExistException extends Exception { public VariableDoesNotExistException(String variableName) { super("Variable " + variableName + " does not exist on this device"); } } public enum KnownApp { TINKER("tinker"); private final String appName; KnownApp(String appName) { this.appName = appName; } public String getAppName() { return appName; } } private static final int MAX_PARTICLE_FUNCTION_ARG_LENGTH = 63; private static final TLog log = TLog.get(ParticleDevice.class); private final CopyOnWriteArrayList<Long> subscriptions = new CopyOnWriteArrayList<>(); private final ApiDefs.CloudApi mainApi; private final ParticleCloud cloud; volatile DeviceState deviceState; private volatile boolean isFlashing = false; ParticleDevice(ApiDefs.CloudApi mainApi, ParticleCloud cloud, DeviceState deviceState) { this.mainApi = mainApi; this.cloud = cloud; this.deviceState = deviceState; } /** * Device ID string */ public String getID() { return deviceState.deviceId; } /** * Device name. Device can be renamed in the cloud via #setName(String) */ public String getName() { return deviceState.name; } /** * Rename the device in the cloud. If renaming fails name will stay the same. */ public void setName(String newName) throws ParticleCloudException { cloud.rename(this.deviceState.deviceId, newName); } /** * Is device connected to the cloud? */ public boolean isConnected() { return deviceState.isConnected; } /** * Get an immutable set of all the function names exposed by device */ public Set<String> getFunctions() { // no need for a defensive copy, this is an immutable set return deviceState.functions; } /** * Get an immutable map of exposed variables on device with their respective types. */ public Map<String, VariableType> getVariables() { // no need for a defensive copy, this is an immutable set return deviceState.variables; } /** * Device firmware version string */ public String getVersion() { return deviceState.version; } public boolean requiresUpdate() { return deviceState.requiresUpdate; } public ParticleDeviceType getDeviceType() { return deviceState.deviceType; } public int getPlatformID() { return deviceState.platformId; } public int getProductID() { return deviceState.productId; } public boolean isCellular() { return deviceState.cellular; } public String getImei() { return deviceState.imei; } public String getIccid() { return deviceState.lastIccid; } public String getCurrentBuild() { return deviceState.currentBuild; } public String getDefaultBuild() { return deviceState.defaultBuild; } public String getIpAddress() { return deviceState.ipAddress; } public String getLastAppName() { return deviceState.lastAppName; } public String getStatus() { return deviceState.status; } public Date getLastHeard() { return deviceState.lastHeard; } @WorkerThread public float getCurrentDataUsage() throws ParticleCloudException { float maxUsage = 0; try { Response response = mainApi.getCurrentDataUsage(deviceState.lastIccid); JSONObject result = new JSONObject(new String(((TypedByteArray) response.getBody()).getBytes())); JSONArray usages = result.getJSONArray("usage_by_day"); for (int i = 0; i < usages.length(); i++) { JSONObject usageElement = usages.getJSONObject(i); if (usageElement.has("mbs_used_cumulative")) { double usage = usageElement.getDouble("mbs_used_cumulative"); if (usage > maxUsage) { maxUsage = (float) usage; } } } } catch (JSONException | RetrofitError e) { throw new ParticleCloudException(e); } return maxUsage; } /** * Return the value for <code>variableName</code> on this Particle device. * <p> * Unless you specifically require generic handling, it is recommended that you use the * <code>get(type)Variable</code> methods instead, e.g.: <code>getIntVariable()</code>. * These type-specific methods don't require extra casting or type checking on your part, and * they more clearly and succinctly express your intent. */ @WorkerThread public Object getVariable(String variableName) throws ParticleCloudException, IOException, VariableDoesNotExistException { VariableRequester<Object, ReadObjectVariableResponse> requester = new VariableRequester<Object, ReadObjectVariableResponse>(this) { @Override ReadObjectVariableResponse callApi(String variableName) { return mainApi.getVariable(deviceState.deviceId, variableName); } }; return requester.getVariable(variableName); } /** * Return the value for <code>variableName</code> as an int. * <p> * Where practical, this method is recommended over the generic {@link #getVariable(String)}. * See the javadoc on that method for details. */ @WorkerThread public int getIntVariable(String variableName) throws ParticleCloudException, IOException, VariableDoesNotExistException, ClassCastException { VariableRequester<Integer, ReadIntVariableResponse> requester = new VariableRequester<Integer, ReadIntVariableResponse>(this) { @Override ReadIntVariableResponse callApi(String variableName) { return mainApi.getIntVariable(deviceState.deviceId, variableName); } }; return requester.getVariable(variableName); } /** * Return the value for <code>variableName</code> as a String. * <p> * Where practical, this method is recommended over the generic {@link #getVariable(String)}. * See the javadoc on that method for details. */ @WorkerThread public String getStringVariable(String variableName) throws ParticleCloudException, IOException, VariableDoesNotExistException, ClassCastException { VariableRequester<String, ReadStringVariableResponse> requester = new VariableRequester<String, ReadStringVariableResponse>(this) { @Override ReadStringVariableResponse callApi(String variableName) { return mainApi.getStringVariable(deviceState.deviceId, variableName); } }; return requester.getVariable(variableName); } /** * Return the value for <code>variableName</code> as a double. * <p> * Where practical, this method is recommended over the generic {@link #getVariable(String)}. * See the javadoc on that method for details. */ @WorkerThread public double getDoubleVariable(String variableName) throws ParticleCloudException, IOException, VariableDoesNotExistException, ClassCastException { VariableRequester<Double, ReadDoubleVariableResponse> requester = new VariableRequester<Double, ReadDoubleVariableResponse>(this) { @Override ReadDoubleVariableResponse callApi(String variableName) { return mainApi.getDoubleVariable(deviceState.deviceId, variableName); } }; return requester.getVariable(variableName); } /** * Call a function on the device * * @param functionName Function name * @param args Array of arguments to pass to the function on the device. * Arguments must not be more than MAX_PARTICLE_FUNCTION_ARG_LENGTH chars * in length. If any arguments are longer, a runtime exception will be thrown. * @return result code: a value of 1 indicates success */ @WorkerThread public int callFunction(String functionName, @Nullable List<String> args) throws ParticleCloudException, IOException, FunctionDoesNotExistException { // TODO: check response of calling a non-existent function if (!deviceState.functions.contains(functionName)) { throw new FunctionDoesNotExistException(functionName); } // null is accepted here, but it won't be in the Retrofit API call later if (args == null) { args = list(); } String argsString = ParticleInternalStringUtils.join(args, ','); Preconditions.checkArgument(argsString.length() < MAX_PARTICLE_FUNCTION_ARG_LENGTH, String.format("Arguments '%s' exceed max args length of %d", argsString, MAX_PARTICLE_FUNCTION_ARG_LENGTH)); Responses.CallFunctionResponse response; try { response = mainApi.callFunction(deviceState.deviceId, functionName, new FunctionArgs(argsString)); } catch (RetrofitError e) { throw new ParticleCloudException(e); } if (!response.connected) { cloud.onDeviceNotConnected(deviceState); throw new IOException("Device is not connected."); } else { return response.returnValue; } } /** * Call a function on the device * * @param functionName Function name * @return value of the function */ @WorkerThread public int callFunction(String functionName) throws ParticleCloudException, IOException, FunctionDoesNotExistException { return callFunction(functionName, null); } /** * Subscribe to events from this device * * @param eventNamePrefix (optional, may be null) a filter to match against for events. If * null or an empty string, all device events will be received by the handler * trigger eventHandler * @param handler The handler for the events received for this subscription. * @return the subscription ID * (see {@link ParticleCloud#subscribeToAllEvents(String, ParticleEventHandler)} for more info */ public long subscribeToEvents(@Nullable String eventNamePrefix, ParticleEventHandler handler) throws IOException { return cloud.subscribeToDeviceEvents(eventNamePrefix, deviceState.deviceId, handler); } /** * Unsubscribe from events. * * @param eventListenerID The ID of the subscription to be cancelled. (returned from * {@link #subscribeToEvents(String, ParticleEventHandler)} */ public void unsubscribeFromEvents(long eventListenerID) throws ParticleCloudException { cloud.unsubscribeFromEventWithID(eventListenerID); } /** * Remove device from current logged in user account */ @WorkerThread public void unclaim() throws ParticleCloudException { try { cloud.unclaimDevice(deviceState.deviceId); } catch (RetrofitError e) { throw new ParticleCloudException(e); } } public boolean isRunningTinker() { List<String> lowercaseFunctions = list(); for (String func : deviceState.functions) { lowercaseFunctions.add(func.toLowerCase()); } List<String> tinkerFunctions = list("analogread", "analogwrite", "digitalread", "digitalwrite"); return (isConnected() && lowercaseFunctions.containsAll(tinkerFunctions)); } public boolean isFlashing() { return isFlashing; } @WorkerThread public void flashKnownApp(final KnownApp knownApp) throws ParticleCloudException { performFlashingChange(() -> mainApi.flashKnownApp(deviceState.deviceId, knownApp.appName)); } @WorkerThread public void flashBinaryFile(final File file) throws ParticleCloudException { performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId, new TypedFile("application/octet-stream", file))); } @WorkerThread public void flashBinaryFile(InputStream stream) throws ParticleCloudException, IOException { final byte[] bytes = Okio.buffer(Okio.source(stream)).readByteArray(); performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId, new TypedFakeFile(bytes))); } @WorkerThread public void flashCodeFile(final File file) throws ParticleCloudException { performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId, new TypedFile("multipart/form-data", file))); } @WorkerThread public void flashCodeFile(InputStream stream) throws ParticleCloudException, IOException { final byte[] bytes = Okio.buffer(Okio.source(stream)).readByteArray(); performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId, new TypedFakeFile(bytes, "multipart/form-data", "code.ino"))); } public ParticleCloud getCloud() { return cloud; } @WorkerThread public void refresh() throws ParticleCloudException { // just calling this get method will update everything as expected. cloud.getDevice(deviceState.deviceId); } private interface FlashingChange { void executeFlashingChange() throws RetrofitError; } // FIXME: ugh. these "cloud.notifyDeviceChanged();" calls are a hint that flashing maybe // should just live in a class of its own, or that it should just be a delegate on // ParticleCloud. Review this later. private void performFlashingChange(FlashingChange flashingChange) throws ParticleCloudException { try { flashingChange.executeFlashingChange(); //listens for flashing event, on success unsubscribe from listening. subscribeToSystemEvent("spark/flash/status", new SimpleParticleEventHandler() { @Override public void onEvent(String eventName, ParticleEvent particleEvent) { if ("success".equals(particleEvent.dataPayload)) { isFlashing = false; try { ParticleDevice.this.refresh(); cloud.unsubscribeFromEventWithHandler(this); } catch (ParticleCloudException e) { // not much else we can really do here... log.w("Unable to reset flashing state for %s" + deviceState.deviceId, e); } } else { isFlashing = true; } cloud.notifyDeviceChanged(); } }); } catch (RetrofitError | IOException e) { throw new ParticleCloudException(e); } } /** * Subscribes to system events of current device. Events emitted to EventBus listener. * * @throws ParticleCloudException Failure to subscribe to system events. * @see <a href="https://github.com/greenrobot/EventBus">EventBus</a> */ @MainThread public void subscribeToSystemEvents() throws ParticleCloudException { try { EventBus eventBus = EventBus.getDefault(); subscriptions.add(subscribeToSystemEvent("spark/status", (eventName, particleEvent) -> sendUpdateStatusChange(eventBus, particleEvent.dataPayload))); subscriptions.add(subscribeToSystemEvent("spark/flash/status", (eventName, particleEvent) -> sendUpdateFlashChange(eventBus, particleEvent.dataPayload))); subscriptions.add(subscribeToSystemEvent("spark/device/app-hash", (eventName, particleEvent) -> sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this, ParticleDeviceState.APP_HASH_UPDATED), eventBus))); subscriptions.add(subscribeToSystemEvent("spark/status/safe-mode", (eventName, particleEvent) -> sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this, ParticleDeviceState.SAFE_MODE_UPDATER), eventBus))); subscriptions.add(subscribeToSystemEvent("spark/safe-mode-updater/updating", (eventName, particleEvent) -> sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this, ParticleDeviceState.ENTERED_SAFE_MODE), eventBus))); } catch (IOException e) { log.d("Failed to auto-subscribe to system events"); throw new ParticleCloudException(e); } } private void sendSystemEventBroadcast(DeviceStateChange deviceStateChange, EventBus eventBus) { cloud.sendSystemEventBroadcast(deviceStateChange); eventBus.post(deviceStateChange); } /** * Unsubscribes from system events of current device. * * @throws ParticleCloudException Failure to unsubscribe from system events. */ public void unsubscribeFromSystemEvents() throws ParticleCloudException { for (Long subscriptionId : subscriptions) { unsubscribeFromEvents(subscriptionId); } } private long subscribeToSystemEvent(String eventNamePrefix, SimpleParticleEventHandler particleEventHandler) throws IOException { //Error would be handled in same way for every event name prefix, thus only simple onEvent listener is needed return subscribeToEvents(eventNamePrefix, new ParticleEventHandler() { @Override public void onEvent(String eventName, ParticleEvent particleEvent) { particleEventHandler.onEvent(eventName, particleEvent); } @Override public void onEventError(Exception e) { log.d("Event error in system event handler"); } }); } private void sendUpdateStatusChange(EventBus eventBus, String data) { DeviceStateChange deviceStateChange = null; switch (data) { case "online": sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.CAME_ONLINE), eventBus); break; case "offline": sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.WENT_OFFLINE), eventBus); break; } } private void sendUpdateFlashChange(EventBus eventBus, String data) { DeviceStateChange deviceStateChange = null; switch (data) { case "started": sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.FLASH_STARTED), eventBus); break; case "success": sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.FLASH_SUCCEEDED), eventBus); break; } } @Override public String toString() { return "ParticleDevice{" + "deviceId=" + deviceState.deviceId + ", isConnected=" + deviceState.isConnected + ", deviceType=" + deviceState.deviceType + '}'; } //region Parcelable @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(deviceState, flags); } @Override public int describeContents() { return 0; } public static final Creator<ParticleDevice> CREATOR = new Creator<ParticleDevice>() { @Override public ParticleDevice createFromParcel(Parcel in) { SDKProvider sdkProvider = ParticleCloudSDK.getSdkProvider(); DeviceState deviceState = in.readParcelable(DeviceState.class.getClassLoader()); return sdkProvider.getParticleCloud().getDeviceFromState(deviceState); } @Override public ParticleDevice[] newArray(int size) { return new ParticleDevice[size]; } }; //endregion private static class TypedFakeFile extends TypedByteArray { private final String fileName; /** * Constructs a new typed byte array. Sets mimeType to {@code application/unknown} if absent. * * @throws NullPointerException if bytes are null */ public TypedFakeFile(byte[] bytes) { this(bytes, "application/octet-stream", "tinker_firmware.bin"); } public TypedFakeFile(byte[] bytes, String mimeType, String fileName) { super(mimeType, bytes); this.fileName = fileName; } @Override public String fileName() { return fileName; } } private static abstract class VariableRequester<T, R extends ReadVariableResponse<T>> { @WorkerThread abstract R callApi(String variableName); private final ParticleDevice device; VariableRequester(ParticleDevice device) { this.device = device; } @WorkerThread T getVariable(String variableName) throws ParticleCloudException, IOException, VariableDoesNotExistException { if (!device.deviceState.variables.containsKey(variableName)) { throw new VariableDoesNotExistException(variableName); } R reply; try { reply = callApi(variableName); } catch (RetrofitError e) { throw new ParticleCloudException(e); } if (!reply.coreInfo.connected) { // FIXME: we should be doing this "connected" check on _any_ reply that comes back // with a "coreInfo" block. device.cloud.onDeviceNotConnected(device.deviceState); throw new IOException("Device is not connected."); } else { return reply.result; } } } }
spark/spark-sdk-android
cloudsdk/src/main/java/io/particle/android/sdk/cloud/ParticleDevice.java
Java
apache-2.0
26,059
<?php /** * Copyright 2012-2014 Rackspace US, Inc. * * 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. */ namespace OpenCloud\Tests\Volume\Resource; use OpenCloud\Tests\Volume\VolumeTestCase; class SnapshotTest extends VolumeTestCase { private $snapshot; public function setupObjects() { parent::setupObjects(); $this->snapshot = $this->service->snapshot(); } public function test_Create() { $this->snapshot->create(array()); } /** * @expectedException OpenCloud\Common\Exceptions\UpdateError */ public function testUpdate() { $this->snapshot->update(); } public function testName() { $this->snapshot->display_name = 'FOOBAR'; $this->assertEquals('FOOBAR', $this->snapshot->Name()); } public function testJsonName() { $this->assertEquals('snapshot', $this->snapshot->JsonName()); } public function testResourceName() { $this->assertEquals('snapshots', $this->snapshot->ResourceName()); } /** * @expectedException \InvalidArgumentException */ public function testUpdateDisallowedProperties() { $this->volume->rename(array( 'volume_id' => 'abcd-ef12' )); } }
haskell-infra/libphutil-rackspace
externals/php-opencloud/vendor/rackspace/php-opencloud/tests/OpenCloud/Tests/Volume/Resource/SnapshotTest.php
PHP
apache-2.0
1,781
package org.grobid.core.features; import org.grobid.core.layout.LayoutToken; import org.grobid.core.utilities.TextUtilities; /** * Class for features used for fulltext parsing. * */ public class FeaturesVectorFulltext { public LayoutToken token = null; // not a feature, reference value public String string = null; // lexical feature public String label = null; // label if known public String blockStatus = null; // one of BLOCKSTART, BLOCKIN, BLOCKEND public String lineStatus = null; // one of LINESTART, LINEIN, LINEEND public String fontStatus = null; // one of NEWFONT, SAMEFONT public String fontSize = null; // one of HIGHERFONT, SAMEFONTSIZE, LOWERFONT public String alignmentStatus = null; // one of ALIGNEDLEFT, INDENTED, CENTERED - applied to the whole line public boolean bold = false; public boolean italic = false; public String capitalisation = null; // one of INITCAP, ALLCAPS, NOCAPS public String digit; // one of ALLDIGIT, CONTAINDIGIT, NODIGIT public boolean singleChar = false; public String punctType = null; // one of NOPUNCT, OPENBRACKET, ENDBRACKET, DOT, COMMA, HYPHEN, QUOTE, PUNCT (default) public int relativeDocumentPosition = -1; public int relativePagePositionChar = -1; public int relativePagePosition = -1; // graphic in closed proximity of the current block public boolean bitmapAround = false; public boolean vectorAround = false; // if a graphic is in close proximity of the current block, characteristics of this graphic public int closestGraphicHeight = -1; public int closestGraphicWidth = -1; public int closestGraphicSurface = -1; public int spacingWithPreviousBlock = 0; // discretized public int characterDensity = 0; // discretized // how the reference callouts are expressed, if known public String calloutType = null; // one of UNKNOWN, NUMBER, AUTHOR public boolean calloutKnown = false; // true if the token match a known reference label public boolean superscript = false; public String printVector() { if (string == null) return null; if (string.length() == 0) return null; StringBuffer res = new StringBuffer(); // token string (1) res.append(string); // lowercase string res.append(" " + string.toLowerCase()); // prefix (4) res.append(" " + TextUtilities.prefix(string, 1)); res.append(" " + TextUtilities.prefix(string, 2)); res.append(" " + TextUtilities.prefix(string, 3)); res.append(" " + TextUtilities.prefix(string, 4)); // suffix (4) res.append(" " + TextUtilities.suffix(string, 1)); res.append(" " + TextUtilities.suffix(string, 2)); res.append(" " + TextUtilities.suffix(string, 3)); res.append(" " + TextUtilities.suffix(string, 4)); // at this stage, we have written 10 features // block information (1) res.append(" " + blockStatus); // line information (1) res.append(" " + lineStatus); // line position/identation (1) res.append(" " + alignmentStatus); // font information (1) res.append(" " + fontStatus); // font size information (1) res.append(" " + fontSize); // string type information (3) if (bold) res.append(" 1"); else res.append(" 0"); if (italic) res.append(" 1"); else res.append(" 0"); // capitalisation (1) if (digit.equals("ALLDIGIT")) res.append(" NOCAPS"); else res.append(" " + capitalisation); // digit information (1) res.append(" " + digit); // character information (1) if (singleChar) res.append(" 1"); else res.append(" 0"); // at this stage, we have written 20 features // punctuation information (1) res.append(" " + punctType); // in case the token is a punctuation (NO otherwise) // relative document position (1) res.append(" " + relativeDocumentPosition); // relative page position (1) res.append(" " + relativePagePosition); // proximity of a graphic to the current block (2) if (bitmapAround) res.append(" 1"); else res.append(" 0"); /*if (vectorAround) res.append(" 1"); else res.append(" 0");*/ // space with previous block, discretised (1) //res.append(" " + spacingWithPreviousBlock); //res.append(" " + 0); // character density of the previous block, discretised (1) //res.append(" " + characterDensity); //res.append(" " + 0); // label - for training data (1) /*if (label != null) res.append(" " + label + "\n"); else res.append(" 0\n"); */ if (calloutType != null) res.append(" " + calloutType); else res.append(" UNKNOWN"); if (calloutKnown) res.append(" 1"); else res.append(" 0"); if (superscript) res.append(" 1"); else res.append(" 0"); res.append("\n"); return res.toString(); } }
kermitt2/grobid
grobid-core/src/main/java/org/grobid/core/features/FeaturesVectorFulltext.java
Java
apache-2.0
5,369
import numpy as np def sigmoid(x): """ Compute the sigmoid function for the input here. """ x = 1. / (1. + np.exp(-x)) return x def sigmoid_grad(f): """ Compute the gradient for the sigmoid function here. Note that for this implementation, the input f should be the sigmoid function value of your original input x. """ f = f * (1. - f) return f def test_sigmoid_basic(): """ Some simple tests to get you started. Warning: these are not exhaustive. """ print "Running basic tests..." x = np.array([[1, 2], [-1, -2]]) f = sigmoid(x) g = sigmoid_grad(f) print f assert np.amax(f - np.array([[0.73105858, 0.88079708], [0.26894142, 0.11920292]])) <= 1e-6 print g assert np.amax(g - np.array([[0.19661193, 0.10499359], [0.19661193, 0.10499359]])) <= 1e-6 print "You should verify these results!\n" def test_sigmoid(): """ Use this space to test your sigmoid implementation by running: python q2_sigmoid.py This function will not be called by the autograder, nor will your tests be graded. """ print "Running your tests..." ### YOUR CODE HERE raise NotImplementedError ### END YOUR CODE if __name__ == "__main__": test_sigmoid_basic(); #test_sigmoid()
zhaojijet/CS224d
Assignment1/q2_sigmoid.py
Python
apache-2.0
1,343
#region Copyright (c) 2011 Atif Aziz. All rights reserved. // // 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. // #endregion // ReSharper disable once CheckNamespace namespace Elmah.Fabmail { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using MoreLinq; partial class StackTraceHtmlFragments : IStackTraceFormatter<string> { public string BeforeType { get; set; } public string AfterType { get; set; } public string BeforeMethod { get; set; } public string AfterMethod { get; set; } public string BeforeParameterType { get; set; } public string AfterParameterType { get; set; } public string BeforeParameterName { get; set; } public string AfterParameterName { get; set; } public string BeforeFile { get; set; } public string AfterFile { get; set; } public string BeforeLine { get; set; } public string AfterLine { get; set; } public string BeforeFrame { get; set; } public string AfterFrame { get; set; } public string BeforeParameters { get; set; } public string AfterParameters { get; set; } string IStackTraceFormatter<string>.Text(string text) => string.IsNullOrEmpty(text) ? string.Empty : WebUtility.HtmlEncode(text); string IStackTraceFormatter<string>.Type(string markup) => BeforeType + markup + AfterType; string IStackTraceFormatter<string>.Method(string markup) => BeforeMethod + markup + AfterMethod; string IStackTraceFormatter<string>.ParameterType(string markup) => BeforeParameterType + markup + AfterParameterType; string IStackTraceFormatter<string>.ParameterName(string markup) => BeforeParameterName + markup + AfterParameterName; string IStackTraceFormatter<string>.File(string markup) => BeforeFile + markup + AfterFile; string IStackTraceFormatter<string>.Line(string markup) => BeforeLine + markup + AfterLine; string IStackTraceFormatter<string>.BeforeFrame => BeforeFrame ?? string.Empty; string IStackTraceFormatter<string>.AfterFrame => AfterFrame ?? string.Empty; string IStackTraceFormatter<string>.BeforeParameters => BeforeParameters ?? string.Empty; string IStackTraceFormatter<string>.AfterParameters => AfterParameters ?? string.Empty; } partial interface IStackTraceFormatter<T> { T Text (string text); T Type (T markup); T Method (T markup); T ParameterType (T markup); T ParameterName (T markup); T File (T markup); T Line (T markup); T BeforeFrame { get; } T AfterFrame { get; } T BeforeParameters { get; } T AfterParameters { get; } } static partial class StackTraceFormatter { static readonly StackTraceHtmlFragments DefaultStackTraceHtmlFragments = new StackTraceHtmlFragments(); public static string FormatHtml(string text, IStackTraceFormatter<string> formatter) { return string.Concat(Format(text, formatter ?? DefaultStackTraceHtmlFragments)); } public static IEnumerable<T> Format<T>(string text, IStackTraceFormatter<T> formatter) { Debug.Assert(text != null); var frames = StackTraceParser.Parse ( text, (idx, len, txt) => new { Index = idx, End = idx + len, Text = txt, Markup = formatter.Text(txt), }, (t, m) => new { Type = new { t.Index, t.End, Markup = formatter.Type(t.Markup) }, Method = new { m.Index, m.End, Markup = formatter.Method(m.Markup) } }, (t, n) => new { Type = new { t.Index, t.End, Markup = formatter.ParameterType(t.Markup) }, Name = new { n.Index, n.End, Markup = formatter.ParameterName(n.Markup) } }, (p, ps) => new { List = p, Parameters = ps.ToArray() }, (f, l) => new { File = f.Text.Length > 0 ? new { f.Index, f.End, Markup = formatter.File(f.Markup) } : null, Line = l.Text.Length > 0 ? new { l.Index, l.End, Markup = formatter.Line(l.Markup) } : null, }, (f, tm, p, fl) => from tokens in new[] { new[] { new { f.Index, End = f.Index, Markup = formatter.BeforeFrame }, tm.Type, tm.Method, new { p.List.Index, End = p.List.Index, Markup = formatter.BeforeParameters }, }, from pe in p.Parameters from e in new[] { pe.Type, pe.Name } select e, new[] { new { Index = p.List.End, p.List.End, Markup = formatter.AfterParameters }, fl.File, fl.Line, new { Index = f.End, f.End, Markup = formatter.AfterFrame }, }, } from token in tokens where token != null select token ); return from token in Enumerable.Repeat(new { Index = 0, End = 0, Markup = default(T) }, 1) .Concat(from tokens in frames from token in tokens select token) .Pairwise((prev, curr) => new { Previous = prev, Current = curr }) from m in new[] { formatter.Text(text.Substring(token.Previous.End, token.Current.Index - token.Previous.End)), token.Current.Markup, } select m; } } }
elmah/Fabmail
src/App_Packages/StackTraceFormatter/StackTraceFormatter.cs
C#
apache-2.0
7,333
# frozen_string_literal: true module Archimate module DataModel # document attribute holds all the concern information. # # This is ConcernType in the XSD class Concern include Comparison # @!attribute [r] label # @return [LangString] one label is required model_attr :label # @!attribute [r] documentation # @return [PreservedLangString] model_attr :documentation, default: nil # @!attribute [r] stakeholders # @return [Array<LangString>] model_attr :stakeholders, default: [] end end end
mmorga/archi-tools-rb
lib/archimate/data_model/concern.rb
Ruby
apache-2.0
576
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.glue.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.glue.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * GetCatalogImportStatusRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetCatalogImportStatusRequestMarshaller { private static final MarshallingInfo<String> CATALOGID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("CatalogId").build(); private static final GetCatalogImportStatusRequestMarshaller instance = new GetCatalogImportStatusRequestMarshaller(); public static GetCatalogImportStatusRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(GetCatalogImportStatusRequest getCatalogImportStatusRequest, ProtocolMarshaller protocolMarshaller) { if (getCatalogImportStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getCatalogImportStatusRequest.getCatalogId(), CATALOGID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GetCatalogImportStatusRequestMarshaller.java
Java
apache-2.0
2,076
/* * Copyright 2017 Seven Bridges Genomics, Inc. All rights reserved. * * 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.sevenbridges.apiclient.transfer; import com.sevenbridges.apiclient.file.File; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * This object allows user to take control of upload submitted to internal transfer manager via the * {@link com.sevenbridges.apiclient.user.UserActions#submitUpload(com.sevenbridges.apiclient.upload.CreateUploadRequest)} * calls. */ public interface UploadContext { /** * <b>BLOCKING CALL</b> * <p> * This is a blocking call, similar to invoking get on a {@link java.util.concurrent.Future} * instance. Current thread will block until the file is fully uploaded to the Seven Bridges * Platform, or until some exception happen. If the thread is interrupted from sleep, a runtime * exception wrapping the interrupted exception will be thrown. If some other thread aborts, or * pauses the upload, another runtime exception will be called, and will wake up the current * sleeping thread. * <p> * If the upload is completed successfully this call will return the {@link File} resource * instance that is uploaded. * * @return File 'file' resource that is uploaded * @throws PausedUploadException if the current upload the thread is blocked on is paused by * {@link #pauseTransfer()} call by some other thread */ File getFile() throws PausedUploadException; /** * <b>BLOCKING CALL</b> * <p> * This is a timed blocking call, similar to invoking get(timeValue, timeUnit) on a {@link * java.util.concurrent.Future} instance. Current thread will wait specified time until the file * is fully uploaded to the Seven Bridges Platform, or until some exception happen. If the thread * is interrupted from sleep, a runtime exception wrapping the interrupted exception will be * thrown. If some other thread aborts, or pauses the upload, another runtime exception will be * called, and will wake up the current sleeping thread. * <p> * If the upload is completed successfully this call will return the {@link File} resource * instance that is uploaded. * * @param timeValue the maximum number of TimeUnits to wait * @param timeUnit durations of one unit of timeValue * @return File 'file' resource that is uploaded * @throws TimeoutException if the wait time times out, and the upload is still not * completed * @throws PausedUploadException if the current upload the thread is blocked on is paused by * {@link #pauseTransfer()} call by some other thread */ File getFile(long timeValue, TimeUnit timeUnit) throws TimeoutException, PausedUploadException; /** * Checks if the current {@link com.sevenbridges.apiclient.upload.Upload}, managed by this * UploadContext is finished successfully. * * @return Boolean indicator is upload finished */ boolean isFinished(); /** * Aborts the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext. Any * thread blocked on the getFile() call on this uploadContext will be woken up by the * RuntimeException. Upload is aborted totally, and any progress on this upload will be lost. */ void abortTransfer(); /** * Gets the current state of the upload managed by this UploadContext. * * @return UploadState current state */ UploadState getState(); /** * Pauses the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext. Any * thread blocked on the getFile() call on this uploadContext will be woken up by the * RuntimeException that indicates that the upload is paused. Paused upload is not aborted on the * Platform, and your progress (measured in file parts) is saved. * <p> * You can use this UploadContext object to resume upload via {@link * com.sevenbridges.apiclient.user.UserActions#resumeUpload(UploadContext, java.io.File)} call. * That call will provide a new instance of UploadContext, this one is useless after that call. * <p> * Pause action is not instantaneous, the call is not blocking, and it will put upload in the * PAUSING state. After the first running part upload is finished, the upload state will change to * PAUSED state. */ void pauseTransfer(); /** * Gets summed number of bytes transferred by the {@link com.sevenbridges.apiclient.upload.Upload} * managed by this UploadContext. This is a pretty low level byte counter, and it will update much * more often than the part upload finished event. * * @return Current bytes transferred for this upload */ long getBytesTransferred(); /** * Size of the whole upload in bytes. * * @return long upload size */ long getUploadSize(); /** * Name of the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext. * * @return String upload name */ String getUploadName(); /** * ID of the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext. * * @return String ID of the upload managed by this upload context */ String getUploadId(); }
sbg/sevenbridges-java
api/src/main/java/com/sevenbridges/apiclient/transfer/UploadContext.java
Java
apache-2.0
5,821
package test_JLabel; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import javax.swing.JFrame; import javax.swing.JLabel; public class JLabel02 { public static void main(String args[]){ JFrame fra = new JFrame("Swing ´°Ìå±êÌâ"); JLabel lab = new JLabel("ÏĹâǬ"+"Èí¼þ¹¤³Ì",JLabel.CENTER); //×ÖÌå Font fon = new Font("Serief",Font.BOLD+Font.ITALIC,37); lab.setFont(fon); lab.setForeground(Color.RED); //ÈÝÆ÷ Container con = fra.getContentPane(); con.add(lab); Dimension dim = new Dimension(); dim.setSize(700, 400); fra.setSize(dim); fra.setBackground(Color.GREEN);//Where my Background Color? Point poi = new Point(); poi.setLocation(300, 90); fra.setLocation(poi); fra.setVisible(true); } }
xgqfrms/JavaWeb
JavaGUI/src/test_JLabel/JLabel02.java
Java
apache-2.0
810
require 'spec_helper' describe Arachni::Element::Capabilities::Auditable::Taint do before :all do Arachni::Options.url = @url = web_server_url_for( :taint ) @auditor = Auditor.new( nil, Arachni::Framework.new ) @positive = Arachni::Element::Link.new( @url, 'input' => '' ) @positive.auditor = @auditor @positive.auditor.page = Arachni::Page.from_url( @url ) @negative = Arachni::Element::Link.new( @url, 'inexistent_input' => '' ) @negative.auditor = @auditor @negative.auditor.page = Arachni::Page.from_url( @url ) end describe '.taint' do before do @seed = 'my_seed' Arachni::Framework.reset end context 'when the element action matches a skip rule' do it 'returns false' do auditable = Arachni::Element::Link.new( 'http://stuff.com/', { 'input' => '' } ) auditable.taint_analysis( @seed ).should be_false end end context 'when called with no opts' do it 'uses the defaults' do @positive.taint_analysis( @seed ) @auditor.http.run issues.size.should == 1 end end context 'when the payloads are per platform' do it 'assigns the platform of the payload to the issue' do payloads = { windows: 'blah', php: @seed, } @positive.taint_analysis( payloads, substring: @seed ) @auditor.http.run issues.size.should == 1 issue = issues.first issue.platform.should == :php issue.platform_type.should == :languages end end context 'when called against non-vulnerable input' do it 'does not log an issue' do @negative.taint_analysis( @seed ) @auditor.http.run issues.should be_empty end end context 'when called with option' do describe :regexp do context String do it 'tries to match the provided pattern' do @positive.taint_analysis( @seed, regexp: @seed, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues.first.injected.should == @seed issues.first.verification.should be_false end end context Array do it 'tries to match the provided patterns' do @positive.taint_analysis( @seed, regexp: [@seed], format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues.first.injected.should == @seed issues.first.verification.should be_false end end context Hash do it 'assigns the relevant platform to the issue' do regexps = { windows: /#{@seed} w.*/, php: /#{@seed} p.*/, } @positive.taint_analysis( "#{@seed} windows", regexp: regexps.dup, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues[0].platform.should == :windows issues[0].regexp.should == regexps[:windows].to_s issues[0].verification.should be_false end context 'when the payloads are per platform' do it 'only tries to matches the regexps for that platform' do issues = [] Arachni::Module::Manager.on_register_results_raw do |results| issues += results end payloads = { windows: "#{@seed} windows", php: "#{@seed} php", asp: "#{@seed} asp" } regexps = { windows: /#{@seed} w.*/, php: /#{@seed} p.*/, # Can match all but should only match # against responses of the ASP payload. asp: /#{@seed}/ } @positive.taint_analysis( payloads.dup, regexp: regexps.dup, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 3 payloads.keys.each do |platform| issue = issues.find{ |i| i.platform == platform } issue.injected.should == payloads[platform] issue.platform.should == platform issue.regexp.should == regexps[platform].to_s issue.verification.should be_false end end context 'when there is not a payload for the regexp platform' do it 'matches against all payload responses and assigns the pattern platform to the issue' do payloads = { windows: "#{@seed} windows", php: "#{@seed} php", } regexps = { # Can match all but should only match # against responses of the ASP payload. asp: /#{@seed}/ } @positive.taint_analysis( payloads.dup, regexp: regexps.dup, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issue = issues.first issue.platform.should == :asp issue.regexp.should == regexps[:asp].to_s issue.verification.should be_false end end end end context 'with valid :match' do it 'verifies the matched data with the provided string' do @positive.taint_analysis( @seed, regexp: /my_.+d/, match: @seed, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues.first.injected.should == @seed issues.first.verification.should be_false end end context 'with invalid :match' do it 'does not log an issue' do @positive.taint_analysis( @seed, regexp: @seed, match: 'blah', format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.should be_empty end end context 'when the page matches the regexp even before we audit it' do it 'flags the issue as requiring manual verification' do seed = 'Inject here' @positive.taint_analysis( 'Inject here', regexp: 'Inject he[er]', format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issue = issues.first issue.injected.should == seed issue.verification.should be_true issue.remarks[:auditor].should be_any end it 'adds a remark' do seed = 'Inject here' @positive.taint_analysis( 'Inject here', regexp: 'Inject he[er]', format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issue = issues.first issue.injected.should == seed issue.verification.should be_true issue.remarks[:auditor].should be_any end end end describe :substring do context String do it 'tries to match the provided pattern' do @positive.taint_analysis( @seed, substring: @seed, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues.first.injected.should == @seed issues.first.verification.should be_false end end context Array do it 'tries to match the provided patterns' do @positive.taint_analysis( @seed, substring: [@seed], format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues.first.injected.should == @seed issues.first.verification.should be_false end end context Hash do it 'assigns the relevant platform to the issue' do substrings = { windows: "#{@seed} w", php: "#{@seed} p", } @positive.taint_analysis( "#{@seed} windows", substring: substrings.dup, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issues[0].platform.should == :windows issues[0].regexp.should == substrings[:windows].to_s issues[0].verification.should be_false end context 'when the payloads are per platform' do it 'only tries to matches the regexps for that platform' do issues = [] Arachni::Module::Manager.on_register_results_raw do |results| issues += results end payloads = { windows: "#{@seed} windows", php: "#{@seed} php", asp: "#{@seed} asp" } substrings = { windows: "#{@seed} w", php: "#{@seed} p", # Can match all but should only match # against responses of the ASP payload. asp: @seed } @positive.taint_analysis( payloads.dup, substring: substrings.dup, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 3 payloads.keys.each do |platform| issue = issues.find{ |i| i.platform == platform } issue.injected.should == payloads[platform] issue.platform.should == platform issue.regexp.should == substrings[platform].to_s issue.verification.should be_false end end end end context 'when the page includes the substring even before we audit it' do it 'flags the issue as requiring manual verification' do seed = 'Inject here' @positive.taint_analysis( 'Inject here', regexp: 'Inject here', format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issue = issues.first issue.injected.should == seed issue.verification.should be_true issue.remarks[:auditor].should be_any end context 'when there is not a payload for the substring platform' do it 'matches against all payload responses and assigns the pattern platform to the issue' do payloads = { windows: "#{@seed} windows", php: "#{@seed} php", } substrings = { # Can match all but should only match # against responses of the ASP payload. asp: @seed } @positive.taint_analysis( payloads.dup, substring: substrings.dup, format: [ Arachni::Module::Auditor::Format::STRAIGHT ] ) @auditor.http.run issues.size.should == 1 issue = issues.first issue.platform.should == :asp issue.regexp.should == substrings[:asp].to_s issue.verification.should be_false end end end end describe :ignore do it 'ignores matches whose response also matches the ignore patterns' do @positive.taint_analysis( @seed, substring: @seed, format: [ Arachni::Module::Auditor::Format::STRAIGHT ], ignore: @seed ) @auditor.http.run issues.should be_empty end end end end end
0x0mar/arachni
spec/arachni/element/capabilities/auditable/taint_spec.rb
Ruby
apache-2.0
16,875
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP # # 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. require_relative '../c7000/volume_template' module OneviewSDK module API2400 module Synergy # Volume Template resource implementation for API2400 Synergy class VolumeTemplate < OneviewSDK::API2400::C7000::VolumeTemplate end end end end
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource/api2400/synergy/volume_template.rb
Ruby
apache-2.0
867
namespace VitalFew.Transdev.Australasia.Data.Api.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
VitalFew/Transdev
VitalFew.Transdev.Australasia.Data.Api/VitalFew.Transdev.Australasia.Data.Api/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
C#
apache-2.0
172
// Copyright 2015, Cyrill @ Schumacher.fm and the CoreStore contributors // // 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 config import "github.com/corestoreio/csfw/utils" // ScopePerm is a bit set and used for permissions, ScopeGroup is not a part of this bit set. // Type ScopeGroup is a subpart of ScopePerm type ScopePerm uint64 // ScopePermAll convenient helper variable contains all scope permission levels var ScopePermAll = ScopePerm(1<<ScopeDefaultID | 1<<ScopeWebsiteID | 1<<ScopeStoreID) // NewScopePerm returns a new permission container func NewScopePerm(scopes ...ScopeGroup) ScopePerm { p := ScopePerm(0) p.Set(scopes...) return p } // All applies all scopes func (bits *ScopePerm) All() ScopePerm { bits.Set(ScopeDefaultID, ScopeWebsiteID, ScopeStoreID) return *bits } // Set takes a variadic amount of ScopeGroup to set them to ScopeBits func (bits *ScopePerm) Set(scopes ...ScopeGroup) ScopePerm { for _, i := range scopes { *bits = *bits | (1 << i) // (1 << power = 2^power) } return *bits } // Has checks if ScopeGroup is in ScopeBits func (bits ScopePerm) Has(s ScopeGroup) bool { var one ScopeGroup = 1 // ^^ return (bits & ScopePerm(one<<s)) != 0 } // Human readable representation of the permissions func (bits ScopePerm) Human() utils.StringSlice { var ret utils.StringSlice var i uint for i = 0; i < 64; i++ { bit := ((bits & (1 << i)) != 0) if bit { ret.Append(ScopeGroup(i).String()) } } return ret } // MarshalJSON implements marshaling into an array or null if no bits are set. @todo UnMarshal func (bits ScopePerm) MarshalJSON() ([]byte, error) { if bits == 0 { return []byte("null"), nil } return []byte(`["` + bits.Human().Join(`","`) + `"]`), nil }
bom-d-van/csfw
config/scopeperm.go
GO
apache-2.0
2,241
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor import datetime import socket import time import sys import os.path lib_path = os.path.abspath('../utils') sys.path.append(lib_path) from myParser import * from myCrypto import * #from myDriver import * #from myCamDriver import * import re import hashlib #from PIL import Image #host='connect.mysensors.info' host='localhost' port=9090 state="INITIAL" device="" server="mysensors" class mySensorDatagramProtocol(DatagramProtocol): def __init__(self, host,port,reactor): self.ip= socket.gethostbyname(host) self.port = port #self._reactor=reactor #self.ip=reactor.resolve(host) def startProtocol(self): self.transport.connect(self.ip,self.port) if state=='INITIAL': #If system is at the initial state, it will send the device creation Senze self.register() else: response=raw_input("Enter your Senze:") self.sendDatagram(response) def stopProtocol(self): #on disconnect #self._reactor.listenUDP(0, self) print "STOP **************" def register(self): global server cry=myCrypto(name=device) senze ='SHARE #pubkey %s @%s' %(pubkey,server) senze=cry.signSENZE(senze) self.transport.write(senze) def sendDatagram(self,senze): global server cry=myCrypto(name=device) senze=cry.signSENZE(senze) print senze self.transport.write(senze) def datagramReceived(self, datagram, host): print 'Datagram received: ', repr(datagram) parser=myParser(datagram) recipients=parser.getUsers() sender=parser.getSender() signature=parser.getSignature() data=parser.getData() sensors=parser.getSensors() cmd=parser.getCmd() if cmd=="DATA": if 'UserCreated' in data['msg']: #Creating the .devicename file and store the device name and PIN f=open(".devicename",'w') f.write(device+'\n') f.close() print device+ " was created at the server." print "You should execute the program again." print "The system halted!" reactor.stop() elif 'UserCreationFailed' in data['msg']: print "This user name may be already taken" print "You can try it again with different username" print "The system halted!" reactor.stop() #self.sendDatagram() def init(): #cam=myCamDriver() global device global pubkey global state #If .device name is not there, we will read the device name from keyboard #else we will get it from .devicename file try: if not os.path.isfile(".devicename"): device=raw_input("Enter the device name: ") # Account need to be created at the server state='INITIAL' else: #The device name will be read form the .devicename file f=open(".devicename","r") device = f.readline().rstrip("\n") state='READY' except: print "ERRER: Cannot access the device name file." raise SystemExit #Here we will generate public and private keys for the device #These keys will be used to perform authentication and key exchange try: cry=myCrypto(name=device) #If keys are not available yet if not os.path.isfile(cry.pubKeyLoc): # Generate or loads an RSA keypair with an exponent of 65537 in PEM format # Private key and public key was saved in the .devicenamePriveKey and .devicenamePubKey files cry.generateRSA(bits=1024) pubkey=cry.loadRSAPubKey() except: print "ERRER: Cannot genereate private/public keys for the device." raise SystemExit print pubkey #Check the network connectivity. #check_connectivity(ServerName) def main(): global host global port protocol = mySensorDatagramProtocol(host,port,reactor) reactor.listenUDP(0, protocol) reactor.run() if __name__ == '__main__': init() main()
kasundezoysa/senze
testpi/myDevice.py
Python
apache-2.0
4,355
package com.nvapp.android.libs.view; public interface TitleProvider { /** * Returns the title of the view at position * * @param position * @return */ public String getTitle(int position); }
nvapp/nv-android-libs
src/com/nvapp/android/libs/view/TitleProvider.java
Java
apache-2.0
205
package com.fifino.patterns.strategy; /** * Created by porfiriopartida on 2/13/16. */ public class ItFlys implements Flys { @Override public String fly() { return "Flying high!"; } }
ppartida/jdesign-patterns
src/com/fifino/patterns/strategy/ItFlys.java
Java
apache-2.0
206
/* * 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.google.devtools.j2objc.translate; import com.google.common.collect.Lists; import com.google.devtools.j2objc.ast.CastExpression; import com.google.devtools.j2objc.ast.Expression; import com.google.devtools.j2objc.ast.ExpressionStatement; import com.google.devtools.j2objc.ast.FieldAccess; import com.google.devtools.j2objc.ast.FunctionInvocation; import com.google.devtools.j2objc.ast.MethodDeclaration; import com.google.devtools.j2objc.ast.MethodInvocation; import com.google.devtools.j2objc.ast.ParenthesizedExpression; import com.google.devtools.j2objc.ast.QualifiedName; import com.google.devtools.j2objc.ast.ReturnStatement; import com.google.devtools.j2objc.ast.SimpleName; import com.google.devtools.j2objc.ast.SuperMethodInvocation; import com.google.devtools.j2objc.ast.TreeUtil; import com.google.devtools.j2objc.ast.TreeVisitor; import com.google.devtools.j2objc.ast.VariableDeclarationFragment; import com.google.devtools.j2objc.types.IOSMethodBinding; import com.google.devtools.j2objc.types.Types; import com.google.devtools.j2objc.util.BindingUtil; import com.google.devtools.j2objc.util.NameTable; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Modifier; import java.util.Arrays; import java.util.List; /** * Adds cast checks to existing java cast expressions. * Adds casts as needed for Objective-C compilation. Usually this occurs when a * method has a declared return type that is more generic than the resolved type * of the expression. */ public class CastResolver extends TreeVisitor { @Override public void endVisit(CastExpression node) { ITypeBinding type = node.getType().getTypeBinding(); Expression expr = node.getExpression(); ITypeBinding exprType = expr.getTypeBinding(); if (Types.isFloatingPointType(exprType)) { if (Types.isLongType(type)) { FunctionInvocation invocation = new FunctionInvocation("J2ObjCFpToLong", type, type, null); invocation.getArguments().add(TreeUtil.remove(expr)); node.replaceWith(invocation); return; } else if (type.isEqualTo(Types.resolveJavaType("char"))) { FunctionInvocation invocation = new FunctionInvocation("J2ObjCFpToUnichar", type, type, null); invocation.getArguments().add(TreeUtil.remove(expr)); node.replaceWith(invocation); return; } else if (Types.isIntegralType(type)) { ITypeBinding intType = Types.resolveJavaType("int"); FunctionInvocation invocation = new FunctionInvocation("J2ObjCFpToInt", intType, intType, null); invocation.getArguments().add(TreeUtil.remove(expr)); Expression newExpr = invocation; if (!type.isEqualTo(intType)) { newExpr = new CastExpression(type, newExpr); } node.replaceWith(newExpr); return; } // else fall-through. } // Lean on Java's type-checking. if (!type.isPrimitive() && exprType.isAssignmentCompatible(type)) { node.replaceWith(TreeUtil.remove(expr)); return; } FunctionInvocation castCheck = createCastCheck(type, expr); if (castCheck != null) { node.setExpression(castCheck); } } private static FunctionInvocation createCastCheck(ITypeBinding type, Expression expr) { // Find the first bound for a type variable. while (type.isTypeVariable()) { ITypeBinding[] bounds = type.getTypeBounds(); if (bounds.length == 0) { break; } type = bounds[0]; } ITypeBinding idType = Types.resolveIOSType("id"); FunctionInvocation invocation = null; if (type.isInterface() && !type.isAnnotation()) { invocation = new FunctionInvocation("check_protocol_cast", idType, idType, null); invocation.getArguments().add(TreeUtil.remove(expr)); FunctionInvocation protocolLiteral = new FunctionInvocation("@protocol", idType, idType, null); protocolLiteral.getArguments().add(new SimpleName(type)); invocation.getArguments().add(protocolLiteral); } else if (type.isClass() || type.isArray() || type.isAnnotation() || type.isEnum()) { invocation = new FunctionInvocation("check_class_cast", idType, idType, null); invocation.getArguments().add(TreeUtil.remove(expr)); IOSMethodBinding binding = IOSMethodBinding.newMethod("class", Modifier.STATIC, idType, type); MethodInvocation classInvocation = new MethodInvocation(binding, new SimpleName(type)); invocation.getArguments().add(classInvocation); } return invocation; } private void addCast(Expression expr) { ITypeBinding exprType = Types.mapType(expr.getTypeBinding().getTypeDeclaration()); CastExpression castExpr = new CastExpression(exprType, null); expr.replaceWith(ParenthesizedExpression.parenthesize(castExpr)); castExpr.setExpression(expr); } private void maybeAddCast(Expression expr, boolean shouldCastFromId) { if (needsCast(expr, shouldCastFromId)) { addCast(expr); } } private boolean needsCast(Expression expr, boolean shouldCastFromId) { ITypeBinding declaredType = getDeclaredType(expr); if (declaredType == null) { return false; } ITypeBinding exprType = Types.mapType(expr.getTypeBinding().getTypeDeclaration()); declaredType = Types.mapType(declaredType.getTypeDeclaration()); if (declaredType.isAssignmentCompatible(exprType)) { return false; } if (declaredType == Types.resolveIOSType("id") && !shouldCastFromId) { return false; } if (exprType.isPrimitive() || Types.isVoidType(exprType)) { return false; } String typeName = NameTable.getSpecificObjCType(exprType); if (typeName.equals(NameTable.ID_TYPE)) { return false; } return true; } private ITypeBinding getDeclaredType(Expression expr) { IVariableBinding var = TreeUtil.getVariableBinding(expr); if (var != null) { return var.getVariableDeclaration().getType(); } switch (expr.getKind()) { case CLASS_INSTANCE_CREATION: return Types.resolveIOSType("id"); case FUNCTION_INVOCATION: return ((FunctionInvocation) expr).getDeclaredReturnType(); case METHOD_INVOCATION: { MethodInvocation invocation = (MethodInvocation) expr; IMethodBinding method = invocation.getMethodBinding(); // Object receiving the message, or null if it's a method in this class. Expression receiver = invocation.getExpression(); ITypeBinding receiverType = receiver != null ? receiver.getTypeBinding() : method.getDeclaringClass(); return getDeclaredReturnType(method, receiverType); } case SUPER_METHOD_INVOCATION: { SuperMethodInvocation invocation = (SuperMethodInvocation) expr; IMethodBinding method = invocation.getMethodBinding(); if (invocation.getQualifier() != null) { // For a qualified super invocation, the statement generator will look // up the IMP using instanceMethodForSelector. if (!method.getReturnType().isPrimitive()) { return Types.resolveIOSType("id"); } else { return null; } } return getDeclaredReturnType( method, TreeUtil.getOwningType(invocation).getTypeBinding().getSuperclass()); } default: return null; } } private static ITypeBinding getDeclaredReturnType( IMethodBinding method, ITypeBinding receiverType) { IMethodBinding actualDeclaration = getFirstDeclaration(getObjCMethodSignature(method), receiverType); if (actualDeclaration == null) { actualDeclaration = method.getMethodDeclaration(); } ITypeBinding returnType = actualDeclaration.getReturnType(); if (returnType.isTypeVariable()) { return Types.resolveIOSType("id"); } return returnType.getErasure(); } /** * Finds the declaration for a given method and receiver in the same way that * the ObjC compiler will search for a declaration. */ private static IMethodBinding getFirstDeclaration(String methodSig, ITypeBinding type) { if (type == null) { return null; } type = type.getTypeDeclaration(); for (IMethodBinding declaredMethod : type.getDeclaredMethods()) { if (methodSig.equals(getObjCMethodSignature(declaredMethod))) { return declaredMethod; } } List<ITypeBinding> supertypes = Lists.newArrayList(); supertypes.addAll(Arrays.asList(type.getInterfaces())); supertypes.add(type.isTypeVariable() ? 0 : supertypes.size(), type.getSuperclass()); for (ITypeBinding supertype : supertypes) { IMethodBinding result = getFirstDeclaration(methodSig, supertype); if (result != null) { return result; } } return null; } private static String getObjCMethodSignature(IMethodBinding method) { StringBuilder sb = new StringBuilder(method.getName()); boolean first = true; for (ITypeBinding paramType : method.getParameterTypes()) { String keyword = NameTable.parameterKeyword(paramType); if (first) { first = false; keyword = NameTable.capitalize(keyword); } sb.append(keyword + ":"); } return sb.toString(); } // Some native objective-c methods are declared to return NSUInteger. private boolean returnValueNeedsIntCast(Expression arg) { IMethodBinding methodBinding = TreeUtil.getMethodBinding(arg); assert methodBinding != null; if (arg.getParent() instanceof ExpressionStatement) { // Avoid "unused return value" warning. return false; } String methodName = NameTable.getMethodSelector(methodBinding); if (methodName.equals("hash") && methodBinding.getReturnType().isEqualTo(Types.resolveJavaType("int"))) { return true; } if (Types.isStringType(methodBinding.getDeclaringClass()) && methodName.equals("length")) { return true; } return false; } @Override public void endVisit(FieldAccess node) { maybeAddCast(node.getExpression(), true); } @Override public void endVisit(MethodInvocation node) { Expression receiver = node.getExpression(); if (receiver != null && !BindingUtil.isStatic(node.getMethodBinding())) { maybeAddCast(receiver, true); } if (returnValueNeedsIntCast(node)) { addCast(node); } } @Override public void endVisit(QualifiedName node) { if (needsCast(node.getQualifier(), true)) { maybeAddCast(TreeUtil.convertToFieldAccess(node).getExpression(), true); } } @Override public void endVisit(ReturnStatement node) { Expression expr = node.getExpression(); if (expr != null) { maybeAddCast(expr, false); } } @Override public void endVisit(SuperMethodInvocation node) { if (returnValueNeedsIntCast(node)) { addCast(node); } } @Override public void endVisit(VariableDeclarationFragment node) { Expression initializer = node.getInitializer(); if (initializer != null) { maybeAddCast(initializer, false); } } /** * Adds a cast check to compareTo methods. This helps Comparable types behave * well in sorted collections which rely on Java's runtime type checking. */ @Override public void endVisit(MethodDeclaration node) { IMethodBinding binding = node.getMethodBinding(); if (!binding.getName().equals("compareTo") || node.getBody() == null) { return; } ITypeBinding comparableType = BindingUtil.findInterface(binding.getDeclaringClass(), "java.lang.Comparable"); if (comparableType == null) { return; } ITypeBinding[] typeArguments = comparableType.getTypeArguments(); ITypeBinding[] parameterTypes = binding.getParameterTypes(); if (typeArguments.length != 1 || parameterTypes.length != 1 || !typeArguments[0].isEqualTo(parameterTypes[0])) { return; } IVariableBinding param = node.getParameters().get(0).getVariableBinding(); FunctionInvocation castCheck = createCastCheck(typeArguments[0], new SimpleName(param)); if (castCheck != null) { node.getBody().getStatements().add(0, new ExpressionStatement(castCheck)); } } }
hambroperks/j2objc
translator/src/main/java/com/google/devtools/j2objc/translate/CastResolver.java
Java
apache-2.0
12,986
package textures; public class TerrainTexturePack { private TerrainTexture backgroundTexture; private TerrainTexture rTexture; private TerrainTexture gTexture; private TerrainTexture bTexture; public TerrainTexture getBackgroundTexture() { return backgroundTexture; } public void setBackgroundTexture(TerrainTexture backgroundTexture) { this.backgroundTexture = backgroundTexture; } public TerrainTexturePack(TerrainTexture backgroundTexture, TerrainTexture rTexture, TerrainTexture gTexture, TerrainTexture bTexture) { super(); this.backgroundTexture = backgroundTexture; this.rTexture = rTexture; this.gTexture = gTexture; this.bTexture = bTexture; } public TerrainTexture getrTexture() { return rTexture; } public void setrTexture(TerrainTexture rTexture) { this.rTexture = rTexture; } public TerrainTexture getgTexture() { return gTexture; } public void setgTexture(TerrainTexture gTexture) { this.gTexture = gTexture; } public TerrainTexture getbTexture() { return bTexture; } public void setbTexture(TerrainTexture bTexture) { this.bTexture = bTexture; } }
fillipesouza/mygame
src/textures/TerrainTexturePack.java
Java
apache-2.0
1,125
package com.zst.xposed.halo.floatingwindow3.prefs; import android.app.*; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.*; import android.os.*; import com.zst.xposed.halo.floatingwindow3.*; import java.util.prefs.*; import android.widget.*; import android.graphics.*; public class FloatDotActivity extends Activity implements OnSharedPreferenceChangeListener { SharedPreferences mPref; //Context mContext; int[] mColors = new int[4]; int mCircleDiameter; ImageView snapDragger; ImageView floatLauncher; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_floatdot); snapDragger = (ImageView) findViewById(R.id.snapDragger); floatLauncher = (ImageView) findViewById(R.id.floatingLauncher); mPref = getSharedPreferences(Common.PREFERENCE_MAIN_FILE, MODE_WORLD_READABLE); updatePrefs(); // getFragmentManager().beginTransaction().replace(R.id.floatDotPrefs, // new FloatDotFragment()).commit(); } private void updatePrefs(){ loadColors(); mCircleDiameter=mPref.getInt(Common.KEY_FLOATDOT_SIZE, Common.DEFAULT_FLOATDOT_SIZE); snapDragger.setImageDrawable(Util.makeDoubleCircle(mColors[0], mColors[1], Util.realDp(mCircleDiameter, getApplicationContext()), Util.realDp(mCircleDiameter/4, getApplicationContext()))); floatLauncher.setImageDrawable(Util.makeDoubleCircle(mColors[2], mColors[3], Util.realDp(mCircleDiameter, getApplicationContext()), Util.realDp(mCircleDiameter/4, getApplicationContext()))); } private void loadColors(){ mColors[0] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER1, Common.DEFAULT_FLOATDOT_COLOR_OUTER1)); if(mPref.getBoolean(Common.KEY_FLOATDOT_SINGLE_COLOR_SNAP, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_SNAP)) mColors[1] = mColors[0]; else mColors[1] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER1, Common.DEFAULT_FLOATDOT_COLOR_INNER1)); mColors[2] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER2, Common.DEFAULT_FLOATDOT_COLOR_OUTER2)); if(mPref.getBoolean(Common.KEY_FLOATDOT_SINGLE_COLOR_LAUNCHER, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_LAUNCHER)) mColors[3] = mColors[2]; else mColors[3] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER2, Common.DEFAULT_FLOATDOT_COLOR_INNER2)); } private void sendRefreshCommand(String key){ int item = 0; int size = 0; float alpha = 0; String mColor = null; if(key.equals(Common.KEY_FLOATDOT_COLOR_OUTER1)) item=0; else if(key.equals(Common.KEY_FLOATDOT_COLOR_INNER1)) item=1; else if(key.equals(Common.KEY_FLOATDOT_COLOR_OUTER2)) item=2; else if(key.equals(Common.KEY_FLOATDOT_COLOR_INNER2)) item=3; else if(key.equals(Common.KEY_FLOATDOT_SINGLE_COLOR_SNAP)){ item = 1; if(mPref.getBoolean(key, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_SNAP)) mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER1, Common.DEFAULT_FLOATDOT_COLOR_OUTER1); else mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER1, Common.KEY_FLOATDOT_COLOR_INNER1); } else if(key.equals(Common.KEY_FLOATDOT_SINGLE_COLOR_LAUNCHER)){ item = 3; if(mPref.getBoolean(key, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_LAUNCHER)) mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER2, Common.DEFAULT_FLOATDOT_COLOR_OUTER2); else mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER2, Common.KEY_FLOATDOT_COLOR_INNER2); } else if(key.equals(Common.KEY_FLOATDOT_SIZE)){ size = mPref.getInt(key, Common.DEFAULT_FLOATDOT_SIZE); } else if(key.equals(Common.KEY_FLOATDOT_ALPHA)){ alpha = mPref.getFloat(key, Common.DEFAULT_FLOATDOT_ALPHA); } else return; if(mColor==null && size==0 && alpha == 0) mColor = mPref.getString(key, null); Intent mIntent = new Intent(Common.UPDATE_FLOATDOT_PARAMS); mIntent.putExtra("color", mColor); mIntent.putExtra("size", size); mIntent.putExtra("alpha", alpha); mIntent.putExtra("item", item); mIntent.setPackage(Common.THIS_MOD_PACKAGE_NAME); getApplicationContext().sendBroadcast(mIntent); } private void enableFloatDotLauncher(boolean enable){ Intent mIntent = new Intent(Common.UPDATE_FLOATDOT_PARAMS); mIntent.putExtra(Common.KEY_FLOATDOT_LAUNCHER_ENABLED, enable); mIntent.setPackage(Common.THIS_MOD_PACKAGE_NAME); getApplicationContext().sendBroadcast(mIntent); } @Override public void onSharedPreferenceChanged(SharedPreferences p1, String key) { updatePrefs(); if(key.equals(Common.KEY_FLOATDOT_LAUNCHER_ENABLED)){ enableFloatDotLauncher(mPref.getBoolean(key, Common.DEFAULT_FLOATDOT_LAUNCHER_ENABLED)); return; } sendRefreshCommand(key); } @Override protected void onResume() { super.onResume(); mPref.registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); mPref.unregisterOnSharedPreferenceChangeListener(this); } }
shooash/XHFW3
app/src/main/java/com/zst/xposed/halo/floatingwindow3/prefs/FloatDotActivity.java
Java
apache-2.0
5,002
package org.nutz.resource; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.Servlet; import junit.extensions.ActiveTestSuite; import junit.extensions.RepeatedTest; import junit.extensions.TestSetup; import junit.framework.Assert; import org.junit.Test; import org.nutz.lang.Files; import org.nutz.lang.Strings; public class ScansTest { @Test public void test_loadResource() throws IOException { String RNAME = "junit/runner/Version.class"; List<NutResource> nrs = Scans.me().loadResource(".*.class", RNAME); assertEquals(1, nrs.size()); NutResource nr = nrs.get(0); assertTrue(nr.getName().indexOf(RNAME) >= 0); InputStream ins = nr.getInputStream(); int len = 0; while (-1 != ins.read()) { len++; } ins.close(); assertTrue(len > 600); } @Test public void test_in_normal_file() throws IOException { String testPath = "~/nutz/unit/rs/test"; File testDir = Files.createDirIfNoExists(testPath); Files.clearDir(testDir); List<NutResource> list = Scans.me().scan(testPath, ".*"); assertEquals(0, list.size()); Files.createDirIfNoExists(testPath + "/a/b/c"); list = Scans.me().scan(testPath, ".*"); assertEquals(0, list.size()); Files.createFileIfNoExists(testPath + "/a/b/c/l.txt"); Files.createFileIfNoExists(testPath + "/a/b/c/m.doc"); Files.createFileIfNoExists(testPath + "/a/b/c/n.jpg"); Files.createFileIfNoExists(testPath + "/a/b/c/o.jpg"); list = Scans.me().scan(testPath, ".*"); assertEquals(4, list.size()); list = Scans.me().scan(testPath, null); assertEquals(4, list.size()); list = Scans.me().scan(testPath, ".+[.]jpg"); assertEquals(2, list.size()); list = Scans.me().scan(testPath, ".*[.]txt"); assertEquals(1, list.size()); Files.deleteDir(testDir); } @Test public void test_in_classpath() { String testPath = Scans.class.getName().replace('.', '/') + ".class"; String testFilter = "^" + Scans.class.getSimpleName() + ".class$"; List<NutResource> list = Scans.me().scan(testPath, testFilter); assertEquals(1, list.size()); } // @Ignore @Test public void test_in_jar() { String testPath = Assert.class.getPackage().getName().replace('.', '/'); String testFilter = "^.*(Assert|Test)\\.class$"; List<NutResource> list = Scans.me().scan(testPath, testFilter); //Collections.sort(list); assertEquals(2, list.size()); assertTrue(list.get(0).getName().endsWith("Test.class")); assertTrue(list.get(1).getName().endsWith("Assert.class")); } // @Ignore @Test public void test_classes_in_jar() { List<Class<?>> list = Scans.me() .scanPackage( ActiveTestSuite.class, ".*(ActiveTestSuite|RepeatedTest|TestSetup)\\.class$"); assertEquals(3, list.size()); Collections.sort(list, new Comparator<Class<?>>() { public int compare(Class<?> o1, Class<?> o2) { return o1.getSimpleName().compareTo(o2.getSimpleName()); } }); assertTrue(ActiveTestSuite.class == list.get(0)); assertTrue(RepeatedTest.class == list.get(1)); assertTrue(TestSetup.class == list.get(2)); } @Test public void test_classes_in_package_path() { List<Class<?>> list = Scans.me().scanPackage("org.nutz", "Strings.class"); assertEquals(1, list.size()); assertTrue(Strings.class == list.get(0)); } @Test public void test_scan_with_unexists_file() { List<NutResource> list = Scans.me().scan("org/nutz/lang/notExist.class", null); assertEquals(0, list.size()); } @Test public void test_class_in_jar() { String testPath = Test.class.getName().replace('.', '/') + ".class"; String testFilter = "^Test.class$"; List<NutResource> list = Scans.me().scan(testPath, testFilter); assertEquals(1, list.size()); } @Test public void test_path_in_jar() { String testPath = Test.class.getPackage().getName().replace('.', '/'); List<NutResource> list = Scans.me().scan(testPath, null); assertTrue(list.size() > 10); } @Test public void test_scan_root() { Scans.me().scan("", ".+\\.xml"); } @Test public void test_resource_jar() throws MalformedURLException { Scans.me().registerLocation(Servlet.class); Scans.me().registerLocation(getClass().getClassLoader().getResource("javax/servlet/Servlet.class")); } }
007slm/nutz
test/org/nutz/resource/ScansTest.java
Java
apache-2.0
5,137
package greatspacerace import ( "bufio" "fmt" "github.com/TSavo/go.firebase" "os" ) func init() { f, err := os.Open("firebase.secret") if err != nil { fmt.Printf("error opening firebase.secret: %v\n", err) } r := bufio.NewReader(f) url, e := Readln(r) if e != nil { panic(e) } secret, e := Readln(r) if e != nil { panic(e) } db = firebase.New(url, secret) } var db *firebase.FirebaseRoot; func Readln(r *bufio.Reader) (string, error) { var ( isPrefix bool = true err error = nil line, ln []byte ) for isPrefix && err == nil { line, isPrefix, err = r.ReadLine() ln = append(ln, line...) } return string(ln), err }
TSavo/FarlightRacing
database.go
GO
apache-2.0
699
define(['socket.io'], function() { var socket = io.connect('//' + window.document.location.host); return socket; })
pinittome/pinitto.me
public/js/socket.js
JavaScript
apache-2.0
124
using System; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; namespace WeatherConsole { public class WeatherService { private const string url = @"http://gardiner-weather.azurewebsites.net/api/forecast/"; //SA/Adelaide"; public Forecast GetForecast(string state, string locality) { string s; using (var client = new HttpClient()) { client.BaseAddress = new Uri(url); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { s = client.GetStringAsync(string.Format(@"{0}/{1}", state, locality)).Result; } catch (AggregateException e) { // We're avoiding using async/await to keep things simple. Unwrap AggregateException and return original exception instead throw e.InnerExceptions.First(); } } var serializer = JsonSerializer.Create(); var forecast = serializer.Deserialize<Forecast>(new JsonTextReader(new StringReader(s))); return forecast; } } }
flcdrg/WeatherConsole
WeatherConsole/WeatherService.cs
C#
apache-2.0
1,347
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.postgresql; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.connection.LocalNativeClientLocation; /** * PostgreServerHome */ public class PostgreServerHome extends LocalNativeClientLocation { private static final Log log = Log.getLog(PostgreServerHome.class); private String name; private String version; private String branding; private String dataDirectory; protected PostgreServerHome(String id, String path, String version, String branding, String dataDirectory) { super(id, path); this.name = branding == null ? id : branding; this.version = version; this.branding = branding; this.dataDirectory = dataDirectory; } @Override public String getDisplayName() { return name; } public String getProductName() { return branding; } public String getProductVersion() { return version; } public String getBranding() { return branding; } public String getDataDirectory() { return dataDirectory; } }
liuyuanyuan/dbeaver
plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/PostgreServerHome.java
Java
apache-2.0
1,764
/* * 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. */ package org.apache.nifi.web.controller; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.authorization.AccessDeniedException; import org.apache.nifi.authorization.AuthorizationResult; import org.apache.nifi.authorization.AuthorizationResult.Result; import org.apache.nifi.authorization.Authorizer; import org.apache.nifi.authorization.RequestAction; import org.apache.nifi.authorization.Resource; import org.apache.nifi.authorization.resource.Authorizable; import org.apache.nifi.authorization.resource.ResourceFactory; import org.apache.nifi.authorization.user.NiFiUser; import org.apache.nifi.authorization.user.NiFiUserUtils; import org.apache.nifi.bundle.Bundle; import org.apache.nifi.bundle.BundleCoordinate; import org.apache.nifi.cluster.protocol.NodeIdentifier; import org.apache.nifi.components.ConfigurableComponent; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.connectable.Connectable; import org.apache.nifi.connectable.Connection; import org.apache.nifi.connectable.Funnel; import org.apache.nifi.connectable.Port; import org.apache.nifi.controller.ContentAvailability; import org.apache.nifi.controller.ControllerService; import org.apache.nifi.controller.Counter; import org.apache.nifi.controller.FlowController; import org.apache.nifi.controller.ProcessorNode; import org.apache.nifi.controller.ReportingTaskNode; import org.apache.nifi.controller.ScheduledState; import org.apache.nifi.controller.Template; import org.apache.nifi.controller.label.Label; import org.apache.nifi.controller.queue.FlowFileQueue; import org.apache.nifi.controller.queue.QueueSize; import org.apache.nifi.controller.repository.ContentNotFoundException; import org.apache.nifi.controller.repository.claim.ContentDirection; import org.apache.nifi.controller.service.ControllerServiceNode; import org.apache.nifi.controller.service.ControllerServiceProvider; import org.apache.nifi.controller.status.ConnectionStatus; import org.apache.nifi.controller.status.PortStatus; import org.apache.nifi.controller.status.ProcessGroupStatus; import org.apache.nifi.controller.status.ProcessorStatus; import org.apache.nifi.controller.status.RemoteProcessGroupStatus; import org.apache.nifi.controller.status.history.ComponentStatusRepository; import org.apache.nifi.diagnostics.SystemDiagnostics; import org.apache.nifi.flowfile.FlowFilePrioritizer; import org.apache.nifi.flowfile.attributes.CoreAttributes; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.groups.ProcessGroupCounts; import org.apache.nifi.groups.RemoteProcessGroup; import org.apache.nifi.nar.ExtensionManager; import org.apache.nifi.nar.NarCloseable; import org.apache.nifi.processor.DataUnit; import org.apache.nifi.processor.Processor; import org.apache.nifi.processor.Relationship; import org.apache.nifi.provenance.ProvenanceEventRecord; import org.apache.nifi.provenance.ProvenanceRepository; import org.apache.nifi.provenance.SearchableFields; import org.apache.nifi.provenance.lineage.ComputeLineageSubmission; import org.apache.nifi.provenance.search.Query; import org.apache.nifi.provenance.search.QueryResult; import org.apache.nifi.provenance.search.QuerySubmission; import org.apache.nifi.provenance.search.SearchTerm; import org.apache.nifi.provenance.search.SearchTerms; import org.apache.nifi.provenance.search.SearchableField; import org.apache.nifi.registry.ComponentVariableRegistry; import org.apache.nifi.registry.VariableDescriptor; import org.apache.nifi.registry.VariableRegistry; import org.apache.nifi.registry.flow.VersionedProcessGroup; import org.apache.nifi.remote.RemoteGroupPort; import org.apache.nifi.remote.RootGroupPort; import org.apache.nifi.reporting.ReportingTask; import org.apache.nifi.scheduling.ExecutionNode; import org.apache.nifi.scheduling.SchedulingStrategy; import org.apache.nifi.search.SearchContext; import org.apache.nifi.search.SearchResult; import org.apache.nifi.search.Searchable; import org.apache.nifi.services.FlowService; import org.apache.nifi.util.BundleUtils; import org.apache.nifi.util.FormatUtils; import org.apache.nifi.util.NiFiProperties; import org.apache.nifi.web.DownloadableContent; import org.apache.nifi.web.NiFiCoreException; import org.apache.nifi.web.ResourceNotFoundException; import org.apache.nifi.web.api.dto.BundleDTO; import org.apache.nifi.web.api.dto.DocumentedTypeDTO; import org.apache.nifi.web.api.dto.DtoFactory; import org.apache.nifi.web.api.dto.provenance.AttributeDTO; import org.apache.nifi.web.api.dto.provenance.ProvenanceDTO; import org.apache.nifi.web.api.dto.provenance.ProvenanceEventDTO; import org.apache.nifi.web.api.dto.provenance.ProvenanceOptionsDTO; import org.apache.nifi.web.api.dto.provenance.ProvenanceRequestDTO; import org.apache.nifi.web.api.dto.provenance.ProvenanceResultsDTO; import org.apache.nifi.web.api.dto.provenance.ProvenanceSearchableFieldDTO; import org.apache.nifi.web.api.dto.provenance.lineage.LineageDTO; import org.apache.nifi.web.api.dto.provenance.lineage.LineageRequestDTO; import org.apache.nifi.web.api.dto.provenance.lineage.LineageRequestDTO.LineageRequestType; import org.apache.nifi.web.api.dto.search.ComponentSearchResultDTO; import org.apache.nifi.web.api.dto.search.SearchResultsDTO; import org.apache.nifi.web.api.dto.status.ControllerStatusDTO; import org.apache.nifi.web.api.dto.status.StatusHistoryDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.WebApplicationException; import java.io.IOException; import java.io.InputStream; import java.text.Collator; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.apache.nifi.controller.FlowController.ROOT_GROUP_ID_ALIAS; public class ControllerFacade implements Authorizable { private static final Logger logger = LoggerFactory.getLogger(ControllerFacade.class); // nifi components private FlowController flowController; private FlowService flowService; private Authorizer authorizer; // properties private NiFiProperties properties; private DtoFactory dtoFactory; private VariableRegistry variableRegistry; /** * Returns the group id that contains the specified processor. * * @param processorId processor id * @return group id */ public String findProcessGroupIdForProcessor(String processorId) { final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId()); final ProcessorNode processor = rootGroup.findProcessor(processorId); if (processor == null) { return null; } else { return processor.getProcessGroup().getIdentifier(); } } public ControllerServiceProvider getControllerServiceProvider() { return flowController; } /** * Sets the name of this controller. * * @param name name */ public void setName(String name) { flowController.setName(name); } @Override public Authorizable getParentAuthorizable() { return flowController.getParentAuthorizable(); } @Override public Resource getResource() { return flowController.getResource(); } /** * Sets the comments of this controller. * * @param comments comments */ public void setComments(String comments) { flowController.setComments(comments); } /** * Gets the cached temporary instance of the component for the given type and bundle. * * @param type type of the component * @param bundle the bundle of the component * @return the temporary component * @throws IllegalStateException if no temporary component exists for the given type and bundle */ public ConfigurableComponent getTemporaryComponent(final String type, final BundleDTO bundle) { final ConfigurableComponent configurableComponent = ExtensionManager.getTempComponent(type, BundleUtils.getBundle(type, bundle)); if (configurableComponent == null) { throw new IllegalStateException("Unable to obtain temporary component for " + type); } return configurableComponent; } /** * Sets the max timer driven thread count of this controller. * * @param maxTimerDrivenThreadCount count */ public void setMaxTimerDrivenThreadCount(int maxTimerDrivenThreadCount) { flowController.setMaxTimerDrivenThreadCount(maxTimerDrivenThreadCount); } /** * Sets the max event driven thread count of this controller. * * @param maxEventDrivenThreadCount count */ public void setMaxEventDrivenThreadCount(int maxEventDrivenThreadCount) { flowController.setMaxEventDrivenThreadCount(maxEventDrivenThreadCount); } /** * Gets the root group id. * * @return group id */ public String getRootGroupId() { return flowController.getRootGroupId(); } /** * Gets the input ports on the root group. * * @return input ports */ public Set<RootGroupPort> getInputPorts() { final Set<RootGroupPort> inputPorts = new HashSet<>(); ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId()); for (final Port port : rootGroup.getInputPorts()) { if (port instanceof RootGroupPort) { inputPorts.add((RootGroupPort) port); } } return inputPorts; } /** * Gets the output ports on the root group. * * @return output ports */ public Set<RootGroupPort> getOutputPorts() { final Set<RootGroupPort> outputPorts = new HashSet<>(); ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId()); for (final Port port : rootGroup.getOutputPorts()) { if (port instanceof RootGroupPort) { outputPorts.add((RootGroupPort) port); } } return outputPorts; } /** * Returns the status history for the specified processor. * * @param processorId processor id * @return status history */ public StatusHistoryDTO getProcessorStatusHistory(final String processorId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final ProcessorNode processor = root.findProcessor(processorId); // ensure the processor was found if (processor == null) { throw new ResourceNotFoundException(String.format("Unable to locate processor with id '%s'.", processorId)); } final boolean authorized = processor.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser()); final StatusHistoryDTO statusHistory = flowController.getProcessorStatusHistory(processorId, authorized); // if not authorized if (!authorized) { statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, processorId); statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_TYPE, "Processor"); } return statusHistory; } /** * Returns the status history for the specified connection. * * @param connectionId connection id * @return status history */ public StatusHistoryDTO getConnectionStatusHistory(final String connectionId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final Connection connection = root.findConnection(connectionId); // ensure the connection was found if (connection == null) { throw new ResourceNotFoundException(String.format("Unable to locate connection with id '%s'.", connectionId)); } final StatusHistoryDTO statusHistory = flowController.getConnectionStatusHistory(connectionId); // if not authorized if (!connection.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser())) { statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, connectionId); statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_SOURCE_NAME, connection.getSource().getIdentifier()); statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_DESTINATION_NAME, connection.getDestination().getIdentifier()); } return statusHistory; } /** * Returns the status history for the specified process group. * * @param groupId group id * @return status history */ public StatusHistoryDTO getProcessGroupStatusHistory(final String groupId) { final String searchId = groupId.equals(ROOT_GROUP_ID_ALIAS) ? flowController.getRootGroupId() : groupId; final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final ProcessGroup group = root.findProcessGroup(searchId); // ensure the processor was found if (group == null) { throw new ResourceNotFoundException(String.format("Unable to locate process group with id '%s'.", groupId)); } final StatusHistoryDTO statusHistory = flowController.getProcessGroupStatusHistory(groupId); // if not authorized if (!group.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser())) { statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, groupId); } return statusHistory; } /** * Returns the status history for the specified remote process group. * * @param remoteProcessGroupId remote process group id * @return status history */ public StatusHistoryDTO getRemoteProcessGroupStatusHistory(final String remoteProcessGroupId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final RemoteProcessGroup remoteProcessGroup = root.findRemoteProcessGroup(remoteProcessGroupId); // ensure the output port was found if (remoteProcessGroup == null) { throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId)); } final StatusHistoryDTO statusHistory = flowController.getRemoteProcessGroupStatusHistory(remoteProcessGroupId); // if not authorized if (!remoteProcessGroup.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser())) { statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, remoteProcessGroupId); statusHistory.getComponentDetails().remove(ComponentStatusRepository.COMPONENT_DETAIL_URI); } return statusHistory; } /** * Get the node id of this controller. * * @return node identifier */ public NodeIdentifier getNodeId() { return flowController.getNodeId(); } /** * @return true if is clustered */ public boolean isClustered() { return flowController.isClustered(); } /** * Gets the name of this controller. * * @return name */ public String getName() { return flowController.getName(); } public String getInstanceId() { return flowController.getInstanceId(); } /** * Gets the comments of this controller. * * @return comments */ public String getComments() { return flowController.getComments(); } /** * Gets the max timer driven thread count of this controller. * * @return count */ public int getMaxTimerDrivenThreadCount() { return flowController.getMaxTimerDrivenThreadCount(); } /** * Gets the max event driven thread count of this controller. * * @return count */ public int getMaxEventDrivenThreadCount() { return flowController.getMaxEventDrivenThreadCount(); } /** * Gets the FlowFileProcessor types that this controller supports. * * @param bundleGroupFilter if specified, must be member of bundle group * @param bundleArtifactFilter if specified, must be member of bundle artifact * @param typeFilter if specified, type must match * @return types */ public Set<DocumentedTypeDTO> getFlowFileProcessorTypes(final String bundleGroupFilter, final String bundleArtifactFilter, final String typeFilter) { return dtoFactory.fromDocumentedTypes(ExtensionManager.getExtensions(Processor.class), bundleGroupFilter, bundleArtifactFilter, typeFilter); } /** * Gets the FlowFileComparator types that this controller supports. * * @return the FlowFileComparator types that this controller supports */ public Set<DocumentedTypeDTO> getFlowFileComparatorTypes() { return dtoFactory.fromDocumentedTypes(ExtensionManager.getExtensions(FlowFilePrioritizer.class), null, null, null); } /** * Returns whether the specified type implements the specified serviceType. * * @param serviceType type * @param type type * @return whether the specified type implements the specified serviceType */ private boolean implementsServiceType(final Class serviceType, final Class type) { final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(type); for (final Class i : interfaces) { if (ControllerService.class.isAssignableFrom(i) && serviceType.isAssignableFrom(i)) { return true; } } return false; } /** * Gets the ControllerService types that this controller supports. * * @param serviceType type * @param serviceBundleGroup if serviceType specified, the bundle group of the serviceType * @param serviceBundleArtifact if serviceType specified, the bundle artifact of the serviceType * @param serviceBundleVersion if serviceType specified, the bundle version of the serviceType * @param bundleGroupFilter if specified, must be member of bundle group * @param bundleArtifactFilter if specified, must be member of bundle artifact * @param typeFilter if specified, type must match * @return the ControllerService types that this controller supports */ public Set<DocumentedTypeDTO> getControllerServiceTypes(final String serviceType, final String serviceBundleGroup, final String serviceBundleArtifact, final String serviceBundleVersion, final String bundleGroupFilter, final String bundleArtifactFilter, final String typeFilter) { final Set<Class> serviceImplementations = ExtensionManager.getExtensions(ControllerService.class); // identify the controller services that implement the specified serviceType if applicable if (serviceType != null) { final BundleCoordinate bundleCoordinate = new BundleCoordinate(serviceBundleGroup, serviceBundleArtifact, serviceBundleVersion); final Bundle csBundle = ExtensionManager.getBundle(bundleCoordinate); if (csBundle == null) { throw new IllegalStateException("Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate()); } Class serviceClass = null; final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(csBundle.getClassLoader()); serviceClass = Class.forName(serviceType, false, csBundle.getClassLoader()); } catch (final Exception e) { Thread.currentThread().setContextClassLoader(currentContextClassLoader); throw new IllegalArgumentException(String.format("Unable to load %s from bundle %s: %s", serviceType, bundleCoordinate, e), e); } final Map<Class, Bundle> matchingServiceImplementations = new HashMap<>(); // check each type and remove those that aren't in the specified ancestry for (final Class csClass : serviceImplementations) { if (implementsServiceType(serviceClass, csClass)) { matchingServiceImplementations.put(csClass, ExtensionManager.getBundle(csClass.getClassLoader())); } } return dtoFactory.fromDocumentedTypes(matchingServiceImplementations, bundleGroupFilter, bundleArtifactFilter, typeFilter); } else { return dtoFactory.fromDocumentedTypes(serviceImplementations, bundleGroupFilter, bundleArtifactFilter, typeFilter); } } /** * Gets the ReportingTask types that this controller supports. * * @param bundleGroupFilter if specified, must be member of bundle group * @param bundleArtifactFilter if specified, must be member of bundle artifact * @param typeFilter if specified, type must match * @return the ReportingTask types that this controller supports */ public Set<DocumentedTypeDTO> getReportingTaskTypes(final String bundleGroupFilter, final String bundleArtifactFilter, final String typeFilter) { return dtoFactory.fromDocumentedTypes(ExtensionManager.getExtensions(ReportingTask.class), bundleGroupFilter, bundleArtifactFilter, typeFilter); } /** * Gets the counters for this controller. * * @return the counters for this controller */ public List<Counter> getCounters() { return flowController.getCounters(); } /** * Resets the counter with the specified id. * * @param id id * @return the counter with the specified id */ public Counter resetCounter(final String id) { final Counter counter = flowController.resetCounter(id); if (counter == null) { throw new ResourceNotFoundException(String.format("Unable to find Counter with id '%s'.", id)); } return counter; } /** * Gets the status of this controller. * * @return the status of this controller */ public ControllerStatusDTO getControllerStatus() { final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId()); final QueueSize controllerQueueSize = flowController.getTotalFlowFileCount(rootGroup); final ControllerStatusDTO controllerStatus = new ControllerStatusDTO(); controllerStatus.setActiveThreadCount(flowController.getActiveThreadCount()); controllerStatus.setQueued(FormatUtils.formatCount(controllerQueueSize.getObjectCount()) + " / " + FormatUtils.formatDataSize(controllerQueueSize.getByteCount())); controllerStatus.setBytesQueued(controllerQueueSize.getByteCount()); controllerStatus.setFlowFilesQueued(controllerQueueSize.getObjectCount()); final ProcessGroupCounts counts = rootGroup.getCounts(); controllerStatus.setRunningCount(counts.getRunningCount()); controllerStatus.setStoppedCount(counts.getStoppedCount()); controllerStatus.setInvalidCount(counts.getInvalidCount()); controllerStatus.setDisabledCount(counts.getDisabledCount()); controllerStatus.setActiveRemotePortCount(counts.getActiveRemotePortCount()); controllerStatus.setInactiveRemotePortCount(counts.getInactiveRemotePortCount()); controllerStatus.setUpToDateCount(counts.getUpToDateCount()); controllerStatus.setLocallyModifiedCount(counts.getLocallyModifiedCount()); controllerStatus.setStaleCount(counts.getStaleCount()); controllerStatus.setLocallyModifiedAndStaleCount(counts.getLocallyModifiedAndStaleCount()); controllerStatus.setSyncFailureCount(counts.getSyncFailureCount()); return controllerStatus; } /** * Gets the status for the specified process group. * * @param groupId group id * @return the status for the specified process group */ public ProcessGroupStatus getProcessGroupStatus(final String groupId) { final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser()); if (processGroupStatus == null) { throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId)); } return processGroupStatus; } /** * Gets the status for the specified processor. * * @param processorId processor id * @return the status for the specified processor */ public ProcessorStatus getProcessorStatus(final String processorId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final ProcessorNode processor = root.findProcessor(processorId); // ensure the processor was found if (processor == null) { throw new ResourceNotFoundException(String.format("Unable to locate processor with id '%s'.", processorId)); } // calculate the process group status final String groupId = processor.getProcessGroup().getIdentifier(); final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser()); if (processGroupStatus == null) { throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId)); } final ProcessorStatus status = processGroupStatus.getProcessorStatus().stream().filter(processorStatus -> processorId.equals(processorStatus.getId())).findFirst().orElse(null); if (status == null) { throw new ResourceNotFoundException(String.format("Unable to locate processor with id '%s'.", processorId)); } return status; } /** * Gets the status for the specified connection. * * @param connectionId connection id * @return the status for the specified connection */ public ConnectionStatus getConnectionStatus(final String connectionId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final Connection connection = root.findConnection(connectionId); // ensure the connection was found if (connection == null) { throw new ResourceNotFoundException(String.format("Unable to locate connection with id '%s'.", connectionId)); } // calculate the process group status final String groupId = connection.getProcessGroup().getIdentifier(); final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser()); if (processGroupStatus == null) { throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId)); } final ConnectionStatus status = processGroupStatus.getConnectionStatus().stream().filter(connectionStatus -> connectionId.equals(connectionStatus.getId())).findFirst().orElse(null); if (status == null) { throw new ResourceNotFoundException(String.format("Unable to locate connection with id '%s'.", connectionId)); } return status; } /** * Gets the status for the specified input port. * * @param portId input port id * @return the status for the specified input port */ public PortStatus getInputPortStatus(final String portId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final Port port = root.findInputPort(portId); // ensure the input port was found if (port == null) { throw new ResourceNotFoundException(String.format("Unable to locate input port with id '%s'.", portId)); } final String groupId = port.getProcessGroup().getIdentifier(); final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser()); if (processGroupStatus == null) { throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId)); } final PortStatus status = processGroupStatus.getInputPortStatus().stream().filter(portStatus -> portId.equals(portStatus.getId())).findFirst().orElse(null); if (status == null) { throw new ResourceNotFoundException(String.format("Unable to locate input port with id '%s'.", portId)); } return status; } /** * Gets the status for the specified output port. * * @param portId output port id * @return the status for the specified output port */ public PortStatus getOutputPortStatus(final String portId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final Port port = root.findOutputPort(portId); // ensure the output port was found if (port == null) { throw new ResourceNotFoundException(String.format("Unable to locate output port with id '%s'.", portId)); } final String groupId = port.getProcessGroup().getIdentifier(); final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser()); if (processGroupStatus == null) { throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId)); } final PortStatus status = processGroupStatus.getOutputPortStatus().stream().filter(portStatus -> portId.equals(portStatus.getId())).findFirst().orElse(null); if (status == null) { throw new ResourceNotFoundException(String.format("Unable to locate output port with id '%s'.", portId)); } return status; } /** * Gets the status for the specified remote process group. * * @param remoteProcessGroupId remote process group id * @return the status for the specified remote process group */ public RemoteProcessGroupStatus getRemoteProcessGroupStatus(final String remoteProcessGroupId) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final RemoteProcessGroup remoteProcessGroup = root.findRemoteProcessGroup(remoteProcessGroupId); // ensure the output port was found if (remoteProcessGroup == null) { throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId)); } final String groupId = remoteProcessGroup.getProcessGroup().getIdentifier(); final ProcessGroupStatus groupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser()); if (groupStatus == null) { throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId)); } final RemoteProcessGroupStatus status = groupStatus.getRemoteProcessGroupStatus().stream().filter(rpgStatus -> remoteProcessGroupId.equals(rpgStatus.getId())).findFirst().orElse(null); if (status == null) { throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId)); } return status; } /** * Saves the state of the flow controller. * * @throws NiFiCoreException ex */ public void save() throws NiFiCoreException { // save the flow controller final long writeDelaySeconds = FormatUtils.getTimeDuration(properties.getFlowServiceWriteDelay(), TimeUnit.SECONDS); flowService.saveFlowChanges(TimeUnit.SECONDS, writeDelaySeconds); } /** * Returns the socket port that the local instance is listening on for * Site-to-Site communications * * @return the socket port that the local instance is listening on for * Site-to-Site communications */ public Integer getRemoteSiteListeningPort() { return flowController.getRemoteSiteListeningPort(); } /** * Returns the http(s) port that the local instance is listening on for * Site-to-Site communications * * @return the socket port that the local instance is listening on for * Site-to-Site communications */ public Integer getRemoteSiteListeningHttpPort() { return flowController.getRemoteSiteListeningHttpPort(); } /** * Indicates whether or not Site-to-Site communications with the local * instance are secure * * @return whether or not Site-to-Site communications with the local * instance are secure */ public Boolean isRemoteSiteCommsSecure() { return flowController.isRemoteSiteCommsSecure(); } /** * Returns a SystemDiagnostics that describes the current state of the node * * @return a SystemDiagnostics that describes the current state of the node */ public SystemDiagnostics getSystemDiagnostics() { return flowController.getSystemDiagnostics(); } public List<Resource> getResources() { final List<Resource> resources = new ArrayList<>(); resources.add(ResourceFactory.getFlowResource()); resources.add(ResourceFactory.getSystemResource()); resources.add(ResourceFactory.getRestrictedComponentsResource()); resources.add(ResourceFactory.getControllerResource()); resources.add(ResourceFactory.getCountersResource()); resources.add(ResourceFactory.getProvenanceResource()); resources.add(ResourceFactory.getPoliciesResource()); resources.add(ResourceFactory.getTenantResource()); resources.add(ResourceFactory.getProxyResource()); resources.add(ResourceFactory.getResourceResource()); resources.add(ResourceFactory.getSiteToSiteResource()); final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); // include the root group final Resource rootResource = root.getResource(); resources.add(rootResource); resources.add(ResourceFactory.getDataResource(rootResource)); resources.add(ResourceFactory.getPolicyResource(rootResource)); // add each processor for (final ProcessorNode processor : root.findAllProcessors()) { final Resource processorResource = processor.getResource(); resources.add(processorResource); resources.add(ResourceFactory.getDataResource(processorResource)); resources.add(ResourceFactory.getPolicyResource(processorResource)); } // add each label for (final Label label : root.findAllLabels()) { final Resource labelResource = label.getResource(); resources.add(labelResource); resources.add(ResourceFactory.getPolicyResource(labelResource)); } // add each process group for (final ProcessGroup processGroup : root.findAllProcessGroups()) { final Resource processGroupResource = processGroup.getResource(); resources.add(processGroupResource); resources.add(ResourceFactory.getDataResource(processGroupResource)); resources.add(ResourceFactory.getPolicyResource(processGroupResource)); } // add each remote process group for (final RemoteProcessGroup remoteProcessGroup : root.findAllRemoteProcessGroups()) { final Resource remoteProcessGroupResource = remoteProcessGroup.getResource(); resources.add(remoteProcessGroupResource); resources.add(ResourceFactory.getDataResource(remoteProcessGroupResource)); resources.add(ResourceFactory.getPolicyResource(remoteProcessGroupResource)); } // add each input port for (final Port inputPort : root.findAllInputPorts()) { final Resource inputPortResource = inputPort.getResource(); resources.add(inputPortResource); resources.add(ResourceFactory.getDataResource(inputPortResource)); resources.add(ResourceFactory.getPolicyResource(inputPortResource)); if (inputPort instanceof RootGroupPort) { resources.add(ResourceFactory.getDataTransferResource(inputPortResource)); } } // add each output port for (final Port outputPort : root.findAllOutputPorts()) { final Resource outputPortResource = outputPort.getResource(); resources.add(outputPortResource); resources.add(ResourceFactory.getDataResource(outputPortResource)); resources.add(ResourceFactory.getPolicyResource(outputPortResource)); if (outputPort instanceof RootGroupPort) { resources.add(ResourceFactory.getDataTransferResource(outputPortResource)); } } // add each controller service final Consumer<ControllerServiceNode> csConsumer = controllerService -> { final Resource controllerServiceResource = controllerService.getResource(); resources.add(controllerServiceResource); resources.add(ResourceFactory.getPolicyResource(controllerServiceResource)); }; flowController.getAllControllerServices().forEach(csConsumer); root.findAllControllerServices().forEach(csConsumer); // add each reporting task for (final ReportingTaskNode reportingTask : flowController.getAllReportingTasks()) { final Resource reportingTaskResource = reportingTask.getResource(); resources.add(reportingTaskResource); resources.add(ResourceFactory.getPolicyResource(reportingTaskResource)); } // add each template for (final Template template : root.findAllTemplates()) { final Resource templateResource = template.getResource(); resources.add(templateResource); resources.add(ResourceFactory.getPolicyResource(templateResource)); } return resources; } /** * Gets the available options for searching provenance. * * @return the available options for searching provenance */ public ProvenanceOptionsDTO getProvenanceSearchOptions() { final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); // create the search options dto final ProvenanceOptionsDTO searchOptions = new ProvenanceOptionsDTO(); final List<ProvenanceSearchableFieldDTO> searchableFieldNames = new ArrayList<>(); final List<SearchableField> fields = provenanceRepository.getSearchableFields(); for (final SearchableField field : fields) { // we exclude the Event Time because it is always searchable but don't want support querying it this way... // we prefer the user queries using startDate and endDate if (SearchableFields.EventTime.equals(field)) { continue; } final ProvenanceSearchableFieldDTO searchableField = new ProvenanceSearchableFieldDTO(); searchableField.setId(field.getIdentifier()); searchableField.setField(field.getSearchableFieldName()); searchableField.setLabel(field.getFriendlyName()); searchableField.setType(field.getFieldType().name()); searchableFieldNames.add(searchableField); } final List<SearchableField> searchableAttributes = provenanceRepository.getSearchableAttributes(); for (final SearchableField searchableAttr : searchableAttributes) { final ProvenanceSearchableFieldDTO searchableAttribute = new ProvenanceSearchableFieldDTO(); searchableAttribute.setId(searchableAttr.getIdentifier()); searchableAttribute.setField(searchableAttr.getSearchableFieldName()); searchableAttribute.setLabel(searchableAttr.getFriendlyName()); searchableAttribute.setType(searchableAttr.getFieldType().name()); searchableFieldNames.add(searchableAttribute); } searchOptions.setSearchableFields(searchableFieldNames); return searchOptions; } /** * Submits a provenance query. * * @param provenanceDto dto * @return provenance info */ public ProvenanceDTO submitProvenance(ProvenanceDTO provenanceDto) { final ProvenanceRequestDTO requestDto = provenanceDto.getRequest(); // create the query final Query query = new Query(provenanceDto.getId()); // if the request was specified if (requestDto != null) { // add each search term specified final Map<String, String> searchTerms = requestDto.getSearchTerms(); if (searchTerms != null) { for (final Map.Entry<String, String> searchTerm : searchTerms.entrySet()) { SearchableField field; field = SearchableFields.getSearchableField(searchTerm.getKey()); if (field == null) { field = SearchableFields.newSearchableAttribute(searchTerm.getKey()); } query.addSearchTerm(SearchTerms.newSearchTerm(field, searchTerm.getValue())); } } // specify the start date if specified if (requestDto.getStartDate() != null) { query.setStartDate(requestDto.getStartDate()); } // ensure an end date is populated if (requestDto.getEndDate() != null) { query.setEndDate(requestDto.getEndDate()); } // set the min/max file size query.setMinFileSize(requestDto.getMinimumFileSize()); query.setMaxFileSize(requestDto.getMaximumFileSize()); // set the max results desired query.setMaxResults(requestDto.getMaxResults()); } // submit the query to the provenance repository final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); final QuerySubmission querySubmission = provenanceRepository.submitQuery(query, NiFiUserUtils.getNiFiUser()); // return the query with the results populated at this point return getProvenanceQuery(querySubmission.getQueryIdentifier(), requestDto.getSummarize(), requestDto.getIncrementalResults()); } /** * Retrieves the results of a provenance query. * * @param provenanceId id * @return the results of a provenance query */ public ProvenanceDTO getProvenanceQuery(String provenanceId, Boolean summarize, Boolean incrementalResults) { try { // get the query to the provenance repository final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); final QuerySubmission querySubmission = provenanceRepository.retrieveQuerySubmission(provenanceId, NiFiUserUtils.getNiFiUser()); // ensure the query results could be found if (querySubmission == null) { throw new ResourceNotFoundException("Cannot find the results for the specified provenance requests. Results may have been purged."); } // get the original query and the results final Query query = querySubmission.getQuery(); final QueryResult queryResult = querySubmission.getResult(); // build the response final ProvenanceDTO provenanceDto = new ProvenanceDTO(); final ProvenanceRequestDTO requestDto = new ProvenanceRequestDTO(); final ProvenanceResultsDTO resultsDto = new ProvenanceResultsDTO(); // include the original request and results provenanceDto.setRequest(requestDto); provenanceDto.setResults(resultsDto); // convert the original request requestDto.setStartDate(query.getStartDate()); requestDto.setEndDate(query.getEndDate()); requestDto.setMinimumFileSize(query.getMinFileSize()); requestDto.setMaximumFileSize(query.getMaxFileSize()); requestDto.setMaxResults(query.getMaxResults()); if (query.getSearchTerms() != null) { final Map<String, String> searchTerms = new HashMap<>(); for (final SearchTerm searchTerm : query.getSearchTerms()) { searchTerms.put(searchTerm.getSearchableField().getFriendlyName(), searchTerm.getValue()); } requestDto.setSearchTerms(searchTerms); } // convert the provenance provenanceDto.setId(query.getIdentifier()); provenanceDto.setSubmissionTime(querySubmission.getSubmissionTime()); provenanceDto.setExpiration(queryResult.getExpiration()); provenanceDto.setFinished(queryResult.isFinished()); provenanceDto.setPercentCompleted(queryResult.getPercentComplete()); // convert each event final boolean includeResults = incrementalResults == null || Boolean.TRUE.equals(incrementalResults); if (includeResults || queryResult.isFinished()) { final List<ProvenanceEventDTO> events = new ArrayList<>(); for (final ProvenanceEventRecord record : queryResult.getMatchingEvents()) { events.add(createProvenanceEventDto(record, Boolean.TRUE.equals(summarize))); } resultsDto.setProvenanceEvents(events); } if (requestDto.getMaxResults() != null && queryResult.getTotalHitCount() >= requestDto.getMaxResults()) { resultsDto.setTotalCount(requestDto.getMaxResults().longValue()); resultsDto.setTotal(FormatUtils.formatCount(requestDto.getMaxResults().longValue()) + "+"); } else { resultsDto.setTotalCount(queryResult.getTotalHitCount()); resultsDto.setTotal(FormatUtils.formatCount(queryResult.getTotalHitCount())); } // include any errors if (queryResult.getError() != null) { final Set<String> errors = new HashSet<>(); errors.add(queryResult.getError()); resultsDto.setErrors(errors); } // set the generated timestamp final Date now = new Date(); resultsDto.setGenerated(now); resultsDto.setTimeOffset(TimeZone.getDefault().getOffset(now.getTime())); // get the oldest available event time final List<ProvenanceEventRecord> firstEvent = provenanceRepository.getEvents(0, 1); if (!firstEvent.isEmpty()) { resultsDto.setOldestEvent(new Date(firstEvent.get(0).getEventTime())); } provenanceDto.setResults(resultsDto); return provenanceDto; } catch (final IOException ioe) { throw new NiFiCoreException("An error occurred while searching the provenance events.", ioe); } } /** * Submits the specified lineage request. * * @param lineageDto dto * @return updated lineage */ public LineageDTO submitLineage(LineageDTO lineageDto) { final LineageRequestDTO requestDto = lineageDto.getRequest(); // get the provenance repo final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); final ComputeLineageSubmission result; if (LineageRequestType.FLOWFILE.equals(requestDto.getLineageRequestType())) { if (requestDto.getUuid() != null) { // submit uuid if it is specified result = provenanceRepository.submitLineageComputation(requestDto.getUuid(), NiFiUserUtils.getNiFiUser()); } else { // submit the event if the flowfile uuid needs to be looked up result = provenanceRepository.submitLineageComputation(requestDto.getEventId(), NiFiUserUtils.getNiFiUser()); } } else { // submit event... (parents or children) if (LineageRequestType.PARENTS.equals(requestDto.getLineageRequestType())) { result = provenanceRepository.submitExpandParents(requestDto.getEventId(), NiFiUserUtils.getNiFiUser()); } else { result = provenanceRepository.submitExpandChildren(requestDto.getEventId(), NiFiUserUtils.getNiFiUser()); } } return getLineage(result.getLineageIdentifier()); } /** * Gets the lineage with the specified id. * * @param lineageId id * @return the lineage with the specified id */ public LineageDTO getLineage(final String lineageId) { // get the query to the provenance repository final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); final ComputeLineageSubmission computeLineageSubmission = provenanceRepository.retrieveLineageSubmission(lineageId, NiFiUserUtils.getNiFiUser()); // ensure the submission was found if (computeLineageSubmission == null) { throw new ResourceNotFoundException("Cannot find the results for the specified lineage request. Results may have been purged."); } return dtoFactory.createLineageDto(computeLineageSubmission); } /** * Deletes the query with the specified id. * * @param provenanceId id */ public void deleteProvenanceQuery(final String provenanceId) { // get the query to the provenance repository final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); final QuerySubmission querySubmission = provenanceRepository.retrieveQuerySubmission(provenanceId, NiFiUserUtils.getNiFiUser()); if (querySubmission != null) { querySubmission.cancel(); } } /** * Deletes the lineage with the specified id. * * @param lineageId id */ public void deleteLineage(final String lineageId) { // get the query to the provenance repository final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository(); final ComputeLineageSubmission computeLineageSubmission = provenanceRepository.retrieveLineageSubmission(lineageId, NiFiUserUtils.getNiFiUser()); if (computeLineageSubmission != null) { computeLineageSubmission.cancel(); } } /** * Gets the content for the specified claim. * * @param eventId event id * @param uri uri * @param contentDirection direction * @return the content for the specified claim */ public DownloadableContent getContent(final Long eventId, final String uri, final ContentDirection contentDirection) { try { final NiFiUser user = NiFiUserUtils.getNiFiUser(); // get the event in order to get the filename final ProvenanceEventRecord event = flowController.getProvenanceRepository().getEvent(eventId); if (event == null) { throw new ResourceNotFoundException("Unable to find the specified event."); } // get the flowfile attributes final Map<String, String> attributes; if (ContentDirection.INPUT.equals(contentDirection)) { attributes = event.getPreviousAttributes(); } else { attributes = event.getAttributes(); } // authorize the event final Authorizable dataAuthorizable; if (event.isRemotePortType()) { dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId()); } else { dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId()); } dataAuthorizable.authorize(authorizer, RequestAction.READ, user, attributes); // get the filename and fall back to the identifier (should never happen) String filename = attributes.get(CoreAttributes.FILENAME.key()); if (filename == null) { filename = event.getFlowFileUuid(); } // get the mime-type final String type = attributes.get(CoreAttributes.MIME_TYPE.key()); // get the content final InputStream content = flowController.getContent(event, contentDirection, user.getIdentity(), uri); return new DownloadableContent(filename, type, content); } catch (final ContentNotFoundException cnfe) { throw new ResourceNotFoundException("Unable to find the specified content."); } catch (final IOException ioe) { logger.error(String.format("Unable to get the content for event (%s) at this time.", eventId), ioe); throw new IllegalStateException("Unable to get the content at this time."); } } /** * Submits a replay request for the specified event id. * * @param eventId event id * @return provenance event */ public ProvenanceEventDTO submitReplay(final Long eventId) { try { final NiFiUser user = NiFiUserUtils.getNiFiUser(); if (user == null) { throw new WebApplicationException(new Throwable("Unable to access details for current user.")); } // lookup the original event final ProvenanceEventRecord originalEvent = flowController.getProvenanceRepository().getEvent(eventId); if (originalEvent == null) { throw new ResourceNotFoundException("Unable to find the specified event."); } // authorize the replay authorizeReplay(originalEvent); // replay the flow file final ProvenanceEventRecord event = flowController.replayFlowFile(originalEvent, user); // convert the event record return createProvenanceEventDto(event, false); } catch (final IOException ioe) { throw new NiFiCoreException("An error occurred while getting the specified event.", ioe); } } /** * Authorizes access to replay a specified provenance event. * * @param event event */ private AuthorizationResult checkAuthorizationForReplay(final ProvenanceEventRecord event) { // if the connection id isn't specified, then the replay wouldn't be available anyways and we have nothing to authorize against so deny it` if (event.getSourceQueueIdentifier() == null) { return AuthorizationResult.denied("The connection id in the provenance event is unknown."); } final NiFiUser user = NiFiUserUtils.getNiFiUser(); final Authorizable dataAuthorizable; if (event.isRemotePortType()) { dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId()); } else { dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId()); } final Map<String, String> eventAttributes = event.getAttributes(); // ensure we can read the data final AuthorizationResult result = dataAuthorizable.checkAuthorization(authorizer, RequestAction.READ, user, eventAttributes); if (!Result.Approved.equals(result.getResult())) { return result; } // ensure we can write the data return dataAuthorizable.checkAuthorization(authorizer, RequestAction.WRITE, user, eventAttributes); } /** * Authorizes access to replay a specified provenance event. * * @param event event */ private void authorizeReplay(final ProvenanceEventRecord event) { // if the connection id isn't specified, then the replay wouldn't be available anyways and we have nothing to authorize against so deny it` if (event.getSourceQueueIdentifier() == null) { throw new AccessDeniedException("The connection id in the provenance event is unknown."); } final NiFiUser user = NiFiUserUtils.getNiFiUser(); final Authorizable dataAuthorizable; if (event.isRemotePortType()) { dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId()); } else { dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId()); } // ensure we can read and write the data final Map<String, String> eventAttributes = event.getAttributes(); dataAuthorizable.authorize(authorizer, RequestAction.READ, user, eventAttributes); dataAuthorizable.authorize(authorizer, RequestAction.WRITE, user, eventAttributes); } /** * Get the provenance event with the specified event id. * * @param eventId event id * @return the provenance event with the specified event id */ public ProvenanceEventDTO getProvenanceEvent(final Long eventId) { try { final ProvenanceEventRecord event = flowController.getProvenanceRepository().getEvent(eventId); if (event == null) { throw new ResourceNotFoundException("Unable to find the specified event."); } // get the flowfile attributes and authorize the event final Map<String, String> attributes = event.getAttributes(); final Authorizable dataAuthorizable; if (event.isRemotePortType()) { dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId()); } else { dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId()); } dataAuthorizable.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser(), attributes); // convert the event return createProvenanceEventDto(event, false); } catch (final IOException ioe) { throw new NiFiCoreException("An error occurred while getting the specified event.", ioe); } } /** * Creates a ProvenanceEventDTO for the specified ProvenanceEventRecord. * * @param event event * @return event */ private ProvenanceEventDTO createProvenanceEventDto(final ProvenanceEventRecord event, final boolean summarize) { final ProvenanceEventDTO dto = new ProvenanceEventDTO(); dto.setId(String.valueOf(event.getEventId())); dto.setEventId(event.getEventId()); dto.setEventTime(new Date(event.getEventTime())); dto.setEventType(event.getEventType().name()); dto.setFlowFileUuid(event.getFlowFileUuid()); dto.setFileSize(FormatUtils.formatDataSize(event.getFileSize())); dto.setFileSizeBytes(event.getFileSize()); dto.setComponentId(event.getComponentId()); dto.setComponentType(event.getComponentType()); // sets the component details if it can find the component still in the flow setComponentDetails(dto); // only include all details if not summarizing if (!summarize) { // convert the attributes final Comparator<AttributeDTO> attributeComparator = new Comparator<AttributeDTO>() { @Override public int compare(AttributeDTO a1, AttributeDTO a2) { return Collator.getInstance(Locale.US).compare(a1.getName(), a2.getName()); } }; final SortedSet<AttributeDTO> attributes = new TreeSet<>(attributeComparator); final Map<String, String> updatedAttrs = event.getUpdatedAttributes(); final Map<String, String> previousAttrs = event.getPreviousAttributes(); // add previous attributes that haven't been modified. for (final Map.Entry<String, String> entry : previousAttrs.entrySet()) { // don't add any attributes that have been updated; we will do that next if (updatedAttrs.containsKey(entry.getKey())) { continue; } final AttributeDTO attribute = new AttributeDTO(); attribute.setName(entry.getKey()); attribute.setValue(entry.getValue()); attribute.setPreviousValue(entry.getValue()); attributes.add(attribute); } // Add all of the update attributes for (final Map.Entry<String, String> entry : updatedAttrs.entrySet()) { final AttributeDTO attribute = new AttributeDTO(); attribute.setName(entry.getKey()); attribute.setValue(entry.getValue()); attribute.setPreviousValue(previousAttrs.get(entry.getKey())); attributes.add(attribute); } // additional event details dto.setAlternateIdentifierUri(event.getAlternateIdentifierUri()); dto.setAttributes(attributes); dto.setTransitUri(event.getTransitUri()); dto.setSourceSystemFlowFileId(event.getSourceSystemFlowFileIdentifier()); dto.setRelationship(event.getRelationship()); dto.setDetails(event.getDetails()); final ContentAvailability contentAvailability = flowController.getContentAvailability(event); // content dto.setContentEqual(contentAvailability.isContentSame()); dto.setInputContentAvailable(contentAvailability.isInputAvailable()); dto.setInputContentClaimSection(event.getPreviousContentClaimSection()); dto.setInputContentClaimContainer(event.getPreviousContentClaimContainer()); dto.setInputContentClaimIdentifier(event.getPreviousContentClaimIdentifier()); dto.setInputContentClaimOffset(event.getPreviousContentClaimOffset()); dto.setInputContentClaimFileSizeBytes(event.getPreviousFileSize()); dto.setOutputContentAvailable(contentAvailability.isOutputAvailable()); dto.setOutputContentClaimSection(event.getContentClaimSection()); dto.setOutputContentClaimContainer(event.getContentClaimContainer()); dto.setOutputContentClaimIdentifier(event.getContentClaimIdentifier()); dto.setOutputContentClaimOffset(event.getContentClaimOffset()); dto.setOutputContentClaimFileSize(FormatUtils.formatDataSize(event.getFileSize())); dto.setOutputContentClaimFileSizeBytes(event.getFileSize()); // format the previous file sizes if possible if (event.getPreviousFileSize() != null) { dto.setInputContentClaimFileSize(FormatUtils.formatDataSize(event.getPreviousFileSize())); } // determine if authorized for event replay final AuthorizationResult replayAuthorized = checkAuthorizationForReplay(event); // replay dto.setReplayAvailable(contentAvailability.isReplayable() && Result.Approved.equals(replayAuthorized.getResult())); dto.setReplayExplanation(contentAvailability.isReplayable() && !Result.Approved.equals(replayAuthorized.getResult()) ? replayAuthorized.getExplanation() : contentAvailability.getReasonNotReplayable()); dto.setSourceConnectionIdentifier(event.getSourceQueueIdentifier()); // event duration if (event.getEventDuration() >= 0) { dto.setEventDuration(event.getEventDuration()); } // lineage duration if (event.getLineageStartDate() > 0) { final long lineageDuration = event.getEventTime() - event.getLineageStartDate(); dto.setLineageDuration(lineageDuration); } // parent uuids final List<String> parentUuids = new ArrayList<>(event.getParentUuids()); Collections.sort(parentUuids, Collator.getInstance(Locale.US)); dto.setParentUuids(parentUuids); // child uuids final List<String> childUuids = new ArrayList<>(event.getChildUuids()); Collections.sort(childUuids, Collator.getInstance(Locale.US)); dto.setChildUuids(childUuids); } return dto; } private void setComponentDetails(final ProvenanceEventDTO dto) { final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId()); final Connectable connectable = root.findLocalConnectable(dto.getComponentId()); if (connectable != null) { dto.setGroupId(connectable.getProcessGroup().getIdentifier()); dto.setComponentName(connectable.getName()); return; } final RemoteGroupPort remoteGroupPort = root.findRemoteGroupPort(dto.getComponentId()); if (remoteGroupPort != null) { dto.setGroupId(remoteGroupPort.getProcessGroupIdentifier()); dto.setComponentName(remoteGroupPort.getName()); return; } final Connection connection = root.findConnection(dto.getComponentId()); if (connection != null) { dto.setGroupId(connection.getProcessGroup().getIdentifier()); String name = connection.getName(); final Collection<Relationship> relationships = connection.getRelationships(); if (StringUtils.isBlank(name) && CollectionUtils.isNotEmpty(relationships)) { name = StringUtils.join(relationships.stream().map(relationship -> relationship.getName()).collect(Collectors.toSet()), ", "); } dto.setComponentName(name); return; } } /** * Searches this controller for the specified term. * * @param search search * @return result */ public SearchResultsDTO search(final String search) { final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId()); final SearchResultsDTO results = new SearchResultsDTO(); search(results, search, rootGroup); return results; } private void search(final SearchResultsDTO results, final String search, final ProcessGroup group) { final NiFiUser user = NiFiUserUtils.getNiFiUser(); if (group.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO groupMatch = search(search, group); if (groupMatch != null) { results.getProcessGroupResults().add(groupMatch); } } for (final ProcessorNode procNode : group.getProcessors()) { if (procNode.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO match = search(search, procNode); if (match != null) { match.setGroupId(group.getIdentifier()); results.getProcessorResults().add(match); } } } for (final Connection connection : group.getConnections()) { if (connection.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO match = search(search, connection); if (match != null) { match.setGroupId(group.getIdentifier()); results.getConnectionResults().add(match); } } } for (final RemoteProcessGroup remoteGroup : group.getRemoteProcessGroups()) { if (remoteGroup.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO match = search(search, remoteGroup); if (match != null) { match.setGroupId(group.getIdentifier()); results.getRemoteProcessGroupResults().add(match); } } } for (final Port port : group.getInputPorts()) { if (port.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO match = search(search, port); if (match != null) { match.setGroupId(group.getIdentifier()); results.getInputPortResults().add(match); } } } for (final Port port : group.getOutputPorts()) { if (port.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO match = search(search, port); if (match != null) { match.setGroupId(group.getIdentifier()); results.getOutputPortResults().add(match); } } } for (final Funnel funnel : group.getFunnels()) { if (funnel.isAuthorized(authorizer, RequestAction.READ, user)) { final ComponentSearchResultDTO match = search(search, funnel); if (match != null) { match.setGroupId(group.getIdentifier()); results.getFunnelResults().add(match); } } } for (final ProcessGroup processGroup : group.getProcessGroups()) { search(results, search, processGroup); } } private ComponentSearchResultDTO search(final String searchStr, final Port port) { final List<String> matches = new ArrayList<>(); addIfAppropriate(searchStr, port.getIdentifier(), "Id", matches); addIfAppropriate(searchStr, port.getVersionedComponentId().orElse(null), "Version Control ID", matches); addIfAppropriate(searchStr, port.getName(), "Name", matches); addIfAppropriate(searchStr, port.getComments(), "Comments", matches); // consider scheduled state if (ScheduledState.DISABLED.equals(port.getScheduledState())) { if (StringUtils.containsIgnoreCase("disabled", searchStr)) { matches.add("Run status: Disabled"); } } else { if (StringUtils.containsIgnoreCase("invalid", searchStr) && !port.isValid()) { matches.add("Run status: Invalid"); } else if (ScheduledState.RUNNING.equals(port.getScheduledState()) && StringUtils.containsIgnoreCase("running", searchStr)) { matches.add("Run status: Running"); } else if (ScheduledState.STOPPED.equals(port.getScheduledState()) && StringUtils.containsIgnoreCase("stopped", searchStr)) { matches.add("Run status: Stopped"); } } if (port instanceof RootGroupPort) { final RootGroupPort rootGroupPort = (RootGroupPort) port; // user access controls for (final String userAccessControl : rootGroupPort.getUserAccessControl()) { addIfAppropriate(searchStr, userAccessControl, "User access control", matches); } // group access controls for (final String groupAccessControl : rootGroupPort.getGroupAccessControl()) { addIfAppropriate(searchStr, groupAccessControl, "Group access control", matches); } } if (matches.isEmpty()) { return null; } final ComponentSearchResultDTO dto = new ComponentSearchResultDTO(); dto.setId(port.getIdentifier()); dto.setName(port.getName()); dto.setMatches(matches); return dto; } public void verifyComponentTypes(VersionedProcessGroup versionedFlow) { flowController.verifyComponentTypesInSnippet(versionedFlow); } private ComponentSearchResultDTO search(final String searchStr, final ProcessorNode procNode) { final List<String> matches = new ArrayList<>(); final Processor processor = procNode.getProcessor(); addIfAppropriate(searchStr, procNode.getIdentifier(), "Id", matches); addIfAppropriate(searchStr, procNode.getVersionedComponentId().orElse(null), "Version Control ID", matches); addIfAppropriate(searchStr, procNode.getName(), "Name", matches); addIfAppropriate(searchStr, procNode.getComments(), "Comments", matches); // consider scheduling strategy if (SchedulingStrategy.EVENT_DRIVEN.equals(procNode.getSchedulingStrategy()) && StringUtils.containsIgnoreCase("event", searchStr)) { matches.add("Scheduling strategy: Event driven"); } else if (SchedulingStrategy.TIMER_DRIVEN.equals(procNode.getSchedulingStrategy()) && StringUtils.containsIgnoreCase("timer", searchStr)) { matches.add("Scheduling strategy: Timer driven"); } else if (SchedulingStrategy.PRIMARY_NODE_ONLY.equals(procNode.getSchedulingStrategy()) && StringUtils.containsIgnoreCase("primary", searchStr)) { // PRIMARY_NODE_ONLY has been deprecated as a SchedulingStrategy and replaced by PRIMARY as an ExecutionNode. matches.add("Scheduling strategy: On primary node"); } // consider execution node if (ExecutionNode.PRIMARY.equals(procNode.getExecutionNode()) && StringUtils.containsIgnoreCase("primary", searchStr)) { matches.add("Execution node: primary"); } // consider scheduled state if (ScheduledState.DISABLED.equals(procNode.getScheduledState())) { if (StringUtils.containsIgnoreCase("disabled", searchStr)) { matches.add("Run status: Disabled"); } } else { if (StringUtils.containsIgnoreCase("invalid", searchStr) && !procNode.isValid()) { matches.add("Run status: Invalid"); } else if (ScheduledState.RUNNING.equals(procNode.getScheduledState()) && StringUtils.containsIgnoreCase("running", searchStr)) { matches.add("Run status: Running"); } else if (ScheduledState.STOPPED.equals(procNode.getScheduledState()) && StringUtils.containsIgnoreCase("stopped", searchStr)) { matches.add("Run status: Stopped"); } } for (final Relationship relationship : procNode.getRelationships()) { addIfAppropriate(searchStr, relationship.getName(), "Relationship", matches); } // Add both the actual class name and the component type. This allows us to search for 'Ghost' // to search for components that could not be instantiated. addIfAppropriate(searchStr, processor.getClass().getSimpleName(), "Type", matches); addIfAppropriate(searchStr, procNode.getComponentType(), "Type", matches); for (final Map.Entry<PropertyDescriptor, String> entry : procNode.getProperties().entrySet()) { final PropertyDescriptor descriptor = entry.getKey(); addIfAppropriate(searchStr, descriptor.getName(), "Property name", matches); addIfAppropriate(searchStr, descriptor.getDescription(), "Property description", matches); // never include sensitive properties values in search results if (descriptor.isSensitive()) { continue; } String value = entry.getValue(); // if unset consider default value if (value == null) { value = descriptor.getDefaultValue(); } // evaluate if the value matches the search criteria if (StringUtils.containsIgnoreCase(value, searchStr)) { matches.add("Property value: " + descriptor.getName() + " - " + value); } } // consider searching the processor directly if (processor instanceof Searchable) { final Searchable searchable = (Searchable) processor; final SearchContext context = new StandardSearchContext(searchStr, procNode, flowController, variableRegistry); // search the processor using the appropriate thread context classloader try (final NarCloseable x = NarCloseable.withComponentNarLoader(processor.getClass(), processor.getIdentifier())) { final Collection<SearchResult> searchResults = searchable.search(context); if (CollectionUtils.isNotEmpty(searchResults)) { for (final SearchResult searchResult : searchResults) { matches.add(searchResult.getLabel() + ": " + searchResult.getMatch()); } } } catch (final Throwable t) { // log this as error } } if (matches.isEmpty()) { return null; } final ComponentSearchResultDTO result = new ComponentSearchResultDTO(); result.setId(procNode.getIdentifier()); result.setMatches(matches); result.setName(procNode.getName()); return result; } private ComponentSearchResultDTO search(final String searchStr, final ProcessGroup group) { final List<String> matches = new ArrayList<>(); final ProcessGroup parent = group.getParent(); if (parent == null) { return null; } addIfAppropriate(searchStr, group.getIdentifier(), "Id", matches); addIfAppropriate(searchStr, group.getVersionedComponentId().orElse(null), "Version Control ID", matches); addIfAppropriate(searchStr, group.getName(), "Name", matches); addIfAppropriate(searchStr, group.getComments(), "Comments", matches); final ComponentVariableRegistry varRegistry = group.getVariableRegistry(); if (varRegistry != null) { final Map<VariableDescriptor, String> variableMap = varRegistry.getVariableMap(); for (final Map.Entry<VariableDescriptor, String> entry : variableMap.entrySet()) { addIfAppropriate(searchStr, entry.getKey().getName(), "Variable Name", matches); addIfAppropriate(searchStr, entry.getValue(), "Variable Value", matches); } } if (matches.isEmpty()) { return null; } final ComponentSearchResultDTO result = new ComponentSearchResultDTO(); result.setId(group.getIdentifier()); result.setName(group.getName()); result.setGroupId(parent.getIdentifier()); result.setMatches(matches); return result; } private ComponentSearchResultDTO search(final String searchStr, final Connection connection) { final List<String> matches = new ArrayList<>(); // search id and name addIfAppropriate(searchStr, connection.getIdentifier(), "Id", matches); addIfAppropriate(searchStr, connection.getVersionedComponentId().orElse(null), "Version Control ID", matches); addIfAppropriate(searchStr, connection.getName(), "Name", matches); // search relationships for (final Relationship relationship : connection.getRelationships()) { addIfAppropriate(searchStr, relationship.getName(), "Relationship", matches); } // search prioritizers final FlowFileQueue queue = connection.getFlowFileQueue(); for (final FlowFilePrioritizer comparator : queue.getPriorities()) { addIfAppropriate(searchStr, comparator.getClass().getName(), "Prioritizer", matches); } // search expiration if (StringUtils.containsIgnoreCase("expires", searchStr) || StringUtils.containsIgnoreCase("expiration", searchStr)) { final int expirationMillis = connection.getFlowFileQueue().getFlowFileExpiration(TimeUnit.MILLISECONDS); if (expirationMillis > 0) { matches.add("FlowFile expiration: " + connection.getFlowFileQueue().getFlowFileExpiration()); } } // search back pressure if (StringUtils.containsIgnoreCase("back pressure", searchStr) || StringUtils.containsIgnoreCase("pressure", searchStr)) { final String backPressureDataSize = connection.getFlowFileQueue().getBackPressureDataSizeThreshold(); final Double backPressureBytes = DataUnit.parseDataSize(backPressureDataSize, DataUnit.B); if (backPressureBytes > 0) { matches.add("Back pressure data size: " + backPressureDataSize); } final long backPressureCount = connection.getFlowFileQueue().getBackPressureObjectThreshold(); if (backPressureCount > 0) { matches.add("Back pressure count: " + backPressureCount); } } // search the source final Connectable source = connection.getSource(); addIfAppropriate(searchStr, source.getIdentifier(), "Source id", matches); addIfAppropriate(searchStr, source.getName(), "Source name", matches); addIfAppropriate(searchStr, source.getComments(), "Source comments", matches); // search the destination final Connectable destination = connection.getDestination(); addIfAppropriate(searchStr, destination.getIdentifier(), "Destination id", matches); addIfAppropriate(searchStr, destination.getName(), "Destination name", matches); addIfAppropriate(searchStr, destination.getComments(), "Destination comments", matches); if (matches.isEmpty()) { return null; } final ComponentSearchResultDTO result = new ComponentSearchResultDTO(); result.setId(connection.getIdentifier()); // determine the name of the search match if (StringUtils.isNotBlank(connection.getName())) { result.setName(connection.getName()); } else if (!connection.getRelationships().isEmpty()) { final List<String> relationships = new ArrayList<>(connection.getRelationships().size()); for (final Relationship relationship : connection.getRelationships()) { if (StringUtils.isNotBlank(relationship.getName())) { relationships.add(relationship.getName()); } } if (!relationships.isEmpty()) { result.setName(StringUtils.join(relationships, ", ")); } } // ensure a name is added if (result.getName() == null) { result.setName("From source " + connection.getSource().getName()); } result.setMatches(matches); return result; } private ComponentSearchResultDTO search(final String searchStr, final RemoteProcessGroup group) { final List<String> matches = new ArrayList<>(); addIfAppropriate(searchStr, group.getIdentifier(), "Id", matches); addIfAppropriate(searchStr, group.getVersionedComponentId().orElse(null), "Version Control ID", matches); addIfAppropriate(searchStr, group.getName(), "Name", matches); addIfAppropriate(searchStr, group.getComments(), "Comments", matches); addIfAppropriate(searchStr, group.getTargetUris(), "URLs", matches); // consider the transmission status if ((StringUtils.containsIgnoreCase("transmitting", searchStr) || StringUtils.containsIgnoreCase("transmission enabled", searchStr)) && group.isTransmitting()) { matches.add("Transmission: On"); } else if ((StringUtils.containsIgnoreCase("not transmitting", searchStr) || StringUtils.containsIgnoreCase("transmission disabled", searchStr)) && !group.isTransmitting()) { matches.add("Transmission: Off"); } if (matches.isEmpty()) { return null; } final ComponentSearchResultDTO result = new ComponentSearchResultDTO(); result.setId(group.getIdentifier()); result.setName(group.getName()); result.setMatches(matches); return result; } private ComponentSearchResultDTO search(final String searchStr, final Funnel funnel) { final List<String> matches = new ArrayList<>(); addIfAppropriate(searchStr, funnel.getIdentifier(), "Id", matches); addIfAppropriate(searchStr, funnel.getVersionedComponentId().orElse(null), "Version Control ID", matches); if (matches.isEmpty()) { return null; } final ComponentSearchResultDTO dto = new ComponentSearchResultDTO(); dto.setId(funnel.getIdentifier()); dto.setName(funnel.getName()); dto.setMatches(matches); return dto; } private void addIfAppropriate(final String searchStr, final String value, final String label, final List<String> matches) { if (StringUtils.containsIgnoreCase(value, searchStr)) { matches.add(label + ": " + value); } } /* * setters */ public void setFlowController(FlowController flowController) { this.flowController = flowController; } public void setProperties(NiFiProperties properties) { this.properties = properties; } public void setAuthorizer(Authorizer authorizer) { this.authorizer = authorizer; } public void setFlowService(FlowService flowService) { this.flowService = flowService; } public void setDtoFactory(DtoFactory dtoFactory) { this.dtoFactory = dtoFactory; } public void setVariableRegistry(VariableRegistry variableRegistry) { this.variableRegistry = variableRegistry; } }
InspurUSA/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/controller/ControllerFacade.java
Java
apache-2.0
86,923
/* * Copyright 2017 David Karnok * * 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 hu.akarnokd.reactive4javaflow.processors; import hu.akarnokd.reactive4javaflow.Esetleg; public abstract class EsetlegProcessor<T> extends Esetleg<T> implements FlowProcessorSupport<T> { @Override public EsetlegProcessor<T> toSerialized() { return this; } @Override public final EsetlegProcessor<T> refCount() { if (this instanceof EsetlegProcessorRefCount) { return this; } return new EsetlegProcessorRefCount<>(this); } }
akarnokd/Reactive4JavaFlow
src/main/java/hu/akarnokd/reactive4javaflow/processors/EsetlegProcessor.java
Java
apache-2.0
1,100
package com.github.mzule.androidweekly.ui.view; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.TextView; import com.github.mzule.androidweekly.R; import com.github.mzule.androidweekly.ui.view.base.BaseLinearLayout; import com.github.mzule.layoutannotation.Layout; import butterknife.Bind; import butterknife.OnClick; /** * Created by CaoDongping on 4/5/16. */ @Layout(R.layout.view_navi_bar) public class NaviBar extends BaseLinearLayout { @Bind(R.id.leftTextView) TextView leftTextView; @Bind(R.id.rightTextView) TextView rightTextView; public NaviBar(Context context) { super(context); } public NaviBar(Context context, AttributeSet attrs) { super(context, attrs); } public NaviBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void init(Context context, AttributeSet attrs) { super.init(context, attrs); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.NaviBar); leftTextView.setText(a.getString(R.styleable.NaviBar_nb_left_text)); rightTextView.setText(a.getString(R.styleable.NaviBar_nb_right_text)); a.recycle(); } } @OnClick(R.id.backButton) void back() { if (getContext() instanceof Activity) { ((Activity) getContext()).finish(); } } public void setLeftText(String text) { leftTextView.setText(text); } public void setRightText(String text) { rightTextView.setText(text); } }
mzule/AndroidWeekly
app/src/main/java/com/github/mzule/androidweekly/ui/view/NaviBar.java
Java
apache-2.0
1,740
package ar_ubin.benotified.base; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import javax.inject.Inject; import ar_ubin.benotified.ActivityModule; import ar_ubin.benotified.ApplicationComponent; import ar_ubin.benotified.BeNotifiedApplication; import ar_ubin.benotified.navigation.Navigator; import ar_ubin.benotified.utils.GsonSharedPrefs; import static com.google.common.base.Preconditions.checkNotNull; public abstract class BaseActivity extends AppCompatActivity { @Inject public Navigator mNavigator; @Inject public GsonSharedPrefs mGsonSharedPrefs; @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); } protected void addFragment( int containerViewId, Fragment fragment ) { checkNotNull( containerViewId ); checkNotNull( fragment ); FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction(); fragmentTransaction.add( containerViewId, fragment ); fragmentTransaction.commit(); } public ApplicationComponent getApplicationComponent() { return ( (BeNotifiedApplication) getApplication() ).getApplicationComponent(); } public ActivityModule getActivityModule() { return new ActivityModule( this ); } }
ar-ubin/BeNotified
app/src/main/java/ar_ubin/benotified/base/BaseActivity.java
Java
apache-2.0
1,440
package com.example.a226; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText et; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b = (Button) findViewById(R.id.button1); et = (EditText) findViewById(R.id.EditText1); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = et.getText().toString(); Intent intent = new Intent("com.example.translate"); intent.putExtra("word", s); startActivity(intent); } }); } }
zelig81/hyperactive-class
A226/src/com/example/a226/MainActivity.java
Java
apache-2.0
776
/* * Copyright (C) 2013 salesforce.com, inc. * * 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. */ ({ /** * Set up the actions by creating a storage, building the hierarchy, and resetting the buffer for the test. */ setUp: function(cmp) { // // Initialize storage here, in JS to avoid issues with instantiating the component multiple // times. // $A.storageService.initStorage("actions", false, false, 100000, 50, 0, true, true, 1); cmp.helper.buildHierarchy(cmp); var ready = false; $A.test.callServerAction($A.test.getAction(cmp, "c.execute", { "commands" : "RESET" }, function() { ready = true; })); $A.test.addWaitFor(true, function() { return ready; }); }, /** * Get a lock name that will not conflict. * * FIXME: there should be a $A.test.getUniqueId() */ getSafeLock: function(cmp, name) { if (!cmp._lock_names) { cmp._lock_names = {}; cmp._lock_base = ""+new Date().getTime(); } if (!cmp._lock_names[name]) { cmp._lock_names[name] = $A.test.getTestName()+"."+cmp._lock_base+"."+name; } return cmp._lock_names[name]; }, /** * Convert an array of command arrays into a simple string. * * This allows us to ensure locks are unique, and check the command string. */ buildCommands: function(cmp, commands) { var i; var commands_out = ""; var name; var parent = cmp; for (i = 0; i < commands.length; i++) { var command_list = commands[i]; var command = command_list[0]; if (command === "WAIT") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "WAIT "+name+";"; } else if (command === "RESUME") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "RESUME "+name+";"; } else if (command === "APPEND") { commands_out += "APPEND "+command_list[1]+";"; } else if (command === "COPY") { commands_out += "COPY;"; } else if (command === "READ") { commands_out += "READ;"; } else { throw new Error("Unknown command "+command+" in "+command_list); } } return commands_out; }, sendAction: function(cmp, path, commands, label, options) { var i; var commands_out = ""; var name; var parent = cmp; for (i = 0; i < commands.length; i++) { var command_list = commands[i]; var command = command_list[0]; if (command === "WAIT") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "WAIT "+name+";"; } else if (command === "RESUME") { name = this.getSafeLock(cmp, command_list[1]); commands_out += "RESUME "+name+";"; } else if (command === "APPEND") { commands_out += "APPEND "+command_list[1]+";"; } else if (command === "COPY") { commands_out += "COPY;"; } else if (command === "READ") { commands_out += "READ;"; } } cmp.runAction(path, parent, commands_out, label, options); }, /** * Wait for a line to appear at a specific location. */ addWaitForLog : function(cmp, index, content, cb, partialMatch) { var actual; $A.test.addWaitForWithFailureMessage(false, function() { actual = cmp.get("v.log")?cmp.get("v.log")[index]:undefined; return actual === undefined; }, "Never received log message '" + content + "' at index " + index, function() { if(partialMatch === true) { $A.test.assertTrue(actual.contains(content), "mismatch on log entry "+index); } else { $A.test.assertEquals(content, actual, "mismatch on log entry "+index); } if (cb) { cb(); } } ); }, /** * Wait for a log entry that will fall in a range due to race conditions. */ addWaitForLogRace : function(cmp, index1, index2, content, partialMatch) { var actual; $A.test.addWaitForWithFailureMessage(true, function() { actual = cmp.get("v.log")?cmp.get("v.log")[index2]:undefined; return actual !== undefined; }, "Never received log message '" + content + "' between index " + index1 + " and " + index2, function() { var i; var logs = cmp.get("v.log"); var acc = ''; for (i = index1; i <= index2; i++) { if(partialMatch === true) { if(logs[i].indexOf(content) >= 0) { return; } } else { if (logs[i] === content) { return; } } acc = acc + '\n' + logs[i]; } $A.test.fail("mismatch in log range "+index1+','+index2+ ': did not find '+content+' in:'+acc); } ); }, /** * Wait for a set of log entries that will fall (in order) in a range due to race conditions. * * Unlike wait for log race above, this requires a set of log lines to be in order, but allows then to have * races with other groups of lines. This is useful when you have several sets of actions in paralel, but * want to ensure that a given set is executed in order. */ addWaitForLogRaceOrdered : function(cmp, index1, index2, contentSet, partialMatch) { var actual; $A.test.addWaitForWithFailureMessage(true, function() { actual = cmp.get("v.log")?cmp.get("v.log")[index2]:undefined; return actual !== undefined; }, "Never received log message '" + contentSet + "' between index " + index1 + " and " + index2, function() { var i, j; var logs = cmp.get("v.log"); var acc = ''; for (i = index1, j=0; j < contentSet.length && i <= index2; i++) { if(partialMatch === true) { if(logs[i].indexOf(contentSet[j]) >= 0) { j++; } } else { if (logs[i] === contentSet[j]) { j++; } } acc = acc + '\n' + logs[i]; } if (j === contentSet.length) { return; } $A.test.fail("mismatch in log range "+index1+','+index2+ ': did not find '+contentSet+' in:'+acc); } ); }, /** * Test that we can enqueue and execute client actions. * * Guarantees: * * client action MUST not run immediately. * * client action MAY run after a timeout. * * client action MUST run before render. */ testEnqueueClientAction : { test : [ function(cmp) { //Action is enqueued but not executed var action = cmp.get("c.client"); // FIXME: Ensure that the component is not rendered until after the client action runs. $A.enqueueAction(action); // logging here should always beat enqueueing. cmp.helper.log(cmp, cmp, "log1"); this.addWaitForLog(cmp, 0, "log1"); // the only guarantee is that the client actions should // execute before the render occurs In this case, we should get exactly one rerender. // FIXME: goliver actions-rewrite // Don't know how to check for this. this.addWaitForLog(cmp, 1, "client"); } ] }, /** * Test that we can have more than one foreground actions run in parallel on server. * * max 4 foreground actions can be run in parallel. here we enqueue 4 foreground actions. ask first 3 to wait on * server till 4th arrives, then release them all. * * if enqueue 4 foreground action without releasing any of them, we will run out of available XHR when we want to * enqueue another, no error/warning message on anywhere though, we just put actions in the deferred queue. * * This is dangerous, so we have to ensure that we don't create races. To avoid races, we explicitely chain * our actions using resume and wait. Be careful of deadlocks. */ testMultipleForegroundInFlight : { labels: ["flapper"], test : [ function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "fore1" ], [ "RESUME", "fore1.chain" ], [ "WAIT", "fore1" ], [ "COPY" ] ], "fore1"); }, function(cmp) { this.sendAction(cmp, [], [ [ "WAIT", "fore1.chain"], [ "APPEND", "fore2" ], [ "RESUME", "fore2.chain" ], [ "WAIT", "fore2" ], [ "COPY" ] ], "fore2"); }, function(cmp) { this.sendAction(cmp, [], [ [ "WAIT", "fore2.chain"], [ "APPEND", "fore3" ], [ "RESUME", "fore3.chain" ], [ "WAIT", "fore3" ], [ "COPY" ] ], "fore3"); }, function(cmp) { this.sendAction(cmp, [], [ [ "WAIT", "fore3.chain"], [ "APPEND", "fore4" ], [ "READ" ], [ "APPEND", "fore4.after" ], [ "RESUME", "fore1" ], [ "RESUME", "fore2" ], [ "RESUME", "fore3" ] ], "fore4"); }, function(cmp) { this.addWaitForLogRace(cmp, 0, 3, "fore1: SUCCESS fore4.after"); this.addWaitForLogRace(cmp, 0, 3, "fore2: SUCCESS fore4.after"); this.addWaitForLogRace(cmp, 0, 3, "fore3: SUCCESS fore4.after"); this.addWaitForLogRace(cmp, 0, 3, "fore4: SUCCESS fore1,fore2,fore3,fore4"); } ] }, /** * Test to ensure that caboose actions are not executed until another foreground action is sent. * * Guarantees: * * Caboose action will not be sent until a server side foreground action is enqueued. * * allAboardCallback will be called before the action is sent, but after the foreground action is enqueued * * This test emulates the log+flush pattern that can be used with a combination of caboose actions and allAboard * callbacks. This pattern lets the user queue a caboose action and use allAboardCallback to set a param (in this * case fake log data) to be attached to the action right before the XHR is sent to the server. */ testCabooseActionsWithAllAboardCallback : { test : [ function(cmp) { var that = this; this.sendAction(cmp, [], [ [ "APPEND", "back1" ], [ "READ" ] ], "back1", [ "background" ]); this.sendAction(cmp, [], [ [ "APPEND", "caboose1" ], [ "READ" ] ], "caboose1", [ "caboose", "allaboard" ]); // verify only background action ran this.addWaitForLog(cmp, 0, "back1: SUCCESS back1"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "back2" ], [ "READ" ] ], "back2", [ "background" ]); this.addWaitForLog(cmp, 1, "back2: SUCCESS back2"); }, function(cmp) { // Client actions also should not trigger the caboose. $A.enqueueAction(cmp.get("c.client")); this.addWaitForLog(cmp, 2, "client"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "fore1" ], [ "READ" ] ], "fore1"); // new foreground action should flush out all pending caboose actions this.addWaitForLog(cmp, 3, "caboose1[AllAboard]: NEW"); this.addWaitForLogRace(cmp, 4, 5, "caboose1: SUCCESS caboose1"); this.addWaitForLogRace(cmp, 4, 5, "fore1: SUCCESS fore1"); } ] }, /** * run storable action ('c.execute', param:'WAIT;READ') couple times, make sure we read response from storage * also check storage is updated when new response come from server (we did it by bgAction1/2/etc). * NOTE: from storage point of view, only action def and parameter matters, foreground or background are the same */ testStorableRefresh : { test : [ function(cmp) { //enqueue foreground action(a), ask it to wait on server, till another action (bgAction1) release it. //a is storable, its return 'initial' is stored var that = this; // prime storage this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "prime", [ "storable" ]); this.sendAction(cmp, [], [ [ "APPEND", "initial" ], [ "RESUME", "prime" ] ], "back", [ "background" ]); this.addWaitForLogRace(cmp, 0, 1, "prime: SUCCESS initial"); this.addWaitForLogRace(cmp, 0, 1, "back: SUCCESS "); }, function(cmp) { //fire foreground action(a), because we already have its response('initial') stored, it will just get that. //we also fire background action(bgAction2), it update a's return with a new value, //it will update stored response for a. this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "refresh", [ "storable" ]); this.addWaitForLog(cmp, 2, "refresh[stored]: SUCCESS initial"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "round two" ], [ "RESUME", "prime" ] ], "back", [ "background" ]); this.addWaitForLogRace(cmp, 3, 4, "back: SUCCESS "); this.addWaitForLogRace(cmp, 3, 4, "refresh: SUCCESS round two"); }, function(cmp) { //fire background action(a), it will read response from storage, which is updated by bgAction2 above //fire foreground action, it update response in storage }, function(cmp) { //enqueue foreground action(a) again to double check update from foreAction1 is indeed in storage. //enqueue background action bgAction3 to release a from server, //also update the storage with new response 'theEnd' } ] }, /** * Make sure that we send only one of two duplicate actions enqueued. * * Test this by putting a single value on the buffer, then reading and clearing in both actions. If they * both go to the server, they will have different values. */ testDeDupeStorable : { test : [ function(cmp) { // The storable actions should be 'de-duped', and only one should go to the server. // This is shown by the fact that they will both get the 'initial' that is saved in a buffer. this.sendAction(cmp, [], [ [ "APPEND", "initial" ] ], "setup", [ "background" ]); this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "prime1", [ "storable" ]); this.sendAction(cmp, [], [ [ "WAIT", "prime" ], [ "READ" ] ], "prime2", [ "storable" ]); this.addWaitForLog(cmp, 0, "setup: SUCCESS "); }, function(cmp) { this.sendAction(cmp, [], [ [ "RESUME", "prime" ] ], "release", [ "background" ]); this.addWaitForLogRace(cmp, 1, 3, "release: SUCCESS "); this.addWaitForLogRace(cmp, 1, 3, "prime1: SUCCESS initial"); this.addWaitForLogRace(cmp, 1, 3, "prime2: SUCCESS initial"); } ] }, /** * enqueue two actions, a1(foreground), a2(background) with same action def and param, they run in parallel * make sure they read response from storage first, then update the storage with their responses. * * Note a1&a2 are not both foreground/background, a2 won't become a dupe of a1 */ testParallelStorable : { test : [ function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "initial" ] ], "setup"); this.addWaitForLog(cmp, 0, "setup: SUCCESS "); }, function(cmp) { this.sendAction(cmp, [], [ [ "READ" ] ], "prime", [ "storable" ]); this.addWaitForLog(cmp, 1, "prime: SUCCESS initial"); }, function(cmp) { this.sendAction(cmp, [], [ [ "APPEND", "second" ] ], "setup2"); this.addWaitForLog(cmp, 2, "setup2: SUCCESS "); }, function(cmp) { this.sendAction(cmp, [], [ [ "READ" ] ], "retrieve-fore", [ "storable" ]); this.sendAction(cmp, [], [ [ "READ" ] ], "retrieve-back", [ "storable", "background" ]); // both callbacks with stored value executed. These should be executed _before_ any refreshes go out. this.addWaitForLogRace(cmp, 3, 4, "retrieve-fore[stored]: SUCCESS initial"); this.addWaitForLogRace(cmp, 3, 4, "retrieve-back[stored]: SUCCESS initial"); //last param=true:we only check partial match this.addWaitForLogRace(cmp, 5, 6, "retrieve-fore: SUCCESS ", true); this.addWaitForLogRace(cmp, 5, 6, "retrieve-back: SUCCESS ", true); } ] }, /** * Check that an abortable action is aborted prior to send. */ testAbortAbortablePriorToSend : { test : [ function(cmp) { $A.test.blockForegroundRequests(); this.sendAction(cmp, [ "child1" ], [ [ "APPEND", "value" ], [ "READ" ] ], "aborted", [ "abortable" ]); // return to top so that the action gets queued up. }, function(cmp) { cmp.helper.deleteChild(cmp, "child1"); }, function(cmp) { $A.test.releaseForegroundRequests(); this.addWaitForLog(cmp, 0, "aborted: ABORTED undefined"); } ] }, /** * Check that an abortable action is aborted after send. */ testAbortAbortableAfterSend : { test : [ function(cmp) { this.sendAction(cmp, [ "child1" ], [ [ "WAIT", "release" ], [ "APPEND", "value" ], [ "READ" ] ], "aborted", [ "abortable" ]); // make sure we sent the action. $A.test.addWaitFor(false, function() { return $A.test.isActionQueued(); }) }, function(cmp) { var old = cmp.find("child1"); cmp.helper.deleteChild(cmp, "child1"); // Make sure that the component is gone before we release. $A.test.addWaitFor(false, function() { return old.isValid(); }) }, function(cmp) { this.sendAction(cmp, [ ], [ [ "RESUME", "release" ] ], "release"); this.addWaitForLogRace(cmp, 0, 1, "aborted: ABORTED value"); this.addWaitForLogRace(cmp, 0, 1, "release: SUCCESS "); } ] }, /** * Check that a non-abortable action is not aborted prior to send. */ testAbortNonAbortableNotPriorToSend : { test : [ function(cmp) { $A.test.blockForegroundRequests(); this.sendAction(cmp, [ "child1" ], [ [ "APPEND", "value" ], [ "READ" ] ], "aborted"); // return to top so that the action gets queued up. }, function(cmp) { cmp.helper.deleteChild(cmp, "child1"); }, function(cmp) { $A.test.releaseForegroundRequests(); this.addWaitForLog(cmp, 0, "aborted: ABORTED value"); } ] }, /** * Check that an abortable action is aborted prior to send. */ testAbortNonAbortableAfterSend : { test : [ function(cmp) { this.sendAction(cmp, [ "child1" ], [ [ "WAIT", "release" ], [ "APPEND", "value" ], [ "READ" ] ], "aborted", [ "abortable" ]); }, function(cmp) { var old = cmp.find("child1"); cmp.helper.deleteChild(cmp, "child1"); // Make sure that the component is gone before we release. $A.test.addWaitFor(false, function() { return old.isValid(); }); }, function(cmp) { this.sendAction(cmp, [ ], [ [ "RESUME", "release" ] ], "release"); this.addWaitForLogRace(cmp, 0, 1, "aborted: ABORTED value"); this.addWaitForLogRace(cmp, 0, 1, "release: SUCCESS "); } ] }, /////////////////////////////////////////////////////////////////////// // runActions /////////////////////////////////////////////////////////////////////// testSimpleRunActions : { test : [ function(cmp) { var helper = cmp.helper; $A.clientService.runActions([ helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "a" ], ["READ"] ]), "first") ], this, function() { cmp.helper.log(cmp, cmp, "group1"); }); }, function(cmp) { var helper = cmp.helper; $A.clientService.runActions([ helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "b1" ], ["READ"] ]), "second"), helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "b2" ], ["READ"] ]), "second") ], this, function() { cmp.helper.log(cmp, cmp, "group2"); }); }, function(cmp) { var helper = cmp.helper; $A.clientService.runActions([ helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "c1" ], ["READ"] ]), "third"), helper.getAction(cmp, cmp, this.buildCommands(cmp, [ [ "APPEND", "c2" ], ["READ"] ]), "third") ], this, function() { cmp.helper.log(cmp, cmp, "group3"); }); }, function(cmp) { this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "first: SUCCESS a", "group1" ] ); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "second: SUCCESS b1", "group2" ]); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "second: SUCCESS b2", "group2" ]); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "third: SUCCESS c1", "group3" ]); this.addWaitForLogRaceOrdered(cmp, 0, 7, [ "third: SUCCESS c2", "group3" ]); }] } })
badlogicmanpreet/aura
aura-components/src/test/components/clientServiceTest/enqueueAction/enqueueActionTest.js
JavaScript
apache-2.0
25,099
/* * Copyright 2010-2011 Raisonne Techonologies. * * 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.raisonne.quartz.scheduler.job.service.impl; /** * <p>A helper class which is responsible for fetching list of all jobs * under a certain group as well individual jobs matching search criteria.</p> * <p> * Triggers associated with the * </p> * @author Umesh Awasthi * * */ public class JobUtil { }
umeshawasthi/blooddonor
src/main/java/com/raisonne/quartz/scheduler/job/service/impl/JobUtil.java
Java
apache-2.0
935
package ftp.v4; import java.io.IOException; import java.nio.file.attribute.UserPrincipalLookupService; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.sshd.common.file.util.BaseFileSystem; import org.apache.sshd.common.file.util.ImmutableList; public class My4FileSystem extends BaseFileSystem<My4Path> { public My4FileSystem(My4FileSystemProvider fileSystemProvider) { super(fileSystemProvider); System.out.println("My4FileSystem constructor()"); } @Override protected My4Path create(String root, ImmutableList<String> names) { System.out.println("My4FileSystem create(); root=" + root + " ; names=" + names); return new My4Path(this, root, names); } @Override public void close() throws IOException { System.out.println("My4FileSystem close()"); } @Override public boolean isOpen() { System.out.println("My4FileSystem isOpen()"); return true; } @Override public Set<String> supportedFileAttributeViews() { System.out.println("My4FileSystem supportedFileAttributeViews()"); return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("posix"))); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { System.out.println("My4FileSystem getUserPrincipalLookupService()"); throw new UnsupportedOperationException("My4FileSystem getUserPrincipalLookupService()"); } }
innocentliny/SFTP_demo
v4/My4FileSystem.java
Java
apache-2.0
1,470
/* * Copyright 2011 Gian Perrone * * 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 de.hhu.jversionnumberer.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation marks interfaces which are intended to be subclassed by * clients of the API and as such break binary compatibility when e.g. methods * are added. * * @author Gian Perrone */ @Documented @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) public @interface ImplementableByClient { }
bendisposto/JVersionNumberer
JVersionNumberer/src/main/java/de/hhu/jversionnumberer/annotations/ImplementableByClient.java
Java
apache-2.0
1,173
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; /** * Lévy distribution median. * * @module @stdlib/stats/base/dists/levy/median * * @example * var median = require( '@stdlib/stats/base/dists/levy/median' ); * * var y = median( 0.0, 1.0 ); * // returns ~2.198 * * y = median( 4.0, 2.0 ); * // returns ~8.396 */ // MODULES // var median = require( './median.js' ); // EXPORTS // module.exports = median;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/levy/median/lib/index.js
JavaScript
apache-2.0
994
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class UpdateUserTableForOauthSupport extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasColumn('user', 'oauth_provider')) { Schema::table( 'user', function (Blueprint $t){ $t->string('oauth_provider', 50)->nullable()->after('remember_token'); } ); } Schema::create( 'oauth_config', function (Blueprint $t){ $t->integer('service_id')->unsigned()->primary(); $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade'); $t->integer('default_role')->unsigned()->nullable(); // previously set to 'restrict' which isn't supported by all databases // removing the onDelete clause gets the same behavior as No Action and Restrict are defaults. $t->foreign('default_role')->references('id')->on('role'); $t->string('client_id'); $t->longText('client_secret'); $t->string('redirect_url'); $t->string('icon_class')->nullable(); } ); } /** * Reverse the migrations. * * @return void */ public function down() { if (Schema::hasColumn('user', 'oauth_provider')) { Schema::table( 'user', function (Blueprint $t){ $t->dropColumn('oauth_provider'); } ); } Schema::dropIfExists('oauth_config'); } }
dreamfactorysoftware/df-oauth
database/migrations/2015_05_02_134911_update_user_table_for_oauth_support.php
PHP
apache-2.0
1,764
# Copyright 2015 Google Inc. # # 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. from __future__ import absolute_import from rigour.errors import ValidationFailed from rigour.types import * from rigour.constraints import length_between import rigour import pytest def test_secrecy_declared_before(): t = String().secret().constrain(length_between(4,6)) with pytest.raises(ValidationFailed) as excinfo: t.check("xxx") message = str(excinfo) assert "xxx" not in message def test_secrecy_declared_after(): t = String().constrain(length_between(4,6)).secret() with pytest.raises(ValidationFailed) as excinfo: t.check("xxx") message = str(excinfo) assert "xxx" not in message
steinarvk/rigour
rigour/tests/test_secrecy.py
Python
apache-2.0
1,198
package service.handler.twostep; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.net.Socket; import java.security.KeyPair; import java.security.PublicKey; import java.security.SignatureException; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import message.Operation; import message.twostep.csn.*; import service.Config; import service.Key; import service.KeyManager; import service.handler.ConnectionHandler; import utility.Utils; /** * * @author Scott */ public class CSNHandler extends ConnectionHandler { public static final File ATTESTATION; private static final ReentrantLock LOCK; private static int CSN; static { ATTESTATION = new File(Config.ATTESTATION_DIR_PATH + "/service-provider/csn"); LOCK = new ReentrantLock(); CSN = 0; } public CSNHandler(Socket socket, KeyPair keyPair) { super(socket, keyPair); } @Override protected void handle(DataOutputStream out, DataInputStream in) throws SignatureException, IllegalAccessException { PublicKey clientPubKey = KeyManager.getInstance().getPublicKey(Key.CLIENT); try { Request req = Request.parse(Utils.receive(in)); LOCK.lock(); if (!req.validate(clientPubKey)) { throw new SignatureException("REQ validation failure"); } String result; Operation op = req.getOperation(); File file = new File(Config.DATA_DIR_PATH + '/' + op.getPath()); boolean sendFileAfterAck = false; if (req.getConsecutiveSequenceNumber() == CSN + 1) { CSN += 1; switch (op.getType()) { case UPLOAD: file = new File(Config.DOWNLOADS_DIR_PATH + '/' + op.getPath()); Utils.receive(in, file); String digest = Utils.digest(file); if (op.getMessage().compareTo(digest) == 0) { result = "ok"; } else { result = "upload fail"; } Utils.writeDigest(file.getPath(), digest); break; case AUDIT: file = new File(op.getPath()); result = Utils.readDigest(file.getPath()); sendFileAfterAck = true; break; case DOWNLOAD: result = Utils.readDigest(file.getPath()); sendFileAfterAck = true; break; default: result = "operation type mismatch"; } } else { result = "CSN mismatch"; } Acknowledgement ack = new Acknowledgement(result, req); ack.sign(keyPair); Utils.send(out, ack.toString()); if (sendFileAfterAck) { Utils.send(out, file); } Utils.appendAndDigest(ATTESTATION, ack.toString() + '\n'); } finally { if (LOCK != null) { LOCK.unlock(); } } } }
CloudComLab/Voting-CAP
src/service/handler/twostep/CSNHandler.java
Java
apache-2.0
3,838
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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. """ The No Age scheduler is based on the Heapset scheduler, though it does not take age into account. .. warning:: This scheduler does not take the age into account, making it **unusable** in simulations where the *timeAdvance* function can return (exactly) 0. If unsure, do **not** use this scheduler, but the more general Heapset scheduler. The heap will contain only the timestamps of events that should happen. One of the dictionaries will contain the actual models that transition at the specified time. The second dictionary than contains a reverse relation: it maps the models to their time_next. This reverse relation is necessary to know the *old* time_next value of the model. Because as soon as the model has its time_next changed, its previously scheduled time will be unknown. This 'previous time' is **not** equal to the *timeLast*, as it might be possible that the models wait time was interrupted. For a schedule, the model is added to the dictionary at the specified time_next. In case it is the first element at this location in the dictionary, we also add the timestamp to the heap. This way, the heap only contains *unique* timestamps and thus the actual complexity is reduced to the number of *different* timestamps. Furthermore, the reverse relation is also updated. Unscheduling is done similarly by simply removing the element from the dictionary. Rescheduling is a slight optimisation of unscheduling, followed by scheduling. This scheduler does still schedule models that are inactive (their time_next is infinity), though this does not influence the complexity. The complexity is not affected due to infinity being a single element in the heap that is always present. Since a heap has O(log(n)) complexity, this one additional element does not have a serious impact. The main advantage over the Activity Heap is that it never gets dirty and thus doesn't require periodical cleanup. The only part that gets dirty is the actual heap, which only contains small tuples. Duplicates of these will also be reduced to a single element, thus memory consumption should not be a problem in most cases. This scheduler is ideal in situations where most transitions happen at exactly the same time, as we can then profit from the internal structure and simply return the mapped elements. It results in sufficient efficiency in most other cases, mainly due to the code base being a lot smaller then the Activity Heap. """ from heapq import heappush, heappop from pypdevs.logger import * class SchedulerNA(object): """ Scheduler class itself """ def __init__(self, models, epsilon, total_models): """ Constructor :param models: all models in the simulation """ self.heap = [] self.reverse = [None] * total_models self.mapped = {} self.infinite = float('inf') # Init the basic 'inactive' entry here, to prevent scheduling in the heap itself self.mapped[self.infinite] = set() self.epsilon = epsilon for m in models: self.schedule(m) def schedule(self, model): """ Schedule a model :param model: the model to schedule """ try: self.mapped[model.time_next[0]].add(model) except KeyError: self.mapped[model.time_next[0]] = set([model]) heappush(self.heap, model.time_next[0]) try: self.reverse[model.model_id] = model.time_next[0] except IndexError: self.reverse.append(model.time_next[0]) def unschedule(self, model): """ Unschedule a model :param model: model to unschedule """ try: self.mapped[self.reverse[model.model_id]].remove(model) except KeyError: pass self.reverse[model.model_id] = None def massReschedule(self, reschedule_set): """ Reschedule all models provided. Equivalent to calling unschedule(model); schedule(model) on every element in the iterable. :param reschedule_set: iterable containing all models to reschedule """ #NOTE the usage of exceptions is a lot better for the PyPy JIT and nets a noticable speedup # as the JIT generates guard statements for an 'if' for model in reschedule_set: model_id = model.model_id try: self.mapped[self.reverse[model_id]].remove(model) except KeyError: # Element simply not present, so don't need to unschedule it pass self.reverse[model_id] = tn = model.time_next[0] try: self.mapped[tn].add(model) except KeyError: # Create a tuple with a single entry and use it to initialize the mapped entry self.mapped[tn] = set((model, )) heappush(self.heap, tn) def readFirst(self): """ Returns the time of the first model that has to transition :returns: timestamp of the first model """ first = self.heap[0] while len(self.mapped[first]) == 0: del self.mapped[first] heappop(self.heap) first = self.heap[0] # The age was stripped of return (first, 1) def getImminent(self, time): """ Returns a list of all models that transition at the provided time, with the specified epsilon deviation allowed. :param time: timestamp to check for models .. warning:: For efficiency, this method only checks the **first** elements, so trying to invoke this function with a timestamp higher than the value provided with the *readFirst* method, will **always** return an empty set. """ t, age = time imm_children = set() try: first = self.heap[0] if (abs(first - t) < self.epsilon): #NOTE this would change the original set, though this doesn't matter as it is no longer used imm_children = self.mapped.pop(first) heappop(self.heap) first = self.heap[0] while (abs(first - t) < self.epsilon): imm_children |= self.mapped.pop(first) heappop(self.heap) first = self.heap[0] except IndexError: pass return imm_children
kdheepak89/pypdevs
pypdevs/schedulers/schedulerNA.py
Python
apache-2.0
7,125
// Copyright 2010 Google Inc. // // 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. #include "Diadem/Test/WindowTestBase.h" #include "Diadem/Binding.h" #include "Diadem/Value.h" class TestBindings : public WindowTestBase {}; TEST_F(TestBindings, testRemoveObserver) { class Ob : public Diadem::ValueObserver { public: Ob() : observe_count_(0) {} void ObserveImp(const char*, const Diadem::Value&) { ++observe_count_; } unsigned int observe_count_; }; Diadem::ChangeMessenger messenger; Ob ob1, ob2; Diadem::Value v; EXPECT_EQ(0, ob1.observe_count_); EXPECT_EQ(0, ob2.observe_count_); messenger.AddObserver("", &ob1); messenger.AddObserver("a", &ob2); messenger.NotifyChange("", v); EXPECT_EQ(1, ob1.observe_count_); EXPECT_EQ(0, ob2.observe_count_); messenger.NotifyChange("a", v); EXPECT_EQ(2, ob1.observe_count_); EXPECT_EQ(1, ob2.observe_count_); messenger.RemoveObserver(&ob1); messenger.NotifyChange("", v); EXPECT_EQ(2, ob1.observe_count_); EXPECT_EQ(1, ob2.observe_count_); messenger.NotifyChange("a", v); EXPECT_EQ(2, ob1.observe_count_); EXPECT_EQ(2, ob2.observe_count_); messenger.RemoveObserver(&ob2); messenger.NotifyChange("a", v); EXPECT_EQ(2, ob1.observe_count_); EXPECT_EQ(2, ob2.observe_count_); } TEST_F(TestBindings, testValueToEnable) { ReadWindowData( "<window text='testValueToEnable'>" "<label text='Label' name='label'>" "<bind source='check' prop='enabled'/>" "</label>" "<check title='Check' name='check'/>" "</window>"); ASSERT_EQ(2, windowRoot_->ChildrenCount()); Diadem::Entity *label = windowRoot_->FindByName("label"); Diadem::Entity *checkbox = windowRoot_->FindByName("check"); ASSERT_EQ(1, label->ChildrenCount()); Diadem::Binding *binding = dynamic_cast<Diadem::Binding*>(label->ChildAt(0)); ASSERT_FALSE(binding == NULL); const Diadem::EntityController &controller = binding->GetController(); EXPECT_EQ(label, controller.GetEntity()); EXPECT_STREQ("enabled", controller.GetPropertyName()); EXPECT_EQ(0, checkbox->GetProperty(Diadem::kPropValue).Coerce<int32_t>()); EXPECT_FALSE(label->GetProperty(Diadem::kPropEnabled).Coerce<bool>()); checkbox->SetProperty(Diadem::kPropValue, 1); EXPECT_TRUE(label->GetProperty(Diadem::kPropEnabled).Coerce<bool>()); }
Uncommon/diadem
Test/BindingTest.cc
C++
apache-2.0
2,858
/* * (C) Copyright IBM Corp. 2019, 2020. * * 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.ibm.watson.visual_recognition.v4.model; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import com.ibm.cloud.sdk.core.service.model.GenericModel; import java.util.ArrayList; import java.util.List; /** The addImages options. */ public class AddImagesOptions extends GenericModel { protected String collectionId; protected List<FileWithMetadata> imagesFile; protected List<String> imageUrl; protected String trainingData; /** Builder. */ public static class Builder { private String collectionId; private List<FileWithMetadata> imagesFile; private List<String> imageUrl; private String trainingData; private Builder(AddImagesOptions addImagesOptions) { this.collectionId = addImagesOptions.collectionId; this.imagesFile = addImagesOptions.imagesFile; this.imageUrl = addImagesOptions.imageUrl; this.trainingData = addImagesOptions.trainingData; } /** Instantiates a new builder. */ public Builder() {} /** * Instantiates a new builder with required properties. * * @param collectionId the collectionId */ public Builder(String collectionId) { this.collectionId = collectionId; } /** * Builds a AddImagesOptions. * * @return the new AddImagesOptions instance */ public AddImagesOptions build() { return new AddImagesOptions(this); } /** * Adds an imagesFile to imagesFile. * * @param imagesFile the new imagesFile * @return the AddImagesOptions builder */ public Builder addImagesFile(FileWithMetadata imagesFile) { com.ibm.cloud.sdk.core.util.Validator.notNull(imagesFile, "imagesFile cannot be null"); if (this.imagesFile == null) { this.imagesFile = new ArrayList<FileWithMetadata>(); } this.imagesFile.add(imagesFile); return this; } /** * Adds an imageUrl to imageUrl. * * @param imageUrl the new imageUrl * @return the AddImagesOptions builder */ public Builder addImageUrl(String imageUrl) { com.ibm.cloud.sdk.core.util.Validator.notNull(imageUrl, "imageUrl cannot be null"); if (this.imageUrl == null) { this.imageUrl = new ArrayList<String>(); } this.imageUrl.add(imageUrl); return this; } /** * Set the collectionId. * * @param collectionId the collectionId * @return the AddImagesOptions builder */ public Builder collectionId(String collectionId) { this.collectionId = collectionId; return this; } /** * Set the imagesFile. Existing imagesFile will be replaced. * * @param imagesFile the imagesFile * @return the AddImagesOptions builder */ public Builder imagesFile(List<FileWithMetadata> imagesFile) { this.imagesFile = imagesFile; return this; } /** * Set the imageUrl. Existing imageUrl will be replaced. * * @param imageUrl the imageUrl * @return the AddImagesOptions builder */ public Builder imageUrl(List<String> imageUrl) { this.imageUrl = imageUrl; return this; } /** * Set the trainingData. * * @param trainingData the trainingData * @return the AddImagesOptions builder */ public Builder trainingData(String trainingData) { this.trainingData = trainingData; return this; } } protected AddImagesOptions(Builder builder) { com.ibm.cloud.sdk.core.util.Validator.notEmpty( builder.collectionId, "collectionId cannot be empty"); collectionId = builder.collectionId; imagesFile = builder.imagesFile; imageUrl = builder.imageUrl; trainingData = builder.trainingData; } /** * New builder. * * @return a AddImagesOptions builder */ public Builder newBuilder() { return new Builder(this); } /** * Gets the collectionId. * * <p>The identifier of the collection. * * @return the collectionId */ public String collectionId() { return collectionId; } /** * Gets the imagesFile. * * <p>An array of image files (.jpg or .png) or .zip files with images. - Include a maximum of 20 * images in a request. - Limit the .zip file to 100 MB. - Limit each image file to 10 MB. * * <p>You can also include an image with the **image_url** parameter. * * @return the imagesFile */ public List<FileWithMetadata> imagesFile() { return imagesFile; } /** * Gets the imageUrl. * * <p>The array of URLs of image files (.jpg or .png). - Include a maximum of 20 images in a * request. - Limit each image file to 10 MB. - Minimum width and height is 30 pixels, but the * service tends to perform better with images that are at least 300 x 300 pixels. Maximum is 5400 * pixels for either height or width. * * <p>You can also include images with the **images_file** parameter. * * @return the imageUrl */ public List<String> imageUrl() { return imageUrl; } /** * Gets the trainingData. * * <p>Training data for a single image. Include training data only if you add one image with the * request. * * <p>The `object` property can contain alphanumeric, underscore, hyphen, space, and dot * characters. It cannot begin with the reserved prefix `sys-` and must be no longer than 32 * characters. * * @return the trainingData */ public String trainingData() { return trainingData; } }
watson-developer-cloud/java-sdk
visual-recognition/src/main/java/com/ibm/watson/visual_recognition/v4/model/AddImagesOptions.java
Java
apache-2.0
6,096
#ifndef USE_LIBSASS_SRC #include "../../libsass_src/src/settings.hpp" #endif
tischda/hugo-search
vendor/github.com/bep/golibsass/internal/libsass/settings.hpp
C++
apache-2.0
77
using System.ComponentModel; using System.Windows.Forms; namespace BulkCrapUninstaller.Forms { partial class DebugWindow { /// <summary> /// Required designer variable. /// </summary> private IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.button2 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.button5 = new System.Windows.Forms.Button(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.buttonGoMessages = new System.Windows.Forms.Button(); this.numericUpDownMessages = new System.Windows.Forms.NumericUpDown(); this.textBoxMessages = new System.Windows.Forms.TextBox(); this.comboBoxMessages = new System.Windows.Forms.ComboBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.labelVersion = new System.Windows.Forms.Label(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.checkBoxDebug = new System.Windows.Forms.CheckBox(); this.checkBox2 = new System.Windows.Forms.CheckBox(); this.groupBox6 = new System.Windows.Forms.GroupBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.button10 = new System.Windows.Forms.Button(); this.button11 = new System.Windows.Forms.Button(); this.button12 = new System.Windows.Forms.Button(); this.button13 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.button7 = new System.Windows.Forms.Button(); this.button8 = new System.Windows.Forms.Button(); this.button9 = new System.Windows.Forms.Button(); this.button14 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox3.SuspendLayout(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownMessages)).BeginInit(); this.groupBox4.SuspendLayout(); this.groupBox5.SuspendLayout(); this.groupBox6.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.checkBox1); this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.button1); this.groupBox1.Controls.Add(this.button5); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Bottom; this.groupBox1.Location = new System.Drawing.Point(7, 335); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(6); this.groupBox1.Size = new System.Drawing.Size(489, 50); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Settings"; // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Dock = System.Windows.Forms.DockStyle.Left; this.checkBox1.Location = new System.Drawing.Point(301, 19); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(118, 25); this.checkBox1.TabIndex = 1; this.checkBox1.Text = "Test setting binding"; this.checkBox1.UseVisualStyleBackColor = true; // // button2 // this.button2.AutoSize = true; this.button2.Dock = System.Windows.Forms.DockStyle.Left; this.button2.Location = new System.Drawing.Point(207, 19); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(94, 25); this.button2.TabIndex = 0; this.button2.Text = "External change"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button1 // this.button1.AutoSize = true; this.button1.Dock = System.Windows.Forms.DockStyle.Left; this.button1.Location = new System.Drawing.Point(127, 19); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(80, 25); this.button1.TabIndex = 2; this.button1.Text = "Force update"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click_1); // // button5 // this.button5.AutoSize = true; this.button5.Dock = System.Windows.Forms.DockStyle.Left; this.button5.Location = new System.Drawing.Point(6, 19); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(121, 25); this.button5.TabIndex = 3; this.button5.Text = "Open settings window"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); // // groupBox3 // this.groupBox3.Controls.Add(this.panel1); this.groupBox3.Controls.Add(this.comboBoxMessages); this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox3.Location = new System.Drawing.Point(7, 89); this.groupBox3.Name = "groupBox3"; this.groupBox3.Padding = new System.Windows.Forms.Padding(6); this.groupBox3.Size = new System.Drawing.Size(489, 196); this.groupBox3.TabIndex = 3; this.groupBox3.TabStop = false; this.groupBox3.Text = "Test message boxes"; // // panel1 // this.panel1.Controls.Add(this.panel2); this.panel1.Controls.Add(this.textBoxMessages); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(6, 40); this.panel1.Name = "panel1"; this.panel1.Padding = new System.Windows.Forms.Padding(0, 6, 0, 0); this.panel1.Size = new System.Drawing.Size(477, 150); this.panel1.TabIndex = 1; // // panel2 // this.panel2.Controls.Add(this.buttonGoMessages); this.panel2.Controls.Add(this.numericUpDownMessages); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(397, 6); this.panel2.Name = "panel2"; this.panel2.Padding = new System.Windows.Forms.Padding(6, 0, 0, 0); this.panel2.Size = new System.Drawing.Size(80, 144); this.panel2.TabIndex = 3; // // buttonGoMessages // this.buttonGoMessages.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonGoMessages.Location = new System.Drawing.Point(6, 20); this.buttonGoMessages.Name = "buttonGoMessages"; this.buttonGoMessages.Size = new System.Drawing.Size(74, 124); this.buttonGoMessages.TabIndex = 1; this.buttonGoMessages.Text = "Open messagebox"; this.buttonGoMessages.UseVisualStyleBackColor = true; this.buttonGoMessages.Click += new System.EventHandler(this.buttonGoMessages_Click); // // numericUpDownMessages // this.numericUpDownMessages.Dock = System.Windows.Forms.DockStyle.Top; this.numericUpDownMessages.Location = new System.Drawing.Point(6, 0); this.numericUpDownMessages.Name = "numericUpDownMessages"; this.numericUpDownMessages.Size = new System.Drawing.Size(74, 20); this.numericUpDownMessages.TabIndex = 3; // // textBoxMessages // this.textBoxMessages.Dock = System.Windows.Forms.DockStyle.Left; this.textBoxMessages.Location = new System.Drawing.Point(0, 6); this.textBoxMessages.Multiline = true; this.textBoxMessages.Name = "textBoxMessages"; this.textBoxMessages.Size = new System.Drawing.Size(397, 144); this.textBoxMessages.TabIndex = 2; this.textBoxMessages.Text = "Text to send to the messagebox\r\nSecond line if the box takes multiple lines\r\nIf m" + "essagebox needs a number it takes it from the number box on right"; // // comboBoxMessages // this.comboBoxMessages.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.comboBoxMessages.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.comboBoxMessages.Dock = System.Windows.Forms.DockStyle.Top; this.comboBoxMessages.FormattingEnabled = true; this.comboBoxMessages.Location = new System.Drawing.Point(6, 19); this.comboBoxMessages.Name = "comboBoxMessages"; this.comboBoxMessages.Size = new System.Drawing.Size(477, 21); this.comboBoxMessages.TabIndex = 0; // // groupBox4 // this.groupBox4.Controls.Add(this.labelVersion); this.groupBox4.Controls.Add(this.button3); this.groupBox4.Controls.Add(this.button4); this.groupBox4.Dock = System.Windows.Forms.DockStyle.Bottom; this.groupBox4.Location = new System.Drawing.Point(7, 285); this.groupBox4.Name = "groupBox4"; this.groupBox4.Padding = new System.Windows.Forms.Padding(6); this.groupBox4.Size = new System.Drawing.Size(489, 50); this.groupBox4.TabIndex = 4; this.groupBox4.TabStop = false; this.groupBox4.Text = "Update system"; // // labelVersion // this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill; this.labelVersion.Location = new System.Drawing.Point(185, 19); this.labelVersion.Name = "labelVersion"; this.labelVersion.Size = new System.Drawing.Size(298, 25); this.labelVersion.TabIndex = 3; this.labelVersion.Text = "remote version"; this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // button3 // this.button3.AutoSize = true; this.button3.Dock = System.Windows.Forms.DockStyle.Left; this.button3.Location = new System.Drawing.Point(110, 19); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 25); this.button3.TabIndex = 2; this.button3.Text = "Download"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.AutoSize = true; this.button4.Dock = System.Windows.Forms.DockStyle.Left; this.button4.Location = new System.Drawing.Point(6, 19); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(104, 25); this.button4.TabIndex = 0; this.button4.Text = "Check for updates"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // groupBox5 // this.groupBox5.Controls.Add(this.checkBoxDebug); this.groupBox5.Controls.Add(this.checkBox2); this.groupBox5.Dock = System.Windows.Forms.DockStyle.Bottom; this.groupBox5.Location = new System.Drawing.Point(7, 385); this.groupBox5.Name = "groupBox5"; this.groupBox5.Padding = new System.Windows.Forms.Padding(6); this.groupBox5.Size = new System.Drawing.Size(489, 50); this.groupBox5.TabIndex = 5; this.groupBox5.TabStop = false; this.groupBox5.Text = "Misc"; // // checkBoxDebug // this.checkBoxDebug.AutoSize = true; this.checkBoxDebug.Dock = System.Windows.Forms.DockStyle.Left; this.checkBoxDebug.Location = new System.Drawing.Point(148, 19); this.checkBoxDebug.Name = "checkBoxDebug"; this.checkBoxDebug.Size = new System.Drawing.Size(121, 25); this.checkBoxDebug.TabIndex = 1; this.checkBoxDebug.Text = "Enable debug mode"; this.checkBoxDebug.UseVisualStyleBackColor = true; // // checkBox2 // this.checkBox2.AutoSize = true; this.checkBox2.Dock = System.Windows.Forms.DockStyle.Left; this.checkBox2.Location = new System.Drawing.Point(6, 19); this.checkBox2.Name = "checkBox2"; this.checkBox2.Size = new System.Drawing.Size(142, 25); this.checkBox2.TabIndex = 0; this.checkBox2.Text = "Override BCU is installed"; this.checkBox2.UseVisualStyleBackColor = true; this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged); // // groupBox6 // this.groupBox6.Controls.Add(this.flowLayoutPanel1); this.groupBox6.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox6.Location = new System.Drawing.Point(7, 7); this.groupBox6.Name = "groupBox6"; this.groupBox6.Padding = new System.Windows.Forms.Padding(6); this.groupBox6.Size = new System.Drawing.Size(489, 82); this.groupBox6.TabIndex = 6; this.groupBox6.TabStop = false; this.groupBox6.Text = "Test methods"; // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoSize = true; this.flowLayoutPanel1.Controls.Add(this.button10); this.flowLayoutPanel1.Controls.Add(this.button11); this.flowLayoutPanel1.Controls.Add(this.button12); this.flowLayoutPanel1.Controls.Add(this.button13); this.flowLayoutPanel1.Controls.Add(this.button6); this.flowLayoutPanel1.Controls.Add(this.button7); this.flowLayoutPanel1.Controls.Add(this.button8); this.flowLayoutPanel1.Controls.Add(this.button9); this.flowLayoutPanel1.Controls.Add(this.button14); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(6, 19); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(477, 57); this.flowLayoutPanel1.TabIndex = 1; // // button10 // this.button10.AutoSize = true; this.button10.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button10.Location = new System.Drawing.Point(3, 3); this.button10.Name = "button10"; this.button10.Size = new System.Drawing.Size(105, 23); this.button10.TabIndex = 7; this.button10.Text = "Test junk searcher"; this.button10.UseVisualStyleBackColor = true; this.button10.Click += new System.EventHandler(this.TestJunkSearcher); // // button11 // this.button11.AutoSize = true; this.button11.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button11.Location = new System.Drawing.Point(114, 3); this.button11.Name = "button11"; this.button11.Size = new System.Drawing.Size(137, 23); this.button11.TabIndex = 6; this.button11.Text = "Crash background thread"; this.button11.UseVisualStyleBackColor = true; this.button11.Click += new System.EventHandler(this.TestCrashBackgroundThread); // // button12 // this.button12.AutoSize = true; this.button12.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button12.Location = new System.Drawing.Point(257, 3); this.button12.Name = "button12"; this.button12.Size = new System.Drawing.Size(88, 23); this.button12.TabIndex = 5; this.button12.Text = "Crash ui thread"; this.button12.UseVisualStyleBackColor = true; this.button12.Click += new System.EventHandler(this.TestCrashUiThread); // // button13 // this.button13.AutoSize = true; this.button13.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button13.Location = new System.Drawing.Point(351, 3); this.button13.Name = "button13"; this.button13.Size = new System.Drawing.Size(117, 23); this.button13.TabIndex = 4; this.button13.Text = "Finish collecting stats"; this.button13.UseVisualStyleBackColor = true; this.button13.Click += new System.EventHandler(this.button13_Click); // // button6 // this.button6.AutoSize = true; this.button6.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button6.Location = new System.Drawing.Point(3, 32); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(67, 23); this.button6.TabIndex = 8; this.button6.Text = "Send stats"; this.button6.UseVisualStyleBackColor = true; this.button6.Click += new System.EventHandler(this.button6_Click); // // button7 // this.button7.AutoSize = true; this.button7.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button7.Location = new System.Drawing.Point(76, 32); this.button7.Name = "button7"; this.button7.Size = new System.Drawing.Size(72, 23); this.button7.TabIndex = 9; this.button7.Text = "Restart app"; this.button7.UseVisualStyleBackColor = true; this.button7.Click += new System.EventHandler(this.button7_Click); // // button8 // this.button8.AutoSize = true; this.button8.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button8.Location = new System.Drawing.Point(154, 32); this.button8.Name = "button8"; this.button8.Size = new System.Drawing.Size(84, 23); this.button8.TabIndex = 10; this.button8.Text = "Get hotkey list"; this.button8.UseVisualStyleBackColor = true; this.button8.Click += new System.EventHandler(this.button8_Click); // // button9 // this.button9.AutoSize = true; this.button9.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button9.Location = new System.Drawing.Point(244, 32); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(65, 23); this.button9.TabIndex = 11; this.button9.Text = "Soft crash"; this.button9.UseVisualStyleBackColor = true; this.button9.Click += new System.EventHandler(this.SoftCrash); // // button14 // this.button14.AutoSize = true; this.button14.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.button14.Location = new System.Drawing.Point(315, 32); this.button14.Name = "button14"; this.button14.Size = new System.Drawing.Size(85, 23); this.button14.TabIndex = 12; this.button14.Text = "Feedback box"; this.button14.UseVisualStyleBackColor = true; this.button14.Click += new System.EventHandler(this.button14_Click); // // DebugWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(503, 442); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox6); this.Controls.Add(this.groupBox5); this.Name = "DebugWindow"; this.Padding = new System.Windows.Forms.Padding(7); this.Text = "DebugWindow (here be dragons)"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox3.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownMessages)).EndInit(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.groupBox6.ResumeLayout(false); this.groupBox6.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private GroupBox groupBox1; private CheckBox checkBox1; private Button button2; private Button button1; private GroupBox groupBox3; private TextBox textBoxMessages; private Button buttonGoMessages; private ComboBox comboBoxMessages; private NumericUpDown numericUpDownMessages; private GroupBox groupBox4; private Label labelVersion; private Button button3; private Button button4; private Button button5; private GroupBox groupBox5; private CheckBox checkBox2; private GroupBox groupBox6; private Panel panel1; private Panel panel2; private CheckBox checkBoxDebug; private FlowLayoutPanel flowLayoutPanel1; private Button button10; private Button button11; private Button button12; private Button button13; private Button button6; private Button button7; private Button button8; private Button button9; private Button button14; } }
Klocman/Bulk-Crap-Uninstaller
source/BulkCrapUninstaller/Forms/Helpers/DebugWindow.Designer.cs
C#
apache-2.0
24,731
/* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.modelcompiler.domain; public class TargetPolicy { private String customerCode; private String productCode; private int coefficient; public String getCustomerCode() { return customerCode; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public int getCoefficient() { return coefficient; } public void setCoefficient(int coefficient) { this.coefficient = coefficient; } }
reynoldsm88/drools
drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/domain/TargetPolicy.java
Java
apache-2.0
1,281