repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
EsfingeFramework/aomrolemapper
AOMRoleMapper/src/main/java/org/esfinge/aom/model/rolemapper/metadata/reader/provider/PropertyReaderProvider.java
<filename>AOMRoleMapper/src/main/java/org/esfinge/aom/model/rolemapper/metadata/reader/provider/PropertyReaderProvider.java package org.esfinge.aom.model.rolemapper.metadata.reader.provider; import org.esfinge.aom.model.rolemapper.metadata.reader.PropertyAnnotationReader; public class PropertyReaderProvider extends ElementReaderProvider { private static PropertyReaderProvider instance; public static PropertyReaderProvider getInstance() { if (instance == null) instance = new PropertyReaderProvider(); return instance; } private PropertyReaderProvider() { metadataReader = new PropertyAnnotationReader(); } }
mudkipmaster/gwlf-e
test/unittests/test_GRLostBarnN.py
<filename>test/unittests/test_GRLostBarnN.py import numpy as np from VariableUnittest import VariableUnitTest from gwlfe.AFOS.GrazingAnimals.Losses.GRLostBarnN import GRLostBarnN from gwlfe.AFOS.GrazingAnimals.Losses.GRLostBarnN import GRLostBarnN_f class TestGRLostBarnN(VariableUnitTest): def test_GRLostBarnN(self): z = self.z np.testing.assert_array_almost_equal( GRLostBarnN(z.NYrs, z.GrazingAnimal_0, z.NumAnimals, z.AvgAnimalWt, z.AnimalDailyN, z.GRPctManApp, z.PctGrazing, z.GRBarnNRate, z.Prec, z.DaysMonth, z.AWMSGrPct, z.GrAWMSCoeffN, z.RunContPct, z.RunConCoeffN), GRLostBarnN_f(z.NYrs, z.Prec, z.DaysMonth, z.GrazingAnimal_0, z.NumAnimals, z.AvgAnimalWt, z.AnimalDailyN, z.GRPctManApp, z.PctGrazing, z.GRBarnNRate, z.AWMSGrPct, z.GrAWMSCoeffN, z.RunContPct, z.RunConCoeffN), decimal=7)
goranstack/jfreeview
se.bluebrim.view.example.svg.resource/src/main/java/se/bluebrim/view/example/svg/resource/SVGSampleProvider.java
<filename>se.bluebrim.view.example.svg.resource/src/main/java/se/bluebrim/view/example/svg/resource/SVGSampleProvider.java package se.bluebrim.view.example.svg.resource; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Font; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.font.TextAttribute; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JToolBar; /** * Initializes a list of predefined SVG resources. * * @author <NAME> * */ public class SVGSampleProvider { public static class Resource { private URL originator; private URL resource; public Resource(URL originator, URL resource) { super(); this.originator = originator; this.resource = resource; } public URL getOriginator() { return originator; } public URL getResource() { return resource; } } private List<Resource> resources = new ArrayList<Resource>(); private Iterator<Resource> resourceIterator; private AbstractAction hyperLinkAction; public SVGSampleProvider() throws MalformedURLException { initializeSampleList(); } private void initializeSampleList() throws MalformedURLException { addSample("http://vector-art.blogspot.com", "Bolt_NWR1.svg"); addSample("http://xmlgraphics.apache.org/batik", "batik3D.svg"); addSample("http://www.isc.tamu.edu/~lewing", "NewTux.svg"); addSample("http://openclipart.org/media/people/mokush", "mokush_Realistic_Coffee_cup_-_Front_3D_view.svg"); addSample("http://openclipart.org/media/files/Chrisdesign/3587", "glossy-buttons.svg"); addSample("http://openclipart.org/media/files/Chrisdesign/9624", "tutanchamun.svg"); addSample("http://openclipart.org/media/files/Chrisdesign/3727", "gibson-les-paul.svg"); addSample("http://openclipart.org/media/files/yves_guillou/11115", "yves_guillou_sport_car_2.svg"); } private void addSample(String originator, String resourceName) throws MalformedURLException { resources.add(new Resource(new URL(originator), getClass().getResource("/" + resourceName))); } public Resource next() { if (resourceIterator == null || !resourceIterator.hasNext()) resourceIterator = resources.iterator(); Resource svgSample = resourceIterator.next(); if (hyperLinkAction != null) hyperLinkAction.putValue(Action.NAME, svgSample.getOriginator().toExternalForm()); return svgSample; } public void setForeignURL(URL url) { hyperLinkAction.putValue(Action.NAME, url.toExternalForm()); } @SuppressWarnings("unchecked") public JButton createOriginatorHyperLinkButton() { hyperLinkAction = new AbstractAction("Xxxxxxxx") { public void actionPerformed(ActionEvent event) { try { Desktop.getDesktop().browse(new URI((String) hyperLinkAction.getValue(Action.NAME))); } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }; JButton hyperLinkButton = new JButton(hyperLinkAction); hyperLinkButton.setBorderPainted(false); hyperLinkButton.setContentAreaFilled(false); Map map = hyperLinkButton.getFont().getAttributes(); map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); map.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR); map.put(TextAttribute.FOREGROUND, Color.BLUE); hyperLinkButton.setFont(new Font(map)); hyperLinkButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); return hyperLinkButton; } public JToolBar createNavigatorToolbar(Action nextAction) { JToolBar toolBar = new JToolBar(JToolBar.HORIZONTAL); JButton nextButton = new JButton(nextAction); nextButton.setContentAreaFilled(true); nextButton.setMargin(new Insets(0, 0, 0, 0)); nextButton.setIcon(new ImageIcon(getClass().getResource("nav_forward.gif"))); toolBar.add(nextButton); toolBar.addSeparator(); return toolBar; } /** * Creates a horizontal panel with the originator hyper link button * */ public Component createOriginatorBar() { Box box = new Box(BoxLayout.X_AXIS); box.add(createOriginatorHyperLinkButton()); return box; } }
PedroBarata/design-patterns
SOLID/src/OCPeDIP/Compra.java
package OCPeDIP; public class Compra { private String cidade; private double valor; public String getCidade() { return cidade; } public double getValor() { return valor; } }
mikosz/coconut
coconut-pulp-mesh/src/main/c++/coconut/pulp/mesh/obj/Importer.hpp
#ifndef _COCONUT_PULP_RENDERER_MESH_OBJ_IMPORTER_HPP_ #define _COCONUT_PULP_RENDERER_MESH_OBJ_IMPORTER_HPP_ #include "coconut/pulp/mesh/Importer.hpp" #include "Parser.hpp" namespace coconut { namespace pulp { namespace mesh { namespace obj { class Importer : public mesh::Importer { public: Importer() = default; Mesh import( const milk::fs::RawData& data, const milk::FilesystemContext& filesystemContext ) override; }; CT_MAKE_POINTER_DEFINITIONS(Importer); } // namespace obj } // namespace mesh } // namespace pulp } // namespace coconut #endif /* _COCONUT_PULP_RENDERER_MESH_OBJ_IMPORTER_HPP_ */
alex-dya/security_scanner
src/scanner/controls/unix/linux/partitions/mount_options.py
from scanner.const import os, mount from scanner.types import BaseContol, is_item_detected, ControlStatus from scanner.transports import get_transport from scanner.functions.unix.mount_parser import MountFinditer class Control(BaseContol, control_number=4): partitions = { '/var/tmp': ( mount.NODEV, mount.NOSUID, mount.NOEXEC, ), '/home': ( mount.NODEV, ), '/dev/shm': ( mount.NODEV, mount.NOSUID, mount.NOEXEC, ), '/tmp': ( mount.NODEV, mount.NOSUID, mount.NOEXEC, ) } def prerequisite(self): return is_item_detected(os.LINUX) def check(self): transport = get_transport('unix') result = transport.send_command('mount') separated = { item.Path: item.Options for item in MountFinditer(text=result.Output) if item.Path in self.partitions } results = [] status = ControlStatus.Compliance for path, options in self.partitions.items(): if path not in separated: status = ControlStatus.NotCompliance results.append( f'{path} has not been mounted on separated partition' ) continue missing_options = ','.join( opt for opt in options if opt not in separated[path] ) needed_options = ','.join(options) if not missing_options: results.append( f'{path} has been mounted with options "{needed_options}"' ) else: status = ControlStatus.NotCompliance results.append( f'{path} has been mounted without options "{missing_options}"' ) self.control.result = '\n'.join(results) self.control.status = status
RogerCVXD/prograiii
HITO3/demo/src/main/java/com/spring/demo/Model/InterfaceModelPersona.java
package com.spring.demo.Model; public interface InterfaceModelPersona { public void Insertar(String nombre); }
YunLemon/jSCSI
bundles/commons/src/main/java/org/jscsi/parser/digest/CRCTables.java
/** * Copyright (c) 2012, University of Konstanz, Distributed Systems Group 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 the University of Konstanz 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 <COPYRIGHT HOLDER> 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 org.jscsi.parser.digest; /** * <h1>CRCTables</h1> * <p> * This class generates tables for CRC algorithm. It is possible to change the generator polynom and the offset. Usage: * <ol> * <li>Make new <code>CRCTables</code> object.</li> * <li>Put <code>generatorPolynom</code> in the constructor.</li> * <li>Invoke the method <code>getTable</code> with offset as an argument. The offset is an integer number, which * specifies the number of bits to shift, e.g. for <code>A</code> offset is <code>56</code>, for <code>D</code> * <code>32</code>.</li> * <li>You will have CRC table(<code>0-255</code>) for the requested polynom.</li> * </ol> * * @author Stepan */ public final class CRCTables { // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- /** The size of a table. */ private static final int SIZE_OF_TABLE = 256; /** Bit mask for throwing away the 33-rd bit. */ private static final long BIN_MASK_33BIT = 0x00000000FFFFFFFFL; /** Bit mask with 1 only in the first position. */ private static final long BIN_MASK_1FIRST_ONLY = 0x8000000000000000L; /** Bit mask with 1 only in the first position for int. */ private static final int BIN_MASK_1FIRST_ONLY_INT = 0x80000000; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- /** The generator polynom. */ private final long generatorPolynom; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- /** * Constructor to create a new, empty <code>CRCTables</code> object with the initialized generator polynom. * * @param initGeneratorPolynom The generator polynom to use. */ public CRCTables (final long initGeneratorPolynom) { // FIXME: Really needed? generatorPolynom = initGeneratorPolynom; } // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- /** * Returns all remainders of the polynomial division for the given offset. * * @param offset The numbers of bits to shift, e.g. for <code>A</code> offset is <code>56</code>, for <code>D</code> * <code>32</code>. * @return The CRC table with all remainders for the given offset. */ public final int[] getTable (final int offset) { final int[] table = new int[SIZE_OF_TABLE]; long numberToCalculate; for (int number = 0; number < table.length; number++) { numberToCalculate = Integer.reverseBytes(Integer.reverse(number)); table[number] = calculateCRC32(numberToCalculate << offset); } return table; } // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- /** * Method for CRC calculation for the just one value (type long) Algorithm: Load the register with zero bits. * Reverse message Augment the message by appending W zero bits to the end of it. While (more message bits) Begin * Shift the register left by one bit, reading the next bit of the augmented message into register bit position 0. * If (a 1 bit popped out of the register during step 3) Register = Register XOR Poly. End Reverse register The * register now contains the CRC. Notes: W=32, that's why we have offsets 32, 40, 48 and 56 instead of 0,8,16,24 * Size of register=W; * * @param value A <code>long</code> value, for which the CRC should be calculated. * @return The remainder of the polynomial division --> CRC. */ protected final int calculateCRC32 (final long value) { long l = value; int register = 0; // We are going to throw the first bit away. Then making int from long. final int gxInt = (int) (generatorPolynom & BIN_MASK_33BIT); // the first bit before bit shifting in the input polynom int bit = 0; for (int i = 0; i < Long.SIZE; i++) { // is the highest bit set? if ((l & BIN_MASK_1FIRST_ONLY) == 0) { bit = 0; } else { bit = 1; } // is the highest bit set? if ((register & BIN_MASK_1FIRST_ONLY_INT) == 0) { register = register << 1; l = l << 1; register += bit; } else { register = register << 1; l = l << 1; register += bit; register = register ^ gxInt; } } return Integer.reverse(register); } // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- }
teneeto/socs-backend
node_modules/flutterwave-node-v3/lib/rave.subscriptions.js
<reponame>teneeto/socs-backend<gh_stars>0 const activate_sub = require('../services/subscriptions/rave.activate') const cancel_sub = require('../services/subscriptions/rave.cancel') const retrieve_all = require('../services/subscriptions/rave.retrieve.all') const fetch_one = require('../services/subscriptions/rave.retrieve.single') function Subscriptions(RaveBase) { this.activate = function (data) { return activate_sub(data, RaveBase); } this.cancel = function (data) { return cancel_sub(data, RaveBase); } this.fetch_all = function (data) { return retrieve_all(data, RaveBase); } this.get = function (data) { return fetch_one(data, RaveBase); } } module.exports = Subscriptions;
pczhangyu/poseidon
poseidon-search-service/src/main/java/com/poseidon/search/builders/IndexBuilder.java
package com.poseidon.search.builders; import org.elasticsearch.action.admin.indices.close.CloseIndexResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.open.OpenIndexResponse; import org.elasticsearch.client.Client; import java.net.UnknownHostException; public class IndexBuilder { /** * 检查索引是否存在 * @param indexName * @return * @throws UnknownHostException */ public static boolean isExists(String indexName) throws UnknownHostException { Client client = ClientBuilder.build(); return client.admin().indices().prepareExists(indexName).execute().actionGet().isExists(); } /** * 创建索引 * @param indexName * @return * @throws UnknownHostException */ public static CreateIndexResponse create(String indexName) throws UnknownHostException { Client client = ClientBuilder.build(); return client.admin().indices().prepareCreate(indexName).execute().actionGet(); } /** * 删除索引 * @param indexName * @return * @throws UnknownHostException */ public static DeleteIndexResponse delete(String indexName) throws UnknownHostException { Client client = ClientBuilder.build(); return client.admin().indices().prepareDelete(indexName).execute().actionGet(); } /** * 开启索引 * @param indexName * @return * @throws UnknownHostException */ public static OpenIndexResponse open(String indexName) throws UnknownHostException { Client client = ClientBuilder.build(); return client.admin().indices().prepareOpen(indexName).execute().actionGet(); } /** * 关闭索引 * @param indexName * @return * @throws UnknownHostException */ public static CloseIndexResponse close(String indexName) throws UnknownHostException { Client client = ClientBuilder.build(); return client.admin().indices().prepareClose(indexName).execute().actionGet(); } }
chrisdearman/mips-lk2
trusty/lib/trusty/vqueue.c
/* * Copyright (c) 2013-2014, Google, Inc. All rights reserved * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <assert.h> #include <err.h> #include <stddef.h> #include <stdlib.h> #include <sys/types.h> #include <trace.h> #include <arch/arch_ops.h> #include <lib/trusty/uio.h> #include <virtio/virtio_ring.h> #include "vqueue.h" #define LOCAL_TRACE 0 #define VQ_LOCK_FLAGS SPIN_LOCK_FLAG_INTERRUPTS int vqueue_init(struct vqueue *vq, uint32_t id, void *desc_addr, void *avail_addr, void *used_addr, uint num, void *priv, vqueue_cb_t notify_cb, vqueue_cb_t kick_cb) { DEBUG_ASSERT(vq); vq->vring_sz = used_addr - desc_addr + sizeof(uint16_t) * 3 + sizeof(struct vring_used_elem) * num; vring_init_v1(&vq->vring, num, desc_addr, avail_addr, used_addr); vq->id = id; vq->priv = priv; vq->notify_cb = notify_cb; vq->kick_cb = kick_cb; // XXX if vrings are placed in kernel virtual memory then vring_addr // will be needed to free the allocated memory. vq->vring_addr = (vaddr_t) desc_addr; event_init(&vq->avail_event, false, 0); return NO_ERROR; } void vqueue_destroy(struct vqueue *vq) { vaddr_t vring_addr; spin_lock_saved_state_t state; DEBUG_ASSERT(vq); spin_lock_save(&vq->slock, &state, VQ_LOCK_FLAGS); vring_addr = vq->vring_addr; vq->vring_addr = (vaddr_t)NULL; vq->vring_sz = 0; spin_unlock_restore(&vq->slock, state, VQ_LOCK_FLAGS); vmm_free_region(vmm_get_kernel_aspace(), vring_addr); } void vqueue_signal_avail(struct vqueue *vq) { spin_lock_saved_state_t state; spin_lock_save(&vq->slock, &state, VQ_LOCK_FLAGS); if (vq->vring_addr) vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY; spin_unlock_restore(&vq->slock, state, VQ_LOCK_FLAGS); event_signal(&vq->avail_event, false); } /* The other side of virtio pushes buffers into our avail ring, and pulls them * off our used ring. We do the reverse. We take buffers off the avail ring, * and put them onto the used ring. */ static int _vqueue_get_avail_buf_locked(struct vqueue *vq, struct vqueue_buf *iovbuf) { uint16_t next_idx; struct vring_desc *desc; DEBUG_ASSERT(vq); DEBUG_ASSERT(iovbuf); if (!vq->vring_addr) { /* there is no vring - return an error */ return ERR_CHANNEL_CLOSED; } /* the idx counter is free running, so check that it's no more * than the ring size away from last time we checked... this * should *never* happen, but we should be careful. */ uint16_t avail_cnt = vq->vring.avail->idx - vq->last_avail_idx; if (unlikely(avail_cnt > (uint16_t) vq->vring.num)) { /* such state is not recoverable */ panic("vq %p: new avail idx out of range (old %u new %u)\n", vq, vq->last_avail_idx, vq->vring.avail->idx); } if (vq->last_avail_idx == vq->vring.avail->idx) { event_unsignal(&vq->avail_event); vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY; mb(); if (vq->last_avail_idx == vq->vring.avail->idx) { /* no buffers left */ return ERR_NOT_ENOUGH_BUFFER; } vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY; event_signal(&vq->avail_event, false); } rmb(); next_idx = vq->vring.avail->ring[vq->last_avail_idx % vq->vring.num]; vq->last_avail_idx++; if (unlikely(next_idx >= vq->vring.num)) { /* index of the first descriptor in chain is out of range. vring is in non recoverable state: we cannot even return an error to the other side */ panic("vq %p: head out of x range %u (max %u) index %d\n", vq, next_idx, vq->vring.num, (vq->last_avail_idx - 1) % vq->vring.num); } iovbuf->head = next_idx; iovbuf->in_iovs.used = 0; iovbuf->in_iovs.len = 0; iovbuf->out_iovs.used = 0; iovbuf->out_iovs.len = 0; do { struct vqueue_iovs *iovlist; if (unlikely(next_idx >= vq->vring.num)) { /* Descriptor chain is in invalid state. * Abort message handling, return an error to the * other side and let it deal with it. */ LTRACEF("vq %p: head out of y range %u (max %u)\n", vq, next_idx, vq->vring.num); return ERR_NOT_VALID; } desc = &vq->vring.desc[next_idx]; if (desc->flags & VRING_DESC_F_WRITE) iovlist = &iovbuf->out_iovs; else iovlist = &iovbuf->in_iovs; if (iovlist->used < iovlist->cnt) { /* .base will be set when we map this iov */ iovlist->iovs[iovlist->used].len = desc->len; iovlist->phys[iovlist->used] = (paddr_t) desc->addr; iovlist->used++; iovlist->len += desc->len; } else { return ERR_TOO_BIG; } /* go to the next entry in the descriptor chain */ next_idx = desc->next; } while (desc->flags & VRING_DESC_F_NEXT); return NO_ERROR; } int vqueue_get_avail_buf(struct vqueue *vq, struct vqueue_buf *iovbuf) { spin_lock_saved_state_t state; spin_lock_save(&vq->slock, &state, VQ_LOCK_FLAGS); int ret = _vqueue_get_avail_buf_locked(vq, iovbuf); spin_unlock_restore(&vq->slock, state, VQ_LOCK_FLAGS); return ret; } static int _vqueue_add_buf_locked(struct vqueue *vq, struct vqueue_buf *buf, uint32_t len) { struct vring_used_elem *used; DEBUG_ASSERT(vq); DEBUG_ASSERT(buf); if (!vq->vring_addr) { /* there is no vring - return an error */ return ERR_CHANNEL_CLOSED; } if (buf->head >= vq->vring.num) { /* this would probable mean corrupted vring */ LTRACEF("vq %p: head (%u) out of range (%u)\n", vq, buf->head, vq->vring.num); return ERR_NOT_VALID; } used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num]; used->id = buf->head; used->len = len; wmb(); vq->vring.used->idx++; vqueue_kick(vq); return NO_ERROR; } int vqueue_add_buf(struct vqueue *vq, struct vqueue_buf *buf, uint32_t len) { spin_lock_saved_state_t state; spin_lock_save(&vq->slock, &state, VQ_LOCK_FLAGS); int ret = _vqueue_add_buf_locked(vq, buf, len); spin_unlock_restore(&vq->slock, state, VQ_LOCK_FLAGS); return ret; } int vqueue_kick(struct vqueue *vq) { if (vq->kick_cb) return vq->kick_cb(vq, vq->priv); return 0; }
kurohayan/dataStructureAndAlgorithm
netty/src/main/java/com/kuroha/netty/niosocket/socket/Client2.java
package com.kuroha.netty.niosocket.socket; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; /** * @author kuroha */ public class Client2 { public static void main(String[] args) throws Exception { Socket socket = new Socket(); System.out.println(socket.getSendBufferSize()); socket.setSendBufferSize(1024*1024); socket.setTrafficClass(0x10); System.out.println(socket.getSendBufferSize()); socket.connect(new InetSocketAddress("localhost", 8848)); OutputStream outputStream = socket.getOutputStream(); for (int i = 0; i < 500000; i++) { outputStream.write("1".getBytes()); } outputStream.write("end!".getBytes()); outputStream.close(); socket.close(); } }
msgimanila/EXT-React-MSG
misc/deprecated/deprecate-ext-react/dist/ExtViewport.js
import reactize from './reactize.js'; import EWCViewport from '@sencha/ext-web-components/src/ext-viewport.component.js'; export default reactize(EWCViewport);
liuzheng/django-project-template
projectname/management/utils/admin.py
<filename>projectname/management/utils/admin.py from django.contrib import admin from django.conf import settings from django.http import HttpResponseForbidden from management.models import ApiLog admin.site.site_header = settings.DJANGO_TITLE def has_permission(perm: str): def decorator(func): def wrapper(request, *args, **kwargs): if request.user.has_perm(perm): return func(request, *args, **kwargs) return HttpResponseForbidden return wrapper return decorator def api_permission(*perms: str): def decorator(func): def wrapper(api, request, *args, **kwargs): for perm in perms: if '.' not in perm: perm = api._class_name + '.' + perm + '_' + api._class_name if request.user.has_perm(perm): log = ApiLog.objects.create(Class=api.__class__.__name__, Function=func.__name__, User=request.user, SourceIP=request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0] if request.META.get('HTTP_X_FORWARDED_FOR') else request.META.get( 'REMOTE_ADDR'), URI=request.get_full_path() ) log.save() res = func(api, request, *args, **kwargs) log.StatusCode = res.status_code log.save() return res return HttpResponseForbidden('You DO NOT have this api permission, Please contact your administrator') return wrapper return decorator
Pixelated-Project/aosp-android-jar
android-31/src/com/android/internal/graphics/palette/WSMeansQuantizer.java
<reponame>Pixelated-Project/aosp-android-jar<filename>android-31/src/com/android/internal/graphics/palette/WSMeansQuantizer.java /* * Copyright (C) 2021 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.internal.graphics.palette; import android.annotation.NonNull; import android.annotation.Nullable; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; /** * A color quantizer based on the Kmeans algorithm. Prefer using QuantizerCelebi. * * This is an implementation of Kmeans based on Celebi's 2011 paper, * "Improving the Performance of K-Means for Color Quantization". In the paper, this algorithm is * referred to as "WSMeans", or, "Weighted Square Means" The main advantages of this Kmeans * implementation are taking advantage of triangle properties to avoid distance calculations, as * well as indexing colors by their count, thus minimizing the number of points to move around. * * Celebi's paper also stabilizes results and guarantees high quality by using starting centroids * from Wu's quantization algorithm. See QuantizerCelebi for more info. */ public final class WSMeansQuantizer implements Quantizer { private static final String TAG = "QuantizerWsmeans"; private static final boolean DEBUG = false; private static final int MAX_ITERATIONS = 10; // Points won't be moved to a closer cluster, if the closer cluster is within // this distance. 3.0 used because L*a*b* delta E < 3 is considered imperceptible. private static final float MIN_MOVEMENT_DISTANCE = 3.0f; private final PointProvider mPointProvider; private @Nullable Map<Integer, Integer> mInputPixelToCount; private float[][] mClusters; private int[] mClusterPopulations; private float[][] mPoints; private int[] mPixels; private int[] mClusterIndices; private int[][] mIndexMatrix = {}; private float[][] mDistanceMatrix = {}; private Palette mPalette; public WSMeansQuantizer(int[] inClusters, PointProvider pointProvider, @Nullable Map<Integer, Integer> inputPixelToCount) { mPointProvider = pointProvider; mClusters = new float[inClusters.length][3]; int index = 0; for (int cluster : inClusters) { float[] point = pointProvider.fromInt(cluster); mClusters[index++] = point; } mInputPixelToCount = inputPixelToCount; } @Override public List<Palette.Swatch> getQuantizedColors() { return mPalette.getSwatches(); } @Override public void quantize(@NonNull int[] pixels, int maxColors) { assert (pixels.length > 0); if (mInputPixelToCount == null) { QuantizerMap mapQuantizer = new QuantizerMap(); mapQuantizer.quantize(pixels, maxColors); mInputPixelToCount = mapQuantizer.getColorToCount(); } mPoints = new float[mInputPixelToCount.size()][3]; mPixels = new int[mInputPixelToCount.size()]; int index = 0; for (int pixel : mInputPixelToCount.keySet()) { mPixels[index] = pixel; mPoints[index] = mPointProvider.fromInt(pixel); index++; } if (mClusters.length > 0) { // This implies that the constructor was provided starting clusters. If that was the // case, we limit the number of clusters to the number of starting clusters and don't // initialize random clusters. maxColors = Math.min(maxColors, mClusters.length); } maxColors = Math.min(maxColors, mPoints.length); initializeClusters(maxColors); for (int i = 0; i < MAX_ITERATIONS; i++) { calculateClusterDistances(maxColors); if (!reassignPoints(maxColors)) { break; } recalculateClusterCenters(maxColors); } List<Palette.Swatch> swatches = new ArrayList<>(); for (int i = 0; i < maxColors; i++) { float[] cluster = mClusters[i]; int colorInt = mPointProvider.toInt(cluster); swatches.add(new Palette.Swatch(colorInt, mClusterPopulations[i])); } mPalette = Palette.from(swatches); } private void initializeClusters(int maxColors) { boolean hadInputClusters = mClusters.length > 0; if (!hadInputClusters) { int additionalClustersNeeded = maxColors - mClusters.length; if (DEBUG) { Log.d(TAG, "have " + mClusters.length + " clusters, want " + maxColors + " results, so need " + additionalClustersNeeded + " additional clusters"); } Random random = new Random(0x42688); List<float[]> additionalClusters = new ArrayList<>(additionalClustersNeeded); Set<Integer> clusterIndicesUsed = new HashSet<>(); for (int i = 0; i < additionalClustersNeeded; i++) { int index = random.nextInt(mPoints.length); while (clusterIndicesUsed.contains(index) && clusterIndicesUsed.size() < mPoints.length) { index = random.nextInt(mPoints.length); } clusterIndicesUsed.add(index); additionalClusters.add(mPoints[index]); } float[][] newClusters = (float[][]) additionalClusters.toArray(); float[][] clusters = Arrays.copyOf(mClusters, maxColors); System.arraycopy(newClusters, 0, clusters, clusters.length, newClusters.length); mClusters = clusters; } mClusterIndices = new int[mPixels.length]; mClusterPopulations = new int[mPixels.length]; Random random = new Random(0x42688); for (int i = 0; i < mPixels.length; i++) { int clusterIndex = random.nextInt(maxColors); mClusterIndices[i] = clusterIndex; mClusterPopulations[i] = mInputPixelToCount.get(mPixels[i]); } } void calculateClusterDistances(int maxColors) { if (mDistanceMatrix.length != maxColors) { mDistanceMatrix = new float[maxColors][maxColors]; } for (int i = 0; i <= maxColors; i++) { for (int j = i + 1; j < maxColors; j++) { float distance = mPointProvider.distance(mClusters[i], mClusters[j]); mDistanceMatrix[j][i] = distance; mDistanceMatrix[i][j] = distance; } } if (mIndexMatrix.length != maxColors) { mIndexMatrix = new int[maxColors][maxColors]; } for (int i = 0; i < maxColors; i++) { ArrayList<Distance> distances = new ArrayList<>(maxColors); for (int index = 0; index < maxColors; index++) { distances.add(new Distance(index, mDistanceMatrix[i][index])); } distances.sort( (a, b) -> Float.compare(a.getDistance(), b.getDistance())); for (int j = 0; j < maxColors; j++) { mIndexMatrix[i][j] = distances.get(j).getIndex(); } } } boolean reassignPoints(int maxColors) { boolean colorMoved = false; for (int i = 0; i < mPoints.length; i++) { float[] point = mPoints[i]; int previousClusterIndex = mClusterIndices[i]; float[] previousCluster = mClusters[previousClusterIndex]; float previousDistance = mPointProvider.distance(point, previousCluster); float minimumDistance = previousDistance; int newClusterIndex = -1; for (int j = 1; j < maxColors; j++) { int t = mIndexMatrix[previousClusterIndex][j]; if (mDistanceMatrix[previousClusterIndex][t] >= 4 * previousDistance) { // Triangle inequality proves there's can be no closer center. break; } float distance = mPointProvider.distance(point, mClusters[t]); if (distance < minimumDistance) { minimumDistance = distance; newClusterIndex = t; } } if (newClusterIndex != -1) { float distanceChange = (float) Math.abs((Math.sqrt(minimumDistance) - Math.sqrt(previousDistance))); if (distanceChange > MIN_MOVEMENT_DISTANCE) { colorMoved = true; mClusterIndices[i] = newClusterIndex; } } } return colorMoved; } void recalculateClusterCenters(int maxColors) { mClusterPopulations = new int[maxColors]; float[] aSums = new float[maxColors]; float[] bSums = new float[maxColors]; float[] cSums = new float[maxColors]; for (int i = 0; i < mPoints.length; i++) { int clusterIndex = mClusterIndices[i]; float[] point = mPoints[i]; int pixel = mPixels[i]; int count = mInputPixelToCount.get(pixel); mClusterPopulations[clusterIndex] += count; aSums[clusterIndex] += point[0] * count; bSums[clusterIndex] += point[1] * count; cSums[clusterIndex] += point[2] * count; } for (int i = 0; i < maxColors; i++) { int count = mClusterPopulations[i]; float aSum = aSums[i]; float bSum = bSums[i]; float cSum = cSums[i]; mClusters[i][0] = aSum / count; mClusters[i][1] = bSum / count; mClusters[i][2] = cSum / count; } } private static class Distance { private final int mIndex; private final float mDistance; int getIndex() { return mIndex; } float getDistance() { return mDistance; } Distance(int index, float distance) { mIndex = index; mDistance = distance; } } }
soker90/arroyo-erp-client
src/pages/Expenses/modals/NewProviderModal/NewProviderModalView.js
<filename>src/pages/Expenses/modals/NewProviderModal/NewProviderModalView.js<gh_stars>1-10 import { memo, useEffect, useReducer } from 'react'; import PropTypes from 'prop-types'; import ProviderModal, { INITIAL_STATE } from 'components/Modals/ProviderModal'; const NewProviderModal = ({ show, close, createProvider, }) => { const [state, setState] = useReducer( (oldState, newState) => ({ ...oldState, ...newState }), INITIAL_STATE, ); useEffect(() => { if (!show) setState(INITIAL_STATE); }, [show]); /** * Handle event save button * @private */ const _handleSubmit = () => { createProvider(state, close); }; return ( <ProviderModal show={show} close={close} title='Crear proveedor de gasto' action={_handleSubmit} state={state} setState={setState} /> ); }; NewProviderModal.propTypes = { show: PropTypes.bool.isRequired, close: PropTypes.func.isRequired, createProvider: PropTypes.func.isRequired, }; NewProviderModal.displayName = 'NewProviderModal'; export const story = NewProviderModal; export default memo(NewProviderModal);
temcocontrols/ModbusToBacnetModule
Bluetooth/external/bacnet-stack/ports/atmega168/bv.h
/************************************************************************** * * Copyright (C) 2006 <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * *********************************************************************/ #ifndef BV_H #define BV_H #include <stdbool.h> #include <stdint.h> #include "bacdef.h" #include "bacerror.h" #include "wp.h" #ifndef MAX_BINARY_VALUES #define MAX_BINARY_VALUES 10 #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void Binary_Value_Property_Lists( const int **pRequired, const int **pOptional, const int **pProprietary); bool Binary_Value_Valid_Instance( uint32_t object_instance); unsigned Binary_Value_Count( void); uint32_t Binary_Value_Index_To_Instance( unsigned index); char *Binary_Value_Name( uint32_t object_instance); void Binary_Value_Init( void); int Binary_Value_Encode_Property_APDU( uint8_t * apdu, uint32_t object_instance, BACNET_PROPERTY_ID property, uint32_t array_index, BACNET_ERROR_CLASS * error_class, BACNET_ERROR_CODE * error_code); bool Binary_Value_Write_Property( BACNET_WRITE_PROPERTY_DATA * wp_data, BACNET_ERROR_CLASS * error_class, BACNET_ERROR_CODE * error_code); #ifdef TEST #include "ctest.h" void testBinary_Value( Test * pTest); #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif
newcommerdontblame/ionlib
src/sdk/hl2_csgo/game/shared/swarm/asw_util_shared.h
#ifndef _INCLUDE_ASW_UTIL_SHARED_H #define _INCLUDE_ASW_UTIL_SHARED_H // Misc functions used by other bits of ASW #include "util_shared.h" #include "asw_shareddefs.h" #ifdef CLIENT_DLL #define CPointCamera C_PointCamera #endif class CPhysicsProp; class CASW_Player; class CASW_Marine; class CASW_Marine_Resource; class CPointCamera; #ifdef CLIENT_DLL class CNewParticleEffect; #endif int UTIL_ASW_GetNumPlayers(); // rotates one angle towards another, with a fixed turning rate over the time float ASW_ClampYaw( float yawSpeedPerSec, float current, float target, float time ); // time independent movement of one angle to a fraction of the desired float ASW_ClampYaw_Fraction( float fraction, float current, float target, float time ); float ASW_Linear_Approach( float current, float target, float delta); bool ASW_LineCircleIntersection( const Vector2D &center, const float radius, const Vector2D &vLinePt, const Vector2D &vLineDir, float *fIntersection1, float *fIntersection2); // is a marine nearby this spot? i.e. can a player controlling this marine see this spot (bCorpseCanSee is set to true if a marine corpse can see this spot) CASW_Marine* UTIL_ASW_MarineCanSee(CASW_Marine_Resource* pMR, const Vector &pos, const int padding, bool &bCorpseCanSee, const int forward_limit = -1); CASW_Marine* UTIL_ASW_AnyMarineCanSee(const Vector &pos, const int padding, bool &bCorpseCanSee, const int forward_limit = -1); // is a marine looking at this spot? bool UTIL_ASW_MarineViewCone(const Vector &pos); // default camera and dot values for the above function #define MARINE_NEARBY_DOT_768 0.6322133 #define MARINE_NEARBY_DOT_1024 0.5335417 #define ASW_DEFAULT_CAMERA_DIR Vector(0,0.500000f,-0.866025f) #define ASW_DEFAULT_CAMERA_OFFSET Vector(0.000009f,-202.499985f,350.740306f) //void UTIL_ASW_ValidateSoundName( string_t &name, const char *defaultStr ); void UTIL_ASW_ValidateSoundName( char *szString, int stringlength, const char *defaultStr ); /// get a parabola that goes from source to destination in specified time Vector UTIL_LaunchVector( const Vector &src, const Vector &dest, float gravity, float flightTime = 0.0f ); // returns the first collision point for a thrown entity (MOVETYPE_FLYGRAVITY) Vector UTIL_Check_Throw( const Vector &vecSrc, const Vector &vecThrowVelocity, float flGravity, const Vector &vecHullMins, const Vector &vecHullMaxs, int iCollisionMask = MASK_NPCSOLID, int iCollisionGroup = COLLISION_GROUP_PROJECTILE, CBaseEntity *pIgnoreEnt = NULL, bool bDrawArc = false ); void UTIL_Bound_Velocity( Vector &vec ); char* ASW_AllocString( const char *szString ); float UTIL_ASW_CalcFastDoorHackTime(int iNumRows, int iNumColumns, int iNumWires, int iHackLevel, float fSpeedScale); #ifdef GAME_DLL void UTIL_ASW_ScreenShake( const Vector &center, float amplitude, float frequency, float duration, float radius, ShakeCommand_t eCommand, bool bAirShake=false ); void UTIL_ASW_ScreenPunch( const Vector &center, const Vector &direction, float amplitude, float frequency, float duration, float radius ); void UTIL_ASW_ScreenPunch( const Vector &center, float radius, const ScreenShake_t &shake ); void UTIL_ASW_PoisonBlur(CBaseEntity *pEntity, float duration); CASW_Marine* UTIL_ASW_NearestMarine( const Vector &pos, float &marine_distance, ASW_Marine_Class marineClass = MARINE_CLASS_UNDEFINED, bool bAIOnly = false ); // returns the nearest marine to this point CASW_Marine* UTIL_ASW_NearestMarine( const CASW_Marine *pMarine, float &marine_distance ); // returns the nearest marine to this marine int UTIL_ASW_NumCommandedMarines( const CASW_Player *pPlayer ); // returns the number of marines commanded by this player bool UTIL_ASW_BlockingMarine( CBaseEntity *pEntity ); CASW_Marine* UTIL_ASW_Marine_Can_Chatter_Spot( CBaseEntity *pEntity, float fDist = 500.0f ); #else bool UTIL_ASW_ClientsideGib(C_BaseAnimating* pEnt); CNewParticleEffect *UTIL_ASW_CreateFireEffect( C_BaseEntity *pEntity ); void TryLocalize(const char *token, wchar_t *unicode, int unicodeBufferSizeInBytes); void UTIL_ASW_ClientFloatingDamageNumber( const CTakeDamageInfo &info ); void UTIL_ASW_ParticleDamageNumber( C_BaseEntity *pEnt, Vector vecPos, int iDamage, int iDmgCustom, float flScale, bool bRandomVelocity ); #endif void ASW_TransmitShakeEvent( CBasePlayer *pPlayer, float localAmplitude, float frequency, float duration, ShakeCommand_t eCommand, const Vector &direction = Vector(0,0,0) ); void ASW_TransmitShakeEvent( CBasePlayer *pPlayer, const ScreenShake_t &shake ); /// this is a convenience function for rapidly iterating on a screenshake. (see .cpp for details) ScreenShake_t ASW_DefaultScreenShake( void ); /// based on the mapname, this reports if a map should show the briefing or not bool UTIL_ASW_MissionHasBriefing(const char* mapname); class CTraceFilterAliensEggsGoo : public CTraceFilterSimple { public: CTraceFilterAliensEggsGoo( const IHandleEntity *passentity, int collisionGroup ) : CTraceFilterSimple( passentity, collisionGroup ) { } virtual TraceType_t GetTraceType() const { return TRACE_ENTITIES_ONLY; } virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask ); }; bool ASW_IsSecurityCam(CPointCamera *pCameraEnt); #endif // _INCLUDE_ASW_UTIL_SHARED_H
dc-tw/ohara
ohara-manager/client/cypress/integration/streamApp.test.js
<filename>ohara-manager/client/cypress/integration/streamApp.test.js /* * Copyright 2019 is-land * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as URLS from '../../src/constants/urls'; import { makeRandomStr } from '../utils'; describe('StreamApp', () => { before(() => { cy.deleteAllWorkers(); cy.createWorker(); }); context('Stream app jars', () => { beforeEach(() => { cy.server(); cy.route('GET', 'api/pipelines/*').as('getPipeline'); cy.route('PUT', 'api/pipelines/*').as('putPipeline'); const pipelineName = makeRandomStr(); cy.visit(URLS.PIPELINES) .getByTestId('new-pipeline') .click() .getByLabelText('Pipeline name') .click() .type(pipelineName) .getByTestId('cluster-select') .select(Cypress.env('WORKER_NAME')) .getByText('Add') .click(); }); it('adds a streamApp into pipeline graph and removes it with the remove button', () => { cy.wait('@getPipeline') .uploadStreamAppJar() .getByText('Stream app successfully uploaded!') .should('have.length', 1) .getByText('ohara-streamapp.jar') .getByText('Add') .click() .getByText('Untitled streamApp') .should('be.exist') .click() .getByTestId('delete-button') .click() .getByText('Yes, Remove this stream app') .click() .wait('@getPipeline') .queryAllByText('Untitled streamApp') .should('have.length', 0) .deleteStreamApp(); }); it('edits a streamApp jar name', () => { cy.wait('@getPipeline') .uploadStreamAppJar() .getByText('ohara-streamapp.jar') .click() .getByTestId('title-input') .type('{leftarrow}{leftarrow}{leftarrow}{leftarrow}') // move the mouse cursor with the left arrow key .type('_2{enter}') .getByTestId('stream-app-item') .find('label') .contains('ohara-streamapp_2.jar') .deleteStreamApp('ohara-streamapp_2.jar'); }); it('deletes streamApp jar', () => { cy.wait('@getPipeline') .uploadStreamAppJar() .getByTestId('delete-stream-app') .click() .getByText('Yes, Delete this jar') .click() .wait(500) .queryAllByTestId('stream-app-item') .should('have.length', 0); }); }); context('Stream app property form', () => { beforeEach(() => { cy.server(); cy.route('GET', 'api/pipelines/*').as('getPipeline'); cy.route('PUT', 'api/pipelines/*').as('putPipeline'); cy.createTopic().as('fromTopic'); cy.createTopic().as('toTopic'); const pipelineName = makeRandomStr(); cy.visit(URLS.PIPELINES) .getByTestId('new-pipeline') .click() .getByLabelText('Pipeline name') .click() .type(pipelineName) .getByTestId('cluster-select') .select(Cypress.env('WORKER_NAME')) .getByText('Add') .click(); }); // TODO: remove the pipeline once the test is finished it('starts a stream app', () => { cy.wait('@getPipeline') .uploadStreamAppJar() .getByText('Add') .click(); // TODO: these two topics can be added via API which should be faster than // adding from the UI cy.getByTestId('toolbar-topics') .click({ force: true }) .get('@fromTopic') .then(from => { cy.getByTestId('topic-select').select(from.name); }) .getByText('Add') .click() .wait('@putPipeline'); cy.getByTestId('toolbar-topics') .click({ force: true }) .get('@toTopic') .then(to => { cy.getByTestId('topic-select').select(to.name); }) .getByText('Add') .click() .wait('@putPipeline'); cy.getByText('Untitled streamApp') .click() .getByDisplayValue('select a from topic...') .get('@fromTopic') .then(from => { cy.getByDisplayValue('select a from topic...') .select(from.name) .wait(2000) // UI has one sec throttle, so we need to wait a bit time and then wait for the request .wait('@putPipeline'); }) .getByDisplayValue('select a to topic...') .get('@toTopic') .then(to => { cy.getByDisplayValue('select a to topic...') .select(to.name) .wait(2000) .wait('@putPipeline'); }) .getByTestId('start-button') .click() .getByText('Stream app successfully started!') .should('be.exist') .getByText('Untitled streamApp') .then($el => { cy.wrap($el.parent()).within(() => { cy.getByText('Status: running').should('be.exist'); }); }) .getByTestId('stop-button') .click(); }); }); });
ZLkanyo009/mindspore
mindspore/lite/src/runtime/agent/npu/subgraph_npu_kernel.h
/** * Copyright 2020-2021 Huawei Technologies Co., Ltd * * 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. */ #ifndef MINDSPORE_LITE_SRC_RUNTIME_AGENT_SUBGRAPH_NPU_KERNEL_H_ #define MINDSPORE_LITE_SRC_RUNTIME_AGENT_SUBGRAPH_NPU_KERNEL_H_ #include <vector> #include <string> #include <memory> #include "include/hiai_ir_build.h" #include "src/sub_graph_kernel.h" #include "src/runtime/agent/npu/npu_executor.h" #include "include/graph/op/all_ops.h" #ifdef SUPPORT_NPU #include "src/runtime/agent/npu/npu_manager.h" #endif namespace mindspore::kernel { using mindspore::lite::RET_ERROR; using mindspore::lite::RET_OK; class SubGraphNpuKernel : public SubGraphKernel { public: SubGraphNpuKernel(const std::vector<lite::Tensor *> &inputs, const std::vector<lite::Tensor *> &outputs, const std::vector<kernel::LiteKernel *> &inKernels, const std::vector<kernel::LiteKernel *> &outKernels, const std::vector<kernel::LiteKernel *> &nodes, const lite::InnerContext *ctx = nullptr, lite::NPUManager *npu_manager = nullptr) : SubGraphKernel(inputs, outputs, inKernels, outKernels, nodes, ctx), npu_manager_(npu_manager) { subgraph_type_ = kNpuSubGraph; desc_.arch = kernel::KERNEL_ARCH::kNPU; } ~SubGraphNpuKernel() override; int Init() override; int Prepare() override; int PreProcess() override { return RET_OK; } int Run() override; int Run(const KernelCallBack &before, const KernelCallBack &after) override { return this->Run(); } int PostProcess() override { return RET_OK; } int ReSize() override { MS_LOG(ERROR) << "NPU does not support the resize function temporarily."; return RET_ERROR; } private: std::shared_ptr<domi::ModelBufferData> BuildIRModel(); int BuildNPUInputOp(); int BuildNPUOutputOp(); std::vector<ge::Operator> GetNPUNodes(const std::vector<kernel::LiteKernel *> &nodes); bool IsSubGraphInputTensor(lite::Tensor *inputs); std::string GetOMModelName(); private: bool is_compiled_ = false; lite::NPUManager *npu_manager_ = nullptr; std::vector<ge::Operator> subgraph_input_op_; std::vector<ge::Operator> subgraph_output_op_; std::vector<lite::Tensor *> out_tensor_sorted_; std::vector<ge::Operator *> op_buffer_; }; } // namespace mindspore::kernel #endif // MINDSPORE_LITE_SRC_RUNTIME_AGENT_SUBGRAPH_NPU_KERNEL_H_
huangyuanzhi1997/BlogSystem
src/main/java/top/huangyuanzhi/service/IUserService.java
<reponame>huangyuanzhi1997/BlogSystem<filename>src/main/java/top/huangyuanzhi/service/IUserService.java package top.huangyuanzhi.service; import top.huangyuanzhi.model.vo.User; /** * <p> * 服务类 * </p> * * @author Huang * @since 2020-09-02 */ public interface IUserService { /** * 用户登录 * @param username * @param password * @return */ User login(String username,String password); }
therussellhome/inherit_the_stars
stars/scan.py
<gh_stars>0 import sys from . import binning from .reference import Reference # Unscanned ships # First level of bins is the player # Second level is the bin number __unscanned = {} # Post scan bins __scanned = {} """ Clear the bins prior to updating them """ def reset(players): global __unscanned __unscanned = {} __scanned = {} for p in players: __unscanned[Reference(p)] = {} __scanned[Reference(p)] = {} """ Update a location """ def add(obj, location, apparent_mass, ke, is_ship=False, has_cloak=False, in_system=False): global __unscanned b = binning.num(location) o = {'obj':obj, 'location':location, 'apparent_mass':apparent_mass, 'ke':ke, 'is_ship':is_ship, 'has_cloak':has_cloak, 'in_system':in_system, 'bin':b} for p in __unscanned: if b not in __unscanned[p]: __unscanned[p][b] = [] __unscanned[p][b].append(o) """ ONLY FOR TESTING """ def _bin_testing(scanned=False): global __unscanned, __scanned if scanned: return __scanned return __unscanned """ Found in bin """ def _bin_found(p_ref, o): global __unscanned, __RANGE_BIN_SIZE __unscanned[p_ref][o['bin']].remove(o) __scanned[p_ref][o['bin']].append(o) """ Search the bins and return the ships seen """ def anticloak(player, location, rng): global __unscanned p_ref = Reference(player) for o in binning.search(__unscanned[p_ref], location, rng): if o['has_cloak'] and location - o['location'] < rng: _bin_found(p_ref, o) player.add_intel(o['obj'], o['obj'].scan_report(scan_type='anticloak')) """ Search the bins and return the ships seen """ def penetrating(player, location, rng): global __unscanned p_ref = Reference(player) for o in binning.search(__unscanned[p_ref], location, rng): if o['apparent_mass'] > 0 and location - o['location'] < rng: _bin_found(p_ref, o) player.add_intel(o['obj'], o['obj'].scan_report(scan_type='penetrating')) """ Search the bins and return the ships seen """ def normal(player, location, rng): global __unscanned p_ref = Reference(player) for o in binning.search(__unscanned[p_ref], location, rng): distance = location - o['location'] if not o['in_system'] and o['apparent_mass'] > 0 and distance < rng and o['ke'] > ((-500000 * rng) / (distance - rng) - 500000): _bin_found(p_ref, o) player.add_intel(o['obj'], o['obj'].scan_report(scan_type='normal')) """ Report on ships seen moving in hyperdenial fields, hyperdenial does its own binning """ def hyperdenial(fleet, players): for player in players: for ship in fleet.ships: player.add_intel(ship, ship.scan_report(scan_type='hyperdenial')) """ Search for closest enemy """ def patrol(player, location, rng): global __scanned p_ref = Reference(player) closest_distance = sys.maxsize closest_object = None for o in binning.search(__scanned[p_ref], location, rng): if o['is_ship'] and player.get_relation(o['obj'].player) == 'enemy': distance = location - o['location'] if distance < closest_distance: closest_distance = distance closest_object = o['obj'] if closest_object: return Location(reference=closest_object) return location
saalk/cards
server/src/main/java/cloud/qasino/quiz/dto/navigation/NavigationGame.java
package cloud.qasino.quiz.dto.navigation; import cloud.qasino.quiz.entity.Game; import cloud.qasino.quiz.entity.League; import cloud.qasino.quiz.entity.User; import cloud.qasino.quiz.entity.enums.game.style.*; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class NavigationGame { private boolean hasBalance; // icon is quizzes -> select/start game to enable nav-game // creating / selecting only possible when <hasBalance = true> @JsonProperty("Game") private Game game; // including a list of players + intiator @JsonProperty("Friends") private List<User> friends; // todo friends @JsonProperty("Leagues") private List<League> leagues; private int totalUsers; private int totalBots; // selections private AnteToWin anteToWin; private BettingStrategy bettingStrategy; private Deck deck; private InsuranceCost insuranceCost; private RoundsToWin roundsToWin; private TurnsToWin turnsToWin; }
skarzhevskyy/gwt-mock-2.5.1
src/main/java/com/google/gwt/i18n/client/impl/cldr/DateTimeFormatInfoImpl_kea.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.i18n.client.impl.cldr; // DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA // cldrVersion=21.0 // number=$Revision: 6546 $ // date=$Date: 2012-02-07 13:32:35 -0500 (Tue, 07 Feb 2012) $ // type=root /** * Implementation of DateTimeFormatInfo for the "kea" locale. */ public class DateTimeFormatInfoImpl_kea extends DateTimeFormatInfoImpl { @Override public String[] ampms() { return new String[] { "am", "pm" }; } @Override public String dateFormatFull() { return "EEEE, d 'di' MMMM 'di' y"; } @Override public String dateFormatLong() { return "d 'di' MMMM 'di' y"; } @Override public String dateFormatMedium() { return "d 'di' MMM 'di' y"; } @Override public String dateFormatShort() { return "d/M/yyyy"; } @Override public String[] erasFull() { return new String[] { "Antis di Kristu", "Dispos di Kristu" }; } @Override public String[] erasShort() { return new String[] { "AK", "DK" }; } @Override public String formatMonthAbbrevDay() { return "d MMM"; } @Override public String formatMonthFullDay() { return "d 'di' MMMM"; } @Override public String formatMonthFullWeekdayDay() { return "EEEE, d 'di' MMMM"; } @Override public String formatMonthNumDay() { return "d/M"; } @Override public String formatYearMonthAbbrev() { return "MMM 'di' y"; } @Override public String formatYearMonthAbbrevDay() { return "d 'di' MMM 'di' y"; } @Override public String formatYearMonthFull() { return "MMMM 'di' y"; } @Override public String formatYearMonthFullDay() { return "d 'di' MMMM 'di' y"; } @Override public String formatYearMonthNum() { return "MM/y"; } @Override public String formatYearMonthWeekdayDay() { return "EEE, d 'di' MMM 'di' y"; } @Override public String formatYearQuarterFull() { return "QQQQ y"; } @Override public String formatYearQuarterShort() { return "Q y"; } @Override public String[] monthsFull() { return new String[] { "Janeru", "Fevereru", "Marsu", "Abril", "Maiu", "Junhu", "Julhu", "Agostu", "Setenbru", "Otubru", "Nuvenbru", "Dizenbru" }; } @Override public String[] monthsShort() { return new String[] { "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Otu", "Nuv", "Diz" }; } @Override public String[] quartersFull() { return new String[] { "Primeru Trimestri", "Sigundu Trimestri", "Terseru Trimestri", "Kuartu Trimestri" }; } @Override public String[] quartersShort() { return new String[] { "T1", "T2", "T3", "T4" }; } @Override public String[] weekdaysFull() { return new String[] { "dumingu", "sigunda-fera", "tersa-fera", "kuarta-fera", "kinta-fera", "sesta-fera", "sabadu" }; } @Override public String[] weekdaysNarrow() { return new String[] { "d", "s", "t", "k", "k", "s", "s" }; } @Override public String[] weekdaysShort() { return new String[] { "dum", "sig", "ter", "kua", "kin", "ses", "sab" }; } }
Rushera/passwdsafe
lib-box/src/main/java/com/box/androidsdk/content/BoxFutureTask.java
package com.box.androidsdk.content; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import com.box.androidsdk.content.models.BoxObject; import com.box.androidsdk.content.requests.BoxRequest; import com.box.androidsdk.content.requests.BoxResponse; /** * * @param <E> * - entity type returned from request */ public class BoxFutureTask<E extends BoxObject> extends FutureTask<BoxResponse<E>> { protected final BoxRequest mRequest; protected ArrayList<OnCompletedListener<E>> mCompletedListeners = new ArrayList<OnCompletedListener<E>>(); public BoxFutureTask(final Class<E> clazz, final BoxRequest request) { super(new Callable<BoxResponse<E>>() { @Override public BoxResponse<E> call() throws Exception { E ret = null; Exception ex = null; try { ret = (E) request.send(); } catch (Exception e) { ex = e; } return new BoxResponse<E>(ret, ex, request); } }); mRequest = request; } @Override protected void done() { BoxResponse<E> response = null; Exception ex = null; try { response = this.get(); } catch (InterruptedException e) { ex = e; } catch (ExecutionException e) { ex = e; } if (ex != null) { response = new BoxResponse<E>(null, new BoxException("Unable to retrieve response from FutureTask.", ex), mRequest); } ArrayList<OnCompletedListener<E>> listener = getCompletionListeners(); for (OnCompletedListener<E> l : listener) { l.onCompleted(response); } } public ArrayList<OnCompletedListener<E>> getCompletionListeners() { return mCompletedListeners; } @SuppressWarnings("unchecked") public BoxFutureTask<E> addOnCompletedListener(OnCompletedListener<E> listener) { mCompletedListeners.add(listener); return this; } public interface OnCompletedListener<E extends BoxObject> { public void onCompleted(BoxResponse<E> response); } }
dhendrix/mosys
platform/reef/reef.c
/* * Copyright 2016, Google 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 Google Inc. 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <unistd.h> #include "mosys/alloc.h" #include "mosys/command_list.h" #include "mosys/platform.h" #include "mosys/intf_list.h" #include "mosys/log.h" #include "drivers/google/cros_ec.h" #include "lib/probe.h" #include "lib/sku.h" #include "lib/smbios.h" #include "lib/elog.h" #include "reef.h" /* sku_info: brand, model, chassis, customization */ static struct sku_info /* Reef SKUs */ /* TODO(hungte) Reef firmware updater was using 'reef' as model name * for Electro and Basking. We should remove the 'reef' below when * updater configuration is corrected. */ SKU_ELECTRO = { .brand = "ACBB", .model = "reef", .chassis = "ELECTRO"}, SKU_BASKING = { .brand = "ASUN", .model = "reef", .chassis = "BASKING"}, /* Coral SKUs */ /* TODO(hungte) Fill the brand code when they are assigned. */ SKU_ASTRONAUT = { .brand = NULL, .model = "astronaut", }, SKU_SANTA = { .brand = NULL, .model = "santa", }, SKU_LAVA = { .brand = NULL, .model = "lava", }, SKU_BLUE = { .brand = NULL, .model = "blue", }, SKU_BRUCE = { .brand = NULL, .model = "bruce", }, SKU_PORBEAGLE = { .brand = NULL, .model = "porbeagle", }, SKU_ROBO = { .brand = NULL, .model = "robo", }, SKU_WHITETIP = { .brand = NULL, .model = "whitetip", }, SKU_NASHER = { .brand = NULL, .model = "nasher", }; /* Reference: b/35583395 */ static struct sku_mapping reef_sku_table[] = { {0, &SKU_BASKING}, {8, &SKU_ELECTRO}, {SKU_NUMBER_ANY, NULL}, }; /** * TODO(hungte) The mapping table below is made by duplicating for ranges. We do * this for now because it's unclear if most projects will be ranged, or is * sufficient with single or discontinuous values. We can revise this to ranges, * or other data structure in future when we have better idea of how the mapping * table looks like in the end. */ /* Reference: Coral SKU Map */ static struct sku_mapping coral_sku_table[] = { {0, &SKU_ASTRONAUT}, {1, &SKU_ASTRONAUT}, {2, &SKU_SANTA}, {3, &SKU_SANTA}, {4, &SKU_LAVA}, {5, &SKU_LAVA}, {6, &SKU_BLUE}, {7, &SKU_BLUE}, {7, &SKU_BRUCE}, {26, &SKU_PORBEAGLE}, {27, &SKU_PORBEAGLE}, {61, &SKU_ASTRONAUT}, {62, &SKU_ASTRONAUT}, {70, &SKU_ROBO}, {71, &SKU_ROBO}, {126, &SKU_WHITETIP}, {127, &SKU_WHITETIP}, {160, &SKU_NASHER}, {161, &SKU_NASHER}, {162, &SKU_NASHER}, {163, &SKU_NASHER}, {164, &SKU_NASHER}, {165, &SKU_NASHER}, {166, &SKU_NASHER}, {SKU_NUMBER_ANY, NULL}, }; struct probe_ids { const char *names[2]; /** * Devices with SKU-based mapping should define sku_table, * otherwise use single_sku. */ struct sku_mapping *sku_table; const struct sku_info single_sku; }; static const struct probe_ids probe_id_list[] = { { { "Reef", }, .sku_table = reef_sku_table }, { { "Coral", }, .sku_table = coral_sku_table }, { { "Pyro", }, .single_sku = { .brand = "LEAN" } }, { { "Sand", }, }, { { "Snappy", }, .single_sku = { .brand = "HPZO", .model = "snappy" } }, { { NULL }, }, }; struct platform_cmd *reef_sub[] = { &cmd_ec, &cmd_eeprom, &cmd_memory, &cmd_nvram, &cmd_pd, &cmd_platform, &cmd_smbios, &cmd_eventlog, NULL }; int reef_probe(struct platform_intf *intf) { static int status, probed; const struct probe_ids *pid; if (probed) return status; for (pid = probe_id_list; pid && pid->names[0]; pid++) { /* FRID */ if (probe_frid((const char **)pid->names)) { status = 1; goto reef_probe_exit; } /* SMBIOS */ if (probe_smbios(intf, (const char **)pid->names)) { status = 1; goto reef_probe_exit; } } return 0; reef_probe_exit: probed = 1; /* Update canonical platform name */ intf->name = pid->names[0]; if (pid->sku_table) { intf->sku_info = sku_find_info(intf, pid->sku_table); } else { intf->sku_info = &pid->single_sku; } return status; } /* late setup routine; not critical to core functionality */ static int reef_setup_post(struct platform_intf *intf) { if (cros_ec_setup(intf) < 0) return -1; return 0; } static int reef_destroy(struct platform_intf *intf) { return 0; } struct eventlog_cb reef_eventlog_cb = { .print_type = &elog_print_type, .print_data = &elog_print_data, .print_multi = &elog_print_multi, .verify = &elog_verify, .verify_header = &elog_verify_header, .fetch = &elog_fetch_from_smbios, }; struct platform_cb reef_cb = { .ec = &cros_ec_cb, .eeprom = &reef_eeprom_cb, .memory = &reef_memory_cb, .nvram = &reef_nvram_cb, .smbios = &smbios_sysinfo_cb, .sys = &reef_sys_cb, .eventlog = &reef_eventlog_cb, }; struct platform_intf platform_reef = { .type = PLATFORM_X86_64, .name = "Reef", .sub = reef_sub, .cb = &reef_cb, .probe = &reef_probe, .setup_post = &reef_setup_post, .destroy = &reef_destroy, };
togogenome/togogenome
app/controllers/report_type/organisms_controller.rb
class ReportType::OrganismsController < ReportType::BaseController end
cowthan2019/xspring-solo
app/src/main/java/com/danger/app/user/model/RegisterForm.java
package com.danger.app.user.model; import com.danger.common.validator.AccountValue; import com.danger.common.validator.CanNotBeNull; import lombok.Data; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; @Data public class RegisterForm { @CanNotBeNull @AccountValue private String account; @CanNotBeNull @Length(min = 6, max = 20, message = "密码不合法") private String password; @CanNotBeNull @Length(min = 3, max = 7, message = "验证码不合法") private String code; @CanNotBeNull @Range(min = 0, max = 1, message = "登录标志位不合法") private Integer login = 1; }
DarkRTA/bfbbdecomp
src/Core/x/xPartition.cpp
<gh_stars>0 #include "xPartition.h"
jayhyun-hwang/personal-archive
repositories/mock/paragraph_repository_mock.go
<filename>repositories/mock/paragraph_repository_mock.go package mock import "github.com/jaeyo/personal-archive/models" type ParagraphRepositoryMock struct { OnSave func(paragraph *models.Paragraph) error OnGetByIDAndNoteID func(id, noteID int64) (*models.Paragraph, error) OnFindByIDsAndNoteID func(ids []int64, noteID int64) (models.Paragraphs, error) OnDeleteByIDs func(ids []int64) error OnDeleteByIDAndNoteID func(id, noteID int64) error } func (m *ParagraphRepositoryMock) Save(paragraph *models.Paragraph) error { return m.OnSave(paragraph) } func (m *ParagraphRepositoryMock) GetByIDAndNoteID(id, noteID int64) (*models.Paragraph, error) { return m.OnGetByIDAndNoteID(id, noteID) } func (m *ParagraphRepositoryMock) FindByIDsAndNoteID(ids []int64, noteID int64) (models.Paragraphs, error) { return m.OnFindByIDsAndNoteID(ids, noteID) } func (m *ParagraphRepositoryMock) DeleteByIDs(ids []int64) error { return m.OnDeleteByIDs(ids) } func (m *ParagraphRepositoryMock) DeleteByIDAndNoteID(id, noteID int64) error { return m.OnDeleteByIDAndNoteID(id, noteID) }
epfl-lasa/TutorialICRA2018
vendor/ruby/2.3.0/gems/aws-sdk-core-2.10.125/lib/aws-sdk-core/resourcegroupstaggingapi.rb
<gh_stars>1-10 Aws.add_service(:ResourceGroupsTaggingAPI, { api: "#{Aws::API_DIR}/resourcegroupstaggingapi/2017-01-26/api-2.json", docs: "#{Aws::API_DIR}/resourcegroupstaggingapi/2017-01-26/docs-2.json", examples: "#{Aws::API_DIR}/resourcegroupstaggingapi/2017-01-26/examples-1.json", paginators: "#{Aws::API_DIR}/resourcegroupstaggingapi/2017-01-26/paginators-1.json", })
fittner/SiMA
Entity/src/complexbody/io/actuators/actionExecutors/clsExecutorInternalRaiseEyeBrowsCorners.java
/** * CHANGELOG * * Sep 5, 2014 volkan - File created * */ package complexbody.io.actuators.actionExecutors; import body.clsComplexBody; import properties.clsProperties; import complexbody.io.actuators.clsInternalActionExecutor; import complexbody.io.actuators.actionCommands.clsInternalActionCommand; import complexbody.io.actuators.actionCommands.clsInternalActionRaiseEyeBrowsCorners; import entities.abstractEntities.clsEntity; import entities.enums.eBodyParts; import body.itfget.itfGetBody; /** * DOCUMENT (volkan) - insert description * * @author volkan * Sep 5, 2014, 5:44:22 PM * */ public class clsExecutorInternalRaiseEyeBrowsCorners extends clsInternalActionExecutor { static double srStaminaDemand = 0; //0.5f; //Stamina demand ? // class variables private clsEntity moEntity; /** * DOCUMENT (volkan) - insert description * * @since Sep 5, 2014 5:47:00 PM * * @param poPrefix * @param poProp */ public clsExecutorInternalRaiseEyeBrowsCorners(String poPrefix, clsProperties poProp, clsEntity poEntity) { super(poPrefix, poProp); moEntity = poEntity; applyProperties(poPrefix, poProp); } public static clsProperties getDefaultProperties(String poPrefix) { String pre = clsProperties.addDot(poPrefix); clsProperties oProp = clsInternalActionExecutor.getDefaultProperties(pre); return oProp; } private void applyProperties(String poPrefix, clsProperties poProp) { String pre = clsProperties.addDot(poPrefix); } /* (non-Javadoc) * * @since Sep 5, 2014 5:45:43 PM * * @see bw.body.io.actuators.clsInternalActionExecutor#setBodyPartId() */ @Override protected void setBodyPartId() { // TODO (volkan) - Auto-generated method stub mePartId = eBodyParts.ACTIONINT_FACIAL_CHANGE_EYEBROWS; } /* (non-Javadoc) * * @since Sep 5, 2014 5:45:43 PM * * @see bw.body.io.actuators.clsInternalActionExecutor#setName() */ @Override protected void setName() { // TODO (volkan) - Auto-generated method stub moName="Raise Eye Brow Corners executor"; } /* (non-Javadoc) * * @since Sep 5, 2014 5:45:43 PM * * @see bw.body.io.actuators.clsInternalActionExecutor#getStaminaDemand(du.itf.actions.clsInternalActionCommand) */ @Override public double getStaminaDemand(clsInternalActionCommand poCommand) { // TODO (volkan) - Auto-generated method stub return srStaminaDemand; } /* (non-Javadoc) * * @since Sep 5, 2014 5:45:43 PM * * @see bw.body.io.actuators.clsInternalActionExecutor#execute(du.itf.actions.clsInternalActionCommand) */ @Override public boolean execute(clsInternalActionCommand poCommand) { clsComplexBody oBody = (clsComplexBody) ((itfGetBody)moEntity).getBody(); clsInternalActionRaiseEyeBrowsCorners oCommand =(clsInternalActionRaiseEyeBrowsCorners) poCommand; // 1. Affect the body oBody.getIntraBodySystem().getFacialExpression().getBOFacialEyeBrows().changeEyeBrowsCorners( oCommand.getEyeBrowsCornersRaise() ); return true; } }
rocious/omaha
third_party/lzma/v4_65/files/CPP/7zip/UI/Common/LoadCodecs.cpp
<reponame>rocious/omaha // LoadCodecs.cpp #include "StdAfx.h" #include "LoadCodecs.h" #include "../../../Common/MyCom.h" #ifdef NEW_FOLDER_INTERFACE #include "../../../Common/StringToInt.h" #endif #include "../../../Windows/PropVariant.h" #include "../../ICoder.h" #include "../../Common/RegisterArc.h" #ifdef EXTERNAL_CODECS #include "../../../Windows/FileFind.h" #include "../../../Windows/DLL.h" #ifdef NEW_FOLDER_INTERFACE #include "../../../Windows/ResourceString.h" static const UINT kIconTypesResId = 100; #endif #ifdef _WIN32 #include "Windows/Registry.h" #endif using namespace NWindows; using namespace NFile; #ifdef _WIN32 extern HINSTANCE g_hInstance; #endif static CSysString GetLibraryFolderPrefix() { #ifdef _WIN32 TCHAR fullPath[MAX_PATH + 1]; ::GetModuleFileName(g_hInstance, fullPath, MAX_PATH); CSysString path = fullPath; int pos = path.ReverseFind(TEXT(CHAR_PATH_SEPARATOR)); return path.Left(pos + 1); #else return CSysString(); // FIX IT #endif } #define kCodecsFolderName TEXT("Codecs") #define kFormatsFolderName TEXT("Formats") static const TCHAR *kMainDll = TEXT("7z.dll"); #ifdef _WIN32 static LPCTSTR kRegistryPath = TEXT("Software") TEXT(STRING_PATH_SEPARATOR) TEXT("7-zip"); static LPCTSTR kProgramPathValue = TEXT("Path"); static bool ReadPathFromRegistry(HKEY baseKey, CSysString &path) { NRegistry::CKey key; if(key.Open(baseKey, kRegistryPath, KEY_READ) == ERROR_SUCCESS) if (key.QueryValue(kProgramPathValue, path) == ERROR_SUCCESS) { NName::NormalizeDirPathPrefix(path); return true; } return false; } #endif CSysString GetBaseFolderPrefixFromRegistry() { CSysString moduleFolderPrefix = GetLibraryFolderPrefix(); NFind::CFileInfo fi; if (NFind::FindFile(moduleFolderPrefix + kMainDll, fi)) if (!fi.IsDir()) return moduleFolderPrefix; if (NFind::FindFile(moduleFolderPrefix + kCodecsFolderName, fi)) if (fi.IsDir()) return moduleFolderPrefix; if (NFind::FindFile(moduleFolderPrefix + kFormatsFolderName, fi)) if (fi.IsDir()) return moduleFolderPrefix; #ifdef _WIN32 CSysString path; if (ReadPathFromRegistry(HKEY_CURRENT_USER, path)) return path; if (ReadPathFromRegistry(HKEY_LOCAL_MACHINE, path)) return path; #endif return moduleFolderPrefix; } typedef UInt32 (WINAPI *GetNumberOfMethodsFunc)(UInt32 *numMethods); typedef UInt32 (WINAPI *GetNumberOfFormatsFunc)(UInt32 *numFormats); typedef UInt32 (WINAPI *GetHandlerPropertyFunc)(PROPID propID, PROPVARIANT *value); typedef UInt32 (WINAPI *GetHandlerPropertyFunc2)(UInt32 index, PROPID propID, PROPVARIANT *value); typedef UInt32 (WINAPI *CreateObjectFunc)(const GUID *clsID, const GUID *iid, void **outObject); typedef UInt32 (WINAPI *SetLargePageModeFunc)(); static HRESULT GetCoderClass(GetMethodPropertyFunc getMethodProperty, UInt32 index, PROPID propId, CLSID &clsId, bool &isAssigned) { NWindows::NCOM::CPropVariant prop; isAssigned = false; RINOK(getMethodProperty(index, propId, &prop)); if (prop.vt == VT_BSTR) { isAssigned = true; clsId = *(const GUID *)prop.bstrVal; } else if (prop.vt != VT_EMPTY) return E_FAIL; return S_OK; } HRESULT CCodecs::LoadCodecs() { CCodecLib &lib = Libs.Back(); lib.GetMethodProperty = (GetMethodPropertyFunc)lib.Lib.GetProcAddress("GetMethodProperty"); if (lib.GetMethodProperty == NULL) return S_OK; UInt32 numMethods = 1; GetNumberOfMethodsFunc getNumberOfMethodsFunc = (GetNumberOfMethodsFunc)lib.Lib.GetProcAddress("GetNumberOfMethods"); if (getNumberOfMethodsFunc != NULL) { RINOK(getNumberOfMethodsFunc(&numMethods)); } for(UInt32 i = 0; i < numMethods; i++) { CDllCodecInfo info; info.LibIndex = Libs.Size() - 1; info.CodecIndex = i; RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kEncoder, info.Encoder, info.EncoderIsAssigned)); RINOK(GetCoderClass(lib.GetMethodProperty, i, NMethodPropID::kDecoder, info.Decoder, info.DecoderIsAssigned)); Codecs.Add(info); } return S_OK; } static HRESULT ReadProp( GetHandlerPropertyFunc getProp, GetHandlerPropertyFunc2 getProp2, UInt32 index, PROPID propID, NCOM::CPropVariant &prop) { if (getProp2) return getProp2(index, propID, &prop);; return getProp(propID, &prop); } static HRESULT ReadBoolProp( GetHandlerPropertyFunc getProp, GetHandlerPropertyFunc2 getProp2, UInt32 index, PROPID propID, bool &res) { NCOM::CPropVariant prop; RINOK(ReadProp(getProp, getProp2, index, propID, prop)); if (prop.vt == VT_BOOL) res = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) return E_FAIL; return S_OK; } static HRESULT ReadStringProp( GetHandlerPropertyFunc getProp, GetHandlerPropertyFunc2 getProp2, UInt32 index, PROPID propID, UString &res) { NCOM::CPropVariant prop; RINOK(ReadProp(getProp, getProp2, index, propID, prop)); if (prop.vt == VT_BSTR) res = prop.bstrVal; else if (prop.vt != VT_EMPTY) return E_FAIL; return S_OK; } #endif static const unsigned int kNumArcsMax = 32; static unsigned int g_NumArcs = 0; static const CArcInfo *g_Arcs[kNumArcsMax]; void RegisterArc(const CArcInfo *arcInfo) { if (g_NumArcs < kNumArcsMax) g_Arcs[g_NumArcs++] = arcInfo; } static void SplitString(const UString &srcString, UStringVector &destStrings) { destStrings.Clear(); UString s; int len = srcString.Length(); if (len == 0) return; for (int i = 0; i < len; i++) { wchar_t c = srcString[i]; if (c == L' ') { if (!s.IsEmpty()) { destStrings.Add(s); s.Empty(); } } else s += c; } if (!s.IsEmpty()) destStrings.Add(s); } void CArcInfoEx::AddExts(const wchar_t* ext, const wchar_t* addExt) { UStringVector exts, addExts; SplitString(ext, exts); if (addExt != 0) SplitString(addExt, addExts); for (int i = 0; i < exts.Size(); i++) { CArcExtInfo extInfo; extInfo.Ext = exts[i]; if (i < addExts.Size()) { extInfo.AddExt = addExts[i]; if (extInfo.AddExt == L"*") extInfo.AddExt.Empty(); } Exts.Add(extInfo); } } #ifdef EXTERNAL_CODECS HRESULT CCodecs::LoadFormats() { const NDLL::CLibrary &lib = Libs.Back().Lib; GetHandlerPropertyFunc getProp = 0; GetHandlerPropertyFunc2 getProp2 = (GetHandlerPropertyFunc2) lib.GetProcAddress("GetHandlerProperty2"); if (getProp2 == NULL) { getProp = (GetHandlerPropertyFunc) lib.GetProcAddress("GetHandlerProperty"); if (getProp == NULL) return S_OK; } UInt32 numFormats = 1; GetNumberOfFormatsFunc getNumberOfFormats = (GetNumberOfFormatsFunc) lib.GetProcAddress("GetNumberOfFormats"); if (getNumberOfFormats != NULL) { RINOK(getNumberOfFormats(&numFormats)); } if (getProp2 == NULL) numFormats = 1; for(UInt32 i = 0; i < numFormats; i++) { CArcInfoEx item; item.LibIndex = Libs.Size() - 1; item.FormatIndex = i; RINOK(ReadStringProp(getProp, getProp2, i, NArchive::kName, item.Name)); NCOM::CPropVariant prop; if (ReadProp(getProp, getProp2, i, NArchive::kClassID, prop) != S_OK) continue; if (prop.vt != VT_BSTR) continue; item.ClassID = *(const GUID *)prop.bstrVal; prop.Clear(); UString ext, addExt; RINOK(ReadStringProp(getProp, getProp2, i, NArchive::kExtension, ext)); RINOK(ReadStringProp(getProp, getProp2, i, NArchive::kAddExtension, addExt)); item.AddExts(ext, addExt); ReadBoolProp(getProp, getProp2, i, NArchive::kUpdate, item.UpdateEnabled); if (item.UpdateEnabled) ReadBoolProp(getProp, getProp2, i, NArchive::kKeepName, item.KeepName); if (ReadProp(getProp, getProp2, i, NArchive::kStartSignature, prop) == S_OK) if (prop.vt == VT_BSTR) { UINT len = ::SysStringByteLen(prop.bstrVal); item.StartSignature.SetCapacity(len); memmove(item.StartSignature, prop.bstrVal, len); } Formats.Add(item); } return S_OK; } #ifdef NEW_FOLDER_INTERFACE void CCodecLib::LoadIcons() { UString iconTypes = MyLoadStringW((HMODULE)Lib, kIconTypesResId); UStringVector pairs; SplitString(iconTypes, pairs); for (int i = 0; i < pairs.Size(); i++) { const UString &s = pairs[i]; int pos = s.Find(L':'); if (pos < 0) continue; CIconPair iconPair; const wchar_t *end; UString num = s.Mid(pos + 1); iconPair.IconIndex = (UInt32)ConvertStringToUInt64(num, &end); if (*end != L'\0') continue; iconPair.Ext = s.Left(pos); IconPairs.Add(iconPair); } } int CCodecLib::FindIconIndex(const UString &ext) const { for (int i = 0; i < IconPairs.Size(); i++) { const CIconPair &pair = IconPairs[i]; if (ext.CompareNoCase(pair.Ext) == 0) return pair.IconIndex; } return -1; } #endif #ifdef _7ZIP_LARGE_PAGES extern "C" { extern SIZE_T g_LargePageSize; } #endif HRESULT CCodecs::LoadDll(const CSysString &dllPath) { { NDLL::CLibrary library; if (!library.LoadEx(dllPath, LOAD_LIBRARY_AS_DATAFILE)) return S_OK; } Libs.Add(CCodecLib()); CCodecLib &lib = Libs.Back(); #ifdef NEW_FOLDER_INTERFACE lib.Path = dllPath; #endif bool used = false; HRESULT res = S_OK; if (lib.Lib.Load(dllPath)) { #ifdef NEW_FOLDER_INTERFACE lib.LoadIcons(); #endif #ifdef _7ZIP_LARGE_PAGES if (g_LargePageSize != 0) { SetLargePageModeFunc setLargePageMode = (SetLargePageModeFunc)lib.Lib.GetProcAddress("SetLargePageMode"); if (setLargePageMode != 0) setLargePageMode(); } #endif lib.CreateObject = (CreateObjectFunc)lib.Lib.GetProcAddress("CreateObject"); if (lib.CreateObject != 0) { int startSize = Codecs.Size(); res = LoadCodecs(); used = (Codecs.Size() != startSize); if (res == S_OK) { startSize = Formats.Size(); res = LoadFormats(); used = used || (Formats.Size() != startSize); } } } if (!used) Libs.DeleteBack(); return res; } HRESULT CCodecs::LoadDllsFromFolder(const CSysString &folderPrefix) { NFile::NFind::CEnumerator enumerator(folderPrefix + CSysString(TEXT("*"))); NFile::NFind::CFileInfo fi; while (enumerator.Next(fi)) { if (fi.IsDir()) continue; RINOK(LoadDll(folderPrefix + fi.Name)); } return S_OK; } #endif #ifndef _SFX static inline void SetBuffer(CByteBuffer &bb, const Byte *data, int size) { bb.SetCapacity(size); memmove((Byte *)bb, data, size); } #endif HRESULT CCodecs::Load() { Formats.Clear(); #ifdef EXTERNAL_CODECS Codecs.Clear(); #endif for (UInt32 i = 0; i < g_NumArcs; i++) { const CArcInfo &arc = *g_Arcs[i]; CArcInfoEx item; item.Name = arc.Name; item.CreateInArchive = arc.CreateInArchive; item.CreateOutArchive = arc.CreateOutArchive; item.AddExts(arc.Ext, arc.AddExt); item.UpdateEnabled = (arc.CreateOutArchive != 0); item.KeepName = arc.KeepName; #ifndef _SFX SetBuffer(item.StartSignature, arc.Signature, arc.SignatureSize); #endif Formats.Add(item); } #ifdef EXTERNAL_CODECS const CSysString baseFolder = GetBaseFolderPrefixFromRegistry(); RINOK(LoadDll(baseFolder + kMainDll)); RINOK(LoadDllsFromFolder(baseFolder + kCodecsFolderName TEXT(STRING_PATH_SEPARATOR))); RINOK(LoadDllsFromFolder(baseFolder + kFormatsFolderName TEXT(STRING_PATH_SEPARATOR))); #endif return S_OK; } #ifndef _SFX int CCodecs::FindFormatForArchiveName(const UString &arcPath) const { int slashPos1 = arcPath.ReverseFind(WCHAR_PATH_SEPARATOR); int slashPos2 = arcPath.ReverseFind(L'.'); int dotPos = arcPath.ReverseFind(L'.'); if (dotPos < 0 || dotPos < slashPos1 || dotPos < slashPos2) return -1; UString ext = arcPath.Mid(dotPos + 1); for (int i = 0; i < Formats.Size(); i++) { const CArcInfoEx &arc = Formats[i]; if (!arc.UpdateEnabled) continue; // if (arc.FindExtension(ext) >= 0) UString mainExt = arc.GetMainExt(); if (!mainExt.IsEmpty() && ext.CompareNoCase(mainExt) == 0) return i; } return -1; } int CCodecs::FindFormatForExtension(const UString &ext) const { if (ext.IsEmpty()) return -1; for (int i = 0; i < Formats.Size(); i++) if (Formats[i].FindExtension(ext) >= 0) return i; return -1; } int CCodecs::FindFormatForArchiveType(const UString &arcType) const { for (int i = 0; i < Formats.Size(); i++) if (Formats[i].Name.CompareNoCase(arcType) == 0) return i; return -1; } bool CCodecs::FindFormatForArchiveType(const UString &arcType, CIntVector &formatIndices) const { formatIndices.Clear(); for (int pos = 0; pos < arcType.Length();) { int pos2 = arcType.Find('.', pos); if (pos2 < 0) pos2 = arcType.Length(); const UString name = arcType.Mid(pos, pos2 - pos); int index = FindFormatForArchiveType(name); if (index < 0 && name != L"*") { formatIndices.Clear(); return false; } formatIndices.Add(index); pos = pos2 + 1; } return true; } #endif #ifdef EXTERNAL_CODECS #ifdef EXPORT_CODECS extern unsigned int g_NumCodecs; STDAPI CreateCoder2(bool encode, UInt32 index, const GUID *iid, void **outObject); STDAPI GetMethodProperty(UInt32 codecIndex, PROPID propID, PROPVARIANT *value); // STDAPI GetNumberOfMethods(UInt32 *numCodecs); #endif STDMETHODIMP CCodecs::GetNumberOfMethods(UInt32 *numMethods) { *numMethods = #ifdef EXPORT_CODECS g_NumCodecs + #endif Codecs.Size(); return S_OK; } STDMETHODIMP CCodecs::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return GetMethodProperty(index, propID, value); #endif const CDllCodecInfo &ci = Codecs[index #ifdef EXPORT_CODECS - g_NumCodecs #endif ]; if (propID == NMethodPropID::kDecoderIsAssigned) { NWindows::NCOM::CPropVariant propVariant; propVariant = ci.DecoderIsAssigned; propVariant.Detach(value); return S_OK; } if (propID == NMethodPropID::kEncoderIsAssigned) { NWindows::NCOM::CPropVariant propVariant; propVariant = ci.EncoderIsAssigned; propVariant.Detach(value); return S_OK; } return Libs[ci.LibIndex].GetMethodProperty(ci.CodecIndex, propID, value); } STDMETHODIMP CCodecs::CreateDecoder(UInt32 index, const GUID *iid, void **coder) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return CreateCoder2(false, index, iid, coder); #endif const CDllCodecInfo &ci = Codecs[index #ifdef EXPORT_CODECS - g_NumCodecs #endif ]; if (ci.DecoderIsAssigned) return Libs[ci.LibIndex].CreateObject(&ci.Decoder, iid, (void **)coder); return S_OK; } STDMETHODIMP CCodecs::CreateEncoder(UInt32 index, const GUID *iid, void **coder) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return CreateCoder2(true, index, iid, coder); #endif const CDllCodecInfo &ci = Codecs[index #ifdef EXPORT_CODECS - g_NumCodecs #endif ]; if (ci.EncoderIsAssigned) return Libs[ci.LibIndex].CreateObject(&ci.Encoder, iid, (void **)coder); return S_OK; } HRESULT CCodecs::CreateCoder(const UString &name, bool encode, CMyComPtr<ICompressCoder> &coder) const { for (int i = 0; i < Codecs.Size(); i++) { const CDllCodecInfo &codec = Codecs[i]; if (encode && !codec.EncoderIsAssigned || !encode && !codec.DecoderIsAssigned) continue; const CCodecLib &lib = Libs[codec.LibIndex]; UString res; NWindows::NCOM::CPropVariant prop; RINOK(lib.GetMethodProperty(codec.CodecIndex, NMethodPropID::kName, &prop)); if (prop.vt == VT_BSTR) res = prop.bstrVal; else if (prop.vt != VT_EMPTY) continue; if (name.CompareNoCase(res) == 0) return lib.CreateObject(encode ? &codec.Encoder : &codec.Decoder, &IID_ICompressCoder, (void **)&coder); } return CLASS_E_CLASSNOTAVAILABLE; } int CCodecs::GetCodecLibIndex(UInt32 index) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) return -1; #endif #ifdef EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index #ifdef EXPORT_CODECS - g_NumCodecs #endif ]; return ci.LibIndex; #else return -1; #endif } bool CCodecs::GetCodecEncoderIsAssigned(UInt32 index) { #ifdef EXPORT_CODECS if (index < g_NumCodecs) { NWindows::NCOM::CPropVariant prop; if (GetProperty(index, NMethodPropID::kEncoder, &prop) == S_OK) if (prop.vt != VT_EMPTY) return true; return false; } #endif #ifdef EXTERNAL_CODECS const CDllCodecInfo &ci = Codecs[index #ifdef EXPORT_CODECS - g_NumCodecs #endif ]; return ci.EncoderIsAssigned; #else return false; #endif } HRESULT CCodecs::GetCodecId(UInt32 index, UInt64 &id) { UString s; NWindows::NCOM::CPropVariant prop; RINOK(GetProperty(index, NMethodPropID::kID, &prop)); if (prop.vt != VT_UI8) return E_INVALIDARG; id = prop.uhVal.QuadPart; return S_OK; } UString CCodecs::GetCodecName(UInt32 index) { UString s; NWindows::NCOM::CPropVariant prop; if (GetProperty(index, NMethodPropID::kName, &prop) == S_OK) if (prop.vt == VT_BSTR) s = prop.bstrVal; return s; } #endif
DalavanCloud/google-ads-java
google-ads/src/main/java/com/google/ads/googleads/v0/enums/TravelPlaceholderFieldProto.java
<filename>google-ads/src/main/java/com/google/ads/googleads/v0/enums/TravelPlaceholderFieldProto.java // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v0/enums/travel_placeholder_field.proto package com.google.ads.googleads.v0.enums; public final class TravelPlaceholderFieldProto { private TravelPlaceholderFieldProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v0_enums_TravelPlaceholderFieldEnum_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v0_enums_TravelPlaceholderFieldEnum_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n<google/ads/googleads/v0/enums/travel_p" + "laceholder_field.proto\022\035google.ads.googl" + "eads.v0.enums\"\326\003\n\032TravelPlaceholderField" + "Enum\"\267\003\n\026TravelPlaceholderField\022\017\n\013UNSPE" + "CIFIED\020\000\022\013\n\007UNKNOWN\020\001\022\022\n\016DESTINATION_ID\020" + "\002\022\r\n\tORIGIN_ID\020\003\022\t\n\005TITLE\020\004\022\024\n\020DESTINATI" + "ON_NAME\020\005\022\017\n\013ORIGIN_NAME\020\006\022\t\n\005PRICE\020\007\022\023\n" + "\017FORMATTED_PRICE\020\010\022\016\n\nSALE_PRICE\020\t\022\030\n\024FO" + "RMATTED_SALE_PRICE\020\n\022\r\n\tIMAGE_URL\020\013\022\014\n\010C" + "ATEGORY\020\014\022\027\n\023CONTEXTUAL_KEYWORDS\020\r\022\027\n\023DE" + "STINATION_ADDRESS\020\016\022\r\n\tFINAL_URL\020\017\022\025\n\021FI" + "NAL_MOBILE_URLS\020\020\022\020\n\014TRACKING_URL\020\021\022\024\n\020A" + "NDROID_APP_LINK\020\022\022\033\n\027SIMILAR_DESTINATION" + "_IDS\020\023\022\020\n\014IOS_APP_LINK\020\024\022\024\n\020IOS_APP_STOR" + "E_ID\020\025B\360\001\n!com.google.ads.googleads.v0.e" + "numsB\033TravelPlaceholderFieldProtoP\001ZBgoo" + "gle.golang.org/genproto/googleapis/ads/g" + "oogleads/v0/enums;enums\242\002\003GAA\252\002\035Google.A" + "ds.GoogleAds.V0.Enums\312\002\035Google\\Ads\\Googl" + "eAds\\V0\\Enums\352\002!Google::Ads::GoogleAds::" + "V0::Enumsb\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_google_ads_googleads_v0_enums_TravelPlaceholderFieldEnum_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v0_enums_TravelPlaceholderFieldEnum_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v0_enums_TravelPlaceholderFieldEnum_descriptor, new java.lang.String[] { }); } // @@protoc_insertion_point(outer_class_scope) }
zealoussnow/chromium
tools/metrics/histograms/update_net_trust_anchors.py
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Updates NetTrustAnchors enum in histograms.xml file with values read from net/data/ssl/root_stores/root_stores.json. If the file was pretty-printed, the updated version is pretty-printed too. """ from __future__ import print_function import json import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common')) import path_util import update_histogram_enum NET_ROOT_CERTS_PATH = 'net/data/ssl/root_stores/root_stores.json' def main(): if len(sys.argv) > 1: print('No arguments expected!', file=sys.stderr) sys.stderr.write(__doc__) sys.exit(1) with open(path_util.GetInputFile(NET_ROOT_CERTS_PATH)) as f: root_stores = json.load(f) spki_enum = {} spki_enum[0] = 'Unknown or locally-installed trust anchor' for spki, spki_data in sorted(root_stores['spkis'].items()): spki_enum[int(spki_data['id'])] = spki update_histogram_enum.UpdateHistogramFromDict( 'NetTrustAnchors', spki_enum, NET_ROOT_CERTS_PATH, os.path.basename(__file__)) if __name__ == '__main__': main()
Muzammil-khan/Aspose.Email-Python-Dotnet
Examples/WorkingWithMimeMessages/ExtractingEmailHeaders.py
from aspose.email import MailMessage def run(): dataDir = "Data/" #ExStart: ExtractingEmailHeaders # Create MailMessage instance by loading an EML file message = MailMessage.load(dataDir + "email-headers.eml"); print("\n\nheaders:\n\n") # Print out all the headers index = 0 for index, header in enumerate(message.headers): print(header + " - ", end=" ") print (message.headers.get(index)) #ExEnd:ExtractingEmailHeaders if __name__ == '__main__': run()
825245794/JavaCodeExercise2015-2019
src/web/jsouptest.java
<reponame>825245794/JavaCodeExercise2015-2019<gh_stars>0 package web; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * 使用Jsoup模拟登陆Iteye * * * 大体思路如下: * * 第一次请求登陆页面,获取页面信息,包含表单信息,和cookie(这个很重要),拿不到,会模拟登陆不上 * * * 第二次登陆,设置用户名,密码,把第一次的cooking,放进去,即可 * * 怎么确定是否登陆成功? * * 登陆后,打印页面,会看见欢迎xxx,即可证明 * * * @date 2014年6月27日 * @author qindongliang * * * **/ public class jsouptest { static String path = "/Users/LJL/Desktop/img/"; static Connection con; public static void main(String[] args)throws Exception { jsouptest jli=new jsouptest(); con=Jsoup.connect("http://www.cengfan8.com/y/");//获取连接 /*把要下载的图片存档在img文件夹下*/ File dir = new File(path); if(!dir.exists()) dir.mkdir(); /*如果目录不存在则创建目录*/ path +="CheckCode.aspx"; jli.download("http://jw.jluzh.com/CheckCode.aspx",path); //输入的用户名,和密码 } /** * 模拟登陆 * * @param userName 用户名 * @param pwd 密码 * * **/ //获取img标签正则 private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>"; public void connect(){ } public void login(String userName,String pwd,String code)throws Exception{ //第一次请求 con.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");//配置模拟浏览器 Response rs= con.execute();//获取响应 Document d1=Jsoup.parse(rs.body());//转换为Dom树 List<Element> et= d1.select("#form1");//获取form表单,可以通过查看页面源码代码得知 //获取,cooking和表单属性,下面map存放post时的数据 Map<String, String> datas=new HashMap<>(); for(Element e:et.get(0).getAllElements()){ if(e.attr("id").equals("txtUserName")){ e.attr("value", userName);//设置用户名 } if(e.attr("id").equals("TextBox2")){ e.attr("value",pwd); //设置用户密码 } if(e.attr("id").equals("txtSecretCode")){ e.attr("value",code); //设置验证码 } if(e.attr("name").length()>0){//排除空值表单属性 datas.put(e.attr("name"), e.attr("value")); } } /** * 第二次请求,post表单数据,以及cookie信息 * * **/ // Connection con2=Jsoup.connect("http://jw.jluzh.com"); // con2.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"); //设置cookie和post上面的map数据 Response login=con.ignoreContentType(false).method(Method.POST).data(datas).cookies(rs.cookies()).execute(); //打印,登陆成功后的信息 System.out.println(login.body()); //登陆成功后的cookie信息,可以保存到本地,以后登陆时,只需一次登陆即可 Map<String, String> map=login.cookies(); for(String s:map.keySet()){ System.out.println(s+" "+map.get(s)); } } public void download(String strUrl,String path){ URL url = null; try { url = new URL(strUrl); } catch (MalformedURLException e2) { e2.printStackTrace(); return; } InputStream is = null; try { is = url.openStream(); } catch (IOException e1) { e1.printStackTrace(); return; } OutputStream os = null; try{ os = new FileOutputStream(path); int bytesRead = 0; byte[] buffer = new byte[8192]; while((bytesRead = is.read(buffer,0,8192))!=-1){ /*buffer数组存放读取的字节,如果因为流位于文件末尾而没有可用的字节,则返回值-1,以整数形式返回实际读取的字节数*/ os.write(buffer,0,bytesRead); } }catch(FileNotFoundException e){ e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } try { Scanner input=new Scanner(System.in); String code=input.next().trim(); login("04151010", "A21210000+*",code); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private List<String> getImageUrl(String HTML) { Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML); List<String> listImgUrl = new ArrayList<String>(); while (matcher.find()) { listImgUrl.add(matcher.group()); } return listImgUrl; } }
faizol/timescaledb
test/src/test_time_to_internal.c
<reponame>faizol/timescaledb<filename>test/src/test_time_to_internal.c /* * This file and its contents are licensed under the Apache License 2.0. * Please see the included NOTICE for copyright information and * LICENSE-APACHE for a copy of the license. */ #include <postgres.h> #include <fmgr.h> #include <catalog/pg_type.h> #include <utils/date.h> #include "export.h" #include "time_utils.h" #include "utils.h" #include "test_utils.h" TS_FUNCTION_INFO_V1(ts_test_time_to_internal_conversion); TS_FUNCTION_INFO_V1(ts_test_interval_to_internal_conversion); Datum ts_test_time_to_internal_conversion(PG_FUNCTION_ARGS) { int16 i16; int32 i32; int64 i64; /* test integer values */ /* int16 */ for (i16 = -100; i16 < 100; i16++) { TestAssertInt64Eq(i16, ts_time_value_to_internal(Int16GetDatum(i16), INT2OID)); TestAssertInt64Eq(DatumGetInt16(ts_internal_to_time_value(i16, INT2OID)), i16); } TestAssertInt64Eq(PG_INT16_MAX, ts_time_value_to_internal(Int16GetDatum(PG_INT16_MAX), INT2OID)); TestAssertInt64Eq(DatumGetInt16(ts_internal_to_time_value(PG_INT16_MAX, INT2OID)), PG_INT16_MAX); TestAssertInt64Eq(PG_INT16_MIN, ts_time_value_to_internal(Int16GetDatum(PG_INT16_MIN), INT2OID)); TestAssertInt64Eq(DatumGetInt16(ts_internal_to_time_value(PG_INT16_MIN, INT2OID)), PG_INT16_MIN); /* int32 */ for (i32 = -100; i32 < 100; i32++) { TestAssertInt64Eq(i32, ts_time_value_to_internal(Int32GetDatum(i32), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_time_value(i32, INT4OID)), i32); } TestAssertInt64Eq(PG_INT16_MAX, ts_time_value_to_internal(Int32GetDatum(PG_INT16_MAX), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_time_value(PG_INT16_MAX, INT4OID)), PG_INT16_MAX); TestAssertInt64Eq(PG_INT32_MAX, ts_time_value_to_internal(Int32GetDatum(PG_INT32_MAX), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_time_value(PG_INT32_MAX, INT4OID)), PG_INT32_MAX); TestAssertInt64Eq(PG_INT32_MIN, ts_time_value_to_internal(Int32GetDatum(PG_INT32_MIN), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_time_value(PG_INT32_MIN, INT4OID)), PG_INT32_MIN); /* int64 */ for (i64 = -100; i64 < 100; i64++) { TestAssertInt64Eq(i64, ts_time_value_to_internal(Int64GetDatum(i64), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_time_value(i64, INT8OID)), i64); } TestAssertInt64Eq(PG_INT16_MIN, ts_time_value_to_internal(Int64GetDatum(PG_INT16_MIN), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_time_value(PG_INT16_MIN, INT8OID)), PG_INT16_MIN); TestAssertInt64Eq(PG_INT32_MAX, ts_time_value_to_internal(Int64GetDatum(PG_INT32_MAX), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_time_value(PG_INT32_MAX, INT8OID)), PG_INT32_MAX); TestAssertInt64Eq(PG_INT64_MAX, ts_time_value_to_internal(Int64GetDatum(PG_INT64_MAX), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_time_value(PG_INT64_MAX, INT8OID)), PG_INT64_MAX); TestAssertInt64Eq(PG_INT64_MIN, ts_time_value_to_internal(Int64GetDatum(PG_INT64_MIN), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_time_value(PG_INT64_MIN, INT8OID)), PG_INT64_MIN); /* test time values round trip */ /* TIMESTAMP */ for (i64 = -100; i64 < 100; i64++) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, TIMESTAMPOID), TIMESTAMPOID)); for (i64 = -10000000; i64 < 100000000; i64 += 1000000) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, TIMESTAMPOID), TIMESTAMPOID)); for (i64 = -1000000000; i64 < 10000000000; i64 += 100000000) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, TIMESTAMPOID), TIMESTAMPOID)); TestAssertInt64Eq(TS_TIME_NOBEGIN, ts_time_value_to_internal(TimestampGetDatum(DT_NOBEGIN), TIMESTAMPOID)); TestAssertInt64Eq(TS_TIME_NOEND, ts_time_value_to_internal(TimestampGetDatum(DT_NOEND), TIMESTAMPOID)); TestAssertInt64Eq(DT_NOBEGIN, DatumGetTimestamp(ts_internal_to_time_value(PG_INT64_MIN, TIMESTAMPOID))); TestEnsureError(ts_internal_to_time_value(TS_TIMESTAMP_INTERNAL_MIN - 1, TIMESTAMPOID)); TestAssertInt64Eq(TS_TIMESTAMP_INTERNAL_MIN, ts_time_value_to_internal(ts_internal_to_time_value(TS_TIMESTAMP_INTERNAL_MIN, TIMESTAMPOID), TIMESTAMPOID)); TestAssertInt64Eq(DT_NOEND, (ts_time_value_to_internal(ts_internal_to_time_value(PG_INT64_MAX, TIMESTAMPOID), TIMESTAMPOID))); /* TIMESTAMPTZ */ for (i64 = -100; i64 < 100; i64++) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, TIMESTAMPTZOID), TIMESTAMPTZOID)); for (i64 = -10000000; i64 < 100000000; i64 += 1000000) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, TIMESTAMPTZOID), TIMESTAMPTZOID)); for (i64 = -1000000000; i64 < 10000000000; i64 += 100000000) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, TIMESTAMPTZOID), TIMESTAMPTZOID)); TestAssertInt64Eq(TS_TIME_NOBEGIN, ts_time_value_to_internal(TimestampTzGetDatum(DT_NOBEGIN), TIMESTAMPTZOID)); TestAssertInt64Eq(TS_TIME_NOEND, ts_time_value_to_internal(TimestampTzGetDatum(DT_NOEND), TIMESTAMPTZOID)); TestAssertInt64Eq(DT_NOBEGIN, DatumGetTimestampTz(ts_internal_to_time_value(PG_INT64_MIN, TIMESTAMPTZOID))); TestEnsureError(ts_internal_to_time_value(TS_TIMESTAMP_INTERNAL_MIN - 1, TIMESTAMPTZOID)); TestAssertInt64Eq(TS_TIMESTAMP_INTERNAL_MIN, ts_time_value_to_internal(ts_internal_to_time_value(TS_TIMESTAMP_INTERNAL_MIN, TIMESTAMPTZOID), TIMESTAMPTZOID)); TestAssertInt64Eq(DT_NOEND, ts_time_value_to_internal(ts_internal_to_time_value(PG_INT64_MAX, TIMESTAMPTZOID), TIMESTAMPTZOID)); /* DATE */ for (i64 = -100 * USECS_PER_DAY; i64 < 100 * USECS_PER_DAY; i64 += USECS_PER_DAY) TestAssertInt64Eq(i64, ts_time_value_to_internal(ts_internal_to_time_value(i64, DATEOID), DATEOID)); TestAssertInt64Eq(DATEVAL_NOBEGIN, DatumGetDateADT(ts_internal_to_time_value(PG_INT64_MIN, DATEOID))); TestAssertInt64Eq(DATEVAL_NOEND, DatumGetDateADT(ts_internal_to_time_value(PG_INT64_MAX, DATEOID))); TestEnsureError(ts_time_value_to_internal(DateADTGetDatum(DATEVAL_NOBEGIN + 1), DATEOID)); TestEnsureError(ts_time_value_to_internal(DateADTGetDatum(DATEVAL_NOEND - 1), DATEOID)); PG_RETURN_VOID(); }; Datum ts_test_interval_to_internal_conversion(PG_FUNCTION_ARGS) { int16 i16; int32 i32; int64 i64; /* test integer values */ /* int16 */ for (i16 = -100; i16 < 100; i16++) { TestAssertInt64Eq(i16, ts_interval_value_to_internal(Int16GetDatum(i16), INT2OID)); TestAssertInt64Eq(DatumGetInt16(ts_internal_to_interval_value(i16, INT2OID)), i16); } TestAssertInt64Eq(PG_INT16_MAX, ts_interval_value_to_internal(Int16GetDatum(PG_INT16_MAX), INT2OID)); TestAssertInt64Eq(DatumGetInt16(ts_internal_to_interval_value(PG_INT16_MAX, INT2OID)), PG_INT16_MAX); TestAssertInt64Eq(PG_INT16_MIN, ts_interval_value_to_internal(Int16GetDatum(PG_INT16_MIN), INT2OID)); TestAssertInt64Eq(DatumGetInt16(ts_internal_to_interval_value(PG_INT16_MIN, INT2OID)), PG_INT16_MIN); /* int32 */ for (i32 = -100; i32 < 100; i32++) { TestAssertInt64Eq(i32, ts_interval_value_to_internal(Int32GetDatum(i32), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_interval_value(i32, INT4OID)), i32); } TestAssertInt64Eq(PG_INT16_MAX, ts_interval_value_to_internal(Int32GetDatum(PG_INT16_MAX), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_interval_value(PG_INT16_MAX, INT4OID)), PG_INT16_MAX); TestAssertInt64Eq(PG_INT32_MAX, ts_interval_value_to_internal(Int32GetDatum(PG_INT32_MAX), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_interval_value(PG_INT32_MAX, INT4OID)), PG_INT32_MAX); TestAssertInt64Eq(PG_INT32_MIN, ts_interval_value_to_internal(Int32GetDatum(PG_INT32_MIN), INT4OID)); TestAssertInt64Eq(DatumGetInt32(ts_internal_to_interval_value(PG_INT32_MIN, INT4OID)), PG_INT32_MIN); /* int64 */ for (i64 = -100; i64 < 100; i64++) { TestAssertInt64Eq(i64, ts_interval_value_to_internal(Int64GetDatum(i64), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_interval_value(i64, INT8OID)), i64); } TestAssertInt64Eq(PG_INT16_MIN, ts_interval_value_to_internal(Int64GetDatum(PG_INT16_MIN), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_interval_value(PG_INT16_MIN, INT8OID)), PG_INT16_MIN); TestAssertInt64Eq(PG_INT32_MAX, ts_interval_value_to_internal(Int64GetDatum(PG_INT32_MAX), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_interval_value(PG_INT32_MAX, INT8OID)), PG_INT32_MAX); TestAssertInt64Eq(PG_INT64_MAX, ts_interval_value_to_internal(Int64GetDatum(PG_INT64_MAX), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_interval_value(PG_INT64_MAX, INT8OID)), PG_INT64_MAX); TestAssertInt64Eq(PG_INT64_MIN, ts_interval_value_to_internal(Int64GetDatum(PG_INT64_MIN), INT8OID)); TestAssertInt64Eq(DatumGetInt64(ts_internal_to_interval_value(PG_INT64_MIN, INT8OID)), PG_INT64_MIN); /* INTERVAL */ for (i64 = -100; i64 < 100; i64++) TestAssertInt64Eq(i64, ts_interval_value_to_internal(ts_internal_to_interval_value(i64, INTERVALOID), INTERVALOID)); for (i64 = -10000000; i64 < 100000000; i64 += 1000000) TestAssertInt64Eq(i64, ts_interval_value_to_internal(ts_internal_to_interval_value(i64, INTERVALOID), INTERVALOID)); for (i64 = -1000000000; i64 < 10000000000; i64 += 100000000) TestAssertInt64Eq(i64, ts_interval_value_to_internal(ts_internal_to_interval_value(i64, INTERVALOID), INTERVALOID)); TestAssertInt64Eq(PG_INT64_MIN, ts_interval_value_to_internal(ts_internal_to_interval_value(PG_INT64_MIN, INTERVALOID), INTERVALOID)); TestAssertInt64Eq(PG_INT64_MAX, ts_interval_value_to_internal(ts_internal_to_interval_value(PG_INT64_MAX, INTERVALOID), INTERVALOID)); PG_RETURN_VOID(); }
pdv-ru/ClickHouse
tests/ci/ccache_utils.py
#!/usr/bin/env python3 import logging import time import sys import os import shutil from pathlib import Path import requests from compress_files import decompress_fast, compress_fast DOWNLOAD_RETRIES_COUNT = 5 def dowload_file_with_progress(url, path): logging.info("Downloading from %s to temp path %s", url, path) for i in range(DOWNLOAD_RETRIES_COUNT): try: with open(path, 'wb') as f: response = requests.get(url, stream=True) response.raise_for_status() total_length = response.headers.get('content-length') if total_length is None or int(total_length) == 0: logging.info("No content-length, will download file without progress") f.write(response.content) else: dl = 0 total_length = int(total_length) logging.info("Content length is %ld bytes", total_length) for data in response.iter_content(chunk_size=4096): dl += len(data) f.write(data) if sys.stdout.isatty(): done = int(50 * dl / total_length) percent = int(100 * float(dl) / total_length) eq_str = '=' * done space_str = ' ' * (50 - done) sys.stdout.write(f"\r[{eq_str}{space_str}] {percent}%") sys.stdout.flush() break except Exception as ex: sys.stdout.write("\n") time.sleep(3) logging.info("Exception while downloading %s, retry %s", ex, i + 1) if os.path.exists(path): os.remove(path) else: raise Exception(f"Cannot download dataset from {url}, all retries exceeded") sys.stdout.write("\n") logging.info("Downloading finished") def get_ccache_if_not_exists(path_to_ccache_dir, s3_helper, current_pr_number, temp_path): ccache_name = os.path.basename(path_to_ccache_dir) cache_found = False prs_to_check = [current_pr_number] if current_pr_number != 0: prs_to_check.append(0) for pr_number in prs_to_check: logging.info("Searching cache for pr %s", pr_number) s3_path_prefix = str(pr_number) + "/ccaches" objects = s3_helper.list_prefix(s3_path_prefix) logging.info("Found %s objects for pr", len(objects)) for obj in objects: if ccache_name in obj: logging.info("Found ccache on path %s", obj) url = "https://s3.amazonaws.com/clickhouse-builds/" + obj compressed_cache = os.path.join(temp_path, os.path.basename(obj)) dowload_file_with_progress(url, compressed_cache) path_to_decompress = str(Path(path_to_ccache_dir).parent) if not os.path.exists(path_to_decompress): os.makedirs(path_to_decompress) if os.path.exists(path_to_ccache_dir): shutil.rmtree(path_to_ccache_dir) logging.info("Ccache already exists, removing it") logging.info("Decompressing cache to path %s", path_to_decompress) decompress_fast(compressed_cache, path_to_decompress) logging.info("Files on path %s", os.listdir(path_to_decompress)) cache_found = True break if cache_found: break if not cache_found: logging.info("ccache not found anywhere, cannot download anything :(") if os.path.exists(path_to_ccache_dir): logging.info("But at least we have some local cache") else: logging.info("ccache downloaded") def upload_ccache(path_to_ccache_dir, s3_helper, current_pr_number, temp_path): logging.info("Uploading cache %s for pr %s", path_to_ccache_dir, current_pr_number) ccache_name = os.path.basename(path_to_ccache_dir) compressed_cache_path = os.path.join(temp_path, ccache_name + ".tar.gz") compress_fast(path_to_ccache_dir, compressed_cache_path) s3_path = str(current_pr_number) + "/ccaches/" + os.path.basename(compressed_cache_path) logging.info("Will upload %s to path %s", compressed_cache_path, s3_path) s3_helper.upload_build_file_to_s3(compressed_cache_path, s3_path) logging.info("Upload finished")
LiterDev/liter-react-mobile
app/components/Buttons/CategoryButton.js
<filename>app/components/Buttons/CategoryButton.js /** * CategoryButton.js created by 08liter */ import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import colorRed from '@material-ui/core/colors/red'; import colorBlue from '@material-ui/core/colors/blue'; import colorGreen from '@material-ui/core/colors/green'; import colorYellow from '@material-ui/core/colors/yellow'; const colorWhite = '#fff'; const styles = (theme) => ({ root: { minWidth: theme.minHeight.miniButton.default, minHeight: theme.minWidth.miniButton.default, margin: theme.spacing.unit / 4, paddingTop: 2, paddingBottom: 2, paddingLeft: theme.spacing.unit * 1.5, paddingRight: theme.spacing.unit * 1.5, backgroundColor: colorYellow[800], color: colorWhite, borderRadius: 2, '&:active': { backgroundColor: colorYellow[600], } } }); function CategoryButton(props) { const { classes, onClick, label = '' } = props; return ( <div> <Button className={classes.root} aria-label={'button'} onClick={onClick}> <span className={classes.label}>{`${label}`}</span> </Button> </div> ); } export default withStyles(styles)(CategoryButton);
vascoalramos/misago-deployment
misago/misago/users/tests/test_user_datadownloads_api.py
from ..datadownloads import request_user_data_download from ..test import AuthenticatedUserTestCase class UserDataDownloadsApiTests(AuthenticatedUserTestCase): def setUp(self): super().setUp() self.link = "/api/users/%s/data-downloads/" % self.user.pk def test_get_other_user_exports_anonymous(self): """requests to api fails if user is anonymous""" self.logout_user() response = self.client.get(self.link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You have to sign in to perform this action."} ) def test_get_other_user_exports(self): """requests to api fails if user tries to access other user""" other_user = self.get_superuser() link = "/api/users/%s/data-downloads/" % other_user.pk response = self.client.get(link) self.assertEqual(response.status_code, 403) self.assertEqual( response.json(), {"detail": "You can't see other users data downloads."} ) def test_get_empty_list(self): """api returns empy list""" self.assertFalse(self.user.datadownload_set.exists()) response = self.client.get(self.link) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), []) def test_populated_list(self): """api returns list""" for _ in range(6): request_user_data_download(self.user) self.assertTrue(self.user.datadownload_set.exists()) response = self.client.get(self.link) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json()), 5)
safiulanik/problem-solving
LeetCode/linked-list/5-remove-nth-node-from-end-of-list.py
<gh_stars>0 """ URL: https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1296/ Problem Statement: ------------------ Given the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Input: head = [1,2], n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz Follow up: Could you do this in one pass? """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: first = second = ListNode() first.next = head for i in range(n + 1): first = first.next if first is None: return head.next while first is not None: first = first.next second = second.next second.next = second.next.next return head
jingcao80/Elastos
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/backup/CFullBackupDataOutput.cpp
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "elastos/droid/app/backup/CFullBackupDataOutput.h" #include "elastos/droid/app/backup/CBackupDataOutput.h" using Elastos::Droid::App::Backup::CBackupDataOutput; using Elastos::Droid::App::Backup::IBackupDataOutput; namespace Elastos { namespace Droid { namespace App { namespace Backup { CAR_INTERFACE_IMPL(CFullBackupDataOutput, Object, IFullBackupDataOutput) CAR_OBJECT_IMPL(CFullBackupDataOutput) ECode CFullBackupDataOutput::constructor( /* [in] */ IParcelFileDescriptor* fdes) { assert(fdes != NULL); AutoPtr<IFileDescriptor> fd; fdes->GetFileDescriptor((IFileDescriptor**)&fd); return CBackupDataOutput::New(fd, (IBackupDataOutput**)&mData); } ECode CFullBackupDataOutput::GetData( /* [out] */ IBackupDataOutput** data) { *data = mData; REFCOUNT_ADD(*data); return NOERROR; } } // namespace Backup } // namespace App } // namespace Droid } // namespace Elastos
nikitavlaev/embox
src/tests/stdlib/strchrnul_test.c
<gh_stars>100-1000 /** * @file * @brief Testing strchrnul function * * @author <NAME> * @date 27.03.2020 */ #include <string.h> #include <embox/test.h> EMBOX_TEST_SUITE("strchrnulnul testing suite"); TEST_CASE("strchrnul should be able to find every character") { const char *str = "abcdefghijklmnopqrstuvwxyz"; int length = strlen(str); int i; for (i = 0; i < length; ++i) { test_assert_equal(&str[i], strchrnul(str, str[i])); } } TEST_CASE("strchrnul should return end of string char") { const char *str = "abc"; test_assert_equal(str + 3, strchrnul("abc", 'd')); test_assert_equal(str + 3, strchrnul("abc", 'e')); test_assert_equal(str + 3, strchrnul("abc", 'f')); } TEST_CASE("strchrnul should find null terminator of a string") { const char *str1 = "abc"; const char *str2 = "abcd"; const char *str3 = "abcdf"; test_assert_equal(str1 + 3, strchrnul(str1, '\0')); test_assert_equal(str2 + 4, strchrnul(str2, '\0')); test_assert_equal(str3 + 5, strchrnul(str3, '\0')); } TEST_CASE("strchrnul should find first occurency of character") { const char *str1 = "aaaabbbb"; const char *str2 = "abababab"; const char *str3 = "abcddcba"; test_assert_equal(str1, strchrnul(str1, 'a')); test_assert_equal(str2 + 1, strchrnul(str2, 'b')); test_assert_equal(str3 + 3, strchrnul(str3, 'd')); }
kelu124/pyS3
org/apache/poi/hssf/usermodel/HSSFPalette.java
<reponame>kelu124/pyS3 package org.apache.poi.hssf.usermodel; import java.util.Locale; import org.apache.poi.hssf.record.PaletteRecord; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.HSSFColor.AUTOMATIC; public final class HSSFPalette { private PaletteRecord _palette; private static final class CustomColor extends HSSFColor { private byte _blue; private short _byteOffset; private byte _green; private byte _red; public CustomColor(short byteOffset, byte[] colors) { this(byteOffset, colors[0], colors[1], colors[2]); } private CustomColor(short byteOffset, byte red, byte green, byte blue) { this._byteOffset = byteOffset; this._red = red; this._green = green; this._blue = blue; } public short getIndex() { return this._byteOffset; } public short[] getTriplet() { return new short[]{(short) (this._red & 255), (short) (this._green & 255), (short) (this._blue & 255)}; } public String getHexString() { StringBuffer sb = new StringBuffer(); sb.append(getGnumericPart(this._red)); sb.append(':'); sb.append(getGnumericPart(this._green)); sb.append(':'); sb.append(getGnumericPart(this._blue)); return sb.toString(); } private String getGnumericPart(byte color) { if (color == (byte) 0) { return "0"; } int c = color & 255; String s = Integer.toHexString(c | (c << 8)).toUpperCase(Locale.ROOT); while (s.length() < 4) { s = "0" + s; } return s; } } protected HSSFPalette(PaletteRecord palette) { this._palette = palette; } public HSSFColor getColor(short index) { if (index == (short) 64) { return AUTOMATIC.getInstance(); } byte[] b = this._palette.getColor(index); if (b != null) { return new CustomColor(index, b); } return null; } public HSSFColor getColor(int index) { return getColor((short) index); } public HSSFColor findColor(byte red, byte green, byte blue) { byte[] b = this._palette.getColor(8); short i = (short) 8; while (b != null) { if (b[0] == red && b[1] == green && b[2] == blue) { return new CustomColor(i, b); } i = (short) (i + 1); b = this._palette.getColor(i); } return null; } public HSSFColor findSimilarColor(byte red, byte green, byte blue) { return findSimilarColor(unsignedInt(red), unsignedInt(green), unsignedInt(blue)); } public HSSFColor findSimilarColor(int red, int green, int blue) { HSSFColor result = null; int minColorDistance = Integer.MAX_VALUE; byte[] b = this._palette.getColor(8); short i = (short) 8; while (b != null) { int colorDistance = (Math.abs(red - unsignedInt(b[0])) + Math.abs(green - unsignedInt(b[1]))) + Math.abs(blue - unsignedInt(b[2])); if (colorDistance < minColorDistance) { minColorDistance = colorDistance; result = getColor(i); } i = (short) (i + 1); b = this._palette.getColor(i); } return result; } private int unsignedInt(byte b) { return b & 255; } public void setColorAtIndex(short index, byte red, byte green, byte blue) { this._palette.setColor(index, red, green, blue); } public HSSFColor addColor(byte red, byte green, byte blue) { byte[] b = this._palette.getColor(8); short i = (short) 8; while (i < (short) 64) { if (b == null) { setColorAtIndex(i, red, green, blue); return getColor(i); } i = (short) (i + 1); b = this._palette.getColor(i); } throw new RuntimeException("Could not find free color index"); } }
cliff363825/TwentyFour
01_Language/05_Python/study/lesson_05/07.递归.py
<filename>01_Language/05_Python/study/lesson_05/07.递归.py # 尝试求10的阶乘(10!) # 1! = 1 # 2! = 1*2 = 2 # 3! = 1*2*3 = 6 # 4! = 1*2*3*4 = 24 # print(1*2*3*4*5*6*7*8*9*10) # 创建一个变量保存结果 # n = 10 # for i in range(1,10): # n *= i # print(n) # 创建一个函数,可以用来求任意数的阶乘 def factorial(n): ''' 该函数用来求任意数的阶乘 参数: n 要求阶乘的数字 ''' # 创建一个变量,来保存结果 result = n for i in range(1, n): result *= i return result # 求10的阶乘 # print(factorial(20)) # 递归式的函数 # 从前有座山,山里有座庙,庙里有个老和尚讲故事,讲的什么故事呢? # 从前有座山,山里有座庙,庙里有个老和尚讲故事,讲的什么故事呢?.... # 递归简单理解就是自己去引用自己! # 递归式函数,在函数中自己调用自己! # 无穷递归,如果这个函数被调用,程序的内存会溢出,效果类似于死循环 # def fn(): # fn() # fn() # 递归是解决问题的一种方式,它和循环很像 # 它的整体思想是,将一个大问题分解为一个个的小问题,直到问题无法分解时,再去解决问题 # 递归式函数的两个要件 # 1.基线条件 # - 问题可以被分解为的最小问题,当满足基线条件时,递归就不在执行了 # 2.递归条件 # - 将问题继续分解的条件 # 递归和循环类似,基本是可以互相代替的, # 循环编写起来比较容易,阅读起来稍难 # 递归编写起来难,但是方便阅读 # 10! = 10 * 9! # 9! = 9 * 8! # 8! = 8 * 7! # ... # 1! = 1 def factorial(n): ''' 该函数用来求任意数的阶乘 参数: n 要求阶乘的数字 ''' # 基线条件 判断n是否为1,如果为1则此时不能再继续递归 if n == 1: # 1的阶乘就是1,直接返回1 return 1 # 递归条件 return n * factorial(n - 1) # print(factorial(10)) # 练习 # 创建一个函数 power 来为任意数字做幂运算 n ** i # 10 ** 5 = 10 * 10 ** 4 # 10 ** 4 = 10 * 10 ** 3 # ... # 10 ** 1 = 10 def power(n, i): ''' power()用来为任意的数字做幂运算 参数: n 要做幂运算的数字 i 做幂运算的次数 ''' # 基线条件 if i == 1: # 求1次幂 return n # 递归条件 return n * power(n, i - 1) # print(power(8,6)) # # 练习 # 创建一个函数,用来检查一个任意的字符串是否是回文字符串,如果是返回True,否则返回False # 回文字符串,字符串从前往后念和从后往前念是一样的 # abcba # abcdefgfedcba # 先检查第一个字符和最后一个字符是否一致,如果不一致则不是回文字符串 # 如果一致,则看剩余的部分是否是回文字符串 # 检查 abcdefgfedcba 是不是回文 # 检查 bcdefgfedcb 是不是回文 # 检查 cdefgfedc 是不是回文 # 检查 defgfed 是不是回文 # 检查 efgfe 是不是回文 # 检查 fgf 是不是回文 # 检查 g 是不是回文 def hui_wen(s): ''' 该函数用来检查指定的字符串是否回文字符串,如果是返回True,否则返回False 参数: s:就是要检查的字符串 ''' # 基线条件 if len(s) < 2: # 字符串的长度小于2,则字符串一定是回文 return True elif s[0] != s[-1]: # 第一个字符和最后一个字符不相等,不是回文字符串 return False # 递归条件 return hui_wen(s[1:-1]) # def hui_wen(s): # ''' # 该函数用来检查指定的字符串是否回文字符串,如果是返回True,否则返回False # 参数: # s:就是要检查的字符串 # ''' # # 基线条件 # if len(s) < 2 : # # 字符串的长度小于2,则字符串一定是回文 # return True # # 递归条件 # return s[0] == s[-1] and hui_wen(s[1:-1]) print(hui_wen('abcdefgfedcba'))
minhloi/dropbox_api
spec/endpoints/files/upload_session_finish_spec.rb
<gh_stars>100-1000 # frozen_string_literal: true describe DropboxApi::Client, '#upload_session_finish' do before :each do @client = DropboxApi::Client.new end it 'will create a file', cassette: 'upload_session_finish/success' do cursor = @client.upload_session_start('Hello Dropbox!') commit = DropboxApi::Metadata::CommitInfo.new({ 'path' => '/Homework/math/Matrices.txt', 'mode' => :add }) file = @client.upload_session_finish(cursor, commit) expect(file).to be_a(DropboxApi::Metadata::File) expect(file.name).to eq('Matrices.txt') end end
nsnikhil/url-shortener
pkg/store/database.go
<filename>pkg/store/database.go<gh_stars>0 package store import ( "context" "database/sql" "github.com/newrelic/go-agent/v3/newrelic" "go.uber.org/zap" ) type ShortenerDatabase interface { Save(url, urlHash string) error Get(urlHash string) (string, error) } const ( saveQuery = "insert into shortener (url, urlhash) values ($1, $2) on conflict on constraint shortener_url_key do nothing returning id" getURLQuery = "select url from shortener where urlhash = $1" ) type urlShortenerDatabase struct { lgr *zap.Logger db *sql.DB newRelic *newrelic.Application } func (usd *urlShortenerDatabase) Save(url, urlHash string) error { return execQuery(usd.lgr, usd.newRelic, "save", usd.db, saveQuery, url, urlHash) } func (usd *urlShortenerDatabase) Get(urlHash string) (string, error) { return get(getURLQuery, urlHash, usd.db, usd.lgr, usd.newRelic, "getURL") } func execQuery(lgr *zap.Logger, newRelic *newrelic.Application, name string, db *sql.DB, query string, args ...interface{}) error { txn := newRelic.StartTransaction(name) ctx := newrelic.NewContext(context.Background(), txn) _, err := db.ExecContext(ctx, query, args...) if err != nil { lgr.Error(err.Error()) return err } return nil } func get(query, url string, db *sql.DB, lgr *zap.Logger, newRelic *newrelic.Application, name string) (string, error) { var res string var err error txn := newRelic.StartTransaction(name) ctx := newrelic.NewContext(context.Background(), txn) err = db.QueryRowContext(ctx, query, url).Scan(&res) if err != nil { lgr.Error(err.Error()) return "", err } return res, nil } func NewShortenerDatabase(db *sql.DB, lgr *zap.Logger, newRelic *newrelic.Application) ShortenerDatabase { return &urlShortenerDatabase{ db: db, lgr: lgr, newRelic: newRelic, } }
kynk94/torch-firewood
tests/__init__.py
<gh_stars>1-10 import os import sys _TEST_ROOT = os.path.dirname(__file__) _PROJECT_ROOT = os.path.dirname(_TEST_ROOT) sys.path.append(os.path.join(_TEST_ROOT, "stylegan3"))
lendlsmith/wagtail-cookiecutter-foundation
{{cookiecutter.project_slug}}/utils/templatetags/settings_tags.py
<reponame>lendlsmith/wagtail-cookiecutter-foundation from django import template from django.conf import settings register = template.Library() @register.simple_tag def get_ga_key(): return getattr(settings, 'GOOGLE_ANALYTICS_KEY', "") @register.simple_tag def get_google_maps_key(): return getattr(settings, 'GOOGLE_MAPS_KEY', "") @register.simple_tag def get_dynamic_map_url(): return getattr(settings, 'DYNAMIC_MAP_URL', "") @register.simple_tag def get_static_map_url(): return getattr(settings, 'STATIC_MAP_URL', "")
getkloudi/integration-wrapper-generator
out/amazon_ec2/dist/model/Image.js
<reponame>getkloudi/integration-wrapper-generator "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _ApiClient = _interopRequireDefault(require("../ApiClient")); var _ArchitectureValues = _interopRequireDefault(require("./ArchitectureValues")); var _BlockDeviceMapping = _interopRequireDefault(require("./BlockDeviceMapping")); var _DeviceType = _interopRequireDefault(require("./DeviceType")); var _HypervisorType = _interopRequireDefault(require("./HypervisorType")); var _ImageState = _interopRequireDefault(require("./ImageState")); var _ImageTypeValues = _interopRequireDefault(require("./ImageTypeValues")); var _PlatformValues = _interopRequireDefault(require("./PlatformValues")); var _ProductCode = _interopRequireDefault(require("./ProductCode")); var _StateReason = _interopRequireDefault(require("./StateReason")); var _Tag = _interopRequireDefault(require("./Tag")); var _VirtualizationType = _interopRequireDefault(require("./VirtualizationType")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * The Image model module. * @module model/Image * @version 1.1.0 */ var Image = /*#__PURE__*/ function () { /** * Constructs a new <code>Image</code>. * Describes an image. * @alias module:model/Image */ function Image() { _classCallCheck(this, Image); Image.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ _createClass(Image, null, [{ key: "initialize", value: function initialize(obj) {} /** * Constructs a <code>Image</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/Image} obj Optional instance to populate. * @return {module:model/Image} The populated <code>Image</code> instance. */ }, { key: "constructFromObject", value: function constructFromObject(data, obj) { if (data) { obj = obj || new Image(); if (data.hasOwnProperty('Architecture')) { obj['Architecture'] = _ArchitectureValues["default"].constructFromObject(data['Architecture']); } if (data.hasOwnProperty('BlockDeviceMappings')) { obj['BlockDeviceMappings'] = _ApiClient["default"].convertToType(data['BlockDeviceMappings'], [_BlockDeviceMapping["default"]]); } if (data.hasOwnProperty('CreationDate')) { obj['CreationDate'] = _ApiClient["default"].convertToType(data['CreationDate'], 'String'); } if (data.hasOwnProperty('Description')) { obj['Description'] = _ApiClient["default"].convertToType(data['Description'], 'String'); } if (data.hasOwnProperty('EnaSupport')) { obj['EnaSupport'] = _ApiClient["default"].convertToType(data['EnaSupport'], 'Boolean'); } if (data.hasOwnProperty('Hypervisor')) { obj['Hypervisor'] = _HypervisorType["default"].constructFromObject(data['Hypervisor']); } if (data.hasOwnProperty('ImageId')) { obj['ImageId'] = _ApiClient["default"].convertToType(data['ImageId'], 'String'); } if (data.hasOwnProperty('ImageLocation')) { obj['ImageLocation'] = _ApiClient["default"].convertToType(data['ImageLocation'], 'String'); } if (data.hasOwnProperty('ImageOwnerAlias')) { obj['ImageOwnerAlias'] = _ApiClient["default"].convertToType(data['ImageOwnerAlias'], 'String'); } if (data.hasOwnProperty('ImageType')) { obj['ImageType'] = _ImageTypeValues["default"].constructFromObject(data['ImageType']); } if (data.hasOwnProperty('KernelId')) { obj['KernelId'] = _ApiClient["default"].convertToType(data['KernelId'], 'String'); } if (data.hasOwnProperty('Name')) { obj['Name'] = _ApiClient["default"].convertToType(data['Name'], 'String'); } if (data.hasOwnProperty('OwnerId')) { obj['OwnerId'] = _ApiClient["default"].convertToType(data['OwnerId'], 'String'); } if (data.hasOwnProperty('Platform')) { obj['Platform'] = _PlatformValues["default"].constructFromObject(data['Platform']); } if (data.hasOwnProperty('ProductCodes')) { obj['ProductCodes'] = _ApiClient["default"].convertToType(data['ProductCodes'], [_ProductCode["default"]]); } if (data.hasOwnProperty('Public')) { obj['Public'] = _ApiClient["default"].convertToType(data['Public'], 'Boolean'); } if (data.hasOwnProperty('RamdiskId')) { obj['RamdiskId'] = _ApiClient["default"].convertToType(data['RamdiskId'], 'String'); } if (data.hasOwnProperty('RootDeviceName')) { obj['RootDeviceName'] = _ApiClient["default"].convertToType(data['RootDeviceName'], 'String'); } if (data.hasOwnProperty('RootDeviceType')) { obj['RootDeviceType'] = _DeviceType["default"].constructFromObject(data['RootDeviceType']); } if (data.hasOwnProperty('SriovNetSupport')) { obj['SriovNetSupport'] = _ApiClient["default"].convertToType(data['SriovNetSupport'], 'String'); } if (data.hasOwnProperty('State')) { obj['State'] = _ImageState["default"].constructFromObject(data['State']); } if (data.hasOwnProperty('StateReason')) { obj['StateReason'] = _StateReason["default"].constructFromObject(data['StateReason']); } if (data.hasOwnProperty('Tags')) { obj['Tags'] = _ApiClient["default"].convertToType(data['Tags'], [_Tag["default"]]); } if (data.hasOwnProperty('VirtualizationType')) { obj['VirtualizationType'] = _VirtualizationType["default"].constructFromObject(data['VirtualizationType']); } } return obj; } }]); return Image; }(); /** * @member {module:model/ArchitectureValues} Architecture */ Image.prototype['Architecture'] = undefined; /** * @member {Array.<module:model/BlockDeviceMapping>} BlockDeviceMappings */ Image.prototype['BlockDeviceMappings'] = undefined; /** * @member {String} CreationDate */ Image.prototype['CreationDate'] = undefined; /** * @member {String} Description */ Image.prototype['Description'] = undefined; /** * @member {Boolean} EnaSupport */ Image.prototype['EnaSupport'] = undefined; /** * @member {module:model/HypervisorType} Hypervisor */ Image.prototype['Hypervisor'] = undefined; /** * @member {String} ImageId */ Image.prototype['ImageId'] = undefined; /** * @member {String} ImageLocation */ Image.prototype['ImageLocation'] = undefined; /** * @member {String} ImageOwnerAlias */ Image.prototype['ImageOwnerAlias'] = undefined; /** * @member {module:model/ImageTypeValues} ImageType */ Image.prototype['ImageType'] = undefined; /** * @member {String} KernelId */ Image.prototype['KernelId'] = undefined; /** * @member {String} Name */ Image.prototype['Name'] = undefined; /** * @member {String} OwnerId */ Image.prototype['OwnerId'] = undefined; /** * @member {module:model/PlatformValues} Platform */ Image.prototype['Platform'] = undefined; /** * @member {Array.<module:model/ProductCode>} ProductCodes */ Image.prototype['ProductCodes'] = undefined; /** * @member {Boolean} Public */ Image.prototype['Public'] = undefined; /** * @member {String} RamdiskId */ Image.prototype['RamdiskId'] = undefined; /** * @member {String} RootDeviceName */ Image.prototype['RootDeviceName'] = undefined; /** * @member {module:model/DeviceType} RootDeviceType */ Image.prototype['RootDeviceType'] = undefined; /** * @member {String} SriovNetSupport */ Image.prototype['SriovNetSupport'] = undefined; /** * @member {module:model/ImageState} State */ Image.prototype['State'] = undefined; /** * @member {module:model/StateReason} StateReason */ Image.prototype['StateReason'] = undefined; /** * @member {Array.<module:model/Tag>} Tags */ Image.prototype['Tags'] = undefined; /** * @member {module:model/VirtualizationType} VirtualizationType */ Image.prototype['VirtualizationType'] = undefined; var _default = Image; exports["default"] = _default;
NewSpring/Eli
src/@data/Client/__mocks__/index.js
import { ApolloClient } from 'apollo-client'; import { SchemaLink } from 'apollo-link-schema'; import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools'; import cache from '../cache'; // TODO: flush out with query interface for mocking tests const typeDefs = ` Query { } `; const schema = makeExecutableSchema({ typeDefs }); addMockFunctionsToSchema({ schema }); export default new ApolloClient({ cache, link: new SchemaLink({ schema }), });
ivanmb/cryptomkt-java
src/main/java/com/cryptomkt/api/entity/Rate.java
package com.cryptomkt.api.entity; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; public class Rate implements Serializable { private static final long serialVersionUID = 1; @JsonProperty("market_maker") private String marketMaker; @JsonProperty("market_taker") private String marketTaker; public String getMarketMaker() { return marketMaker; } public void setMarketMaker(String marketMaker) { this.marketMaker = marketMaker; } public String getMarketTaker() { return marketTaker; } public void setMarketTaker(String marketTaker) { this.marketTaker = marketTaker; } @Override public String toString() { return "Rate{" + "marketMaker='" + marketMaker + '\'' + ", marketTaker='" + marketTaker + '\'' + '}'; } }
Jonathas-coder/Local-develop-web---cod3r
fundamentos/usandoLETemLOOP.js
<gh_stars>1-10 for (let i = 0; i < 10; i++){ console.log(i) } console.log('i=', i) // i não será exibido fora do laço porque a variavel let tem escopo de bloco.
cbshuman/Bugger
src/bugger/dataAccessInterface/dao/IcookieAccess.java
package bugger.dataAccessInterface.dao; import bugger.dataModel.serverModel.Cookie; public interface IcookieAccess extends Idao<Cookie> { Cookie CreateNewCookie(String userID); Cookie[] GetUserCookies(String userID); boolean DeleteCookie(String cookieID); }
jnthn/intellij-community
python/testData/inspections/PyTypeCheckerInspection/AgainstMergedTypingProtocols.py
<gh_stars>1-10 from typing import Protocol, Sized class SupportsClose(Protocol): def close(self) -> None: pass class SizedAndClosable(Sized, SupportsClose, Protocol): pass class Resource: def __len__(self) -> int: return 0 def close(self) -> None: pass def close(sized_and_closeable: SizedAndClosable) -> None: print(len(sized_and_closeable)) sized_and_closeable.close() r = Resource() close(r) close(<warning descr="Expected type 'SizedAndClosable', got 'int' instead">1</warning>)
sahilmalik5/angular2
node_modules/angular2-hmr/state.js
<reponame>sahilmalik5/angular2 module.exports = require('./dist/webpack-state');
OpenBEL/openbel-framework
org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/WriteCache.java
<filename>org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/WriteCache.java /** * Copyright (C) 2012-2013 Selventa, Inc. * * This file is part of the OpenBEL Framework. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The OpenBEL Framework is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the OpenBEL Framework. If not, see <http://www.gnu.org/licenses/>. * * Additional Terms under LGPL v3: * * This license does not authorize you and you are prohibited from using the * name, trademarks, service marks, logos or similar indicia of Selventa, Inc., * or, in the discretion of other licensors or authors of the program, the * name, trademarks, service marks, logos or similar indicia of such authors or * licensors, in any marketing or advertising materials relating to your * distribution of the program or any covered product. This restriction does * not waive or limit your obligation to keep intact all copyright notices set * forth in the program as delivered to you. * * If you distribute the program in whole or in part, or any modified version * of the program, and you assume contractual liability to the recipient with * respect to the program or modified version, then you will indemnify the * authors and licensors of the program for any liabilities that these * contractual assumptions directly impose on those licensors and authors. */ package org.openbel.framework.common.external; import static java.util.Collections.unmodifiableSet; import static org.openbel.framework.common.BELUtilities.constrainedHashMap; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Write operation caching mechanism associated with * {@link CachingExternalizable}. * <p> * This caching mechanism should only be used to cache objects of a specific * type. * </p> * * @see ReadCache */ public class WriteCache { private final Map<Integer, Object> cache; private final Map<Object, Integer> keys; private int next = 0; /** * Constructs a write cache. Prefer {@link #WriteCache(int)} to this * constructor. * * @see #WriteCache(int) */ public WriteCache() { cache = new HashMap<Integer, Object>(); keys = new HashMap<Object, Integer>(); } /** * Constructs a write cache with the specified initial capacity. * * @param capacity Initial capacity of the backing map * @see HashMap#HashMap(int) */ public WriteCache(int capacity) { cache = constrainedHashMap(capacity); keys = constrainedHashMap(capacity); } /** * Retrieves a cached object's key. * * @param value {@link Object} whose key should be retrieved * @return {@link Integer} key; may be null if the provided object is not * cached */ public Integer get(Object value) { synchronized (this) { return keys.get(value); } } /** * Caches an object, returning its key. * <p> * If the object has already been cached, its existing key is returned. * </p> * * @param value {@link Object} to cache * @return Non-null {@link Integer} */ public Integer cache(Object value) { synchronized (this) { Integer key = keys.get(value); // Already cached? if (key != null) return key; key = next; cache.put(key, value); keys.put(value, key); next++; return key; } } /** * Returns a read-only view of the cache's contents. * * @return {@link Set} of {@link Entry} objects */ public Set<Entry<Integer, Object>> entries() { synchronized (this) { return unmodifiableSet(cache.entrySet()); } } /** * Returns the number of items cached. * * @return {@code int} */ public int size() { return cache.size(); } }
ales-tsurko/strvct.net
source/apps/Stats/mapping/places/Features.js
<gh_stars>0 "use strict" /* Features */ window.Features = class Features extends BMNode { initPrototype () { this.newSlot("features", null) } init () { super.init() return this } allCoordinates () { const coords = [] // array of points like: [x, y] this.features().forEach((f) => { f.geometry.coordinates.forEach((coordSet) => { coordSet.forEach((coord) => coords.push(coord)) }) }) return coords } featureBounds () { if (!this._featureBounds) { this._featureBounds = this.calcBounds() } return this._featureBounds } calcBounds () { const features = this.features() const coords = this.allCoordinates() const xs = coords.map(p => p[0]) const ys = coords.map(p => p[1]) const x1 = xs.minValue() const x2 = xs.maxValue() const y1 = ys.minValue() const y2 = ys.maxValue() const bounds = Rectangle.clone() bounds.origin().set(x1, y1) bounds.setWidth(x2 - x1, y2 - y1) return bounds } }.initThisClass()
yannicnoller/hydiff
experiments/subjects/time_1/symexe/src/org/joda/time/MutableDateTime.java
/* * Copyright 2001-2013 <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 org.joda.time; import static gov.nasa.jpf.symbc.ChangeAnnotation.*; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Locale; import org.joda.convert.FromString; import org.joda.convert.ToString; import org.joda.time.base.BaseDateTime; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * MutableDateTime is the standard implementation of a modifiable datetime class. * It holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. * <p> * This class uses a Chronology internally. The Chronology determines how the * millisecond instant value is converted into the date time fields. * The default Chronology is <code>ISOChronology</code> which is the agreed * international standard and compatible with the modern Gregorian calendar. * <p> * Each individual field can be accessed in two ways: * <ul> * <li><code>getHourOfDay()</code> * <li><code>hourOfDay().get()</code> * </ul> * The second technique also provides access to other useful methods on the * field: * <ul> * <li>get numeric value * <li>set numeric value * <li>add to numeric value * <li>add to numeric value wrapping with the field * <li>get text value * <li>get short text value * <li>set text value * <li>field maximum value * <li>field minimum value * </ul> * * <p> * MutableDateTime is mutable and not thread-safe, unless concurrent threads * are not invoking mutator methods. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @since 1.0 * @see DateTime */ public class MutableDateTime extends BaseDateTime implements ReadWritableDateTime, Cloneable, Serializable { /** Serialization version */ private static final long serialVersionUID = 2852608688135209575L; /** Rounding is disabled */ public static final int ROUND_NONE = 0; /** Rounding mode as described by {@link DateTimeField#roundFloor} */ public static final int ROUND_FLOOR = 1; /** Rounding mode as described by {@link DateTimeField#roundCeiling} */ public static final int ROUND_CEILING = 2; /** Rounding mode as described by {@link DateTimeField#roundHalfFloor} */ public static final int ROUND_HALF_FLOOR = 3; /** Rounding mode as described by {@link DateTimeField#roundHalfCeiling} */ public static final int ROUND_HALF_CEILING = 4; /** Rounding mode as described by {@link DateTimeField#roundHalfEven} */ public static final int ROUND_HALF_EVEN = 5; /** The field to round on */ private DateTimeField iRoundingField; /** The mode of rounding */ private int iRoundingMode; //----------------------------------------------------------------------- /** * Obtains a {@code MutableDateTime} set to the current system millisecond time * using <code>ISOChronology</code> in the default time zone. * * @return the current date-time, not null * @since 2.0 */ public static MutableDateTime now() { return new MutableDateTime(); } /** * Obtains a {@code MutableDateTime} set to the current system millisecond time * using <code>ISOChronology</code> in the specified time zone. * * @param zone the time zone, not null * @return the current date-time, not null * @since 2.0 */ public static MutableDateTime now(DateTimeZone zone) { if (zone == null) { throw new NullPointerException("Zone must not be null"); } return new MutableDateTime(zone); } /** * Obtains a {@code MutableDateTime} set to the current system millisecond time * using the specified chronology. * * @param chronology the chronology, not null * @return the current date-time, not null * @since 2.0 */ public static MutableDateTime now(Chronology chronology) { if (chronology == null) { throw new NullPointerException("Chronology must not be null"); } return new MutableDateTime(chronology); } //----------------------------------------------------------------------- /** * Parses a {@code MutableDateTime} from the specified string. * <p> * This uses {@link ISODateTimeFormat#dateTimeParser()}. * * @param str the string to parse, not null * @since 2.0 */ @FromString public static MutableDateTime parse(String str) { return parse(str, ISODateTimeFormat.dateTimeParser().withOffsetParsed()); } /** * Parses a {@code MutableDateTime} from the specified string using a formatter. * * @param str the string to parse, not null * @param formatter the formatter to use, not null * @since 2.0 */ public static MutableDateTime parse(String str, DateTimeFormatter formatter) { return formatter.parseDateTime(str).toMutableDateTime(); } //----------------------------------------------------------------------- /** * Constructs an instance set to the current system millisecond time * using <code>ISOChronology</code> in the default time zone. * * @see #now() */ public MutableDateTime() { super(); } /** * Constructs an instance set to the current system millisecond time * using <code>ISOChronology</code> in the specified time zone. * <p> * If the specified time zone is null, the default zone is used. * * @param zone the time zone, null means default zone * @see #now(DateTimeZone) */ public MutableDateTime(DateTimeZone zone) { super(zone); } /** * Constructs an instance set to the current system millisecond time * using the specified chronology. * <p> * If the chronology is null, <code>ISOChronology</code> * in the default time zone is used. * * @param chronology the chronology, null means ISOChronology in default zone * @see #now(Chronology) */ public MutableDateTime(Chronology chronology) { super(chronology); } //----------------------------------------------------------------------- /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using <code>ISOChronology</code> in the default time zone. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public MutableDateTime(long instant) { super(instant); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using <code>ISOChronology</code> in the specified time zone. * <p> * If the specified time zone is null, the default zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public MutableDateTime(long instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using the specified chronology. * <p> * If the chronology is null, <code>ISOChronology</code> * in the default time zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime(long instant, Chronology chronology) { super(instant, chronology); } //----------------------------------------------------------------------- /** * Constructs an instance from an Object that represents a datetime. * <p> * If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used. Otherwise, ISO default is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. * <p> * The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object, null means now * @throws IllegalArgumentException if the instant is invalid */ public MutableDateTime(Object instant) { super(instant, (Chronology) null); } /** * Constructs an instance from an Object that represents a datetime, * forcing the time zone to that specified. * <p> * If the object implies a chronology (such as GregorianCalendar does), * then that chronology will be used, but with the time zone adjusted. * Otherwise, ISO is used in the specified time zone. * If the specified time zone is null, the default zone is used. * Thus if a GregorianCalendar is passed in, the chronology used will * be GJ, but if a Date is passed in the chronology will be ISO. * <p> * The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object, null means now * @param zone the time zone, null means default time zone * @throws IllegalArgumentException if the instant is invalid */ public MutableDateTime(Object instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance from an Object that represents a datetime, * using the specified chronology. * <p> * If the chronology is null, ISO in the default time zone is used. * Any chronology implied by the object (such as GregorianCalendar does) * is ignored. * <p> * The recognised object types are defined in * {@link org.joda.time.convert.ConverterManager ConverterManager} and * include ReadableInstant, String, Calendar and Date. * * @param instant the datetime object, null means now * @param chronology the chronology, null means ISOChronology in default zone * @throws IllegalArgumentException if the instant is invalid */ public MutableDateTime(Object instant, Chronology chronology) { super(instant, DateTimeUtils.getChronology(chronology)); } //----------------------------------------------------------------------- /** * Constructs an instance from datetime field values * using <code>ISOChronology</code> in the default time zone. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } /** * Constructs an instance from datetime field values * using <code>ISOChronology</code> in the specified time zone. * <p> * If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param zone the time zone, null means default time zone */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. * <p> * If the chronology is null, <code>ISOChronology</code> * in the default time zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, chronology); } //----------------------------------------------------------------------- /** * Gets the field used for rounding this instant, returning null if rounding * is not enabled. * * @return the rounding field */ public DateTimeField getRoundingField() { return iRoundingField; } /** * Gets the rounding mode for this instant, returning ROUND_NONE if rounding * is not enabled. * * @return the rounding mode constant */ public int getRoundingMode() { return iRoundingMode; } /** * Sets the status of rounding to use the specified field and ROUND_FLOOR mode. * A null field will disable rounding. * Once set, the instant is then rounded using the new field and mode. * <p> * Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} * to be rounded. This can be used to control the precision of the instant, * for example by setting a rounding field of minuteOfDay, the seconds and * milliseconds will always be zero. * * @param field rounding field or null to disable */ public void setRounding(DateTimeField field) { setRounding(field, MutableDateTime.ROUND_FLOOR); } /** * Sets the status of rounding to use the specified field and mode. * A null field or mode of ROUND_NONE will disable rounding. * Once set, the instant is then rounded using the new field and mode. * <p> * Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} * to be rounded. This can be used to control the precision of the instant, * for example by setting a rounding field of minuteOfDay, the seconds and * milliseconds will always be zero. * * @param field rounding field or null to disable * @param mode rounding mode or ROUND_NONE to disable * @throws IllegalArgumentException if mode is unknown, no exception if field is null */ public void setRounding(DateTimeField field, int mode) { if (field != null && (mode < ROUND_NONE || mode > ROUND_HALF_EVEN)) { throw new IllegalArgumentException("Illegal rounding mode: " + mode); } iRoundingField = (mode == ROUND_NONE ? null : field); iRoundingMode = (field == null ? ROUND_NONE : mode); setMillis(getMillis()); } //----------------------------------------------------------------------- /** * Set the milliseconds of the datetime. * <p> * All changes to the millisecond field occurs via this method. * * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the * datetime to */ public void setMillis(long instant) { switch (iRoundingMode) { case ROUND_NONE: break; case ROUND_FLOOR: instant = iRoundingField.roundFloor(instant); break; case ROUND_CEILING: instant = iRoundingField.roundCeiling(instant); break; case ROUND_HALF_FLOOR: instant = iRoundingField.roundHalfFloor(instant); break; case ROUND_HALF_CEILING: instant = iRoundingField.roundHalfCeiling(instant); break; case ROUND_HALF_EVEN: instant = iRoundingField.roundHalfEven(instant); break; } super.setMillis(instant); } /** * Sets the millisecond instant of this instant from another. * <p> * This method does not change the chronology of this instant, just the * millisecond instant. * * @param instant the instant to use, null means now */ public void setMillis(ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); setMillis(instantMillis); // set via this class not super } //----------------------------------------------------------------------- /** * Add an amount of time to the datetime. * * @param duration the millis to add * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(long duration) { setMillis(FieldUtils.safeAdd(getMillis(), duration)); // set via this class not super } /** * Adds a duration to this instant. * <p> * This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadableDuration duration) { add(duration, 1); } /** * Adds a duration to this instant specifying how many times to add. * <p> * This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadableDuration duration, int scalar) { if (duration != null) { add(FieldUtils.safeMultiply(duration.getMillis(), scalar)); } } /** * Adds a period to this instant. * <p> * This will typically change the value of most fields. * * @param period the period to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadablePeriod period) { add(period, 1); } /** * Adds a period to this instant specifying how many times to add. * <p> * This will typically change the value of most fields. * * @param period the period to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadablePeriod period, int scalar) { if (period != null) { setMillis(getChronology().add(period, getMillis(), scalar)); // set via this class not super } } //----------------------------------------------------------------------- /** * Set the chronology of the datetime. * <p> * All changes to the chronology occur via this method. * * @param chronology the chronology to use, null means ISOChronology in default zone */ public void setChronology(Chronology chronology) { super.setChronology(chronology); } //----------------------------------------------------------------------- /** * Sets the time zone of the datetime, changing the chronology and field values. * <p> * Changing the zone using this method retains the millisecond instant. * The millisecond instant is adjusted in the new zone to compensate. * * chronology. Setting the time zone does not affect the millisecond value * of this instant. * <p> * If the chronology already has this time zone, no change occurs. * * @param newZone the time zone to use, null means default zone * @see #setZoneRetainFields */ public void setZone(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); Chronology chrono = getChronology(); if (chrono.getZone() != newZone) { setChronology(chrono.withZone(newZone)); // set via this class not super } } /** * Sets the time zone of the datetime, changing the chronology and millisecond. * <p> * Changing the zone using this method retains the field values. * The millisecond instant is adjusted in the new zone to compensate. * <p> * If the chronology already has this time zone, no change occurs. * * @param newZone the time zone to use, null means default zone * @see #setZone */ public void setZoneRetainFields(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); if (newZone == originalZone) { return; } long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); setChronology(getChronology().withZone(newZone)); // set via this class not super setMillis(millis); } //----------------------------------------------------------------------- /** * Sets the value of one of the fields of the instant, such as hourOfDay. * * @param type a field type, usually obtained from DateTimeFieldType, not null * @param value the value to set the field to * @throws IllegalArgumentException if the value is null or invalid */ public void set(DateTimeFieldType type, int value) { if (type == null) { throw new IllegalArgumentException("Field must not be null"); } setMillis(type.getField(getChronology()).set(getMillis(), value)); } /** * Adds to the instant specifying the duration and multiple to add. * * @param type a field type, usually obtained from DateTimeFieldType, not null * @param amount the amount to add of this duration * @throws IllegalArgumentException if the value is null or invalid * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(DurationFieldType type, int amount) { if (type == null) { throw new IllegalArgumentException("Field must not be null"); } if (change(true, amount != 0)) { // change added guard setMillis(type.getField(getChronology()).add(getMillis(), amount)); } } //----------------------------------------------------------------------- /** * Set the year to the specified value. * * @param year the year * @throws IllegalArgumentException if the value is invalid */ public void setYear(final int year) { setMillis(getChronology().year().set(getMillis(), year)); } /** * Add a number of years to the date. * * @param years the years to add * @throws IllegalArgumentException if the value is invalid */ public void addYears(final int years) { if (change(true, years != 0)) { // change added guard setMillis(getChronology().years().add(getMillis(), years)); } } //----------------------------------------------------------------------- /** * Set the weekyear to the specified value. * * @param weekyear the weekyear * @throws IllegalArgumentException if the value is invalid */ public void setWeekyear(final int weekyear) { setMillis(getChronology().weekyear().set(getMillis(), weekyear)); } /** * Add a number of weekyears to the date. * * @param weekyears the weekyears to add * @throws IllegalArgumentException if the value is invalid */ public void addWeekyears(final int weekyears) { if (weekyears != 0) { setMillis(getChronology().weekyears().add(getMillis(), weekyears)); } } //----------------------------------------------------------------------- /** * Set the month of the year to the specified value. * * @param monthOfYear the month of the year * @throws IllegalArgumentException if the value is invalid */ public void setMonthOfYear(final int monthOfYear) { setMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); } /** * Add a number of months to the date. * * @param months the months to add * @throws IllegalArgumentException if the value is invalid */ public void addMonths(final int months) { if (change(true, months != 0)) { // change added guard setMillis(getChronology().months().add(getMillis(), months)); } } //----------------------------------------------------------------------- /** * Set the week of weekyear to the specified value. * * @param weekOfWeekyear the week of the weekyear * @throws IllegalArgumentException if the value is invalid */ public void setWeekOfWeekyear(final int weekOfWeekyear) { setMillis(getChronology().weekOfWeekyear().set(getMillis(), weekOfWeekyear)); } /** * Add a number of weeks to the date. * * @param weeks the weeks to add * @throws IllegalArgumentException if the value is invalid */ public void addWeeks(final int weeks) { if (change(true, weeks != 0)) { // change added guard setMillis(getChronology().weeks().add(getMillis(), weeks)); } } //----------------------------------------------------------------------- /** * Set the day of year to the specified value. * * @param dayOfYear the day of the year * @throws IllegalArgumentException if the value is invalid */ public void setDayOfYear(final int dayOfYear) { setMillis(getChronology().dayOfYear().set(getMillis(), dayOfYear)); } /** * Set the day of the month to the specified value. * * @param dayOfMonth the day of the month * @throws IllegalArgumentException if the value is invalid */ public void setDayOfMonth(final int dayOfMonth) { setMillis(getChronology().dayOfMonth().set(getMillis(), dayOfMonth)); } /** * Set the day of week to the specified value. * * @param dayOfWeek the day of the week * @throws IllegalArgumentException if the value is invalid */ public void setDayOfWeek(final int dayOfWeek) { setMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); } /** * Add a number of days to the date. * * @param days the days to add * @throws IllegalArgumentException if the value is invalid */ public void addDays(final int days) { if (change(true, days != 0)) { // change added guard setMillis(getChronology().days().add(getMillis(), days)); } } //----------------------------------------------------------------------- /** * Set the hour of the day to the specified value. * * @param hourOfDay the hour of day * @throws IllegalArgumentException if the value is invalid */ public void setHourOfDay(final int hourOfDay) { setMillis(getChronology().hourOfDay().set(getMillis(), hourOfDay)); } /** * Add a number of hours to the date. * * @param hours the hours to add * @throws IllegalArgumentException if the value is invalid */ public void addHours(final int hours) { if (change(true, hours != 0)) { // change added guard setMillis(getChronology().hours().add(getMillis(), hours)); } } //----------------------------------------------------------------------- /** * Set the minute of the day to the specified value. * * @param minuteOfDay the minute of day * @throws IllegalArgumentException if the value is invalid */ public void setMinuteOfDay(final int minuteOfDay) { setMillis(getChronology().minuteOfDay().set(getMillis(), minuteOfDay)); } /** * Set the minute of the hour to the specified value. * * @param minuteOfHour the minute of hour * @throws IllegalArgumentException if the value is invalid */ public void setMinuteOfHour(final int minuteOfHour) { setMillis(getChronology().minuteOfHour().set(getMillis(), minuteOfHour)); } /** * Add a number of minutes to the date. * * @param minutes the minutes to add * @throws IllegalArgumentException if the value is invalid */ public void addMinutes(final int minutes) { if (change(true, minutes != 0)) { // change added guard setMillis(getChronology().minutes().add(getMillis(), minutes)); } } //----------------------------------------------------------------------- /** * Set the second of the day to the specified value. * * @param secondOfDay the second of day * @throws IllegalArgumentException if the value is invalid */ public void setSecondOfDay(final int secondOfDay) { setMillis(getChronology().secondOfDay().set(getMillis(), secondOfDay)); } /** * Set the second of the minute to the specified value. * * @param secondOfMinute the second of minute * @throws IllegalArgumentException if the value is invalid */ public void setSecondOfMinute(final int secondOfMinute) { setMillis(getChronology().secondOfMinute().set(getMillis(), secondOfMinute)); } /** * Add a number of seconds to the date. * * @param seconds the seconds to add * @throws IllegalArgumentException if the value is invalid */ public void addSeconds(final int seconds) { if (change(true, seconds != 0)) { // change added guard setMillis(getChronology().seconds().add(getMillis(), seconds)); } } //----------------------------------------------------------------------- /** * Set the millis of the day to the specified value. * * @param millisOfDay the millis of day * @throws IllegalArgumentException if the value is invalid */ public void setMillisOfDay(final int millisOfDay) { setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); } /** * Set the millis of the second to the specified value. * * @param millisOfSecond the millis of second * @throws IllegalArgumentException if the value is invalid */ public void setMillisOfSecond(final int millisOfSecond) { setMillis(getChronology().millisOfSecond().set(getMillis(), millisOfSecond)); } /** * Add a number of milliseconds to the date. The implementation of this * method differs from the {@link #add(long)} method in that a * DateTimeField performs the addition. * * @param millis the milliseconds to add * @throws IllegalArgumentException if the value is invalid */ public void addMillis(final int millis) { if (change(true, millis != 0)) { // change added guard setMillis(getChronology().millis().add(getMillis(), millis)); } } //----------------------------------------------------------------------- /** * Set the date from milliseconds. * The time part of this object will be unaffected. * * @param instant an instant to copy the date from, time part ignored * @throws IllegalArgumentException if the value is invalid */ public void setDate(final long instant) { setMillis(getChronology().millisOfDay().set(instant, getMillisOfDay())); } /** * Set the date from another instant. * The time part of this object will be unaffected. * <p> * If the input is a {@code ReadableDateTime} then it is converted to the * same time-zone as this object before using the instant millis. * * @param instant an instant to copy the date from, time part ignored * @throws IllegalArgumentException if the object is invalid */ public void setDate(final ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); if (instant instanceof ReadableDateTime) { ReadableDateTime rdt = (ReadableDateTime) instant; Chronology instantChrono = DateTimeUtils.getChronology(rdt.getChronology()); DateTimeZone zone = instantChrono.getZone(); if (zone != null) { instantMillis = zone.getMillisKeepLocal(getZone(), instantMillis); } } setDate(instantMillis); } /** * Set the date from fields. * The time part of this object will be unaffected. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @throws IllegalArgumentException if the value is invalid */ public void setDate( final int year, final int monthOfYear, final int dayOfMonth) { Chronology c = getChronology(); long instantMidnight = c.getDateTimeMillis(year, monthOfYear, dayOfMonth, 0); setDate(instantMidnight); } //----------------------------------------------------------------------- /** * Set the time from milliseconds. * The date part of this object will be unaffected. * * @param millis an instant to copy the time from, date part ignored * @throws IllegalArgumentException if the value is invalid */ public void setTime(final long millis) { int millisOfDay = ISOChronology.getInstanceUTC().millisOfDay().get(millis); setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); } /** * Set the time from another instant. * The date part of this object will be unaffected. * * @param instant an instant to copy the time from, date part ignored * @throws IllegalArgumentException if the object is invalid */ public void setTime(final ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); Chronology instantChrono = DateTimeUtils.getInstantChronology(instant); DateTimeZone zone = instantChrono.getZone(); if (zone != null) { instantMillis = zone.getMillisKeepLocal(DateTimeZone.UTC, instantMillis); } setTime(instantMillis); } /** * Set the time from fields. * The date part of this object will be unaffected. * * @param hour the hour * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @throws IllegalArgumentException if the value is invalid */ public void setTime( final int hour, final int minuteOfHour, final int secondOfMinute, final int millisOfSecond) { long instant = getChronology().getDateTimeMillis( getMillis(), hour, minuteOfHour, secondOfMinute, millisOfSecond); setMillis(instant); } /** * Set the date and time from fields. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @throws IllegalArgumentException if the value is invalid */ public void setDateTime( final int year, final int monthOfYear, final int dayOfMonth, final int hourOfDay, final int minuteOfHour, final int secondOfMinute, final int millisOfSecond) { long instant = getChronology().getDateTimeMillis( year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); setMillis(instant); } //----------------------------------------------------------------------- /** * Gets the property object for the specified type, which contains many useful methods. * * @param type the field type to get the chronology for * @return the property object * @throws IllegalArgumentException if the field is null or unsupported * @since 1.2 */ public Property property(DateTimeFieldType type) { if (type == null) { throw new IllegalArgumentException("The DateTimeFieldType must not be null"); } DateTimeField field = type.getField(getChronology()); if (field.isSupported() == false) { throw new IllegalArgumentException("Field '" + type + "' is not supported"); } return new Property(this, field); } /** * Get the era property. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the year of a week based year property. * * @return the year of a week based year property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property. * <p> * The values for day of month are defined in {@link DateTimeConstants}. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property. * <p> * The values for day of week are defined in {@link DateTimeConstants}. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } //----------------------------------------------------------------------- /** * Get the hour of day field property * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, getChronology().hourOfDay()); } /** * Get the minute of day property * * @return the minute of day property */ public Property minuteOfDay() { return new Property(this, getChronology().minuteOfDay()); } /** * Get the minute of hour field property * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, getChronology().minuteOfHour()); } /** * Get the second of day property * * @return the second of day property */ public Property secondOfDay() { return new Property(this, getChronology().secondOfDay()); } /** * Get the second of minute field property * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, getChronology().secondOfMinute()); } /** * Get the millis of day property * * @return the millis of day property */ public Property millisOfDay() { return new Property(this, getChronology().millisOfDay()); } /** * Get the millis of second property * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, getChronology().millisOfSecond()); } //----------------------------------------------------------------------- /** * Clone this object without having to cast the returned object. * * @return a clone of the this object. */ public MutableDateTime copy() { return (MutableDateTime) clone(); } //----------------------------------------------------------------------- /** * Clone this object. * * @return a clone of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError("Clone error"); } } /** * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ). * * @return ISO8601 time formatted string. */ @ToString public String toString() { return ISODateTimeFormat.dateTime().print(this); } /** * MutableDateTime.Property binds a MutableDateTime to a * DateTimeField allowing powerful datetime functionality to be easily * accessed. * <p> * The example below shows how to use the property to change the value of a * MutableDateTime object. * <pre> * MutableDateTime dt = new MutableDateTime(1972, 12, 3, 13, 32, 19, 123); * dt.year().add(20); * dt.second().roundFloor().minute().set(10); * </pre> * <p> * MutableDateTime.Propery itself is thread-safe and immutable, but the * MutableDateTime being operated on is not. * * @author <NAME> * @author <NAME> * @since 1.0 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -4481126543819298617L; /** The instant this property is working against */ private MutableDateTime iInstant; /** The field this property is working against */ private DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(MutableDateTime instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Writes the property in a safe serialization format. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(iInstant); oos.writeObject(iField.getType()); } /** * Reads the property from a safe serialization format. */ private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException { iInstant = (MutableDateTime) oos.readObject(); DateTimeFieldType type = (DateTimeFieldType) oos.readObject(); iField = type.getField(iInstant.getChronology()); } //----------------------------------------------------------------------- /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the milliseconds of the datetime that this property is linked to. * * @return the milliseconds */ protected long getMillis() { return iInstant.getMillis(); } /** * Gets the chronology of the datetime that this property is linked to. * * @return the chronology * @since 1.4 */ protected Chronology getChronology() { return iInstant.getChronology(); } /** * Gets the mutable datetime being used. * * @return the mutable datetime */ public MutableDateTime getMutableDateTime() { return iInstant; } //----------------------------------------------------------------------- /** * Adds a value to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#add(long,int) */ public MutableDateTime add(int value) { iInstant.setMillis(getField().add(iInstant.getMillis(), value)); return iInstant; } /** * Adds a value to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#add(long,long) */ public MutableDateTime add(long value) { iInstant.setMillis(getField().add(iInstant.getMillis(), value)); return iInstant; } /** * Adds a value, possibly wrapped, to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#addWrapField */ public MutableDateTime addWrapField(int value) { iInstant.setMillis(getField().addWrapField(iInstant.getMillis(), value)); return iInstant; } //----------------------------------------------------------------------- /** * Sets a value. * * @param value the value to set. * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#set(long,int) */ public MutableDateTime set(int value) { iInstant.setMillis(getField().set(iInstant.getMillis(), value)); return iInstant; } /** * Sets a text value. * * @param text the text value to set * @param locale optional locale to use for selecting a text symbol * @return the mutable datetime being used, so calls can be chained * @throws IllegalArgumentException if the text value isn't valid * @see DateTimeField#set(long,java.lang.String,java.util.Locale) */ public MutableDateTime set(String text, Locale locale) { iInstant.setMillis(getField().set(iInstant.getMillis(), text, locale)); return iInstant; } /** * Sets a text value. * * @param text the text value to set * @return the mutable datetime being used, so calls can be chained * @throws IllegalArgumentException if the text value isn't valid * @see DateTimeField#set(long,java.lang.String) */ public MutableDateTime set(String text) { set(text, null); return iInstant; } //----------------------------------------------------------------------- /** * Round to the lowest whole unit of this field. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundFloor */ public MutableDateTime roundFloor() { iInstant.setMillis(getField().roundFloor(iInstant.getMillis())); return iInstant; } /** * Round to the highest whole unit of this field. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundCeiling */ public MutableDateTime roundCeiling() { iInstant.setMillis(getField().roundCeiling(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field, favoring the floor if * halfway. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfFloor */ public MutableDateTime roundHalfFloor() { iInstant.setMillis(getField().roundHalfFloor(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field, favoring the ceiling if * halfway. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfCeiling */ public MutableDateTime roundHalfCeiling() { iInstant.setMillis(getField().roundHalfCeiling(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field. If halfway, the ceiling * is favored over the floor only if it makes this field's value even. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfEven */ public MutableDateTime roundHalfEven() { iInstant.setMillis(getField().roundHalfEven(iInstant.getMillis())); return iInstant; } } }
mbenson/therian
core/src/test/java/therian/operator/convert/NOPConverterTest.java
<reponame>mbenson/therian /* * Copyright the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package therian.operator.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import org.apache.commons.lang3.reflect.TypeLiteral; import org.junit.Test; import therian.TherianModule; import therian.operation.Convert; import therian.operator.OperatorTest; import therian.testfixture.MetasyntacticVariable; import therian.util.Positions; public class NOPConverterTest extends OperatorTest { private static final TypeLiteral<CharSequence> charSequenceType = new TypeLiteral<CharSequence>() {}; @Override protected TherianModule module() { return TherianModule.create().withOperators(new NOPConverter()); } @Test public void test() { assertEquals("", therianContext.eval(Convert.to(String.class, Positions.readOnly("")))); assertEquals(MetasyntacticVariable.FOO, therianContext.eval(Convert.to(MetasyntacticVariable.class, Positions.readOnly(MetasyntacticVariable.FOO)))); assertEquals(Long.valueOf(100L), therianContext.eval(Convert.to(Long.class, Positions.readOnly(Long.valueOf(100L))))); assertEquals(Boolean.TRUE, therianContext.eval(Convert.to(Boolean.class, Positions.readOnly(Boolean.TRUE)))); assertNull(therianContext.eval(Convert.to(charSequenceType, Positions.readOnly(String.class, (String) null)))); assertEquals("", therianContext.eval(Convert.to(charSequenceType, Positions.readOnly("")))); assertEquals("", therianContext.eval(Convert.to(String.class, Positions.readOnly("")))); assertSame(MetasyntacticVariable.FOO, therianContext.eval(Convert.to(MetasyntacticVariable.class, Positions.readOnly(MetasyntacticVariable.FOO)))); assertSame(MetasyntacticVariable.FOO, therianContext.eval(Convert.to(new TypeLiteral<Enum<?>>() {}, Positions.readOnly(MetasyntacticVariable.FOO)))); assertEquals(Integer.valueOf(666), therianContext.eval(Convert.to(Integer.class, Positions.readOnly(Integer.valueOf(666))))); assertEquals(Integer.valueOf(666), therianContext.eval(Convert.to(Number.class, Positions.readOnly(Integer.valueOf(666))))); } @Test public void testNullValueUnsupportedHint() { assertFalse(therianContext.supports(Convert.to(charSequenceType, Positions.readOnly(String.class, (String) null)), NOPConverter.NullBehavior.UNSUPPORTED)); } }
xiaohaijin/RHIC-STAR
StRoot/StDbUtilities/St_svtHybridDriftVelocityC.cxx
<reponame>xiaohaijin/RHIC-STAR<gh_stars>1-10 #include <assert.h> #include "TMath.h" #include "TString.h" #include "Stiostream.h" #include "St_svtHybridDriftVelocityC.h" ClassImp(St_svtHybridDriftVelocityC); St_svtHybridDriftVelocityC *St_svtHybridDriftVelocityC::fgsvtHybridDriftVelocityC = 0; Double_t St_svtHybridDriftVelocityC::mAnodePitch = 0.0250; Double_t St_svtHybridDriftVelocityC::mWaferLength = 2.9928; Double_t St_svtHybridDriftVelocityC::mWaferWidth = 3.0000; Double_t St_svtHybridDriftVelocityC::mNoAnodes = 2*St_svtHybridDriftVelocityC::mWaferWidth/St_svtHybridDriftVelocityC::mAnodePitch; Double_t St_svtHybridDriftVelocityC::mSamplingFrequency = 25000000.0; static const Int_t NB = 3; static const Int_t NL = 16; static const Int_t NW = 7; static const Int_t NH = 2; static svtHybridDriftVelocity_st *pointers[3][16][7][2]; static svtHybridDriftVelocity_st *DataOld = 0; //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::STcheb(Int_t N, Double_t *par, Double_t x) {// N polynome degree, dimension is par[N+1] if (N < 0 || N > 12) return 0; Double_t T0 = 1; Double_t T1 = 2*x - 1; Double_t T2; Double_t Sum = par[0]*T0; if (N >= 1) { T1 = 2*x - 1; Sum += par[1]*T1; for (int n = 2; n <= N; n++) { T2 = 2*(2*x - 1)*T1 - T0; Sum += par[n]*T2; T0 = T1; T1 = T2; } } return Sum; } //________________________________________________________________________________ St_svtHybridDriftVelocityC::St_svtHybridDriftVelocityC (St_svtHybridDriftVelocity *table) : TChair(table) { if (fgsvtHybridDriftVelocityC) delete fgsvtHybridDriftVelocityC; fgsvtHybridDriftVelocityC = this; Init(); } //________________________________________________________________________________ void St_svtHybridDriftVelocityC::Init() { memset (&pointers[0][0][0][0], 0, NB*NL*NW*NH*sizeof(svtHybridDriftVelocity_st *)); St_svtHybridDriftVelocity *Table = (St_svtHybridDriftVelocity *) GetThisTable(); if (Table) { svtHybridDriftVelocity_st *Data = Table->GetTable(); DataOld = Data; Int_t N = Table->GetNRows(); for (Int_t j = 0; j < N; j++, Data++) { if (Data->barrel < 1 || Data->barrel > NB || Data->ladder < 1 || Data->ladder > NL || Data->wafer < 1 || Data->wafer > NW || Data->hybrid < 1 || Data->hybrid > NH) continue; pointers[Data->barrel-1][Data->ladder-1][Data->wafer-1][Data->hybrid-1] = Data; } } } //________________________________________________________________________________ svtHybridDriftVelocity_st *St_svtHybridDriftVelocityC::p(Int_t barrel, Int_t ladder, Int_t wafer, Int_t hybrid) { svtHybridDriftVelocity_st *p = 0; if (! GetThisTable()) return p; if (((St_svtHybridDriftVelocity *)GetThisTable())->GetTable() != DataOld) Init(); if (barrel >= 1 && barrel <= NB && ladder >= 1 && ladder <= NL && wafer >= 1 && wafer <= NW && hybrid >= 1 && hybrid <= NH) p = pointers[barrel-1][ladder-1][wafer-1][hybrid-1]; return p; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::uHat(svtHybridDriftVelocity_st *p, Double_t timeBin) { if (! p) return -99; Double_t u = 1 - (timeBin - p->tmin)/(p->tmax - p->tmin); if (p->hybrid == 1) u = -u; return u; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::vHat(svtHybridDriftVelocity_st *p, Double_t anode) { if (! p) return -99; Double_t v = 1 - anode/mNoAnodes; if (p->hybrid == 1) v = -v; return v; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::CalcDriftLength(svtHybridDriftVelocity_st *p, Double_t timeBin, Double_t anode) { if (! p) return -99; Double_t u = uHat(p,timeBin); Double_t uD = mWaferLength*u; Double_t *coef = &p->v0; Int_t nu = p->npar%10; if (nu > 0) uD -= STcheb(nu-1, coef, TMath::Abs(u)); Int_t nv = (p->npar/10)%10; if (nv > 0) { Double_t v = vHat(p,anode); uD -= STcheb(nv-1, &coef[nu], TMath::Abs(v)); } return uD; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::UnCalcDriftLength(svtHybridDriftVelocity_st *p, Double_t x) { if (! p) return -99; Double_t d = TMath::Min(mWaferLength,TMath::Max(0.,x)); return p->tmin + (p->tmax - p->tmin)*d/mWaferLength; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::DriftVelocity(svtHybridDriftVelocity_st *p) { return p ? mSamplingFrequency*mWaferLength/(p->tmax - p->tmin): -1; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::CalcU(Int_t barrel, Int_t ladder, Int_t wafer, Int_t hybrid, Double_t timeBin, Double_t anode) { return CalcDriftLength(barrel, ladder, wafer, hybrid, timeBin, anode); } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::CalcV(Int_t hybrid, Double_t x) { Double_t vd = CalcTransLength(x); if (hybrid == 1) vd = vd - WaferWidth(); else vd = WaferWidth() - vd; return vd; } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::UnCalcU(Int_t barrel, Int_t ladder, Int_t wafer, Int_t hybrid, Double_t ud) { if (hybrid == 1) ud = ud + WaferLength(); else ud = WaferLength() - ud; return UnCalcDriftLength(barrel, ladder, wafer, hybrid, ud); } //________________________________________________________________________________ Double_t St_svtHybridDriftVelocityC::UnCalcV(Int_t hybrid, Double_t vd) { if (hybrid == 1) vd = vd + WaferWidth(); else vd = WaferWidth() - vd; return UnCalcTransLength(vd); } //________________________________________________________________________________ Bool_t St_svtHybridDriftVelocityC::IsValidDriftRegion(Int_t barrel, Int_t ladder, Int_t wafer, Int_t hybrid, Double_t timeBin) { svtHybridDriftVelocity_st *pp = p(barrel, ladder, wafer, hybrid); if (! pp) return kFALSE; Int_t I = (pp->npar/100)%10; if (! I) return kTRUE; Double_t u = TMath::Abs(uHat(pp,timeBin)); if (u >= pp->dtmin && u <= pp->dtmax) return kTRUE; return kFALSE; }
FloThinksPi-Forks/vstutils
vstutils/translations/ru.py
# flake8: noqa: E501 TRANSLATION = { 'create': 'создать', 'add': 'добавить', 'edit': 'редактировать', 'save': 'сохранить', 'remove': 'удалить', 'reload': 'перезагрузить', 'send': 'отправить', 'select': 'выбрать', 'filters': 'фильтры', 'apply': 'применить', 'cancel': 'отменить', 'field': 'поле', 'actions': 'действия', 'sublinks': 'вложенные ссылки', 'name': 'имя', 'type': 'тип', 'owner': 'владелец', 'notes': 'заметки', 'copy': 'копировать', 'error': 'ошибка', 'home': 'главная', 'login': 'войти', 'logout': 'выйти', 'profile': 'профиль', 'settings': 'настройки', 'version': 'версий | версия | версии', 'cache': 'кэш', 'documentation': 'документация', 'request': 'запрос', 'repository': 'репозиторий', 'app info': 'инфо', 'status': 'статус', 'list is empty': 'список пуст', 'child instances': 'вложенные объекты', 'enter value': 'введите значение', 'more info': 'подробнее', 'search by': 'поиск по полю', # field's validation # empty 'Field "<b>{0}</b>" is empty.': 'Поле "<b>{0}</b>" пустое.', # required 'Field "<b>{0}</b>" is required.': 'Поле "<b>{0}</b>" обязательно для заполнения.', # minLength 'Field "<b>{0}</b>" is too short.<br> Field length should not be shorter, than {1}.': 'Длина поля "<b>{0}</b>" слишком мала.<br>Длина поля должна быть не меньше, чем {1}.', # maxLength 'Field "<b>{0}</b>" is too long. <br> Field length should not be longer, than {1}.': 'Длина поля "<b>{0}</b>" слишком велика.<br>Длина поля должна быть не больше, чем {1}.', # min 'Field "<b>{0}</b>" is too small.<br> Field should not be smaller, than {1}.': 'Значение поля "<b>{0}</b>" слишком мало.<br> Значение поля должно быть не меньше, чем {1}.', # max 'Field "<b>{0}</b>" is too big.<br> Field should not be bigger, than {1}.': 'Значение поля "<b>{0}</b>" слишком велико.<br> Значение поля должно быть не больше, чем {1}.', # invalid '<b>{0} </b> value is not valid for <b>{1}</b> field.': 'Значение <b>{0}</b> не допустимо для поля <b>{1}</b>.', # email '<b>"{0}"</b> field should be written in <b>"<EMAIL>"</b> format.': 'Поле <b>"{0}"</b> должно быть заполнено в формате <b>"<EMAIL>"</b>.', # instance operation success # add 'Child "<b>{0}</b>" instance was successfully added to parent list.': 'Дочерний объект "<b>{0}</b>" был успешно добавлен в родительский список.', # create 'New "<b>{0}</b>" instance was successfully created.': 'Новый объект "<b>{0}</b>" был успешно создан.', # remove '"<b>{0}</b>" {1} was successfully removed.': '"<b>{0}</b>" {1} был(а) успешно удален.', # save 'Changes in "<b>{0}</b>" {1} were successfully saved.': 'Изменения в объекте {1} "<b>{0}</b>" были успешно сохранены.', # execute 'Action "<b>{0}</b>" was successfully executed on "<b>{1}</b>" instance.': 'Действие "<b>{0}</b>" было успешно запущено на объекте "<b>{1}</b>".', # instance operation error # add: 'Some error occurred during adding of child "<b>{0}</b>" instance to parent list.<br> Error details: {1}': 'Во время добавления дочернего объекта "<b>{0}</b>" к родительскому списку произошла ошибка.<br> Подробнее: {1}', # create: 'Some error occurred during new "<b>{0}</b>" instance creation.<br> Error details: {1}': 'Во время создания нового объекта "<b>{0}</b>" произошла ошибка.<br> Подробнее: {1}', # remove: 'Some error occurred during remove process of "<b>{0}</b>" {1}.<br> Error details: {2}': 'Во время удаления {1} "<b>{0}</b>" произошла ошибка.<br> Подробнее: {2}', # save: 'Some error occurred during saving process of "<b>{0}</b>" {1}.<br> Error details: {2}': 'Во время сохранения {1} "<b>{0}</b>" произошла ошибка.<br> Подробнее: {2}', # execute: 'Some error occurred during "<b>{0}</b>" action execution on {1}.<br> Error details: {2}': 'Во время запуска действия "<b>{0}</b>" на {1} произошла ошибка.<br> Подробнее: {2}', # guiCustomizer translations 'customize application styles': 'настройка цветовых стилей приложения', 'skin': 'тема', 'skin settings': 'настройки темы', 'active menu background': 'фон активного элемента меню', 'active menu color': 'активный элемент меню', 'body background': 'фон страницы', 'top navigation background': 'фон верхнего блока навигации', 'top navigation border': 'окантовка верхнего блока навигации', 'left sidebar background': 'фон сайдбара слева', 'left sidebar border': 'окантовка сайдбара слева', 'customizer sidebar background': 'фон данного сайдбара', 'breadcrumbs background': 'фон хлебный крошек', 'buttons default background': 'фон стандартной кнопки', 'buttons default text': 'текст стандартной кнопки', 'buttons default border': 'окантовка стандартной кнопки', 'buttons primary background': 'фон основной кнопки', 'buttons primary text': 'текст основной кнопки', 'buttons primary border': 'окантовка основной кнопки', 'buttons danger background': 'фон danger кнопки', 'buttons danger text': 'текст danger кнопки', 'buttons danger border': 'окантовка danger кнопки', 'buttons warning background': 'фон warning кнопки', 'buttons warning text': 'текст warning кнопки', 'buttons warning border': 'окантовка warning кнопки', 'links': 'ссылка', 'links hover': 'ссылка при наведении', 'links revers': 'ссылка на темном фоне', 'links hover revers': 'ссылка на темном фоне при наведении', 'text color': 'текст', 'ico default color': 'стандартаный цвет иконки', 'text header color': 'заголовок', 'background default color': 'стандартный цвет фона', 'card header background': 'фон верхней части "card" блока', 'card body background': 'фон основной части "card" блока', 'card footer background': 'фон нижней части "card" блока', 'card color': 'текст "card" в блоке', 'labels': 'лейбл', 'help content': 'вспомогательный контент', 'help text color': 'вспомогательный текст', 'table line hover bg color': 'фон табличного ряда при наведении', 'table border color': 'окантовка таблицы', 'table line selected bg color': 'фон выделенного табличного ряда', 'background active color': 'фон активного элемента', 'background passive color': 'фон неактивного элемента', 'text hover color': 'цвет текста при наведении', 'boolean true color': 'цвет для булевых переменных со значением "true"', 'boolean false color': 'цвет для булевых переменных со значением "false"', 'modal background color': 'фон модального окна', 'api sections background color': 'фон секций в Api', 'api sections border color': 'окантовка секций в Api', 'code highlighting color 1': 'подсветка кода - цвет 1', 'code highlighting color 2': 'подсветка кода - цвет 2', 'code highlighting color 3': 'подсветка кода - цвет 3', 'code highlighting color 4': 'подсветка кода - цвет 4', 'code highlighting color 5': 'подсветка кода - цвет 5', 'code highlighting color 6': 'подсветка кода - цвет 6', 'code highlighting color 7': 'подсветка кода - цвет 7', 'custom css': 'пользовательский css', 'reset skin settings to default': 'к настройкам по умолчанию', 'save skin': 'сохранить тему', 'Skin settings were successfully reset to default.': 'Настройки темы были успешно возвращены к стандратным.', 'Skin settings were successfully saved': 'Настройки темы были успешно сохранены.', # multiactions button 'actions on': 'действия над', 'on item': 'элементов | элементом | элементами | элементами', 'key': 'ключ', 'value': 'значение', 'new owner': 'новый владелец', 'detail': 'детали', 'description': 'описание', 'username': 'имя пользователя', 'is active': 'активен', 'user': 'пользователь', 'yes': 'да', 'no': 'нет', 'is staff': 'админ', 'first name': 'имя', 'last name': 'фамилия', 'password': '<PASSWORD>', 'change_password': '<PASSWORD>', 'generate password': '<PASSWORD>', 'repeat password': '<PASSWORD>', 'old password': '<PASSWORD>', 'new password': '<PASSWORD>', 'confirm new password': '<PASSWORD>', 'kind': 'вид', 'mode': 'режим', 'options': 'опции', 'information': 'информация', 'date': 'дата', 'file n selected': 'файл не выбран | 1 файл выбран | {n} файла выбрано | {n} файлов выбрано', 'image n selected': 'изображение не выбрано | 1 изображение выбрано | {n} изображения выбрано | {n} изображений выбрано', # filters 'ordering': 'порядок сортировки', 'id__not': 'id не равный', 'name__not': 'имя не равное', 'is_active': 'активен', 'first_name': 'имя', 'last_name': 'фамилия', # 'email': '', 'username__not': 'имя пользователя не равное', 'status__not': 'статус не равный', # filters description 'boolean value meaning status of user.': 'булево значение обозначающее статус пользователя.', 'users first name.': '<NAME>', 'users last name.': '<NAME>', 'users e-mail value.': 'email пользователя', 'which field to use when ordering the results.': 'поле по которому производить сортировку результатов.', 'a unique integer value (or comma separated list) identifying this instance.': 'уникальное числовое значение (или их последовательность разделенная запятой) идентифицирующая данный объект.', 'a name string value (or comma separated list) of instance.': 'имя объекта - строковое значение (или их последовательность разделенная запятой).', 'page matching current url was not found': 'страница, соответствующая данному url, не была найдена', }
swaplicado/sa-lib-10
src/sa/lib/srv/SSrvResponse.java
<reponame>swaplicado/sa-lib-10 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sa.lib.srv; import java.io.Serializable; import sa.lib.SLibConsts; /** * * @author <NAME> */ public class SSrvResponse implements Serializable { protected int mnResponseType; protected Object moPacket; protected int mnResultType; protected String msMessage; /** * @param responseType Constants defined in sa.lib.srv.SSrvConsts. */ public SSrvResponse(int responseType) { this(responseType, null); } /** * @param responseType Constants defined in sa.lib.srv.SSrvConsts. * @param packet Response information packet. */ public SSrvResponse(int responseType, Object packet) { mnResponseType = responseType; moPacket = packet; mnResultType = SLibConsts.UNDEFINED; msMessage = ""; } public void setResponseType(int n) { mnResponseType = n; } public void setPacket(Object packet) { moPacket = packet; } public void setResultType(int n) { mnResultType = n; } public void setMessage(String s) { msMessage = s; } public int getResponseType() { return mnResponseType; } public Object getPacket() { return moPacket; } public int getResultType() { return mnResultType; } public String getMessage() { return msMessage; } }
Hacky-DH/pytorch
torch/csrc/stub.c
#include <Python.h> #ifdef _WIN32 __declspec(dllimport) #endif extern PyObject* initModule(void); #ifndef _WIN32 #ifdef __cplusplus extern "C" #endif __attribute__((visibility("default"))) PyObject* PyInit__C(void); #endif PyMODINIT_FUNC PyInit__C(void) { return initModule(); }
oakesville/mdw
mdw-common/src/com/centurylink/mdw/test/TestCaseFile.java
<reponame>oakesville/mdw package com.centurylink.mdw.test; import java.io.FileInputStream; import java.io.IOException; public class TestCaseFile extends java.io.File { public TestCaseFile(String pathname) { super(pathname); } public String getText() throws IOException { return text(); } public String text() throws IOException { return new String(read()); } private byte[] read() throws IOException { FileInputStream fis = null; try { fis = new FileInputStream(this); byte[] bytes = new byte[(int) this.length()]; fis.read(bytes); return bytes; } finally { if (fis != null) fis.close(); } } }
little9/laevigata
app/forms/hyrax/etd_form.rb
<gh_stars>1-10 # Generated via # `rails generate hyrax:work Etd` module Hyrax class EtdForm < Hyrax::Forms::WorkForm include SingleValuedForm self.model_class = ::Etd # about me terms self.terms += [:graduation_date] self.terms += [:post_graduation_email] self.terms += [:resource_type] self.terms += [:school] self.terms += [:department] self.terms += [:subfield] self.terms += [:degree] self.terms += [:partnering_agency] self.terms += [:submitting_type] self.terms += [:committee_chair] self.terms += [:committee_members] self.terms -= [:rights] # about my etd terms self.terms += [:abstract] self.terms += [:keyword] self.terms += [:language] self.terms += [:research_field] self.terms += [:table_of_contents] self.terms += [:copyright_question_one] self.terms += [:copyright_question_two] self.terms += [:copyright_question_three] # my embargo terms self.terms += [:embargo_length] self.terms += [:embargo_release_date] self.terms += [:files_embargoed] self.terms += [:abstract_embargoed] self.terms += [:toc_embargoed] self.single_valued_fields = [:title, :creator, :post_graduation_email, :submitting_type, :graduation_date, :degree, :subfield, :department, :school, :language, :abstract, :table_of_contents] def about_me_fields [:creator, :graduation_date, :post_graduation_email] end def about_my_program_fields [:school, :department, :subfield, :partnering_agency, :degree, :submitting_type] end def about_my_etd_fields [:language, :abstract, :table_of_contents, :research_field] end def primary_pdf_name model.primary_pdf_file_name end # Initial state for the 'No Supplemental Files' checkbox. # Supplemental files aren't required for an ETD, but the # form validation requires the user to explicitly check the # 'No Supplemental Files' checkbox if they don't intend to # add any additional files. def no_supplemental_files model.persisted? && supplemental_files.blank? end def supplemental_files model.ordered_members.to_a.select(&:supplementary?) end # Initial state for the 'No Embargo' checkbox. def no_embargoes model.persisted? && !model.under_embargo? end def selected_embargo_type return '[:files_embargoed, :toc_embargoed, :abstract_embargoed]' if true_string?(model.abstract_embargoed) return '[:files_embargoed, :toc_embargoed]' if true_string?(model.toc_embargoed) return '[:files_embargoed]' if true_string?(model.files_embargoed) end # Both String and boolean 'true' should count as true. def true_string?(field) field == 'true' || field == true end # we need to pass a nil to Hyrax in order to remove a subfield # from an existing ETD, because the absence of the parameter won't def self.sanitize_params(form_params) form_params["subfield"] = nil unless form_params.include?("subfield") check_for_no_embargoes(form_params) super end # If no_embargoes is set, set all embargo fields to false def self.check_for_no_embargoes(params) return unless params["no_embargoes"] == "1" params["files_embargoed"] = "false" params["abstract_embargoed"] = "false" params["toc_embargoed"] = "false" end # Select the correct affiliation type for committee member def cm_affiliation_type(value) value = Array(value).first if value.blank? || value == 'Emory University' cm_affiliation_options[0] else cm_affiliation_options[1] end end # Select the correct affiliation type for committee chair def cc_affiliation_type(value) value = Array(value).first if value.blank? || value == 'Emory University' cc_affiliation_options[0] else cc_affiliation_options[1] end end def cm_affiliation_options ["Emory Committee Member", "Non-Emory Committee Member"] end def cc_affiliation_options ["Emory Committee Chair", "Non-Emory Committee Chair"] end # In the view we have "fields_for :committee_members". # This method is needed to make fields_for behave as an # association and populate the form with the correct # committee member data. delegate :committee_members_attributes=, to: :model delegate :committee_chair_attributes=, to: :model # We need to call '.to_a' on committee_members to force it # to resolve. Otherwise in the form, the fields don't # display the committee member's name and affiliation. # Instead they display something like: # '#<ActiveTriples::Relation:0x007fb564969c88>' def committee_members model.committee_members.build if model.committee_members.blank? model.committee_members.to_a end def committee_chair model.committee_chair.build if model.committee_chair.blank? model.committee_chair.to_a end def no_committee_members str_committee_members = model.committee_members.to_a.join(',') value = str_committee_members.count("a-zA-Z").zero? empty_committee_members = value model.persisted? && empty_committee_members end def self.build_permitted_params permitted = super permitted << { committee_members_attributes: [:id, { name: [] }, { affiliation: [] }, :affiliation_type, { netid: [] }, :_destroy] } permitted << { committee_chair_attributes: [:id, { name: [] }, { affiliation: [] }, :affiliation_type, { netid: [] }, :_destroy] } permitted end # If the student selects 'Emory Committee Chair' or # 'Emory Committee Member' for the 'affiliation_type' field, # then the 'affiliation' field becomes disabled in the form. # In that case, we need to fill in the 'affiliation' data # with 'Emory University', and we need to remove the # 'affiliation_type' field because that is not a valid field # for the CommitteeMember model. def self.model_attributes(form_params) attrs = super keys = ['committee_chair_attributes', 'committee_members_attributes'] keys.each do |field_name| next if attrs[field_name].blank? attrs[field_name].each do |member_key, member_attrs| aff_type = attrs[field_name][member_key].delete 'affiliation_type' names = attrs[field_name][member_key]['name'] || [] netids = attrs[field_name][member_key]['netid'] || [] names_blank = names.all?(&:blank?) netids_blank = netids.all?(&:blank?) next if names_blank && netids_blank if member_attrs['affliation'].blank? && aff_type && aff_type.start_with?('Emory') attrs[field_name][member_key]['affiliation'] = ['Emory University'] end end end attrs end end end
trolldbois/metasploit-framework
lib/gemcache/ruby/1.9.1/gems/tzinfo-0.3.33/lib/tzinfo/definitions/Asia/Tel_Aviv.rb
<filename>lib/gemcache/ruby/1.9.1/gems/tzinfo-0.3.33/lib/tzinfo/definitions/Asia/Tel_Aviv.rb module TZInfo module Definitions module Asia module Tel_Aviv include TimezoneDefinition linked_timezone 'Asia/Tel_Aviv', 'Asia/Jerusalem' end end end end
yhl452493373/Blog
src/main/java/com/yang/blog/es/dao/base/EsBaseDao.java
package com.yang.blog.es.dao.base; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.repository.NoRepositoryBean; import java.io.Serializable; @NoRepositoryBean public interface EsBaseDao<EsDoc, ID extends Serializable> extends ElasticsearchRepository<EsDoc, ID> { }
maqiangddb/AndroidVncServer
jni/guacd/pixman/demos/gtk-utils.c
#include <gtk/gtk.h> #include <config.h> #include "../test/utils.h" #include "gtk-utils.h" GdkPixbuf * pixbuf_from_argb32 (uint32_t *bits, gboolean has_alpha, int width, int height, int stride) { GdkPixbuf *pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, width, height); int p_stride = gdk_pixbuf_get_rowstride (pixbuf); guint32 *p_bits = (guint32 *)gdk_pixbuf_get_pixels (pixbuf); int i; for (i = 0; i < height; ++i) { uint32_t *src_row = &bits[i * (stride / 4)]; uint32_t *dst_row = p_bits + i * (p_stride / 4); a8r8g8b8_to_rgba_np (dst_row, src_row, width); } return pixbuf; } static gboolean on_expose (GtkWidget *widget, GdkEventExpose *expose, gpointer data) { GdkPixbuf *pixbuf = data; gdk_draw_pixbuf (widget->window, NULL, pixbuf, 0, 0, 0, 0, gdk_pixbuf_get_width (pixbuf), gdk_pixbuf_get_height (pixbuf), GDK_RGB_DITHER_NONE, 0, 0); return TRUE; } void show_image (pixman_image_t *image) { GtkWidget *window; GdkPixbuf *pixbuf; int width, height, stride; int argc; char **argv; char *arg0 = g_strdup ("pixman-test-program"); gboolean has_alpha; pixman_format_code_t format; argc = 1; argv = (char **)&arg0; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); width = pixman_image_get_width (image); height = pixman_image_get_height (image); stride = pixman_image_get_stride (image); gtk_window_set_default_size (GTK_WINDOW (window), width, height); format = pixman_image_get_format (image); if (format == PIXMAN_a8r8g8b8) has_alpha = TRUE; else if (format == PIXMAN_x8r8g8b8) has_alpha = FALSE; else g_error ("Can't deal with this format: %x\n", format); pixbuf = pixbuf_from_argb32 (pixman_image_get_data (image), has_alpha, width, height, stride); g_signal_connect (window, "expose_event", G_CALLBACK (on_expose), pixbuf); g_signal_connect (window, "delete_event", G_CALLBACK (gtk_main_quit), NULL); gtk_widget_show (window); gtk_main (); }
gengyuanzhe/betwixt
src/test/org/apache/commons/betwixt/TestOptions.java
<filename>src/test/org/apache/commons/betwixt/TestOptions.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.commons.betwixt; import junit.framework.TestCase; /** * @author <a href='http://commons.apache.org/'>Apache Commons Team</a> * @version $Revision: 561314 $ */ public class TestOptions extends TestCase { private static final int A_SHIFT = 1 << 0; private static final int B_SHIFT = 1 << 1; private static final int C_SHIFT = 1 << 2; public void testGetValue() { Options options = new Options(); options.addOption("A", "Alpha"); options.addOption("B", "Beta"); assertEquals("Get added value", "Alpha", options.getValue("A")); assertNull("Value not added is null", options.getValue("C")); options.addOption("A", "New Value"); assertEquals("Lat value set wins", "New Value", options.getValue("A")); } public void testGetNames() { Options options = new Options(); options.addOption("A", "Alpha"); options.addOption("B", "Beta"); options.addOption("C", "Gamma"); String[] names = options.getNames(); assertEquals("Expected three names", 3, names.length); int flag = (A_SHIFT) + (B_SHIFT) + (C_SHIFT); for ( int i = 0; i <3 ; i++ ) { if (names[i].equals("A")) { assertTrue("A named twice", (flag & (A_SHIFT))>0); flag -= (A_SHIFT); } else if (names[i].equals("B")) { assertTrue("B named twice", (flag & (B_SHIFT))>0); flag -= (B_SHIFT); } else if (names[i].equals("C")) { assertTrue("C named twice", (flag & (C_SHIFT))>0); flag -= (C_SHIFT); } else { fail("Unexpected name: " + names[i]); } } } public void testAddOptions() { Options a = new Options(); a.addOption("A", "Alpha"); a.addOption("B", "Beta"); a.addOption("C", "Gamma"); Options b = new Options(); b.addOption("A", "Apple"); b.addOption("C", "Carrot"); b.addOption("E", "Egg Plant"); a.addOptions(b); // Lat value set wins assertEquals("Apple",a.getValue("A")); assertEquals("Beta",a.getValue("B")); assertEquals("Carrot",a.getValue("C")); assertEquals("Egg Plant",a.getValue("E")); } }
Umi-faith/data-cleaning-master
src/main/java/utils/JDBCUtil.java
package utils; /** * @Author twh * @Date 2020/4/4 17:01 */ import java.sql.*; public class JDBCUtil { static final String DriverName="org.apache.hive.jdbc.HiveDriver"; static final String url="jdbc:hive2://cdh-slave1:10000/faith_server"; static final String user=""; static final String pass=""; /** * 创建连接 * @return * @throws ClassNotFoundException * @throws SQLException */ public static Connection getConn() throws ClassNotFoundException, SQLException { Class.forName(DriverName); Connection connection = DriverManager.getConnection(url,user,pass); return connection; } /** * 创建命令 * @param connection * @return * @throws SQLException */ public static Statement getStmt(Connection connection) throws SQLException { return connection.createStatement(); } /** * 关闭连接 * @param connection * @param statement * @throws SQLException */ public static void closeFunc(Connection connection, Statement statement) throws SQLException { statement.close(); connection.close(); } public static void main(String[] args) throws SQLException, ClassNotFoundException { } }
ujjwalgulecha/Coding
Others/test.cpp
#include "hungarian.h" std::vector< std::vector<int> > array_to_matrix(int* m, int rows, int cols) { int i,j; std::vector< std::vector<int> > r; r.resize(rows, std::vector<int>(cols, 0)); for(i=0;i<rows;i++) { for(j=0;j<cols;j++) r[i][j] = m[i*cols+j]; } return r; } int main() { /* an example cost matrix */ int r[3*3] = {20,90,10,60,30,40,90,90, 120}; std::vector< std::vector<int> > m = array_to_matrix(r,3,3); /* initialize the gungarian_problem using the cost matrix*/ Hungarian hungarian(m , 3,3, HUNGARIAN_MODE_MINIMIZE_COST) ; //fprintf(stderr, "assignement matrix has a now a size %d rows and %d columns.\n\n", hungarian.ro,matrix_size); /* some output */ fprintf(stderr, "cost-matrix:"); hungarian.print_cost(); /* solve the assignement problem */ hungarian.solve(); /* some output */ fprintf(stderr, "assignment:"); hungarian.print_assignment(); return 0; }
kslat3r/terraform-provider-form3
models/user.go
<gh_stars>0 // Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "strconv" strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // User user // swagger:model User type User struct { // attributes Attributes *UserAttributes `json:"attributes,omitempty"` // id // Format: uuid ID strfmt.UUID `json:"id,omitempty"` // organisation id // Format: uuid OrganisationID strfmt.UUID `json:"organisation_id,omitempty"` // type Type string `json:"type,omitempty"` // version // Minimum: 0 Version *int64 `json:"version,omitempty"` } // Validate validates this user func (m *User) Validate(formats strfmt.Registry) error { var res []error if err := m.validateAttributes(formats); err != nil { res = append(res, err) } if err := m.validateID(formats); err != nil { res = append(res, err) } if err := m.validateOrganisationID(formats); err != nil { res = append(res, err) } if err := m.validateVersion(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *User) validateAttributes(formats strfmt.Registry) error { if swag.IsZero(m.Attributes) { // not required return nil } if m.Attributes != nil { if err := m.Attributes.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("attributes") } return err } } return nil } func (m *User) validateID(formats strfmt.Registry) error { if swag.IsZero(m.ID) { // not required return nil } if err := validate.FormatOf("id", "body", "uuid", m.ID.String(), formats); err != nil { return err } return nil } func (m *User) validateOrganisationID(formats strfmt.Registry) error { if swag.IsZero(m.OrganisationID) { // not required return nil } if err := validate.FormatOf("organisation_id", "body", "uuid", m.OrganisationID.String(), formats); err != nil { return err } return nil } func (m *User) validateVersion(formats strfmt.Registry) error { if swag.IsZero(m.Version) { // not required return nil } if err := validate.MinimumInt("version", "body", int64(*m.Version), 0, false); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *User) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *User) UnmarshalBinary(b []byte) error { var res User if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // UserAttributes user attributes // swagger:model UserAttributes type UserAttributes struct { // email // Pattern: ^[A-Za-z0-9-+@.]*$ Email string `json:"email,omitempty"` // role ids RoleIds []strfmt.UUID `json:"role_ids"` // username // Pattern: ^[A-Za-z0-9-+@.]*$ Username string `json:"username,omitempty"` } // Validate validates this user attributes func (m *UserAttributes) Validate(formats strfmt.Registry) error { var res []error if err := m.validateEmail(formats); err != nil { res = append(res, err) } if err := m.validateRoleIds(formats); err != nil { res = append(res, err) } if err := m.validateUsername(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *UserAttributes) validateEmail(formats strfmt.Registry) error { if swag.IsZero(m.Email) { // not required return nil } if err := validate.Pattern("attributes"+"."+"email", "body", string(m.Email), `^[A-Za-z0-9-+@.]*$`); err != nil { return err } return nil } func (m *UserAttributes) validateRoleIds(formats strfmt.Registry) error { if swag.IsZero(m.RoleIds) { // not required return nil } for i := 0; i < len(m.RoleIds); i++ { if err := validate.FormatOf("attributes"+"."+"role_ids"+"."+strconv.Itoa(i), "body", "uuid", m.RoleIds[i].String(), formats); err != nil { return err } } return nil } func (m *UserAttributes) validateUsername(formats strfmt.Registry) error { if swag.IsZero(m.Username) { // not required return nil } if err := validate.Pattern("attributes"+"."+"username", "body", string(m.Username), `^[A-Za-z0-9-+@.]*$`); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *UserAttributes) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *UserAttributes) UnmarshalBinary(b []byte) error { var res UserAttributes if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
zjclugger/ComponentApp
Buyer/src/main/java/com/zjclugger/buyer/repository/FinanceRepository.java
<reponame>zjclugger/ComponentApp<gh_stars>0 package com.zjclugger.buyer.repository; public class FinanceRepository { private static FinanceRepository mInstance; public static FinanceRepository getInstance() { if (mInstance == null) { mInstance = new FinanceRepository(); } return mInstance; } /* private FinanceApi getApi() { return BaseWebApi.instance().getApi(FinanceApi.class, BuildConfig.URL_FINANCE); } public LiveData<ApiResponse<BaseWrapperEntity<OriginalBillResult>>> uploadBillImage(Map<String, Object> params) { return getApi().uploadBillImage(params); } public LiveData<ApiResponse<BaseWrapperEntities<OriginalBillResult>>> getCompanyBill(String companyId) { return getApi().getCompanyBill(companyId); } public LiveData<ApiResponse<BaseWrapperEntity<OriginalBillResult>>> getBill(String id) { return getApi().getBill(id); } public LiveData<ApiResponse<BaseWrapperEntity<OriginalBillListResult>>> getOriginalList(Map<String, Object> params) { return getApi().getOriginalList(params); } public LiveData<ApiResponse<BaseWrapperEntity<AccountBillListResult>>> getAccountBillList(Map<String, Object> params) { // return getApi().getAccountBillList(params); return BaseWebApi.instance().setNullDefaultStringValue("暂无").getApi(FinanceApi.class, BuildConfig.URL_FINANCE).getAccountBillList(params); } public LiveData<ApiResponse<BaseWrapperEntities<BillTypeResult>>> getBillTypeAll() { return getApi().getBillTypeAll(); } public LiveData<ApiResponse<BaseWrapperEntity<OriginalDetailResult>>> getOriginalDetail(String id) { return getApi().getOriginalDetail(id); } public LiveData<ApiResponse<BaseWrapperEntity<AccountBillDetailResult>>> getAccountDetail(String id) { return BaseWebApi.instance().setNullDefaultStringValue("暂无").getApi(FinanceApi.class, BuildConfig.URL_FINANCE).getAccountDetail(id); } public LiveData<ApiResponse<BaseWrapper<String>>> updateOriginalBill(String originalJson) { RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;" + "charset=UTF-8"), originalJson); return getApi().updateOriginalBill(requestBody); } public LiveData<ApiResponse<BaseWrapper<String>>> submitToCheck(String originalId) { return getApi().submitToCheck(originalId); } public LiveData<ApiResponse<BaseWrapper<String>>> checkOriginal(String originalId, boolean isPass) { return isPass ? getApi().checkPass(originalId) : getApi().checkFail(originalId); } public LiveData<ApiResponse<BaseWrapper<String>>> createAccountBill(String originalId) { return getApi().createAccountBill(originalId); } public LiveData<ApiResponse<BaseWrapper<String>>> submitApprove(String accountId) { return getApi().submitApprove(accountId); } public LiveData<ApiResponse<BaseWrapper<String>>> passApprove(String accountId) { return getApi().passApprove(accountId); } public LiveData<ApiResponse<BaseWrapper<String>>> notPassApprove(String accountId, String reason) { return getApi().notPassApprove(accountId, reason); } public LiveData<ApiResponse<BaseWrapper<String>>> posting(String accountId) { return getApi().posting(accountId); } public LiveData<ApiResponse<BaseWrapperEntities<ReportProfitResult>>> getProfitReport(String endDate) { return getApi().getProfitReport(endDate); } public LiveData<ApiResponse<BaseWrapperEntity<ReportAssetsLiabilitiesResult>>> getAssetsLiabilitiesReport(String endDate) { return getApi().getAssetsLiabilitiesReport(endDate); } public LiveData<ApiResponse<BaseWrapperEntity<ReimbursementResult>>> getReportForm(Map<String , Object> params) { return getApi().getReportForm(params); } public LiveData<ApiResponse<BaseWrapper<JsonArray>>> getOrganizationDeparts() { return getApi().getOrganizationDeparts(); } public LiveData<ApiResponse<BaseWrapperEntities<OrganizationUserResult>>> getOrganizationUsers(String orgId) { return getApi().getOrganizationUsers(orgId); } public LiveData<ApiResponse<BaseWrapperEntity<DepartReimbursementResult>>> getDepartmentReimbursement() { return getApi().getDepartmentReimbursement(); } public LiveData<ApiResponse<BaseWrapper<JsonArray>>> getReasonReimbursement() { return getApi().getReasonReimbursement(); } public LiveData<ApiResponse<BaseWrapper<JsonObject>>> getMonthPercentage() { return getApi().getMonthPercentage(); } public LiveData<ApiResponse<BaseWrapper<JsonArray>>> getSortReimbursement() { return getApi().getSortReimbursement(); }*/ }
burnsba/getools
Getools.Test/TestFiles/stan/Tbg_testbeta_all_p_stanZ.c
<reponame>burnsba/getools /* * This file was automatically generated * * Thursday, August 5, 2021 7:29:18 PM * Getools.Lib: 192.168.3.11 */ #include "ultra64.h" #include "stan.h" // forward declarations BetaStandTile tile_0; StandFileHeader Tbg_testbeta_all_p_stanZ = { NULL, &tile_0, {0x00, 0x00, 0x00, 0x00} }; BetaStandTile tile_0 = { "p502a2", 0x0, 0xf, 0xf, 0xf, 0x002e, 3, 0x00, 0x01, 0x02, { {192, 0, 2308, 0x00000048}, {-769, 0, 2500, 0x00000000}, {192, 0, 2500, 0x000012e0} } }; BetaStandTile tile_1 = { "p502a1", 0x0, 0xf, 0xf, 0xf, 0x002e, 7, 0x00, 0x05, 0x06, { {192, 0, 2308, 0x00000000}, {0, 0, 2308, 0x000003dc}, {-231, 0, 2308, 0x00000000}, {-346, 0, 2308, 0x00000454}, {-577, 0, 2308, 0x00000000}, {-769, 0, 2308, 0x0000132c}, {-769, 0, 2500, 0x0000000c} } }; BetaStandTile tile_2 = { "p486a2", 0x0, 0xf, 0xf, 0xf, 0x002d, 3, 0x00, 0x01, 0x02, { {-2308, 0, 769, 0x00000100}, {-2500, 0, -192, 0x00000000}, {-2500, 0, 769, 0x000007e8} } }; StandTile tile_3 = { 0x000000, 0x00, 0x0, 0x0, 0x0, 0x0, 0, 0x0, 0x0, 0x0 }; StandFileFooter footer = { "unstric", NULL, NULL, NULL, NULL };
jorgeldra/CongressDroid
src/com/jorgeldra/seio/entidad/AlmacenConferencia.java
package com.jorgeldra.seio.entidad; import java.util.ArrayList; public class AlmacenConferencia implements InterfazConferencia{ private ArrayList<Conferencia> conferencias; public AlmacenConferencia() { // TODO Auto-generated constructor stub conferencias = new ArrayList<Conferencia>(); } @Override public void guardarConferencia(String title,String title2, String presentation, String home_text, ArrayList<ImagenConf> listaImagenesConf) { // TODO Auto-generated method stub Conferencia conferencia = new Conferencia(title,title2,presentation,home_text,listaImagenesConf); conferencias.add(conferencia); } @Override public void guardarConferencia(Conferencia conferencia) { // TODO Auto-generated method stub conferencias.add(conferencia); } @Override public ArrayList<Conferencia> listaConferencia() { // TODO Auto-generated method stub return this.conferencias; } @Override public void liberarListaConferencia() { // TODO Auto-generated method stub this.conferencias.clear(); } @Override public void actualizarListaConferencia(ArrayList<Conferencia> listConferencia) { this.conferencias = listConferencia; } }
Wanzyee/UnityLab
html/class_wanzyee_studio_1_1_json_1_1_color_converter.js
<filename>html/class_wanzyee_studio_1_1_json_1_1_color_converter.js var class_wanzyee_studio_1_1_json_1_1_color_converter = [ [ "GetPropertyNames", "class_wanzyee_studio_1_1_json_1_1_color_converter.html#a61eca50fcecd37b6ced0c9f9a8b0672c", null ], [ "CreateInstance", "class_wanzyee_studio_1_1_json_1_1_color_converter.html#a07606f5a91b11a5fe26eb9fbcbfbbd7d", null ], [ "CanConvert", "class_wanzyee_studio_1_1_json_1_1_color_converter.html#a8cf86720a5481c744a0a551d1541f5d8", null ], [ "ReadJson", "class_wanzyee_studio_1_1_json_1_1_color_converter.html#a63d4f63128781acfa8229a12763b5440", null ], [ "WriteJson", "class_wanzyee_studio_1_1_json_1_1_color_converter.html#a05ac0c517b46f5f9bf33cb826ca8e465", null ] ];
yntelectual/nlighten
nlighten-backend/src/main/java/me/nlighten/backend/rest/model/LessonDTO.java
<gh_stars>1-10 package me.nlighten.backend.rest.model; import java.util.Date; import java.util.Set; /** * The Class Lesson. * * @author Lubo */ public class LessonDTO extends TraceAbleDTO { /** * The title. */ private String title; /** * The description. */ private String description; /** * The order. */ private int order; /** * The duration. */ private Date duration; /** * The comments. */ private Set<CommentDTO> comments; /** * The questions. */ private Set<QuestionDTO> questions; /** * The course. */ private CourseDTO course; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public Date getDuration() { return duration; } public void setDuration(Date duration) { this.duration = duration; } public Set<CommentDTO> getComments() { return comments; } public void setComments(Set<CommentDTO> comments) { this.comments = comments; } public Set<QuestionDTO> getQuestions() { return questions; } public void setQuestions(Set<QuestionDTO> questions) { this.questions = questions; } public CourseDTO getCourse() { return course; } public void setCourse(CourseDTO course) { this.course = course; } }
voc-chain/re-birth
db/migrate/20181229030703_add_timestamp_to_transactions.rb
<reponame>voc-chain/re-birth<filename>db/migrate/20181229030703_add_timestamp_to_transactions.rb class AddTimestampToTransactions < ActiveRecord::Migration[5.2] def change add_column :transactions, :timestamp, :bigint reversible do |dir| dir.up do execute %{UPDATE transactions AS tx SET "timestamp" = subquery.timestamp FROM (SELECT block_hash, "timestamp" FROM blocks AS b) AS subquery WHERE tx.block_hash = subquery.block_hash;} end end end end
Corpus-2021/nakedobjects-4.0.0
core/metamodel/src/main/java/org/nakedobjects/metamodel/facets/object/notpersistable/NotPersistableFacetImpl.java
package org.nakedobjects.metamodel.facets.object.notpersistable; import org.nakedobjects.applib.events.UsabilityEvent; import org.nakedobjects.metamodel.facets.FacetHolder; import org.nakedobjects.metamodel.interactions.UsabilityContext; public class NotPersistableFacetImpl extends NotPersistableFacetAbstract { public NotPersistableFacetImpl(final InitiatedBy value, final FacetHolder holder) { super(value, holder); } public String disables(final UsabilityContext<? extends UsabilityEvent> ic) { final InitiatedBy by = value(); if (ic.isProgrammatic() && ic.equals(InitiatedBy.USER)) { return null; } return "Not persistable"; } } // Copyright (c) Naked Objects Group Ltd.
SoyaYooh/Panda
panda-services/panda-user-service/src/main/java/com/yukong/panda/user/service/impl/SysUserServiceImpl.java
package com.yukong.panda.user.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.google.common.base.Strings; import com.yukong.panda.common.enums.PasswordEncoderEnum; import com.yukong.panda.common.vo.SysUserVo; import com.yukong.panda.user.mapper.SysUserRoleMapper; import com.yukong.panda.user.model.dto.SysRoleDTO; import com.yukong.panda.user.model.dto.SysUserInfoDTO; import com.yukong.panda.user.model.entity.SysResource; import com.yukong.panda.user.model.entity.SysRoleResource; import com.yukong.panda.user.model.entity.SysUser; import com.yukong.panda.user.mapper.SysUserMapper; import com.yukong.panda.user.model.entity.SysUserRole; import com.yukong.panda.user.model.query.SysUserVoQuery; import com.yukong.panda.user.service.SysResourceService; import com.yukong.panda.user.service.SysUserService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * <p> * 用户表 服务实现类 * </p> * * @author yukong * @since 2018-10-08 */ @Service public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService { @Autowired private SysUserMapper sysUserMapper; @Autowired private SysResourceService sysResourceService; @Autowired private SysUserRoleMapper sysUserRoleMapper; @Autowired private PasswordEncoder passwordEncoder; @Override public SysUserVo loadUserByUsername(String username) { return sysUserMapper.loadUserByUsername(username); } @Override public SysUserVo loadUserByMobile(String mobile) { return sysUserMapper.loadUserByMobile(mobile); } @Override public SysUserInfoDTO getUserInfo(Integer userId, List<String> roles) { SysUserInfoDTO sysUserInfoDTO = new SysUserInfoDTO(); SysUser sysUser = sysUserMapper.selectById(userId); sysUserInfoDTO.setSysUser(sysUser); sysUserInfoDTO.setRoles(roles); Set<SysResource> sysResources = sysResourceService.getSysResourceRoleCodes(roles); List<String> permissions = sysResources.stream() .map(SysResource::getPermission) .collect(Collectors.toList()) .stream() .filter(permission -> !Strings.isNullOrEmpty(permission) ).collect(Collectors.toList()); sysUserInfoDTO.setPermissions(permissions); return sysUserInfoDTO; } @Override public SysUserVoQuery pageUserVoByQuery(SysUserVoQuery query) { query.setOptimizeCountSql(false); Integer total = sysUserMapper.countUserByQuery(query.getUsername()); query.setTotal(total); sysUserMapper.pageUserVoByQuery(query); return query; } @Transactional(rollbackFor = Exception.class) @Override public Boolean save(SysUserVo sysUserVo) { // 新增用户 SysUser sysUser = new SysUser(); BeanUtils.copyProperties(sysUserVo, sysUser); sysUser.setPassword(passwordEncoder.encode(PasswordEncoderEnum.BCRYPT.getValue() + sysUser.getPassword())); this.save(sysUser); sysUserVo.setUserId(sysUser.getUserId()); // 角色用户信息维护 bindUserWithRole(sysUserVo); return Boolean.TRUE; } @Transactional(rollbackFor = Exception.class) @Override public Boolean update(SysUserVo sysUserVo) { // 新增用户 SysUser sysUser = new SysUser(); BeanUtils.copyProperties(sysUserVo, sysUser); this.updateById(sysUser); // 删除原来的角色用户绑定信息 deleteUserWithRole(sysUserVo.getUserId()); // 角色用户信息维护 bindUserWithRole(sysUserVo); return Boolean.TRUE; } @Transactional(rollbackFor = Exception.class) @Override public Boolean delete(Integer userId) { this.removeById(userId); // 删除原来的角色用户绑定信息 deleteUserWithRole(userId); return Boolean.TRUE; } /** * 绑定用户与角色信息 * @param sysUserVo */ private void bindUserWithRole(SysUserVo sysUserVo) { sysUserVo.getSysRoleVoList().forEach(role -> { SysUserRole sysUserRole = new SysUserRole(); sysUserRole.setRoleId(role.getRoleId()); sysUserRole.setUserId(sysUserVo.getUserId()); sysUserRoleMapper.insert(sysUserRole); }); } /** * 删除用户与角色信息 * @param userId */ private void deleteUserWithRole(Integer userId) { QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>(); wrapper.lambda().eq(SysUserRole::getUserId, userId); sysUserRoleMapper.delete(wrapper); } }
belyokhin/trusteeWallet
crypto/blockchains/bch/BchScannerProcessor.js
<reponame>belyokhin/trusteeWallet /** * @version 0.11 * https://developer.bitcoin.com/rest/docs/address => trezor */ import DogeScannerProcessor from '../doge/DogeScannerProcessor' import BtcCashUtils from './ext/BtcCashUtils' export default class BchScannerProcessor extends DogeScannerProcessor{ /** * @type {number} * @private */ _blocksToConfirm = 5 /** * @type {string} * @private */ _trezorServerCode = 'BCH_TREZOR_SERVER' async _get(address, jsonData) { let legacyAddress if (typeof jsonData.legacyAddress !== 'undefined') { legacyAddress = jsonData.legacyAddress } else { legacyAddress = BtcCashUtils.toLegacyAddress(address) } return super._get(legacyAddress) } _addressesForFind(address, jsonData) { let legacyAddress if (typeof jsonData.legacyAddress !== 'undefined') { legacyAddress = jsonData.legacyAddress } else { legacyAddress = BtcCashUtils.toLegacyAddress(address) } return [address, legacyAddress, 'bitcoincash:' + address] } }
danifeijo/JS-Practica
PracticaJS/js/17.js
<filename>PracticaJS/js/17.js const numero1 = 20 ; const numero2 = '20'; console.log (parseInt(numero2)) ; // es una funcion console.log(numero1.toString()) ; // es un metodo
sjj3086786/aliyun-openapi-java-sdk
aliyun-java-sdk-dm/src/main/java/com/aliyuncs/dm/simple/MailSender.java
<reponame>sjj3086786/aliyun-openapi-java-sdk package com.aliyuncs.dm.simple; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.concurrent.*; public class MailSender { private static final int DEFAULT_POOL_SIZE = 10; private static final int SHUTDOWN_WAIT_SECONDS = 5; private static final String EMAIL_ENCODING = "utf-8"; private static final String X_SMTP_TRANS_PARAM = "X-SMTP-TRANS-PARAM"; private Session session; public MailSender(String host, String port, final String userName, final String password) { final Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }; session = Session.getInstance(props, authenticator); } public List<String> batchSendMail(final List<Email> emailList) { List<String> rtnList = new ArrayList<String>(); ExecutorService executor = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); final CountDownLatch countDownLatch = new CountDownLatch(emailList.size()); List<Future<String>> resultList = new ArrayList<Future<String>>(); for (int i = 0; i < emailList.size(); i++) { Future<String> f = executor.submit(new SendTask(countDownLatch, emailList.get(i))); resultList.add(f); } try { countDownLatch.await(); for (Future<String> f : resultList) { rtnList.add(f.get()); } executor.shutdown(); executor.awaitTermination(SHUTDOWN_WAIT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { if (!executor.isTerminated()) { System.err.println("cancel non-finished tasks"); } executor.shutdownNow(); System.out.println("shutdown finished"); } return rtnList; } public String sendMail(Email email) { try { MimeMessage mimeMessage = getMimeMessage(email); Transport.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); return e.getMessage(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } return "success"; } private MimeMessage getMimeMessage(Email email) throws MessagingException, UnsupportedEncodingException { MimeMessage message = new MimeMessage(session); setFrom(email, message); setTo(email, message); setCc(email, message); setReplyto(email, message); setSubject(email, message); setContent(email, message); setHeader(email, message); return message; } class SendTask implements Callable<String> { CountDownLatch latch; Email email; SendTask(CountDownLatch countDownLatch, Email email) { this.latch = countDownLatch; this.email = email; } @Override public String call() throws Exception { String result = sendMail(email); latch.countDown(); return result; } } private void setFrom(Email email, MimeMessage message) throws UnsupportedEncodingException, MessagingException { InternetAddress from = null; from = new InternetAddress(email.getFrom().getEmail(), email.getFrom().getName(), EMAIL_ENCODING); message.setFrom(from); } private void setTo(Email email, MimeMessage message) throws UnsupportedEncodingException, MessagingException { Address[] toArr = new InternetAddress[email.getRecipients().size()]; for (int i = 0; i < email.getRecipients().size(); i++) { toArr[i] = new InternetAddress(email.getRecipients().get(i).getEmail(), email.getRecipients().get(i).getName(), EMAIL_ENCODING); } message.setRecipients(MimeMessage.RecipientType.TO, toArr); } private void setCc(Email email, MimeMessage message) throws UnsupportedEncodingException, MessagingException { if(email.getCc() == null) { return ; } Address[] ccArr = new InternetAddress[email.getCc().size()]; for (int i = 0; i < email.getCc().size(); i++) { ccArr[i] = new InternetAddress(email.getCc().get(i).getEmail(), email.getCc().get(i).getName(), EMAIL_ENCODING); } if(ccArr != null && ccArr.length > 0) { message.setRecipients(MimeMessage.RecipientType.CC, ccArr); } } private void setSubject(Email email, MimeMessage message) throws UnsupportedEncodingException, MessagingException { message.setSubject(email.getSubject()); if (email.getHeaders() != null && email.getHeaders().size() > 0) { for (Map.Entry e : email.getHeaders().entrySet()) { message.setHeader((String) e.getKey(), (String) e.getValue()); } } } private void setReplyto(Email email, MimeMessage message) throws UnsupportedEncodingException, MessagingException { Address[] a = new Address[1]; a[0] = new InternetAddress(email.getReplyToAddress().getEmail(), email.getReplyToAddress().getName() == null ? "" : email.getReplyToAddress().getName()); message.setReplyTo(a); } private void setContent(Email email, MimeMessage message) throws UnsupportedEncodingException, MessagingException { Multipart multipart = new MimeMultipart(); if (email.getText() != null) { final MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(email.getText(), EMAIL_ENCODING); multipart.addBodyPart(messagePart); } if (email.getTextHTML() != null) { final MimeBodyPart messagePartHTML = new MimeBodyPart(); messagePartHTML.setContent(email.getTextHTML(), "text/html; charset=\"" + EMAIL_ENCODING + "\""); multipart.addBodyPart(messagePartHTML); } // attachment if (email.getAttachments() != null && email.getAttachments().size() > 0) { for (Email.Attachment ea : email.getAttachments()) { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = ea.getDataSource(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(ea.getName()); multipart.addBodyPart(messageBodyPart); } } message.setContent(multipart); } private void setHeader(Email email, Message message) throws UnsupportedEncodingException, MessagingException { if(email.getTemplateContent() != null && email.getTemplateContent().length() > 0) { email.getHeaders().put(X_SMTP_TRANS_PARAM, email.getTemplateContent()); } for(Map.Entry<String, String> header : email.getHeaders().entrySet()) { String name = header.getKey(); String value = MimeUtility.encodeText(header.getValue(), EMAIL_ENCODING, null); String foldedHeaderValue = MimeUtility.fold(name.length() + 2, value); message.addHeader(header.getKey(), foldedHeaderValue); } } }
AllanMangeni/Tatum-crypto-exchange
node_modules/stellar-base/lib/account.js
<reponame>AllanMangeni/Tatum-crypto-exchange<filename>node_modules/stellar-base/lib/account.js<gh_stars>0 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Account = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _bignumber = require('bignumber.js'); var _bignumber2 = _interopRequireDefault(_bignumber); var _isString = require('lodash/isString'); var _isString2 = _interopRequireDefault(_isString); var _strkey = require('./strkey'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Create a new Account object. * * `Account` represents a single account in Stellar network and its sequence number. * Account tracks the sequence number as it is used by {@link TransactionBuilder}. * See [Accounts](https://stellar.org/developers/learn/concepts/accounts.html) for more information about how * accounts work in Stellar. * @constructor * @param {string} accountId ID of the account (ex. `<KEY>`) * @param {string} sequence current sequence number of the account */ var Account = exports.Account = function () { function Account(accountId, sequence) { _classCallCheck(this, Account); if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) { throw new Error('accountId is invalid'); } if (!(0, _isString2.default)(sequence)) { throw new Error('sequence must be of type string'); } this._accountId = accountId; this.sequence = new _bignumber2.default(sequence); } /** * Returns Stellar account ID, ex. `<KEY>` * @returns {string} */ _createClass(Account, [{ key: 'accountId', value: function accountId() { return this._accountId; } /** * @returns {string} */ }, { key: 'sequenceNumber', value: function sequenceNumber() { return this.sequence.toString(); } /** * Increments sequence number in this object by one. * @returns {void} */ }, { key: 'incrementSequenceNumber', value: function incrementSequenceNumber() { this.sequence = this.sequence.add(1); } }]); return Account; }();
yudong2015/openpitrix
pkg/service/category/handler.go
<filename>pkg/service/category/handler.go // Copyright 2018 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. package category import ( "context" "time" "openpitrix.io/openpitrix/pkg/client/attachment" "openpitrix.io/openpitrix/pkg/constants" "openpitrix.io/openpitrix/pkg/db" "openpitrix.io/openpitrix/pkg/gerr" "openpitrix.io/openpitrix/pkg/logger" "openpitrix.io/openpitrix/pkg/manager" "openpitrix.io/openpitrix/pkg/models" "openpitrix.io/openpitrix/pkg/pb" "openpitrix.io/openpitrix/pkg/pi" "openpitrix.io/openpitrix/pkg/util/ctxutil" "openpitrix.io/openpitrix/pkg/util/imageutil" "openpitrix.io/openpitrix/pkg/util/pbutil" "openpitrix.io/openpitrix/pkg/util/stringutil" ) func (p *Server) DescribeCategories(ctx context.Context, req *pb.DescribeCategoriesRequest) (*pb.DescribeCategoriesResponse, error) { var categories []*models.Category offset := pbutil.GetOffsetFromRequest(req) limit := pbutil.GetLimitFromRequest(req) displayColumns := manager.GetDisplayColumns(req.GetDisplayColumns(), models.CategoryColumns) query := pi.Global().DB(ctx). Select(displayColumns...). From(constants.TableCategory). Offset(offset). Limit(limit). Where(manager.BuildPermissionFilter(ctx)). Where(manager.BuildFilterConditions(req, constants.TableCategory)) // TODO: validate sort_key query = manager.AddQueryOrderDir(query, req, constants.ColumnCreateTime) if len(displayColumns) > 0 { _, err := query.Load(&categories) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } } count, err := query.Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } res := &pb.DescribeCategoriesResponse{ CategorySet: models.CategoriesToPbs(categories), TotalCount: count, } return res, nil } func (p *Server) CreateCategory(ctx context.Context, req *pb.CreateCategoryRequest) (*pb.CreateCategoryResponse, error) { s := ctxutil.GetSender(ctx) category := models.NewCategory( req.GetName().GetValue(), req.GetLocale().GetValue(), req.GetDescription().GetValue(), s.GetOwnerPath()) var iconAttachmentId string if req.GetIcon() != nil { // upload icon attachment attachmentManagerClient, err := attachmentclient.NewAttachmentManagerClient() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } icon := req.GetIcon().GetValue() content, err := imageutil.Thumbnail(ctx, icon) if err != nil { logger.Error(ctx, "Make thumbnail failed: %+v", err) return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorImageDecodeFailed) } createAttachmentRes, err := attachmentManagerClient.CreateAttachment(ctx, &pb.CreateAttachmentRequest{ AttachmentContent: content, }) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } iconAttachmentId = createAttachmentRes.AttachmentId } category.Icon = iconAttachmentId _, err := pi.Global().DB(ctx). InsertInto(constants.TableCategory). Record(category). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorCreateResourcesFailed) } res := &pb.CreateCategoryResponse{ CategoryId: pbutil.ToProtoString(category.CategoryId), } return res, nil } func (p *Server) ModifyCategory(ctx context.Context, req *pb.ModifyCategoryRequest) (*pb.ModifyCategoryResponse, error) { // TODO: check resource permission categoryId := req.GetCategoryId().GetValue() category, err := p.getCategory(ctx, categoryId) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } attributes := manager.BuildUpdateAttributes(req, constants.ColumnName, constants.ColumnLocale, constants.ColumnDescription) attributes[constants.ColumnUpdateTime] = time.Now() if req.GetIcon() != nil { // upload or replace icon attachment attachmentManagerClient, err := attachmentclient.NewAttachmentManagerClient() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } content, err := imageutil.Thumbnail(ctx, req.GetIcon().GetValue()) if err != nil { logger.Error(ctx, "Make thumbnail failed: %+v", err) return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorImageDecodeFailed) } if category.Icon == "" { createAttachmentRes, err := attachmentManagerClient.CreateAttachment(ctx, &pb.CreateAttachmentRequest{ AttachmentContent: content, }) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } attributes[constants.ColumnIcon] = createAttachmentRes.AttachmentId } else { _, err := attachmentManagerClient.ReplaceAttachment(ctx, &pb.ReplaceAttachmentRequest{ AttachmentId: category.Icon, AttachmentContent: content, }) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } } } _, err = pi.Global().DB(ctx). Update(constants.TableCategory). SetMap(attributes). Where(db.Eq(constants.ColumnCategoryId, categoryId)). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorModifyResourcesFailed) } res := &pb.ModifyCategoryResponse{ CategoryId: req.GetCategoryId(), } return res, nil } func (p *Server) DeleteCategories(ctx context.Context, req *pb.DeleteCategoriesRequest) (*pb.DeleteCategoriesResponse, error) { categoryIds := req.GetCategoryId() if stringutil.StringIn(models.UncategorizedId, categoryIds) { return nil, gerr.New(ctx, gerr.PermissionDenied, gerr.ErrorCannotDeleteDefaultCategory) } _, err := pi.Global().DB(ctx). DeleteFrom(constants.TableCategory). Where(db.Eq(constants.ColumnCategoryId, categoryIds)). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDeleteResourcesFailed) } return &pb.DeleteCategoriesResponse{ CategoryId: categoryIds, }, nil }
flashboss/rubia-forums
rubia-forums-jsf/src/test/java/it/vige/rubia/selenium/moderate/action/RemoveForum.java
<reponame>flashboss/rubia-forums<filename>rubia-forums-jsf/src/test/java/it/vige/rubia/selenium/moderate/action/RemoveForum.java package it.vige.rubia.selenium.moderate.action; import static it.vige.rubia.properties.OperationType.CONFIRM; import static org.openqa.selenium.By.className; import static org.openqa.selenium.By.linkText; import static org.openqa.selenium.By.tagName; import static org.openqa.selenium.By.xpath; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import it.vige.rubia.dto.ForumBean; import it.vige.rubia.dto.TopicBean; import it.vige.rubia.properties.OperationType; public class RemoveForum { public static final String REMOVE_LINK = "buttonMed"; public static final String REMOVE_FORUM_LINK = "buttonMed"; public static final String SELECT_TYPE = "form"; public static final String RESULT_REMOVE_FORUM = "forumtitletext"; public static String removeForum(WebDriver driver, OperationType removeType, ForumBean forum) { if (forum != null) for (TopicBean topic : forum.getTopics()) { WebElement topicToSelect = driver.findElement(linkText(topic.getSubject())) .findElement(xpath("../../td[5]/input")); topicToSelect.click(); } WebElement removeForum = driver.findElements(className(REMOVE_LINK)).get(0); removeForum.click(); String message = ""; WebElement resultRemoveForum = null; try { resultRemoveForum = driver.findElement(className(RESULT_REMOVE_FORUM)) .findElement(xpath("//table/tbody/tr/td")); message = resultRemoveForum.getText(); } catch (NoSuchElementException ex) { if (removeType == CONFIRM) { WebElement option = driver.findElements(tagName(SELECT_TYPE)).get(1).findElement(xpath("input[3]")); option.click(); resultRemoveForum = driver.findElement(className(RESULT_REMOVE_FORUM)) .findElement(xpath("//table/tbody/tr/td")); message = resultRemoveForum.getText(); } else { WebElement option = driver.findElements(tagName(SELECT_TYPE)).get(1).findElement(xpath("input[4]")); option.click(); } return message; } return message; } }
kleineroscar/jare
src/main/java/com/datamelt/util/AvroSchemaUtility.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 com.datamelt.util; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.Schema.Field; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericRecord; import org.apache.avro.util.Utf8; /** * utility class to simplify the retrieval of fields and data of an Avro file. * * * @author <NAME> */ public class AvroSchemaUtility { private static final String FIELDTYPE_UNION = "union"; private static final String COMPLEX_TYPE_RECORD = "record"; private List<Field> fields; /* * constructor for AvroSchemaUtility object. * * note that only schemas with a complex type = RECORD are processed. * * @param avroSchema an Avro schema */ public AvroSchemaUtility (Schema avroSchema) throws Exception { Type schemaType = avroSchema.getType(); if(!schemaType.getName().toLowerCase().equals(COMPLEX_TYPE_RECORD)) { throw new Exception("complex type of the Avro schema is not equal to [RECORD]"); } this.fields = avroSchema.getFields(); } /* * method to return an array of field types * * @return array of field types */ public String[] getFieldTypes() throws Exception { String[] fieldTypes = new String[fields.size()]; for(int i=0;i<fields.size();i++) { Type fieldType = getFieldType(fields.get(i)); fieldTypes[i] = fieldType.getName(); } return fieldTypes; } /** * retrieves the type of the field from an Avro schema * * the type of a field is defined in the Avro schema. The type can have one or two values: * either it has simply a single type of string, int, float, etc. (see Avro documentation for possible types) * or it can have the type of "null". If more than these two types are defined, this method will throw an * exception, as the type can not be determined. Otherwise the method will return the type (string, int, etc.). * * @param schemaField the Avro schema field * @throws Exception exception thrown when a field has more than two possible types * @return the Avro type of the field */ public Type getFieldType(Field schemaField) throws Exception { // get the fields schema Schema schema = schemaField.schema(); // get the fields type Type fieldType = schema.getType(); // if the field is a union then loop over the types if(fieldType.getName().equals(FIELDTYPE_UNION)) { for (Schema s : schema.getTypes()) { // if we have two types and one is null, then the other one is the type if(schema.getTypes().size()==2) { if (s.getType() != Type.NULL ) { fieldType = s.getType(); } } // we have more than two types else { throw new Exception("field: [" + schemaField.name() + "] has more than two possible values for the type - can not determine type"); } } } return fieldType; } /** * extracts the names of all fields of a complex type=RECORD from * an Avro schema * * @return an array of field names */ public String[] getFieldNames() { String[] fieldNames = new String[fields.size()]; for(int i=0;i<fields.size();i++) { fieldNames[i] = fields.get(i).name(); } return fieldNames; } /** * Collects all values of the avro record for the array of field names * * @param record an avro record * @return array of objects */ public Object[] getGenericRecordData(GenericRecord record) { Object[] objects = new Object[getFieldNames().length]; for(int i=0;i<getFieldNames().length;i++) { objects[i] = record.get(getFieldNames()[i]); if(objects[i] instanceof Utf8) { objects[i] = objects[i].toString(); } } return objects; } }
brown-ccv/VRG3D
vrbase/ViewerHCI.cpp
<gh_stars>0 #include "ViewerHCI.H" #include "ConfigVal.H" #include "StringUtils.H" namespace VRBase { using namespace G3D; ViewerHCI::ViewerHCI(EventMgrRef eventMgr, GfxMgrRef gfxMgr) { _eventMgr = eventMgr; _gfxMgr = gfxMgr; _rocking = false; _rockingDir = 1.0; _totalAngle = 0.0; _rotAngularVel = ConfigVal("ViewerHCI_RockingSpeed", 0.35, false); _rockingAngle = ConfigVal("ViewerHCI_RockingAngle", 0.8, false); _boundingSphere = Sphere(Vector3::zero(), ConfigVal("ViewerHCI_TrackballRad", 0.55, false)); _panAmt = ConfigVal("ViewerHCI_PanIncrement", 0.05, false); _fsa = new Fsa("ViewerHCI FSA"); _fsa->addState("Start"); _fsa->addState("Trackball"); _fsa->addArc("TrackOn", "Start", "Trackball", splitStringIntoArray(ConfigVal("ViewerHCI_TrackballOn", "Mouse_Left_Btn_down", false))); _fsa->addArcCallback("TrackOn", this, &ViewerHCI::trackballOn); _fsa->addArc("TrackMove", "Trackball", "Trackball", splitStringIntoArray("Mouse_Pointer")); _fsa->addArcCallback("TrackMove", this, &ViewerHCI::trackballMove); _fsa->addArc("TrackOff", "Trackball", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_TrackballOff", "Mouse_Left_Btn_up", false))); _fsa->addArcCallback("TrackOff", this, &ViewerHCI::trackballOff); _fsa->addArc("Rock", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_ToggleRocking", "kbd_SPACE_down", false))); _fsa->addArcCallback("Rock", this, &ViewerHCI::toggleRocking); _fsa->addArc("ScaleUp", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_ScaleUp", "kbd_PAGEUP_down", false))); _fsa->addArcCallback("ScaleUp", this, &ViewerHCI::scaleUp); _fsa->addArc("ScaleDown", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_ScaleDown", "kbd_PAGEDOWN_down", false))); _fsa->addArcCallback("ScaleDown", this, &ViewerHCI::scaleDown); _fsa->addArc("DollyIn", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_DollyIn", "kbd_I_down", false))); _fsa->addArcCallback("DollyIn", this, &ViewerHCI::dollyIn); _fsa->addArc("DollyOut", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_DollyOut", "kbd_O_down", false))); _fsa->addArcCallback("DollyOut", this, &ViewerHCI::dollyOut); _fsa->addArc("PanUp", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_PanUp", "kbd_UP_down", false))); _fsa->addArcCallback("PanUp", this, &ViewerHCI::panUp); _fsa->addArc("PanDown", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_PanDown", "kbd_DOWN_down", false))); _fsa->addArcCallback("PanDown", this, &ViewerHCI::panDown); _fsa->addArc("PanLeft", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_PanLeft", "kbd_LEFT_down", false))); _fsa->addArcCallback("PanLeft", this, &ViewerHCI::panLeft); _fsa->addArc("PanRight", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_PanRight", "kbd_RIGHT_down", false))); _fsa->addArcCallback("PanRight", this, &ViewerHCI::panRight); _fsa->addArc("SpeedUpRock", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_SpeedUpRocking", "kbd_F_down", false))); _fsa->addArcCallback("SpeedUpRock", this, &ViewerHCI::speedUpRocking); _fsa->addArc("SlowDownRock", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_SlowDownRocking", "kbd_S_down", false))); _fsa->addArcCallback("SlowDownRock", this, &ViewerHCI::slowDownRocking); _fsa->addArc("IncRockAng", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_IncRockingAngle", "kbd_W_down", false))); _fsa->addArcCallback("IncRockAng", this, &ViewerHCI::incRockingAngle); _fsa->addArc("DecRockAng", "Start", "Start", splitStringIntoArray(ConfigVal("ViewerHCI_DecRockingAngle", "kbd_N_down", false))); _fsa->addArcCallback("DecRockAng", this, &ViewerHCI::decRockingAngle); _eventMgr->addFsaRef(_fsa); } ViewerHCI::~ViewerHCI() { } void ViewerHCI::trackballOn(VRG3D::EventRef e) { _lastIntersectionPt = Vector3::inf(); } void ViewerHCI::trackballMove(VRG3D::EventRef e) { Vector2 newPos = e->get2DData(); // All coordinates here in RoomSpace Vector3 orig = _gfxMgr->getCamera()->getCameraPos(); Vector3 dir = (_gfxMgr->screenPointToRoomSpaceFilmplane(newPos) - orig).unit(); Ray r = Ray::fromOriginAndDirection(orig, dir); double t = r.intersectionTime(_boundingSphere); if ((isFinite(t)) && (t > 0)) { Vector3 intersectionPt = orig + t*dir; if (_lastIntersectionPt != Vector3::inf()) { Vector3 v1 = (_lastIntersectionPt - _boundingSphere.center).unit(); Vector3 v2 = (intersectionPt - _boundingSphere.center).unit(); Vector3 rotAxis = v1.cross(v2).unit(); double dot = v1.dot(v2); double angle = -aCos(dot); if ((rotAxis.isFinite()) && (!rotAxis.isZero())) { Matrix3 rot = Matrix3::fromAxisAngle(rotAxis, angle); rot.orthonormalize(); CoordinateFrame frame = CoordinateFrame(_boundingSphere.center) * CoordinateFrame(rot, Vector3::zero()) * CoordinateFrame(-_boundingSphere.center); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * frame); } } _lastIntersectionPt = intersectionPt; } else { _lastIntersectionPt = Vector3::inf(); } } void ViewerHCI::trackballOff(VRG3D::EventRef e) { } void ViewerHCI::toggleRocking(VRG3D::EventRef e) { _rocking = !_rocking; if (_rocking) { _lastRotTime = -1; _animationCallbackID = _gfxMgr->addPoseCallback(this, &ViewerHCI::poseForAnimation); } else { _gfxMgr->removePoseCallback(_animationCallbackID); } } void ViewerHCI::poseForAnimation(Array<SurfaceRef> &posedModels, const CoordinateFrame &virtualToRoomSpace) { double now = SynchedSystem::getLocalTime(); if (_lastRotTime == -1) { _lastRotTime = now; } else { double deltaT = now - _lastRotTime; _lastRotTime = now; double angle = _rotAngularVel * deltaT; if (_rockingDir < 0.0) { angle = -angle; } _totalAngle += angle; if (fabs(_totalAngle) > _rockingAngle) { if (_totalAngle > 0.0) { _rockingDir = -1.0; } else { _rockingDir = 1.0; } } Vector3 rotAxis(0,1,0); Matrix3 r = Matrix3::fromAxisAngle(rotAxis, angle); CoordinateFrame f = CoordinateFrame(_boundingSphere.center) * CoordinateFrame(r, Vector3::zero()) * CoordinateFrame(-_boundingSphere.center); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * f); } } void ViewerHCI::panLeft(VRG3D::EventRef e) { CoordinateFrame t(Vector3(_panAmt,0,0)); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * t); } void ViewerHCI::panRight(VRG3D::EventRef e) { CoordinateFrame t(Vector3(-_panAmt,0,0)); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * t); } void ViewerHCI::panUp(VRG3D::EventRef e) { CoordinateFrame t(Vector3(0,-_panAmt,0)); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * t); } void ViewerHCI::panDown(VRG3D::EventRef e) { CoordinateFrame t(Vector3(0,_panAmt,0)); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * t); } void ViewerHCI::dollyIn(VRG3D::EventRef e) { CoordinateFrame t(Vector3(0,0,-_panAmt)); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * t); } void ViewerHCI::dollyOut(VRG3D::EventRef e) { CoordinateFrame t(Vector3(0,0,_panAmt)); _gfxMgr->setRoomToVirtualSpaceFrame(_gfxMgr->getRoomToVirtualSpaceFrame() * t); } void ViewerHCI::scaleUp(VRG3D::EventRef e) { _gfxMgr->setRoomToVirtualSpaceScale(0.95 * _gfxMgr->getRoomToVirtualSpaceScale()); } void ViewerHCI::scaleDown(VRG3D::EventRef e) { _gfxMgr->setRoomToVirtualSpaceScale(1.05 * _gfxMgr->getRoomToVirtualSpaceScale()); } void ViewerHCI::speedUpRocking(VRG3D::EventRef e) { _rotAngularVel += 0.05; } void ViewerHCI::slowDownRocking(VRG3D::EventRef e) { _rotAngularVel -= 0.05; } void ViewerHCI::incRockingAngle(VRG3D::EventRef e) { _rockingAngle += 0.05; } void ViewerHCI::decRockingAngle(VRG3D::EventRef e) { _rockingAngle -= 0.05; } } // namespace
cquoss/jboss-4.2.3.GA-jdk8
system/src/main/org/jboss/deployment/ClasspathExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.deployment; import java.net.URL; import javax.management.ObjectName; import org.jboss.mx.loading.LoaderRepositoryFactory; import org.jboss.mx.loading.RepositoryClassLoader; import org.jboss.system.ServiceMBeanSupport; /** A service that allows one to add an arbitrary URL to a named LoaderRepository. * * Created: Sun Jun 30 13:17:22 2002 * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Revision: 57205 $ * * @jmx:mbean name="jboss:type=Service,service=ClasspathExtension" * extends="org.jboss.system.ServiceMBean" */ public class ClasspathExtension extends ServiceMBeanSupport implements ClasspathExtensionMBean { private String metadataURL; private ObjectName loaderRepository; private RepositoryClassLoader ucl; public ClasspathExtension() { } /** * mbean get-set pair for field metadataURL * Get the value of metadataURL * @return value of metadataURL * * @jmx:managed-attribute */ public String getMetadataURL() { return metadataURL; } /** * Set the value of metadataURL * @param metadataURL Value to assign to metadataURL * * @jmx:managed-attribute */ public void setMetadataURL(String metadataURL) { this.metadataURL = metadataURL; } /** * mbean get-set pair for field loaderRepository * Get the value of loaderRepository * @return value of loaderRepository * * @jmx:managed-attribute */ public ObjectName getLoaderRepository() { return loaderRepository; } /** * Set the value of loaderRepository * @param loaderRepository Value to assign to loaderRepository * * @jmx:managed-attribute */ public void setLoaderRepository(ObjectName loaderRepository) { this.loaderRepository = loaderRepository; } protected void createService() throws Exception { if (metadataURL != null) { URL url = new URL(metadataURL); if( loaderRepository == null ) loaderRepository = LoaderRepositoryFactory.DEFAULT_LOADER_REPOSITORY; Object[] args = {url, url, Boolean.TRUE}; String[] sig = {"java.net.URL", "java.net.URL", "boolean"}; ucl = (RepositoryClassLoader) server.invoke(loaderRepository, "newClassLoader",args, sig); } // end of if () } protected void destroyService() throws Exception { if (ucl != null) ucl.unregister(); } }// ClasspathExtension
felipeorlando/k121
api/routes/auth.js
<gh_stars>1-10 import express from 'express'; import AuthController from '../controllers/auth'; class AuthRoute { constructor() { this.router = express.Router(); this.authController = new AuthController(); } init() { return this.router .post('/check', this.authController.check) .post('/login', this.authController.login); } } export default AuthRoute;
rokka-io/rokka-ui
src/components/operations/StackOperation.js
import React, { Fragment } from 'react' import StringStackOption from '../options/StringStackOption' import SelectStackOption from '../options/SelectStackOption' import { readableInputLabel } from '../../utils/string' import RangeStackOption from '../options/RangeStackOption' import ColorStackOption from '../options/ColorStackOption' import BooleanStackOption from '../options/BooleanStackOption' const SORT_ORDERS = { integer: 4, number: 4, boolean: 3, string: 2, color: 2, default: 0 } /** * Returns the type used for sorting * @param {String} name * @param {String} type * @param {Object} definition * @returns {Integer} */ function getSortOrder(name, { type, ...definition }) { if (name.includes('color')) { return SORT_ORDERS['color'] } return SORT_ORDERS[type] || SORT_ORDERS['default'] } export default function StackOperation({ availableOperations = {}, name, values, onChange = null, errors = {}, ...props }) { if (!availableOperations[name]) { return null } const { properties, required = [] } = availableOperations[name] const sortedProps = Object.keys(properties).sort( (a, b) => getSortOrder(b, properties[b]) - getSortOrder(a, properties[a]) ) const $rows = sortedProps.map(name => { const definition = properties[name] const operationProps = { key: name, label: readableInputLabel(name), name, definitions: definition, value: values[name], onChange, error: errors[name], required: required.includes(name) } if (Array.isArray(definition.values)) { return <SelectStackOption {...operationProps} /> } if (name.includes('color')) { return <ColorStackOption {...operationProps} /> } switch (definition.type) { case 'number': // fallthrough case 'integer': if (onChange) { return <RangeStackOption {...operationProps} /> } return <StringStackOption {...operationProps} /> case 'boolean': return <BooleanStackOption {...operationProps} /> default: return <StringStackOption {...operationProps} /> } }) return <Fragment>{$rows}</Fragment> }
mostynb/webrtc
examples/objc/AppRTCDemo/ARDSDPUtils.h
/* * Copyright 2015 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #import <Foundation/Foundation.h> @class RTCSessionDescription; @interface ARDSDPUtils : NSObject // Updates the original SDP description to instead prefer the specified video // codec. We do this by placing the specified codec at the beginning of the // codec list if it exists in the sdp. + (RTCSessionDescription *) descriptionForDescription:(RTCSessionDescription *)description preferredVideoCodec:(NSString *)codec; @end
kanzankazu/OG
app/src/main/java/com/gandsoft/openguide/model/BaseExpandableListModel.java
<reponame>kanzankazu/OG<gh_stars>0 package com.gandsoft.openguide.model; import java.util.ArrayList; import java.util.List; public class BaseExpandableListModel { private String title; private String info; private List<SubBaseExpanderListModel> detail = new ArrayList<>(); public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setInfo(String info) { this.info = info; } public String getInfo() { return info; } public List<SubBaseExpanderListModel> getDetail() { return detail; } public void setDetail(List<SubBaseExpanderListModel> detail) { this.detail = detail; } }
directionless/google-cloud-ruby
google-cloud-trace/lib/google/cloud/trace/span.rb
# Copyright 2014 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "set" require "google/devtools/cloudtrace/v1/trace_pb" module Google module Cloud module Trace ## # Span represents a span in a trace record. Spans are contained in # a trace and arranged in a forest. That is, each span may be a root span # or have a parent span, and may have zero or more children. # class Span ## # The Trace object containing this span. # # @return [Google::Cloud::Trace::TraceRecord] # attr_reader :trace ## # The TraceSpan object representing this span's parent, or `nil` if # this span is a root span. # # @return [Google::Cloud::Trace::Span, nil] # attr_reader :parent ## # The numeric ID of this span. # # @return [Integer] # attr_reader :span_id ## # The ID of the parent span, as an integer that may be zero if this # is a true root span. # # Note that it is possible for a span to be "orphaned", that is, to be # a root span with a nonzero parent ID, indicating that parent has not # (yet) been written. In that case, `parent` will return nil, but # `parent_span_id` will have a value. # # @return [Integer] # attr_reader :parent_span_id ## # The kind of this span. # # @return [Google::Cloud::Trace::SpanKind] # attr_accessor :kind ## # The name of this span. # # @return [String] # attr_accessor :name ## # The starting timestamp of this span in UTC, or `nil` if the # starting timestamp has not yet been populated. # # @return [Time, nil] # attr_accessor :start_time ## # The ending timestamp of this span in UTC, or `nil` if the # ending timestamp has not yet been populated. # # @return [Time, nil] # attr_accessor :end_time ## # The properties of this span. # # @return [Hash{String => String}] # attr_reader :labels ## # Create an empty Span object. # # @private # def initialize trace, id, parent_span_id, parent, name, kind, start_time, end_time, labels @trace = trace @span_id = id @parent_span_id = parent_span_id @parent = parent @children = [] @name = name @kind = kind @start_time = start_time @end_time = end_time @labels = labels end # rubocop:disable Metrics/AbcSize ## # Standard value equality check for this object. # # @param [Object] other # @return [Boolean] # def eql? other other.is_a?(Google::Cloud::Trace::Span) && trace.trace_context == other.trace.trace_context && span_id == other.span_id && parent_span_id == other.parent_span_id && same_children?(other) && kind == other.kind && name == other.name && start_time == other.start_time && end_time == other.end_time && labels == other.labels end alias == eql? # rubocop:enable Metrics/AbcSize ## # Create a new Span object from a TraceSpan protobuf and insert it # into the given trace. # # @param [Google::Devtools::Cloudtrace::V1::TraceSpan] span_proto The # span protobuf from the V1 gRPC Trace API. # @param [Google::Cloud::Trace::TraceRecord] trace The trace object # to contain the span. # @return [Google::Cloud::Trace::Span] A corresponding Span object. # def self.from_grpc span_proto, trace labels = {} span_proto.labels.each { |k, v| labels[k] = v } span_kind = SpanKind.get span_proto.kind start_time = Google::Cloud::Trace::Utils.grpc_to_time span_proto.start_time end_time = Google::Cloud::Trace::Utils.grpc_to_time span_proto.end_time trace.create_span span_proto.name, parent_span_id: span_proto.parent_span_id.to_i, span_id: span_proto.span_id.to_i, kind: span_kind, start_time: start_time, end_time: end_time, labels: labels end ## # Convert this Span object to an equivalent TraceSpan protobuf suitable # for the V1 gRPC Trace API. # # @param [Integer] default_parent_id The parent span ID to use if the # span has no parent in the trace tree. Optional; defaults to 0. # @return [Google::Devtools::Cloudtrace::V1::TraceSpan] The generated # protobuf. # def to_grpc default_parent_id = 0 start_proto = Google::Cloud::Trace::Utils.time_to_grpc start_time end_proto = Google::Cloud::Trace::Utils.time_to_grpc end_time Google::Devtools::Cloudtrace::V1::TraceSpan.new \ span_id: span_id.to_i, kind: kind.to_sym, name: name, start_time: start_proto, end_time: end_proto, parent_span_id: parent_span_id || default_parent_id, labels: labels end ## # Returns true if this span exists. A span exists until it has been # removed from its trace. # # @return [Boolean] # def exists? !@trace.nil? end ## # Returns the trace context in effect within this span. # # @return [Stackdriver::Core::TraceContext] # def trace_context ensure_exists! trace.trace_context.with span_id: span_id end ## # Returns the trace ID for this span. # # @return [String] The trace ID string. # def trace_id ensure_exists! trace.trace_id end ## # Returns a list of children of this span. # # @return [Array{TraceSpan}] The children. # def children ensure_exists! @children.dup end ## # Creates a new child span under this span. # # @param [String] name The name of the span. # @param [Integer] span_id The numeric ID of the span, or nil to # generate a new random unique ID. Optional (defaults to nil). # @param [SpanKind] kind The kind of span. Optional. # @param [Time] start_time The starting timestamp, or nil if not yet # specified. Optional (defaults to nil). # @param [Time] end_time The ending timestamp, or nil if not yet # specified. Optional (defaults to nil). # @param [Hash{String=>String}] labels The span properties. Optional # (defaults to empty). # @return [TraceSpan] The created span. # # @example # require "google/cloud/trace" # # trace_record = Google::Cloud::Trace::TraceRecord.new "my-project" # span = trace_record.create_span "root_span" # subspan = span.create_span "subspan" # def create_span name, span_id: nil, kind: SpanKind::UNSPECIFIED, start_time: nil, end_time: nil, labels: {} ensure_exists! span = trace.internal_create_span self, span_id, self.span_id, name, kind, start_time, end_time, labels @children << span span end ## # Creates a root span around the given block. Automatically populates # the start and end timestamps. The span (with start time but not end # time populated) is yielded to the block. # # @param [String] name The name of the span. # @param [SpanKind] kind The kind of span. Optional. # @param [Hash{String=>String}] labels The span properties. Optional # (defaults to empty). # @return [TraceSpan] The created span. # # @example # require "google/cloud/trace" # # trace_record = Google::Cloud::Trace::TraceRecord.new "my-project" # trace_record.in_span "root_span" do |span| # # Do stuff... # span.in_span "subspan" do |subspan| # # Do subspan stuff... # end # # Do stuff... # end # def in_span name, kind: SpanKind::UNSPECIFIED, labels: {} span = create_span name, kind: kind, labels: labels span.start! yield span ensure span.finish! end ## # Sets the starting timestamp for this span to the current time. # Asserts that the timestamp has not yet been set, and throws a # RuntimeError if that is not the case. # Also ensures that all ancestor spans have already started, and # starts them if not. # def start! raise "Span already started" if start_time ensure_started end ## # Sets the ending timestamp for this span to the current time. # Asserts that the timestamp has not yet been set, and throws a # RuntimeError if that is not the case. # Also ensures that all descendant spans have also finished, and # finishes them if not. # def finish! raise "Span not yet started" unless start_time raise "Span already finished" if end_time ensure_finished end ## # Sets the starting timestamp for this span to the current time, if # it has not yet been set. Also ensures that all ancestor spans have # also been started. # Does nothing if the starting timestamp for this span is already set. # def ensure_started ensure_exists! unless start_time self.start_time = ::Time.now.utc parent.ensure_started if parent end self end ## # Sets the ending timestamp for this span to the current time, if # it has not yet been set. Also ensures that all descendant spans have # also been finished. # Does nothing if the ending timestamp for this span is already set. # def ensure_finished ensure_exists! unless end_time self.end_time = ::Time.now.utc @children.each(&:ensure_finished) end self end ## # Deletes this span, and all descendant spans. After this completes, # {Span#exists?} will return `false`. # def delete ensure_exists! @children.each(&:delete) parent.remove_child(self) if parent trace.remove_span(self) @trace = nil @parent = nil self end ## # Moves this span under a new parent, which must be part of the same # trace. The entire tree under this span moves with it. # # @param [Google::Cloud::Trace::Span] new_parent The new parent. # # @example # require "google/cloud/trace" # # trace_record = Google::Cloud::Trace::TraceRecord.new "my-project" # root1 = trace_record.create_span "root_span_1" # root2 = trace_record.create_span "root_span_2" # subspan = root1.create_span "subspan" # subspan.move_under root2 # def move_under new_parent ensure_exists! ensure_no_cycle! new_parent if parent parent.remove_child self else trace.remove_root self end if new_parent new_parent.add_child self @parent_span_id = new_parent.span_id else trace.add_root self @parent_span_id = 0 end @parent = new_parent self end ## # Add the given span to this span's child list. # # @private # def add_child child @children << child end ## # Remove the given span from this span's child list. # # @private # def remove_child child @children.delete child end ## # Ensure this span exists (i.e. has not been deleted) and throw a # RuntimeError if not. # # @private # def ensure_exists! raise "Span has been deleted" unless trace end ## # Ensure moving this span under the given parent would not result # in a cycle, and throw a RuntimeError if it would. # # @private # def ensure_no_cycle! new_parent ptr = new_parent until ptr.nil? raise "Move would result in a cycle" if ptr.equal?(self) ptr = ptr.parent end end ## # Returns true if this span has the same children as the given other. # # @private # def same_children? other child_ids = @children.map(&:span_id) other_child_ids = other.children.map(&:span_id) ::Set.new(child_ids) == ::Set.new(other_child_ids) end end end end end
hongdongni/onebusaway-application-modules
onebusaway-admin-webapp/src/main/java/org/onebusaway/admin/service/impl/BarcodeServiceImpl.java
/** * Copyright (C) 2015 Cambridge Systematics, 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.onebusaway.admin.service.impl; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.onebusaway.admin.service.BarcodeService; import org.onebusaway.admin.service.RemoteConnectionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BarcodeServiceImpl implements BarcodeService { private RemoteConnectionService remoteConnectionService; @Override public InputStream getQRCodesInBatch(File stopIdFile, int dimensions) throws IOException{ String tdmHost = System.getProperty("tdm.host"); String url = buildURL(tdmHost, "/barcode/batchGen?img-dimension=", dimensions); InputStream barCodeZip = remoteConnectionService.postBinaryData(url, stopIdFile, InputStream.class); return barCodeZip; } private String buildURL(String host, String api, int dimensionParam) { return "http://" + host + "/api" + api + String.valueOf(dimensionParam); } /** * @param remoteConnectionService the remoteConnectionService to set */ @Autowired public void setRemoteConnectionService( RemoteConnectionService remoteConnectionService) { this.remoteConnectionService = remoteConnectionService; } }
wkma/bk-sops
gcloud/core/tasks.py
<filename>gcloud/core/tasks.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging import traceback from contextlib import contextmanager from django.core.cache import cache from celery import task from celery.five import monotonic from celery.task import periodic_task from gcloud import exceptions from gcloud.conf import settings from gcloud.core.project import sync_projects_from_cmdb from pipeline.engine.core.data.api import _backend, _candidate_backend from pipeline.engine.core.data.redis_backend import RedisDataBackend from pipeline.contrib.periodic_task.djcelery.tzcrontab import TzAwareCrontab loggger = logging.getLogger("celery") LOCK_EXPIRE = 60 * 10 LOCK_ID = "cmdb_business_sync_lock" @contextmanager def redis_lock(lock_id, task_id): timeout_at = monotonic() + LOCK_EXPIRE - 3 # cache.add fails if the key already exists status = cache.add(lock_id, task_id, LOCK_EXPIRE) try: yield status finally: # advantage of using add() for atomic locking if monotonic() < timeout_at and status: # don't release the lock if we exceeded the timeout # to lessen the chance of releasing an expired lock # owned by someone else # also don't release the lock if we didn't acquire it cache.delete(lock_id) @periodic_task(run_every=TzAwareCrontab(minute="*/2")) def cmdb_business_sync_task(): task_id = cmdb_business_sync_task.request.id with redis_lock(LOCK_ID, task_id) as acquired: if acquired: loggger.info("Start sync business from cmdb...") try: sync_projects_from_cmdb(username=settings.SYSTEM_USE_API_ACCOUNT, use_cache=False) except exceptions.APIError as e: loggger.error( "An error occurred when sync cmdb business, message: {msg}, trace: {trace}".format( msg=str(e), trace=traceback.format_exc() ) ) else: loggger.info("Can not get sync_business lock, sync operation abandon") @task def migrate_pipeline_parent_data_task(): """ 将 pipeline 的 schedule_parent_data 从 _backend(redis) 迁移到 _candidate_backend(mysql) """ if not isinstance(_backend, RedisDataBackend): loggger.error("[migrate_pipeline_parent_data] _backend should be RedisDataBackend") return if _candidate_backend is None: loggger.error( "[migrate_pipeline_parent_data]_candidate_backend is None, " "please set env variable(BKAPP_PIPELINE_DATA_CANDIDATE_BACKEND) first" ) return r = settings.redis_inst pipeline_data_keys = list(r.scan_iter("*_schedule_parent_data")) keys_len = len(pipeline_data_keys) loggger.info("[migrate_pipeline_parent_data] start to migrate {} keys.".format(keys_len)) for i, key in enumerate(pipeline_data_keys, 1): try: loggger.info("[migrate_pipeline_parent_data] process[{}/{}]".format(i, keys_len)) value = _backend.get_object(key) _candidate_backend.set_object(key, value) r.expire(key, 60 * 60 * 24) # expire in 1 day except Exception: loggger.exception("[migrate_pipeline_parent_data] {} key migrate err.".format(i)) loggger.info("[migrate_pipeline_parent_data] migrate done!")
MaximilianWenzel/DeductiveClosureComputation
dcc-lib/src/main/java/util/serialization/Serializer.java
package util.serialization; import java.io.IOException; import java.io.Serializable; import java.nio.ByteBuffer; public interface Serializer { byte[] serialize(Serializable obj) throws IOException; void serializeToByteBuffer(Serializable obj, ByteBuffer buffer) throws IOException; Object deserializeFromByteBuffer(ByteBuffer buffer) throws IOException, ClassNotFoundException; Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException; }
KMCzajkowski/pyscf
examples/mcscf/43-dmet_cas.py
#!/usr/bin/env python from functools import reduce import numpy import scipy.linalg from pyscf import scf from pyscf import gto from pyscf import mcscf, fci ''' Triplet and quintet energy gap of Iron-Porphyrin molecule In this example, we use density matrix embedding theory (ref. Q Sun, JCTC, 10(2014), 3784) to generate initial guess. ''' # # For 3d transition metal, people usually consider the so-called double # d-shell effects for CASSCF calculation. Double d-shell here refers to 3d # and 4d atomic orbitals. Density matrix embedding theory (DMET) provides a # method to generate CASSCF initial guess in terms of localized orbitals. # Given DMET impurity and truncated bath, we can select Fe 3d and 4d orbitals # and a few entangled bath as the active space. # ################################################## # # Quintet # ################################################## mol = gto.Mole() mol.atom = [ ['Fe', (0. , 0.0000 , 0.0000)], ['N' , (1.9764 , 0.0000 , 0.0000)], ['N' , (0.0000 , 1.9884 , 0.0000)], ['N' , (-1.9764 , 0.0000 , 0.0000)], ['N' , (0.0000 , -1.9884 , 0.0000)], ['C' , (2.8182 , -1.0903 , 0.0000)], ['C' , (2.8182 , 1.0903 , 0.0000)], ['C' , (1.0918 , 2.8249 , 0.0000)], ['C' , (-1.0918 , 2.8249 , 0.0000)], ['C' , (-2.8182 , 1.0903 , 0.0000)], ['C' , (-2.8182 , -1.0903 , 0.0000)], ['C' , (-1.0918 , -2.8249 , 0.0000)], ['C' , (1.0918 , -2.8249 , 0.0000)], ['C' , (4.1961 , -0.6773 , 0.0000)], ['C' , (4.1961 , 0.6773 , 0.0000)], ['C' , (0.6825 , 4.1912 , 0.0000)], ['C' , (-0.6825 , 4.1912 , 0.0000)], ['C' , (-4.1961 , 0.6773 , 0.0000)], ['C' , (-4.1961 , -0.6773 , 0.0000)], ['C' , (-0.6825 , -4.1912 , 0.0000)], ['C' , (0.6825 , -4.1912 , 0.0000)], ['H' , (5.0441 , -1.3538 , 0.0000)], ['H' , (5.0441 , 1.3538 , 0.0000)], ['H' , (1.3558 , 5.0416 , 0.0000)], ['H' , (-1.3558 , 5.0416 , 0.0000)], ['H' , (-5.0441 , 1.3538 , 0.0000)], ['H' , (-5.0441 , -1.3538 , 0.0000)], ['H' , (-1.3558 , -5.0416 , 0.0000)], ['H' , (1.3558 , -5.0416 , 0.0000)], ['C' , (2.4150 , 2.4083 , 0.0000)], ['C' , (-2.4150 , 2.4083 , 0.0000)], ['C' , (-2.4150 , -2.4083 , 0.0000)], ['C' , (2.4150 , -2.4083 , 0.0000)], ['H' , (3.1855 , 3.1752 , 0.0000)], ['H' , (-3.1855 , 3.1752 , 0.0000)], ['H' , (-3.1855 , -3.1752 , 0.0000)], ['H' , (3.1855 , -3.1752 , 0.0000)], ] mol.basis = 'ccpvdz' mol.verbose = 4 mol.output = 'fepor.out' mol.spin = 4 mol.symmetry = True mol.build() mf = scf.ROHF(mol) mf = scf.fast_newton(mf) idx3d4d = [i for i,s in enumerate(mol.spheric_labels(1)) if 'Fe 3d' in s or 'Fe 4d' in s] ncas, nelecas, mo = dmet_cas.guess_cas(mf, mf.make_rdm1(), idx3d) mc = mcscf.approx_hessian(mcscf.CASSCF(mf, ncas, nelecas) mc.kernel(mo) e_q = mc.e_tot # -2244.82910509839 ################################################## # # Triplet # ################################################## mol.spin = 2 mol.build(0, 0) # (0, 0) to avoid dumping input file again mf = scf.ROHF(mol) mf = scf.fast_newton(mf) # # CAS(8e, 11o) # mf = scf.ROHF(mol) mf = scf.fast_newton(mf) idx3d4d = [i for i,s in enumerate(mol.spheric_labels(1)) if 'Fe 3d' in s or 'Fe 4d' in s] ncas, nelecas, mo = dmet_cas.guess_cas(mf, mf.make_rdm1(), idx3d) mc = mcscf.approx_hessian(mcscf.CASSCF(mf, ncas, nelecas) mc.kernel(mo) e_t = mc.e_tot # -2244.81493852189 print('E(T) = %.15g E(Q) = %.15g gap = %.15g' % (e_t, e_q, e_t-e_q))