repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
y2ghost/study
java/servlet/src/main/java/study/ywork/servlet/example/SimpleServlet.java
<reponame>y2ghost/study package study.ywork.servlet.example; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static study.ywork.servlet.constant.MediaType.TEXT_HTML_UTF8; public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType(TEXT_HTML_UTF8); PrintWriter writer = response.getWriter(); writer.print("<html><head></head>" + "<body>欢迎测试 web.xml(SimpleServlet)</body></html"); } }
BlockSpaces/rchain
rholang/src/main/scala/coop/rchain/rholang/interpreter/Runtime.scala
<reponame>BlockSpaces/rchain<gh_stars>0 package coop.rchain.rholang.interpreter import java.nio.file.{Files, Path} import coop.rchain.models.Channel.ChannelInstance.{ChanVar, Quote} import coop.rchain.models.Expr.ExprInstance.GString import coop.rchain.models.TaggedContinuation.TaggedCont.ScalaBodyRef import coop.rchain.models.Var.VarInstance.FreeVar import coop.rchain.models.{BindPattern, Channel, TaggedContinuation, Var} import coop.rchain.rholang.interpreter.implicits._ import coop.rchain.rholang.interpreter.storage.implicits._ import coop.rchain.rspace.{install, IStore, LMDBStore} import monix.eval.Task import scala.collection.immutable class Runtime private (val reducer: Reduce[Task], val store: IStore[Channel, BindPattern, Seq[Channel], TaggedContinuation]) object Runtime { type Name = String type Arity = Int type Remainder = Option[Var] type Ref = Long private def introduceSystemProcesses( store: IStore[Channel, BindPattern, Seq[Channel], TaggedContinuation], processes: immutable.Seq[(Name, Arity, Remainder, Ref)]) : Seq[Option[(TaggedContinuation, Seq[Seq[Channel]])]] = processes.map { case (name, arity, remainder, ref) => install( store, List(Channel(Quote(GString(name)))), List( BindPattern((0 until arity).map[Channel, Seq[Channel]](i => ChanVar(FreeVar(i))), remainder, freeCount = arity)), TaggedContinuation(ScalaBodyRef(ref)) ) } def create(dataDir: Path, mapSize: Long): Runtime = { if (Files.notExists(dataDir)) Files.createDirectory(dataDir) val store = LMDBStore .create[Channel, BindPattern, Seq[Channel], TaggedContinuation](dataDir, mapSize) lazy val dispatcher: Dispatch[Task, Seq[Channel], TaggedContinuation] = RholangAndScalaDispatcher.create(store, dispatchTable) lazy val dispatchTable = Map( 0L -> SystemProcesses.stdout, 1L -> SystemProcesses.stdoutAck(store, dispatcher), 2L -> SystemProcesses.stderr, 3L -> SystemProcesses.stderrAck(store, dispatcher) ) val procDefs: immutable.Seq[(Name, Arity, Remainder, Ref)] = List( ("stdout", 1, None, 0L), ("stdoutAck", 2, None, 1L), ("stderr", 1, None, 2L), ("stderrAck", 2, None, 3L) ) val res: Seq[Option[(TaggedContinuation, Seq[Seq[Channel]])]] = introduceSystemProcesses(store, procDefs) assert(res.forall(_.isEmpty)) new Runtime(dispatcher.reducer, store) } }
sajustsmile/twitter-blockchain
studio/node_modules/@sanity/state-router/lib/utils/isEmpty.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isEmpty; var _hasOwn = _interopRequireDefault(require("./hasOwn")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isEmpty(object) { for (var key in object) { if ((0, _hasOwn.default)(object, key)) { return false; } } return true; }
kubohiroya/sqs-editor
src/main/java/net/sqs2/editor/sqs/modules/panel/SelectFormItemListPanel.java
/* SelectFormItemList.java Copyright 2004 <NAME> (<EMAIL>). 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. Created on 2004/08/01 */ package net.sqs2.editor.sqs.modules.panel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashSet; import javax.swing.Box; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import javax.swing.undo.UndoManager; import net.sqs2.editor.base.modules.AbstractNodeEditor; import net.sqs2.editor.base.modules.EditorUtil; import net.sqs2.editor.base.modules.UpdateListener; import net.sqs2.editor.base.modules.UpdateTarget; import net.sqs2.editor.base.modules.panel.AbstractNodeEditorPanel; import net.sqs2.editor.base.swing.Messages; import net.sqs2.swing.EditMenuTextField; import net.sqs2.xmlns.SQSNamespaces; import org.w3c.dom.Element; /** * @author hiroya * */ public class SelectFormItemListPanel extends AbstractNodeEditorPanel implements UpdateTarget { public static final long serialVersionUID = 0; transient SelectFormItemListModel model; transient Icon itemIcon = null; Item[] itemList = null; Box itemListFormInnerPane; SelectFormItemListPanel self; transient Thread invalidValuesAlartThread = null; public SelectFormItemListPanel(AbstractNodeEditor editor) { super(editor); this.self = this; this.model = new SelectFormItemListModel(editor.getMediator(), editor.getSource(), (Element) editor .getNode()); this.itemIcon = editor.getMediator().getCurrentTreePane().getIcon("item", SQSNamespaces.XFORMS_URI); this.itemListFormInnerPane = Box.createVerticalBox(); JPanel itemListForm = new JPanel(); itemListForm.setBorder(new TitledBorder(EditorUtil.LOWERED_BORDER, Messages.FORM_QUESTION_ITEMS)); itemListForm.setBackground(editor.getResource().bgcolor); itemListForm.setLayout(new BorderLayout()); itemListForm.add(createItemListScrollPanel(), BorderLayout.CENTER); setBackground(editor.getResource().bgcolor); add(itemListForm); initialize(); initSize(); } public int getPreferredHeight() { return 40; } public boolean validateValues() { HashSet<String> set = new HashSet<String>(); for (int i = 0; i < this.itemList.length; i++) { Item item = this.itemList[i]; String value = item.getValueText(); if (set.contains(value)) { item.setValueText("?" + value); return false; } set.add(value); } return true; } /** * @param model * @return */ private JScrollPane createItemListScrollPanel() { final JScrollPane itemListFormScrollPane = new JScrollPane(itemListFormInnerPane); itemListFormScrollPane.setWheelScrollingEnabled(true); itemListFormScrollPane.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent ev) { if (itemListFormScrollPane != null && model != null) { int increment = 10; itemListFormScrollPane.getVerticalScrollBar().setUnitIncrement(increment); } } }); return itemListFormScrollPane; } public synchronized void initialize() { this.itemListFormInnerPane.removeAll(); this.itemList = new Item[this.model.size()]; for (int i = 0; i < this.model.size(); i++) { Item item = createItem(i); this.itemList[i] = item; this.itemListFormInnerPane.add(item); } } public Item createItem(int i) { return new Item(this, i); } public synchronized Item get(int index) { return this.itemList[index]; } public boolean updateNodeValue() { boolean isUpdated = false; if (!validateValues()) { this.invalidValuesAlartThread = new Thread() { public void run() { synchronized (self) { JOptionPane.showMessageDialog(self, Messages.ERROR_FORM_ITEM_VALUE_OVERLOAD, "alert", JOptionPane.ERROR_MESSAGE); invalidValuesAlartThread = null; } } }; if (invalidValuesAlartThread != null) { invalidValuesAlartThread.start(); } return true; } for (int i = 0; i < this.itemList.length; i++) { if (this.itemList[i].updateNodeValue()) { isUpdated = true; } else { } } if (isUpdated) { getEditor().updateNodeValue(true); } return isUpdated; } public class Item extends JPanel { public static final long serialVersionUID = 0; PopupMenu popupMenu; int index; EditMenuTextField valueTextField; EditMenuTextField labelTextField; UpdateListener updateListener; JComponent itemFormWest; Item(AbstractNodeEditorPanel itemListForm, int index) { this.index = index; this.updateListener = new UpdateListener(self); this.popupMenu = new PopupMenu(index); setLayout(new BorderLayout()); setBackground(getEditor().getResource().bgcolor); this.itemFormWest = createFormItemWest(); add(this.itemFormWest, BorderLayout.WEST); this.labelTextField = createFormItemCenter(); add(this.labelTextField, BorderLayout.CENTER); /* * labelTextField.setTransferHandler(new TransferHandler("text")); * labelTextField.addMouseListener(new MouseAdapter() { public void * mousePressed(MouseEvent e) { JComponent c = * (JComponent)e.getSource(); TransferHandler th = * c.getTransferHandler(); th.exportAsDrag(c, e, * TransferHandler.COPY); } }); */ setPreferredSize(new Dimension(340, 20)); setSize(new Dimension(340, 20)); addMouseListener(popupMenu.getMouseListener()); } public void setSelectedBackGroundColor(boolean isSelected) { if (isSelected) { setBackground(getEditor().getResource().bgcolor.brighter()); } else { setBackground(getEditor().getResource().bgcolor); } } JTextField getLabelTextField() { return this.labelTextField; } public boolean updateNodeValue() { return model.updateNodeValue(this.index, this.labelTextField.getText(), this.valueTextField .getText()); } public String getValueText() { return this.valueTextField.getText(); } public void setValueText(String text) { this.valueTextField.setText(text); } private JComponent createFormItemWest() { this.valueTextField = new EditMenuTextField(); this.valueTextField.setSize(2, 1); this.valueTextField.setText(model.getValue(this.index)); this.valueTextField.setBackground(getBackground()); this.valueTextField.setEditable(true); this.valueTextField.addFocusListener(this.updateListener); this.valueTextField.setPreferredSize(new Dimension(16, 14)); this.valueTextField.setUndoManager(new UndoManager()); JComponent itemFormWest = Box.createHorizontalBox(); itemFormWest.add(new JLabel(itemIcon)); itemFormWest.add(this.valueTextField); itemFormWest.add(new JLabel(":")); if (getEditor().getSource().isReadOnly()) { this.valueTextField.setEnabled(false); } return itemFormWest; } private EditMenuTextField createFormItemCenter() { this.labelTextField = new EditMenuTextField(); this.labelTextField.setSize(10, 1); this.labelTextField.setText(model.getLabel(this.index)); this.labelTextField.addFocusListener(this.updateListener); this.labelTextField.setUndoManager(new UndoManager()); if (getEditor().getSource().isReadOnly()) { this.labelTextField.setEnabled(false); } return this.labelTextField; } class PopupMenu extends JPopupMenu { public static final long serialVersionUID = 0; transient private PopupAdapter listener; private JMenuItem deleteButton; transient private MouseAdapter mouseAdapter = new MouseAdapter() { public void mouseEntered(MouseEvent e) { setSelectedBackGroundColor(true); } public void mouseExited(MouseEvent e) { setSelectedBackGroundColor(false); } }; PopupMenu(int index) { setPopupSize(300, 70); addMouseListener(this.mouseAdapter); this.listener = new PopupAdapter(this); JMenuItem insertBeforeButton = createPopupMenuItem( Messages.FORM_QUESTION_PASTE_ITEM_AS_PRECEDING_SIBLING, "b " + index); JMenuItem insertAfterButton = createPopupMenuItem( Messages.FORM_QUESTION_PASTE_ITEM_AS_FOLLOWING_SIBLING, "a " + index); this.deleteButton = createPopupMenuItem(Messages.FORM_QUESTION_DELETE_ITEM, "d " + index); add(insertBeforeButton); add(insertAfterButton); addSeparator(); add(this.deleteButton); } private JMenuItem createPopupMenuItem(String label, String command) { JMenuItem item = new JMenuItem(label); item.setActionCommand(command); item.addActionListener(this.listener); item.addMouseListener(this.mouseAdapter); return item; } MouseAdapter getMouseListener() { return this.listener; } public JMenuItem getDeleteButton() { return this.deleteButton; } class PopupAdapter extends MouseAdapter implements ActionListener { private JPopupMenu popupMenu; PopupAdapter(JPopupMenu commandPopup) { this.popupMenu = commandPopup; } public void actionPerformed(ActionEvent ev) { String[] commandArgs = ev.getActionCommand().split("\\s"); String command = commandArgs[0]; int target = Integer.parseInt(commandArgs[1]); if (command.equals("d")) { delete(target); } else if (command.equals("b")) { insertBefore(target); } else if (command.equals("a")) { insertAfter(target); } else { return; } setSelectedBackGroundColor(false); initialize(); if (command.equals("b")) { get(target).getLabelTextField().requestFocus(); } else if (command.equals("a")) { get(target + 1).getLabelTextField().requestFocus(); } getEditor().updateNodeValue(true); getEditor().updateUI(); getEditor().getMediator().getCurrentTreePane().updateUI(); } private void insertAfter(int target) { if (target == model.size() - 1) { model.add("", "", 1); } else { model.insert(target + 1, "", "", 1); } getDeleteButton().setEnabled(true); } private void insertBefore(int target) { model.insert(target, "", "", 1); getDeleteButton().setEnabled(true); } private void delete(int target) { if (1 < model.size()) { model.remove(target); if (model.size() == 1) { getDeleteButton().setEnabled(false); } } } public void mousePressed(MouseEvent e) { // if (e.isPopupTrigger()) { setSelectedBackGroundColor(true); popupMenu.show(e.getComponent(), e.getX(), e.getY()); // } } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { setSelectedBackGroundColor(true); } public void mouseExited(MouseEvent e) { if (!popupMenu.isVisible()) { setSelectedBackGroundColor(false); } } } } } }
bryanbalderas/DAS_Sistemas
Ago-Dic-2020/rodriguez-martinez-jesus-angel/Practica-3/observer.test.py
import unittest from observer import Subscriber, Publisher class SubscriberTest(unittest.TestCase): def test_subscriber_creation(self): sub = Subscriber("Bob") self.assertEqual(str(sub), "I'm Bob") class PublisherTest(unittest.TestCase): def test_publisher_creation(self): pub = Publisher() bob = Subscriber("Bob") pub.register(bob) self.assertEqual(pub.dispatch("First update from publisher"), 'Bob got message: "First update from publisher"\n') if __name__ == "__main__": unittest.main()
monkiyang/objc-runtime
applesources/xnu-3789.41.3/tools/tests/libMicro/memcpy.c
<reponame>monkiyang/objc-runtime /* * CDDL HEADER START * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * usr/src/OPENSOLARIS.LICENSE. If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * memcpy */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "libmicro.h" #define DEFS 8192 #define DEFR 1 static long long opts = DEFS; static int optf; static int optt; static int opta; typedef struct { char *ts_src; char *ts_dest; int ts_srcsize; int ts_destsize; } tsd_t; int benchmark_init() { lm_tsdsize = sizeof (tsd_t); (void) sprintf(lm_optstr, "a:s:ft"); (void) sprintf(lm_usage, " [-s buffer-size (default %d)]\n" " [-a relative alignment (default page aligned)]\n" " [-f (rotate \"from\" buffer to keep it out of cache)]\n" " [-t (rotate \"to\" buffer to keep it out of cache)]\n" "notes: measures memcpy()\n", DEFS); (void) sprintf(lm_header, "%8s", "size"); return (0); } int benchmark_optswitch(int opt, char *optarg) { switch (opt) { case 'f': optf++; break; case 't': optt++; break; case 's': opts = sizetoll(optarg); break; case 'a': opta = sizetoint(optarg); break; default: return (-1); } return (0); } int benchmark_initworker(void *tsd) { tsd_t *ts = (tsd_t *)tsd; if (optf) ts->ts_srcsize = 64 * 1024 * 1024; else ts->ts_srcsize = opts + opta; if (optt) ts->ts_destsize = 64 * 1024 * 1024; else ts->ts_destsize = (int)opts; ts->ts_src = opta + (char *)valloc(ts->ts_srcsize); ts->ts_dest = valloc(ts->ts_destsize); return (0); } int benchmark(void *tsd, result_t *res) { tsd_t *ts = (tsd_t *)tsd; int i; char *src = ts->ts_src; char *dest = ts->ts_dest; int bump = (int)opts; if (bump < 1024) bump = 1024; /* avoid prefetched area */ for (i = 0; i < lm_optB; i++) { (void) memcpy(dest, src, opts); if (optf) { src += bump; if (src + opts > ts->ts_src + ts->ts_srcsize) src = ts->ts_src; } if (optt) { dest += bump; if (dest + opts > ts->ts_dest + ts->ts_destsize) dest = ts->ts_dest; } } res->re_count = i; return (0); } char * benchmark_result() { static char result[256]; (void) sprintf(result, "%8lld", opts); return (result); }
poovarasanvasudevan/atlas
resources/assets/js/components/icons/svg/Star.js
<filename>resources/assets/js/components/icons/svg/Star.js import React from "react"; const Star = props => ( <svg width="1em" height="1em" viewBox="0 0 1792 1792" {...props}> <path d="M1728 647q0 22-26 48l-363 354 86 500q1 7 1 20 0 21-10.5 35.5T1385 1619q-19 0-40-12l-449-236-449 236q-22 12-40 12-21 0-31.5-14.5T365 1569q0-6 2-20l86-500L89 695q-25-27-25-48 0-37 56-46l502-73L847 73q19-41 49-41t49 41l225 455 502 73q56 9 56 46z" /> </svg> ); export default Star;
InCadence/coalesce
src/Coalesce/src/main/java/com/incadencecorp/coalesce/framework/exim/impl/JsonFullEximImpl.java
/*-----------------------------------------------------------------------------' Copyright 2016 - InCadence Strategic Solutions Inc., All Rights Reserved Notwithstanding any contractor copyright notice, the Government has Unlimited Rights in this work as defined by DFARS 252.227-7013 and 252.227-7014. Use of this work other than as specifically authorized by these DFARS Clauses may violate Government rights in this work. DFARS Clause reference: 252.227-7013 (a)(16) and 252.227-7014 (a)(16) Unlimited Rights. The Government has the right to use, modify, reproduce, perform, display, release or disclose this computer software and to have or authorize others to do so. Distribution Statement D. Distribution authorized to the Department of Defense and U.S. DoD contractors only in support of U.S. DoD efforts. -----------------------------------------------------------------------------*/ package com.incadencecorp.coalesce.framework.exim.impl; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.incadencecorp.coalesce.api.CoalesceErrors; import com.incadencecorp.coalesce.api.CoalesceExim; import com.incadencecorp.coalesce.api.Views; import com.incadencecorp.coalesce.common.exceptions.CoalesceException; import com.incadencecorp.coalesce.framework.datamodel.*; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This implementation of the {@link CoalesceExim} interface creates * {@link JSONObject}s * * @author n78554 */ public class JsonFullEximImpl implements CoalesceExim<JSONObject> { private static final Logger LOGGER = LoggerFactory.getLogger(JsonFullEximImpl.class); private Class<?> view = Views.Entity.class; /** * @param clazz the JSON view to use. */ public void setView(Class<?> clazz) { this.view = clazz; } @Override public JSONObject exportValues(CoalesceEntity entity, boolean includeEntityType) throws CoalesceException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION); try { return new JSONObject(mapper.writerWithView(view).writeValueAsString(entity)); } catch (IOException e) { throw new CoalesceException(e); } } @Override public CoalesceEntity importValues(JSONObject values, CoalesceEntityTemplate template) throws CoalesceException { CoalesceEntity entity = template.createNewEntity(); entity.initialize(); importValues(values, entity); return entity; } private static final List<String> OMMIT = Arrays.asList("namepath", "sectionsaslist", "otherattributes", "recordsetsaslist", "linkagesection", "tag", "fielddefinitions", "allrecords", "fields", "linkagesaslist", "datatype", "type", "classname", "portionmarking", "classificationmarkingasstring", "allowedit", "allownew", "allowremove", "count", "hasactiverecords", "hasrecords", "createdby"); @Override public void importValues(JSONObject values, CoalesceEntity entity) throws CoalesceException { copyAttributes(values, entity); copyLinkageSection(values.getJSONObject("linkageSection"), entity.getLinkageSection()); JSONArray jsonSections = values.getJSONArray("sectionsAsList"); for (int i = 0; i < jsonSections.length(); i++) { copySection(jsonSections.getJSONObject(i), entity); } } private void copyLinkageSection(JSONObject json, CoalesceLinkageSection section) { copyAttributes(json, section); JSONArray jsonLinkages = json.getJSONArray("linkagesAsList"); for (int ii = 0; ii < jsonLinkages.length(); ii++) { copyAttributes(jsonLinkages.getJSONObject(ii), section.createLinkage()); } } private void copySection(JSONObject json, CoalesceObject parent) throws CoalesceException { String name = json.getString(CoalesceObject.ATTRIBUTE_NAME); CoalesceSection section = parent.getCoalesceSectionForNamePath(parent.getName(), name); // Exists? if (section != null) { // Copy Attributes copyAttributes(json, section); // Create Nested Sections JSONArray jsonSections = json.getJSONArray("sectionsAsList"); for (int ii = 0; ii < jsonSections.length(); ii++) { copySection(jsonSections.getJSONObject(ii), section); } // Create Record Sets JSONArray jsonRecordSets = json.getJSONArray("recordsetsAsList"); for (int ii = 0; ii < jsonRecordSets.length(); ii++) { copyRecordset(jsonRecordSets.getJSONObject(ii), section); } } else { LOGGER.warn(String.format(CoalesceErrors.INVALID_OBJECT, "Section", name)); } } private void copyRecordset(JSONObject json, CoalesceSection section) throws CoalesceException { String name = json.getString(CoalesceSection.ATTRIBUTE_NAME); CoalesceRecordset recordset = section.getCoalesceRecordsetForNamePath(section.getName(), name); // Exists? if (recordset != null) { copyAttributes(json, recordset); JSONArray jsonRecords = json.getJSONArray("allRecords"); if (recordset.getMaxRecords() == 1 && recordset.getMinRecords() == 1) { copyRecord(jsonRecords.getJSONObject(0), recordset.getAllRecords().get(0)); } else { for (int ii = 0; ii < jsonRecords.length(); ii++) { copyRecord(jsonRecords.getJSONObject(ii), recordset.addNew()); } } } else { LOGGER.warn(String.format(CoalesceErrors.INVALID_OBJECT, "Recordset", name)); } } private void copyRecord(JSONObject json, CoalesceRecord record) { // Copy Attributes copyAttributes(json, record); JSONArray jsonFields = json.getJSONArray("fields"); for (int ii = 0; ii < jsonFields.length(); ii++) { JSONObject jsonField = jsonFields.getJSONObject(ii); String name = jsonField.getString("name"); CoalesceField<?> field = record.getFieldByName(name); if (field != null) { copyAttributes(jsonField, field); } else { LOGGER.warn("Field {} Does not Exists", name); } } } private void copyAttributes(JSONObject json, CoalesceObject node) { for (String name : JSONObject.getNames(json)) { if (!OMMIT.contains(name.toLowerCase())) { Object value = json.get(name); if (value instanceof String) { node.setAttribute(name, (String) value); } else if (value instanceof Integer) { node.setAttribute(name, String.valueOf(value)); } else if (value instanceof Boolean) { node.setAttribute(name, String.valueOf(value)); } else if (value.getClass().getSimpleName().equalsIgnoreCase("Null")) { node.setAttribute(name, ""); } else if (value instanceof JSONArray && node instanceof CoalesceField && ((CoalesceField<?>) node).isListType()) { JSONArray values = (JSONArray) value; List<String> baseValue = new ArrayList<>(); switch (((CoalesceField<?>) node).getDataType()) { case STRING_LIST_TYPE: for (int ii = 0; ii < values.length(); ii++) { baseValue.add((String) values.get(ii)); } break; default: LOGGER.warn("Attribute ({}) from ({}) was an unhandled list type ({})", name, json.getString("name"), ((CoalesceField<?>) node).getDataType()); break; } node.setAttribute(CoalesceField.ATTRIBUTE_VALUE, StringUtils.join(baseValue.toArray(new String[baseValue.size()]), ",")); } else { LOGGER.warn("Attribute ({}) from ({}) was an unhandled type ({})", name, json.getString("name"), value.getClass().getSimpleName()); } } } } }
terceiro/rmagick
spec/rmagick/image/opaque_spec.rb
RSpec.describe Magick::Image, '#opaque' do it 'works' do image = described_class.new(20, 20) result = image.opaque('white', 'red') expect(result).to be_instance_of(described_class) expect(result).not_to be(image) red = Magick::Pixel.new(Magick::QuantumRange) blue = Magick::Pixel.new(0, 0, Magick::QuantumRange) expect { image.opaque(red, blue) }.not_to raise_error expect { image.opaque(red, 2) }.to raise_error(TypeError) expect { image.opaque(2, blue) }.to raise_error(TypeError) end end
leonardoanthony/Origamid
react-js/mod4/inputs/src/0402/App.js
import React from "react"; const App = () => { const [mensagem, setMensagem] = React.useState(""); function handleChange({target}) { setMensagem(target.value); } return ( <form> <textarea rows="3" value={mensagem} onChange={handleChange} /> {mensagem} </form> ); }; export default App;
JavaQualitasCorpus/myfaces_core-2.1.10
src/myfaces-api-2.1.10-sources/javax/faces/component/html/HtmlDoctype.java
/* * 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 javax.faces.component.html; import javax.faces.el.ValueBinding; import javax.el.ValueExpression; import javax.faces.context.FacesContext; import javax.faces.component.UIComponent; import javax.faces.convert.Converter; // Generated from class javax.faces.component.html._HtmlDoctype. // // WARNING: This file was automatically generated. Do not edit it directly, // or you will lose your changes. public class HtmlDoctype extends javax.faces.component.UIOutput { static public final String COMPONENT_FAMILY = "javax.faces.Output"; static public final String COMPONENT_TYPE = "javax.faces.OutputDoctype"; public HtmlDoctype() { setRendererType("javax.faces.Doctype"); } @Override public String getFamily() { return COMPONENT_FAMILY; } // Property: public public String getPublic() { return (String) getStateHelper().eval(PropertyKeys.publicVal); } public void setPublic(String publicParam) { getStateHelper().put(PropertyKeys.publicVal, publicParam ); } // Property: rootElement public String getRootElement() { return (String) getStateHelper().eval(PropertyKeys.rootElement); } public void setRootElement(String rootElement) { getStateHelper().put(PropertyKeys.rootElement, rootElement ); } // Property: system public String getSystem() { return (String) getStateHelper().eval(PropertyKeys.system); } public void setSystem(String system) { getStateHelper().put(PropertyKeys.system, system ); } protected enum PropertyKeys { publicVal("public") , rootElement , system ; String c; PropertyKeys() { } //Constructor needed by "for" property PropertyKeys(String c) { this.c = c; } public String toString() { return ((this.c != null) ? this.c : super.toString()); } } }
luci/luci-go
cv/internal/common/tree/tree_test.go
// Copyright 2021 The LUCI 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 tree import ( "context" "fmt" "net/http" "net/http/httptest" "testing" "time" . "github.com/smartystreets/goconvey/convey" . "go.chromium.org/luci/common/testing/assertions" ) func TestTreeStatesClient(t *testing.T) { t.Parallel() Convey("FetchLatest", t, func() { ctx := context.Background() client := &httpClientImpl{ &http.Client{Transport: &http.Transport{}}, } Convey("Works", func() { var actualReqURL string mockSrv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { actualReqURL = req.URL.String() rw.WriteHeader(200) rw.Header().Set("Content-Type", "application/json") fmt.Fprint(rw, `{ "username":"<EMAIL>", "can_commit_freely":true, "general_state":"open", "key":1234567, "date":"2000-01-02 03:04:05.678910111", "message":"tree is open" }`) })) defer mockSrv.Close() ts, err := client.FetchLatest(ctx, mockSrv.URL) So(err, ShouldBeNil) So(ts, ShouldResemble, Status{ State: Open, Since: time.Date(2000, 01, 02, 03, 04, 05, 678910111, time.UTC), }) So(actualReqURL, ShouldEqual, "/current?format=json") }) Convey("Error if http call fails", func() { mockSrv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(500) })) defer mockSrv.Close() _, err := client.FetchLatest(ctx, mockSrv.URL) So(err, ShouldErrLike, "received error when caling") }) Convey("Error if response is not JSON", func() { mockSrv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(200) rw.Header().Set("Content-Type", "text/plain") fmt.Fprint(rw, "I'm not JSON") })) defer mockSrv.Close() _, err := client.FetchLatest(ctx, mockSrv.URL) So(err, ShouldErrLike, "failed to unmarshal JSON") }) Convey("Error if data format is invalid", func() { mockSrv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(200) rw.Header().Set("Content-Type", "text/plain") fmt.Fprint(rw, `{ "general_state":"open", "date":"2000-01-02T03:04:05.678910111Z" }`) })) defer mockSrv.Close() _, err := client.FetchLatest(ctx, mockSrv.URL) So(err, ShouldErrLike, "failed to parse date") }) }) }
cquiroz/ocs
bundle/jsky.app.ot/src/main/scala/jsky/app/ot/gemini/editor/auxfile/AuxFileModel.scala
package jsky.app.ot.gemini.editor.auxfile import edu.gemini.auxfile.api.AuxFile import edu.gemini.auxfile.client.AuxFileClient import edu.gemini.sp.vcs.reg.VcsRegistrar import edu.gemini.spModel.core.SPProgramID import AuxFileState.{Busy, Idle} import scala.swing.Publisher import jsky.app.ot.OT /** * The AuxFileModel manages/manipulates/publishes the current state of the * auxiliary file information in the Observing Tool. It is not thread-safe and * is meant to be used solely from the Swing event loop. */ class AuxFileModel(reg: VcsRegistrar) extends Publisher { var currentState: Option[AuxFileState] = None def currentPid: Option[SPProgramID] = currentState.map(_.pid) def currentFiles: Option[List[AuxFile]] = currentState.map(_.files) def currentSelection: Option[List[AuxFile]] = currentState.map(_.selection) def client: Option[AuxFileClient] = for { s <- currentState p <- reg.registration(s.pid) } yield new AuxFileClient(OT.getKeyChain, p.host, p.port) private def update(pid: SPProgramID, condition: AuxFileState => Boolean)(modification: AuxFileState => AuxFileState) { if (currentState.exists(s => s.pid == pid && condition(s))) { currentState = currentState.map(modification) publish(AuxFileStateEvent(currentState)) } } def select(pid: SPProgramID, sel: List[AuxFile]) { update(pid, s => s.status == Idle && sel.forall(f => currentFiles.exists(_.contains(f)))) { _.copy(selection = sel) } } def init(pid: SPProgramID) { currentState = Some(AuxFileState(pid)) publish(new AuxFileStateEvent(currentState)) } def busy(pid: SPProgramID) { update(pid, _.status == Idle) { _.copy(status = Busy) } } def success(pid: SPProgramID, files: List[AuxFile]) { update(pid, _.status == Busy) { _.copy(status = Idle, files = files.sorted, selection = Nil) } } def failure(pid: SPProgramID) { update(pid, _ => true) { _.copy(status = Idle) } } }
concord-consortium/energy3d
src/main/java/org/concord/energy3d/Designer.java
package org.concord.energy3d; import java.io.Serializable; /** * @author <NAME> */ public class Designer implements Serializable { private static final long serialVersionUID = 1L; private String name; private String email; private String organization; public Designer() { name = "User"; } public void setName(final String name) { this.name = name; } public String getName() { return name; } public void setEmail(final String email) { this.email = email; } public String getEmail() { return email; } public void setOrganization(final String organization) { this.organization = organization; } public String getOrganization() { return organization; } }
valenciateh-nus/HRMS
src/App.js
import { StyledEngineProvider, ThemeProvider } from '@material-ui/core'; import AdapterDateFns from '@mui/lab/AdapterDateFns'; import LocalizationProvider from '@mui/lab/LocalizationProvider'; import { onAuthStateChanged } from 'firebase/auth'; import { useState } from 'react'; import 'react-perfect-scrollbar/dist/css/styles.css'; import { Navigate, useRoutes } from 'react-router-dom'; import DashboardLayout from './components/DashboardLayout'; import GlobalStyles from './components/GlobalStyles'; import MainLayout from './components/MainLayout'; import { auth } from './firebase-config'; import Account from './pages/Account'; import Appraisal from './pages/Appraisal'; import Attendance from './pages/Attendance'; import Dashboard from './pages/Dashboard'; import EmployeesPage from './pages/EmployeesPage'; import LeavePage from './pages/LeavePage'; import Login from './pages/Login'; import NotFound from './pages/NotFound'; import Payroll from './pages/Payroll'; import QR from './pages/QR'; import UserAppraisal from './pages/UserAppraisal'; import UserAttendance from './pages/UserAttendance'; import UserLeave from './pages/UserLeave'; import UserPayroll from './pages/UserPayroll'; import theme from './theme'; // import { useEffect, useState } from 'react'; const App = () => { const [currUser, setCurrUser] = useState(JSON.parse(localStorage.getItem('currUser'))); // const currEmployee = JSON.parse(localStorage.getItem('currUser')); onAuthStateChanged(auth, (user) => { if (user) { console.log('logged in as', user.email); localStorage.setItem('currUser', JSON.stringify(user)); setCurrUser(user); } else { console.log('No logged in user'); } }); const routes = [ { path: 'app', element: (currUser !== null ? <DashboardLayout /> : <Navigate to="/login" />), children: [ { path: 'dashboard', element: <Dashboard /> }, { path: 'account', element: <Account /> }, { path: 'employees', element: <EmployeesPage /> }, { path: 'appraisal', element: <Appraisal /> }, { path: 'attendance', element: <Attendance /> }, { path: 'leave', element: <LeavePage /> }, { path: 'payroll', element: <Payroll /> }, { path: 'qr', element: <QR /> }, { path: '*', element: <Navigate to="/404" replace="false" /> }, ] }, { path: 'user', element: (currUser !== null ? <DashboardLayout /> : <Navigate to="/login" />), children: [ { path: 'attendance', element: <UserAttendance /> }, { path: 'appraisal', element: <UserAppraisal /> }, { path: 'payroll', element: <UserPayroll /> }, { path: 'leave', element: <UserLeave /> }, { path: '*', element: <Navigate to="/404" replace="false" /> }, ] }, { path: '/', element: <MainLayout />, children: [ { path: '', element: (currUser === null ? <Navigate to="/login" /> : <Navigate to="/app/account" />) }, { path: 'login', element: <Login /> }, { path: '404', element: <NotFound /> }, { path: '*', element: <Navigate to="/404" replace="false" /> }, ] } ]; return ( <LocalizationProvider dateAdapter={AdapterDateFns}> <StyledEngineProvider injectFirst> <ThemeProvider theme={theme}> <GlobalStyles /> {useRoutes(routes)} </ThemeProvider> </StyledEngineProvider> </LocalizationProvider> ); }; export default App;
FOC-framework/l3
foc/src/b01/foc/calendar/HolidayDesc.java
<filename>foc/src/b01/foc/calendar/HolidayDesc.java package b01.foc.calendar; import java.sql.Date; import b01.foc.desc.FocDesc; import b01.foc.desc.field.FCharField; import b01.foc.desc.field.FDateField; import b01.foc.desc.field.FField; import b01.foc.desc.field.FObjectField; import b01.foc.list.FocList; import b01.foc.list.FocListOrder; import b01.foc.property.FProperty; import b01.foc.property.FPropertyListener; public class HolidayDesc extends FocDesc{ public static final int FLD_START_DATE = 1; public static final int FLD_END_DATE = 2; public static final int FLD_REASON = 3; public static final int FLD_FCALENDAR = 4; public HolidayDesc(){ super(Holiday.class, FocDesc.DB_RESIDENT, "Holiday", false); setGuiBrowsePanelClass(HolidayGuiBrowsePanel.class); //setGuiDetailsPanelClass(HolidayGuiDetailsPanel.class); FField focFld = addReferenceField(); focFld = new FDateField("HOLIDAY_DATE", "Start Date", FLD_START_DATE, false); //focFld.setLockValueAfterCreation(true); focFld.setMandatory(true); focFld.addListener(getDatePropertyListener()); addField(focFld); focFld = new FDateField("HOLIDAY_END_DATE", "End Date", FLD_END_DATE, false); //focFld.setLockValueAfterCreation(true); focFld.setMandatory(true); addField(focFld); focFld = new FCharField("REASON", "Holidays", FLD_REASON, false, 30); //focFld.setLockValueAfterCreation(true); focFld.setMandatory(true); addField(focFld); FObjectField objFld = new FObjectField("FCALENDAR", "FCalendar", FLD_FCALENDAR, false, FCalendarDesc.getInstance(), "FCALENDAR_", this, FCalendarDesc.FLD_HOLIDAYS_LIST); objFld.setNullValueMode(FObjectField.NULL_VALUE_ALLOWED_AND_SHOWN); objFld.setSelectionList(FCalendarDesc.getList(FocList.NONE)); objFld.setMandatory(true); addField(objFld); } public FPropertyListener getDatePropertyListener(){ return new FPropertyListener(){ public void dispose() { } public void propertyModified(FProperty property) { if(property != null && !property.isLastModifiedBySetSQLString()){ Holiday holidayDate = (Holiday) property.getFocObject(); Date startDate = holidayDate.getPropertyDate(HolidayDesc.FLD_START_DATE); holidayDate.setPropertyDate(HolidayDesc.FLD_END_DATE, startDate); } } }; } //ooooooooooooooooooooooooooooooooooo // oooooooooooooooooooooooooooooooooo // SINGLE LIST // oooooooooooooooooooooooooooooooooo // oooooooooooooooooooooooooooooooooo private static FocList list = null; public static FocList getList(int mode){ list = getInstance().getList(list, mode); list.setDirectlyEditable(true); list.setDirectImpactOnDatabase(false); if(list.getListOrder() == null){ FocListOrder order = new FocListOrder(FLD_START_DATE); list.setListOrder(order); } return list; } //ooooooooooooooooooooooooooooooooooo // oooooooooooooooooooooooooooooooooo // SINGLE INSTANCE // oooooooooooooooooooooooooooooooooo // oooooooooooooooooooooooooooooooooo private static FocDesc focDesc = null; public static FocDesc getInstance() { if (focDesc==null){ focDesc = new /*XXX*/HolidayDesc(); } return focDesc; } }
mennooo/apex-powerful-javascript-skills
src/apex/demo/modules/jet.js
<reponame>mennooo/apex-powerful-javascript-skills /* global apex kscope */ ;(function ($, apex, kscope) { function addReferenceObject (da, options) { // referenceObject defaults var defaults = { lineWidth: 3, color: 'red', location: 'front', value: 10 } // extending defaults with user options var settings = $.extend({}, defaults, options) // Oracle JET uses RequireJS and all modules must be loaded require(['ojs/ojcore', 'jquery', 'ojs/ojchart', 'ojs/ojgauge', 'ojs/ojvalidation'], function () { // Add the reference object to the selected JET Chart apex.region(da.action.affectedRegionId).widget().ojChart('option', 'yAxis.referenceObjects', [settings]) }) } // Export this module kscope.jet = { addReferenceObject: addReferenceObject } })(apex.jQuery, apex, kscope)
Scottacus64/mpf
mpf/modes/tilt/__init__.py
<reponame>Scottacus64/mpf """Default tilt mode."""
CoOwner/VisualPvP
com/mongodb/operation/IndexHelper.java
package com.mongodb.operation; import org.bson.BsonDocument; import org.bson.BsonNumber; import org.bson.BsonString; import org.bson.BsonValue; final class IndexHelper { static String generateIndexName(BsonDocument index) { StringBuilder indexName = new StringBuilder(); for (String keyNames : index.keySet()) { if (indexName.length() != 0) { indexName.append('_'); } indexName.append(keyNames).append('_'); BsonValue ascOrDescValue = index.get(keyNames); if ((ascOrDescValue instanceof BsonNumber)) { indexName.append(((BsonNumber)ascOrDescValue).intValue()); } else if ((ascOrDescValue instanceof BsonString)) { indexName.append(((BsonString)ascOrDescValue).getValue().replace(' ', '_')); } } return indexName.toString(); } private IndexHelper() {} }
ninoseki/SimpleWhatWeb
lib/whatweb/plugins/clicky.rb
# frozen_string_literal: true ## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## WhatWeb::Plugin.define "Clicky" do @author = "<NAME> <<EMAIL>>" # 2012-04-07 @version = "0.1" @description = "Clicky - Real Time Web Analytics" @website = "https://www.getclicky.com/" # Matches # @matches = [ # JavaScript { regexp: /<script[^>]+src=["'](https?:)?\/\/static\.getclicky\.com/i }, ] end
moutainhigh/ses-server
ses-app/ses-web-ros/src/main/java/com/redescooter/ses/web/ros/vo/wms/cn/WhOutDetailResult.java
package com.redescooter.ses.web.ros.vo.wms.cn; import com.redescooter.ses.api.common.vo.base.GeneralResult; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import io.swagger.annotations.*; /** * @ClassName:WhOutDetailResult * @description: WhOutDetailResult * @author: Alex * @Version:1.3 * @create: 2020/07/20 11:07 */ @ApiModel(value = "出库单详情", description = "出库单详情") @Data //生成getter,setter等函数 @AllArgsConstructor //生成全参数构造函数 @NoArgsConstructor//生成无参构造函数 @EqualsAndHashCode(callSuper = false) @Builder public class WhOutDetailResult extends GeneralResult { @ApiModelProperty(value = "id") private Long id; @ApiModelProperty(value = "出库单号") private String whOutN; @ApiModelProperty(value = "目标仓库Id") private Long goalWhId; @ApiModelProperty(value = "仓库名称") private String goalWhName; @ApiModelProperty(value = "地址") private String address; @ApiModelProperty(value = "收获人Id") private String consigneeId; @ApiModelProperty(value = "收获人姓名") private String consigneeFirstName; @ApiModelProperty(value = "收获人姓名") private String consigneeLastName; @ApiModelProperty(value = "收获人电话") private String telephone; @ApiModelProperty(value = "收获人电话国家代码") private String countryCode; @ApiModelProperty(value = "收获人邮箱") private String email; @ApiModelProperty(value = "通知人Id") private Long notifyId; @ApiModelProperty(value = "通知人") private String notifyFirstName; @ApiModelProperty(value = "通知人") private String notifyLastName; @ApiModelProperty(value = "物流方式") private String consignType; @ApiModelProperty(value = "委托方式") private String consignMethod; @ApiModelProperty(value = "物流公司") private String consignCompany; @ApiModelProperty(value = "物流单号") private String trackingN; @ApiModelProperty(value = "附件") private String annex; @ApiModelProperty(value = "价格") private String price; @ApiModelProperty(value = "状态") private String status; }
Civil-Service-Human-Resources/identity-management
src/main/java/uk/gov/cshr/service/RequestEntityException.java
package uk.gov.cshr.service; public class RequestEntityException extends RuntimeException { public RequestEntityException(Throwable cause) { super("Unable to create request", cause); } }
nikolasco/amanda
ndmp-src/ndmp-proxy_main.c
/* * Copyright (c) 1998,1999,2000 * Traakan, Inc., Los Altos, CA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice unmodified, this list of conditions, and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Project: NDMJOB * Ident: $Id: $ * * Description: * */ #define GLOBAL #include "ndmjob.h" static void proxy_usage(void) { g_fprintf(stderr, "USAGE: ndmp-proxy CONFIG PORT\n"); exit(1); } static void ndma_proxy_session (struct ndm_session *sess, int proxy_port) { int conn_sock, len, rc; struct sockaddr sa; int proxy_sock; int fd; sess->proxy_starting = TRUE; sess->proxy_connections = 0; proxy_sock = socket (AF_INET, SOCK_STREAM, 0); if (proxy_sock < 0) { fprintf(stdout, "opening socket: %s\n", strerror(errno)); exit(1); } ndmalogf (sess, 0, 2, "set sess->protocol_listen"); ndmos_condition_listen_socket (sess, proxy_sock); NDMOS_MACRO_SET_SOCKADDR(&sa, 0, proxy_port); if (bind (proxy_sock, &sa, sizeof sa) < 0) { int err = errno; ndmalogf (sess, 0, 2, "Can't bind the socket(%d): %s\n", proxy_port, strerror(err)); if (err == EADDRINUSE) { fprintf(stdout, "INUSE\n"); fflush(stdout); exit(0); } else { fprintf(stdout, "while binding tcp port %d: %s\n", proxy_port, strerror(err)); fflush(stdout); exit(1); } } if (listen (proxy_sock, 5) < 0) { fprintf(stdout, "listening on socket: %s\n", strerror(errno)); exit(1); } /* set up to listen on this new socket */ ndmchan_initialize(&sess->listen_chan, "proxy-listen"); ndmchan_start_listen(&sess->listen_chan, proxy_sock); /* tell our invoker that we are OK */ if (full_write(1, "OK\n", 3) != 3) { fprintf(stderr, "ndmp-proxy writing to stdout: %s\n", strerror(errno)); exit(1); } /* send an EOF on stdout */ close(1); /* open /dev/null on fds 0 and 1 */ fd = open("/dev/null", O_RDONLY); if (fd < 0) { fprintf(stderr, "cannot open /dev/null\n"); /* ignore the error */ } else if (fd != 1) { dup2(fd, 1); close(fd); } fd = open("/dev/null", O_WRONLY); if (fd < 0) { fprintf(stderr, "cannot open /dev/null\n"); /* ignore the error */ } else if (fd != 0) { dup2(fd, 0); close(fd); } } int main (int ac, char *av[]) { int rc; int port; NDMOS_MACRO_ZEROFILL(&the_session); d_debug = -1; /* ready the_param early so logging works during process_args() */ NDMOS_MACRO_ZEROFILL (&the_param); the_param.log.deliver = ndmjob_log_deliver; the_param.log_level = d_debug; the_param.log_tag = "SESS"; the_param.config_file_name = g_strdup_printf("%s/ndmjob.conf", amdatadir); #ifndef NDMOS_OPTION_NO_CONTROL_AGENT b_bsize = 20; index_fp = stderr; o_tape_addr = -1; o_from_addr = -1; o_to_addr = -1; #endif /* !NDMOS_OPTION_NO_CONTROL_AGENT */ log_fp = stderr; if (ac != 3) proxy_usage(); /* (config arg is ignored for now) */ port = atoi(av[2]); if (!port) proxy_usage(); the_session.param = the_param; ndma_proxy_session (&the_session, port); /* run until all open connections have closed; note that * ndma_dispatch_proxy in ndma_comm_proxy.c will be called in each * quantum */ while (the_session.proxy_starting || the_session.proxy_connections > 0) { ndma_session_quantum(&the_session, 10000); } g_fprintf(stderr, "DONE\n"); /* NOTREACHED */ return 0; }
TechnologicalPizza/AC-1.7.3
src/main/java/io/github/ryuu/adventurecraft/overrides/st.java
<gh_stars>0 package io.github.ryuu.adventurecraft.overrides; public class st { public final eb a; public int b; public int c; public int d; public int e; public int f; public int g; public st(eb enumskyblock, int i, int j, int k, int l, int i1, int j1) { this.a = enumskyblock; this.b = i; this.c = j; this.d = k; this.e = l; this.f = i1; this.g = j1; } public void a(fd world) { int i = this.e - this.b + 1; int j = this.f - this.c + 1; int k = this.g - this.d + 1; int l = i * j * k; if (l > 32768) { System.out.println("Light too large, skipping!"); return; } int i1 = 0; int j1 = 0; boolean flag = false; boolean flag1 = false; for (int k1 = this.b; k1 <= this.e; k1++) { for (int l1 = this.d; l1 <= this.g; l1++) { int i2 = k1 >> 4; int j2 = l1 >> 4; boolean flag2 = false; if (flag && i2 == i1 && j2 == j1) { flag2 = flag1; } else { flag2 = world.b(k1, 0, l1, 1); if (flag2) { lm chunk = world.c(k1 >> 4, l1 >> 4); if (chunk.h()) flag2 = false; } flag1 = flag2; i1 = i2; j1 = j2; } if (flag2) { if (this.c < 0) this.c = 0; if (this.f >= 128) this.f = 127; for (int k2 = this.c; k2 <= this.f; k2++) { int l2 = world.a(this.a, k1, k2, l1); int i3 = 0; int j3 = world.a(k1, k2, l1); int k3 = Tile.q[j3]; if (k3 == 0) k3 = 1; int l3 = 0; if (this.a == eb.a) { if (world.o(k1, k2, l1)) l3 = 15; } else if (this.a == eb.b) { if (Tile.m[j3] != null) { l3 = Tile.m[j3].getBlockLightValue((xp) world, k1, k2, l1); } else { l3 = Tile.s[j3]; } } if (k3 >= 15 && l3 == 0) { i3 = 0; } else { int i4 = world.a(this.a, k1 - 1, k2, l1); int k4 = world.a(this.a, k1 + 1, k2, l1); int l4 = world.a(this.a, k1, k2 - 1, l1); int i5 = world.a(this.a, k1, k2 + 1, l1); int j5 = world.a(this.a, k1, k2, l1 - 1); int k5 = world.a(this.a, k1, k2, l1 + 1); i3 = i4; if (k4 > i3) i3 = k4; if (l4 > i3) i3 = l4; if (i5 > i3) i3 = i5; if (j5 > i3) i3 = j5; if (k5 > i3) i3 = k5; i3 -= k3; if (i3 < 0) i3 = 0; if (l3 > i3) i3 = l3; } if (l2 != i3) { world.b(this.a, k1, k2, l1, i3); int j4 = i3 - 1; if (j4 < 0) j4 = 0; world.a(this.a, k1 - 1, k2, l1, j4); world.a(this.a, k1, k2 - 1, l1, j4); world.a(this.a, k1, k2, l1 - 1, j4); if (k1 + 1 >= this.e) world.a(this.a, k1 + 1, k2, l1, j4); if (k2 + 1 >= this.f) world.a(this.a, k1, k2 + 1, l1, j4); if (l1 + 1 >= this.g) world.a(this.a, k1, k2, l1 + 1, j4); } } } } } } public boolean a(int i, int j, int k, int l, int i1, int j1) { if (i >= this.b && j >= this.c && k >= this.d && l <= this.e && i1 <= this.f && j1 <= this.g) return true; int k1 = 1; if (i >= this.b - k1 && j >= this.c - k1 && k >= this.d - k1 && l <= this.e + k1 && i1 <= this.f + k1 && j1 <= this.g + k1) { int l1 = this.e - this.b; int i2 = this.f - this.c; int j2 = this.g - this.d; if (i > this.b) i = this.b; if (j > this.c) j = this.c; if (k > this.d) k = this.d; if (l < this.e) l = this.e; if (i1 < this.f) i1 = this.f; if (j1 < this.g) j1 = this.g; int k2 = l - i; int l2 = i1 - j; int i3 = j1 - k; int j3 = l1 * i2 * j2; int k3 = k2 * l2 * i3; if (k3 - j3 <= 2) { this.b = i; this.c = j; this.d = k; this.e = l; this.f = i1; this.g = j1; return true; } } return false; } }
olia-la/airy
lib/java/spring/auth/src/test/java/co/airy/spring/auth/JwtAuthenticationFilterTest.java
package co.airy.spring.auth; import co.airy.spring.jwt.Jwt; import co.airy.spring.core.AirySpringBootApplication; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest(properties = { "auth.jwt-secret=424242424242424242424242424242424242424242424242424242" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AirySpringBootApplication.class) @AutoConfigureMockMvc @ExtendWith(SpringExtension.class) public class JwtAuthenticationFilterTest { @Autowired private MockMvc mvc; @Autowired private Jwt jwt; @Test void rejectsMissingJwt() throws Exception { mvc.perform(post("/jwt.get")) .andExpect(status().isForbidden()) .andExpect(jsonPath("$").doesNotExist()); } @Test void setsCorsHeaders() throws Exception { final String origin = "http://example.org"; mvc.perform(options("/jwt.get") .header("Access-Control-Request-Method", "GET") .header("Origin", origin) ) .andExpect(status().isOk()) .andExpect(header().string("Access-Control-Allow-Origin", origin)); } @Test void rejectsInvalidJwt() throws Exception { mvc.perform(post("/jwt.get") .header(HttpHeaders.AUTHORIZATION, "not a jwt") ) .andExpect(status().isForbidden()) .andExpect(jsonPath("$").doesNotExist()); } @Test void authenticatesUser() throws Exception { final String userId = "user-id"; final String token = jwt.tokenFor(userId); mvc.perform(post("/jwt.get") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(HttpHeaders.AUTHORIZATION, token) ) .andExpect(status().isOk()) .andExpect(jsonPath("$.user_id", equalTo(userId))); } }
craftmania-cz/craftmanager
src/main/java/cz/wake/manager/commads/Hud_Command.java
package cz.wake.manager.commads; import co.aikar.commands.BaseCommand; import co.aikar.commands.CommandHelp; import co.aikar.commands.annotation.CommandAlias; import co.aikar.commands.annotation.Default; import co.aikar.commands.annotation.Description; import co.aikar.commands.annotation.HelpCommand; import cz.craftmania.craftlibs.utils.ChatInfo; import cz.wake.manager.Main; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @CommandAlias("hud") @Description("Zobrazování polohy na vrchu obrazovky") public class Hud_Command extends BaseCommand { @HelpCommand public void helpCommand(CommandSender sender, CommandHelp help) { sender.sendMessage("§e§lHUD příkazy:"); help.showHelp(); } @Default public void toggleHud(CommandSender sender) { if (sender instanceof Player) { Player player = (Player) sender; if (Main.getInstance().getMySQL().getSettings(player, "hud_bossbar") == 1) { Main.getInstance().getMySQL().updateSettings(player, "hud_bossbar", 0); Main.getInstance().getCompassManager().removePlayer(player); ChatInfo.INFO.send(player, "Deaktivoval jsi zobrazování polohy na vrchu obrazovky."); } else { Main.getInstance().getMySQL().updateSettings(player, "hud_bossbar", 1); Main.getInstance().getCompassManager().addPlayer(player); ChatInfo.SUCCESS.send(player, "Aktivoval jsi si zobrazování polohy na vrchu obrazovky."); } } } }
anjingbin/starccm
xercesc/xerces-c1_7_0-SolForCC/include/xercesc/util/XMLUniDefs.hpp
<filename>xercesc/xerces-c1_7_0-SolForCC/include/xercesc/util/XMLUniDefs.hpp /* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact <EMAIL>. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id: XMLUniDefs.hpp,v 1.1 2004/07/13 02:37:43 WangKeBo Exp $ */ #if !defined(XMLUNIDEFS_HPP) #define XMLUNIDEFS_HPP #include <xercesc/util/XercesDefs.hpp> // --------------------------------------------------------------------------- // Constants for the Unicode characters of interest to us in an XML parser // We don't put these inside the class because then they could not be const // inline values, which would have significant performance ramifications. // // We cannot use a namespace because of the requirement to support old // compilers. // --------------------------------------------------------------------------- const XMLCh chNull = 0x00; const XMLCh chHTab = 0x09; const XMLCh chLF = 0x0A; const XMLCh chVTab = 0x0B; const XMLCh chFF = 0x0C; const XMLCh chCR = 0x0D; const XMLCh chAmpersand = 0x26; const XMLCh chAsterisk = 0x2A; const XMLCh chAt = 0x40; const XMLCh chBackSlash = 0x5C; const XMLCh chBang = 0x21; const XMLCh chCaret = 0x5E; const XMLCh chCloseAngle = 0x3E; const XMLCh chCloseCurly = 0x7D; const XMLCh chCloseParen = 0x29; const XMLCh chCloseSquare = 0x5D; const XMLCh chColon = 0x3A; const XMLCh chComma = 0x2C; const XMLCh chDash = 0x2D; const XMLCh chDollarSign = 0x24; const XMLCh chDoubleQuote = 0x22; const XMLCh chEqual = 0x3D; const XMLCh chForwardSlash = 0x2F; const XMLCh chGrave = 0x60; const XMLCh chNEL = 0x85; const XMLCh chOpenAngle = 0x3C; const XMLCh chOpenCurly = 0x7B; const XMLCh chOpenParen = 0x28; const XMLCh chOpenSquare = 0x5B; const XMLCh chPercent = 0x25; const XMLCh chPeriod = 0x2E; const XMLCh chPipe = 0x7C; const XMLCh chPlus = 0x2B; const XMLCh chPound = 0x23; const XMLCh chQuestion = 0x3F; const XMLCh chSingleQuote = 0x27; const XMLCh chSpace = 0x20; const XMLCh chSemiColon = 0x3B; const XMLCh chTilde = 0x7E; const XMLCh chUnderscore = 0x5F; const XMLCh chSwappedUnicodeMarker = XMLCh(0xFFFE); const XMLCh chUnicodeMarker = XMLCh(0xFEFF); const XMLCh chDigit_0 = 0x30; const XMLCh chDigit_1 = 0x31; const XMLCh chDigit_2 = 0x32; const XMLCh chDigit_3 = 0x33; const XMLCh chDigit_4 = 0x34; const XMLCh chDigit_5 = 0x35; const XMLCh chDigit_6 = 0x36; const XMLCh chDigit_7 = 0x37; const XMLCh chDigit_8 = 0x38; const XMLCh chDigit_9 = 0x39; const XMLCh chLatin_A = 0x41; const XMLCh chLatin_B = 0x42; const XMLCh chLatin_C = 0x43; const XMLCh chLatin_D = 0x44; const XMLCh chLatin_E = 0x45; const XMLCh chLatin_F = 0x46; const XMLCh chLatin_G = 0x47; const XMLCh chLatin_H = 0x48; const XMLCh chLatin_I = 0x49; const XMLCh chLatin_J = 0x4A; const XMLCh chLatin_K = 0x4B; const XMLCh chLatin_L = 0x4C; const XMLCh chLatin_M = 0x4D; const XMLCh chLatin_N = 0x4E; const XMLCh chLatin_O = 0x4F; const XMLCh chLatin_P = 0x50; const XMLCh chLatin_Q = 0x51; const XMLCh chLatin_R = 0x52; const XMLCh chLatin_S = 0x53; const XMLCh chLatin_T = 0x54; const XMLCh chLatin_U = 0x55; const XMLCh chLatin_V = 0x56; const XMLCh chLatin_W = 0x57; const XMLCh chLatin_X = 0x58; const XMLCh chLatin_Y = 0x59; const XMLCh chLatin_Z = 0x5A; const XMLCh chLatin_a = 0x61; const XMLCh chLatin_b = 0x62; const XMLCh chLatin_c = 0x63; const XMLCh chLatin_d = 0x64; const XMLCh chLatin_e = 0x65; const XMLCh chLatin_f = 0x66; const XMLCh chLatin_g = 0x67; const XMLCh chLatin_h = 0x68; const XMLCh chLatin_i = 0x69; const XMLCh chLatin_j = 0x6A; const XMLCh chLatin_k = 0x6B; const XMLCh chLatin_l = 0x6C; const XMLCh chLatin_m = 0x6D; const XMLCh chLatin_n = 0x6E; const XMLCh chLatin_o = 0x6F; const XMLCh chLatin_p = 0x70; const XMLCh chLatin_q = 0x71; const XMLCh chLatin_r = 0x72; const XMLCh chLatin_s = 0x73; const XMLCh chLatin_t = 0x74; const XMLCh chLatin_u = 0x75; const XMLCh chLatin_v = 0x76; const XMLCh chLatin_w = 0x77; const XMLCh chLatin_x = 0x78; const XMLCh chLatin_y = 0x79; const XMLCh chLatin_z = 0x7A; const XMLCh chYenSign = 0xA5; const XMLCh chWonSign = 0x20A9; const XMLCh chLineSeparator = 0x2028; const XMLCh chParagraphSeparator = 0x2029; #endif
lubbo/onebusaway-openswift
onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/tripplanner/StopTransferServiceImpl.java
<reponame>lubbo/onebusaway-openswift /** * Copyright (C) 2011 <NAME> <<EMAIL>> * * 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.onebusaway.transit_data_federation.impl.tripplanner; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import org.onebusaway.collections.CollectionsLibrary; import org.onebusaway.container.refresh.Refreshable; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.transit_data_federation.impl.RefreshableResources; import org.onebusaway.transit_data_federation.impl.transit_graph.StopEntryImpl; import org.onebusaway.transit_data_federation.services.FederatedTransitDataBundle; import org.onebusaway.transit_data_federation.services.transit_graph.StopEntry; import org.onebusaway.transit_data_federation.services.transit_graph.TransitGraphDao; import org.onebusaway.transit_data_federation.services.tripplanner.StopTransfer; import org.onebusaway.transit_data_federation.services.tripplanner.StopTransferService; import org.onebusaway.utility.ObjectSerializationLibrary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class StopTransferServiceImpl implements StopTransferService { private static Logger _log = LoggerFactory.getLogger(StopTransferServiceImpl.class); private static final StopTransferList EMPTY_TRANSFERS = new StopTransferList( new ArrayList<StopTransfer>()); private FederatedTransitDataBundle _bundle; private TransitGraphDao _transitGraphDao; @Autowired public void setBundle(FederatedTransitDataBundle bundle) { _bundle = bundle; } @Autowired public void setTransitGraphDao(TransitGraphDao transitGraphDao) { _transitGraphDao = transitGraphDao; } @PostConstruct @Refreshable(dependsOn = RefreshableResources.STOP_TRANSFER_DATA) public void setup() throws IOException, ClassNotFoundException { File path = _bundle.getStopTransfersPath(); if (path.exists()) { StopTransferAndHopData allData = ObjectSerializationLibrary.readObject(path); Map<AgencyAndId, List<StopTransferData>> stopTransferDataByStopId = allData.getTransferData(); Map<AgencyAndId, List<StopTransferData>> reversedStopTransfersByStopId = reverseTransfers(stopTransferDataByStopId); Set<AgencyAndId> stopIds = new HashSet<AgencyAndId>(); stopIds.addAll(stopTransferDataByStopId.keySet()); stopIds.addAll(reversedStopTransfersByStopId.keySet()); _log.info("stop transfers=" + stopTransferDataByStopId.size()); _log.info("reverse stop transfers=" + reversedStopTransfersByStopId.size()); for (AgencyAndId stopId : stopIds) { StopEntry stop = _transitGraphDao.getStopEntryForId(stopId); if (stop == null) { _log.warn("unknown stop: " + stopId); continue; } List<StopTransferData> transfersFromStopData = stopTransferDataByStopId.get(stopId); List<StopTransferData> transfersToStopData = reversedStopTransfersByStopId.get(stopId); List<StopTransfer> transfersFromStop = getTransferDataAsList(transfersFromStopData); List<StopTransfer> transfersToStop = getTransferDataAsList(transfersToStopData); StopEntryImpl stopEntry = (StopEntryImpl) stop; stopEntry.setTransfers(new StopTransfers(transfersFromStop, transfersToStop)); } } } @Override public List<StopTransfer> getTransfersFromStop(StopEntry stop) { StopEntryImpl impl = (StopEntryImpl) stop; StopTransfers transfers = impl.getTransfers(); if (transfers == null || transfers.getTransfersFromStop() == null) return EMPTY_TRANSFERS; return transfers.getTransfersFromStop(); } @Override public List<StopTransfer> getTransfersToStop(StopEntry stop) { StopEntryImpl impl = (StopEntryImpl) stop; StopTransfers transfers = impl.getTransfers(); if (transfers == null || transfers.getTransfersToStop() == null) return EMPTY_TRANSFERS; return transfers.getTransfersToStop(); } /**** * ****/ private Map<AgencyAndId, List<StopTransferData>> reverseTransfers( Map<AgencyAndId, List<StopTransferData>> stopTransferDataByStopId) { Map<AgencyAndId, List<StopTransferData>> reversed = new HashMap<AgencyAndId, List<StopTransferData>>(); for (Map.Entry<AgencyAndId, List<StopTransferData>> entry : stopTransferDataByStopId.entrySet()) { AgencyAndId fromStop = entry.getKey(); for (StopTransferData transfer : entry.getValue()) { AgencyAndId toStop = transfer.getStopId(); List<StopTransferData> transfers = reversed.get(toStop); if (transfers == null) { transfers = new ArrayList<StopTransferData>(); reversed.put(toStop, transfers); } StopTransferData reversedTransfer = new StopTransferData(fromStop, transfer.getMinTransferTime(), transfer.getDistance()); transfers.add(reversedTransfer); } } return reversed; } private List<StopTransfer> getTransferDataAsList( List<StopTransferData> transferData) { if (CollectionsLibrary.isEmpty(transferData)) return null; List<StopTransfer> transfers = new ArrayList<StopTransfer>(); for (StopTransferData data : transferData) { AgencyAndId targetStopId = data.getStopId(); StopEntry targetStop = _transitGraphDao.getStopEntryForId(targetStopId); if (targetStop == null) { _log.warn("unkown stop: " + targetStopId); continue; } StopTransfer transfer = new StopTransfer(targetStop, data.getMinTransferTime(), data.getDistance()); transfers.add(transfer); } return new StopTransferList(transfers); } }
lucb31/beam
src/main/scala/ftm/charging/NonlinearChargingModel.scala
<gh_stars>0 package ftm.charging object NonlinearChargingModel { def calcChargingPower(currentEnergyLevelInJoule: Double, batteryCapacityInJoule: Double, maxChargingPowerInKw: Double): Double = { if (currentEnergyLevelInJoule > 0.0) (0.6 * Math.pow(0.05, currentEnergyLevelInJoule / batteryCapacityInJoule) + 0.4) * maxChargingPowerInKw else maxChargingPowerInKw } def calcAvgChargingPowerNumeric(currentEnergyLevelInJoule: Double, batteryCapacityInJoule: Double, maxChargingPowerInKw: Double, chargingLimits: (Double, Double), stepSize: Int = 10): Double = { var updatedEnergyLevelInJoule = currentEnergyLevelInJoule var currentTimestep = 1 // Start at 1 to avoid division by zero while(updatedEnergyLevelInJoule < chargingLimits._2) { val currentChargingPowerInKw = NonlinearChargingModel.calcChargingPower(currentEnergyLevelInJoule, batteryCapacityInJoule, maxChargingPowerInKw) val stepEnergyInJoule = stepSize * currentChargingPowerInKw * 1000 // 3.6e6 / 3600 = 1000 currentTimestep += stepSize updatedEnergyLevelInJoule += stepEnergyInJoule } (chargingLimits._2 - currentEnergyLevelInJoule) / currentTimestep / 1000 } }
looeee/THREE.App
src/DebugOverlay/LightsDebug/subfolders/addDirectionalLightShadowDebug.js
<filename>src/DebugOverlay/LightsDebug/subfolders/addDirectionalLightShadowDebug.js<gh_stars>1-10 function addDirectionalLightShadowDebug(folder, light) { const subfolder = folder.addFolder('Shadow'); subfolder.open(); const shadowCamera = light.shadow.camera; const params = { castShadow: light.castShadow, near: shadowCamera.near, far: shadowCamera.far, top: shadowCamera.top, bottom: shadowCamera.bottom, left: shadowCamera.left, right: shadowCamera.right, radius: light.shadow.radius, bias: light.shadow.bias, }; subfolder .add(params, 'castShadow') .name('Cast Shadow') .onChange(() => { light.castShadow = params.castShadow; }); subfolder .add(params, 'near', 0.001, shadowCamera.near + 5, 0.001) .name('Near') .onChange(() => { shadowCamera.near = params.near; shadowCamera.updateProjectionMatrix(); }); subfolder .add( params, 'far', shadowCamera.far - 5, shadowCamera.far + 5, 0.001, ) .name('far') .onChange(() => { shadowCamera.far = params.far; shadowCamera.updateProjectionMatrix(); }); subfolder .add( params, 'top', shadowCamera.top - 5, shadowCamera.top + 5, 0.001, ) .name('top') .onChange(() => { shadowCamera.top = params.top; shadowCamera.updateProjectionMatrix(); }); subfolder .add( params, 'bottom', shadowCamera.bottom - 5, shadowCamera.bottom + 5, 0.001, ) .name('bottom') .onChange(() => { shadowCamera.bottom = params.bottom; shadowCamera.updateProjectionMatrix(); }); subfolder .add( params, 'left', shadowCamera.left - 5, shadowCamera.left + 5, 0.001, ) .name('left') .onChange(() => { shadowCamera.left = params.left; shadowCamera.updateProjectionMatrix(); }); subfolder .add( params, 'right', shadowCamera.right - 5, shadowCamera.right + 5, 0.001, ) .name('right') .onChange(() => { shadowCamera.right = params.right; shadowCamera.updateProjectionMatrix(); }); subfolder .add(params, 'radius', 1, 8, 0.1) .name('radius') .onChange(() => { light.shadow.radius = params.radius; }); subfolder .add(params, 'bias', -0.01, 0.01, 0.00001) .name('bias') .onChange(() => { light.shadow.bias = params.bias; }); } export { addDirectionalLightShadowDebug };
sunkeding/NEGroupCall
iOS/NEGroupCall-iOS/Class/Person/UI/View/NEFeedbackInputCell.h
// // NEFeedbackInputCell.h // NLiteAVDemo // // Created by <NAME> on 2020/11/22. // Copyright © 2020 Netease. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface NEFeedbackInputCell : UITableViewCell @property (weak, nonatomic) IBOutlet UITextView *textView; @end NS_ASSUME_NONNULL_END
liyaovvvv/RuoYi-fast
src/main/java/com/ruoyi/project/monitor/job/task/RyTask.java
<gh_stars>0 package com.ruoyi.project.monitor.job.task; import com.ruoyi.project.system.data.service.IDataViewService; import com.ruoyi.project.system.gbdata.service.IGbDataService; import com.ruoyi.project.system.gbdata.service.IRefreshSignKeyService; import org.springframework.stereotype.Component; import com.ruoyi.common.utils.StringUtils; import javax.annotation.Resource; /** * 定时任务调度测试 * * @author ruoyi */ @Component("ryTask") public class RyTask { @Resource IDataViewService dataViewService; @Resource private IRefreshSignKeyService refreshSignKeyService; @Resource private IGbDataService gbDataService; public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) { System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i)); } public void ryParams(String params) { System.out.println("执行有参方法:" + params); } public void ryNoParams() { System.out.println("执行无参方法"); } /** * 地市合表统计定时任务 */ public void getDsTableGroupData(){ dataViewService.getDsTableGroupData(); } /** * 省直合表统计定时任务 */ public void getSzTableGroupData(){ dataViewService.getSzTableGroupData(); } /** * 数据治理明细统计定时任务 */ public void accountData(){ dataViewService.accountData(); } /** * 前置库省直数据量统计定时任务 */ public void accountSz(){ dataViewService.accountSz(); } /** * 前置库地市数据量统计定时任务 */ public void accountQZ(){ dataViewService.accountQZ(); } /** * 错误数据统计定时任务 */ public void getZlErrorData(){ dataViewService.getZlErrorData(); } /** * 省直监管事项主营覆盖率 */ public void getSzJgsxZyfgl(){ dataViewService.getSzJgsxZyfgl(); } /** * 地市监管事项主营覆盖率 */ public void getDsJgsxZyfgl(){ dataViewService.getDsJgsxZyfgl(); } /** * 国办数据下发任务密钥更新 */ public void getRefreshSignSecretKey(){ refreshSignKeyService.refreshSignKey(); } /** * 国办数据下发任务检查数据拉取 */ public void getJgxwCheckActionData(){ gbDataService.getGbDataByHttp("1", "0", null); } /** * 国办数据下发任务检查数据拉取 */ public void getJgxwForceActionData(){ gbDataService.getGbDataByHttp("2", "0", null); } /** * 国办数据下发任务检查数据拉取 */ public void getJgxwOtherActionData(){ gbDataService.getGbDataByHttp("3", "0", null); } /** * 国办数据下发任务检查数据拉取 */ public void getJgxwPunishActionData(){ gbDataService.getGbDataByHttp("4", "0", null); } }
unisoc-android/android_packages_apps_TV
src/com/android/tv/ui/api/TunableTvViewPlayingApi.java
/* * Copyright (C) 2018 The Android Open Source Project * * 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.android.tv.ui.api; /** API to play pause and set the volume of a TunableTvView */ public interface TunableTvViewPlayingApi { boolean isPlaying(); void setStreamVolume(float volume); void setTimeShiftListener(TimeShiftListener listener); boolean isTimeShiftAvailable(); void timeShiftPlay(); void timeShiftPause(); void timeShiftRewind(int speed); void timeShiftFastForward(int speed); void timeShiftSeekTo(long timeMs); long timeShiftGetCurrentPositionMs(); /** Used to receive the time-shift events. */ abstract class TimeShiftListener { /** * Called when the availability of the time-shift for the current channel has been changed. * It should be guaranteed that this is called only when the availability is really changed. */ public abstract void onAvailabilityChanged(); /** * Called when the record start time has been changed. This is not called when the recorded * programs is played. */ public abstract void onRecordStartTimeChanged(long recordStartTimeMs); } }
Azure-ukgov-paas/paas-cli
plugin_examples/call_cli_cmd/main/call_cli_cmd.go
/** * This plugin is an example plugin that allows a user to call a cli-command * by typing `cf cli-command name-of-command args.....`. This plugin also prints * the output returned by the CLI when a cli-command is invoked. */ package main import ( "fmt" "github.com/cloudfoundry/cli/plugin" ) type CliCmd struct{} func (c *CliCmd) GetMetadata() plugin.PluginMetadata { return plugin.PluginMetadata{ Name: "CliCmd", Version: plugin.VersionType{ Major: 1, Minor: 1, Build: 0, }, Commands: []plugin.Command{ { Name: "cli-command", HelpText: "Command to call cli command. It passes all arguments through to the command", UsageDetails: plugin.Usage{ Usage: "cli-command\n cf cli-command CORE-COMMAND", }, }, }, } } func main() { plugin.Start(new(CliCmd)) } func (c *CliCmd) Run(cliConnection plugin.CliConnection, args []string) { // Invoke the cf command passed as the set of arguments // after the first argument. // // Calls to plugin.CliCommand([]string) must be done after the invocation // of plugin.Start() to ensure the environment is bootstrapped. output, err := cliConnection.CliCommand(args[1:]...) // The call to plugin.CliCommand() returns an error if the cli command // returns a non-zero return code. The output written by the CLI // is returned in any case. if err != nil { fmt.Println("PLUGIN ERROR: Error from CliCommand: ", err) } // Print the output returned from the CLI command. fmt.Println("") fmt.Println("---------- Command output from the plugin ----------") for index, val := range output { fmt.Println("#", index, " value: ", val) } fmt.Println("---------- FIN -----------") }
dartartem/eventuate-tram-messaging-http
eventuate-tram-messaging-proxy-service/src/main/java/io/eventuate/tram/messaging/proxy/service/SubscriptionRequestManager.java
<filename>eventuate-tram-messaging-proxy-service/src/main/java/io/eventuate/tram/messaging/proxy/service/SubscriptionRequestManager.java package io.eventuate.tram.messaging.proxy.service; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.Consumer; public class SubscriptionRequestManager { private String path; private Logger logger = LoggerFactory.getLogger(getClass()); private CuratorFramework curatorFramework; private TreeCache treeCache; private int ttl; public SubscriptionRequestManager(CuratorFramework curatorFramework, String path, int ttl) { this.path = path; this.curatorFramework = curatorFramework; this.ttl = ttl; } public void subscribe(Consumer<SubscriptionInfo> nodeAddedCallback, Consumer<SubscriptionInfo> nodeRemovedCallback) { if (treeCache != null) { treeCache.close(); } treeCache = new TreeCache(curatorFramework, path); treeCache.getListenable().addListener((client, event) -> { Consumer<SubscriptionInfo> callback; switch (event.getType()) { case NODE_ADDED: { callback = nodeAddedCallback; break; } case NODE_REMOVED: { callback = nodeRemovedCallback; break; } default: return; } if (event.getData().getData() != null && event.getData().getData().length != 0) { callback.accept(SubscriptionUtils.deserializeSubscriptionInfo(event.getData().getData())); } }); try { treeCache.start(); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } } public void touch(String subscriptionInstanceId) { String path = pathForSubscriptionRequest(subscriptionInstanceId); try { curatorFramework .create() .orSetData() .withTtl(ttl) .creatingParentContainersIfNeeded() .withMode(CreateMode.PERSISTENT_WITH_TTL) .forPath(path, curatorFramework.getData().forPath(path)); } catch (KeeperException.NoNodeException e) { //ignore } catch (Exception e) { throw new RuntimeException(e); } } public void createSubscriptionRequest(SubscriptionInfo subscriptionInfo) { try { curatorFramework .create() .orSetData() .withTtl(ttl) .creatingParentContainersIfNeeded() .withMode(CreateMode.PERSISTENT_WITH_TTL) .forPath(pathForSubscriptionRequest(subscriptionInfo.getSubscriptionInstanceId()), SubscriptionUtils.serializeSubscriptionInfo(subscriptionInfo)); } catch (KeeperException.NodeExistsException e) { //ignore } catch (Exception e) { throw new RuntimeException(e); } } public void removeSubscriptionRequest(String subscriptionInstanceId) { try { curatorFramework .delete() .forPath(pathForSubscriptionRequest(subscriptionInstanceId)); } catch (KeeperException.NoNodeException e) { //ignore } catch (Exception e) { throw new RuntimeException(e); } } public void stop() { treeCache.close(); } public String pathForSubscriptionRequest(String subscriptionInstanceId) { return String.format("%s/%s", path, subscriptionInstanceId); } }
Aleksey-Voko/Word_forms_bases
BS/BS_050_120321/main.py
from BS.utils import read_src_socket_bs, save_list_to_file, read_src_bs CYRILLIC = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' def get_bg_abbreviation(): socket_group_list = read_src_socket_bs('src_dict/БГ 09.03.21.txt') abbreviation_bg = [] capital_letter_bg = [] for socket_group in socket_group_list: for sub_group in socket_group.sub_groups: for word_form in sub_group.socket_word_forms: if not word_form.invisible: form_name = word_form.name.replace('*', '') chars = set(form_name[:2]) if all(map(lambda x: x in CYRILLIC, chars)): abbreviation_bg.append(str(word_form)) elif form_name[0] in CYRILLIC: capital_letter_bg.append(str(word_form)) save_list_to_file( sorted(abbreviation_bg, key=lambda x: x.replace('*', '')), 'out/Аббревиатура. БГ.txt' ) save_list_to_file( sorted(capital_letter_bg, key=lambda x: x.replace('*', '')), 'out/Большая буква. БГ.txt' ) def get_bs_abbreviation(): word_forms_bases = read_src_bs('src_dict/БС 09.03.21.txt') abbreviation_bs = [] capital_letter_bs = [] for group in word_forms_bases: title_form = group.title_word_form form_name = title_form.name.replace('*', '') chars = set(form_name[:2]) if all(map(lambda x: x in CYRILLIC, chars)): abbreviation_bs.append(str(title_form)) elif form_name[0] in CYRILLIC: capital_letter_bs.append(str(title_form)) save_list_to_file( sorted(abbreviation_bs, key=lambda x: x.replace('*', '')), 'out/Аббревиатура. БС.txt' ) save_list_to_file( sorted(capital_letter_bs, key=lambda x: x.replace('*', '')), 'out/Большая буква. БС.txt' ) if __name__ == '__main__': get_bs_abbreviation()
probonopd/imagewriter
dependencies/libarchive-3.4.2/libarchive/test/test_write_disk_lookup.c
/*- * Copyright (c) 2003-2010 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.h" __FBSDID("$FreeBSD$"); static void group_cleanup(void *d) { int *mp = d; assertEqualInt(*mp, 0x13579); *mp = 0x2468; } static int64_t group_lookup(void *d, const char *name, int64_t g) { int *mp = d; (void)g; /* UNUSED */ assertEqualInt(*mp, 0x13579); if (strcmp(name, "FOOGROUP")) return (1); return (73); } static void user_cleanup(void *d) { int *mp = d; assertEqualInt(*mp, 0x1234); *mp = 0x2345; } static int64_t user_lookup(void *d, const char *name, int64_t u) { int *mp = d; (void)u; /* UNUSED */ assertEqualInt(*mp, 0x1234); if (strcmp("FOO", name) == 0) return (2); return (74); } DEFINE_TEST(test_write_disk_lookup) { struct archive *a; int gmagic = 0x13579, umagic = 0x1234; int64_t id; assert((a = archive_write_disk_new()) != NULL); /* Default uname/gname lookups always return ID. */ assertEqualInt(0, archive_write_disk_gid(a, "", 0)); assertEqualInt(12, archive_write_disk_gid(a, "root", 12)); assertEqualInt(12, archive_write_disk_gid(a, "wheel", 12)); assertEqualInt(0, archive_write_disk_uid(a, "", 0)); assertEqualInt(18, archive_write_disk_uid(a, "root", 18)); /* Register some weird lookup functions. */ assertEqualInt(ARCHIVE_OK, archive_write_disk_set_group_lookup(a, &gmagic, &group_lookup, &group_cleanup)); /* Verify that our new function got called. */ assertEqualInt(73, archive_write_disk_gid(a, "FOOGROUP", 8)); assertEqualInt(1, archive_write_disk_gid(a, "NOTFOOGROUP", 8)); /* De-register. */ assertEqualInt(ARCHIVE_OK, archive_write_disk_set_group_lookup(a, NULL, NULL, NULL)); /* Ensure our cleanup function got called. */ assertEqualInt(gmagic, 0x2468); /* Same thing with uname lookup.... */ assertEqualInt(ARCHIVE_OK, archive_write_disk_set_user_lookup(a, &umagic, &user_lookup, &user_cleanup)); assertEqualInt(2, archive_write_disk_uid(a, "FOO", 0)); assertEqualInt(74, archive_write_disk_uid(a, "NOTFOO", 1)); assertEqualInt(ARCHIVE_OK, archive_write_disk_set_user_lookup(a, NULL, NULL, NULL)); assertEqualInt(umagic, 0x2345); /* Try the standard lookup functions. */ if (archive_write_disk_set_standard_lookup(a) != ARCHIVE_OK) { skipping("standard uname/gname lookup"); } else { /* Try a few common names for group #0. */ id = archive_write_disk_gid(a, "wheel", 8); if (id != 0) id = archive_write_disk_gid(a, "root", 8); failure("Unable to verify lookup of group #0"); #if defined(_WIN32) && !defined(__CYGWIN__) /* Not yet implemented on Windows. */ assertEqualInt(8, id); #else assertEqualInt(0, id); #endif /* Try a few common names for user #0. */ id = archive_write_disk_uid(a, "root", 8); failure("Unable to verify lookup of user #0"); #if defined(_WIN32) && !defined(__CYGWIN__) /* Not yet implemented on Windows. */ assertEqualInt(8, id); #else assertEqualInt(0, id); #endif } /* Deregister again and verify the default lookups again. */ assertEqualInt(ARCHIVE_OK, archive_write_disk_set_group_lookup(a, NULL, NULL, NULL)); assertEqualInt(ARCHIVE_OK, archive_write_disk_set_user_lookup(a, NULL, NULL, NULL)); assertEqualInt(0, archive_write_disk_gid(a, "", 0)); assertEqualInt(0, archive_write_disk_uid(a, "", 0)); /* Re-register our custom handlers. */ gmagic = 0x13579; umagic = 0x1234; assertEqualInt(ARCHIVE_OK, archive_write_disk_set_group_lookup(a, &gmagic, &group_lookup, &group_cleanup)); assertEqualInt(ARCHIVE_OK, archive_write_disk_set_user_lookup(a, &umagic, &user_lookup, &user_cleanup)); /* Destroy the archive. */ assertEqualInt(ARCHIVE_OK, archive_read_free(a)); /* Verify our cleanup functions got called. */ assertEqualInt(gmagic, 0x2468); assertEqualInt(umagic, 0x2345); }
palantir/stashbot
src/test/java/com/palantir/stash/stashbot/upgrade/ConfigurationUpgradeV2Test.java
// Copyright 2015 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.palantir.stash.stashbot.upgrade; import net.java.ao.DBParam; import net.java.ao.EntityManager; import net.java.ao.test.jdbc.Data; import net.java.ao.test.jdbc.DatabaseUpdater; import net.java.ao.test.jdbc.DynamicJdbcConfiguration; import net.java.ao.test.jdbc.Jdbc; import net.java.ao.test.jdbc.NonTransactional; import net.java.ao.test.junit.ActiveObjectsJUnitRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import com.atlassian.activeobjects.external.ActiveObjects; import com.atlassian.activeobjects.external.ModelVersion; import com.atlassian.activeobjects.test.TestActiveObjects; import com.palantir.stash.stashbot.config.ConfigurationTest.DataStuff; import com.palantir.stash.stashbot.persistence.JobTypeStatusMapping; import com.palantir.stash.stashbot.persistence.RepositoryConfiguration; @RunWith(ActiveObjectsJUnitRunner.class) @Jdbc(DynamicJdbcConfiguration.class) @Data(DataStuff.class) public class ConfigurationUpgradeV2Test { private EntityManager entityManager; private ActiveObjects ao; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); ao = new TestActiveObjects(entityManager); } @Test @NonTransactional public void upgradeTest() throws Exception { ConfigurationV2UpgradeTask u = new ConfigurationV2UpgradeTask(); u.upgrade(ModelVersion.valueOf("1"), ao); Assert.assertEquals(3, ao.find(JobTypeStatusMapping.class).length); } public static class DataStuff implements DatabaseUpdater { @SuppressWarnings("unchecked") @Override public void update(EntityManager entityManager) throws Exception { // create some repo config entityManager.migrate(RepositoryConfiguration.class); RepositoryConfiguration rc = entityManager.create( RepositoryConfiguration.class, new DBParam("REPO_ID", new Integer(10))); rc.setCiEnabled(true); rc.setPublishBranchRegex("publishBranchRegex"); rc.setPublishBuildCommand("publishBuildCommand"); rc.setVerifyBranchRegex("verifyBranchRegex"); rc.setVerifyBuildCommand("verifyBuildCommand"); rc.save(); RepositoryConfiguration rc2 = entityManager.create( RepositoryConfiguration.class, new DBParam("REPO_ID", new Integer(11))); rc2.setCiEnabled(false); rc2.setPublishBranchRegex("publishBranchRegex"); rc2.setPublishBuildCommand("publishBuildCommand"); rc2.setVerifyBranchRegex("verifyBranchRegex"); rc2.setVerifyBuildCommand("verifyBuildCommand"); rc2.save(); } } }
mamez/netCashMovilBase
pom-padre-pibee/pibee_movil_cbd/src/main/java/com/bbva/pibee/cbd/mappers/TtlnemanMapper.java
<filename>pom-padre-pibee/pibee_movil_cbd/src/main/java/com/bbva/pibee/cbd/mappers/TtlnemanMapper.java package com.bbva.pibee.cbd.mappers; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.bbva.pibee.arq.annotations.UtilDto; import com.bbva.pibee.dto.cbd.prueba.TtlnemanDto; public class TtlnemanMapper extends UtilDto implements RowMapper<TtlnemanDto>{ public TtlnemanMapper() { super(TtlnemanDto.class); } @Override public TtlnemanDto mapRow(ResultSet rs, int rowNum) throws SQLException { TtlnemanDto dto= new TtlnemanDto(); dto.setIdOrden(rs.getString(getValueField("idOrden").trim())); dto.setReferencia(rs.getString(getValueField("referencia").trim())); return dto; } }
cheyiliu/test4XXX
test4txMap2/src/com/didi/es/map/marker/EsFromToInfoMarker.java
package com.didi.es.map.marker; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.didi.es.map.base.EsMapView; import com.didi.es.map.base.EsMarkerBase; import com.example.test4txmap.EsApp; import com.example.test4txmap.R; import com.tencent.tencentmap.mapsdk.maps.model.Marker; /** * 在地图上展示行驶里程数和所用时间。 * * @author houshengyong * @since 2015-6-4 */ public class EsFromToInfoMarker extends EsMarkerBase { private View mRootView; private TextView mTextViewFrom; private TextView mTextViewTo; /** * @param mapView * @param iconId * @param lat * @param lng */ public EsFromToInfoMarker(EsMapView mapView, int iconId, double lat, double lng) { super(mapView, iconId, lat, lng); mRootView = LayoutInflater.from(EsApp.sAppContext).inflate(R.layout.map_marker_from_to, null); mTextViewFrom = (TextView) mRootView.findViewById(R.id.from_pos); mTextViewTo = (TextView) mRootView.findViewById(R.id.to_pos); } @Override public View getInfoWindow(Marker arg0) { return mRootView; } /** * 设置从哪里出发的相关信息 * * @param fromPos * @param fromPosDes */ public void setFromInfo(String fromPos, String fromPosDes) { mTextViewFrom.setText(fromPos); showInfoWindow(); } /** * 设置到哪里去的相关信息 * * @param toPos */ public void setToInfo(String toPos) { mTextViewTo.setText(toPos); showInfoWindow(); } /** * 设置从哪里到哪里 * * @param fromPos * @param toPos */ public void setFromToInfo(String fromPos, String toPos) { mTextViewFrom.setText(fromPos); mTextViewTo.setText(toPos); showInfoWindow(); } }
dareludum/icfpc2020
vendor/fltk-sys/cfltk/fltk/src/Fl_Gl_Choice.cxx
// // OpenGL visual selection code for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2018 by <NAME> and others. // // This library is free software. Distribution and use rights are outlined in // the file "COPYING" which should have been included with this file. If this // file is missing or damaged, see the license at: // // https://www.fltk.org/COPYING.php // // Please see the following page on how to report bugs and issues: // // https://www.fltk.org/bugs.php // #include "config_lib.h" #if HAVE_GL # include <FL/Fl.H> # include <stdlib.h> # include "Fl_Gl_Choice.H" # include <FL/Fl_Gl_Window.H> # include "Fl_Gl_Window_Driver.H" # include <FL/gl_draw.H> # include "flstring.h" # include <FL/fl_utf8.h> static GLContext *context_list = 0; static int nContext = 0, NContext = 0; static void add_context(GLContext ctx) { if (!ctx) return; if (nContext==NContext) { if (!NContext) NContext = 8; NContext *= 2; context_list = (GLContext*)realloc( context_list, NContext*sizeof(GLContext)); } context_list[nContext++] = ctx; } static void del_context(GLContext ctx) { int i; for (i=0; i<nContext; i++) { if (context_list[i]==ctx) { memmove(context_list+i, context_list+i+1, (nContext-i-1) * sizeof(GLContext)); context_list[--nContext] = 0; break; } } if (!nContext) gl_remove_displaylist_fonts(); } static Fl_Gl_Choice *first; /** \cond DriverDev \addtogroup DriverDeveloper \{ */ // this assumes one of the two arguments is zero: // We keep the list system in Win32 to stay compatible and interpret // the list later... Fl_Gl_Choice *Fl_Gl_Window_Driver::find_begin(int m, const int *alistp) { Fl_Gl_Choice *g; for (g = first; g; g = g->next) if (g->mode == m && g->alist == alistp) return g; return NULL; } /** \} \endcond */ static GLContext cached_context; static Fl_Window* cached_window; #ifdef FL_CFG_GFX_QUARTZ # include "drivers/Cocoa/Fl_Cocoa_Window_Driver.H" # include "Fl_Screen_Driver.H" extern void gl_texture_reset(); Fl_Gl_Choice *Fl_Cocoa_Gl_Window_Driver::find(int m, const int *alistp) { Fl::screen_driver()->open_display(); // useful when called through gl_start() Fl_Gl_Choice *g = Fl_Gl_Window_Driver::find_begin(m, alistp); if (g) return g; NSOpenGLPixelFormat* fmt = Fl_Cocoa_Window_Driver::mode_to_NSOpenGLPixelFormat(m, alistp); if (!fmt) return 0; g = new Fl_Gl_Choice(m, alistp, first); first = g; g->pixelformat = fmt; return g; } GLContext Fl_Cocoa_Gl_Window_Driver::create_gl_context(Fl_Window* window, const Fl_Gl_Choice* g, int layer) { GLContext context, shared_ctx = 0; if (context_list && nContext) shared_ctx = context_list[0]; // resets the pile of string textures used to draw strings // necessary before the first context is created if (!shared_ctx) gl_texture_reset(); context = Fl_Cocoa_Window_Driver::create_GLcontext_for_window((NSOpenGLPixelFormat*)g->pixelformat, shared_ctx, window); if (!context) return 0; add_context(context); return (context); } void Fl_Cocoa_Gl_Window_Driver::set_gl_context(Fl_Window* w, GLContext context) { if (context != cached_context || w != cached_window) { cached_context = context; cached_window = w; Fl_Cocoa_Window_Driver::GLcontext_makecurrent(context); } } void Fl_Cocoa_Gl_Window_Driver::delete_gl_context(GLContext context) { if (cached_context == context) { cached_context = 0; cached_window = 0; Fl_Cocoa_Window_Driver::GL_cleardrawable(); } Fl_Cocoa_Window_Driver::GLcontext_release(context); del_context(context); } #endif // FL_CFG_GFX_QUARTZ #ifdef FL_CFG_GFX_GDI # include <FL/platform.H> # include <FL/Fl_Graphics_Driver.H> #include "drivers/WinAPI/Fl_WinAPI_Window_Driver.H" extern void fl_save_dc(HWND, HDC); // STR #3119: select pixel format with composition support // ... and no more than 32 color bits (8 bits/color) // Ref: PixelFormatDescriptor Object // https://msdn.microsoft.com/en-us/library/cc231189.aspx #if !defined(PFD_SUPPORT_COMPOSITION) # define PFD_SUPPORT_COMPOSITION (0x8000) #endif #define DEBUG_PFD (0) // 1 = PFD selection debug output, 0 = no debug output Fl_Gl_Choice *Fl_WinAPI_Gl_Window_Driver::find(int m, const int *alistp) { Fl_Gl_Choice *g = Fl_Gl_Window_Driver::find_begin(m, alistp); if (g) return g; // Replacement for ChoosePixelFormat() that finds one with an overlay if possible: HDC gc = (HDC)(fl_graphics_driver ? fl_graphics_driver->gc() : 0); if (!gc) gc = fl_GetDC(0); int pixelformat = 0; PIXELFORMATDESCRIPTOR chosen_pfd; for (int i = 1; ; i++) { PIXELFORMATDESCRIPTOR pfd; if (!DescribePixelFormat(gc, i, sizeof(pfd), &pfd)) break; // continue if it does not satisfy our requirements: if (~pfd.dwFlags & (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL)) continue; if (pfd.iPixelType != ((m&FL_INDEX)?PFD_TYPE_COLORINDEX:PFD_TYPE_RGBA)) continue; if ((m & FL_ALPHA) && !pfd.cAlphaBits) continue; if ((m & FL_ACCUM) && !pfd.cAccumBits) continue; if ((!(m & FL_DOUBLE)) != (!(pfd.dwFlags & PFD_DOUBLEBUFFER))) continue; if ((!(m & FL_STEREO)) != (!(pfd.dwFlags & PFD_STEREO))) continue; if ((m & FL_DEPTH) && !pfd.cDepthBits) continue; if ((m & FL_STENCIL) && !pfd.cStencilBits) continue; #if DEBUG_PFD printf("pfd #%d supports composition: %s\n", i, (pfd.dwFlags & PFD_SUPPORT_COMPOSITION) ? "yes" : "no"); printf(" ... & PFD_GENERIC_FORMAT: %s\n", (pfd.dwFlags & PFD_GENERIC_FORMAT) ? "generic" : "accelerated"); printf(" ... Overlay Planes : %d\n", pfd.bReserved & 15); printf(" ... Color & Depth : %d, %d\n", pfd.cColorBits, pfd.cDepthBits); if (pixelformat) printf(" current pixelformat : %d\n", pixelformat); fflush(stdout); #endif // DEBUG_PFD // see if better than the one we have already: if (pixelformat) { // offering non-generic rendering is better (read: hardware acceleration) if (!(chosen_pfd.dwFlags & PFD_GENERIC_FORMAT) && (pfd.dwFlags & PFD_GENERIC_FORMAT)) continue; // offering overlay is better: else if (!(chosen_pfd.bReserved & 15) && (pfd.bReserved & 15)) {} // otherwise prefer a format that supports composition (STR #3119) else if ((chosen_pfd.dwFlags & PFD_SUPPORT_COMPOSITION) && !(pfd.dwFlags & PFD_SUPPORT_COMPOSITION)) continue; // otherwise more bit planes is better, but no more than 32 (8 bits per channel): else if (pfd.cColorBits > 32 || chosen_pfd.cColorBits > pfd.cColorBits) continue; else if (chosen_pfd.cDepthBits > pfd.cDepthBits) continue; } pixelformat = i; chosen_pfd = pfd; } #if DEBUG_PFD static int bb = 0; if (!bb) { bb = 1; printf("PFD_SUPPORT_COMPOSITION = 0x%x\n", PFD_SUPPORT_COMPOSITION); } printf("Chosen pixel format is %d\n", pixelformat); printf("Color bits = %d, Depth bits = %d\n", chosen_pfd.cColorBits, chosen_pfd.cDepthBits); printf("Pixel format supports composition: %s\n", (chosen_pfd.dwFlags & PFD_SUPPORT_COMPOSITION) ? "yes" : "no"); fflush(stdout); #endif // DEBUG_PFD if (!pixelformat) return 0; g = new Fl_Gl_Choice(m, alistp, first); first = g; g->pixelformat = pixelformat; g->pfd = chosen_pfd; return g; } GLContext Fl_WinAPI_Gl_Window_Driver::create_gl_context(Fl_Window* window, const Fl_Gl_Choice* g, int layer) { Fl_X* i = Fl_X::i(window); HDC hdc = Fl_WinAPI_Window_Driver::driver(window)->private_dc; if (!hdc) { hdc = Fl_WinAPI_Window_Driver::driver(window)->private_dc = GetDCEx(i->xid, 0, DCX_CACHE); fl_save_dc(i->xid, hdc); SetPixelFormat(hdc, g->pixelformat, (PIXELFORMATDESCRIPTOR*)(&g->pfd)); # if USE_COLORMAP if (fl_palette) SelectPalette(hdc, fl_palette, FALSE); # endif } GLContext context = layer ? wglCreateLayerContext(hdc, layer) : wglCreateContext(hdc); if (context) { if (context_list && nContext) wglShareLists(context_list[0], context); add_context(context); } return context; } void Fl_WinAPI_Gl_Window_Driver::set_gl_context(Fl_Window* w, GLContext context) { if (context != cached_context || w != cached_window) { cached_context = context; cached_window = w; wglMakeCurrent(Fl_WinAPI_Window_Driver::driver(w)->private_dc, context); } } void Fl_WinAPI_Gl_Window_Driver::delete_gl_context(GLContext context) { if (cached_context == context) { cached_context = 0; cached_window = 0; wglMakeCurrent(0, 0); } wglDeleteContext(context); del_context(context); } #endif // FL_CFG_GFX_GDI #ifdef FL_CFG_GFX_XLIB # include <FL/platform.H> static XVisualInfo *gl3_getvisual(const int *blist, GLXFBConfig *pbestFB) { int glx_major, glx_minor; // FBConfigs were added in GLX version 1.3. if ( !glXQueryVersion(fl_display, &glx_major, &glx_minor) || ( ( glx_major == 1 ) && ( glx_minor < 3 ) ) || ( glx_major < 1 ) ) { return NULL; } //printf( "Getting matching framebuffer configs\n" ); int fbcount; GLXFBConfig* fbc = glXChooseFBConfig(fl_display, DefaultScreen(fl_display), blist, &fbcount); if (!fbc) { //printf( "Failed to retrieve a framebuffer config\n" ); return NULL; } //printf( "Found %d matching FB configs.\n", fbcount ); // Pick the FB config/visual with the most samples per pixel int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; for (int i = 0; i < fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig( fl_display, fbc[i] ); if (vi) { int samp_buf, samples; glXGetFBConfigAttrib(fl_display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetFBConfigAttrib(fl_display, fbc[i], GLX_SAMPLES , &samples ); /*printf( " Matching fbconfig %d, visual ID 0x%2lx: SAMPLE_BUFFERS = %d, SAMPLES = %d\n", i, vi -> visualid, samp_buf, samples );*/ if ( best_fbc < 0 || (samp_buf && samples > best_num_samp) ) best_fbc = i, best_num_samp = samples; if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp ) worst_fbc = i, worst_num_samp = samples; } XFree(vi); } GLXFBConfig bestFbc = fbc[ best_fbc ]; // Be sure to free the FBConfig list allocated by glXChooseFBConfig() XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(fl_display, bestFbc); *pbestFB = bestFbc; return vi; } Fl_Gl_Choice *Fl_X11_Gl_Window_Driver::find(int m, const int *alistp) { Fl_Gl_Choice *g = Fl_Gl_Window_Driver::find_begin(m, alistp); if (g) return g; const int *blist; int list[32]; if (alistp) blist = alistp; else { int n = 0; if (m & FL_INDEX) { list[n++] = GLX_BUFFER_SIZE; list[n++] = 8; // glut tries many sizes, but this should work... } else { list[n++] = GLX_RGBA; list[n++] = GLX_GREEN_SIZE; list[n++] = (m & FL_RGB8) ? 8 : 1; if (m & FL_ALPHA) { list[n++] = GLX_ALPHA_SIZE; list[n++] = (m & FL_RGB8) ? 8 : 1; } if (m & FL_ACCUM) { list[n++] = GLX_ACCUM_GREEN_SIZE; list[n++] = 1; if (m & FL_ALPHA) { list[n++] = GLX_ACCUM_ALPHA_SIZE; list[n++] = 1; } } } if (m & FL_DOUBLE) { list[n++] = GLX_DOUBLEBUFFER; } if (m & FL_DEPTH) { list[n++] = GLX_DEPTH_SIZE; list[n++] = 1; } if (m & FL_STENCIL) { list[n++] = GLX_STENCIL_SIZE; list[n++] = 1; } if (m & FL_STEREO) { list[n++] = GLX_STEREO; } # if defined(GLX_VERSION_1_1) && defined(GLX_SGIS_multisample) if (m & FL_MULTISAMPLE) { list[n++] = GLX_SAMPLES_SGIS; list[n++] = 4; // value Glut uses } # endif list[n] = 0; blist = list; } fl_open_display(); XVisualInfo *visp = NULL; GLXFBConfig best_fb = NULL; if (m & FL_OPENGL3) { visp = gl3_getvisual((const int *)blist, &best_fb); } if (!visp) { visp = glXChooseVisual(fl_display, fl_screen, (int *)blist); if (!visp) { # if defined(GLX_VERSION_1_1) && defined(GLX_SGIS_multisample) if (m&FL_MULTISAMPLE) return find(m&~FL_MULTISAMPLE, 0); # endif return 0; } } g = new Fl_Gl_Choice(m, alistp, first); first = g; g->vis = visp; g->best_fb = best_fb; if (/*MaxCmapsOfScreen(ScreenOfDisplay(fl_display,fl_screen))==1 && */ visp->visualid == fl_visual->visualid && !fl_getenv("MESA_PRIVATE_CMAP")) g->colormap = fl_colormap; else g->colormap = XCreateColormap(fl_display, RootWindow(fl_display,fl_screen), visp->visual, AllocNone); return g; } static bool ctxErrorOccurred = false; static int ctxErrorHandler( Display *dpy, XErrorEvent *ev ) { ctxErrorOccurred = true; return 0; } GLContext Fl_X11_Gl_Window_Driver::create_gl_context(Fl_Window* window, const Fl_Gl_Choice* g, int layer) { GLContext shared_ctx = 0; if (context_list && nContext) shared_ctx = context_list[0]; typedef GLContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLContext, Bool, const int*); // It is not necessary to create or make current to a context before calling glXGetProcAddressARB static glXCreateContextAttribsARBProc glXCreateContextAttribsARB = #if defined(HAVE_GLXGETPROCADDRESSARB) (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte *)"glXCreateContextAttribsARB"); #else NULL; #endif GLContext ctx = 0; // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. const char *glxExts = glXQueryExtensionsString(fl_display, fl_screen); if (g->best_fb && strstr(glxExts, "GLX_ARB_create_context") && glXCreateContextAttribsARB ) { int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 2, //GLX_CONTEXT_FLAGS_ARB , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, //GLX_CONTEXT_PROFILE_MASK_ARB , GLX_CONTEXT_CORE_PROFILE_BIT_ARB, None }; ctxErrorOccurred = false; XErrorHandler oldHandler = XSetErrorHandler(&ctxErrorHandler); ctx = glXCreateContextAttribsARB(fl_display, g->best_fb, shared_ctx, true, context_attribs); XSync(fl_display, false); // Sync to ensure any errors generated are processed. if (ctxErrorOccurred) ctx = 0; XSetErrorHandler(oldHandler); } if (!ctx) { // use OpenGL 1-style context creation ctx = glXCreateContext(fl_display, g->vis, shared_ctx, true); } if (ctx) add_context(ctx); //glXMakeCurrent(fl_display, fl_xid(window), ctx);printf("%s\n", glGetString(GL_VERSION)); return ctx; } GLContext Fl_X11_Gl_Window_Driver::create_gl_context(XVisualInfo *vis) { GLContext shared_ctx = 0; if (context_list && nContext) shared_ctx = context_list[0]; GLContext context = glXCreateContext(fl_display, vis, shared_ctx, 1); if (context) add_context(context); return context; } void Fl_X11_Gl_Window_Driver::set_gl_context(Fl_Window* w, GLContext context) { if (context != cached_context || w != cached_window) { cached_context = context; cached_window = w; glXMakeCurrent(fl_display, fl_xid(w), context); } } void Fl_X11_Gl_Window_Driver::delete_gl_context(GLContext context) { if (cached_context == context) { cached_context = 0; cached_window = 0; glXMakeCurrent(fl_display, 0, 0); } glXDestroyContext(fl_display, context); del_context(context); } #endif // FL_CFG_GFX_XLIB #endif // HAVE_GL
rafarbop/Python
desafio33.py
# Desafio 33 Curso em Video Python # Este programa ordena três números em sequência. # By Rafabr import sys import time import os import random os.system('clear') print('\nDesafio 33') print('Este programa ordena três números em sequência.\n\n') try: n1 = float(input('Informe o primeiro número: ').strip()) n2 = float(input('Informe o segundo número: ').strip()) n3 = float(input('Informe o terceiro número: ').strip()) except ValueError: os.system('clear') print('Voçe não digitou números válido!') time.sleep(0.5) sys.exit() if n1 == n2 or n1 == n3 or n2 == n3: os.system('clear') print('Voçe digitou 2 números ou mais iguais!') time.sleep(0.5) sys.exit() os.system('clear') if n1 < n2: if n1 < n3: print(f'O menor número é {n1}') if n2 < n3: print(f'O maior número é {n3}') print(f'A sequência crescente é {n1} -> {n2} -> {n3}') else: print(f'O maior número é {n2}') print(f'A sequência crescente é {n1} -> {n3} -> {n2}') else: print(f'O menor número é {n3}') print(f'O maior número é {n2}') print(f'A sequência crescente é {n3} -> {n1} -> {n2}') else: if n2 < n3: print(f'O menor número é {n2}') if n1 < n3: print(f'O maior número é {n3}') print(f'A sequência crescente é {n2} -> {n1} -> {n3}') else: print(f'O maior número é {n1}') print(f'A sequência crescente é {n2} -> {n3} -> {n1}') else: print(f'O menor número é {n3}') print(f'O maior número é {n1}') print(f'A sequência crescente é {n3} -> {n2} -> {n1}') print('\n---Fim da execução---\n')
zhangdddong/beautifulNLP
命名实体识别/hmm/model_utils.py
<filename>命名实体识别/hmm/model_utils.py<gh_stars>1-10 #!/usr/bin/python3 # -*- coding: UTF-8 -*- __author__ = 'zd' import numpy as np def log(v): if v == 0: return np.log(v + 0.00000001) return np.log(v) def get_matrix(word2id, tag2id, id2tag, file_path): """ :param word2id: :param tag2id: :param id2tag: :param file_path: :return: """ num_words = len(word2id) # 训练集中词的数量 num_tags = len(tag2id) # 训练集中的标签的数量 pi = np.zeros(num_tags) # 初始状态概率矩阵 A = np.zeros((num_tags, num_words)) # 发射概率矩阵 B = np.zeros((num_tags, num_tags)) # 状态转移概率矩阵 # 计算矩阵中的对应数据出现的次数 prev_tag = '' for line in open(file_path, encoding='UTF-8'): items = line.split(' ') wordId, tagId = word2id[items[0]], tag2id[items[1].rstrip()] if prev_tag == '': pi[tagId] += 1 A[tagId][wordId] += 1 else: A[tagId][wordId] += 1 B[tag2id[prev_tag]][tagId] += 1 if items[0] == '.': prev_tag = '' else: prev_tag = id2tag[tagId] # normalize 将统计的个数化成概率 pi = pi / sum(pi) for i in range(num_tags): A[i] /= sum(A[i]) B[i] /= sum(B[i]) # 到此为止,计算完了模型的所有参数:pi A B return pi, A, B
jadedevin13/collect
collect-webapp/frontend/src/common/hooks/index.js
<gh_stars>10-100 export { useRecordEvent } from './useRecordEvent' export { useWindowResize } from './useWindowResize'
jiaojie1989/osc-android
app/src/main/java/net/oschina/app/fragment/TweetsFragment.java
package net.oschina.app.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import net.oschina.app.AppContext; import net.oschina.app.R; import net.oschina.app.adapter.TweetAdapter; import net.oschina.app.api.OperationResponseHandler; import net.oschina.app.api.remote.OSChinaApi; import net.oschina.app.base.BaseListFragment; import net.oschina.app.bean.Constants; import net.oschina.app.bean.Result; import net.oschina.app.bean.ResultBean; import net.oschina.app.bean.Tweet; import net.oschina.app.bean.TweetsList; import net.oschina.app.improve.account.AccountHelper; import net.oschina.app.improve.tweet.activities.TweetDetailActivity; import net.oschina.app.improve.utils.DialogHelper; import net.oschina.app.interf.OnTabReselectListener; import net.oschina.app.ui.empty.EmptyLayout; import net.oschina.app.util.HTMLUtil; import net.oschina.app.util.TDevice; import net.oschina.app.util.UIHelper; import net.oschina.app.util.XmlUtils; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import cz.msebera.android.httpclient.Header; /** * @author kymjs (http://www.kymjs.com) */ public class TweetsFragment extends BaseListFragment<Tweet> implements OnItemLongClickListener, OnTabReselectListener { protected static final String TAG = TweetsFragment.class.getSimpleName(); private static final String CACHE_KEY_PREFIX = "tweetslist_"; private class DeleteTweetResponseHandler extends OperationResponseHandler { DeleteTweetResponseHandler(Object... args) { super(args); } @Override public void onSuccess(int code, ByteArrayInputStream is, Object[] args) throws Exception { try { Result res = XmlUtils.toBean(ResultBean.class, is).getResult(); if (res != null && res.OK()) { AppContext.showToastShort(R.string.delete_success); Tweet tweet = (Tweet) args[0]; mAdapter.removeItem(tweet); mAdapter.notifyDataSetChanged(); } else { onFailure(code, res.getErrorMessage(), args); } } catch (Exception e) { e.printStackTrace(); onFailure(code, e.getMessage(), args); } } @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) { super.onSuccess(arg0, arg1, arg2); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { AppContext.showToastShort(R.string.delete_faile); } } @Override protected int getLayoutId() { return R.layout.fragment_tweets; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mCatalog > 0) { IntentFilter filter = new IntentFilter( Constants.INTENT_ACTION_USER_CHANGE); filter.addAction(Constants.INTENT_ACTION_LOGOUT); getActivity().registerReceiver(mReceiver, filter); } } @Override public void onDestroy() { if (mCatalog > 0) { getActivity().unregisterReceiver(mReceiver); } super.onDestroy(); } @Override protected TweetAdapter getListAdapter() { return new TweetAdapter(); } @Override protected String getCacheKeyPrefix() { Bundle bundle = getArguments(); if (bundle != null) { String str = bundle.getString("topic"); if (str != null) { return str; } } return CACHE_KEY_PREFIX + mCatalog; } public String getTopic() { Bundle bundle = getArguments(); if (bundle != null) { String str = bundle.getString("topic"); if (str != null) { return str; } } return ""; } @Override protected TweetsList parseList(InputStream is) throws Exception { TweetsList list = XmlUtils.toBean(TweetsList.class, is); return list; } @Override protected TweetsList readList(Serializable seri) { return ((TweetsList) seri); } @Override protected void sendRequestData() { Bundle bundle = getArguments(); if (bundle != null) { String str = bundle.getString("topic"); if (str != null) { OSChinaApi.getTweetTopicList(mCurrentPage, str, mHandler); return; } } OSChinaApi.getTweetList(mCatalog, mCurrentPage, mHandler); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = mAdapter.getItem(position); if (tweet != null) { // UIUtil.showTweetDetail(view.getContext(), null, tweet.getId()); TweetDetailActivity.show(view.getContext(), tweet.getId()); } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (isAdded()) { setupContent(); } } }; private void setupContent() { if (AccountHelper.isLogin()) { mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING); requestData(true); } else { mCatalog = TweetsList.CATALOG_ME; mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR); mErrorLayout.setErrorMessage(getString(R.string.unlogin_tip)); } } @Override protected void requestData(boolean refresh) { if (mCatalog > 0) { if (AccountHelper.isLogin()) { mCatalog = (int) AccountHelper.getUserId(); super.requestData(refresh); } else { mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR); mErrorLayout.setErrorMessage(getString(R.string.unlogin_tip)); } } else { super.requestData(refresh); } } @Override public void initView(View view) { super.initView(view); mListView.setOnItemLongClickListener(this); mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCatalog > 0) { if (AccountHelper.isLogin()) { mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING); requestData(true); } else { UIHelper.showLoginActivity(getActivity()); } } else { mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING); requestData(true); } } }); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = mAdapter.getItem(position); if (tweet != null) { handleLongClick(tweet); return true; } return false; } private void handleLongClick(final Tweet tweet) { String[] items; if (AccountHelper.getUserId() == tweet.getAuthorid()) { items = new String[]{getString(R.string.copy), getString(R.string.delete)}; } else { items = new String[]{getString(R.string.copy)}; } DialogHelper.getSelectDialog(getActivity(), items, "消息", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i) { case 0: TDevice.copyTextToBoard(HTMLUtil.delHTMLTag(tweet.getBody())); break; case 1: handleDeleteTweet(tweet); break; } } }).show(); } private void handleDeleteTweet(final Tweet tweet) { DialogHelper.getConfirmDialog(getActivity(), "是否删除该动弹?", new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { OSChinaApi.deleteTweet(tweet.getAuthorid(), tweet .getId(), new DeleteTweetResponseHandler(tweet)); } }).show(); } @Override public void onTabReselect() { onRefresh(); } @Override protected long getAutoRefreshTime() { // 最新动弹3分钟刷新一次 if (mCatalog == TweetsList.CATALOG_LATEST) { return 3 * 60; } return super.getAutoRefreshTime(); } }
ivan-gammel/orm16
processor/src/main/java/com/esoftworks/orm16/processor/model/TypeMapping.java
<filename>processor/src/main/java/com/esoftworks/orm16/processor/model/TypeMapping.java<gh_stars>0 package com.esoftworks.orm16.processor.model; public record TypeMapping(String jdbcType, boolean cast, ConversionInvocation onRead, ConversionInvocation onWrite) { public static TypeMapping mapTo(String type) { return new TypeMapping(type, false, null, null); } public static TypeMapping cast(String type) { return new TypeMapping(type, true, null, null); } public static TypeMapping mapTo(String type, ConversionInvocation onRead, ConversionInvocation onWrite) { return new TypeMapping(type, false, onRead, onWrite); } }
WerHawer/goit-js-fe-25
module-8/photoToPage.js
"use strict"; import photos from "./gallery-items.js"; import photoMarkup from "./photoMarkup.js"; import refs from "./refs.js"; import { lazyLoad } from "./lazyLoad.js"; export function photoToPage(arr) { const allPhoto = arr .map(({ preview, original, description }) => photoMarkup(preview, original, description) ) .join(""); refs.galeryArea.insertAdjacentHTML("beforeend", allPhoto); } photoToPage(photos); const lazyPhotos = document.querySelectorAll("li img"); lazyPhotos.forEach(photo => { lazyLoad(photo); });
sramana2/so
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PayloadConstants.java
<filename>bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PayloadConstants.java<gh_stars>0 /*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2019 Bell Canada * ================================================================================ * Modifications Copyright (C) 2020 Nordix * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.so.client.cds; public final class PayloadConstants { private PayloadConstants() { } public static final String REQUEST = "request"; public static final String PROPERTIES = "properties"; public static final String SCOPE = "scope"; public static final String ACTION = "action"; public static final String MODE = "mode"; public static final String SEPARATOR = "-"; public static final String PNF_SCOPE = "pnf"; public static final String VNF_SCOPE = "vnf"; public static final String VF_MODULE_SCOPE = "vfModule"; public static final String SERVICE_SCOPE = "service"; public static final String RESOLUTION_KEY = "resolution-key"; public static final String CDS_ACTOR = "cds"; public static final String PRC_BLUEPRINT_NAME = "PRC_blueprintName"; public static final String PRC_BLUEPRINT_VERSION = "PRC_blueprintVersion"; public static final String PRC_CUSTOMIZATION_UUID = "PRC_customizationUuid"; public static final String PRC_TARGET_SOFTWARE_VERSION = "targetSoftwareVersion"; public final static String PNF_CORRELATION_ID = "pnfCorrelationId"; public final static String PNF_UUID = "pnfUuid"; public final static String SERVICE_INSTANCE_ID = "serviceInstanceId"; public final static String MODEL_UUID = "modelUuid"; }
qianzha/BloodMagic
BM_src/forestry/api/apiculture/package-info.java
<reponame>qianzha/BloodMagic<gh_stars>0 @API(apiVersion="1.0", owner="ForestryAPI|core", provides="ForestryAPI|apiculture") package forestry.api.apiculture; import cpw.mods.fml.common.API;
dunwu/zero
zero-aaa/zero-aaa-provider/src/main/java/io/github/dunwu/zero/aaa/controller/LoginInfoController.java
<reponame>dunwu/zero package io.github.dunwu.zero.aaa.controller; import io.github.dunwu.core.*; import io.github.dunwu.zero.aaa.entity.LoginInfo; import io.github.dunwu.zero.aaa.service.LoginInfoService; import io.github.dunwu.web.controller.CrudController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.Serializable; import java.util.Collection; /** * 登录信息表 前端控制器 * * @author <a href="mailto:<EMAIL>"><NAME></a> * @since 2019-06-16 */ @RestController @RequestMapping("/login-info") @Api(tags = "LoginInfo", description = "登录信息表 CRUD Controller") public class LoginInfoController extends CrudController<LoginInfo> { private final LoginInfoService service; @Autowired public LoginInfoController(LoginInfoService service) { super(service); this.service = service; } @Override @GetMapping("count") @ApiOperation(value = "返回符合查询条件的 LoginInfo 记录数,如果 entity 为 null,返回所有记录数") public DataResult<Integer> count(LoginInfo entity) { return super.count(entity); } @Override @GetMapping("list") @ApiOperation(value = "返回符合查询条件的 LoginInfo 记录,如果 entity 为 null,返回所有记录") public DataListResult<LoginInfo> list(LoginInfo entity) { return super.list(entity); } @Override @GetMapping("page") @ApiOperation(value = "分页查询符合条件的 LoginInfo 记录,如果 entity 为 null,返回所有记录的分页查询结果") public PageResult<LoginInfo> page(LoginInfo entity, Page page) { return super.page(entity, page); } @Override @PostMapping("save") @ApiOperation(value = "插入一条 LoginInfo 记录(选择字段)") public BaseResult save(LoginInfo entity) { return super.save(entity); } @Override @PostMapping("saveBatch") @ApiOperation(value = "批量添加 LoginInfo 记录(选择字段)") public BaseResult saveBatch(Collection<LoginInfo> entityList) { return super.saveBatch(entityList); } @Override @PostMapping("remove") @ApiOperation(value = "删除符合条件的 LoginInfo 记录") public BaseResult remove(LoginInfo entity) { return super.remove(entity); } @Override @PostMapping("removeById") @ApiOperation(value = "根据 ID 删除一条 LoginInfo 记录") public BaseResult removeById(Long id) { return super.removeById(id); } @Override @PostMapping("removeByIds") @ApiOperation(value = "根据 ID 批量删除 LoginInfo 记录") public BaseResult removeByIds(Collection<? extends Serializable> idList) { return super.removeByIds(idList); } @Override @PostMapping("update") @ApiOperation(value = "根据 origin 条件,更新一条 LoginInfo 记录 target") public BaseResult update( @RequestBody @ApiParam(name = "target", value = "LoginInfo 对象(json 格式)", required = true) LoginInfo target, LoginInfo origin) { return super.update(target, origin); } @Override @PostMapping("updateById") @ApiOperation(value = "根据 ID 选择修改一条 LoginInfo 记录") public BaseResult updateById(LoginInfo entity) { return super.updateById(entity); } @Override @PostMapping("updateBatchById") @ApiOperation(value = "根据 ID 批量修改 LoginInfo 记录") public BaseResult updateBatchById(Collection<LoginInfo> entityList) { return super.updateBatchById(entityList); } }
sacloud/libsacloud-v2
internal/schema/resource.go
<filename>internal/schema/resource.go package schema import ( "net/http" "strings" "github.com/sacloud/libsacloud-v2/internal/schema/meta" "github.com/sacloud/libsacloud-v2/sacloud/naked" ) // Resources []*Resourceのエイリアス type Resources []*Resource // ImportStatements コード生成時に利用するimport文を生成する func (r Resources) ImportStatements(additionalImports ...string) []string { ss := wrapByDoubleQuote(additionalImports...) for _, re := range r { ss = append(ss, re.ImportStatements()...) } return uniqStrings(ss) } // ImportStatementsForModelDef Resources配下に含まれる全てのモデルのフィールドを含めたimport文を生成する func (r Resources) ImportStatementsForModelDef(additionalImports ...string) []string { ss := wrapByDoubleQuote(additionalImports...) for _, m := range r.Models() { ss = append(ss, m.ImportStatementsForModelDef()...) } return uniqStrings(ss) } // Def リソースの定義 func (r *Resources) Def(rs *Resource) { if *r == nil { rr := Resources{} *r = rr } if rs.OperationsDefineFunc != nil { rs.AddOperations(rs.OperationsDefineFunc(rs)...) } *r = append(*r, rs) } // Define リソースの定義(for fluent API) func (r *Resources) Define(name string) *Resource { if *r == nil { rr := Resources{} *r = rr } rs := &Resource{ Name: name, } *r = append(*r, rs) return rs } // DefineWith リソースの定義 & 定義したリソースを利用するfuncの実施 func (r *Resources) DefineWith(name string, f func(*Resource)) *Resource { rs := r.Define(name) f(rs) return rs } // Models モデル一覧を取得 func (r Resources) Models() Models { ms := Models{} for _, res := range r { for _, o := range res.Operations() { ms = append(ms, o.Models()...) } } return ms.UniqByName() } // OperationsDefineFunc リソースに対するオペレーション定義用Func type OperationsDefineFunc func(r *Resource) []*Operation // Resource APIで操作する対象のリソース type Resource struct { Name string // リソース名 e.g.: Server PathName string // リソースのパス名 APIのURLで利用される e.g.: server 省略した場合はNameを小文字にしたものとなる PathSuffix string // APIのURLで利用されるプレフィックス e.g.: api/cloud/1.1 IsGlobal bool // 全ゾーンで共通リソース(グローバルリソース) operations []*Operation // このリソースに対する操作、OperationsDefineFuncが設定されている場合はそちらを呼び出して設定される OperationsDefineFunc OperationsDefineFunc // このリソースに対する操作を定義するFunc } // GetPathName リソースのパス名 APIのエンドポイントURLの算出で利用される 例: server // // 省略した場合はNameをスネークケース(小文字+アンダーバー)に変換したものが利用される func (r *Resource) GetPathName() string { if r.PathName != "" { return r.PathName } return toSnakeCaseName(r.Name) } // GetPathSuffix PathSuffixの取得 func (r *Resource) GetPathSuffix() string { if r.PathSuffix != "" { return r.PathSuffix } return CloudAPISuffix } // Operations リソースに対する操作の定義を取得 func (r *Resource) Operations() []*Operation { return r.operations } // AddOperation リソースに対する操作の定義を追加 func (r *Resource) AddOperation(op *Operation) { r.operations = append(r.operations, op) } // AddOperations リソースに対する操作の定義を追加 func (r *Resource) AddOperations(ops ...*Operation) { for _, op := range ops { r.AddOperation(op) } } // DefineOperation リソースに対する操作の定義 func (r *Resource) DefineOperation(name string) *Operation { return &Operation{ resource: r, name: name, } } func (r *Resource) defineOperationFind(nakedType meta.Type, findParam, result *Model, payloadName string) *Operation { if findParam.Name == "" { findParam.Name = "FindCondition" } if result.Name == "" { result.Name = r.Name } if result.NakedType == nil { result.NakedType = nakedType } return r.DefineOperation("Find"). Method(http.MethodGet). PathFormat(DefaultPathFormat). Argument(ArgumentZone). PassthroughModelArgumentWithEnvelope("conditions", findParam). ResultPluralFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: nakedType, PayloadName: payloadName, }) } // DefineOperationFind Find操作を定義 func (r *Resource) DefineOperationFind(nakedType meta.Type, findParam, result *Model) *Operation { return r.defineOperationFind(nakedType, findParam, result, "") } // DefineOperationApplianceFind Find操作を定義 func (r *Resource) DefineOperationApplianceFind(nakedType meta.Type, findParam, result *Model) *Operation { return r.defineOperationFind(nakedType, findParam, result, "Appliances") } // DefineOperationCommonServiceItemFind Find操作を定義 func (r *Resource) DefineOperationCommonServiceItemFind(nakedType meta.Type, findParam, result *Model) *Operation { return r.defineOperationFind(nakedType, findParam, result, "CommonServiceItems") } func (r *Resource) defineOperationCreate(nakedType meta.Type, createParam, result *Model, payloadName string) *Operation { if createParam.Name == "" { createParam.Name = r.Name + "CreateRequest" } if result.Name == "" { result.Name = r.Name } if createParam.NakedType == nil { createParam.NakedType = nakedType } if result.NakedType == nil { result.NakedType = nakedType } return r.DefineOperation("Create"). Method(http.MethodPost). PathFormat(DefaultPathFormat). RequestEnvelope(&EnvelopePayloadDesc{ PayloadType: nakedType, PayloadName: payloadName, }). Argument(ArgumentZone). MappableArgument("param", createParam). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: nakedType, PayloadName: payloadName, }) } // DefineOperationCreate Create操作を定義 func (r *Resource) DefineOperationCreate(nakedType meta.Type, createParam, result *Model) *Operation { return r.defineOperationCreate(nakedType, createParam, result, "") } // DefineOperationApplianceCreate Create操作を定義 func (r *Resource) DefineOperationApplianceCreate(nakedType meta.Type, createParam, result *Model) *Operation { return r.defineOperationCreate(nakedType, createParam, result, "Appliance") } // DefineOperationCommonServiceItemCreate Create操作を定義 func (r *Resource) DefineOperationCommonServiceItemCreate(nakedType meta.Type, createParam, result *Model) *Operation { return r.defineOperationCreate(nakedType, createParam, result, "CommonServiceItem") } func (r *Resource) defineOperationRead(nakedType meta.Type, result *Model, payloadName string) *Operation { if result.Name == "" { result.Name = r.Name } if result.NakedType == nil { result.NakedType = nakedType } return r.DefineOperation("Read"). Method(http.MethodGet). PathFormat(DefaultPathFormatWithID). Argument(ArgumentZone). Argument(ArgumentID). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: nakedType, PayloadName: payloadName, }) } // DefineOperationRead Read操作を定義 func (r *Resource) DefineOperationRead(nakedType meta.Type, result *Model) *Operation { return r.defineOperationRead(nakedType, result, "") } // DefineOperationApplianceRead Read操作を定義 func (r *Resource) DefineOperationApplianceRead(nakedType meta.Type, result *Model) *Operation { return r.defineOperationRead(nakedType, result, "Appliance") } // DefineOperationCommonServiceItemRead Read操作を定義 func (r *Resource) DefineOperationCommonServiceItemRead(nakedType meta.Type, result *Model) *Operation { return r.defineOperationRead(nakedType, result, "CommonServiceItem") } func (r *Resource) defineOperationUpdate(nakedType meta.Type, updateParam, result *Model, payloadName string) *Operation { if updateParam.Name == "" { updateParam.Name = r.Name + "UpdateRequest" } if result.Name == "" { result.Name = r.Name } if updateParam.NakedType == nil { updateParam.NakedType = nakedType } if result.NakedType == nil { result.NakedType = nakedType } return r.DefineOperation("Update"). Method(http.MethodPut). PathFormat(DefaultPathFormatWithID). RequestEnvelope(&EnvelopePayloadDesc{ PayloadType: nakedType, PayloadName: payloadName, }). Argument(ArgumentZone). Argument(ArgumentID). MappableArgument("param", updateParam). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: nakedType, PayloadName: payloadName, }) } // DefineOperationUpdate Update操作を定義 func (r *Resource) DefineOperationUpdate(nakedType meta.Type, updateParam, result *Model) *Operation { return r.defineOperationUpdate(nakedType, updateParam, result, "") } // DefineOperationApplianceUpdate Update操作を定義 func (r *Resource) DefineOperationApplianceUpdate(nakedType meta.Type, updateParam, result *Model) *Operation { return r.defineOperationUpdate(nakedType, updateParam, result, "Appliance") } // DefineOperationCommonServiceItemUpdate Update操作を定義 func (r *Resource) DefineOperationCommonServiceItemUpdate(nakedType meta.Type, updateParam, result *Model) *Operation { return r.defineOperationUpdate(nakedType, updateParam, result, "CommonServiceItem") } // DefineOperationDelete Delete操作を定義 func (r *Resource) DefineOperationDelete() *Operation { return r.DefineOperation("Delete"). Method(http.MethodDelete). PathFormat(DefaultPathFormatWithID). Argument(ArgumentZone). Argument(ArgumentID) } // DefineOperationCRUD リソースに対する基本的なCRUDを定義 func (r *Resource) DefineOperationCRUD(nakedType meta.Type, findParam, createParam, updateParam, result *Model) []*Operation { var ops []*Operation ops = append(ops, r.DefineOperationFind(nakedType, findParam, result)) ops = append(ops, r.DefineOperationCreate(nakedType, createParam, result)) ops = append(ops, r.DefineOperationRead(nakedType, result)) ops = append(ops, r.DefineOperationUpdate(nakedType, updateParam, result)) ops = append(ops, r.DefineOperationDelete()) return ops } // DefineOperationConfig Config操作を定義 func (r *Resource) DefineOperationConfig() *Operation { return r.DefineOperation("Config"). Method(http.MethodPut). PathFormat(IDAndSuffixPathFormat("config")). Argument(ArgumentZone). Argument(ArgumentID) } // DefineOperationBoot リソースに対するBoot操作を定義 func (r *Resource) DefineOperationBoot() *Operation { return r.DefineOperation("Boot"). Method(http.MethodPut). PathFormat(IDAndSuffixPathFormat("power")). Argument(ArgumentZone). Argument(ArgumentID) } // DefineOperationShutdown リソースに対するシャットダウン操作を定義 func (r *Resource) DefineOperationShutdown() *Operation { return r.DefineOperation("Shutdown"). Method(http.MethodDelete). PathFormat(IDAndSuffixPathFormat("power")). Argument(ArgumentZone). Argument(ArgumentID). PassthroughModelArgumentWithEnvelope("shutdownOption", &Model{ Name: "ShutdownOption", Fields: []*FieldDesc{ { Name: "Force", Type: meta.TypeFlag, }, }, }) } // DefineOperationReset リソースに対するリセット操作を定義 func (r *Resource) DefineOperationReset() *Operation { return r.DefineOperation("Reset"). Method(http.MethodPut). PathFormat(IDAndSuffixPathFormat("reset")). Argument(ArgumentZone). Argument(ArgumentID) } // DefineOperationPowerManagement リソースに対する電源管理操作を定義 func (r *Resource) DefineOperationPowerManagement() []*Operation { return []*Operation{ r.DefineOperationBoot(), r.DefineOperationShutdown(), r.DefineOperationReset(), } } // DefineOperationStatus ステータス取得操作を定義 func (r *Resource) DefineOperationStatus(nakedType meta.Type, result *Model) *Operation { return r.DefineOperation("Status"). Method(http.MethodGet). PathFormat(IDAndSuffixPathFormat("status")). Argument(ArgumentZone). Argument(ArgumentID). ResultPluralFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: meta.Static(naked.LoadBalancerStatus{}), PayloadName: r.FieldName(PayloadForms.Singular), }) } // DefineOperationOpenFTP FTPオープン操作を定義 func (r *Resource) DefineOperationOpenFTP(openParam, result *Model) *Operation { o := r.DefineOperation("OpenFTP"). Method(http.MethodPut). PathFormat(IDAndSuffixPathFormat("ftp")). Argument(ArgumentZone). Argument(ArgumentID). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadName: result.Name, PayloadType: meta.Static(naked.OpeningFTPServer{}), }) if openParam != nil { o.PassthroughModelArgumentWithEnvelope("openOption", openParam) } return o } // DefineOperationCloseFTP FTPクローズ操作を定義 func (r *Resource) DefineOperationCloseFTP() *Operation { return r.DefineOperation("CloseFTP"). Method(http.MethodDelete). PathFormat(IDAndSuffixPathFormat("ftp")). Argument(ArgumentZone). Argument(ArgumentID) } // DefineSimpleOperation ID+αのみを引数にとるシンプルなオペレーションを定義 func (r *Resource) DefineSimpleOperation(opName, method, pathSuffix string, arguments ...*Argument) *Operation { o := r.DefineOperation(opName). Method(method). PathFormat(IDAndSuffixPathFormat(pathSuffix)). Argument(ArgumentZone). Argument(ArgumentID) if len(arguments) > 0 { o.Arguments(arguments) } return o } // DefineOperationMonitor アクティビティモニタ取得操作を定義 func (r *Resource) DefineOperationMonitor(monitorParam, result *Model) *Operation { return r.DefineOperation("Monitor"). Method(http.MethodGet). PathFormat(IDAndSuffixPathFormat("monitor")). Argument(ArgumentZone). Argument(ArgumentID). PassthroughModelArgumentWithEnvelope("condition", monitorParam). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: meta.Static(naked.MonitorValues{}), PayloadName: "Data", }) } // DefineOperationMonitorChild アクティビティモニタ取得操作を定義 func (r *Resource) DefineOperationMonitorChild(funcNameSuffix, childResourceName string, monitorParam, result *Model) *Operation { return r.DefineOperation("Monitor"+funcNameSuffix). Method(http.MethodGet). PathFormat(IDAndSuffixPathFormat(childResourceName+"/monitor")). Argument(ArgumentZone). Argument(ArgumentID). PassthroughModelArgumentWithEnvelope("condition", monitorParam). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: meta.Static(naked.MonitorValues{}), PayloadName: "Data", }) } // DefineOperationMonitorChildBy アプライアンスなどでの内部リソースインデックスを持つアクティビティモニタ取得操作を定義 func (r *Resource) DefineOperationMonitorChildBy(funcNameSuffix, childResourceName string, monitorParam, result *Model) *Operation { pathSuffix := childResourceName + "/{{if eq .index 0}}{{.index}}{{end}}/monitor" return r.DefineOperation("Monitor"+funcNameSuffix). Method(http.MethodGet). PathFormat(IDAndSuffixPathFormat(pathSuffix)). Argument(ArgumentZone). Argument(ArgumentID). Argument(&Argument{ Name: "index", Type: meta.TypeInt, }). PassthroughModelArgumentWithEnvelope("condition", monitorParam). ResultFromEnvelope(result, &EnvelopePayloadDesc{ PayloadType: meta.Static(naked.MonitorValues{}), PayloadName: "Data", }) } // FileSafeName スネークケースにしたResourceの名前、コード生成時の保存先ファイル名に利用される func (r *Resource) FileSafeName() string { return toSnakeCaseName(r.Name) } // TypeName 型名を返す、コード生成時の型定義などで利用される func (r *Resource) TypeName() string { return r.Name } // ImportStatements コード生成時に利用するimport文を生成する func (r *Resource) ImportStatements(additionalImports ...string) []string { ss := wrapByDoubleQuote(additionalImports...) for _, o := range r.Operations() { ss = append(ss, o.ImportStatements()...) } return uniqStrings(ss) } // FieldName ペイロードなどで利用される場合のフィールド名を返す func (r *Resource) FieldName(form PayloadForm) string { switch { case form.IsSingular(): return r.Name case form.IsPlural(): // TODO とりあえずワードで例外指定 switch { case r.Name == "NFS": return r.Name case strings.HasSuffix(r.Name, "ch"): return r.Name + "es" default: return r.Name + "s" } default: return "" } }
tony2u/Medusa
Medusa/MedusaExtension/CocosStudio/Reader/SpriteReader.cpp
<gh_stars>100-1000 #include "MedusaExtensionPreCompiled.h" #include "SpriteReader.h" #include "Core/String/StringRef.h" #include "Core/IO/FileId.h" #include "Node/Sprite/Sprite.h" #include "Node/NodeFactory.h" #include "ReaderFactory.h" #include "CocosStudio/CSParseBinary_generated.h" #include "Rendering/RenderingObjectFactory.h" #include "Rendering/RenderingObject.h" #include "Resource/Model/Mesh/IMesh.h" #include "Core/IO/Path.h" MEDUSA_COCOS_BEGIN; INode* SpriteReader::CreateNodeWithFlatBuffers(INodeEditor& editor, const flatbuffers::Table* spriteOptions, const StringRef& className /*= StringRef::Empty*/, NodeCreateFlags flags /*= NodeCreateFlags::None*/) { auto options = (flatbuffers::SpriteOptions*)spriteOptions; auto sprite = CreateSprite(options->fileNameData()->path()->c_str()); SetPropsWithFlatBuffers(sprite, (flatbuffers::Table*) options->nodeOptions()); return sprite; } INode* SpriteReader::CreateNodeWithJson(INodeEditor& editor, const rapidjson::Value& nodeTree, const StringRef& className /*= StringRef::Empty*/, NodeCreateFlags flags /*= NodeCreateFlags::None*/) { const rapidjson::Value& fileDataNode = nodeTree["FileData"]; StringRef path = fileDataNode.GetMember("Path", nullptr); Sprite* sprite = CreateSprite(path); SetPropsWithJson(sprite, nodeTree); return sprite; } Sprite* SpriteReader::CreateSprite(StringRef fullName) { Sprite* sprite = new Sprite(); if (!fullName.IsEmpty()) { auto fileId = FileId::ParseFrom(fullName); auto renderingObject = RenderingObjectFactory::Instance().CreateFromTexture(fileId); Log::Assert(renderingObject != nullptr, " sprite file path error"); sprite->SetRenderingObject(renderingObject); sprite->SetSize(renderingObject.Mesh()->Size()); sprite->Initialize(); } return sprite; } MEDUSA_COCOS_END;
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/sling/1019.java
/******************************************************************************* * 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.sling.scripting.sightly.impl.plugin; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import org.apache.sling.scripting.sightly.impl.compiler.expression.Expression; import org.apache.sling.scripting.sightly.impl.compiler.ris.command.Conditional; import org.apache.sling.scripting.sightly.impl.compiler.ris.command.VariableBinding; import org.apache.sling.scripting.sightly.impl.compiler.common.DefaultPluginInvoke; import org.apache.sling.scripting.sightly.impl.compiler.frontend.CompilerContext; import org.apache.sling.scripting.sightly.impl.compiler.util.stream.PushStream; /** * Implementation for the test plugin */ @Component @Service(Plugin.class) @Properties({ @Property(name = Plugin.SCR_PROP_NAME_BLOCK_NAME, value = "test"), @Property(name = Plugin.SCR_PROP_NAME_PRIORITY, intValue = 1) }) public class TestPlugin extends PluginComponent { @Override public PluginInvoke invoke(final Expression expressionNode, final PluginCallInfo callInfo, final CompilerContext compilerContext) { return new DefaultPluginInvoke() { private boolean globalBinding; @Override public void beforeElement(PushStream stream, String tagName) { String variableName = decodeVariableName(); globalBinding = variableName != null; if (variableName == null) { variableName = compilerContext.generateVariable("testVariable"); } if (globalBinding) { stream.emit(new VariableBinding.Global(variableName, expressionNode.getRoot())); } else { stream.emit(new VariableBinding.Start(variableName, expressionNode.getRoot())); } stream.emit(new Conditional.Start(variableName, true)); } @Override public void afterElement(PushStream stream) { stream.emit(Conditional.END); if (!globalBinding) { stream.emit(VariableBinding.END); } } private String decodeVariableName() { String[] args = callInfo.getArguments(); if (args.length > 0) { return args[0]; } return null; } }; } }
sujoypodder/HMS
HMS/src/hms/Update.java
<filename>HMS/src/hms/Update.java package hms; import java.sql.Connection; import java.sql.*; import javax.swing.JOptionPane; public class Update extends javax.swing.JFrame { /** * Creates new form Update */ public Update() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(430, 330)); setMinimumSize(new java.awt.Dimension(430, 330)); setPreferredSize(new java.awt.Dimension(430, 330)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N jLabel1.setForeground(new java.awt.Color(153, 0, 0)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Update Your Info"); getContentPane().add(jLabel1); jLabel1.setBounds(89, 11, 224, 19); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(0, 0, 153)); jLabel2.setText("Address"); getContentPane().add(jLabel2); jLabel2.setBounds(40, 50, 60, 17); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(0, 0, 153)); jLabel3.setText("Contact No"); getContentPane().add(jLabel3); jLabel3.setBounds(17, 94, 80, 21); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(0, 0, 153)); jLabel4.setText("Password"); getContentPane().add(jLabel4); jLabel4.setBounds(20, 150, 70, 17); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(0, 0, 153)); jLabel5.setText("Security Key"); getContentPane().add(jLabel5); jLabel5.setBounds(10, 200, 90, 20); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField1.setForeground(new java.awt.Color(153, 0, 0)); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); getContentPane().add(jTextField1); jTextField1.setBounds(110, 50, 190, 30); jTextField2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField2.setForeground(new java.awt.Color(153, 0, 0)); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); getContentPane().add(jTextField2); jTextField2.setBounds(110, 90, 190, 30); jTextField3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField3.setForeground(new java.awt.Color(153, 0, 0)); jTextField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField3ActionPerformed(evt); } }); getContentPane().add(jTextField3); jTextField3.setBounds(110, 140, 190, 30); jTextField4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jTextField4.setForeground(new java.awt.Color(153, 0, 0)); jTextField4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField4ActionPerformed(evt); } }); getContentPane().add(jTextField4); jTextField4.setBounds(110, 190, 190, 30); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setForeground(new java.awt.Color(0, 0, 153)); jButton1.setText("Update"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(310, 50, 90, 25); jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton2.setForeground(new java.awt.Color(0, 0, 153)); jButton2.setText("Update"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(310, 90, 90, 25); jButton3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton3.setForeground(new java.awt.Color(0, 0, 153)); jButton3.setText("Update"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(310, 140, 90, 25); jButton4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton4.setForeground(new java.awt.Color(0, 0, 153)); jButton4.setText("Update"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); getContentPane().add(jButton4); jButton4.setBounds(310, 190, 90, 25); jButton5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton5.setForeground(new java.awt.Color(0, 0, 153)); jButton5.setText("OK"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); getContentPane().add(jButton5); jButton5.setBounds(152, 240, 60, 25); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField4ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed address=jTextField1.getText(); password=jTextField3.getText(); ResultSet rs=null; PreparedStatement ps=null; String update=new String(); try{ update="update data set password='"+password+"' where address='"+address+"'"; ps=conn.prepareStatement(update); ps.executeUpdate(); JOptionPane.showMessageDialog(null,"Password Update Successfully"); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Login failed! Please try again!","Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton3ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed this.setVisible(false); Login lg=new Login(); lg.setVisible(true); }//GEN-LAST:event_jButton5ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed address=jTextField1.getText(); securitykey=jTextField4.getText(); ResultSet rs=null; PreparedStatement ps=null; String update=new String(); try{ update="update data set securitykey='"+securitykey+"' where address='"+address+"'"; ps=conn.prepareStatement(update); ps.executeUpdate(); JOptionPane.showMessageDialog(null,"SecurityWord Update Successfully"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Login failed! Please try again!","Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton4ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed address = jTextField1.getText(); password=jTextField3.getText(); ResultSet rs=null; PreparedStatement ps=null; String update=new String(); try{ update="update data set address='"+address+"' where password='"+password+"'"; ps=conn.prepareStatement(update); ps.executeUpdate(); JOptionPane.showMessageDialog(null,"Address Update Successfully"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Login failed! Please try again!","Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton1ActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened conn = Sqlite.ConnectDB(); }//GEN-LAST:event_formWindowOpened private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed address=jTextField1.getText(); contactno=jTextField2.getText(); ResultSet rs=null; PreparedStatement ps=null; String update=new String(); try{ update="update data set contactno='"+contactno+"' where address='"+address+"'"; ps=conn.prepareStatement(update); ps.executeUpdate(); JOptionPane.showMessageDialog(null,"Contact Update Successfully"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Login failed! Please try again!","Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton2ActionPerformed private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField3ActionPerformed public Connection conn=null; public String address=new String(); public String password=new String(); public String contactno=new String(); public String securitykey=new String(); /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Update.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Update.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Update.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Update.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Update().setVisible(true); } }); } public javax.swing.JLabel jLabel1; public javax.swing.JLabel jLabel2; public javax.swing.JLabel jLabel3; public javax.swing.JLabel jLabel4; public javax.swing.JLabel jLabel5; public javax.swing.JLabel jLabel6; public javax.swing.JButton jButton1; public javax.swing.JButton jButton2; public javax.swing.JButton jButton3; public javax.swing.JButton jButton4; public javax.swing.JButton jButton5; public javax.swing.JTextField jTextField1; public javax.swing.JTextField jTextField2; public javax.swing.JTextField jTextField3; public javax.swing.JTextField jTextField4; public javax.swing.JTextField jTextField5; /* // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables */}
daodao10/chart
cn/SZ399974_d.js
<reponame>daodao10/chart var data=[['20141229',1419.190], ['20141230',1398.740], ['20141231',1418.310], ['20150105',1449.150], ['20150106',1464.710], ['20150107',1460.470], ['20150108',1441.030], ['20150109',1426.050], ['20150112',1406.770], ['20150113',1415.970], ['20150114',1407.210], ['20150115',1429.810], ['20150116',1444.030], ['20150119',1358.620], ['20150120',1389.170], ['20150121',1432.350], ['20150122',1453.230], ['20150123',1448.060], ['20150126',1493.100], ['20150127',1491.830], ['20150128',1473.160], ['20150129',1457.030], ['20150130',1438.430], ['20150202',1416.670], ['20150203',1440.730], ['20150204',1428.620], ['20150205',1411.830], ['20150206',1393.860], ['20150209',1400.700], ['20150210',1417.920], ['20150211',1433.070], ['20150212',1440.340], ['20150213',1450.820], ['20150216',1474.930], ['20150217',1491.310], ['20150225',1486.680], ['20150226',1517.360], ['20150227',1530.840], ['20150302',1549.840], ['20150303',1528.740], ['20150304',1549.720], ['20150305',1539.770], ['20150306',1528.440], ['20150309',1546.050], ['20150310',1554.980], ['20150311',1550.160], ['20150312',1564.750], ['20150313',1575.290], ['20150316',1616.180], ['20150317',1648.650], ['20150318',1673.400], ['20150319',1676.190], ['20150320',1689.820], ['20150323',1719.270], ['20150324',1724.410], ['20150325',1724.010], ['20150326',1727.450], ['20150327',1737.760], ['20150330',1770.260], ['20150331',1755.030], ['20150401',1791.090], ['20150402',1806.960], ['20150403',1831.910], ['20150407',1857.080], ['20150408',1844.200], ['20150409',1831.980], ['20150410',1872.580], ['20150413',1900.790], ['20150414',1912.020], ['20150415',1853.380], ['20150416',1898.480], ['20150417',1943.630], ['20150420',1942.850], ['20150421',1997.390], ['20150422',2053.780], ['20150423',2075.560], ['20150424',2098.110], ['20150427',2139.460], ['20150428',2089.480], ['20150429',2126.540], ['20150430',2121.430], ['20150504',2150.500], ['20150505',2052.090], ['20150506',2016.140], ['20150507',1961.890], ['20150508',2012.320], ['20150511',2079.460], ['20150512',2134.490], ['20150513',2128.000], ['20150514',2118.630], ['20150515',2086.960], ['20150518',2088.660], ['20150519',2141.830], ['20150520',2166.830], ['20150521',2227.500], ['20150522',2275.470], ['20150525',2362.700], ['20150526',2427.860], ['20150527',2441.860], ['20150528',2275.760], ['20150529',2297.660], ['20150601',2416.770], ['20150602',2502.220], ['20150603',2493.620], ['20150604',2468.990], ['20150605',2512.220], ['20150608',2545.690], ['20150609',2563.890], ['20150610',2592.390], ['20150611',2601.950], ['20150612',2637.580], ['20150615',2598.650], ['20150616',2506.240], ['20150617',2550.900], ['20150618',2471.240], ['20150619',2307.170], ['20150623',2345.300], ['20150624',2415.790], ['20150625',2316.410], ['20150626',2120.300], ['20150629',2002.370], ['20150630',2111.970], ['20150701',1992.820], ['20150702',1862.280], ['20150703',1731.760], ['20150706',1719.740], ['20150707',1618.160], ['20150708',1510.960], ['20150709',1616.450], ['20150710',1731.100], ['20150713',1841.980], ['20150714',1834.810], ['20150715',1718.430], ['20150716',1755.760], ['20150717',1851.170], ['20150720',1881.060], ['20150721',1894.180], ['20150722',1920.810], ['20150723',1985.520], ['20150724',1961.220], ['20150727',1809.290], ['20150728',1797.320], ['20150729',1880.400], ['20150730',1834.250], ['20150731',1801.510], ['20150803',1761.190], ['20150804',1848.920], ['20150805',1830.820], ['20150806',1811.280], ['20150807',1863.770], ['20150810',1971.970], ['20150811',1980.500], ['20150812',1973.630], ['20150813',2027.990], ['20150814',2049.460], ['20150817',2084.840], ['20150818',1927.220], ['20150819',1958.040], ['20150820',1870.940], ['20150821',1774.700], ['20150824',1629.800], ['20150825',1504.590], ['20150826',1456.880], ['20150827',1533.500], ['20150828',1630.100], ['20150831',1613.130], ['20150901',1550.220], ['20150902',1531.350], ['20150907',1507.060], ['20150908',1559.840], ['20150909',1603.930], ['20150910',1580.830], ['20150911',1591.940], ['20150914',1518.460], ['20150915',1435.390], ['20150916',1527.030], ['20150917',1491.450], ['20150918',1499.370], ['20150921',1545.700], ['20150922',1552.970], ['20150923',1526.920], ['20150924',1542.170], ['20150925',1501.170], ['20150928',1512.010], ['20150929',1475.190], ['20150930',1479.840], ['20151008',1536.230], ['20151009',1556.130], ['20151012',1617.350], ['20151013',1628.750], ['20151014',1600.240], ['20151015',1651.830], ['20151016',1692.460], ['20151019',1693.580], ['20151020',1717.350], ['20151021',1621.970], ['20151022',1665.970], ['20151023',1691.970], ['20151026',1698.190], ['20151027',1704.000], ['20151028',1660.670], ['20151029',1673.120], ['20151030',1668.400], ['20151102',1627.550], ['20151103',1616.410], ['20151104',1693.330], ['20151105',1719.320], ['20151106',1751.420], ['20151109',1768.670], ['20151110',1761.210], ['20151111',1770.580], ['20151112',1753.840], ['20151113',1725.700], ['20151116',1741.350], ['20151117',1733.800], ['20151118',1705.630], ['20151119',1736.740], ['20151120',1746.670], ['20151123',1730.980], ['20151124',1729.720], ['20151125',1748.750], ['20151126',1739.020], ['20151127',1623.930], ['20151130',1617.720], ['20151201',1627.650], ['20151202',1655.750], ['20151203',1672.980], ['20151204',1645.250], ['20151207',1660.290], ['20151208',1620.620], ['20151209',1623.190], ['20151210',1616.170], ['20151211',1614.790], ['20151214',1664.010], ['20151215',1657.530], ['20151216',1654.210], ['20151217',1685.920], ['20151218',1683.340], ['20151221',1714.830], ['20151222',1723.460], ['20151223',1709.880], ['20151224',1693.130], ['20151225',1698.410], ['20151228',1655.680], ['20151229',1670.650], ['20151230',1679.950], ['20151231',1667.550], ['20160104',1531.940], ['20160105',1531.660], ['20160106',1566.050], ['20160107',1430.880], ['20160108',1454.260], ['20160111',1355.810], ['20160112',1362.910], ['20160113',1315.390], ['20160114',1351.480], ['20160115',1295.720], ['20160118',1312.230], ['20160119',1366.860], ['20160120',1347.200], ['20160121',1293.960], ['20160122',1313.170], ['20160125',1325.610], ['20160126',1229.890], ['20160127',1217.650], ['20160128',1162.720], ['20160129',1207.740], ['20160201',1185.440], ['20160202',1221.780], ['20160203',1223.270], ['20160204',1243.440], ['20160205',1231.050], ['20160215',1227.240], ['20160216',1273.610], ['20160217',1292.480], ['20160218',1283.940], ['20160219',1286.640], ['20160222',1314.750], ['20160223',1303.930], ['20160224',1329.130], ['20160225',1226.550], ['20160226',1234.890], ['20160229',1179.210], ['20160301',1202.490], ['20160302',1263.790], ['20160303',1271.930], ['20160304',1264.930], ['20160307',1285.300], ['20160308',1281.920], ['20160309',1251.570], ['20160310',1228.420], ['20160311',1227.960], ['20160314',1260.790], ['20160315',1258.010], ['20160316',1252.030], ['20160317',1279.250], ['20160318',1309.650], ['20160321',1341.550], ['20160322',1338.840], ['20160323',1343.020], ['20160324',1321.320], ['20160325',1331.920], ['20160328',1322.870], ['20160329',1295.340], ['20160330',1332.770], ['20160331',1336.550], ['20160401',1338.610], ['20160405',1361.250], ['20160406',1361.440], ['20160407',1340.050], ['20160408',1328.070], ['20160411',1350.530], ['20160412',1344.350], ['20160413',1363.130], ['20160414',1370.490], ['20160415',1365.480], ['20160418',1341.090], ['20160419',1343.120], ['20160420',1298.340], ['20160421',1287.490], ['20160422',1290.240], ['20160425',1282.980], ['20160426',1291.300], ['20160427',1283.930], ['20160428',1276.890], ['20160429',1276.590], ['20160503',1310.090], ['20160504',1310.410], ['20160505',1312.290], ['20160506',1271.580], ['20160509',1235.200], ['20160510',1238.280], ['20160511',1242.750], ['20160512',1239.010], ['20160513',1232.800], ['20160516',1244.360], ['20160517',1240.360], ['20160518',1220.600], ['20160519',1219.940], ['20160520',1229.890], ['20160523',1239.560], ['20160524',1224.400], ['20160525',1219.240], ['20160526',1219.250], ['20160527',1220.680], ['20160530',1216.830], ['20160531',1262.280], ['20160601',1263.400], ['20160602',1265.560], ['20160603',1273.960], ['20160606',1272.980], ['20160607',1271.870], ['20160608',1268.600], ['20160613',1231.090], ['20160614',1234.710], ['20160615',1257.530], ['20160616',1245.710], ['20160617',1252.350], ['20160620',1249.720], ['20160621',1242.780], ['20160622',1256.110], ['20160623',1250.770], ['20160624',1234.280], ['20160627',1259.820], ['20160628',1268.020], ['20160629',1276.090], ['20160630',1273.000], ['20160701',1273.290], ['20160704',1306.260], ['20160705',1319.340], ['20160706',1335.200], ['20160707',1336.360], ['20160708',1330.840], ['20160711',1339.990], ['20160712',1366.170], ['20160713',1369.550], ['20160714',1363.000], ['20160715',1362.950], ['20160718',1359.490], ['20160719',1355.340], ['20160720',1348.530], ['20160721',1354.080], ['20160722',1339.850], ['20160725',1339.470], ['20160726',1362.560], ['20160727',1337.640], ['20160728',1346.440], ['20160729',1332.710], ['20160801',1314.480], ['20160802',1326.370], ['20160803',1333.730], ['20160804',1335.410], ['20160805',1329.370], ['20160808',1348.830], ['20160809',1357.610], ['20160810',1352.500], ['20160811',1337.560], ['20160812',1355.500], ['20160815',1390.790], ['20160816',1392.430], ['20160817',1393.700], ['20160818',1392.320], ['20160819',1392.130], ['20160822',1374.820], ['20160823',1373.900], ['20160824',1369.540], ['20160825',1354.650], ['20160826',1354.640], ['20160829',1357.770], ['20160830',1357.680], ['20160831',1360.810], ['20160901',1348.550], ['20160902',1351.000], ['20160905',1353.610], ['20160906',1365.150], ['20160907',1367.410], ['20160908',1369.960], ['20160909',1362.180], ['20160912',1333.330], ['20160913',1334.420], ['20160914',1323.060], ['20160919',1333.810], ['20160920',1331.870], ['20160921',1334.150], ['20160922',1342.640], ['20160923',1339.980], ['20160926',1309.300], ['20160927',1318.130], ['20160928',1314.980], ['20160929',1317.900], ['20160930',1326.850], ['20161010',1347.050], ['20161011',1359.230], ['20161012',1356.420], ['20161013',1359.430], ['20161014',1367.170], ['20161017',1357.050], ['20161018',1381.850], ['20161019',1383.940], ['20161020',1384.180], ['20161021',1389.950], ['20161024',1406.470], ['20161025',1410.780], ['20161026',1402.940], ['20161027',1397.840], ['20161028',1388.450], ['20161031',1383.760], ['20161101',1394.190], ['20161102',1376.060], ['20161103',1396.580], ['20161104',1392.410], ['20161107',1393.980], ['20161108',1399.940], ['20161109',1388.330], ['20161110',1408.380], ['20161111',1423.270], ['20161114',1434.030], ['20161115',1431.150], ['20161116',1432.040], ['20161117',1441.140], ['20161118',1432.210], ['20161121',1439.590], ['20161122',1450.360], ['20161123',1445.900], ['20161124',1449.600], ['20161125',1460.650], ['20161128',1475.900], ['20161129',1489.380], ['20161130',1472.890], ['20161201',1485.310], ['20161202',1463.850], ['20161205',1436.510], ['20161206',1432.530], ['20161207',1443.260], ['20161208',1440.380], ['20161209',1448.820], ['20161212',1407.240], ['20161213',1414.220], ['20161214',1395.730], ['20161215',1393.210], ['20161216',1395.580], ['20161219',1397.390], ['20161220',1391.570], ['20161221',1412.810], ['20161222',1419.620], ['20161223',1409.480], ['20161226',1418.610], ['20161227',1414.670], ['20161228',1405.620], ['20161229',1406.280], ['20161230',1405.280], ['20170103',1418.150], ['20170104',1434.060], ['20170105',1438.590], ['20170106',1437.290], ['20170109',1451.330], ['20170110',1440.400], ['20170111',1428.160], ['20170112',1415.130], ['20170113',1410.840], ['20170116',1408.610], ['20170117',1410.950], ['20170118',1418.300], ['20170119',1409.380], ['20170120',1420.070], ['20170123',1428.520], ['20170124',1428.850], ['20170125',1436.400], ['20170126',1439.520], ['20170203',1433.370], ['20170206',1440.320], ['20170207',1436.940], ['20170208',1446.990], ['20170209',1457.880], ['20170210',1469.750], ['20170213',1479.000], ['20170214',1489.190], ['20170215',1480.120], ['20170216',1488.410], ['20170217',1473.920], ['20170220',1501.410], ['20170221',1505.130], ['20170222',1512.210], ['20170223',1500.760], ['20170224',1503.230], ['20170227',1487.960], ['20170228',1495.460], ['20170301',1501.940], ['20170302',1488.100], ['20170303',1485.390], ['20170306',1491.720], ['20170307',1491.180], ['20170308',1495.070], ['20170309',1480.120], ['20170310',1475.430], ['20170313',1484.450], ['20170314',1482.000], ['20170315',1484.060], ['20170316',1492.730], ['20170317',1477.920], ['20170320',1488.020], ['20170321',1502.800], ['20170322',1502.360], ['20170323',1503.910], ['20170324',1519.080], ['20170327',1510.000], ['20170328',1505.210], ['20170329',1506.990], ['20170330',1491.080], ['20170331',1496.000], ['20170405',1528.620], ['20170406',1544.950], ['20170407',1548.970], ['20170410',1548.130], ['20170411',1564.450], ['20170412',1559.240], ['20170413',1565.520], ['20170414',1552.350], ['20170417',1553.800], ['20170418',1551.120], ['20170419',1537.080], ['20170420',1548.730], ['20170421',1540.500], ['20170424',1508.430], ['20170425',1513.120], ['20170426',1511.970], ['20170427',1515.460], ['20170428',1515.350], ['20170502',1513.540], ['20170503',1506.680], ['20170504',1508.070], ['20170505',1494.690], ['20170508',1476.130], ['20170509',1470.730], ['20170510',1449.710], ['20170511',1459.250], ['20170512',1461.240], ['20170515',1466.620], ['20170516',1486.500], ['20170517',1480.780], ['20170518',1471.030], ['20170519',1475.090], ['20170522',1467.870], ['20170523',1463.570], ['20170524',1463.900], ['20170525',1476.150], ['20170526',1478.310], ['20170531',1481.940], ['20170601',1480.300], ['20170602',1481.010], ['20170605',1474.050], ['20170606',1483.220], ['20170607',1505.290], ['20170608',1512.440], ['20170609',1520.600], ['20170612',1519.690], ['20170613',1528.220], ['20170614',1511.350], ['20170615',1507.000], ['20170616',1497.000], ['20170619',1512.710], ['20170620',1507.840], ['20170621',1523.990], ['20170622',1517.950], ['20170623',1521.410], ['20170626',1542.110], ['20170627',1545.120], ['20170628',1531.270], ['20170629',1539.610], ['20170630',1542.890], ['20170703',1538.340], ['20170704',1528.330], ['20170705',1539.500], ['20170706',1540.100], ['20170707',1538.080], ['20170710',1534.280], ['20170711',1528.710], ['20170712',1521.260], ['20170713',1530.530], ['20170714',1537.200], ['20170717',1509.670], ['20170718',1523.910], ['20170719',1547.100], ['20170720',1555.200], ['20170721',1554.980], ['20170724',1560.430], ['20170725',1549.390], ['20170726',1540.350], ['20170727',1535.700], ['20170728',1541.630], ['20170731',1552.990], ['20170801',1557.710], ['20170802',1544.950], ['20170803',1535.620], ['20170804',1537.020], ['20170807',1551.030], ['20170808',1551.140], ['20170809',1559.450], ['20170810',1557.350], ['20170811',1534.590], ['20170814',1550.770], ['20170815',1546.420], ['20170816',1543.110], ['20170817',1560.030], ['20170818',1557.250], ['20170821',1569.670], ['20170822',1568.610], ['20170823',1558.350], ['20170824',1543.810], ['20170825',1564.630], ['20170828',1579.120], ['20170829',1571.940], ['20170830',1581.460], ['20170831',1572.920], ['20170901',1576.810], ['20170904',1581.590], ['20170905',1573.980], ['20170906',1578.590], ['20170907',1565.580], ['20170908',1562.970], ['20170911',1566.580], ['20170912',1570.400], ['20170913',1573.470], ['20170914',1567.690], ['20170915',1561.290], ['20170918',1567.350], ['20170919',1559.430], ['20170920',1561.020], ['20170921',1556.840], ['20170922',1556.360], ['20170925',1558.450], ['20170926',1563.750], ['20170927',1562.580], ['20170928',1561.060], ['20170929',1562.500], ['20171009',1572.270], ['20171010',1571.370], ['20171011',1581.190], ['20171012',1583.870], ['20171013',1584.110], ['20171016',1582.020], ['20171017',1578.410], ['20171018',1592.290], ['20171019',1589.650], ['20171020',1595.650], ['20171023',1599.890], ['20171024',1609.150], ['20171025',1612.010], ['20171026',1624.220], ['20171027',1631.890], ['20171030',1630.820], ['20171031',1631.650], ['20171101',1632.850], ['20171102',1628.350], ['20171103',1620.360], ['20171106',1629.040], ['20171107',1638.190], ['20171108',1634.750], ['20171109',1644.540], ['20171110',1657.030], ['20171113',1662.050], ['20171114',1655.770], ['20171115',1651.690], ['20171116',1660.440], ['20171117',1661.010], ['20171120',1662.460], ['20171121',1672.310], ['20171122',1676.220], ['20171123',1630.890], ['20171124',1629.020], ['20171127',1609.290], ['20171128',1620.470], ['20171129',1618.470], ['20171130',1606.850], ['20171201',1603.730], ['20171204',1612.220], ['20171205',1620.940], ['20171206',1610.360], ['20171207',1594.740], ['20171208',1601.720], ['20171211',1623.330], ['20171212',1599.180], ['20171213',1614.090], ['20171214',1608.050], ['20171215',1592.800], ['20171218',1594.570], ['20171219',1614.430], ['20171220',1613.210], ['20171221',1628.610], ['20171222',1625.820], ['20171225',1618.670], ['20171226',1628.180], ['20171227',1608.020], ['20171228',1616.720], ['20171229',1622.690], ['20180102',1643.920], ['20180103',1653.180], ['20180104',1660.670], ['20180105',1663.440], ['20180108',1677.880], ['20180109',1680.320], ['20180110',1675.630], ['20180111',1664.510], ['20180112',1665.040], ['20180115',1664.730], ['20180116',1682.440], ['20180117',1678.390], ['20180118',1688.970], ['20180119',1690.500], ['20180122',1703.740], ['20180123',1716.200], ['20180124',1717.160], ['20180125',1718.110], ['20180126',1726.730], ['20180129',1702.480], ['20180130',1685.290], ['20180131',1683.780], ['20180201',1671.630], ['20180202',1693.830], ['20180205',1703.100], ['20180206',1651.700], ['20180207',1621.270], ['20180208',1594.370], ['20180209',1516.710], ['20180212',1530.190], ['20180213',1548.910], ['20180214',1556.940], ['20180222',1594.490], ['20180223',1606.490], ['20180226',1624.430], ['20180227',1599.360], ['20180228',1579.620], ['20180301',1580.470], ['20180302',1572.920], ['20180305',1571.190], ['20180306',1596.820], ['20180307',1582.920], ['20180308',1596.900], ['20180309',1603.990], ['20180312',1610.080], ['20180313',1597.920], ['20180314',1595.630], ['20180315',1601.080], ['20180316',1586.780], ['20180319',1580.570], ['20180320',1583.790], ['20180321',1578.260], ['20180322',1563.650], ['20180323',1527.900], ['20180326',1511.110], ['20180327',1520.910], ['20180328',1497.610], ['20180329',1524.620], ['20180330',1523.250], ['20180402',1523.200], ['20180403',1511.910], ['20180404',1506.160], ['20180409',1508.830], ['20180410',1537.570], ['20180411',1542.040], ['20180412',1526.120], ['20180413',1520.460], ['20180416',1491.600], ['20180417',1469.570], ['20180418',1477.790], ['20180419',1495.670], ['20180420',1480.430], ['20180423',1477.000], ['20180424',1508.480], ['20180425',1500.680], ['20180426',1483.850], ['20180427',1488.870], ['20180502',1492.780], ['20180503',1503.490], ['20180504',1500.830], ['20180507',1526.480], ['20180508',1542.110], ['20180509',1541.140], ['20180510',1546.420], ['20180511',1536.770], ['20180514',1546.000], ['20180515',1548.880], ['20180516',1536.070], ['20180517',1525.510], ['20180518',1543.080], ['20180521',1549.460], ['20180522',1543.450], ['20180523',1521.760], ['20180524',1511.480], ['20180525',1508.520], ['20180528',1510.310], ['20180529',1502.460], ['20180530',1466.520], ['20180531',1496.100], ['20180601',1487.410], ['20180604',1510.450], ['20180605',1524.450], ['20180606',1525.320], ['20180607',1528.810], ['20180608',1505.850], ['20180611',1503.120], ['20180612',1526.840], ['20180613',1514.480], ['20180614',1500.030], ['20180615',1488.780], ['20180619',1438.530], ['20180620',1439.960], ['20180621',1428.290], ['20180622',1433.940], ['20180625',1409.110], ['20180626',1392.080], ['20180627',1366.500], ['20180628',1347.390], ['20180629',1387.110], ['20180702',1353.620], ['20180703',1357.710], ['20180704',1344.700], ['20180705',1333.250], ['20180706',1334.320], ['20180709',1377.750], ['20180710',1391.120], ['20180711',1366.760], ['20180712',1399.260], ['20180713',1410.930], ['20180716',1405.720], ['20180717',1400.480], ['20180718',1390.060], ['20180719',1378.850], ['20180720',1404.170], ['20180723',1422.010], ['20180724',1442.180], ['20180725',1445.140], ['20180726',1426.940], ['20180727',1416.770], ['20180730',1412.310], ['20180731',1416.990], ['20180801',1391.700], ['20180802',1359.500], ['20180803',1327.240], ['20180806',1302.370], ['20180807',1342.110], ['20180808',1320.920], ['20180809',1358.340], ['20180810',1365.070], ['20180813',1364.800], ['20180814',1358.210], ['20180815',1330.030], ['20180816',1320.850], ['20180817',1298.320], ['20180820',1309.510], ['20180821',1334.530], ['20180822',1325.530], ['20180823',1329.550], ['20180824',1330.210], ['20180827',1371.490], ['20180828',1372.250], ['20180829',1365.060], ['20180830',1351.010], ['20180831',1348.890], ['20180903',1345.580], ['20180904',1360.050], ['20180905',1332.110], ['20180906',1321.000], ['20180907',1321.030], ['20180910',1300.850], ['20180911',1298.460], ['20180912',1289.400], ['20180913',1305.260], ['20180914',1299.310], ['20180917',1281.250], ['20180918',1307.640], ['20180919',1327.890], ['20180920',1325.830], ['20180921',1366.000], ['20180925',1354.930], ['20180926',1369.710], ['20180927',1361.820], ['20180928',1369.440], ['20181008',1305.590], ['20181009',1294.220], ['20181010',1290.770], ['20181011',1223.850], ['20181012',1245.210], ['20181015',1226.500], ['20181016',1204.320], ['20181017',1209.320], ['20181018',1179.220], ['20181019',1211.600], ['20181022',1265.060], ['20181023',1230.670], ['20181024',1225.820], ['20181025',1223.790], ['20181026',1217.210], ['20181029',1184.920], ['20181030',1197.550], ['20181031',1218.250], ['20181101',1228.780], ['20181102',1269.820], ['20181105',1256.970], ['20181106',1254.440], ['20181107',1248.650], ['20181108',1241.860], ['20181109',1231.080], ['20181112',1247.100], ['20181113',1256.750], ['20181114',1249.210], ['20181115',1263.380], ['20181116',1269.960], ['20181119',1280.940], ['20181120',1254.180], ['20181121',1257.420], ['20181122',1254.470], ['20181123',1227.810], ['20181126',1225.590], ['20181127',1222.800], ['20181128',1238.720], ['20181129',1222.910], ['20181130',1235.010], ['20181203',1269.400], ['20181204',1270.200], ['20181205',1264.760], ['20181206',1239.450], ['20181207',1240.620], ['20181210',1228.620], ['20181211',1237.420], ['20181212',1240.400], ['20181213',1262.600], ['20181214',1241.760], ['20181217',1242.300], ['20181218',1228.850], ['20181219',1216.240], ['20181220',1209.070], ['20181221',1195.130], ['20181224',1206.880], ['20181225',1202.330], ['20181226',1198.560], ['20181227',1193.370], ['20181228',1193.740], ['20190102',1180.570], ['20190103',1176.110], ['20190104',1201.060], ['20190107',1216.960], ['20190108',1212.820], ['20190109',1222.550], ['20190110',1217.760], ['20190111',1228.550], ['20190114',1216.050], ['20190115',1236.260], ['20190116',1237.880], ['20190117',1230.100], ['20190118',1248.330], ['20190121',1257.680], ['20190122',1236.760], ['20190123',1239.680], ['20190124',1244.480], ['20190125',1253.510], ['20190128',1254.480], ['20190129',1257.820], ['20190130',1250.570], ['20190131',1258.050], ['20190201',1277.100], ['20190211',1296.520], ['20190212',1305.420], ['20190213',1333.200], ['20190214',1331.540], ['20190215',1303.270], ['20190218',1348.840], ['20190219',1346.370], ['20190220',1352.260], ['20190221',1348.760], ['20190222',1380.050], ['20190225',1456.870], ['20190226',1436.160], ['20190227',1434.840], ['20190228',1431.080], ['20190301',1452.000], ['20190304',1470.730], ['20190305',1483.540], ['20190306',1495.860], ['20190307',1483.420], ['20190308',1427.940], ['20190311',1457.390], ['20190312',1477.540], ['20190313',1453.710], ['20190314',1441.390], ['20190315',1456.790], ['20190318',1495.940], ['20190319',1493.120], ['20190320',1495.890], ['20190321',1500.660], ['20190322',1499.650], ['20190325',1477.450], ['20190326',1449.030], ['20190327',1464.780], ['20190328',1458.920], ['20190329',1514.240], ['20190401',1555.510], ['20190402',1552.730], ['20190403',1574.770], ['20190404',1592.780], ['20190408',1584.360], ['20190409',1586.380], ['20190410',1585.830], ['20190411',1551.440], ['20190412',1547.900], ['20190415',1544.070], ['20190416',1582.550], ['20190417',1583.570], ['20190418',1577.820], ['20190419',1589.460], ['20190422',1557.350], ['20190423',1541.780], ['20190424',1548.030], ['20190425',1508.130], ['20190426',1488.530], ['20190429',1486.880], ['20190430',1492.360], ['20190506',1396.660], ['20190507',1412.510], ['20190508',1396.310], ['20190509',1375.940], ['20190510',1428.630], ['20190513',1408.790], ['20190514',1398.240], ['20190515',1422.760], ['20190516',1429.740], ['20190517',1393.270], ['20190520',1388.640], ['20190521',1409.080], ['20190522',1408.310], ['20190523',1385.990], ['20190524',1383.630], ['20190527',1404.570], ['20190528',1416.880], ['20190529',1407.360], ['20190530',1397.320], ['20190531',1395.490], ['20190603',1397.710], ['20190604',1385.620], ['20190605',1385.880], ['20190606',1370.440], ['20190610',1385.350], ['20190611',1425.040], ['20190612',1416.500], ['20190613',1412.160], ['20190614',1398.400], ['20190617',1398.660], ['20190618',1397.120], ['20190619',1417.260], ['20190620',1458.040], ['20190621',1466.400], ['20190624',1468.530], ['20190625',1457.900], ['20190626',1459.420], ['20190627',1473.310], ['20190628',1468.940], ['20190701',1508.110], ['20190702',1508.240], ['20190703',1493.600], ['20190704',1491.590], ['20190705',1494.280], ['20190708',1456.000], ['20190709',1451.390], ['20190710',1447.720], ['20190711',1441.550], ['20190712',1448.890], ['20190715',1459.110], ['20190716',1452.320], ['20190717',1452.010], ['20190718',1431.990], ['20190719',1447.660], ['20190722',1439.560], ['20190723',1444.630], ['20190724',1458.910], ['20190725',1471.380], ['20190726',1478.290], ['20190729',1475.450], ['20190730',1478.340], ['20190731',1467.110], ['20190801',1451.080], ['20190802',1428.460], ['20190805',1400.310], ['20190806',1384.240], ['20190807',1374.080], ['20190808',1392.870], ['20190809',1373.830], ['20190812',1396.990], ['20190813',1382.690], ['20190814',1389.260], ['20190815',1392.970], ['20190816',1394.970], ['20190819',1436.100], ['20190820',1434.080], ['20190821',1436.820], ['20190822',1439.480], ['20190823',1444.740], ['20190826',1431.480], ['20190827',1454.450], ['20190828',1446.880], ['20190829',1440.410], ['20190830',1441.680], ['20190902',1467.590], ['20190903',1474.170], ['20190904',1490.250], ['20190905',1503.060], ['20190906',1517.060], ['20190909',1535.700], ['20190910',1529.320], ['20190911',1517.320], ['20190912',1530.870], ['20190916',1526.030], ['20190917',1498.010], ['20190918',1501.460], ['20190919',1507.590], ['20190920',1509.670], ['20190923',1495.650], ['20190924',1501.820], ['20190925',1488.590], ['20190926',1475.100], ['20190927',1475.880], ['20190930',1460.570], ['20191008',1470.010], ['20191009',1474.950], ['20191010',1483.400], ['20191011',1495.510], ['20191014',1510.070], ['20191015',1493.880], ['20191016',1493.290], ['20191017',1493.120], ['20191018',1471.910], ['20191021',1474.790], ['20191022',1480.000], ['20191023',1471.470], ['20191024',1468.790], ['20191025',1478.940], ['20191028',1491.670], ['20191029',1481.210], ['20191030',1473.990], ['20191031',1471.070], ['20191101',1496.910], ['20191104',1505.990], ['20191105',1515.650], ['20191106',1507.110], ['20191107',1508.260], ['20191108',1500.710], ['20191111',1473.740], ['20191112',1475.050], ['20191113',1472.810], ['20191114',1475.170], ['20191115',1465.650], ['20191118',1476.680], ['20191119',1489.610], ['20191120',1477.370], ['20191121',1473.020], ['20191122',1461.540], ['20191125',1476.190], ['20191126',1479.500], ['20191127',1475.250], ['20191128',1471.840], ['20191129',1462.690], ['20191202',1465.260], ['20191203',1470.770], ['20191204',1469.590], ['20191205',1482.040], ['20191206',1488.490], ['20191209',1490.720], ['20191210',1493.470], ['20191211',1496.410], ['20191212',1493.460], ['20191213',1515.480], ['20191216',1531.300], ['20191217',1548.580], ['20191218',1543.850], ['20191219',1545.820], ['20191220',1538.970], ['20191223',1518.810], ['20191224',1527.690], ['20191225',1532.030], ['20191226',1546.650], ['20191227',1541.950], ['20191230',1565.560], ['20191231',1572.320], ['20200102',1596.160], ['20200103',1600.650], ['20200106',1593.090], ['20200107',1600.720], ['20200108',1586.640], ['20200109',1606.820], ['20200110',1602.860], ['20200113',1616.650], ['20200114',1605.720], ['20200115',1597.600], ['20200116',1594.260], ['20200117',1593.390], ['20200120',1603.510], ['20200121',1572.700], ['20200122',1583.220], ['20200123',1530.440], ['20200203',1407.890], ['20200204',1439.860], ['20200205',1457.450], ['20200206',1485.320], ['20200207',1490.620], ['20200210',1503.430], ['20200211',1511.690], ['20200212',1523.600], ['20200213',1518.440], ['20200214',1527.660], ['20200217',1564.490], ['20200218',1560.400], ['20200219',1559.510], ['20200220',1591.800], ['20200221',1599.250], ['20200224',1602.410], ['20200225',1596.960], ['20200226',1577.670], ['20200227',1586.520], ['20200228',1529.230], ['20200302',1591.860], ['20200303',1598.280], ['20200304',1607.140], ['20200305',1637.970], ['20200306',1606.660], ['20200309',1553.360], ['20200310',1594.260], ['20200311',1572.880], ['20200312',1545.460], ['20200313',1529.250], ['20200316',1458.650], ['20200317',1448.140], ['20200318',1417.910], ['20200319',1399.850], ['20200320',1424.870], ['20200323',1371.410], ['20200324',1409.900], ['20200325',1450.760], ['20200326',1435.520], ['20200327',1440.890], ['20200330',1418.870], ['20200331',1415.160], ['20200401',1410.990], ['20200402',1436.230], ['20200403',1427.350], ['20200407',1463.350], ['20200408',1459.740], ['20200409',1464.730], ['20200410',1449.950], ['20200413',1446.180], ['20200414',1474.090], ['20200415',1457.250], ['20200416',1461.730], ['20200417',1474.530], ['20200420',1485.140], ['20200421',1471.470], ['20200422',1482.780], ['20200423',1476.930], ['20200424',1464.180], ['20200427',1468.370], ['20200428',1479.640], ['20200429',1488.760], ['20200430',1513.700], ['20200506',1525.110], ['20200507',1518.020], ['20200508',1537.200], ['20200511',1536.890], ['20200512',1536.340], ['20200513',1538.280], ['20200514',1519.710], ['20200515',1516.230], ['20200518',1516.590], ['20200519',1534.810], ['20200520',1521.840], ['20200521',1508.400], ['20200522',1476.460], ['20200525',1472.010], ['20200526',1493.950], ['20200527',1481.620], ['20200528',1486.920], ['20200529',1487.540], ['20200601',1530.650], ['20200602',1535.640], ['20200603',1535.450], ['20200604',1529.690], ['20200605',1536.440], ['20200608',1546.500], ['20200609',1552.870], ['20200610',1549.430], ['20200611',1536.020], ['20200612',1536.100], ['20200615',1519.320], ['20200616',1543.460], ['20200617',1544.580], ['20200618',1553.920], ['20200619',1568.930], ['20200622',1568.880], ['20200623',1575.230], ['20200624',1583.400], ['20200629',1574.010], ['20200630',1595.180], ['20200701',1636.100], ['20200702',1670.240], ['20200703',1706.800], ['20200706',1806.980], ['20200707',1813.190], ['20200708',1847.000], ['20200709',1872.150], ['20200710',1839.440], ['20200713',1871.800], ['20200714',1856.360], ['20200715',1827.020], ['20200716',1739.440], ['20200717',1755.800], ['20200720',1818.670], ['20200721',1812.620], ['20200722',1826.710], ['20200723',1825.590], ['20200724',1742.360], ['20200727',1748.080], ['20200728',1764.200], ['20200729',1806.510], ['20200730',1798.510], ['20200731',1815.530], ['20200803',1855.760], ['20200804',1845.540], ['20200805',1847.100], ['20200806',1858.440], ['20200807',1848.550], ['20200810',1857.030], ['20200811',1834.680], ['20200812',1817.760], ['20200813',1813.630], ['20200814',1840.110], ['20200817',1881.570], ['20200818',1883.340], ['20200819',1853.710], ['20200820',1827.040], ['20200821',1837.300], ['20200824',1849.880], ['20200825',1847.010], ['20200826',1825.220], ['20200827',1834.750], ['20200828',1880.140], ['20200831',1865.820], ['20200901',1877.840], ['20200902',1876.010], ['20200903',1869.840], ['20200904',1851.050], ['20200907',1808.640], ['20200908',1817.200], ['20200909',1776.540], ['20200910',1773.670], ['20200911',1787.750], ['20200914',1790.920], ['20200915',1806.500], ['20200916',1800.210], ['20200917',1794.000], ['20200918',1830.460], ['20200921',1818.380], ['20200922',1788.630], ['20200923',1789.710], ['20200924',1753.070], ['20200925',1748.980], ['20200928',1751.940], ['20200929',1759.170], ['20200930',1753.530]]; var source='wstock.net';
hortonworks/kite
kite-morphlines/kite-morphlines-core/src/test/java/org/kitesdk/morphline/stdlib/PatternMetricFilterTest.java
<filename>kite-morphlines/kite-morphlines-core/src/test/java/org/kitesdk/morphline/stdlib/PatternMetricFilterTest.java /* * Copyright 2013 Cloudera 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.kitesdk.morphline.stdlib; import org.junit.Assert; import org.junit.Test; import org.kitesdk.morphline.api.MorphlineCompilationException; import org.kitesdk.morphline.base.Configs; import com.codahale.metrics.Counter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.Timer; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; public class PatternMetricFilterTest extends Assert { @Test public void testCompletelyEmpty() throws Exception { String str = "{}"; Config config = ConfigFactory.parseString(str); MetricFilter filter = PatternMetricFilter.parse(new Configs(), config); assertSame(filter, MetricFilter.ALL); assertTrue(filter.matches("foo", new Counter())); } @Test public void testEmpty() throws Exception { String str = "{ metricFilter : {} }"; Config config = ConfigFactory.parseString(str); MetricFilter filter = PatternMetricFilter.parse(new Configs(), config); assertNotSame(filter, MetricFilter.ALL); assertTrue(filter.matches("foo", new Counter())); assertTrue(filter.toString().length() > 0); } @Test public void testComplex() throws Exception { String str = "{" + "\n metricFilter : {" + "\n includes : { " + "\n \"literal:foo\" : \"glob:foo*\"" + "\n \"regex:.*\" : \"glob:*\"" + "\n \"regex:.*.*\" : \"glob:**\"" + "\n }" + "\n excludes : { # if missing defaults to match none" + "\n \"literal:foo.bar\" : \"glob:*\"" + "\n \"literal:boo\" : \"glob:*Timer\"" + "\n }}}"; Config config = ConfigFactory.parseString(str); MetricFilter filter = PatternMetricFilter.parse(new Configs(), config); assertNotSame(filter, MetricFilter.ALL); assertTrue(filter.matches("foo", new Counter())); assertTrue(filter.matches("boo", new Counter())); assertFalse(filter.matches("foo.bar", new Counter())); assertFalse(filter.matches("boo", new Timer())); assertTrue(filter.toString().length() > 0); } @Test public void testNotIncluded() throws Exception { String str = "{" + "\n metricFilter : {" + "\n includes : { " + "\n \"literal:foo\" : \"glob:*\"" + "\n }" + "\n }}"; Config config = ConfigFactory.parseString(str); MetricFilter filter = PatternMetricFilter.parse(new Configs(), config); assertNotSame(filter, MetricFilter.ALL); assertTrue(filter.matches("foo", new Counter())); assertFalse(filter.matches("boo", new Counter())); assertTrue(filter.toString().length() > 0); } @Test public void testWildcardMeansMatchAll() throws Exception { String str = "{" + "\n metricFilter : {" + "\n includes : { " + "\n \"*\" : \"*\"" + "\n }" + "\n }}"; Config config = ConfigFactory.parseString(str); MetricFilter filter = PatternMetricFilter.parse(new Configs(), config); assertNotSame(filter, MetricFilter.ALL); assertTrue(filter.matches("foo", new Counter())); assertTrue(filter.matches("boo", new Counter())); assertTrue(filter.toString().length() > 0); } @Test public void testUnrecognizedPatternType() throws Exception { String str = "{" + "\n metricFilter : {" + "\n includes : { " + "\n \"unRecognizedType:foo\" : \"glob:*\"" + "\n }" + "\n }}"; Config config = ConfigFactory.parseString(str); try { PatternMetricFilter.parse(new Configs(), config); fail(); } catch (MorphlineCompilationException e) { ; // expected } } @Test public void testIllegalPatternType() throws Exception { String str = "{" + "\n metricFilter : {" + "\n includes : { " + "\n \"ILLEGAL\" : \"glob:*\"" + "\n }" + "\n }}"; Config config = ConfigFactory.parseString(str); try { PatternMetricFilter.parse(new Configs(), config); fail(); } catch (MorphlineCompilationException e) { ; // expected } } }
KrimsonKing1337/gordey-backend
src/routes/tag/index.js
const express = require('express'); const getTagsAll = require('./get-all.js'); const postTag = require('./post.js'); const patchTag = require('./patch.js'); const deleteTag = require('./delete.js'); const router = express.Router(); router.use(getTagsAll); router.use(postTag); router.use(patchTag); router.use(deleteTag); module.exports = router;
Antag99/aquarria
aquarria/src/com/github/antag99/aquarria/BasicItemType.java
/******************************************************************************* * Copyright (c) 2014-2015, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Aquarria nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package com.github.antag99.aquarria; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.github.antag99.aquarria.entity.PlayerEntity; /** * Implements basic item types, loaded from json files. */ public class BasicItemType extends BasicType implements ItemType, Json.Serializable { private float width; private float height; private int maxStack; private Sprite icon; public BasicItemType() { } @Override public void read(Json json, JsonValue jsonData) { super.read(json, jsonData); width = jsonData.getFloat("width"); height = jsonData.getFloat("height"); maxStack = jsonData.getInt("maxStack", 99); icon = Assets.getSprite(jsonData.getString("icon", "null.png")); } @Override public float getWidth() { return width; } @Override public float getHeight() { return height; } /** * Sets the physical width of this item type */ public void setWidth(float width) { this.width = width; } /** * Sets the physical height of this item type */ public void setHeight(float height) { this.height = height; } @Override public int getMaxStack() { return maxStack; } /** * Sets the maximum amount of items of this type that can be stored in one slot. */ public void setMaxStack(int maxStack) { this.maxStack = maxStack; } @Override public Sprite getIcon() { return icon; } /** * Sets the texture of the item type. */ public void setIcon(Sprite icon) { this.icon = icon; } @Override public float getUsageDelay() { return 0f; } @Override public boolean getUsageRepeat() { return false; } @Override public ItemAnimation getUsageAnimation() { return null; } @Override public boolean isConsumable() { return false; } @Override public boolean canUse(PlayerEntity player, Item stack) { return false; } @Override public boolean usageEffect(PlayerEntity player, Item stack) { return false; } }
Ehtisham-Ayaan/aoo-ghr-bnain-update
node_modules/@iconify/icons-mdi/pub-outline.js
<reponame>Ehtisham-Ayaan/aoo-ghr-bnain-update<gh_stars>1-10 var data = { "body": "<path d=\"M4 2l2 20h11l2-20H4m2.2 2h10.6l-.3 3.23c-3.32 1.27-4.65.44-5.12.08c-.25-.19-.61-.62-1.27-.92c-.66-.31-1.56-.39-2.61-.07c-.41.11-.73.29-1 .47L6.2 4m2.66 4.11c.19 0 .3.04.41.09c.23.1.44.35.9.7c.86.66 2.86 1.46 6.09.51L15.2 20H7.8L6.71 9.06c.05-.06.2-.17.46-.35c.33-.21.74-.43.83-.46h.03c.38-.11.64-.15.83-.14z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; exports.__esModule = true; exports.default = data;
benknoll-umn/BioMedICUS
biomedicus-core/src/main/java/edu/umn/biomedicus/normalization/TermPos.java
<gh_stars>10-100 /* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.normalization; import edu.umn.biomedicus.common.dictionary.StringIdentifier; import edu.umn.biomedicus.common.types.syntax.PartOfSpeech; import java.nio.ByteBuffer; import javax.annotation.Nonnull; /** * A storage / hash map key object that is a tuple of a term and a part of speech. * * @author <NAME> * @since 1.7.0 */ final class TermPos implements Comparable<TermPos> { private static final int BYTES = Integer.BYTES * 2; private final int indexedTerm; private final PartOfSpeech partOfSpeech; TermPos(StringIdentifier termIdentifier, PartOfSpeech partOfSpeech) { this.indexedTerm = termIdentifier.value(); this.partOfSpeech = partOfSpeech; } TermPos(byte[] bytes) { ByteBuffer wrap = ByteBuffer.wrap(bytes); indexedTerm = wrap.getInt(); partOfSpeech = PartOfSpeech.values()[wrap.getInt()]; } StringIdentifier getIndexedTerm() { return new StringIdentifier(indexedTerm); } PartOfSpeech getPartOfSpeech() { return partOfSpeech; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TermPos termPos = (TermPos) o; if (indexedTerm != termPos.indexedTerm) { return false; } return partOfSpeech == termPos.partOfSpeech; } @Override public int hashCode() { int result = indexedTerm; result = 31 * result + partOfSpeech.hashCode(); return result; } @Override public int compareTo(@Nonnull TermPos o) { int compare = Integer.compare(indexedTerm, o.indexedTerm); if (compare != 0) { return compare; } return partOfSpeech.compareTo(o.partOfSpeech); } byte[] getBytes() { return ByteBuffer.allocate(BYTES).putInt(indexedTerm).putInt(partOfSpeech.ordinal()).array(); } }
cxelegance/bread-calculator
src/tests/lib/calculators.test.js
import {twoDecimal, zeroOrNumber} from '../../lib/calculators'; const zero = '0.00'; test('twoDecimal handles 0 correctly', () => { expect(twoDecimal(0)).toBe(zero); expect(twoDecimal(-0)).toBe(zero); expect(twoDecimal(+0)).toBe(zero); expect(twoDecimal('0')).toBe(zero); expect(twoDecimal('-0')).toBe(zero); expect(twoDecimal('+0')).toBe(zero); expect(twoDecimal(0.00)).toBe(zero); expect(twoDecimal(0.000000)).toBe(zero); }); test('zeroOrNumber handles 0 correctly', () => { expect(zeroOrNumber(0)).toBe(0); expect(zeroOrNumber(-0)).toBe(0); expect(zeroOrNumber(+0)).toBe(0); expect(zeroOrNumber('0')).toBe(0); expect(zeroOrNumber('-0')).toBe(0); expect(zeroOrNumber('+0')).toBe(0); expect(zeroOrNumber(0.00)).toBe(0); expect(zeroOrNumber(0.000000)).toBe(0); }); test('twoDecimal handles infinity and NaN correctly', () => { expect(twoDecimal(NaN)).toBe(zero); expect(twoDecimal(Infinity)).toBe(zero); expect(twoDecimal(1/0)).toBe(zero); expect(twoDecimal(2 * 'a')).toBe(zero); expect(twoDecimal('b' * 1)).toBe(zero); expect(twoDecimal(2 * '1')).toBe('2.00'); expect(twoDecimal('2' * 1)).toBe('2.00'); expect(twoDecimal('1')).toBe(zero); expect(twoDecimal('2')).toBe(zero); }); test('zeroOrNumber handles infinity and NaN correctly', () => { expect(zeroOrNumber(NaN)).toBe(0); expect(zeroOrNumber(Infinity)).toBe(0); expect(zeroOrNumber(1/0)).toBe(0); expect(zeroOrNumber(2 * 'a')).toBe(0); expect(zeroOrNumber('b' * 1)).toBe(0); expect(zeroOrNumber(2 * '1')).toBe(2); expect(zeroOrNumber('2' * 1)).toBe(2); expect(zeroOrNumber('1')).toBe(0); expect(zeroOrNumber('2')).toBe(0); }); test('twoDecimal handles rounding as expected', () => { expect(twoDecimal(0.004)).toBe(zero); expect(twoDecimal(0.005)).toBe('0.01'); expect(twoDecimal(0.009)).toBe('0.01'); expect(twoDecimal(0.554)).toBe('0.55'); expect(twoDecimal(0.555)).toBe('0.56'); expect(twoDecimal(0.556)).toBe('0.56'); expect(twoDecimal(9.556)).toBe('9.56'); expect(twoDecimal(9.559)).toBe('9.56'); expect(twoDecimal(9.564)).toBe('9.56'); });
djose1164/Immortal-WIll
include/core/physics.h
<filename>include/core/physics.h #ifndef PHYSICS #define PHYSICS #include "living.h" #include <raylib.h> struct World { double gravity; }; static inline double physics_get_velocity(Living *being, const double time) { return (double)(being->str / being->weight) * time; } static inline double physics_speed(double distance, double time) { return (double)(distance/time); } #endif //PHYSICS
smileytechguy/COMPPROG1
Ch02/A3_010_RandomBox_Overcash.java
/** * @author <NAME> -- smileytechguy * @version 2.0.1.2.43.3.2.3 * explainations of code: https://goo.gl/RyIzwb */ import objectdraw.*; import java.awt.*; import java.util.*; public class A3_010_RandomBox_Overcash extends WindowController { public static void main(String[ ]args) { A3_010_RandomBox_Overcash oc = new A3_010_RandomBox_Overcash(); oc.startController(600, 600); } RandomIntGenerator rColorg = new RandomIntGenerator(0, 255); RandomIntGenerator rHWg = new RandomIntGenerator(0, 300); int[] rColor = {0, 0, 0}; int rWidth; int rHeight; FilledRect box = new FilledRect(250, 250, 100, 100, canvas); FramedRect boxFrame = new FramedRect(250, 250, 100, 100, canvas); Text widthT = new Text("Width: null", 0, 0, canvas); Text heightT = new Text("Height: null", 0, 14, canvas); Text locT = new Text("Location: null", 0, 28, canvas); Text colorT = new Text("Color: rgb(null)", 0, 42, canvas); public void onMousePress(Location p) { rColor[0] = rColorg.nextValue(); rColor[1] = rColorg.nextValue(); rColor[2] = rColorg.nextValue(); rWidth = rHWg.nextValue(); rHeight = rHWg.nextValue(); System.out.println("new color "+Arrays.toString(rColor)); System.out.println("new h/w "+Arrays.toString(new int[] {rWidth, rHeight})); System.out.println("calculated coords ["+((canvas.getWidth()/2)-(rWidth/2))+", "+((canvas.getHeight()/2)-(rHeight/2))+"]"); box.setColor(new Color(rColor[0], rColor[1], rColor[2])); box.setWidth(rWidth); box.setHeight(rHeight); boxFrame.setWidth(rWidth); boxFrame.setHeight(rHeight); box.moveTo(((canvas.getWidth()/2)-(rWidth/2)), ((canvas.getHeight()/2)-(rHeight/2))); boxFrame.moveTo(((canvas.getWidth()/2)-(rWidth/2)), ((canvas.getHeight()/2)-(rHeight/2))); widthT.setText("Widt: "+rWidth); heightT.setText("Heit: "+rHeight); locT.setText("Locashun: ["+((canvas.getWidth()/2)-(rWidth/2))+", "+((canvas.getHeight()/2)-(rHeight/2))+"]"); colorT.setText("Colaaaaaaaaaaaaaaaaaaaaa: rgb("+Arrays.toString(rColor)+")"); } public void begin() { rColor[0] = rColorg.nextValue(); rColor[1] = rColorg.nextValue(); rColor[2] = rColorg.nextValue(); rWidth = rHWg.nextValue(); rHeight = rHWg.nextValue(); System.out.println("new color "+Arrays.toString(rColor)); System.out.println("new h/w "+Arrays.toString(new int[] {rWidth, rHeight})); System.out.println("calculated coords ["+((canvas.getWidth()/2)-(rWidth/2))+", "+((canvas.getHeight()/2)-(rHeight/2))+"]"); box.setColor(new Color(rColor[0], rColor[1], rColor[2])); box.setWidth(rWidth); box.setHeight(rHeight); boxFrame.setWidth(rWidth); boxFrame.setHeight(rHeight); box.moveTo(((canvas.getWidth()/2)-(rWidth/2)), ((canvas.getHeight()/2)-(rHeight/2))); boxFrame.moveTo(((canvas.getWidth()/2)-(rWidth/2)), ((canvas.getHeight()/2)-(rHeight/2))); widthT.setText("Widt: "+rWidth); heightT.setText("Heit: "+rHeight); locT.setText("Locashun: ["+((canvas.getWidth()/2)-(rWidth/2))+", "+((canvas.getHeight()/2)-(rHeight/2))+"]"); colorT.setText("Colaaaaaaaaaaaaaaaaaaaaa: rgb("+Arrays.toString(rColor)+")"); } public void onMouseEnter(Location p) { boxFrame.show(); box.show(); rColor[0] = rColorg.nextValue(); rColor[1] = rColorg.nextValue(); rColor[2] = rColorg.nextValue(); rWidth = rHWg.nextValue(); rHeight = rHWg.nextValue(); System.out.println("new color "+Arrays.toString(rColor)); System.out.println("new h/w "+Arrays.toString(new int[] {rWidth, rHeight})); System.out.println("calculated coords ["+((canvas.getWidth()/2)-(rWidth/2))+", "+((canvas.getHeight()/2)-(rHeight/2))+"]"); box.setColor(new Color(rColor[0], rColor[1], rColor[2])); box.setWidth(rWidth); box.setHeight(rHeight); boxFrame.setWidth(rWidth); boxFrame.setHeight(rHeight); box.moveTo(((canvas.getWidth()/2)-(rWidth/2)), ((canvas.getHeight()/2)-(rHeight/2))); boxFrame.moveTo(((canvas.getWidth()/2)-(rWidth/2)), ((canvas.getHeight()/2)-(rHeight/2))); widthT.setText("Widt: "+rWidth); heightT.setText("Heit: "+rHeight); locT.setText("Locashun: ["+((canvas.getWidth()/2)-(rWidth/2))+", "+((canvas.getHeight()/2)-(rHeight/2))+"]"); colorT.setText("Colaaaaaaaaaaaaaaaaaaaaa: rgb("+Arrays.toString(rColor)+")"); } public void onMouseExit(Location p) { box.hide(); boxFrame.hide(); widthT.setText("Width: null"); heightT.setText("Height: null"); locT.setText("Location: null"); colorT.setText("Color: null"); } }
frederic-lefevre/FlUtils
src/main/java/org/fl/util/io/ForkableInputStream.java
package org.fl.util.io; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class ForkableInputStream extends InputStream { private final Logger logger; private final int readerId; private final MultiReaderCircularBuffer<Integer> buffer; private final InputStream sourceInputStream; private final InputStream originInputStream; private List<ForkedOutputStream> forkedOutputStreams; private long nbBytesRead; private boolean isClosed = false; public ForkableInputStream(InputStream originInputStream, Logger l) { this.originInputStream = originInputStream; // As the implementation of read(yte[] b, int off, int len) calls read() // there is a high interest in enclosing the source inputStream in a BufferedInputStream // There is a small penalty if the source inputStream is already buffered but a great advantage if it is not // That is the case for FileInputStream, for instance this.logger = l; this.sourceInputStream = new BufferedInputStream(originInputStream); this.buffer = new MultiReaderCircularBuffer<>(); this.readerId = this.buffer.newReadClient(); this.forkedOutputStreams = new ArrayList<>(); this.nbBytesRead = 0; } public ForkableInputStream(InputStream originInputStream, int capacity, Logger l) { this.logger = l; this.originInputStream = originInputStream; this.sourceInputStream = new BufferedInputStream(originInputStream); this.buffer = new MultiReaderCircularBuffer<>(capacity); this.readerId = this.buffer.newReadClient(); this.forkedOutputStreams = new ArrayList<>(); this.nbBytesRead = 0; } // Essentially for test protected ForkableInputStream(InputStream originInputStream, int capacity, boolean force, Logger l) { this.logger = l; this.originInputStream = originInputStream; this.sourceInputStream = new BufferedInputStream(originInputStream); this.buffer = new MultiReaderCircularBuffer<>(capacity, force); this.readerId = this.buffer.newReadClient(); this.forkedOutputStreams = new ArrayList<>(); this.nbBytesRead = 0; } public boolean addForkedOutputStream(OutputStream outputStream) { int osReaderClient = buffer.newReadClient(); if (osReaderClient > -1) { forkedOutputStreams.add(new ForkedOutputStream(osReaderClient, outputStream)); return true; } else { logger.severe("Impossible to fork an output stream: maximal number of fork reached"); return false; } } @Override public int read() throws IOException { Integer b = buffer.read(readerId); if (b == null) { // no bytes available in buffer for this reader // fill buffer with source int i = sourceInputStream.read(); if (buffer.write(i)) { b = buffer.read(readerId); } else { // no more space in buffer // Make space in sending to output streams writeToForkedOutputStreams(); if (buffer.write(i)) { b = buffer.read(readerId); } else { // Still no more space, give up throw new IOException("ForkableInputStream buffer full"); } } } if (b == -1) { // end of source input stream writeToForkedOutputStreams(); } else { this.nbBytesRead++; } return b; } // The read(byte[] b, int off, int len) has to be overridden in case the source InputStream has itself overridden it // without calling the read() in its implementation // This ensures that all the bytes are going into the MultiReaderCircularBuffer @Override public int read(byte[] b, int off, int len) throws IOException { // Check parameters if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } int c = read(); if (c == -1) { // end of source inputStream // The writeToForkedOutputStreams has already been done in read() return -1; } b[off] = (byte)c; int numberOfBytesRead = 1; try { for (; numberOfBytesRead < len ; numberOfBytesRead++) { c = read(); if (c == -1) { // end of source inputStream // The writeToForkedOutputStreams has already been done in read() break; } b[off + numberOfBytesRead] = (byte)c; } } catch (IOException ignored) { // Treated as if it were end of file, according to InputStream contract } return numberOfBytesRead; } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public void close() throws IOException { if (! isClosed) { super.close(); originInputStream.close(); isClosed = true; closeForkedOutputStreams(); if (logger.isLoggable(Level.FINEST)) { logger.finest(() -> "Number of bytes read on " + this + " : " + this.nbBytesRead); for (ForkedOutputStream forkedOutputStream : forkedOutputStreams) { logger.finest(() -> "Number of bytes written on " + forkedOutputStream + " : " + forkedOutputStream.getNbBytesWritten()); } } } } // skip has to be overridden. If not, bytes skipped would be written to outputStreams @Override public long skip(long n) throws IOException { if (n <= 0) { return 0; } long remaining = n; while (remaining > 0) { // Use read() only, NOT read array int b = sourceInputStream.read(); if (b == -1) { // end of source input stream break; } remaining--; } return n - remaining; } @Override public synchronized void mark(int readlimit) { // As bytes are written to outputStream as they are read, mark cannot be supported } // As bytes are written to outputStream as they are read, mark cannot be supported @Override public synchronized void reset() throws IOException { throw new IOException("mark/reset not supported"); } // As bytes are written to outputStream as they are read, mark cannot be supported @Override public boolean markSupported() { return false; } @Override public int available() { return (int)Math.min(buffer.available(readerId), Integer.MAX_VALUE); } private void writeToForkedOutputStreams() throws IOException { for (ForkedOutputStream forkedOutputStream : forkedOutputStreams) { Integer b = 0; long nbBytesWritten = 0; while (b != null) { b = buffer.read(forkedOutputStream.readerId); if ((b != null) && (b != -1)) { forkedOutputStream.write(b); nbBytesWritten++; } } forkedOutputStream.addNbBytesWritten(nbBytesWritten); } } private void closeForkedOutputStreams() throws IOException { for (ForkedOutputStream forkedOutputStream : forkedOutputStreams) { forkedOutputStream.close(); } } private static class ForkedOutputStream { private final int readerId; private final OutputStream outputStream; private long nbBytesWritten; public ForkedOutputStream(int readerId, OutputStream outputStream) { this.readerId = readerId; this.outputStream = outputStream; this.nbBytesWritten = 0; } public void addNbBytesWritten(long n) { this.nbBytesWritten = this.nbBytesWritten + n; } public long getNbBytesWritten() { return this.nbBytesWritten; } public void write(int b) throws IOException { this.outputStream.write(b); } public void close() throws IOException { this.outputStream.flush(); this.outputStream.close(); } } }
ECharts-Java/ECharts-Java
src/main/java/org/icepear/echarts/origin/util/CircleLayoutOptionMixin.java
package org.icepear.echarts.origin.util; /** * https://github.com/apache/echarts/blob/790687df55a5dbe286e52cf182c0983938efd367/src/util/types.ts#L834 */ public interface CircleLayoutOptionMixin { CircleLayoutOptionMixin setCenter(Number[] center); CircleLayoutOptionMixin setCenter(String[] center); CircleLayoutOptionMixin setRadius(Number radius); CircleLayoutOptionMixin setRadius(Number[] radius); CircleLayoutOptionMixin setRadius(Object[] radius); CircleLayoutOptionMixin setRadius(String radius); CircleLayoutOptionMixin setRadius(String[] radius); }
cristigr/macrobase
lib/src/test/java/edu/stanford/futuredata/macrobase/analysis/summary/fpg/result/ExplanationTest.java
<gh_stars>100-1000 package edu.stanford.futuredata.macrobase.analysis.summary.fpg.result; import edu.stanford.futuredata.macrobase.analysis.summary.fpg.FPGExplanation; import edu.stanford.futuredata.macrobase.analysis.summary.fpg.result.FPGAttributeSet; import org.junit.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class ExplanationTest { @Test public void testPrune() throws Exception { Map<String, String> v1 = new HashMap<>(); v1.put("c1", "val1"); v1.put("c2", "val2"); Map<String, String> v2 = new HashMap<>(); v2.put("c2", "val2"); FPGAttributeSet a1 = new FPGAttributeSet( .2, 10.0, 21.2, v1 ); // a2 makes a1 redundant FPGAttributeSet a2 = new FPGAttributeSet( .7, 30.0, 25.0, v2 ); FPGExplanation e = new FPGExplanation( Arrays.asList(a1, a2), 100, 10, 0 ); assertEquals(2, e.getItemsets().size()); assertEquals(1, e.prune().getItemsets().size()); } }
juanfelipe82193/opensap
sapui5-sdk-1.74.0/resources/sap/gantt/shape/cal/Calendar-dbg.js
<filename>sapui5-sdk-1.74.0/resources/sap/gantt/shape/cal/Calendar-dbg.js /*! * SAP UI development toolkit for HTML5 (SAPUI5) (c) Copyright 2009-2015 SAP SE. All rights reserved */ sap.ui.define([ "sap/gantt/shape/Rectangle" ], function (Rectangle) { "use strict"; /** * Creates a Calendar shape which consumes pattern from Calendar in 'def' package. * * @param {string} [sId] ID of the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * Calendar shape. * * <p> * The Calendar shape must be used in combination with Calendar def class {@link sap.gantt.def.cal.Calendar} which draws SVG 'defs' tag. * </p> * * @extends sap.gantt.shape.Rectangle * * @author SAP SE * @version 1.74.0 * * @constructor * @public * @alias sap.gantt.shape.cal.Calendar */ var Calendar = Rectangle.extend("sap.gantt.shape.cal.Calendar", /** @lends sap.gantt.shape.cal.Calendar.prototype */ { metadata: { properties: { isBulk: {type: "boolean", defaultValue: true}, enableSelection: {type: "boolean", defaultValue: false}, calendarName: {type: "string", defaultValue: "nwt"} } } }); Calendar.prototype.init = function() { Rectangle.prototype.init.apply(this, arguments); var oRb = sap.ui.getCore().getLibraryResourceBundle("sap.gantt"); this.setProperty("ariaLabel", oRb.getText("ARIA_CALENDAR")); }; /** * Gets the value of property <code>calendarName</code>. * * <p> * Calendar key. * * This property is used to generate referencing string to compose the <code>fill</code> property. This property is must provided. * </p> * * @param {object} oData Shape data. * @param {object} oRowInfo Information about the row and the row data. * @return {string} Value of property <code>calendarName</code>. * @public */ Calendar.prototype.getCalendarName = function (oData) { return this._configFirst("calendarName", oData); }; /** * Gets current value of property <code>isBulk</code>. * * General recommendation is don't configure or code against this property. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {boolean} Value of property <code>isBulk</code>. * @public */ Calendar.prototype.getIsBulk = function (oData) { if (this.mShapeConfig.isBulk) { return this._configFirst("isBulk", oData); } return true; }; /** * Gets current value of property <code>enableSelection</code>. * * General recommendation is don't configure or code against this property. Calendar is treated as a bulk shape filled with pattern occupying visible chart area. * Application should implement their own shape if a select able calendar is expected. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {boolean} Value of property <code>enableSelection</code>. * @public */ Calendar.prototype.getEnableSelection = function (oData) { if (this.mShapeConfig.enableSelection) { return this._configFirst("enableSelection", oData); } return false; }; /** * Gets current value of property <code>x</code>. * * General recommendation is don't configure or code against this property. Calendar is treated as a bulk shape filled with pattern occupying visible chart area. * Application should implement their own shape if a select able calendar is expected. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {number} Value of property <code>x</code>. * @public */ Calendar.prototype.getX = function (oData) { if (this.mShapeConfig.x) { return this._configFirst("x", oData); } return this.mChartInstance._oStatusSet.aViewBoundary[0]; }; /** * Gets current value of property <code>y</code>. * * General recommendation is don't configure or code against this property. Calendar is treated as a bulk shape filled with pattern occupying visible chart area. * Application should implement their own shape if a select able calendar is expected. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {number} Value of property <code>y</code>. * @public */ Calendar.prototype.getY = function (oData, oRowInfo) { if (this.mShapeConfig.y) { return this._configFirst("y", oData); } return oRowInfo.y; }; /** * Gets current value of property <code>width</code>. * * General recommendation is don't configure or code against this property. Calendar is treated as a bulk shape filled with pattern occupying visible chart area. * Application should implement their own shape if a select able calendar is expected. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {number} Value of property <code>width</code>. * @public */ Calendar.prototype.getWidth = function (oData) { if (this.mShapeConfig.width) { return this._configFirst("width", oData); } var oStatusSet = this.mChartInstance._oStatusSet; if (oStatusSet) { return oStatusSet.aViewBoundary[1] - oStatusSet.aViewBoundary[0]; } else { return 0; } }; /** * Gets current value of property <code>height</code>. * * General recommendation is don't configure or code against this property. Calendar is treated as a bulk shape filled with pattern occupying visible chart area. * Application should implement their own shape if a select able calendar is expected. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {number} Value of property <code>height</code>. * @public */ Calendar.prototype.getHeight = function (oData, oRowInfo) { if (this.mShapeConfig.height) { return this._configFirst("height", oData); } return oRowInfo.rowHeight; }; /** * Gets current value of property <code>fill</code>. * * General recommendation is don't configure or code against this property. Calendar is treated as a bulk shape filled with pattern occupying visible chart area. * Application should implement their own shape if a select able calendar is expected. * * @param {object} oData Shape data. * @param {object} oRowInfo Information of the row and row data. * @return {string} Value of property <code>fill</code>. * @public */ Calendar.prototype.getFill = function (oData, oRowInfo) { if (this.mShapeConfig.hasShapeProperty("fill")) { return this._configFirst("fill", oData); } var sCalendarName = this.getCalendarName(oData, oRowInfo); var oPaintServerDef = this.mChartInstance.getCalendarDef(); if (oPaintServerDef) { return oPaintServerDef.getRefString(sCalendarName); } }; return Calendar; }, true);
oscana/oscana-s2n-javaconverter
src/main/java/jp/co/tis/s2n/javaConverter/convert/validation/sastruts/DateFormatValidateHandler.java
<filename>src/main/java/jp/co/tis/s2n/javaConverter/convert/validation/sastruts/DateFormatValidateHandler.java<gh_stars>0 package jp.co.tis.s2n.javaConverter.convert.validation.sastruts; import jp.co.tis.s2n.javaConverter.convert.validation.annotation.FieldValidateAnnotation; import jp.co.tis.s2n.javaConverter.convert.validation.annotation.ValidateAnnotation; import jp.co.tis.s2n.javaConverter.node.AnnotationNodeUtil; /** * Date型に変換可能であるかのチェックを行う。 * @author <NAME> * */ public class DateFormatValidateHandler extends SAStrutsAbstractValidateHandler { /** * 変換主処理。 * @param memberAnnotationNode 変換対象のアノテーションノードユーティリティ * @return 変換結果 */ @Override public ValidateAnnotation handle(AnnotationNodeUtil memberAnnotationNode) { String datePattern = memberAnnotationNode.getStringValue("format"); return new FieldValidateAnnotation("DateFormat").addStringParameter("format", datePattern) .addStringParameter("message", "\"{errors.dateformat}\"").addStringParameter("target", memberAnnotationNode.getStringValue("target")); } }
velasqueziturrate/multiplataforma
node_modules/.staging/@nativescript/core-b2cc363a/fps-meter/index.js
import * as fpsNative from './fps-native'; const callbacks = {}; let idCounter = 0; let _minFps = 1000; let framesRendered = 0; let frameStartTime = 0; function doFrame(currentTimeMillis) { let fps = 0; if (frameStartTime > 0) { // take the span in milliseconds const timeSpan = currentTimeMillis - frameStartTime; framesRendered++; if (timeSpan > 1000) { fps = (framesRendered * 1000) / timeSpan; if (fps < _minFps) { _minFps = fps; } notify(fps); frameStartTime = currentTimeMillis; framesRendered = 0; } } else { frameStartTime = currentTimeMillis; } } let native; function ensureNative() { if (!native) { native = new fpsNative.FPSCallback(doFrame); } } export function reset() { _minFps = 1000; frameStartTime = 0; framesRendered = 0; } export function running() { if (!native) { return false; } return native.running; } export function minFps() { return _minFps; } export function start() { ensureNative(); native.start(); } export function stop() { if (!native) { return; } native.stop(); reset(); } export function addCallback(callback) { const id = idCounter; // Wrap all calback in zonedCallback so that they work with the current zone. callbacks[id] = zonedCallback(callback); idCounter++; return id; } export function removeCallback(id) { if (id in callbacks) { delete callbacks[id]; } } function notify(fps) { let callback; for (let id in callbacks) { callback = callbacks[id]; callback(fps, _minFps); } } //# sourceMappingURL=index.js.map
397786756/noark3
noark-core/src/main/java/xyz/noark/core/ioc/manager/EventMethodManager.java
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.ioc.manager; import xyz.noark.core.event.Event; import xyz.noark.core.ioc.wrap.method.EventMethodWrapper; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * 事件处理管理类. * * @author 小流氓[<EMAIL>] * @since 3.0 */ public class EventMethodManager { private static final EventMethodManager INSTANCE = new EventMethodManager(); private final Map<Class<? extends Event>, List<EventMethodWrapper>> handlers = new ConcurrentHashMap<>(); private final Set<Class<? extends Event>> rebuildSet = new HashSet<>(); private EventMethodManager() { } public static EventMethodManager getInstance() { return INSTANCE; } /** * 获取事件订阅列表. * * @param eventClass 事件源类型 * @return 订阅列表 */ public List<EventMethodWrapper> getEventMethodWrappers(Class<? extends Event> eventClass) { return handlers.getOrDefault(eventClass, Collections.emptyList()); } /** * 注册事件处理方法. * * @param eventWrapper 事件处理方法包装对象 */ public void resetEventHandler(EventMethodWrapper eventWrapper) { handlers.computeIfAbsent(eventWrapper.getEventClass(), key -> new ArrayList<>()).add(eventWrapper); } /** * 事件处理器排序执行 */ public void sort() { handlers.values().forEach(v -> sort(v)); } /** * 同一事件源的处理器进行排序,同步事件优化,然后才是异步事件. * * @param handlers 处理器列表 */ private void sort(List<EventMethodWrapper> handlers) { Collections.sort(handlers); } /** * 扩展事件监听处理器. * * @return 事件处理管理类单例 */ public EventMethodManager listenerExtend() { final Map<Class<? extends Event>, Set<EventMethodWrapper>> extend = new HashMap<>(32); // 查找一下所有父类,有监听那就要增强扩展 for (Class<? extends Event> klass : handlers.keySet()) { for (Map.Entry<Class<? extends Event>, List<EventMethodWrapper>> e : handlers.entrySet()) { // klass 是 e.getKey() 的父类 if (!klass.equals(e.getKey()) && e.getKey().isAssignableFrom(klass)) { extend.computeIfAbsent(klass, key -> new HashSet<>()).addAll(e.getValue()); } } } // 再把上面的扩展加进去... extend.forEach((k, v) -> handlers.computeIfAbsent(k, key -> new ArrayList<>()).addAll(v)); return INSTANCE; } /** * 重构事件处理器. * <p> * 当有接口有子类时只监听了接口会出现这种情况. * * @param klass 事件类型 * @return 返回关心这个事件的所有处理器 */ public List<EventMethodWrapper> rebuildEventHandler(Class<? extends Event> klass) { List<EventMethodWrapper> result = this.getEventMethodWrappers(klass); if (!result.isEmpty() || rebuildSet.contains(klass)) { return result; } // 存档在重构过的集合中 this.rebuildSet.add(klass); // 查找一下所有父类,有监听那就要增强扩展 final Set<EventMethodWrapper> hs = new HashSet<>(); for (Map.Entry<Class<? extends Event>, List<EventMethodWrapper>> e : handlers.entrySet()) { // klass 是 e.getKey() 的父类 if (!klass.equals(e.getKey()) && e.getKey().isAssignableFrom(klass)) { hs.addAll(e.getValue()); } } // 重新构建新的监听器列表,需要对此再排序一次 result = new ArrayList<EventMethodWrapper>(hs); this.sort(result); handlers.put(klass, result); return result; } }
Kamilleski/classics-archivee
app/models/rss_to_dumped_link.rb
<filename>app/models/rss_to_dumped_link.rb require 'rss' module RSSToDumpedLink def get_feed(rss_url) response = HTTParty.get rss_url feed = RSS::Parser.parse response.body end def feed_to_link(parsed_feed) existing_titles = Article.all.map(&:title).concat DumpedLink.all.map(&:title) parsed_feed.items.each do |item| title = item.title unless existing_titles.include? title DumpedLink.create( title: title, url: item.link, submission_route: 'RSS Feed', rss_object: item.to_json ) end end end def self.check_feeds RssFeed.all.each do |f| feed = get_feed(f.feed_url) feed_to_link(feed) end end end
Oonan/Uckeckin
modules/signals/client/signals.client.module.js
'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('signals', ['core']); ApplicationConfiguration.registerModule('signals.admin', ['core.admin']); ApplicationConfiguration.registerModule('signals.admin.routes', ['core.admin.routes']); ApplicationConfiguration.registerModule('signals.routes', ['ui.router', 'core.routes', 'signals.services']); ApplicationConfiguration.registerModule('signals.services');
berenddeboer/ewg
library/runtime/c/src/ewg_identified.c
/* The following has been taken from eGTK. */ /* It is the C part of a weak reference implementation for SE. */ /* If I understand it correctly, `id_table' will never shrink. */ /* Thats why this implementation is suboptimal, but word on the street */ /* is that SE will gain native weak references really soon now. */ /* As soon as they are there, we should use those and dump this. */ /* Copyright 1999 <NAME> and others Licensed under Eiffel Forum Freeware License, version 1; (see forum.txt) */ #include <stdio.h> #if defined(__APPLE__) || defined(__FreeBSD__) #include <stdlib.h> #else #include <malloc.h> #endif #define SIZE_INCREMENT 1024 /* This is really an pointer to an array of pointers */ /* Size of pointers can is not always 4 bytes (eg. on the Alpha) */ /* so be careful with sizes of things. */ static int **id_table = NULL; /* Capacity in integers */ static int id_table_capacity = 0; static int next_id = 0; /***************************************/ /* Assign a new ID to an Eiffel object */ /***************************************/ int ewg_new_id (void *object) { /* Allocate a new table if needed */ if (id_table == NULL) { id_table = (int **) malloc (SIZE_INCREMENT * sizeof (int *)); id_table_capacity = SIZE_INCREMENT; } /* Bump ID to the next one */ next_id++; /* If table too small, realloc */ if (next_id > id_table_capacity) { id_table_capacity = id_table_capacity + SIZE_INCREMENT; id_table = (int **) realloc (id_table, id_table_capacity * sizeof(int *)); } /* Store the Eiffel reference */ id_table [next_id] = (int *) object; return next_id; } void *ewg_id_object (int id) { void *result; if (id <= next_id) { result = (void *)id_table [id]; } else { result = NULL; } return result; } void ewg_free_id (int id) { if (id <= next_id) { id_table[id] = 0; } }
shiomusubi496/library
test/yuki/1601-RangeSet.test.cpp
<filename>test/yuki/1601-RangeSet.test.cpp #define PROBLEM "https://yukicoder.me/problems/1601" #include "../../other/template.hpp" #include "../../data-struct/other/RangeSet.hpp" using namespace std; int main() { ll D, Q; cin >> D >> Q; RangeSet st; ll ans = 0; rep (Q) { ll a, b; cin >> a >> b; st.insert(a, b + 1); auto p = st.find(a); chmax(ans, p.second - p.first); cout << ans << endl; } }
stackriot/micro-stripe-example
packages/stripe-mongoose/src/subscription-items/schema.js
<reponame>stackriot/micro-stripe-example const { required, ref, refList } = require('../_schema/helpers') module.exports = { id: required(String), plan: ref('Plan'), quantity: Number }
Stanford-PERTS/triton
src/state/metrics/selectors.js
import _values from 'lodash/values'; export const allMetrics = state => _values(state.metrics).sort((a, b) => { // alphabetical sort if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; }); export const mapMetricIdToBool = state => Object.keys(state.metrics).reduce((o, m) => { o[m] = false; return o; }, {});
vftens/MuZeroText2021
MuZero/muzero-general/games/RocAlphaGo_aug25_keras2_py35/node_modules/@consta/uikit/__internal__/cjs-src/utils/types/PropsWithAsAttributes.js
"use strict"; exports.__esModule = true; exports.forwardRefWithAs = void 0; var tslib_1 = require("tslib"); var react_1 = tslib_1.__importDefault(require("react")); function forwardRefWithAs(render) { return react_1["default"].forwardRef(render); } exports.forwardRefWithAs = forwardRefWithAs;
beyzanurkarakaya/Java-Programming
OOP-Proje-2019/CENG102_PROJE_2019_OTEL/src/CENG102_PROJE_2019_OTEL/RezervasyonEkle.java
/* * 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 CENG102_PROJE_2019_OTEL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; /** * * @author beyza */ public class RezervasyonEkle extends javax.swing.JFrame { String connectionString = "jdbc:sqlserver://127.0.0.1; databaseName=OTEL_Proje_2019"; Item[] oda; /** * Creates new form RezervasyonEkle */ public RezervasyonEkle() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { rezervasyonOnayla = new javax.swing.JPanel(); odaAdi = new javax.swing.JLabel(); musTc = new javax.swing.JLabel(); kalacakY = new javax.swing.JLabel(); kalacakC = new javax.swing.JLabel(); girisT = new javax.swing.JLabel(); cikisT = new javax.swing.JLabel(); kalınacakGun = new javax.swing.JLabel(); rezOnayla = new javax.swing.JButton(); textMusTc = new javax.swing.JTextField(); textKalanY = new javax.swing.JTextField(); textKalanC = new javax.swing.JTextField(); textGirisT = new javax.swing.JTextField(); textCikisT = new javax.swing.JTextField(); textGun = new javax.swing.JTextField(); tutarHesaplaButonu = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); rezTuruUyari = new javax.swing.JTextArea(); rezTuru = new javax.swing.JLabel(); odaCombo = new javax.swing.JComboBox<>(); tutar = new javax.swing.JFormattedTextField(); textRezTuru = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); rezervasyonOnayla.setBackground(new java.awt.Color(255, 255, 204)); odaAdi.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N odaAdi.setText("Oda Tipi:"); musTc.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N musTc.setText("Müşteri TC:"); kalacakY.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N kalacakY.setText("Kalacak Yetişkin Sayısı:"); kalacakC.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N kalacakC.setText("Kalacak Çocuk Sayısı:"); girisT.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N girisT.setText("Giriş Tarihi:"); cikisT.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N cikisT.setText("Çıkış Tarihi:"); kalınacakGun.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N kalınacakGun.setText("Kalınacak Gün Sayısı:"); rezOnayla.setFont(new java.awt.Font("Cambria", 2, 12)); // NOI18N rezOnayla.setForeground(new java.awt.Color(102, 0, 102)); rezOnayla.setText("<NAME>"); rezOnayla.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rezOnaylaActionPerformed(evt); } }); tutarHesaplaButonu.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N tutarHesaplaButonu.setForeground(new java.awt.Color(102, 0, 102)); tutarHesaplaButonu.setText("Toplam Tutarı Hesapla:"); tutarHesaplaButonu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tutarHesaplaButonuActionPerformed(evt); } }); rezTuruUyari.setColumns(20); rezTuruUyari.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N rezTuruUyari.setRows(5); rezTuruUyari.setText("REZERVASYON TÜRÜ TABLOSU\n\n(Ücretlendirmeler Kişi Başınadır)\n\n1 - Sadece Oda: Oda Fiyatı\n2 - Yarım Pansiyon: +15\n3 - Tam Pansiyon: +30\n4 - Her Şey Dahil: +50"); jScrollPane2.setViewportView(rezTuruUyari); rezTuru.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N rezTuru.setText("Rezervasyon Türü:"); tutar.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("")))); javax.swing.GroupLayout rezervasyonOnaylaLayout = new javax.swing.GroupLayout(rezervasyonOnayla); rezervasyonOnayla.setLayout(rezervasyonOnaylaLayout); rezervasyonOnaylaLayout.setHorizontalGroup( rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(rezTuru, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(girisT, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE) .addComponent(cikisT, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE) .addComponent(kalınacakGun, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)) .addComponent(kalacakC, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(musTc, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(odaAdi, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(odaCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textMusTc, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addComponent(kalacakY, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textKalanC, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textKalanY, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textGirisT, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textCikisT, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textGun, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textRezTuru, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 31, Short.MAX_VALUE))) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rezervasyonOnaylaLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(70, 70, 70)) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rezOnayla) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addComponent(tutarHesaplaButonu, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tutar, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(97, 97, 97)))) ); rezervasyonOnaylaLayout.setVerticalGroup( rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(odaAdi, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(odaCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(musTc, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textMusTc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(kalacakY, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textKalanY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kalacakC, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textKalanC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(girisT, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textGirisT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(2, 2, 2) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cikisT, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textCikisT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rezervasyonOnaylaLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tutarHesaplaButonu) .addComponent(tutar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(13, 13, 13))) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(kalınacakGun, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textGun, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(rezervasyonOnaylaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rezTuru, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textRezTuru, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(154, 154, 154)) .addGroup(rezervasyonOnaylaLayout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(rezOnayla, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rezervasyonOnayla, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rezervasyonOnayla, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Rezervasyon onayla butonuna basınca bilgi kaydetme metodunu çağıtıyor private void rezOnaylaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rezOnaylaActionPerformed // TODO add your handling code here: rezervasyonKaydet(); }//GEN-LAST:event_rezOnaylaActionPerformed // Girilen bilgileri veritabanında musteriKayit tablosuna kaydediyor private void rezervasyonKaydet() { // TODO add your handling code here: Item item = (Item) odaCombo.getSelectedItem(); int odaID = item.getId(); String musteriTC = (String) textMusTc.getText(); int yetiskin= Integer.parseInt(textKalanY.getText()); int cocuk = Integer.parseInt(textKalanC.getText()); String giris = (String) textGirisT.getText(); String cikis = (String) textCikisT.getText(); int gun = Integer.parseInt(textGun.getText()); String query = String.format("INSERT INTO tblMusteriKayit VALUES(%d,'%s',%d,%d,'%s','%s',%d)", odaID, musteriTC, yetiskin, cocuk, giris, cikis, gun); System.out.println(""+query); try { DBHandler dbh = new DBHandler(connectionString,"beyza","bnk"); ResultSet rs = dbh.executeQuery(query); dbh.close(); } catch (SQLException ex) { //java.util.logging.Logger.getLogger(AdminSayfasi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // TODO add your handling code here: odaDoldur(); }//GEN-LAST:event_formWindowOpened // Girilen bilgilere göre toplam tutarı hesaplayıp formattedText kutucuğuna yazdırıyor private void tutarHesaplaButonuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tutarHesaplaButonuActionPerformed // TODO add your handling code here: // ComboBoxtan odaID'yi almak için yazdık Item item = (Item) odaCombo.getSelectedItem(); int odaID = item.getId(); System.out.println("Oda ID: "+odaID); int yetiskin = Integer.parseInt(textKalanY.getText()); int cocuk = Integer.parseInt(textKalanC.getText()); int gun = Integer.parseInt(textGun.getText()); int toplamTutar = 0; int tutarYetiskin = 0; int tutarCocuk = 0; if(odaID > 100 && odaID < 111) { tutarYetiskin = gun*yetiskin*100; tutarCocuk = gun*cocuk*50; toplamTutar = tutarYetiskin + tutarCocuk; } else if(odaID > 200 && odaID < 211) { tutarYetiskin = gun*yetiskin*150; tutarCocuk = gun*cocuk*75; toplamTutar = tutarYetiskin + tutarCocuk; } else if(odaID > 300 && odaID < 308) { tutarYetiskin = gun*yetiskin*300; tutarCocuk = gun*cocuk*150; toplamTutar = tutarYetiskin + tutarCocuk; } else if(odaID > 400 && odaID < 403) { tutarYetiskin = gun*yetiskin*500; tutarCocuk = gun*cocuk*0; toplamTutar = tutarYetiskin + tutarCocuk; } else if(odaID > 500 && odaID < 502) { tutarYetiskin = gun*yetiskin*1000; tutarCocuk = gun*cocuk*500; toplamTutar = tutarYetiskin + tutarCocuk; } int tur = Integer.parseInt(textRezTuru.getText()); System.out.println("Rezervasyon Türü: "+tur); if(tur == 1) { //tutar.setColumns(toplamTutar); tutar.setValue(new Integer(toplamTutar)); } else if(tur == 2) { int top = yetiskin + cocuk; int araToplam = top*15; toplamTutar = toplamTutar + araToplam; //tutar.setColumns(toplamTutar); tutar.setValue(new Integer(toplamTutar)); } else if(tur == 3) { int top = yetiskin + cocuk; int araToplam = top*30; toplamTutar = toplamTutar + araToplam; //tutar.setColumns(toplamTutar); tutar.setValue(new Integer(toplamTutar)); } else if(tur == 4) { int top = yetiskin + cocuk; int araToplam = top*50; toplamTutar = toplamTutar + araToplam; //tutar.setColumns(toplamTutar); tutar.setValue(new Integer(toplamTutar)); } }//GEN-LAST:event_tutarHesaplaButonuActionPerformed // Boş olan odaları müşterinin seçebilmesi için ComboBoxa dolduruyor public void odaDoldur() { DBHandler dbh = null; try { String query = "SELECT odaId, odaAd FROM tblOda WHERE odaID not in (SELECT odaID FROM tblMusteriKayit)"; System.out.println(""+query); dbh = new DBHandler(connectionString,"beyza","bnk"); ResultSet rs = dbh.executeQuery(query); int count=0; Vector model = new Vector(); while(rs.next()){ model.addElement(rs.getString(1)+" "+rs.getString(2)); count++; } odaCombo.setModel(new DefaultComboBoxModel(model)); if (dbh != null) { dbh.close(); } }catch (SQLException ex) { System.out.println("catccath"+ex.getMessage()); //Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex) } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RezervasyonEkle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RezervasyonEkle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RezervasyonEkle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RezervasyonEkle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RezervasyonEkle().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel cikisT; private javax.swing.JLabel girisT; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel kalacakC; private javax.swing.JLabel kalacakY; private javax.swing.JLabel kalınacakGun; private javax.swing.JLabel musTc; private javax.swing.JLabel odaAdi; private javax.swing.JComboBox<String> odaCombo; private javax.swing.JButton rezOnayla; private javax.swing.JLabel rezTuru; private javax.swing.JTextArea rezTuruUyari; private javax.swing.JPanel rezervasyonOnayla; private javax.swing.JTextField textCikisT; private javax.swing.JTextField textGirisT; private javax.swing.JTextField textGun; private javax.swing.JTextField textKalanC; private javax.swing.JTextField textKalanY; private javax.swing.JTextField textMusTc; private javax.swing.JTextField textRezTuru; private javax.swing.JFormattedTextField tutar; private javax.swing.JButton tutarHesaplaButonu; // End of variables declaration//GEN-END:variables }
ScalablyTyped/SlinkyTyped
m/maxim_mazurok__gapi_dot_client_dot_containeranalysis/src/main/scala/typingsSlinky/maximMazurokGapiClientContaineranalysis/gapi/client/containeranalysis/Installation.scala
package typingsSlinky.maximMazurokGapiClientContaineranalysis.gapi.client.containeranalysis import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait Installation extends StObject { /** Required. All of the places within the filesystem versions of this package have been found. */ var location: js.UndefOr[js.Array[Location]] = js.native /** Output only. The name of the installed package. */ var name: js.UndefOr[String] = js.native } object Installation { @scala.inline def apply(): Installation = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[Installation] } @scala.inline implicit class InstallationMutableBuilder[Self <: Installation] (val x: Self) extends AnyVal { @scala.inline def setLocation(value: js.Array[Location]): Self = StObject.set(x, "location", value.asInstanceOf[js.Any]) @scala.inline def setLocationUndefined: Self = StObject.set(x, "location", js.undefined) @scala.inline def setLocationVarargs(value: Location*): Self = StObject.set(x, "location", js.Array(value :_*)) @scala.inline def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any]) @scala.inline def setNameUndefined: Self = StObject.set(x, "name", js.undefined) } }
osorubeki-fujita/tokyo_metro
db/seeds/tsukaisute.rb
require_relative 'add_change_to_db.rb' load 'C:/RubyPj/rails_tokyo_metro_dev/lib/tokyo_metro.rb' # db_add_train_times_of_zhmnty # seed_train_operation_info_status # db_add_train_times_of_namboku_line_meguro_and_later # db_update_to_station_info_id_of_namboku_line_train_bound_for_musashi_kosugi reset_train_type_infos_20141118_0608
5g-core/openapi
models/model_eps_iwk_pgw.go
<reponame>5g-core/openapi<filename>models/model_eps_iwk_pgw.go<gh_stars>0 /* * Nudr_DataRepository API OpenAPI file * * Unified Data Repository Service. © 2021, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * API version: 2.1.5 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package models import ( ) type EpsIwkPgw struct { // simple type PgwFqdn string `json:"pgwFqdn" yaml:"pgwFqdn" bson:"pgwFqdn" mapstructure:"PgwFqdn"` SmfInstanceId string `json:"smfInstanceId" yaml:"smfInstanceId" bson:"smfInstanceId" mapstructure:"SmfInstanceId"` }
wh6648/OperationManager
static/javascripts/performance/salaryInfo.js
<filename>static/javascripts/performance/salaryInfo.js $(function() { "use strict"; events(); render(); function events() { $("#search-btn").on("click", function(err) { var dept = $("#select-dept").find("option:selected").text(); var office = $("#select-office").find("option:selected").text(); var name = $("#select-name").find("option:selected").text(); if(dept === ' -- 请选择 -- ') { dept = ''; } if(office === ' -- 请选择 -- ') { office = ''; } if(name === ' -- 请选择 -- ') { name = ''; } filterColumn( dept, office, name );//部门,组/办,姓名 }); } function filterColumn ( t1, t2, t3) { //部门 $('#example').DataTable().column( 36 ).search( t1 ).draw(); //组/办-办事处 *** $('#example').DataTable().column( 35 ).search( t2 ).draw(); //姓名 $('#example').DataTable().column( 4 ).search( t3 ).draw(); } function render() { /** * 加载数据 */ $('#example thead th[colspan]').wrapInner( '<span/>' ).append( '&nbsp;' ); // Standard initialisation var table = $('#example').DataTable( { "iDisplayLength": 15, dom: "Cfrtip", scrollY: "600px", scrollX: true, scrollCollapse: true, paging: true, "bPaginate": true,//分页按钮 "bLengthChange": true,//每行显示记录数 "bFilter": true,//搜索栏 "bSort": false,//排序 "bInfo": true,//Showing 1 to 10 of 23 entries 总记录数没也显示多少等信息 "bAutoWidth": true, 'language': { 'emptyTable': '没有数据', 'loadingRecords': '加载中...', 'processing': '查询中...', 'search': '检索:', 'lengthMenu': '每页 _MENU_ 条', 'zeroRecords': '没有数据', 'paginate': { 'first': '第一页', 'last': '最后一页', 'next': '', 'previous': '' }, //'info': '第 _PAGE_ 页 / 总 _PAGES_ 页', 'info': '', 'infoEmpty': '没有数据', 'infoFiltered': '(过滤总件数 _MAX_ 条)' }, responsive: true, "sAjaxSource": "/performance/getEmpPerformanceForHrInfo", //指定要从哪个URL获取数据 "fnInitComplete": function(oSettings, json) { //alert("成功!"); }, "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { //用于替换默认发到服务端的请求操作 var start = 0,limit = 10,sSearch = ""; var orgId = $("#hid-user").val(); _.each(aoData, function(param) { if ("iDisplayStart" ===param.name) { start = param.value; } if ("iDisplayLength" ===param.name) { limit = param.value; } if ("sSearch" ===param.name) { sSearch = param.value; } }); oSettings.jqXHR = $.ajax( { "dataType": "json", "type": "GET", "url": sSource, "data": { keyword: sSearch, skip: start, limit: limit, orgId: orgId }, "success": function(json) { //console.log("######json:",json); var resultData = json.data; var totalItems = 0; if(json.data.length > 0){ totalItems = json.data.length; } fnCallback( { iTotalRecords: totalItems //json.data.totalItems , iTotalDisplayRecords: totalItems //json.data.totalItems , aaData: resultData }); } }); }, "columns": [ {"mData":"ROWNUM", "sDefaultContent": "","width":"20px"},//0.序号 {"mData":"CDEPT", "sDefaultContent": "","width":"20px"},//1.部门 {"mData":"CGROUP", "sDefaultContent": "","width":"20px"},//2.组/办 {"mData":"CLEI", "sDefaultContent": "","width":"20px"},//3.归属类 {"mData":"NAME", "sDefaultContent": "","width":"20px"},//4.姓名 {"mData":"RANK", "sDefaultContent": "","width":"30px"},//5.职级 {"mData":"CJBMONEY", "sDefaultContent": "","width":"20px"},//6.基本工资 {"mData":"CGWMONEY", "sDefaultContent": "","width":"60px" },//7.岗位工资 {"mData":"CXCMONEY", "sDefaultContent": "","width":"60px" },//8.现场津贴 {"mData":"COTHERFOODMONEY", "sDefaultContent": "","width":"60px" },//9.其他餐补 {"mData":"CZWMONEY", "sDefaultContent": "","width":"60px" },//10.驻外津贴 {"mData":"CDQMONEY", "sDefaultContent": "","width":"60px" },//11.地区补差 {"mData":"COTHERSUBSIDY", "sDefaultContent": "","width":"60px" },//12.其他补贴 {"mData":"CJBMONEYSUM", "sDefaultContent": "","width":"20px"},//13.基本薪资总计 {"mData":"CRANKSTANDARD", "sDefaultContent": "","width":"20px"},//14.职级/工资标准 {"mData":"CRANKSUM", "sDefaultContent": "","width":"20px"},//15.职级工资总计 {"mData":"CMONEYADD", "sDefaultContent": "","width":"20px"},//16.工资增加 {"mData":"CMONTHMONEYADD", "sDefaultContent": "","width":"20px"},//17.月收入增加 {"mData":"ENTRY_TIME", "sDefaultContent": "","width":"10px" },//18.入职日期 {"mData":"POSITIVE_TIME", "sDefaultContent": "","width":"40px" },//19.转正日期 {"mData":"REMARKS", "sDefaultContent": "","width":"40px"},//20.备注 {"mData":"DEPARTURE_TIME", "sDefaultContent": "","width":"20px"},//21.离职日期 {"mData":"PRE_AWARD", "sDefaultContent": "","width":"20px"},//22.二季度月奖金 {"mData":"PRE_AWARD", "sDefaultContent": "","width":"20px"},//23.季度合计 {"mData":{}, "sDefaultContent": "","width":"20px"},//24.月收入 {"mData":"", "sDefaultContent": "","width":"20px"},//25.奖金环比 {"mData":"", "sDefaultContent": "","width":"20px"},//26.月收入环比 {"mData":"", "sDefaultContent": "","width":"30px"},//27.三季度总额奖金 {"mData":"PROPORTION", "sDefaultContent": "","width":"20px"},//28.打分 {"mData":"SUPERIORPRO", "sDefaultContent": "","width":"60px" },//29.调整后打分 {"mData":"NOW_AWARD", "sDefaultContent": "","width":"60px"},//30.月奖金 {"mData":"NOW_AWARD", "sDefaultContent": "","width":"10px" },//31.季度合计 {"mData":{}, "sDefaultContent": "","width":"10px" },//32.月收入 {"mData":{}, "sDefaultContent": "","width":"40px" },//33.奖金环比 {"mData":{}, "sDefaultContent": "","width":"40px"},//34.月收入环比 {"mData":"OFFICE_NAME", "sDefaultContent": "","width":"40px","class":"hidden"},//35.办事处 {"mData":"COMPANY_NAME", "sDefaultContent": "","width":"40px","class":"hidden"}//36.部门 ], "columnDefs": [ { "targets": [18], "data": "入职日期", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = moment(data).format("YYYY-MM-DD"); } return aa; } }, { "targets": [19], "data": "转正日期", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = moment(data).format("YYYY-MM-DD"); } return aa; } }, { "targets": [21], "data": "离职日期", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = moment(data).format("YYYY-MM-DD"); } return aa; } }, { "targets": [22], "data": "上季度月奖金", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = parseFloat(data/3).toFixed(2); } return aa; } }, { "targets": [23], "data": "上季度奖金合计", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = data.toFixed(2); } return aa; } }, { "targets": [24], "data": "上季度月收入", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { if(data.PRE_CJBMONEYSUM === '' || data.PRE_CJBMONEYSUM === null){ data.PRE_CJBMONEYSUM = 0; } if(data.PRE_AWARD === '' || data.PRE_AWARD === null){ data.PRE_AWARD = 0; } aa = parseFloat(data.PRE_CJBMONEYSUM + (data.PRE_AWARD / 3)).toFixed(2); } return aa; } }, { "targets": [30], "data": "月奖金", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = (data / 3).toFixed(2); } return aa; } }, { "targets": [31], "data": "季度合计", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { aa = data.toFixed(2); } return aa; } }, { "targets": [32], "data": "月收入", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--' }else { if(data.CJBMONEY === '' || data.CJBMONEY === null) { data.CJBMONEY = 0; } if(data.NOW_AWARD === '' || data.NOW_AWARD === null) { data.NOW_AWARD = 0; } //基本薪资总计+月奖金 aa = parseFloat(data.CJBMONEYSUM + (data.NOW_AWARD / 3)).toFixed(2); } return aa; } }, { "targets": [33], "data": "奖金环比", "render": function (data){ var aa,bb; if (data) { if (data.PRE_AWARD != null){ if(data.PRE_AWARD != 0) { aa = ((data.NOW_AWARD / 200) * 100).toFixed(2) + '%'; }else { aa = '--'; } }else { aa = '--'; } } else { aa = '--'; } return aa; } }, { "targets": [34], "data": "月收入环比", "render": function (data){ var aa; if (data === '' || data === null) { aa = '--'; }else { //当前季度得月收入/上个季度得月收入 if(data.PRE_CJBMONEYSUM === 0 && data.PRE_AWARD === 0){ aa = '--'; } if(data.CJBMONEYSUM === '' || data.CJBMONEYSUM === null) { data.CJBMONEYSUM = 0; } if(data.NOW_AWARD === '' || data.NOW_AWARD === null) { data.NOW_AWARD = 0; } if(data.PRE_CJBMONEYSUM === '' || data.PRE_CJBMONEYSUM === null) { data.PRE_CJBMONEYSUM = 0; } if(data.PRE_AWARD === '' || data.PRE_AWARD === null) { data.PRE_AWARD = 0; } aa = parseFloat((data.CJBMONEYSUM + (data.NOW_AWARD / 3)) / (data.PRE_CJBMONEYSUM + (data.PRE_AWARD / 3)) * 100).toFixed(2)+"%"; if(data.PRE_CJBMONEYSUM === 0 && data.PRE_AWARD === 0){ aa = '--'; } } return aa; } } ] } ); new $.fn.dataTable.FixedColumns( table, { leftColumns: 6 } ); /** * 获得检索的数据 */ light.doget("/performance/getSearchTable", function(err, result) { for(var i=0;i<result[0].length;i++){ $("#select-dept").append("<option id='"+result[0][i].ID+"'>"+result[0][i].NAME+"</option>"); } for(var i=0;i<result[1].length;i++){ $("#select-office").append("<option id='"+result[1][i].ID+"'>"+result[1][i].NAME+"</option>"); } for(var i=0;i<result[2].length;i++){ $("#select-name").append("<option id='"+result[2][i].ID+"'>"+result[2][i].NAME+"</option>"); } $('#select-dept').chosen(); $('#select-office').chosen(); $('#select-name').chosen(); }); } });
ItamarLourenco/px-android
px-checkout/src/main/java/com/mercadopago/android/px/internal/viewmodel/SummaryItemType.java
package com.mercadopago.android.px.internal.viewmodel; public class SummaryItemType { public static final String PRODUCT = "product"; public static final String CHARGE = "charge"; public static final String TAXES = "taxes"; public static final String SHIPPING = "shipping"; public static final String ARREARS = "arrears"; public static final String DISCOUNT = "discount"; private SummaryItemType() { } }
tiborvass/go
misc/sortac/sortac.go
<filename>misc/sortac/sortac.go // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Sortac sorts the AUTHORS and CONTRIBUTORS files. // // Usage: // // sortac [file...] // // Sortac sorts the named files in place. // If given no arguments, it sorts standard input to standard output. package main import ( "bufio" "bytes" "flag" "fmt" "io" "io/ioutil" "log" "os" "golang.org/x/text/collate" "golang.org/x/text/language" ) func main() { log.SetFlags(0) log.SetPrefix("sortac: ") flag.Parse() args := flag.Args() if len(args) == 0 { os.Stdout.Write(sortAC(os.Stdin)) } else { for _, arg := range args { f, err := os.Open(arg) if err != nil { log.Fatal(err) } sorted := sortAC(f) f.Close() if err := ioutil.WriteFile(arg, sorted, 0644); err != nil { log.Fatal(err) } } } } func sortAC(r io.Reader) []byte { bs := bufio.NewScanner(r) var header []string var lines []string for bs.Scan() { t := bs.Text() lines = append(lines, t) if t == "# Please keep the list sorted." { header = lines lines = nil continue } } if err := bs.Err(); err != nil { log.Fatal(err) } var out bytes.Buffer c := collate.New(language.Und, collate.Loose) c.SortStrings(lines) for _, l := range header { fmt.Fprintln(&out, l) } for _, l := range lines { fmt.Fprintln(&out, l) } return out.Bytes() }
ZPhilo/pybricks-micropython
pybricks/parameters/pb_type_direction.c
<gh_stars>100-1000 // SPDX-License-Identifier: MIT // Copyright (c) 2018-2020 The Pybricks Authors #include "py/mpconfig.h" #if PYBRICKS_PY_PARAMETERS #include <pbio/dcmotor.h> #include <pybricks/parameters.h> #include <pybricks/util_mp/pb_type_enum.h> const pb_obj_enum_member_t pb_Direction_CLOCKWISE_obj = { {&pb_enum_type_Direction}, .name = MP_QSTR_CLOCKWISE, .value = PBIO_DIRECTION_CLOCKWISE }; const pb_obj_enum_member_t pb_Direction_COUNTERCLOCKWISE_obj = { {&pb_enum_type_Direction}, .name = MP_QSTR_COUNTERCLOCKWISE, .value = PBIO_DIRECTION_COUNTERCLOCKWISE }; STATIC const mp_rom_map_elem_t pb_enum_Direction_table[] = { { MP_ROM_QSTR(MP_QSTR_CLOCKWISE), MP_ROM_PTR(&pb_Direction_CLOCKWISE_obj) }, { MP_ROM_QSTR(MP_QSTR_COUNTERCLOCKWISE), MP_ROM_PTR(&pb_Direction_COUNTERCLOCKWISE_obj) }, }; STATIC MP_DEFINE_CONST_DICT(pb_enum_type_Direction_locals_dict, pb_enum_Direction_table); const mp_obj_type_t pb_enum_type_Direction = { { &mp_type_type }, .name = MP_QSTR_Direction, .print = pb_type_enum_print, .unary_op = mp_generic_unary_op, .locals_dict = (mp_obj_dict_t *)&(pb_enum_type_Direction_locals_dict), }; #endif // PYBRICKS_PY_PARAMETERS
SherryLGT/CZ3003-BTOFindr
app/src/main/java/com/btofindr/model/NavDrawerItem.java
<reponame>SherryLGT/CZ3003-BTOFindr package com.btofindr.model; /** * This describes a navigation drawer item. * * @author <NAME> <NAME> * @version 1.0 * @since 31/08/2016 */ public class NavDrawerItem { private int icon; private String title; public NavDrawerItem(){}; public NavDrawerItem(int icon, String title){ this.icon = icon; this.title = title; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
ntduy96/book-rental-system
src/main/java/com/chothuesach/repository/NhanVienRepository.java
<filename>src/main/java/com/chothuesach/repository/NhanVienRepository.java<gh_stars>0 package com.chothuesach.repository; import com.chothuesach.model.ChucVu; import com.chothuesach.model.NhanVien; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; @Repository public interface NhanVienRepository extends CrudRepository<NhanVien, String> { List<NhanVien> getAllByOrderByHoTenNguoiDung(); List<NhanVien> getAllByChucVu(ChucVu chucVu); Optional<NhanVien> getByTenNguoiDung(String tenNguoiDung); @Modifying @Query("DELETE FROM NhanVien WHERE MA_NHAN_VIEN = ?1") @Transactional void deleteNhanVienByMaNguoiDung(String maNguoiDung); }
JiangYongKang/NewStock-iOS
NewStock/View/GoodStockView/ZNXGView.h
<filename>NewStock/View/GoodStockView/ZNXGView.h // // ZNXGView.h // NewStock // // Created by 王迪 on 2017/3/9. // Copyright © 2017年 Willey. All rights reserved. // #import <UIKit/UIKit.h> #import "TaoIndexModel.h" @interface ZNXGView : UIView @property (nonatomic, strong) TaoIndexModelList *model; @property (nonatomic, copy) void(^urlBlock)(NSString *); @property (nonatomic, copy) void(^pushBlcok)(TaoIndexModelClildStock *); @end
lborgav/Historical-Source-Codes
Microsoft Word for Windows Version 1.1a/Word 1.1a CHM Distribution/Opus/fedt.h
#ifndef RC_INVOKED /*---------------------------------------------------------------------------- | FEDT structure | | Data structure defining a FEDT formula edit control. | | Fields: | hwnd window handle of the fedt control. | hdc device context for the window. | fSingleLine single line editcontrol | fPointSel if control supports point mode | fOverType text is inserted in over-type mode | fMacCaret Caret is at mac end-point of the selection | fShowSel selection is currently visible, and the | caret is blinking | fCaretOn caret has been created for this window | fTypingUndo typing undo is being created | fBadBrks ran out of memory trying to allocate line | break array | cchText number of characters in the text | hszText text in the fedt control | ichMicSel start of current selection | ichMacSel end of current selection | liCaret line the caret is on | ptCaret position of the blinking caret | hrgnSel region describing the inverted part of the | current selection | rcFmt formatting rectangle | pfnNextBrk routine to find next word break position | pfnPrevBrk routine to find previous word break position | liMac number of lines of text displayed in the | control | liMax size of mpliichBrk array | ichBrk0 dummy line break position for 0th line | mpliichBrk line break array ----------------------------------------------------------------------------*/ #ifdef CC #define SEL2 sel2 #define UNSEL unsel #else #define SEL2 #define UNSEL #endif typedef struct _fedtsel { BYTE liCaret; BYTE fMacCaret; int rgichSel[2]; } FEDTSEL; typedef struct _fedt { HWND hwnd; HWND hwndParent; HDC hdc; unsigned fSingleLine:1, fPointSel:1, fOverType:1, fShowSel:1, fCaretOn:1, :1, fBadBrks:1, :4, fCombo:1, unused1:4; /* text in the control */ int cchText; char **hszText; /* selection position */ union { struct { BYTE liCaret; BYTE fMacCaret; int ichMicSel; int ichMacSel; } SEL2; FEDTSEL sel; } UNSEL; /* selection as shown on physical display */ struct PT ptCaret; HRGN hrgnSel; /* formatting area */ struct RC rcFmt; struct RC rcView; /* line breaks */ BYTE liMac; BYTE liMax; int ichBrk0; /* WARNING!! - must preceed mpliichBrk */ int mpliichBrk[1]; } FEDT; #define CbFedt(liMac) (sizeof(FEDT)-sizeof(int)+(liMac)*sizeof(int)) #define HfedtFromHwnd(hwnd) ((FEDT **)GetWindowWord(hwnd, 0)) #define HwndListBoxFromFedt(hfedt) ((HWND)GetWindowWord((*hfedt)->hwndParent,IDWHLBOX)) #define PchFromHsz(hsz) ((char *)(*(hsz))) /* Fedt notification codes - MUST BE COMPATIBLE WITH WINDOWS EDIT CONTROL EN_* NOTIFICATION CODES!! */ #define FN_SETFOCUS 0x0100 #define FN_KILLFOCUS 0x0200 #define FN_CHANGE 0x0300 /* out of memory notification codes */ #define FN_ERRSPACE 0x0500 #define FN_OOMTEXT 0x00 #define FN_OOMLINEBRKS 0x01 #define FN_OOMCOPY 0x02 /* return values from FN_ERRSPACE */ #define FN_OOMALERT 0x00 #define FN_OOMABORT 0x01 #define FN_OOMRETRY 0x02 #define FN_OOMIGNORE 0x03 /* miscellaneous notification codes */ #define FN_VERIFYREPLACE 0x0700 #endif /* RC_INVOKED */ /* Fedt control styles in CreateWindow call */ #define FS_MULTILINE 0x0004L /* extra space in window */ #define CBWEFEDT sizeof(char **)
UCL/EIDP-4
eidpauth/src/test/java/uk/ac/ucl/eidp/auth/model/UsereNgTest.java
<filename>eidpauth/src/test/java/uk/ac/ucl/eidp/auth/model/UsereNgTest.java package uk.ac.ucl.eidp.auth.model; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.HashSet; import java.util.Set; /** * Unit tests for UserE. * @author rebmdgu */ public class UsereNgTest { private UserE instance = new UserE(); private final Set<RoleE> roles = new HashSet<>(); private final String[] rolenames = { "user", "admin", "root" }; /** * Empty constructor. */ public UsereNgTest() { for (String role : rolenames) { roles.add(createRole(role)); } instance = resetUserE(instance); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { } @AfterMethod public void tearDownMethod() throws Exception { instance = resetUserE(instance); } /** * Test of getId method, of class UserE. */ @Test public void testGetId() { System.out.println("getId"); Long expResult = Long.MIN_VALUE; Long result = instance.getId(); assertEquals(result, expResult); } /** * Test of setId method, of class UserE. */ @Test public void testSetId() { System.out.println("setId"); Long id = Long.MAX_VALUE; instance.setId(id); assertEquals(instance.getId(), id); } /** * Test of getRoles method, of class UserE. */ @Test public void testGetRoles() { System.out.println("getRoles"); Set expResult = roles; Set result = instance.getRoles(); assertEquals(result, expResult); } /** * Test of setRoles method, of class UserE. */ @Test public void testSetRoles() { System.out.println("setRoles"); instance.setRoles(null); assertNull(instance.getRoles()); } /** * Test of getToken method, of class UserE. */ @Test public void testGetToken() { System.out.println("getToken"); String expResult = "thetoken"; String result = instance.getToken(); assertEquals(result, expResult); } /** * Test of setToken method, of class UserE. */ @Test public void testSetToken() { System.out.println("setToken"); String token = "<PASSWORD>"; instance.setToken(token); assertEquals(instance.getToken(), token); } /** * Test of hashCode method, of class UserE. */ @Test public void testHashCode() { System.out.println("hashCode"); Long id = Long.MIN_VALUE; int expResult = id.hashCode(); int result = instance.hashCode(); assertEquals(result, expResult); } /** * Test of equals method, of class UserE. * Must have same id. */ @Test public void testEquals() { System.out.println("equals"); UserE object = new UserE(); object.setId(Long.MIN_VALUE); boolean expResult = true; boolean result = instance.equals(object); assertEquals(result, expResult); } /** * Test of toString method, of class UserE. */ @Test public void testToString() { System.out.println("toString"); String expResult = "uk.ac.ucl.eidp.auth.model.UserE[ id=-9223372036854775808 ]"; String result = instance.toString(); assertEquals(result, expResult); } private UserE resetUserE(UserE userE) { if (null != userE) { userE.setId(Long.MIN_VALUE); userE.setToken("thetoken"); userE.setRoles(roles); } return userE; } private RoleE createRole(String rolename) { RoleE role = mock(RoleE.class); when(role.getRoleName()).thenReturn(rolename); return role; } }
zyz610650/beanbox
beanbox-core/src/main/java/com/beanbox/event/ContextRefreshedEvent.java
<filename>beanbox-core/src/main/java/com/beanbox/event/ContextRefreshedEvent.java<gh_stars>1-10 package com.beanbox.event; /** * @author: @zyz */ public class ContextRefreshedEvent extends ApplicationContextEvent{ public ContextRefreshedEvent (Object source) { super (source); } }
bcl-lab-pub/PCM-App
SMART Genome Precision Cancer Medicine/FHIRGroup.h
<filename>SMART Genome Precision Cancer Medicine/FHIRGroup.h<gh_stars>1-10 /* Copyright (c) 2011-2013, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Generated on Fri, May 9, 2014 11:14+1000 for FHIR v0.0.81 */ /* * Group of multiple entities * * [FhirResource("Group")] * [Serializable] */ #import "FHIRBaseResource.h" @class FHIRIdentifier; @class FHIRCode; @class FHIRBoolean; @class FHIRCodeableConcept; @class FHIRString; @class FHIRInteger; @class FHIRGroupCharacteristicComponent; @class FHIRResource; @interface FHIRGroup : FHIRBaseResource /* * Types of resources that are part of group */ typedef enum { kGroupTypePerson, // Group contains "person" Patient resources. kGroupTypeAnimal, // Group contains "animal" Patient resources. kGroupTypePractitioner, // Group contains healthcare practitioner resources. kGroupTypeDevice, // Group contains Device resources. kGroupTypeMedication, // Group contains Medication resources. kGroupTypeSubstance, // Group contains Substance resources. } kGroupType; /* * Unique id */ @property (nonatomic, strong) FHIRIdentifier *identifier; /* * person | animal | practitioner | device | medication | substance */ @property (nonatomic, strong) FHIRCode/*<code>*/ *typeElement; @property (nonatomic) kGroupType type; /* * Descriptive or actual */ @property (nonatomic, strong) FHIRBoolean *actualElement; @property (nonatomic, strong) NSNumber *actual; /* * Kind of Group members */ @property (nonatomic, strong) FHIRCodeableConcept *code; /* * Label for Group */ @property (nonatomic, strong) FHIRString *nameElement; @property (nonatomic, strong) NSString *name; /* * Number of members */ @property (nonatomic, strong) FHIRInteger *quantityElement; @property (nonatomic, strong) NSNumber *quantity; /* * Trait of group members */ @property (nonatomic, strong) NSArray/*<GroupCharacteristicComponent>*/ *characteristic; /* * Who is in group */ @property (nonatomic, strong) NSArray/*<ResourceReference>*/ *member; - (FHIRErrorList *)validate; @end
firgaty/Uni
POO/TP/TP3/Joueur.java
import java.util.Scanner; public class Joueur { private String nom; private Scanner scan; public Joueur(){ //Par défaut, le nom du joueur est "Anonyme". Le constructeur initialise un scan qui pourra vous être utile. this.scan = new Scanner(System.in); this.nom = "Anonyme"; } public void setNom() { System.out.println("Entrez nouveau nom:"); this.nom = scan.next(); } public String getNom() { return this.nom; } public int nombreChoisi() { System.out.println("Entrez un nombre : "); while(!scan.hasNextInt()) { scan.next(); System.out.println("Entrez un VRAI nombre (Entier qui plus est)."); } return scan.nextInt(); } public boolean ouiNon() { do { System.out.println("Oui/Non (o/n) :"); String in = scan.next(); switch(in) { case "oui" : return true; case "Oui" : return true; case "o" : return true; case "O" : return true; case "non" : return false; case "Non" : return false; case "n" : return false; case "N" : return false; } System.out.println("Non valide... (u.u) Recommencez (et suivez les intructions)."); } while (true); } public int[] actionChoisie() { int[] out = new int[3]; doLoop: do { System.out.println("Choisisser une action (x y action) (int int int) :"); String in = scan.nextLine(); String[] nb = in.split(" "); for(int i = 0; i < 3; i++) { if(!isInteger(nb[i])) { System.out.println("Veuille respecter le format, que des entiers."); continue doLoop; } out[i] = Integer.parseInt(nb[i]); } break; } while (true); return out; } private boolean isInteger(String s) { try { Integer.parseInt(s); } catch(NumberFormatException e) { return false; } catch(NullPointerException e) { return false; } return true; } }
rpatil524/dmptool
db/migrate/20140214155629_dmptemplates_guidance_groups.rb
<filename>db/migrate/20140214155629_dmptemplates_guidance_groups.rb class DmptemplatesGuidanceGroups < ActiveRecord::Migration[4.2] def change create_table :dmptemplates_guidance_groups, :id => false do |t| t.integer :dmptemplate_id t.integer :guidance_group_id end end end
zyndor/xrhodes
xr3core/h/xr/strings/StringProxy.hpp
<filename>xr3core/h/xr/strings/StringProxy.hpp #ifndef XR_STRINGPROXY_HPP #define XR_STRINGPROXY_HPP //============================================================================== // // XRhodes // // copyright (c) <NAME>. All rights reserved. // // License: https://github.com/zyndor/xrhodes#License-bsd-2-clause // //============================================================================== #include <cstring> namespace xr { //============================================================================== ///@brief StringProxy offers capability to reference a const char buffer /// without having to allocate memory and copy contents, until absolutely /// needed -- when the StringProxy object itself is copied. class [[deprecated("Use std::string_view.")]] StringProxy { public: // structors StringProxy() : m_data(nullptr), m_isOwned(false) {} StringProxy(char const* d, bool copy = false) : m_data(d), m_isOwned(false) { if (copy) { CopyInternal(d); } } StringProxy(StringProxy const& rhs) : m_data(nullptr), m_isOwned(false) { CopyInternal(rhs.m_data); } StringProxy(StringProxy&& rhs) : m_data(rhs.m_data), m_isOwned(rhs.m_isOwned) { rhs.m_isOwned = false; } ~StringProxy() { Destroy(); } // general void Destroy() { if (m_isOwned) { delete[] m_data; m_data = nullptr; m_isOwned = false; } } // operator overloads operator char const*() const { return m_data; } StringProxy& operator=(StringProxy const& rhs) { if (rhs.m_data != m_data) { Destroy(); if (rhs.m_data) { CopyInternal(rhs.m_data); } } return *this; } StringProxy& operator=(char const* d) { // Dubious why anyone would want to do this, but in case of // assigning its own buffer, do nothing. We do not want to make // a deep copy at this point, so we have to do this. if (d != m_data) { Destroy(); // clean up previous buffer m_data = d; // assign, but don't own buffer. } return *this; } // overloads bool operator<(StringProxy const& rhs) const { return strcmp(m_data, rhs.m_data) < 0; } private: // data char const* m_data; bool m_isOwned; // internal void CopyInternal(char const* d) { size_t len = strlen(d); char* buffer = new char[len + 1]; // null terminator memcpy(buffer, d, len); buffer[len] = '\0'; m_data = buffer; m_isOwned = true; } }; } // xr #endif //XR_STRINGPROXY_HPP
patil215/v8
fuzzer_output/interesting/sample_1554114886349.js
function main() { const v4 = [13.37,13.37,13.37,13.37]; const v6 = [1337,1337]; const v8 = (2147483647)[1337]; function v9(v10,v11) { 'use strict' let v12 = v9; return v12; } const v14 = [13.37,13.37,13.37,13.37]; function v16(v17,v18,v19,v20) { for (let v24 = 0; v24 < 100; v24++) { const v28 = (1337)[1337]; let v29 = 0; if (0) { const v30 = v28[-301963087]; v29 = v30; } else { const v31 = 0 - 1; v29 = v19; } for (let v32 = 0; v32 < 1337; v32++) { } const v34 = [1337]; const v35 = [v34]; } } const v38 = v16(1337,10,1337,"object",v14); const v39 = []; const v40 = {charAt:13.37,isFinite:1337,b:Map,toPrimitive:v6}; const v41 = {getUint32:"Z6HVy*PuQW"}; let v42 = 2147483647; function v43(v44,v45,v46,v47) { let v50 = 0; const v51 = v46 / v45; const v52 = v50 + 1; v50 = v52; const v55 = [1337]; const v56 = {}; const v57 = [v56,v56]; for (const v58 in v50) { let v61 = 0; while (v61 < 0) { v57.setInt8 = v38; const v62 = v61 + 1; v61 = v62; } } let v63 = "undefined"; const v65 = [1337]; const v66 = typeof v14; const v68 = v66 === "object"; v65.length = 2; for (const v70 of v55) { v63 = v70; } const v75 = [1337]; const v76 = [v75]; let v78 = "undefined"; const v80 = [1337]; const v82 = v63[1000]; let v85 = 0; const v86 = v85 + 1; v85 = v86; return v39; } let v89 = v41; if (10) { const v90 = v4 && v89; v89 = v90; } else { const v92 = [13.37,13.37,13.37,13.37,13.37]; v89 = v92; } const v96 = [1337]; for (let v100 = 0; v100 < 100; v100++) { const v101 = v43(10,Function,1337,v96,Function); } } %NeverOptimizeFunction(main); main();
enioka/enioka_scan
enioka_scan/src/main/java/com/enioka/scanner/bt/manager/classicserial/ClassicBtSppScanner.java
<reponame>enioka/enioka_scan<filename>enioka_scan/src/main/java/com/enioka/scanner/bt/manager/classicserial/ClassicBtSppScanner.java package com.enioka.scanner.bt.manager.classicserial; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.enioka.scanner.api.callbacks.ScannerStatusCallback; import com.enioka.scanner.api.proxies.ScannerStatusCallbackProxy; import com.enioka.scanner.bt.api.BtSppScannerProvider; import com.enioka.scanner.bt.api.Command; import com.enioka.scanner.bt.api.DataSubscriptionCallback; import com.enioka.scanner.bt.api.ParsingResult; import com.enioka.scanner.bt.api.ScannerDataParser; import com.enioka.scanner.bt.manager.SerialBtScannerProvider; import com.enioka.scanner.bt.manager.common.BluetoothScannerInternal; import com.enioka.scanner.bt.manager.common.DataSubscription; import com.enioka.scanner.bt.manager.common.OnConnectedCallback; import com.enioka.scanner.bt.manager.common.SerialBtScannerPassiveConnectionManager; import com.enioka.scanner.sdk.zebraoss.SsiOverSppParser; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; /** * Internal class used as the main interaction entry point for bluetooth devices. * It handles all connection/reconnection boilerplate and delegates level 7 stuff to a {@link ScannerDataParser}. */ public class ClassicBtSppScanner implements Closeable, BluetoothScannerInternal { private static final String LOG_TAG = "BtSppSdk"; private static final int RECONNECTION_MAX_ATTEMPTS = 5; private static final int RECONNECTION_INTERVAL_MS = 1000; private static final int RECONNECTION_TIMEOUT_MS = 5000; private final SerialBtScannerPassiveConnectionManager parentProvider; private BtSppScannerProvider scannerDriver; private final BluetoothDevice rawDevice; private ClassicBtConnectToDeviceThread connectionThread; private Timer timeoutHunter; private final String name; private boolean masterBtDevice = false; private int connectionFailures = 0; private BluetoothSocket clientSocket; private ClassicBtSocketStreamReader inputStreamReader; private ClassicBtSocketStreamWriter outputStreamWriter; private ScannerDataParser inputHandler; private ScannerStatusCallbackProxy statusCallback; private final Handler uiHandler = new Handler(Looper.getMainLooper()); /** * All the callbacks which are registered to run on received data (post-parsing). Key is data class name. */ private final Map<String, DataSubscription> dataSubscriptions = new HashMap<>(); /** * Create an <strong>unconnected</strong> device from a cached device definition.<br> * Need to call {@link #connect(OnConnectedCallback)} before any interaction with the device.<br> * Used for slave BT devices. * * @param device a device definition */ public ClassicBtSppScanner(SerialBtScannerPassiveConnectionManager parentProvider, BluetoothDevice device) { this.rawDevice = device; this.parentProvider = parentProvider; this.name = this.rawDevice.getName(); this.inputHandler = new SsiOverSppParser(); this.setUpTimeoutTimer(); } /** * Create a <strong>connected</strong> device from an already open bluetooth socket.<br> * Used for master BT devices. * * @param socket a socket to a bluetooth device. */ ClassicBtSppScanner(SerialBtScannerProvider parentProvider, BluetoothSocket socket) { this.rawDevice = socket.getRemoteDevice(); this.parentProvider = parentProvider; this.name = this.rawDevice.getName(); this.inputHandler = new SsiOverSppParser(); this.masterBtDevice = true; this.clientSocket = socket; this.connectStreams(); this.setUpTimeoutTimer(); Log.i(LOG_TAG, "Device " + ClassicBtSppScanner.this.name + " reports it is connected"); } /** * Start a timer which checks if data subscribers are timed-out and deals with the consequences. */ private void setUpTimeoutTimer() { this.timeoutHunter = new Timer(); this.timeoutHunter.schedule(new TimerTask() { @Override public void run() { synchronized (dataSubscriptions) { List<String> toRemove = new ArrayList<>(0); for (Map.Entry<String, DataSubscription> entry : dataSubscriptions.entrySet()) { DataSubscription subscription = entry.getValue(); String expectedDataClass = entry.getKey(); if (subscription.isTimedOut()) { Log.d(LOG_TAG, "A data subscription has timed out"); toRemove.add(expectedDataClass); subscription.getCallback().onTimeout(); outputStreamWriter.endOfCommand(); } } for (String key : toRemove) { dataSubscriptions.remove(key); } } } }, 0, 100); } @Override public void setProvider(BtSppScannerProvider provider) { this.scannerDriver = provider; this.inputHandler = scannerDriver.getInputHandler(); } @Override public void connect(final OnConnectedCallback callback) { Log.i(LOG_TAG, "Starting connection to device " + ClassicBtSppScanner.this.name); connectionThread = new ClassicBtConnectToDeviceThread(rawDevice, new OnStreamConnectedCallback() { @Override public void connected(BluetoothSocket bluetoothSocket) { ClassicBtSppScanner.this.connectionThread = null; Log.i(LOG_TAG, "Device " + ClassicBtSppScanner.this.name + " reports it is connected"); ClassicBtSppScanner.this.clientSocket = bluetoothSocket; connectStreams(); if (callback != null) { callback.connected(ClassicBtSppScanner.this); } } @Override public void failed() { if (callback != null) { callback.failed(); } } }); connectionThread.start(); } @Override public void disconnect() { this.close(); } private void connectStreams() { if (this.clientSocket == null) { return; } try { this.inputStreamReader = new ClassicBtSocketStreamReader(this.clientSocket.getInputStream(), this); this.inputStreamReader.start(); this.outputStreamWriter = new ClassicBtSocketStreamWriter(this.clientSocket.getOutputStream(), this); } catch (IOException e) { e.printStackTrace(); } } @Override public void close() { if (this.connectionThread != null) { this.connectionThread.cancel(); this.connectionThread = null; } this.closeStreams(); if (this.timeoutHunter != null) { this.timeoutHunter.cancel(); this.timeoutHunter = null; } } private void closeStreams() { if (this.inputStreamReader != null) { try { this.inputStreamReader.close(); } catch (IOException e) { Log.e(LOG_TAG, "Could not close reader", e); } } if (this.outputStreamWriter != null) { try { this.outputStreamWriter.close(); } catch (IOException e) { Log.e(LOG_TAG, "Could not close writer", e); } } if (this.clientSocket != null) { try { this.clientSocket.close(); } catch (IOException e) { Log.e(LOG_TAG, "Could not close socket", e); } } } void onConnectionFailure() { Log.w(LOG_TAG, "A connection to an SPP BT device was lost"); this.closeStreams(); if (this.masterBtDevice) { Log.w(LOG_TAG, "Reconnection will not be attempted as it was a master device - the device itself should reconnect."); this.parentProvider.resetListener(BluetoothAdapter.getDefaultAdapter()); if (statusCallback != null) { statusCallback.onStatusChanged(null, ScannerStatusCallback.Status.FAILURE); } return; } Log.w(LOG_TAG, "This is a slave device, attempting reconnection"); if (statusCallback != null) { statusCallback.onStatusChanged(null, ScannerStatusCallback.Status.RECONNECTING); } // We choose to disable master connection if socket is still open - that way devices which are both master and slave will not reconnect the "wrong" way. this.parentProvider.stopMasterListener(); // Go for reconnection loop. this.reconnect(); } private void reconnect() { if (clientSocket != null && clientSocket.isConnected()) { Log.w(LOG_TAG, "Reconnection failed: device is already connected"); return; } Log.w(LOG_TAG, "Reconnection attempt " + (this.connectionFailures + 1) + " out of " + RECONNECTION_MAX_ATTEMPTS); // Always sleeps first (and not only in case of failure) as sockets take time to close for small ring scanners. try { Thread.sleep(RECONNECTION_INTERVAL_MS); // Allowed: we are in a dedicated thread which has nothing to do anyway. } catch (InterruptedException e) { // Ignore. } connectionThread = new ClassicBtConnectToDeviceThread(rawDevice, new OnStreamConnectedCallback() { @Override public void connected(BluetoothSocket bluetoothSocket) { ClassicBtSppScanner.this.connectionThread = null; Log.i(LOG_TAG, "Device " + ClassicBtSppScanner.this.name + " reports it has reconnected"); ClassicBtSppScanner.this.connectionFailures = 0; ClassicBtSppScanner.this.clientSocket = bluetoothSocket; connectStreams(); if (ClassicBtSppScanner.this.statusCallback != null) { ClassicBtSppScanner.this.statusCallback.onStatusChanged(null, ScannerStatusCallback.Status.CONNECTED); } } @Override public void failed() { ClassicBtSppScanner.this.connectionFailures++; if (ClassicBtSppScanner.this.connectionFailures < ClassicBtSppScanner.RECONNECTION_MAX_ATTEMPTS) { ClassicBtSppScanner.this.reconnect(); } else { Log.w(LOG_TAG, "Giving up on dead scanner " + ClassicBtSppScanner.this.name); if (ClassicBtSppScanner.this.statusCallback != null) { ClassicBtSppScanner.this.statusCallback.onStatusChanged(null, ScannerStatusCallback.Status.FAILURE); } } } }); connectionThread.start(); // Handling reconnection timeout new Timer().schedule(new TimerTask() { @Override public void run() { if (ClassicBtSppScanner.this.connectionThread != null) { ClassicBtSppScanner.this.connectionThread.timeout(); } } }, RECONNECTION_TIMEOUT_MS); } @Override public String getName() { return this.name; } @Override public <T> void runCommand(final Command<T> command, final DataSubscriptionCallback<T> subscription) { byte[] cmd = command.getCommand(this); if (subscription != null) { synchronized (dataSubscriptions) { String expectedDataClass = command.getReturnType().getCanonicalName(); this.dataSubscriptions.put(expectedDataClass, new DataSubscription(subscription, command.getTimeOut(), false)); } } else { // Nothing is expected in return, so no need to wait before running the next command. this.outputStreamWriter.endOfCommand(); } Log.d(LOG_TAG, "Queuing for dispatch command " + command.getClass().getSimpleName()); this.outputStreamWriter.write(cmd); } public <T> void registerSubscription(final DataSubscriptionCallback<T> subscription, final Class<? extends T> targetType) { if (subscription != null) { synchronized (dataSubscriptions) { String expectedDataClass = targetType.getCanonicalName(); this.dataSubscriptions.put(expectedDataClass, new DataSubscription(subscription, 0, true)); } } } @Override public void registerStatusCallback(final ScannerStatusCallbackProxy statusCallback) { this.statusCallback = statusCallback; } @Override public boolean isBleDevice() { return false; } void handleInputBuffer(byte[] buffer, int offset, int length) { int read = offset; while (read < length) { read += handleInputBufferLoop(buffer, read, length); if (read < length) { Log.d(LOG_TAG, "The buffer contains multiple tokens - a loop will happen starting at position " + read + " until " + length); } } } private int handleInputBufferLoop(byte[] buffer, int offset, int length) { ParsingResult res = this.inputHandler.parse(buffer, offset, length); if (length > 0 && res.read == 0) { Log.w(LOG_TAG, "The buffer is abandoned as the parser did not read any byte on the latest loop"); this.outputStreamWriter.endOfCommand(); if (res.acknowledger != null) { this.outputStreamWriter.write(res.acknowledger.getCommand(this), true); } return length; } if (!res.expectingMoreData && res.data != null) { Log.d(LOG_TAG, "Data was interpreted as: " + res.data.toString()); // ACK first - the event handlers may write to stream and create out of order ACKs. if (res.acknowledger != null) { this.outputStreamWriter.endOfCommand(); this.outputStreamWriter.write(res.acknowledger.getCommand(this), true); } // Subscriptions to fulfill on that data type? synchronized (dataSubscriptions) { if (this.dataSubscriptions.containsKey(res.data.getClass().getCanonicalName())) { DataSubscription subscription = this.dataSubscriptions.get(res.data.getClass().getCanonicalName()); // Remove callback before calling it - that way callbacks can re-subscribe at once. if (!subscription.isPermanent()) { this.dataSubscriptions.remove(res.data.getClass().getCanonicalName()); } DataSubscriptionCallback callback = subscription.getCallback(); callback.onSuccess(res.data); } } this.outputStreamWriter.endOfCommand(); } else if (!res.expectingMoreData && !res.rejected) { Log.d(LOG_TAG, "Message was interpreted as: message without additional data"); if (res.acknowledger != null) { this.outputStreamWriter.write(res.acknowledger.getCommand(this), true); } this.outputStreamWriter.endOfCommand(); } else if (!res.expectingMoreData && res.rejected) { Log.d(LOG_TAG, "Message was rejected " + res.result); if (res.acknowledger != null) { this.outputStreamWriter.write(res.acknowledger.getCommand(this), true); } this.outputStreamWriter.endOfCommand(); } else { Log.d(LOG_TAG, "Data was not interpreted yet as we are expecting more data"); if (res.acknowledger != null) { this.outputStreamWriter.write(res.acknowledger.getCommand(this), true); } } return res.read; } }
z8g/app
wmdblog1.0/src/main/java/net/zhaoxuyang/blog/function/PrintTime.java
/* __ ____ __ ____ ____ _ ___ ____ \ \ / / \/ | _ \ | __ )| | / _ \ / ___| \ \ /\ / /| |\/| | | | | | _ \| | | | | | | _ \ V V / | | | | |_| | | |_) | |__| |_| | |_| | \_/\_/ |_| |_|____/ |____/|_____\___/ \____| */ package net.zhaoxuyang.blog.function; import java.lang.invoke.MethodHandles; import org.beetl.core.Context; import org.beetl.core.Function; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PrintTime implements Function { final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public String call(Object[] objects, Context context) { LOG.info("String call"); LOG.info("objects=" + Arrays.toString(objects)); LOG.info("context=" + context); Date date = (Date) objects[0]; Date now = new Date(); Long fiveM = date.getTime() + (5*60*1000); Long thM = date.getTime() + (30*60*1000); Long oneH = date.getTime() + (60*60*1000); if(now.getTime() < fiveM){ return "刚刚"; } if(now.getTime() < thM){ return "半小时前"; } if(now.getTime() < oneH){ return "一小时前"; } SimpleDateFormat sdf = new SimpleDateFormat(objects[1].toString()); return sdf.format(date); } }
joshsalverda/polyfill-library
polyfills/String/prototype/codePointAt/tests.js
<reponame>joshsalverda/polyfill-library /* globals proclaim */ it('is a function', function () { proclaim.isFunction(String.prototype.codePointAt); }); it('has correct arity', function () { proclaim.arity(String.prototype.codePointAt, 1); }); it('has correct name', function () { proclaim.hasName(String.prototype.codePointAt, 'codePointAt'); }); it('is not enumerable', function () { proclaim.isNotEnumerable(String.prototype, 'codePointAt'); }); var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { enumerable: false, value: obj }); for (var _ in obj) { return false; } return obj.x === obj; } catch (e) { // this is IE 8. return false; } }; var ifSupportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported() ? it : xit; // Tests ported from https://github.com/es-shims/es6-shim/blob/master/test/string.js#L496-L541 var hasStrictMode = (function () { return this === null; }).call(null); var ifHasStrictModeIt = hasStrictMode ? it : it.skip; describe('#codePointAt()', function () { it('is a function', function () { proclaim.isFunction(String.prototype.codePointAt); }); ifSupportsDescriptors('is not enumerable', function () { proclaim.isFalse(Object.prototype.propertyIsEnumerable.call(String.prototype.codePointAt)); }); it('has the right arity', function () { proclaim.strictEqual(String.prototype.codePointAt.length, 1); }); ifHasStrictModeIt('should throw a TypeError when called on null or undefined', function () { proclaim["throws"](function () { String.prototype.codePointAt.call(undefined); }, TypeError); proclaim["throws"](function () { String.prototype.codePointAt.call(null); }, TypeError); proclaim["throws"](function () { String.prototype.codePointAt.apply(undefined); }, TypeError); proclaim["throws"](function () { String.prototype.codePointAt.apply(null); }, TypeError); }); it('should work', function () { var str = 'abc'; proclaim.strictEqual(str.codePointAt(0), 97); proclaim.strictEqual(str.codePointAt(1), 98); proclaim.strictEqual(str.codePointAt(2), 99); }); it('should work with unicode', function () { proclaim.strictEqual('\u2500'.codePointAt(0), 0x2500); proclaim.strictEqual('\ud800\udc00'.codePointAt(0), 0x10000); proclaim.strictEqual('\udbff\udfff'.codePointAt(0), 0x10ffff); proclaim.strictEqual('\ud800\udc00\udbff\udfff'.codePointAt(0), 0x10000); proclaim.strictEqual('\ud800\udc00\udbff\udfff'.codePointAt(1), 0xdc00); proclaim.strictEqual('\ud800\udc00\udbff\udfff'.codePointAt(2), 0x10ffff); proclaim.strictEqual('\ud800\udc00\udbff\udfff'.codePointAt(3), 0xdfff); }); it('should return undefined when pos is negative or too large', function () { var str = 'abc'; proclaim.isUndefined(str.codePointAt(-1)); proclaim.isUndefined(str.codePointAt(str.length)); }); }); it('works as expected', function () { proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(''), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt('_'), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(-Infinity), undefined); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(-1), undefined); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(-0), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(0), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(3), 0x1D306); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(4), 0xDF06); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(5), 0x64); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(42), undefined); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(Infinity), undefined); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(Infinity), undefined); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(NaN), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(false), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(null), 0x61); proclaim.strictEqual('abc\uD834\uDF06def'.codePointAt(undefined), 0x61); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(''), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt('1'), 0xDF06); proclaim.strictEqual('\uD834\uDF06def'.codePointAt('_'), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(-1), undefined); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(-0), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(0), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(1), 0xDF06); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(42), undefined); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(false), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(null), 0x1D306); proclaim.strictEqual('\uD834\uDF06def'.codePointAt(undefined), 0x1D306); proclaim.strictEqual('\uD834abc'.codePointAt(''), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt('_'), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(-1), undefined); proclaim.strictEqual('\uD834abc'.codePointAt(-0), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(0), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(false), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(NaN), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(null), 0xD834); proclaim.strictEqual('\uD834abc'.codePointAt(undefined), 0xD834); proclaim.strictEqual('\uDF06abc'.codePointAt(''), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt('_'), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(-1), undefined); proclaim.strictEqual('\uDF06abc'.codePointAt(-0), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(0), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(false), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(NaN), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(null), 0xDF06); proclaim.strictEqual('\uDF06abc'.codePointAt(undefined), 0xDF06); if (hasStrictMode) { proclaim["throws"](function () { String.prototype.codePointAt.call(null, 0); }, TypeError); proclaim["throws"](function () { String.prototype.codePointAt.call(undefined, 0); }, TypeError); } });
gordonli08/Exercism-python
grains/grains.py
def square(number): if number < 1 or number > 64: raise ValueError('Invalid chessboard square number') return 2 ** (number - 1) def total(): ret = 0 for i in range(1,65): ret += square(i) return ret