repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
xpp011/tea-java
src/test/java/com/aliyun/tea/utils/IOUtilsTest.java
package com.aliyun.tea.utils; import org.junit.Assert; import org.junit.Test; import java.io.*; public class IOUtilsTest { @Test public void closeQuietlyTest() { byte[] source = {66, 99}; InputStream inputStream = new ByteArrayInputStream(source); try { IOUtils.closeQuietly(inputStream); } catch (Exception e) { Assert.fail(); } } @Test public void closeIfCloseableTest() { try { IOUtils.closeIfCloseable("test"); } catch (Exception e) { Assert.fail(); } } }
eventide-project/consumer
lib/consumer/controls/consumer/error_handler.rb
<gh_stars>0 module Consumer module Controls module Consumer module ErrorHandler def self.example(category=nil) category ||= Category.example Example.new(category) end class Example include ::Consumer attr_accessor :handled_error attr_accessor :failed_message handler Handle::Example handler Handle::RaiseError::Example def error_raised(error, message) self.handled_error = error self.failed_message = message end def handled_error?(error=nil) if error.nil? !handled_error.nil? else handled_error == error end end def failed_message?(message) failed_message == message end end end end end end
lmeysel/fa-compatible-icons
ion/trendingDownOutline.js
<filename>ion/trendingDownOutline.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'ion'; var iconName = 'trending-down-outline'; var width = 512; var height = 512; var ligatures = []; var unicode = null; var svgPathData = 'M 47.785156 128 A 16 16 0 0 0 36.685547 132.68555 A 16 16 0 0 0 36.685547 155.31445 L 158.05664 276.68359 C 176.6688 295.29784 207.334 295.2972 225.94531 276.68164 L 276.68359 225.94336 A 16.0016 16.0016 0 0 0 276.68555 225.94336 C 283.06832 219.55913 292.93168 219.55913 299.31445 225.94336 A 16.0016 16.0016 0 0 0 299.31641 225.94336 L 425.37109 352 L 352 352 A 16 16 0 0 0 336 368 A 16 16 0 0 0 352 384 L 464 384 A 16.0016 16.0016 0 0 0 480 368 L 480 256 A 16 16 0 0 0 464 240 A 16 16 0 0 0 448 256 L 448 329.37109 L 321.94531 203.31836 C 303.33335 184.70214 272.66665 184.70214 254.05469 203.31836 L 203.31641 254.05664 A 16.0016 16.0016 0 0 0 203.31445 254.05664 C 196.93168 260.44087 187.06832 260.44087 180.68555 254.05664 A 16.0016 16.0016 0 0 0 180.68359 254.05664 L 59.314453 132.68555 A 16 16 0 0 0 48.121094 128 A 16 16 0 0 0 47.785156 128 z '; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.ionTrendingDownOutline = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
jdmclark/gorc
src/game/world/events/landed.hpp
#pragma once #include "content/id.hpp" namespace gorc { namespace game { namespace world { namespace events { class landed { public: #include "landed.uid" thing_id thing; landed(thing_id thing); }; } } } }
ciena-frost/ember-frost-list
tests/integration/components/frost-list-item-content-test.js
/** * Integration test for the frost-list-item-content component */ import {expect} from 'chai' import Ember from 'ember' import {$hook, initialize as initializeHook} from 'ember-hook' import wait from 'ember-test-helpers/wait' import {registerMockComponent, unregisterMockComponent} from 'ember-test-utils/test-support/mock-component' import {integration} from 'ember-test-utils/test-support/setup-component-test' import hbs from 'htmlbars-inline-precompile' import {afterEach, beforeEach, describe, it} from 'mocha' const test = integration('frost-list-item-content') describe(test.label, function () { test.setup() beforeEach(function () { initializeHook() }) describe('renders frost-list-item-content', function () { beforeEach(function () { registerMockComponent(this, 'mock-list-item') registerMockComponent(this, 'mock-list-item-expansion') this.setProperties({ model: Ember.Object.create({id: '0'}), index: 0, onExpand: function () {}, onSelect: function () {} }) this.render(hbs` {{frost-list-item-content hook='myListItemContent' hookQualifiers=(hash index=index) model=model index=index onExpand=onExpand onSelect=onSelect item=(component 'mock-list-item') itemExpansion=(component 'mock-list-item-expansion') }} `) return wait() }) afterEach(function () { unregisterMockComponent(this, 'mock-list-item') unregisterMockComponent(this, 'mock-list-item-expansion') }) it('should set "frost-list-item-content" class', function () { expect(this.$('.frost-list-item-content')).to.have.length(1) }) it('should create one list item content', function () { expect($hook('myListItemContent', {index: 0})).to.have.length(1) }) it('should concatenate the -item-container hook property', function () { expect($hook('myListItemContent-item-container', {index: 0})).to.have.length(1) }) it('should concatenate the -item hook property', function () { expect($hook('myListItemContent-item', {index: 0})).to.have.length(1) }) it('should concatenate the -expnansion hook property', function () { expect($hook('myListItemContent-expansion', {index: 0})).to.have.length(1) }) }) })
06keito/study-atcoder
src/abc215_c.py
<reponame>06keito/study-atcoder import itertools def main(): S,K = input().split() tmp = list(set(itertools.permutations(list(S),len(S)))) array = [list(i) for i in tmp] array.sort() print("".join(array[int(K)-1])) if __name__ == '__main__': main()
sgholamian/log-aware-clone-detection
NLPCCd/Hive/1785_2.java
//,temp,sample_3421.java,2,17,temp,sample_1984.java,2,17 //,3 public class xxx { public void dummy_method(){ key.set(pos); pos++; Map<String, Object> record = iterator.next(); if ((record != null) && (!record.isEmpty())) { for (Entry<String, Object> entry : record.entrySet()) { value.put(new Text(entry.getKey()), entry.getValue() == null ? NullWritable.get() : new ObjectWritable(entry.getValue())); } return true; } else { log.info("jdbcrecordreader got null record"); } } };
sgammon/modeldemo
pipeline/src/main/java/io/momentum/demo/models/logic/service/transformers/RefSerializer.java
<gh_stars>0 package io.momentum.demo.models.logic.service.transformers; import com.google.api.server.spi.config.Transformer; import com.googlecode.objectify.Key; import com.googlecode.objectify.Ref; /** * Created by sam on 1/12/16. */ public final class RefSerializer implements Transformer<Ref, String> { @Override public String transformTo(Ref ref) { return ref != null ? ref.key().toWebSafeString() : null; } @Override public Ref transformFrom(String encoded) { try { Key target = Key.create(encoded); return Ref.create(target); } catch (RuntimeException e) { return null; } } }
swedenconnect/eidas-eu-mock
EIDAS-Sources-2.3.1-MDSL/EIDAS-Commons/src/main/java/eu/eidas/auth/commons/attribute/MemoryAttributeDefinitionDao.java
/* # Copyright (c) 2017 European Commission # Licensed under the EUPL, Version 1.2 or – as soon they will be # approved by the European Commission - subsequent versions of the # EUPL (the "Licence"); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: # * https://joinup.ec.europa.eu/page/eupl-text-11-12 # * # Unless required by applicable law or agreed to in writing, software # distributed under the Licence is distributed on an "AS IS" basis, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Licence for the specific language governing permissions and limitations under the Licence. */ package eu.eidas.auth.commons.attribute; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import eu.eidas.auth.commons.io.SingletonAccessor; import eu.eidas.util.Preconditions; /** * MemoryAttributeDefinitionDao * * @since 1.1 */ final class MemoryAttributeDefinitionDao implements AttributeDefinitionDao { private static final class AtomicState implements SingletonAccessor<ImmutableSortedSet<AttributeDefinition<?>>> { @Nonnull private final AtomicReference<ImmutableSortedSet<AttributeDefinition<?>>> reference; private AtomicState(@Nonnull ImmutableSortedSet<AttributeDefinition<?>> definitions) { Preconditions.checkNotNull(definitions, "definitions"); reference = new AtomicReference<>(definitions); } @Nullable @Override public ImmutableSortedSet<AttributeDefinition<?>> get() { return reference.get(); } @Override public void set(@Nonnull ImmutableSortedSet<AttributeDefinition<?>> newValue) { Preconditions.checkNotNull(newValue, "newValue"); reference.set(newValue); } } static final MemoryAttributeDefinitionDao EMPTY = new MemoryAttributeDefinitionDao( ImmutableList.of(new SingletonAccessor<ImmutableSortedSet<AttributeDefinition<?>>>() { @Nullable @Override public ImmutableSortedSet<AttributeDefinition<?>> get() throws IOException { return ImmutableSortedSet.of(); } @Override public void set(@Nonnull ImmutableSortedSet<AttributeDefinition<?>> newValue) throws IOException { throw new UnsupportedOperationException(); } })); static MemoryAttributeDefinitionDao copyOf(@Nonnull Iterable<AttributeDefinition<?>> definitions) { Preconditions.checkNotNull(definitions, "definitions"); ImmutableSortedSet<AttributeDefinition<?>> copyOf = ImmutableSortedSet.copyOf(definitions); if (copyOf.isEmpty()) { return EMPTY; } return new MemoryAttributeDefinitionDao(copyOf); } static MemoryAttributeDefinitionDao copyOf(@Nonnull AttributeDefinition<?>... definitions) { Preconditions.checkNotNull(definitions, "definitions"); ImmutableSortedSet<AttributeDefinition<?>> copyOf = ImmutableSortedSet.copyOf(definitions); if (copyOf.isEmpty()) { return EMPTY; } return new MemoryAttributeDefinitionDao(copyOf); } private final ImmutableList<? extends SingletonAccessor<ImmutableSortedSet<AttributeDefinition<?>>>> accessors; private MemoryAttributeDefinitionDao(@Nonnull final ImmutableSortedSet<AttributeDefinition<?>> definitions) { this(ImmutableList.of(new AtomicState(definitions))); } private MemoryAttributeDefinitionDao( @Nonnull ImmutableList<? extends SingletonAccessor<ImmutableSortedSet<AttributeDefinition<?>>>> accessors) { this.accessors = accessors; } @Nonnull @Override public ImmutableList<? extends SingletonAccessor<ImmutableSortedSet<AttributeDefinition<?>>>> getAttributeDefinitionAccessors() { return accessors; } }
lifeibiren/Nut
syscall/sys_ioctl.c
<reponame>lifeibiren/Nut<gh_stars>1-10 #include <syscall.h> int sys_ioctl(int fd, int request) { fs_context_t *fs_context = get_fd_ptr(fd); if (fs_context == NULL) return -1; return fs_ioctl(fs_context, request); }
yacchin1205/RDM-modular-file-renderer
mfr/core/metrics.py
<reponame>yacchin1205/RDM-modular-file-renderer import copy def _merge_dicts(a, b, path=None): """"merges b into a Taken from: http://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): _merge_dicts(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass # same leaf value else: raise Exception('Conflict at %s' % '.'.join(path + [str(key)])) else: a[key] = b[key] return a class MetricsBase(): """Lightweight wrapper around a dict to make keeping track of metrics a little easier. Current functionality is limited, but may be extended later. To do: * update/override method to indicate expectations of existing key self.metrics.add_default('some.flag', True) <later> self.metrics.override('some.flag', False) # dies if 'some.flag' doesn't already exist * optional type validation? self.metrics.add('some.flag', True, bool()) -or- self.metrics.define('some.flag', bool()) <later> self.metrics.add('some.flag', 'foobar') # dies, 'foobar' isn't a bool """ def __init__(self): self._metrics = {} def key(self): """ID string for this object""" raise NotImplementedError def add(self, key, value): """add() stores the given value under the given key. Subkeys can be specified by placing a dot between the parent and child keys. e.g. 'foo.bar' will be interpreted as ``self._metrics['foo']['bar']`` :param str key: the key to store ``value`` under :param value: the value to store, type unrestricted """ self._set_dotted_key(self._metrics, key, value) def merge(self, record): """Merges a dict into the current metrics. :param dict record: a dict to merge with the current metrics """ _merge_dicts(self._metrics, record) def serialize(self): """Return a copy of the metrics""" return copy.deepcopy(self._metrics) def manifesto(self): """'This is who I am and this is what I stand for!' Returns a dict with one entry: our key pointing to our metrics """ return {self.key: self.serialize()} def _set_dotted_key(self, store, key, value): """Naive method to set nested dict values via dot-separated keys. e.g ``_set_dotted_keys(self._metrics, 'foo.bar', 'moo')`` is equivalent to ``self._metrics['foo']['bar'] = 'moo'``. This method is neither resilient nor intelligent and will react with bad grace if one of the keys already exists and is not a dict key. """ parts = key.split('.') current = store for part in parts[:-1]: if part not in current: current[part] = {} current = current[part] current[parts[-1]] = value class MetricsRecord(MetricsBase): """An extension to MetricsBase that carries a category and list of submetrics. When serialized, will include the serialized child metrics """ def __init__(self, category): super().__init__() self.category = category self.subrecords = [] @property def key(self): """ID string for this record: '{category}'""" return self.category def serialize(self): """Returns its metrics with the metrics for each of the subrecords included under their key. """ metrics = super().serialize() for subrecord in self.subrecords: metrics[subrecord.key] = subrecord.serialize() return metrics def new_subrecord(self, name): """Create a new MetricsSubRecord object with our category and save it to the subrecords list.""" subrecord = MetricsSubRecord(self.category, name) self.subrecords.append(subrecord) return subrecord class MetricsSubRecord(MetricsRecord): """An extension to MetricsRecord that carries a name in addition to a category. Will identify itself as {category}_{name}. Can create its own subrecord whose category will be this subrecord's ``name``. """ def __init__(self, category, name): super().__init__(category) self.name = name @property def key(self): """ID string for this subrecord: '{category}_{name}'""" return '{}_{}'.format(self.category, self.name) def new_subrecord(self, name): """Creates and saves a new subrecord. The new subrecord will have its category set to the parent subrecord's ``name``. ex:: parent = MetricsRecord('foo') child = parent.new_subrecord('bar') grandchild = child.new_subrecord('baz') print(parent.key) # foo print(child.key) # foo_bar print(grandchild.key) # bar_baz """ subrecord = MetricsSubRecord(self.name, name) self.subrecords.append(subrecord) return subrecord
niryarden/euler_project_solutions
solutions/euler5.py
# answer: 232792560 status = True num = 2520 answer = 0 while status: num = num + 20 # make a list of all the remainders of the deviding by 1 to 20 remainders = [] for i in range(1, 21, 1): remainders.append(num % i) # check if the sum of the remainders is 0 (which means the number fits) if sum(remainders) == 0: answer = num status = False print(f"answer: {answer}")
Sod-Momas/momas-project
momas-wesay/momas-wesay-java-client/src/main/java/cc/momas/wesay/netty/java/WeSayEnvironment.java
<gh_stars>0 package cc.momas.wesay.netty.java; import org.apache.commons.cli.*; import java.util.Arrays; /** * 环境变量 * * @author Sod-Momas * @since 2021-02-24 */ public class WeSayEnvironment { private final CommandLine cmd; public WeSayEnvironment(String[] args) { // log.debug("args=" + Arrays.toString(args)); System.out.println("args=" + Arrays.toString(args)); // create Options object final Options options = new Options(); // add t option options.addOption("p", "port", true, "The port of server bind."); options.addOption("h", "host", true, "The host of server bind."); final CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException e) { commandLine = null; e.printStackTrace(); } cmd = commandLine; } /** * 获取服务器启动的端口,默认为9000 * * @return 服务器启动的端口 */ public int getPort() { // get value from cmd final String port = cmd.getOptionValue('p', "9000"); return Integer.parseInt(port); } /** * 获取服务器地址 * * @return 服务器地址,默认为localhost */ public String getHost() { return cmd.getOptionValue('h', "localhost"); } }
AbdulMoeedSaleem/boiler-plate
templates/typescript/server/middlewares/response.js
<reponame>AbdulMoeedSaleem/boiler-plate const logCat = require("../../library/logger")("app"); const config = require('../../config/app'); module.exports = function (req, res, next) { req.offset = req.query.offset ? req.query.offset : 0; const lang = (req.get('mbq_lang') || req.headers['mbq_lang'] || 'en').toString(); res.sendJSON = (data, msg = null, status = 200) => { let resObj = { status: true, message: msg ? msg : "", error: null }; if (typeof data == "object") { resObj.data = data; } else { resObj.data = { app_code: data }; } res.status(status).json(resObj); } res.sendError = (error_obj, msg = null, status = 200) => { logCat(error_obj) // Handle the error message of knex.js ORM for production only. // Prevent to expose stack-trace of database entity breaking const isProdEnv = config.ENVIRONMENT === "production"; const isKnexError = error_obj && error_obj.routine && error_obj.detail; const errorMessage = msg ? msg : "" if (isProdEnv) { console.error(error_obj); } if (isProdEnv && isKnexError) { res.status(status).json({ status: false, message: errorMessage, data: null, error: { message: errorMessage } }); } else res.status(status).json({ status: false, message: errorMessage, data: null, error: error_obj }); } next(); }
benety/mongo
src/mongo/db/repl/tenant_migration_shared_data.h
<reponame>benety/mongo /** * Copyright (C) 2020-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include "mongo/db/repl/optime.h" #include "mongo/db/repl/repl_sync_shared_data.h" namespace mongo { namespace repl { enum class ResumePhase { kNone, kDataSync, kOplogCatchup }; class TenantMigrationSharedData final : public ReplSyncSharedData { public: TenantMigrationSharedData(ClockSource* clock, const UUID& migrationId) : ReplSyncSharedData(clock), _migrationId(migrationId), _resumePhase(ResumePhase::kNone) {} TenantMigrationSharedData(ClockSource* clock, const UUID& migrationId, ResumePhase resumePhase) : ReplSyncSharedData(clock), _migrationId(migrationId), _resumePhase(resumePhase) {} void setLastVisibleOpTime(WithLock, OpTime opTime); OpTime getLastVisibleOpTime(WithLock); const mongo::UUID& getMigrationId() const { return _migrationId; } ResumePhase getResumePhase() const { return _resumePhase; } private: // Must hold mutex (in base class) to access this. // Represents last visible majority committed donor opTime. OpTime _lastVisibleOpTime; // Id of the current tenant migration. const UUID _migrationId; // Indicate the phase from which the tenant migration is resuming due to recipient/donor // failovers. const ResumePhase _resumePhase; }; } // namespace repl } // namespace mongo
paullewallencom/java-978-1-7898-0977-0
_src/Chapter04/CH4Prototype/Dungeon.java
package CH4Prototype; public class Dungeon extends BaseLevel { public Dungeon(String name) { levelName = name; } @Override public BaseLevel clone() throws CloneNotSupportedException { return (Dungeon)super.clone(); } }
SerBuitrago/PastLey
src/com/pastley/models/component/ItemComponent.java
package com.pastley.models.component; public class ItemComponent<A> extends Component{ private static final long serialVersionUID = 1L; private A entity; private String path; public ItemComponent(A entity) { this(null, null, null, entity, null, null); } public ItemComponent(A entity, String path, String icon) { this(null, null, null, entity, path, icon); } public ItemComponent(A entity, String path, String title, String icon) { this(null, null, title, entity, path, icon); } public ItemComponent(String id, String icon, boolean isClass) { this(id, (isClass ? id : null), null, null, null, icon); } public ItemComponent(String id, String styleClass, String title, A entity, String path, String icon) { super(id, styleClass, title, null, icon); this.entity = entity; this.path = path; } public A getEntity() { return entity; } public void setEntity(A entity) { this.entity = entity; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public static long getSerialversionuid() { return serialVersionUID; } }
Squantor/libMcuLL
inc/nxp/LPC8XX/LPC84X_dma.h
<reponame>Squantor/libMcuLL<filename>inc/nxp/LPC8XX/LPC84X_dma.h /* * SPDX-License-Identifier: Unlicense * * Copyright (c) 2021 <NAME> * For conditions of distribution and use, see LICENSE file */ /* * LPC840 series DMA registers, defines and functions. */ #ifndef LPC84X_DMA_H #define LPC84X_DMA_H /** DMA - Register Layout Typedef */ typedef volatile struct DMA_Struct { uint32_t CTRL; /**< DMA control., offset: 0x0 */ const uint32_t INTSTAT; /**< Interrupt status., offset: 0x4 */ uint32_t SRAMBASE; /**< SRAM address of the channel configuration table., offset: 0x8 */ uint8_t RESERVED_0[20]; struct { /* offset: 0x20, array step: 0x5C */ uint32_t ENABLESET; /**< Channel Enable read and Set for all DMA channels., array offset: 0x20, array step: 0x5C */ uint8_t RESERVED_0[4]; uint32_t ENABLECLR; /**< Channel Enable Clear for all DMA channels., array offset: 0x28, array step: 0x5C */ uint8_t RESERVED_1[4]; const uint32_t ACTIVE; /**< Channel Active status for all DMA channels., array offset: 0x30, array step: 0x5C */ uint8_t RESERVED_2[4]; const uint32_t BUSY; /**< Channel Busy status for all DMA channels., array offset: 0x38, array step: 0x5C */ uint8_t RESERVED_3[4]; uint32_t ERRINT; /**< Error Interrupt status for all DMA channels., array offset: 0x40, array step: 0x5C */ uint8_t RESERVED_4[4]; uint32_t INTENSET; /**< Interrupt Enable read and Set for all DMA channels., array offset: 0x48, array step: 0x5C */ uint8_t RESERVED_5[4]; uint32_t INTENCLR; /**< Interrupt Enable Clear for all DMA channels., array offset: 0x50, array step: 0x5C */ uint8_t RESERVED_6[4]; uint32_t INTA; /**< Interrupt A status for all DMA channels., array offset: 0x58, array step: 0x5C */ uint8_t RESERVED_7[4]; uint32_t INTB; /**< Interrupt B status for all DMA channels., array offset: 0x60, array step: 0x5C */ uint8_t RESERVED_8[4]; uint32_t SETVALID; /**< Set ValidPending control bits for all DMA channels., array offset: 0x68, array step: 0x5C */ uint8_t RESERVED_9[4]; uint32_t SETTRIG; /**< Set Trigger control bits for all DMA channels., array offset: 0x70, array step: 0x5C */ uint8_t RESERVED_10[4]; uint32_t ABORT; /**< Channel Abort control for all DMA channels., array offset: 0x78, array step: 0x5C */ } COMMON[1]; uint8_t RESERVED_1[900]; struct { /* offset: 0x400, array step: 0x10 */ uint32_t CFG; /**< Configuration register for DMA channel ., array offset: 0x400, array step: 0x10 */ const uint32_t CTLSTAT; /**< Control and status register for DMA channel ., array offset: 0x404, array step: 0x10 */ uint32_t XFERCFG; /**< Transfer configuration register for DMA channel ., array offset: 0x408, array step: 0x10 */ uint8_t RESERVED_0[4]; } CHANNEL[25]; } DMA_Type; #endif
PrincetonUniversity/ASPIRE-Python
src/aspire/classification/legacy_implementations.py
import logging import numpy as np import scipy.sparse as sps from scipy.linalg import qr logger = logging.getLogger(__name__) def pca_y(x, k, num_iters=2): """ PCA using QR factorization. See: An algorithm for the principal component analysis of large data sets. Halko, Martinsson, Shkolnisky, Tygert , SIAM 2011. :param x: Data matrix :param k: Number of estimated Principal Components. :param num_iters: Number of dot product applications. :return: (left Singular Vectors, Singular Values, right Singular Vectors) """ m, n = x.shape def operator(mat): return x.dot(mat) def operator_transpose(mat): return np.conj(x.T).dot(mat) flag = False if m < n: flag = True operator_transpose, operator = operator, operator_transpose m, n = n, m ones = np.ones((n, k + 2)) if x.dtype == np.dtype("complex"): h = operator( (2 * np.random.random((k + 2, n)).T - ones) + 1j * (2 * np.random.random((k + 2, n)).T - ones) ) else: h = operator(2 * np.random.random((k + 2, n)).T - ones) f = [h] for _ in range(num_iters): h = operator_transpose(h) h = operator(h) f.append(h) f = np.concatenate(f, axis=1) # f has e-16 error, q has e-13 q, _, _ = qr(f, mode="economic", pivoting=True) b = np.conj(operator_transpose(q)).T u, s, v = np.linalg.svd(b, full_matrices=False) # not sure how to fix the signs but it seems like I dont need to # TODO use fix_svd, here and matlab # u, v = fix_svd(u, v) v = v.conj() u = np.dot(q, u) u = u[:, :k] v = v[:k] s = s[:k] if flag: u, v = v.T, u.T return u, s, v def bispec_operator_1(freqs): max_freq = np.max(freqs) count = 0 for i in range(2, max_freq): for j in range(1, min(i, max_freq - i + 1)): k = i + j id1 = np.where(freqs == i)[0] id2 = np.where(freqs == j)[0] id3 = np.where(freqs == k)[0] nd1 = len(id1) nd2 = len(id2) nd3 = len(id3) count += nd1 * nd2 * nd3 full_list = np.zeros((count, 3), dtype="int") count = 0 for i in range(2, max_freq): for j in range(1, min(i, max_freq - i + 1)): k = i + j id1 = np.where(freqs == i)[0] id2 = np.where(freqs == j)[0] id3 = np.where(freqs == k)[0] nd1 = len(id1) nd2 = len(id2) nd3 = len(id3) nd = nd1 * nd2 * nd3 if nd != 0: tmp1 = np.tile(id1, nd2) tmp2 = np.repeat(id2, nd1) tmp = np.stack((tmp1, tmp2), axis=1) tmp1 = np.tile(tmp, (nd3, 1)) tmp2 = np.repeat(id3, nd1 * nd2) full_list[count : count + nd, :2] = tmp1 full_list[count : count + nd, 2] = tmp2 count += nd val = np.ones(full_list.shape) val[:, 2] = -1 # conjugation n_col = count full_list = full_list.flatten("F") val = val.flatten("F") col = np.tile(np.arange(n_col), 3) o1 = sps.csr_matrix( (np.ones(len(full_list)), (col, full_list)), shape=(n_col, len(freqs)) ) o2 = sps.csr_matrix((val, (col, full_list)), shape=(n_col, len(freqs))) return o1, o2 def bispec_2drot_large(coeff, freqs, eigval, alpha, sample_n): """ alpha 1/3 sample_n 4000 """ freqs_not_zero = freqs != 0 coeff_norm = np.log(np.power(np.absolute(coeff[freqs_not_zero]), alpha)) if np.any(coeff_norm == float("-inf")): raise ValueError("coeff_norm should not be -inf") phase = coeff[freqs_not_zero] / np.absolute(coeff[freqs_not_zero]) phase = np.arctan2(np.imag(phase), np.real(phase)) eigval = eigval[freqs_not_zero] o1, o2 = bispec_operator_1(freqs[freqs_not_zero]) # GBW, naively handle vanishing eigvals. # This became a problem with very noisy images... p = np.power(eigval, alpha) mask = np.where(p, p, -1) # taking the log in the next step will yield a 0 m = np.exp(o1 * np.log(p, where=(mask > 0))) p_m = m / m.sum() x = np.random.rand(len(m)) m_id = np.where(x < sample_n * p_m)[0] o1 = o1[m_id] o2 = o2[m_id] m = np.exp(o1 * coeff_norm + 1j * o2 * phase) # svd of the reduced bispectrum u, s, v = pca_y(m, 300) coeff_b = np.einsum("i, ij -> ij", s, np.conjugate(v)) coeff_b_r = np.conjugate(u.T).dot(np.conjugate(m)) coeff_b = coeff_b / np.linalg.norm(coeff_b, axis=0) coeff_b_r = coeff_b_r / np.linalg.norm(coeff_b_r, axis=0) return coeff_b, coeff_b_r
Team-4361/RobotCode2021
src/main/java/frc/team4361/season2021/surrogate/ShooterSurrogate.java
<reponame>Team-4361/RobotCode2021<filename>src/main/java/frc/team4361/season2021/surrogate/ShooterSurrogate.java<gh_stars>0 package frc.team4361.season2021.surrogate; import org.roxbotix.elibs2.robot.components.Encoder; import org.roxbotix.elibs2.robot.components.TlMotor; import frc.team4361.season2021.legacy.CoreShooter; public class ShooterSurrogate { private final TlMotor flywheel; private final TlMotor actuator; private final Encoder flywheelEncoder; private final Encoder actuatorEncoder; private final double flywheelTpr; private final double actuatorTpr; private final double flywheelDiameter; private final CoreShooter coreShooter; public ShooterSurrogate(TlMotor flywheel, TlMotor actuator, Encoder flywheelEncoder, Encoder actuatorEncoder, double flywheelTpr, double actuatorTpr, double flywheelDiameter) { this.flywheel = flywheel; this.actuator = actuator; this.flywheelEncoder = flywheelEncoder; this.actuatorEncoder = actuatorEncoder; this.flywheelTpr = flywheelTpr; this.actuatorTpr = actuatorTpr; this.flywheelDiameter = flywheelDiameter; coreShooter = new CoreShooter( flywheel.getTalon(), actuator.getTalon(), flywheelEncoder.getEncoder(), actuatorEncoder.getEncoder(), flywheelTpr, actuatorTpr, flywheelDiameter ); } public TlMotor getFlywheel() { return flywheel; } public TlMotor getActuator() { return actuator; } public Encoder getFlywheelEncoder() { return flywheelEncoder; } public Encoder getActuatorEncoder() { return actuatorEncoder; } public double getFlywheelTpr() { return flywheelTpr; } public double getActuatorTpr() { return actuatorTpr; } public double getFlywheelDiameter() { return flywheelDiameter; } public CoreShooter getCoreShooter() { return coreShooter; } }
sofimrtn/Gestion_Hospital_IPS
IPS-GestionHospital/src/business/dto/PacienteDto.java
package business.dto; public class PacienteDto { public int id; public String dni; public String nombre; public String contacto; public String estado; @Override public String toString() { return nombre + " DNI paciente: " + dni + "."; } }
xmaruto/mcord
xos/tosca/resources/port.py
<gh_stars>0 import os import pdb import sys import tempfile sys.path.append("/opt/tosca") from translator.toscalib.tosca_template import ToscaTemplate from core.models import Instance,User,Network,NetworkTemplate,Port from xosresource import XOSResource class XOSPort(XOSResource): provides = ["tosca.nodes.network.Port"] xos_model = Port def get_existing_objs(self): # Port objects have no name, their unique key is (instance, network) args = self.get_xos_args(throw_exception=False) instance = args.get('instance',None) network = args.get('network',None) if (not instance) or (not network): return [] return self.xos_model.objects.filter(**{'instance': instance, 'network': network}) def get_xos_args(self, throw_exception=True): args = {} instance_name = self.get_requirement("tosca.relationships.network.BindsTo") if instance_name: args["instance"] = self.get_xos_object(Instance, throw_exception, name=instance_name) net_name = self.get_requirement("tosca.relationships.network.LinksTo") if net_name: args["network"] = self.get_xos_object(Network, throw_exception, name=net_name) return args def postprocess(self, obj): pass def create(self): xos_args = self.get_xos_args() if not xos_args.get("instance", None): raise Exception("Must specify slver when creating port") if not xos_args.get("network", None): raise Exception("Must specify network when creating port") port = Port(**xos_args) port.caller = self.user port.save() self.postprocess(port) self.info("Created Port '%s' connect instance '%s' to network %s" % (str(port), str(port.instance), str(port.network))) def delete(self, obj): super(XOSPort, self).delete(obj)
Chainsawkitten/Deathcap
src/Editor/main.cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <Engine/MainWindow.hpp> #include "Editor.hpp" #include "Util/EditorSettings.hpp" #include <Engine/Util/Input.hpp> #include <Engine/Util/FileSystem.hpp> #include <Utility/Log.hpp> #include <Engine/Input/Input.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ScriptManager.hpp> #include <Engine/Manager/ProfilingManager.hpp> #include <Engine/Manager/ParticleManager.hpp> #include <Engine/Manager/DebugDrawingManager.hpp> #include <Engine/Manager/RenderManager.hpp> #include <Engine/Manager/VRManager.hpp> #include <Engine/Util/Profiling.hpp> #include <Engine/Util/GPUProfiling.hpp> #include <Engine/Hymn.hpp> #include <thread> #include "ImGui/OpenGLImplementation.hpp" #include <imgui.h> #include "GUI/ProfilingWindow.hpp" #include <iostream> #ifdef USINGMEMTRACK #include <MemTrackInclude.hpp> #endif int main() { Log().SetupStreams(&std::cout, &std::cout, &std::cout, &std::cerr); // Enable logging if requested. if (EditorSettings::GetInstance().GetBool("Logging")){ FILE* file = freopen(FileSystem::DataPath("Deathcap Engine", "log.txt").c_str(), "a", stderr); if (file == nullptr) Log() << "Could not open logging file!\n"; } Log() << "Editor started - " << time(nullptr) << "\n"; if (!glfwInit()) return 1; MainWindow* window = new MainWindow(EditorSettings::GetInstance().GetLong("Width"), EditorSettings::GetInstance().GetLong("Height"), false, false, "Deathcap Engine", EditorSettings::GetInstance().GetBool("Debug Context")); glewInit(); window->Init(false); Input::GetInstance().SetWindow(window->GetGLFWWindow()); Managers().StartUp(); Editor* editor = new Editor(); // Setup imgui implementation. ImGuiImplementation::Init(window->GetGLFWWindow()); bool profiling = false; GUI::ProfilingWindow profilingWindow; // Main loop. double targetFPS = 60.0; double lastTime = glfwGetTime(); double lastTimeRender = glfwGetTime(); while (!window->ShouldClose() || !editor->ReadyToClose()) { float deltaTime = static_cast<float>(glfwGetTime() - lastTime); lastTime = glfwGetTime(); Managers().profilingManager->SetActive(profiling); // Begin new profiling frame. if (Managers().profilingManager->Active()) Managers().profilingManager->BeginFrame(); { PROFILE("Frame"); { GPUPROFILE("Frame", Video::Query::Type::TIME_ELAPSED); glfwPollEvents(); if (Input()->Triggered(InputHandler::WINDOWMODE)) { bool fullscreen, borderless; window->GetWindowMode(fullscreen, borderless); window->SetWindowMode(!fullscreen, borderless); } if (Input()->Triggered(InputHandler::PROFILE)) profiling = !profiling; // Start new frame. ImGuiImplementation::NewFrame(); window->Update(); if (editor->IsVisible()) { Hymn().world.ClearKilled(); Managers().particleManager->Update(Hymn().world, deltaTime, true); Managers().debugDrawingManager->Update(deltaTime); Hymn().Render(RenderManager::MONITOR, editor->GetCamera(), EditorSettings::GetInstance().GetBool("Sound Source Icons"), EditorSettings::GetInstance().GetBool("Particle Emitter Icons"), EditorSettings::GetInstance().GetBool("Light Source Icons"), EditorSettings::GetInstance().GetBool("Camera Icons"), EditorSettings::GetInstance().GetBool("Physics Volumes"), EditorSettings::GetInstance().GetBool("Lighting"), EditorSettings::GetInstance().GetBool("Light Volumes")); if (window->ShouldClose()) editor->Close(); editor->Show(deltaTime); if (window->ShouldClose() && !editor->isClosing()) window->CancelClose(); } else { { PROFILE("Update"); { GPUPROFILE("Update", Video::Query::Type::TIME_ELAPSED); Hymn().Update(deltaTime); } } { PROFILE("Render"); { GPUPROFILE("Render", Video::Query::Type::TIME_ELAPSED); if (Managers().vrManager->Active()) Hymn().Render(RenderManager::HMD); else Hymn().Render(RenderManager::MONITOR); } } if (Input()->Triggered(InputHandler::PLAYTEST)) { // Rollback to the editor state. editor->LoadSceneState(); // Turn editor back on. editor->SetVisible(true); } } } } if (Managers().profilingManager->Active()) { Managers().profilingManager->EndFrame(); profilingWindow.Show(); } ImGui::Render(); // Swap buffers and wait until next frame. window->SwapBuffers(); long wait = static_cast<long>((1.0 / targetFPS + lastTimeRender - glfwGetTime()) * 1000000.0); if (wait > 0) std::this_thread::sleep_for(std::chrono::microseconds(wait)); lastTimeRender = glfwGetTime(); } #ifdef USINGMEMTRACK MemTrack::TrackListMemoryUsage(); #endif // Save editor settings. EditorSettings::GetInstance().Save(); // Shut down and cleanup. ImGuiImplementation::Shutdown(); delete editor; Hymn().world.Clear(); Managers().ShutDown(); delete window; glfwTerminate(); Log() << "Editor ended - " << time(nullptr) << "\n"; return 0; }
cuba-rnd/entity-views
modules/global/src/com/haulmont/addons/cuba/entity/views/scan/ViewsNamespaceHandler.java
package com.haulmont.addons.cuba.entity.views.scan; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * Registers parser for the custom tag. */ public class ViewsNamespaceHandler extends NamespaceHandlerSupport { public static final String VIEWS = "views"; @Override public void init() { registerBeanDefinitionParser(VIEWS, new ViewsConfigurationParser()); } }
brandonbraun653/Apollo
lib/am335x_sdk/ti/csl/src/ip/emif4/V4/csl_emif4a.h
<filename>lib/am335x_sdk/ti/csl/src/ip/emif4/V4/csl_emif4a.h /** * @file csl_emif4a.h * * @brief * This is the main header file for the EMIF4F Module which defines * all the data structures and exported API. * * \par * ============================================================================ * @n (C) Copyright 2016, Texas Instruments, Inc. * * 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 Texas Instruments Incorporated 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. * */ /** @defgroup CSL_EMIF4F_API EMIF4F * * @section Introduction * The External Memory Interface (EMIF) is a TI developed re-usable IP component * targeted for SOC designs. The EMIF is a VBUSM slave peripheral providing an * interface to a wide variety of DDR SDRAM. This memory controller is a soft * macro and must be used with the DDR PHY hard macros to interface to the * DDR SDRAM. * * @subsection References * -# EMIF4F Functional Specification */ #ifndef CSL_EMIF4A_H_ #define CSL_EMIF4A_H_ #ifdef __cplusplus extern "C" { #endif #include <ti/csl/soc.h> #include <ti/csl/csl.h> #include <ti/csl/cslr_emif4f.h> /** @defgroup CSL_EMIF4F_SYMBOL EMIF4F Symbols Defined @ingroup CSL_EMIF4F_API */ /** @defgroup CSL_EMIF4F_DATASTRUCT EMIF4F Data Structures @ingroup CSL_EMIF4F_API */ /** @defgroup CSL_EMIF4F_FUNCTION EMIF4F Functions @ingroup CSL_EMIF4F_API */ /** @addtogroup CSL_EMIF4F_SYMBOL @{ */ /** * Handle to access EMIF4F registers accessible through config bus. */ #define hEmif ((CSL_EmifaRegs*)CSL_EMIFA_0_REGS) /** @} */ /** @addtogroup CSL_EMIF4F_DATASTRUCT @{ */ /** @brief This is the handle to the MPU Register */ typedef volatile CSL_EmifaRegs* CSL_Emif4fHandle; /** @brief EMIF4F SDRAM Configuration * * This structure is used to define the EMIF4F SDRAM * Configuration */ typedef struct EMIF4F_SDRAM_CONFIG { Uint8 sr; Uint8 pd; Uint8 pdwr; Uint8 nm; Uint8 cl; Uint8 bit11_9Lock; Uint8 iBank; Uint8 eBank; Uint8 pageSize; Uint8 NVMEnable; Uint8 eBankPos; Uint8 rdbNum; Uint8 rdbSize; }EMIF4F_SDRAM_CONFIG; /** @brief EMIF4F Asynchronous1 Configuration * * This structure is used to define the EMIF4F Asynchronous1 * Configuration */ typedef struct EMIF4F_ASYNC1_CONFIG { Uint8 ss; Uint8 ew; Uint8 w_setup; Uint8 w_strobe; Uint8 w_hold; Uint8 r_setup; Uint8 r_strobe; Uint8 r_hold; Uint8 ta; Uint8 aSize; }EMIF4F_ASYNC1_CONFIG; /** @brief EMIF4F Asynchronous2 Configuration * * This structure is used to define the EMIF4F Asynchronous2 * Configuration */ typedef struct EMIF4F_ASYNC2_CONFIG { Uint8 ss; Uint8 ew; Uint8 w_setup; Uint8 w_strobe; Uint8 w_hold; Uint8 r_setup; Uint8 r_strobe; Uint8 r_hold; Uint8 ta; Uint8 aSize; }EMIF4F_ASYNC2_CONFIG; /** @brief EMIF4F Asynchronous3 Configuration * * This structure is used to define the EMIF4F Asynchronous3 * Configuration */ typedef struct EMIF4F_ASYNC3_CONFIG { Uint8 ss; Uint8 ew; Uint8 w_setup; Uint8 w_strobe; Uint8 w_hold; Uint8 r_setup; Uint8 r_strobe; Uint8 r_hold; Uint8 ta; Uint8 aSize; }EMIF4F_ASYNC3_CONFIG; /** @brief EMIF4F Asynchronous4 Configuration * * This structure is used to define the EMIF4F Asynchronous4 * Configuration */ typedef struct EMIF4F_ASYNC4_CONFIG { Uint8 ss; Uint8 ew; Uint8 w_setup; Uint8 w_strobe; Uint8 w_hold; Uint8 r_setup; Uint8 r_strobe; Uint8 r_hold; Uint8 ta; Uint8 aSize; }EMIF4F_ASYNC4_CONFIG; /** @brief EMIF4F Timing Configuration * * This structure is used to define the EMIF4F Timing * Configuration */ typedef struct EMIF4F_TIMING_CONFIG { Uint8 t_rfc; Uint8 t_rp; Uint8 t_rcd; Uint8 t_wr; Uint8 t_ras; Uint8 t_rc; Uint8 t_rrd; }EMIF4F_TIMING_CONFIG; /** @brief EMIF4F NANDFCR Configuration * * This structure is used to define the EMIF4F NANDFCR * Configuration */ typedef struct EMIF4F_NANDFCR_CONFIG { Uint8 biteccAddCalcStart; Uint8 biteccStart; Uint16 cs5ecc; Uint16 cs4ecc; Uint8 cs3ecc; Uint8 cs2ecc; Uint16 bitEccSel; Uint16 cs5nand; Uint8 cs3nand; Uint8 cs2nand; }EMIF4F_NANDFCR_CONFIG; /** @brief NAND Flash Status * * This structure is used to define the NAND Flash Status */ typedef struct EMIF4F_NANDFSR_STAT { Uint8 eccErrNum; Uint8 eccState; Uint8 waitst; }EMIF4F_NANDFSR_STAT; /** @brief NAND Flash 1 ECC Register * * This structure is used to define the NAND Flash 1 ECC Register */ typedef struct EMIF4F_NANDF1ECC_REG { Uint8 p2048o; Uint8 p1204o; Uint8 p512o; Uint8 p256o; Uint8 p128o; Uint8 p64o; Uint8 p32o; Uint8 p16o; Uint8 p8o; Uint8 p4o; Uint8 p2o; Uint8 p1o; Uint8 p2948e; Uint8 p102e; Uint8 p512e; Uint8 p256e; Uint8 p128e; Uint8 p64e; Uint8 p32e; Uint8 p16e; Uint8 p8e; Uint8 p4e; Uint8 p2e; Uint8 p1e; }EMIF4F_NANDF1ECC_REG; /** @brief NAND Flash 2 ECC Register * * This structure is used to define the NAND Flash 2 ECC Register */ typedef struct EMIF4F_NANDF2ECC_REG { Uint8 p2048o; Uint8 p1204o; Uint8 p512o; Uint8 p256o; Uint8 p128o; Uint8 p64o; Uint8 p32o; Uint8 p16o; Uint8 p8o; Uint8 p4o; Uint8 p2o; Uint8 p1o; Uint8 p2948e; Uint8 p102e; Uint8 p512e; Uint8 p256e; Uint8 p128e; Uint8 p64e; Uint8 p32e; Uint8 p16e; Uint8 p8e; Uint8 p4e; Uint8 p2e; Uint8 p1e; }EMIF4F_NANDF2ECC_REG; /** @brief NAND Flash 3 ECC Register * * This structure is used to define the NAND Flash 3 ECC Register */ typedef struct EMIF4F_NANDF3ECC_REG { Uint8 p2048o; Uint8 p1204o; Uint8 p512o; Uint8 p256o; Uint8 p128o; Uint8 p64o; Uint8 p32o; Uint8 p16o; Uint8 p8o; Uint8 p4o; Uint8 p2o; Uint8 p1o; Uint8 p2948e; Uint8 p102e; Uint8 p512e; Uint8 p256e; Uint8 p128e; Uint8 p64e; Uint8 p32e; Uint8 p16e; Uint8 p8e; Uint8 p4e; Uint8 p2e; Uint8 p1e; }EMIF4F_NANDF3ECC_REG; /** @brief NAND Flash 4 ECC Register * * This structure is used to define the NAND Flash 4 ECC Register */ typedef struct EMIF4F_NANDF4ECC_REG { Uint8 p2048o; Uint8 p1204o; Uint8 p512o; Uint8 p256o; Uint8 p128o; Uint8 p64o; Uint8 p32o; Uint8 p16o; Uint8 p8o; Uint8 p4o; Uint8 p2o; Uint8 p1o; Uint8 p2948e; Uint8 p102e; Uint8 p512e; Uint8 p256e; Uint8 p128e; Uint8 p64e; Uint8 p32e; Uint8 p16e; Uint8 p8e; Uint8 p4e; Uint8 p2e; Uint8 p1e; }EMIF4F_NANDF4ECC_REG; /** @brief NAND Flash 4-Bit ECC LOAD Register * * This structure is used to define the NAND Flash 4-Bit ECC LOAD Register. */ typedef struct EMIF4F_NAND4BITECCLOAD_REG { Uint16 bitEccLoad; }EMIF4F_NAND4BITECCLOAD_REG; /** @brief NAND Flash 4-Bit ECC Register 1 * * This structure is used to define the NAND Flash 4-Bit ECC Register 1 */ typedef struct EMIF4F_NAND4BITECC1_REG { Uint16 bitEccVal2; Uint16 bitEccVal1; }EMIF4F_NAND4BITECC1_REG; /** @brief NAND Flash 4-Bit ECC Register 2 * * This structure is used to define the NAND Flash 4-Bit ECC Register 2 */ typedef struct EMIF4F_NAND4BITECC2_REG { Uint16 bitEccVal4; Uint16 bitEccVal3; }EMIF4F_NAND4BITECC2_REG; /** @brief NAND Flash 4-Bit ECC Register 3 * * This structure is used to define the NAND Flash 4-Bit ECC Register 3 */ typedef struct EMIF4F_NAND4BITECC3_REG { Uint16 bitEccVal6; Uint16 bitEccVal5; }EMIF4F_NAND4BITECC3_REG; /** @brief NAND Flash 4-Bit ECC Register 4 * * This structure is used to define the NAND Flash 4-Bit ECC Register 4 */ typedef struct EMIF4F_NAND4BITECC4_REG { Uint16 bitEccVal8; Uint16 bitEccVal7; }EMIF4F_NAND4BITECC4_REG; /** @brief NAND Flash 4-Bit ECC Error Address Register 1 * * This structure is used to define the NAND Flash 4-Bit ECC Error Address Register 1 */ typedef struct EMIF4F_NANDERRADD1_REG { Uint16 bitEccErrAdd2; Uint16 bitEccErrAdd1; }EMIF4F_NANDERRADD1_REG; /** @brief NAND Flash 4-Bit ECC Error Address Register 2 * * This structure is used to define the NAND Flash 4-Bit ECC Error Address Register 2 */ typedef struct EMIF4F_NANDERRADD2_REG { Uint16 bitEccErrAdd4; Uint16 bitEccErrAdd3; }EMIF4F_NANDERRADD2_REG; /** @brief NAND Flash 4-Bit ECC Error Value Register 1 * * This structure is used to define the NAND Flash 4-Bit ECC Error Value Register 1 */ typedef struct EMIF4F_NANDERRVAL1_VALUE { Uint16 bitEccErrVal2; Uint16 bitEccErrVal1; }EMIF4F_NANDERRADD1_VALUE; /** @brief NAND Flash 4-Bit ECC Error Value Register 2 * * This structure is used to define the NAND Flash 4-Bit ECC Error Value Register 2 */ typedef struct EMIF4F_NANDERRVAL2_VALUE { Uint16 bitEccErrVal4; Uint16 bitEccErrVal3; }EMIF4F_NANDERRADD2_VALUE; /* @} */ /** @addtogroup CSL_EMIF4F_FUNCTION @{ */ /* @} */ #ifdef __cplusplus } #endif #endif /* CSL_EMIF4F_H_ */
duanyifei1937/go-tour
src/chapter08/demo_8.1.4/anonymous/anonymous.go
<gh_stars>0 package main import "fmt" type firstS struct { in1 int in2 int } // 匿名字段和面向对象编程中的继承概念相似,可以被用来模拟类似继承的行为。 // Go语言中的继随是通过内嵌或组合来实现的,所以可以说在Go语言中,组合比继承更受欢迎。 type secondS struct { b int c float32 int // 匿名字段 firstS // 匿名字段 } func main() { sec := new(secondS) sec.b = 6 sec.c = 7.5 sec.int = 60 sec.in1 = 5 sec.in2 = 10 fmt.Printf("sec.b is : %d\n", sec.b) fmt.Printf("sec.c is : %f\n", sec.c) fmt.Printf("sec.int is : %d\n", sec.int) fmt.Printf("sec.in1 is : %d\n", sec.in1) fmt.Printf("sec.in2 is : %d\n", sec.in2) // 使用结构体字面量 sec2 := secondS{6, 7.5, 60, firstS{5, 10}} fmt.Println("sec2 is:", sec2) }
ee7/exercism-c
exercises/practice/triangle/triangle.h
<reponame>ee7/exercism-c #ifndef TRIANGLE_H #define TRIANGLE_H typedef struct { double a; double b; double c; } triangle_t; #endif
wipup/discord-bot
src/main/java/wp/discord/bot/config/properties/DiscordProperties.java
package wp.discord.bot.config.properties; import java.util.Set; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; import wp.discord.bot.util.ToStringUtils; @Data @ConfigurationProperties(prefix = "discord") public class DiscordProperties { private String oauth2Url; private String token; private Integer largeThreshold; private DiscordStatus status; private Set<DiscordUserProperties> users; private String audioFolder; @Override public String toString() { return ToStringUtils.toString(this); } }
LaCocoRoco/Scope
src/twincat/scope/TriggerGroup.java
<reponame>LaCocoRoco/Scope package twincat.scope; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.concurrent.CopyOnWriteArrayList; public class TriggerGroup implements Observer { /*********************************/ /******** global variable ********/ /*********************************/ private String triggerGroupName = "TriggerGroup"; private boolean enabled = true; private int triggerOffset = 0; /*********************************/ /***** global final variable *****/ /*********************************/ private final CopyOnWriteArrayList<Long> triggerTimeStampList = new CopyOnWriteArrayList<Long>(); private final CopyOnWriteArrayList<TriggerChannel> triggerChannelList = new CopyOnWriteArrayList<TriggerChannel>(); /*********************************/ /******** setter & getter ********/ /*********************************/ public String getTriggerGroupName() { return triggerGroupName; } public void setTriggerGroupName(String triggerGroupName) { this.triggerGroupName = triggerGroupName; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getTriggerOffset() { return triggerOffset; } public void setTriggerOffset(int triggerOffset) { this.triggerOffset = triggerOffset; } public CopyOnWriteArrayList<Long> getTriggerTimeStampList() { return triggerTimeStampList; } public CopyOnWriteArrayList<TriggerChannel> getTriggerChannelList() { return triggerChannelList; } /*********************************/ /******** override method ********/ /*********************************/ @Override public String toString() { return triggerGroupName; } @Override public void update(Observable observable, Object object) { if (getTriggerCombined()) { TriggerChannel triggerChannel = (TriggerChannel) observable; triggerTimeStampList.add(triggerChannel.getReleaseTimeStamp()); } } /*********************************/ /********* public method *********/ /*********************************/ public long getTriggerTimeStamp(long displayTime) { if (enabled) { if (!triggerTimeStampList.isEmpty()) { long displayTimeOffset = displayTime / 100 * (100 - triggerOffset); long lastTriggerTimeStamp = triggerTimeStampList.get(triggerTimeStampList.size() - 1); for (int i = triggerTimeStampList.size() - 1; i >= 0; i--) { long triggerTimeStamp = triggerTimeStampList.get(i); if (triggerTimeStamp < lastTriggerTimeStamp - displayTimeOffset) { return triggerTimeStamp + displayTimeOffset; } } } } return 0; } public void addTriggerChannel(TriggerChannel triggerChannel) { triggerChannel.addObserver(this); triggerChannelList.add(triggerChannel); } public void removeTrigger(TriggerChannel remove) { for (TriggerChannel triggerChannel : triggerChannelList) { if (triggerChannel.equals(remove)) { triggerChannel.deleteObserver(this); triggerChannelList.remove(triggerChannel); } } } /*********************************/ /******** private method *********/ /*********************************/ private boolean getTriggerCombined() { if (!triggerChannelList.isEmpty()) { Iterator<TriggerChannel> triggerChannelIterator = triggerChannelList.iterator(); while (triggerChannelIterator.hasNext()) { TriggerChannel triggerChannel = triggerChannelIterator.next(); if (triggerChannel.getCombine() == TriggerChannel.Combine.OR) { if (triggerChannel.getReleaseTimeStamp() != 0) { return true; } } if (triggerChannel.getCombine() == TriggerChannel.Combine.AND) { if (triggerChannel.getReleaseTimeStamp() == 0) { return false; } } } return true; } return false; } }
Farhan-hyd/CodingPractice
modulewise.practice/stlchallange/unlock.java
import java.io.*; import java.util.*; class Res { String max = ""; } class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void findMaximumNum(char[] ar, int k, Res r) { if (k == 0) return; int n = ar.length; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (ar[j] > ar[i]) { char temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; String st = new String(ar); if (r.max.compareTo(st) < 0) { r.max = st; } findMaximumNum(ar, k - 1, r); temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } } } } public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int n = sc.nextInt(); int k = sc.nextInt(); String[] inp = sc.nextLine().split(" "); String str = ""; for (int i = 0; i < n; i++) { str += inp[i]; } Res r = new Res(); r.max = str; findMaximumNum(str.toCharArray(), k, r); char[] ch = r.max.toCharArray(); for (char c : ch) { System.out.print(c+" "); } } } // #include<bits/stdc++.h> // using namespace std; // #define ll long long // int main(){ // int N,K; // cin>>N>>K; // int arr[N+1],index[N+1]; // for(int i=1;i<=N;i++){ // cin>>arr[i]; // index[arr[i]]=i; // } // int temp=N,i=1; // while(K && i<=N){ // if(arr[i]!=temp){ // int pos=index[temp]; // index[arr[i]]=pos; // swap(arr[i],arr[pos]); // K--; // } // i++; // temp--; // } // for(int i=1;i<=N;i++) // cout<<arr[i]<<" "; // }
ChimpGamer/HubParkour
src/main/java/me/block2block/hubparkour/listeners/SetupListener.java
package me.block2block.hubparkour.listeners; import me.block2block.hubparkour.Main; import me.block2block.hubparkour.api.events.admin.ParkourSetupEvent; import me.block2block.hubparkour.api.plates.*; import me.block2block.hubparkour.entities.Parkour; import me.block2block.hubparkour.managers.CacheManager; import me.block2block.hubparkour.utils.ConfigUtil; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings("ALL") public class SetupListener implements Listener { private List<PressurePlate> data = new ArrayList<>(); private List<String> commandData = new ArrayList<>(); private int after = -1; @SuppressWarnings("unused") @EventHandler public void onChat(AsyncPlayerChatEvent e) { if (CacheManager.isSetup(e.getPlayer())) { e.setCancelled(CacheManager.getSetupWizard().onChat(e.getMessage())); } else if (CacheManager.isEdit(e.getPlayer())) { e.setCancelled(CacheManager.getEditWizard().onChat(e.getMessage())); } } @SuppressWarnings("unused") @EventHandler public void onInteract(PlayerInteractEvent e) { if (CacheManager.isSetup(e.getPlayer())) { if (e.hasItem()) { if (e.getItem().getType() == Material.STICK && ChatColor.stripColor(e.getItem().getItemMeta().getDisplayName()).equals("HubParkour Setup Stick")) { Location location = e.getPlayer().getLocation().getBlock().getLocation(); location.setPitch(e.getPlayer().getLocation().getPitch()); location.setYaw(e.getPlayer().getLocation().getYaw()); CacheManager.getSetupWizard().stickInteract(location); } } } else if (CacheManager.isEdit(e.getPlayer())) { if (e.hasItem()) { if (e.getItem().getType() == Material.STICK && ChatColor.stripColor(e.getItem().getItemMeta().getDisplayName()).equals("HubParkour Setup Stick")) { Location location = e.getPlayer().getLocation().getBlock().getLocation(); location.setPitch(e.getPlayer().getLocation().getPitch()); location.setYaw(e.getPlayer().getLocation().getYaw()); CacheManager.getEditWizard().onStick(location); } } } } }
wzaylor/FEBio_MCLS
FEBioSource2.9/FECore/FEBroydenStrategy.cpp
<reponame>wzaylor/FEBio_MCLS<filename>FEBioSource2.9/FECore/FEBroydenStrategy.cpp /*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2019 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "FEBroydenStrategy.h" #include "LinearSolver.h" #include "FEException.h" //----------------------------------------------------------------------------- //! constructor FEBroydenStrategy::FEBroydenStrategy(FENewtonSolver* pns) : FENewtonStrategy(pns) { } //----------------------------------------------------------------------------- //! Initialization void FEBroydenStrategy::Init(int neq, LinearSolver* pls) { if (m_max_buf_size <= 0) m_max_buf_size = m_maxups; // allocate storage for Broyden update vectors m_R.resize(m_max_buf_size, neq); m_D.resize(m_max_buf_size, neq); m_rho.resize(m_max_buf_size); m_q.resize(neq, 0.0); m_neq = neq; m_nups = 0; m_plinsolve = pls; m_bnewStep = true; } //! Presolve update void FEBroydenStrategy::PreSolveUpdate() { m_bnewStep = true; } //----------------------------------------------------------------------------- //! perform a quasi-Newton udpate bool FEBroydenStrategy::Update(double s, vector<double>& ui, vector<double>& R0, vector<double>& R1) { // calculate q1 m_q.assign(m_neq, 0.0); if (m_plinsolve->BackSolve(m_q, R1) == false) throw LinearSolverFailed(); // only update when allowed if ((m_nups < m_max_buf_size) || (m_cycle_buffer == true)) { // since the number of updates can be larger than buffer size we need to clamp int nups = (m_nups >= m_max_buf_size ? m_max_buf_size - 1 : m_nups); // get the "0" buffer index int n0 = (m_nups >= m_max_buf_size ? (m_nups + 1) % m_max_buf_size : 0); int n1 = (m_nups >= m_max_buf_size ? (m_nups) % m_max_buf_size : m_nups); // loop over update vectors for (int j = 0; j<nups; ++j) { int n = (n0 + j) % m_max_buf_size; double w = 0.0; for (int i = 0; i<m_neq; ++i) w += (m_D[n][i] * m_q[i]); double g = m_rho[n] * w; for (int i = 0; i<m_neq; ++i) m_q[i] += g*(m_D[n][i] - m_R[n][i]); } // form and store the next update vector double rhoi = 0.0; for (int i = 0; i<m_neq; ++i) { double ri = m_q[i] - ui[i]; double di = -s*ui[i]; m_R[n1][i] = ri; m_D[n1][i] = di; rhoi += di*ri; } m_rho[n1] = 1.0 / (rhoi); } m_nups++; return true; } //----------------------------------------------------------------------------- //! solve the equations void FEBroydenStrategy::SolveEquations(vector<double>& x, vector<double>& b) { // loop over update vectors if (m_nups == 0) { if (m_plinsolve->BackSolve(x, b) == false) throw LinearSolverFailed(); m_bnewStep = false; } else { // since the number of updates can be larger than buffer size we need to clamp int nups = (m_nups > m_max_buf_size ? m_max_buf_size : m_nups); // get the first and last buffer index int n0 = 0; int n1 = nups - 1; if ((m_nups > m_max_buf_size) && (m_cycle_buffer == true)) { n0 = m_nups % m_max_buf_size; n1 = (m_nups - 1) % m_max_buf_size; } if (m_bnewStep) { m_q.assign(m_neq, 0.0); if (m_plinsolve->BackSolve(m_q, b) == false) throw LinearSolverFailed(); for (int j = 0; j<nups - 1; ++j) { int n = (n0 + j) % m_max_buf_size; double w = 0.0; for (int i = 0; i<m_neq; ++i) w += (m_D[n][i] * m_q[i]); double g = m_rho[n] * w; for (int i = 0; i<m_neq; ++i) m_q[i] += g*(m_D[n][i] - m_R[n][i]); } m_bnewStep = false; } // calculate solution double rho = 0.0; for (int i = 0; i<m_neq; ++i) rho += m_D[n1][i] * m_q[i]; rho *= m_rho[n1]; for (int i = 0; i<m_neq; ++i) { x[i] = m_q[i] + rho*(m_D[n1][i] - m_R[n1][i]); } } } /* //----------------------------------------------------------------------------- //! perform a quasi-Newton udpate bool FEBroydenStrategy::Update(double s, vector<double>& ui, vector<double>& R0, vector<double>& R1) { // calculate q1 // TODO: q is not initialized. Don't the iterative solvers use this as an initial guess? // TODO: Can I use ui as an initial guess for q? vector<double> q(m_neq); if (m_plinsolve->BackSolve(q, R1) == false) throw LinearSolverFailed(); // only update when allowed if ((m_nups < m_max_buf_size) || (m_cycle_buffer == true)) { // since the number of updates can be larger than buffer size we need to clamp int nups = (m_nups >= m_max_buf_size ? m_max_buf_size - 1: m_nups); // get the "0" buffer index int n0 = (m_nups >= m_max_buf_size ? (m_nups + 1) % m_max_buf_size : 0); int n1 = (m_nups >= m_max_buf_size ? (m_nups ) % m_max_buf_size : m_nups); // loop over update vectors for (int j=0; j<nups; ++j) { int n = (n0 + j) % m_max_buf_size; double w = 0.0; for (int i=0; i<m_neq; ++i) w += (m_D[n][i]*q[i]); double g = m_rho[n]*w; for (int i=0; i<m_neq; ++i) q[i] += g*(m_D[n][i] - m_R[n][i]); } // form and store the next update vector double rhoi = 0.0; for (int i=0; i<m_neq; ++i) { double ri = q[i] - ui[i]; double di = -s*ui[i]; m_R[n1][i] = ri; m_D[n1][i] = di; rhoi += di*ri; } m_rho[n1] = 1.0 / (rhoi); } m_nups++; return true; } //----------------------------------------------------------------------------- //! solve the equations void FEBroydenStrategy::SolveEquations(vector<double>& x, vector<double>& b) { // loop over update vectors if (m_nups == 0) { if (m_plinsolve->BackSolve(x, b) == false) throw LinearSolverFailed(); } else { // calculate q1 vector<double> q(m_neq); if (m_plinsolve->BackSolve(q, b) == false) throw LinearSolverFailed(); // since the number of updates can be larger than buffer size we need to clamp int nups = (m_nups > m_max_buf_size ? m_max_buf_size : m_nups); // get the first and last buffer index int n0 = 0; int n1 = nups - 1; if ((m_nups > m_max_buf_size) && (m_cycle_buffer == true)) { n0 = m_nups % m_max_buf_size; n1 = (m_nups - 1) % m_max_buf_size; } for (int j=0; j<nups-1; ++j) { int n = (n0 + j) % m_max_buf_size; double w = 0.0; for (int i=0; i<m_neq; ++i) w += (m_D[n][i]*q[i]); double g = m_rho[n]*w; for (int i=0; i<m_neq; ++i) q[i] += g*(m_D[n][i] - m_R[n][i]); } // calculate solution double rho = 0.0; for (int i=0; i<m_neq; ++i) rho += m_D[n1][i]*q[i]; rho *= m_rho[n1]; for (int i=0; i<m_neq; ++i) { x[i] = q[i] + rho*(m_D[n1][i] - m_R[n1][i]); } } } */
asminer/smart
src/_Meddly/src/storage/ct_styles.cc
<gh_stars>1-10 /* Meddly: Multi-terminal and Edge-valued Decision Diagram LibrarY. Copyright (C) 2009, Iowa State University Research Foundation, Inc. This library 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. This library 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 library. If not, see <http://www.gnu.org/licenses/>. */ #include "ct_styles.h" // #define DEBUG_SLOW // #define DEBUG_CT_SEARCHES // #define DEBUG_CT_SLOTS // #define DEBUG_REHASH // #define DEBUG_TABLE2LIST // #define DEBUG_LIST2TABLE // #define DEBUG_CTALLOC // #define DEBUG_ISDEAD // #define DEBUG_ISSTALE // #define DEBUG_REMOVESTALES // #define DEBUG_REMOVESTALES_DETAILS // #define DEBUG_CT_SCAN // #define DEBUG_CT // #define DEBUG_VALIDATE_COUNTS #define INTEGRATED_MEMMAN #include "../hash_stream.h" #include <climits> #include "ct_typebased.h" #include "ct_none.h" // ********************************************************************** // * * // * monolithic_chained_style methods * // * * // ********************************************************************** MEDDLY::monolithic_chained_style::monolithic_chained_style() { } MEDDLY::compute_table* MEDDLY::monolithic_chained_style::create(const ct_initializer::settings &s) const { switch (s.compression) { case ct_initializer::None: return new ct_none<true, true>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<true, true>(s, 0, 0); default: return 0; } } bool MEDDLY::monolithic_chained_style::usesMonolithic() const { return true; } // ********************************************************************** // * * // * monolithic_unchained_style methods * // * * // ********************************************************************** MEDDLY::monolithic_unchained_style::monolithic_unchained_style() { } MEDDLY::compute_table* MEDDLY::monolithic_unchained_style::create(const ct_initializer::settings &s) const { switch (s.compression) { case ct_initializer::None: return new ct_none<true, false>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<true, false>(s, 0, 0); default: return 0; } } bool MEDDLY::monolithic_unchained_style::usesMonolithic() const { return true; } // ********************************************************************** // * * // * operation_chained_style methods * // * * // ********************************************************************** MEDDLY::operation_chained_style::operation_chained_style() { } MEDDLY::compute_table* MEDDLY::operation_chained_style::create(const ct_initializer::settings &s, operation* op, unsigned slot) const { switch (s.compression) { case ct_initializer::None: return new ct_none<false, true>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<false, true>(s, 0, 0); default: return 0; } } bool MEDDLY::operation_chained_style::usesMonolithic() const { return false; } // ********************************************************************** // * * // * operation_unchained_style methods * // * * // ********************************************************************** MEDDLY::operation_unchained_style::operation_unchained_style() { } MEDDLY::compute_table* MEDDLY::operation_unchained_style::create(const ct_initializer::settings &s, operation* op, unsigned slot) const { switch (s.compression) { case ct_initializer::None: return new ct_none<false, false>(s, 0, 0); case ct_initializer::TypeBased: return new ct_typebased<false, false>(s, 0, 0); default: return 0; } } bool MEDDLY::operation_unchained_style::usesMonolithic() const { return false; }
dgrlucky/PointLegend
PointLegend/Classes/PLChooseWindow.h
<reponame>dgrlucky/PointLegend // // PLChooseWindow.h // Legend // // Created by ydcq on 15/12/2. // Copyright © 2015年 frocky. All rights reserved. // #import <UIKit/UIKit.h> @interface PLChooseWindow : UIWindow /** * 筛选条件数组 */ @property (nonatomic, strong) NSArray *itemArray; @property (nonatomic, weak) id delegate; - (void)show; - (void)dismiss; void setSelectedIndexToZero(); @end
vitorrsbarbosa/ResolucoesLivros
Programacao/Treinamento_em_Liguagem_C/Cap1/ex26.c
<filename>Programacao/Treinamento_em_Liguagem_C/Cap1/ex26.c /*Treinamento em Linguagem C - <NAME> Capítulo 1 - Conceitos Basicos Exercício 26: Escreva um programa que tenha a seguinte saida: Treinamento em Programacao. Linguagem C. a) com uma unica instrucao de impressao b) com tres instrucoes de impressao c) dentro de uma moldura */ #include<stdio.h> int main(){ printf("Treinamento em Programacao.\nLinguagem C");/*a)*/ printf("\n\n"); /* Separar o a) do b) */ printf("Treinamento em "); /*b)*/ printf("Programacao."); printf("\nLinguagem C."); printf("\n\n"); /* Separar o b) do c) */ printf("\n\t\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB"); printf("\n\t\xBA Linguagem em Programacao \xBA"); printf("\n\t\xBA Linguagem C \xBA"); printf("\n\t\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC"); return 0; }
Gridelen/core-python-ex
12/12.6/import.py
<reponame>Gridelen/core-python-ex ''' 12-6. Extended Import. Create a new function called importAs(). This function will import a module into your namespace, but with a name you specify, not its original name. For example, calling newname=importAs ('mymodule') will import the module mymodule, but the module and all its elements are accessible only as newname or newname.attr. This is the exact functionality provided by the new extended import syntax introduced in Python 2.0. ''' def importAs(module_name): return __import__(module_name) syst = importAs('os') print('cpu count', syst.cpu_count())
chen-star/Spring-Framework-Impl
src/test/java/org/alex/aop/AspectListExecutorTest.java
<filename>src/test/java/org/alex/aop/AspectListExecutorTest.java package org.alex.aop; import org.alex.aop.aspect.AspectInfo; import org.alex.aop.mock.MockDefaultAspect1; import org.alex.aop.mock.MockDefaultAspect2; import org.alex.aop.mock.MockDefaultAspect3; import org.alex.aop.mock.MockDefaultAspect4; import org.alex.aop.mock.MockDefaultAspect5; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; class AspectListExecutorTest { @DisplayName("AspectListExecutorTest: sortTest") @Test public void sortTest() { List<AspectInfo> aspectInfos = new ArrayList<>(); aspectInfos.add(new AspectInfo(3, new MockDefaultAspect1(), null)); aspectInfos.add(new AspectInfo(5, new MockDefaultAspect2(), null)); aspectInfos.add(new AspectInfo(2, new MockDefaultAspect3(), null)); aspectInfos.add(new AspectInfo(4, new MockDefaultAspect4(), null)); aspectInfos.add(new AspectInfo(1, new MockDefaultAspect5(), null)); AspectListExecutor executor = new AspectListExecutor(AspectListExecutorTest.class, aspectInfos); List<AspectInfo> sortedAspectInfos = executor.getSortedAspectInfoList(); for(AspectInfo aspectInfo : sortedAspectInfos) { System.out.println(aspectInfo.getAspectObject().getClass()); } Assertions.assertEquals(MockDefaultAspect1.class, sortedAspectInfos.get(2).getAspectObject().getClass()); } }
redhawkIT/typescript-eslint
packages/shared-fixtures/fixtures/javascript/templateStrings/tagged-no-placeholders.src.js
<filename>packages/shared-fixtures/fixtures/javascript/templateStrings/tagged-no-placeholders.src.js foo`foo`;
hashimati/MicroCli
Code Examples/JWT/java/SecurityExample/src/main/java/io/hashimati/security/repository/UserRepository.java
package io.hashimati.security.repository; import io.hashimati.security.domains.LoginStatus; import io.hashimati.security.domains.User; import io.micronaut.data.jdbc.annotation.JdbcRepository; import io.micronaut.data.model.query.builder.sql.Dialect; import io.micronaut.data.repository.CrudRepository; import java.time.Instant; import java.util.List; @JdbcRepository(dialect = Dialect.H2) public interface UserRepository extends CrudRepository<User, Long> { public User findByUsername(String username); public List<User> findAll(); public boolean existsByUsername(String username); public Long updateByUsername(String username, LoginStatus lastLoginStatus, Instant lastTimeTryToLogin); }
justem007/rossina
public/node_modules/ng-admin/src/javascripts/ng-admin/Crud/fieldView/EmbeddedListFieldView.js
<filename>public/node_modules/ng-admin/src/javascripts/ng-admin/Crud/fieldView/EmbeddedListFieldView.js module.exports = { getReadWidget: () => '<ma-embedded-list-column field="::field" value="::value" datastore="::datastore"></ma-embedded-list-column>', getLinkWidget: () => 'error: cannot display referenced_list field as linkable', getFilterWidget: () => 'error: cannot display referenced_list field as filter', getWriteWidget: () => '<ma-embedded-list-field field="::field" value="value" datastore="::datastore"></ma-embedded-list-field>' };
wangsenyuan/learn-go
src/leetcode/set1000/set1000/set1300/set1370/p1377/solution.go
<reponame>wangsenyuan/learn-go package p1377 func frogPosition(n int, edges [][]int, t int, target int) float64 { conns := make([][]int, n) for i := 0; i < n; i++ { conns[i] = make([]int, 0, 3) } for _, e := range edges { u, v := e[0]-1, e[1]-1 conns[u] = append(conns[u], v) conns[v] = append(conns[v], u) } depth := make([]int, n) var dfs func(p, u int) dp := make([]float64, n) dp[0] = 1 leaf := make([]bool, n) dfs = func(p, u int) { c := len(conns[u]) if p >= 0 { c-- } for _, v := range conns[u] { if p == v { continue } dp[v] = dp[u] * (1 / float64(c)) } leaf[u] = true for _, v := range conns[u] { if p == v { continue } depth[v] = depth[u] + 1 leaf[u] = false dfs(u, v) } } dfs(-1, 0) target-- if depth[target] > t { return 0 } if depth[target] == t || leaf[target] { return dp[target] } return 0 }
TheGoldLab/TheGoldLab.github.io
SnowDotsDocumentation/DoxyDocs/classdots_all_singleton_objects.js
<filename>SnowDotsDocumentation/DoxyDocs/classdots_all_singleton_objects.js var classdots_all_singleton_objects = [ [ "reset", "classdots_all_singleton_objects.html#a1a7708cf677a74c3d8b61271d3d80faf", null ], [ "initialize", "classdots_all_singleton_objects.html#ad5621c741ad3ecc4b4d0f261d2bc0956", null ], [ "initializeLists", "classdots_all_singleton_objects.html#a14617ca6a83aaa6ebbf83f6f7373428d", null ], [ "set", "classdots_all_singleton_objects.html#ab2b08ddc4e66b7c4343e8ae574a380ab", null ], [ "obj", "classdots_all_singleton_objects.html#aa769c4e57badebc6937a3243f73a1653", null ], [ "g", "classdots_all_singleton_objects.html#ac335fcd3ffded2d63c1bfe27453421ae", null ] ];
HarryStevens/swiftmap
src/utils/isString.js
export default function isString(str){ return !!str && typeof str === "string"; }
NaxHPL/RiichiCompanion
RiichiCompanion/app/src/main/java/com/example/riichicompanion/handcalculation/yaku/Haitei.java
<gh_stars>0 package com.example.riichicompanion.handcalculation.yaku; import com.example.riichicompanion.handcalculation.Hand; import com.example.riichicompanion.handcalculation.HandArrangement; import com.example.riichicompanion.handcalculation.WinConditions; import java.util.ArrayList; public class Haitei implements Yaku { @Override public boolean isConditionMet(Hand hand, HandArrangement arrangement, WinConditions conditions) { return conditions.isHaiteiOrHoutei() && conditions.isTsumo(); } @Override public int getYakumans() { return 0; } @Override public int getHan() { return 1; } @Override public String getDisplayName() { return "Haitei raoyui"; } @Override public ArrayList<Class<? extends Yaku>> getInvalidYaku() { return new ArrayList<Class<? extends Yaku>>(3) {{ add(Rinshan.class); add(Houtei.class); add(Chankan.class); }}; } }
seatsio/seatsio-java
src/main/java/seatsio/reports/usage/detailsForEventInMonth/UsageForObject.java
<filename>src/main/java/seatsio/reports/usage/detailsForEventInMonth/UsageForObject.java package seatsio.reports.usage.detailsForEventInMonth; import java.time.Instant; public class UsageForObject { public String object; public int numFirstBookings; public Instant firstBookingDate; public int numFirstSelections; public int numFirstBookingsOrSelections; }
Lesterpig/dfss
tests/dummy.go
<reponame>Lesterpig/dfss<gh_stars>1-10 // Package tests provides DFSS integration tests. package tests
rajagurunath/mlvajra
mlvajra/explanations/localExp.py
import shap import numpy as np import pandas as pd import enum from typing import Callable from lime.lime_tabular import LimeTabularExplainer from sklearn.preprocessing import MinMaxScaler try: import tensorflow as tf from sklearn.base import BaseEstimator import catboost import xgboost except ImportError as e: print(e) finally: print("Above Modules are not available -use other supported packages") class Explain(object): def __init__(self,path:str,modelloader:Callable): self.modelloader=modelloader def explain(self,exptype): pass def applytransform(self,): pass def exportExplanation(self,): pass class LimeExp(Explain): def __init__(self,config,df=None): self.config=config self.sc=MinMaxScaler() if not isinstance(df,pd.DataFrame): df=pd.read_csv('../temp_data/val.csv.tar.gz') features=self.sc.fit_transform(df[config['columns']].dropna()) self.explainer=LimeTabularExplainer(features, feature_names=self.config['columns'], class_names=['not anomaly','anomaly'], discretize_continuous=True) #pickle.dump(self.explainer,open('{}/limeexp.pkl'.format(self.DIR))) def explain(self,array:np.array,model): #self.explainer=pickle.load(open('{}/limeexp.pkl'.format(self.DIR))) response,contrib=[],[] for instance in array: exp = self.explainer.explain_instance(instance,model.predict_proba, num_features=5,num_samples=1000) dict_=dict(exp.as_list()) response.append(",".join(list(dict_.keys()))) contrib.append(",".join(list(map(str,dict_.values())))) return response,contrib class ShapExp(Explain): def __init__(self,config,df=None,model=None): self.config=config if not isinstance(df,pd.DataFrame): df=pd.read_csv('../temp_data/val.csv.tar.gz') if not model: import tensorflow as tf model=tf.keras.models.load_model(config['model_path']) self.explainer = shap.KernelExplainer(model.predict, df.loc[:10000,config['columns']]) def explain(self,array): shap_list=[] for instance in array: shap_values = self.explainer.shap_values(instance, nsamples=50) shap_list.append(np.mean(np.array(shap_values),axis=0)) return [self.config['columns']]*len(shap_list),np.array(shap_list) # if __name__=='__main__': # CONFIG={} # she=ShapExp(CONFIG) # #s,a=she.explain(X.iloc[:10].values)
BuckWang0509/codeforces-go
leetcode/weekly/272/c/c.go
<gh_stars>1-10 package main /* 分组循环 将 $\textit{prices}$ 按照平滑下降的定义分成若干组。例如 $[3,2,1,4]$ 分为 $[3,2,1]$ 和 $[4]$ 两组。 对于每一组的所有非空子数组,都是平滑下降的。设该组长度为 $m$,则该组的非空子数组个数为 $$ C_{m+1}^2 = \dfrac{m(m+1)}{2} $$ 累加每组的非空子区间个数即为答案。 - 时间复杂度:$O(n)$,其中 $n$ 是数组 $\textit{prices}$ 的长度。注意下面代码内外层循环共用同一个变量 $i$,时间复杂度就是 `i++` 的执行次数,即 $O(n)$。 - 空间复杂度:$O(1)$,我们只需要常数的空间保存若干变量。 */ // github.com/EndlessCheng/codeforces-go func getDescentPeriods(prices []int) (ans int64) { for i, n := 0, len(prices); i < n; { i0 := i for i++; i < n && prices[i] == prices[i-1]-1; i++ { } ans += int64(i-i0) * int64(i-i0+1) / 2 } return }
brettdavidson3/eclipselink.runtime
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/queries/report/ReportQueryRetrievePrimaryKeysCursorTest.java
<gh_stars>0 package org.eclipse.persistence.testing.tests.queries.report; import java.math.BigDecimal; import java.util.HashMap; import java.util.Vector; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.queries.CursoredStream; import org.eclipse.persistence.queries.ReportQuery; import org.eclipse.persistence.queries.ReportQueryResult; import org.eclipse.persistence.testing.framework.TestCase; import org.eclipse.persistence.testing.models.employee.domain.Employee; /** * Test retrieving primary keys and other values with a ReportQuery, using a Cursor * Bug TO-DO */ public class ReportQueryRetrievePrimaryKeysCursorTest extends TestCase { protected ReportQuery reportQuery; protected HashMap<Object, ReportQueryResult> expectedResults; protected HashMap<Object, ReportQueryResult> cursoredResults; public ReportQueryRetrievePrimaryKeysCursorTest() { super(); setDescription("Test retrieving primary keys with a ReportQuery, using a Cursor"); } protected void queryForExpectedResults() { expectedResults = new HashMap<Object, ReportQueryResult>(); ReportQuery expectedResultsReportQuery = new ReportQuery(Employee.class, new ExpressionBuilder()); ExpressionBuilder builder = expectedResultsReportQuery.getExpressionBuilder(); // required expectedResultsReportQuery.retrievePrimaryKeys(); expectedResultsReportQuery.addAttribute("idResult", builder.get("id")); // number expectedResultsReportQuery.addAttribute("firstNameResult", builder.get("firstName")); // string expectedResultsReportQuery.addAttribute("lastNameResult", builder.get("lastName")); // string expectedResultsReportQuery.addAttribute("addressResult", builder.get("address").get("id")); // number Vector<ReportQueryResult> someResults = (Vector<ReportQueryResult>)getSession().executeQuery(expectedResultsReportQuery); for (ReportQueryResult result : someResults) { expectedResults.put(result.getId(), result); } } protected void buildCursoredResultsReportQuery() { cursoredResults = new HashMap<Object, ReportQueryResult>(); reportQuery = new ReportQuery(Employee.class, new ExpressionBuilder()); ExpressionBuilder builder = reportQuery.getExpressionBuilder(); // required reportQuery.retrievePrimaryKeys(); reportQuery.addAttribute("idResult", builder.get("id")); // number reportQuery.addAttribute("firstNameResult", builder.get("firstName")); // string reportQuery.addAttribute("lastNameResult", builder.get("lastName")); // string reportQuery.addAttribute("addressResult", builder.get("address").get("id")); // number // required reportQuery.useCursoredStream(5, 5); } @Override protected void setup() throws Throwable { if (getSession().isRemoteSession()) { throwWarning("Report queries with objects are not supported on remote session."); } super.setup(); queryForExpectedResults(); buildCursoredResultsReportQuery(); } @Override public void test() { CursoredStream stream = (CursoredStream) getSession().executeQuery(reportQuery); while (!stream.atEnd()) { ReportQueryResult result = (ReportQueryResult) stream.read(); cursoredResults.put(result.getId(), result); stream.releasePrevious(); } stream.close(); } @Override public void verify() { assertNotNull("Expected results should be non-null", expectedResults); assertFalse("Expected results should not be zero", expectedResults.size() == 0); assertNotNull("Cursored results should be non-null", cursoredResults); assertFalse("Cursored results should not be zero", cursoredResults.size() == 0); assertEquals("Cursored results differs from expected results", expectedResults.size(), cursoredResults.size()); for (Object id : expectedResults.keySet()) { if (!cursoredResults.containsKey(id)) { fail("Cursored results does not contain entry for id: " + id); } } } @Override public void reset() { this.cursoredResults = null; this.expectedResults = null; this.reportQuery = null; } }
amrut-prabhu/club-connect
src/test/java/guitests/guihandles/TaskCardHandle.java
package guitests.guihandles; import javafx.scene.Node; import javafx.scene.control.Label; /** * Provides a handle to a task card in the task list panel. */ public class TaskCardHandle extends NodeHandle<Node> { private static final String ID_FIELD_ID = "#id"; private static final String DESCRIPTION_FIELD_ID = "#description"; private static final String DATE_FIELD_ID = "#date"; private static final String TIME_FIELD_ID = "#time"; private static final String ASSIGNOR_FIELD_ID = "#assignor"; private static final String ASSIGNEE_FIELD_ID = "#assignee"; private static final String STATUS_FIELD_ID = "#status"; private final Label idLabel; private final Label descriptionLabel; private final Label dateLabel; private final Label timeLabel; private final Label assignorLabel; private final Label assigneeLabel; private final Label statusLabel; public TaskCardHandle(Node cardNode) { super(cardNode); this.idLabel = getChildNode(ID_FIELD_ID); this.descriptionLabel = getChildNode(DESCRIPTION_FIELD_ID); this.dateLabel = getChildNode(DATE_FIELD_ID); this.timeLabel = getChildNode(TIME_FIELD_ID); this.assignorLabel = getChildNode(ASSIGNOR_FIELD_ID); this.assigneeLabel = getChildNode(ASSIGNEE_FIELD_ID); this.statusLabel = getChildNode(STATUS_FIELD_ID); } public String getId() { return idLabel.getText(); } public String getDescription() { return descriptionLabel.getText(); } public String getDate() { return dateLabel.getText(); } public String getTime() { return timeLabel.getText(); } public String getAssignor() { return assignorLabel.getText(); } public String getAssignee() { return assigneeLabel.getText(); } public String getStatus() { return statusLabel.getText(); } }
felixding/vnstat-ruby
lib/vnstat/result/day.rb
# frozen_string_literal: true module Vnstat class Result ## # A class representing a tracking result for a specific day. # # @!attribute [r] date # @return [Date] The date the result was captured on. class Day < Result include DateDelegation attr_reader :date ## # Initializes the {Day}. # # @param [Date] date The date the result was captured on. # @param [Integer] bytes_received The received bytes. # @param [Integer] bytes_sent The sent bytes. def initialize(date, bytes_received, bytes_sent) @date = date super(bytes_received, bytes_sent) end ## # Initializes a {Day} using the the data contained in the given XML # element. # # @param [Nokogiri::XML::Element] element The XML element. # @return [Day] def self.extract_from_xml_element(element) new( Parser.extract_date_from_xml_element(element), *Parser.extract_transmitted_bytes_from_xml_element(element) ) end ## # @return [Integer, nil] def <=>(other) return nil unless other.respond_to?(:bytes_transmitted) return nil unless other.respond_to?(:date) [date, bytes_transmitted] <=> [other.date, other.bytes_transmitted] end end end end
Kirishikesan/haiku
src/apps/icon-o-matic/generic/gui/popup_control/InputSlider.cpp
<gh_stars>1000+ /* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #include "InputSlider.h" #include <stdio.h> #include <Message.h> #include <MessageFilter.h> #include "NummericalTextView.h" // MouseDownFilter class NumericInputFilter : public BMessageFilter { public: NumericInputFilter(InputSlider* slider); virtual filter_result Filter(BMessage*, BHandler** target); private: InputSlider* fSlider; }; // constructor NumericInputFilter::NumericInputFilter(InputSlider* slider) : BMessageFilter(B_ANY_DELIVERY, B_ANY_SOURCE), fSlider(slider) { } // Filter filter_result NumericInputFilter::Filter(BMessage* msg, BHandler** target) { filter_result result = B_DISPATCH_MESSAGE; switch (msg->what) { case B_KEY_DOWN: case B_KEY_UP: { msg->PrintToStream(); const char *string; if (msg->FindString("bytes", &string) == B_OK) { while (*string != 0) { if (*string < '0' || *string > '9') { if (*string != '-') { result = B_SKIP_MESSAGE; } } string++; } } break; } default: break; } /* if (fWindow) { if (BView* view = dynamic_cast<BView*>(*target)) { BPoint point; if (message->FindPoint("where", &point) == B_OK) { if (!fWindow->Frame().Contains(view->ConvertToScreen(point))) *target = fWindow; } } }*/ return result; } // constructor InputSlider::InputSlider(const char* name, const char* label, BMessage* model, BHandler* target, int32 min, int32 max, int32 value, const char* formatString) : PopupSlider(name, label, model, target, min, max, value, formatString), fTextView(new NummericalTextView(BRect(0, 0 , 20, 20), "input", BRect(5, 5, 15, 15), B_FOLLOW_NONE, B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE)) //fTextViewFilter(dynamic_cast<BMessageFilter*>(new NumericInputFilter(this))) { // prepare fTextView fTextView->SetWordWrap(false); fTextView->SetViewColor(255,255,255,0); fTextView->SetValue(Value()); //fTextView->AddFilter(fTextViewFilter); AddChild(fTextView); } // destructor InputSlider::~InputSlider() { //delete fTextViewFilter; } // layout BRect InputSlider::layout(BRect frame) { PopupSlider::layout(frame); frame = SliderFrame(); frame.right -= 10.0; frame.InsetBy(2, 2); fTextView->MoveTo(frame.LeftTop()); fTextView->ResizeTo(frame.Width(), frame.Height()); BRect textRect(fTextView->Bounds()); textRect.InsetBy(1, 1); fTextView->SetTextRect(textRect); fTextView->SetAlignment(B_ALIGN_CENTER); return Frame(); } // MouseDown void InputSlider::MouseDown(BPoint where) { if (fTextView->Frame().Contains(where)) return; fTextView->MakeFocus(true); if (SliderFrame().Contains(where)) { SetValue(fTextView->IntValue()); PopupSlider::MouseDown(where); } } // SetEnabled void InputSlider::SetEnabled(bool enable) { PopupSlider::SetEnabled(enable); // fTextView->SetEnabled(enable); } // ValueChanged void InputSlider::ValueChanged(int32 newValue) { PopupSlider::ValueChanged(newValue); // change fTextView's value if (LockLooper()) { fTextView->SetValue(Value()); UnlockLooper(); } } // DrawSlider void InputSlider::DrawSlider(BRect frame, bool enabled) { rgb_color background = ui_color(B_PANEL_BACKGROUND_COLOR); rgb_color lightShadow; rgb_color midShadow; rgb_color darkShadow; rgb_color light; if (enabled) { lightShadow = tint_color(background, B_DARKEN_1_TINT); midShadow = tint_color(background, B_DARKEN_2_TINT); darkShadow = tint_color(background, B_DARKEN_4_TINT); light = tint_color(background, B_LIGHTEN_MAX_TINT); } else { lightShadow = background; midShadow = tint_color(background, B_DARKEN_1_TINT); darkShadow = tint_color(background, B_DARKEN_2_TINT); light = tint_color(background, B_LIGHTEN_1_TINT); } // frame around text view BRect r(frame); BeginLineArray(16); AddLine(BPoint(r.left, r.bottom), BPoint(r.left, r.top), lightShadow); AddLine(BPoint(r.left + 1.0, r.top), BPoint(r.right, r.top), lightShadow); AddLine(BPoint(r.right, r.top + 1.0), BPoint(r.right, r.bottom), light); AddLine(BPoint(r.right - 1.0, r.bottom), BPoint(r.left + 1.0, r.bottom), light); r = fTextView->Frame().InsetByCopy(-1, -1); AddLine(BPoint(r.left, r.bottom), BPoint(r.left, r.top), darkShadow); AddLine(BPoint(r.left + 1.0, r.top), BPoint(r.right, r.top), darkShadow); AddLine(BPoint(r.right, r.top + 1.0), BPoint(r.right, r.bottom), background); AddLine(BPoint(r.right - 1.0, r.bottom), BPoint(r.left + 1.0, r.bottom), background); r.left = r.right + 1; r.right = frame.right - 1; AddLine(BPoint(r.left, r.bottom), BPoint(r.left, r.top + 1.0), midShadow); AddLine(BPoint(r.left, r.top), BPoint(r.right, r.top), darkShadow); AddLine(BPoint(r.right, r.top + 1.0), BPoint(r.right, r.bottom), midShadow); AddLine(BPoint(r.right - 1.0, r.bottom), BPoint(r.left + 1.0, r.bottom), midShadow); r.InsetBy(1, 1); AddLine(BPoint(r.left, r.bottom), BPoint(r.left, r.top), light); AddLine(BPoint(r.left + 1.0, r.top), BPoint(r.right, r.top), light); AddLine(BPoint(r.right, r.top + 1.0), BPoint(r.right, r.bottom), lightShadow); AddLine(BPoint(r.right - 1.0, r.bottom), BPoint(r.left + 1.0, r.bottom), lightShadow); EndLineArray(); r.InsetBy(1, 1); SetLowColor(background); FillRect(r, B_SOLID_LOW); }
pickettd/code-dot-org
cookbooks/cdo-nodejs/recipes/default.rb
<gh_stars>0 # # Cookbook Name:: cdo-nodejs # Recipe:: default # node.default['nodejs']['repo'] = "https://deb.nodesource.com/node_#{node['cdo-nodejs']['version']}" include_recipe 'nodejs' # Keep nodejs up to date package 'nodejs' do action :upgrade end nodejs_npm 'npm' do version node['cdo-nodejs']['npm_version'] end nodejs_npm 'grunt-cli'
benetech/MathShareBackend
src/main/java/org/benetech/mathshare/mappers/UserInfoMapper.java
<gh_stars>1-10 package org.benetech.mathshare.mappers; import org.benetech.mathshare.model.dto.UserInfoDTO; import org.benetech.mathshare.model.entity.UserInfo; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public interface UserInfoMapper { UserInfoMapper INSTANCE = Mappers.getMapper(UserInfoMapper.class); UserInfo fromDto(UserInfoDTO userInfo); UserInfoDTO toDto(UserInfo userInfo); }
alf-tool/alf-core
spec/unit/alf-types/attr_name/test_triple_equal.rb
<reponame>alf-tool/alf-core require 'spec_helper' module Alf describe AttrName, "===" do it "should allow normal names" do (AttrName === :city).should be_true end it "should allow underscores" do (AttrName === :my_city).should be_true end it "should allow numbers" do (AttrName === :city2).should be_true end it "should allow question marks and bang" do (AttrName === :big?).should be_true (AttrName === :big!).should be_true end it "should not allow strange attribute names" do (AttrName === "$$$".to_sym).should be_false end end end
jnvshubham7/CPP_Programming
450Question(DayWise)/57.cpp
class Solution { public: int maximumSwap(int num) { string n=to_string(num); //keep in a map the last accurance of each digit unodered_map<int,int> last; for(int i=0;i<n.size();i++) last[n[i]-'0']=i; for(int i=0;i<n.size();i++) { for(int j=9;j>n[i]-'0';j--) { if(last[j]>i) { swap(n[i],n[last[j]]); return stoi(n); } } } return stoi(n); } };
ScalablyTyped/SlinkyTyped
a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/chimeMod/SigninDelegateGroup.scala
<gh_stars>10-100 package typingsSlinky.awsSdk.chimeMod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait SigninDelegateGroup extends StObject { /** * The group name. */ var GroupName: js.UndefOr[NonEmptyString] = js.native } object SigninDelegateGroup { @scala.inline def apply(): SigninDelegateGroup = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[SigninDelegateGroup] } @scala.inline implicit class SigninDelegateGroupMutableBuilder[Self <: SigninDelegateGroup] (val x: Self) extends AnyVal { @scala.inline def setGroupName(value: NonEmptyString): Self = StObject.set(x, "GroupName", value.asInstanceOf[js.Any]) @scala.inline def setGroupNameUndefined: Self = StObject.set(x, "GroupName", js.undefined) } }
pintomau/commercetools-sdk-java-v2
commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/shipping_method/ShippingRate.java
package com.commercetools.api.models.shipping_method; import java.time.*; import java.util.*; import java.util.function.Function; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.commercetools.api.models.common.TypedMoney; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.*; import io.vrap.rmf.base.client.utils.Generated; @Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen") @JsonDeserialize(as = ShippingRateImpl.class) public interface ShippingRate { @NotNull @Valid @JsonProperty("price") public TypedMoney getPrice(); /** * <p>The shipping is free if the order total (the sum of line item prices) exceeds the <code>freeAbove</code> value. * Note: <code>freeAbove</code> applies before any Cart or Product discounts, and can cause discounts to apply in invalid scenarios. * Use a Cart Discount to set the shipping price to 0 to avoid providing free shipping in invalid discount scenarios.</p> */ @Valid @JsonProperty("freeAbove") public TypedMoney getFreeAbove(); /** * <p>Only appears in response to requests for shipping methods by cart or location to mark this shipping rate as one that matches the cart or location.</p> */ @JsonProperty("isMatching") public Boolean getIsMatching(); /** * <p>A list of shipping rate price tiers.</p> */ @NotNull @Valid @JsonProperty("tiers") public List<ShippingRatePriceTier> getTiers(); public void setPrice(final TypedMoney price); public void setFreeAbove(final TypedMoney freeAbove); public void setIsMatching(final Boolean isMatching); @JsonIgnore public void setTiers(final ShippingRatePriceTier... tiers); public void setTiers(final List<ShippingRatePriceTier> tiers); public static ShippingRate of() { return new ShippingRateImpl(); } public static ShippingRate of(final ShippingRate template) { ShippingRateImpl instance = new ShippingRateImpl(); instance.setPrice(template.getPrice()); instance.setFreeAbove(template.getFreeAbove()); instance.setIsMatching(template.getIsMatching()); instance.setTiers(template.getTiers()); return instance; } public static ShippingRateBuilder builder() { return ShippingRateBuilder.of(); } public static ShippingRateBuilder builder(final ShippingRate template) { return ShippingRateBuilder.of(template); } default <T> T withShippingRate(Function<ShippingRate, T> helper) { return helper.apply(this); } }
FallenShard/Crisp
Crisp/Camera/AbstractCamera.hpp
<filename>Crisp/Camera/AbstractCamera.hpp #pragma once #include <array> #include <CrispCore/Math/Headers.hpp> namespace crisp { class AbstractCamera { public: static constexpr uint32_t FrustumPlaneCount = 6; static constexpr uint32_t FrustumPointCount = 8; AbstractCamera(); virtual ~AbstractCamera() = default; virtual void update(float dt) = 0; virtual void rotate(float dx, float dy) = 0; virtual void setRotation(float yaw, float pitch, float roll) = 0; virtual void walk(float dt) = 0; virtual void strafe(float dt) = 0; virtual void lift(float dt) = 0; void setupProjection(float fovY, float aspectRatio, float zNear, float zFar); void setupProjection(float fovY, float aspectRatio); const glm::mat4& getProjectionMatrix() const; void setFovY(float fovY); float getFovY() const; void setApectRatio(float aspectRatio); float getAspectRatio() const; void setNearPlaneDistance(float zNear); float getNearPlaneDistance() const; void setFarPlaneDistance(float zFar); float getFarPlaneDistance() const; void setPosition(const glm::vec3& position); glm::vec3 getPosition() const; virtual void setTarget(const glm::vec3& target) = 0; glm::vec3 getLookDirection() const; glm::vec3 getRightDirection() const; glm::vec3 getUpDirection() const; const glm::mat4& getViewMatrix() const; void calculateFrustumPlanes() const; bool isPointInFrustum(const glm::vec3& point); bool isSphereInFrustum(const glm::vec3& center, float radius); bool isBoxInFrustum(const glm::vec3& min, const glm::vec3& max); std::array<glm::vec4, FrustumPlaneCount> getFrustumPlanes() const; glm::vec4 getFrustumPlane(size_t index) const; std::array<glm::vec3, FrustumPointCount> getFrustumPoints(float zNear, float zFar) const; std::array<glm::vec3, FrustumPointCount> getFrustumPoints() const; glm::vec4 calculateBoundingSphere(float zNear, float zFar) const; protected: void updateProjectionMatrix(); float m_fovY; float m_aspectRatio; float m_zNear; float m_zFar; glm::mat4 m_P; glm::vec3 m_position; glm::vec3 m_look; glm::vec3 m_right; glm::vec3 m_up; glm::mat4 m_V; glm::vec3 m_absPos; glm::vec3 m_absTarget; std::array<glm::vec4, FrustumPlaneCount> m_frustumPlanes; }; }
ArcticReal/eCommerce
plugins/eCommerce/src/main/java/com/skytala/eCommerce/service/skytalaPlugin/PluginsSkytalaPluginsServiceController.java
package com.skytala.eCommerce.service.skytalaPlugin; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.List; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.service.ServiceAuthException; import org.apache.ofbiz.service.ServiceValidationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*; @RestController @RequestMapping("/service/pluginsSkytalaPlugins") public class PluginsSkytalaPluginsServiceController{ @RequestMapping(method = RequestMethod.POST, value = "/simplesoap") public ResponseEntity<Map<String, Object>> simplesoap(HttpSession session, @RequestParam(value="defaultValue") Double defaultValue, @RequestParam(value="message", required=false) String message) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("defaultValue",defaultValue); paramMap.put("message",message); paramMap.put("userLogin", session.getAttribute("userLogin")); Map<String, Object> result = new HashMap<>(); LocalDispatcher dispatcher = (LocalDispatcher) session.getServletContext().getAttribute("dispatcher"); try { result = dispatcher.runSync("simplesoap", paramMap); } catch (ServiceAuthException e) { e.printStackTrace(); return unauthorized(); } catch (ServiceValidationException e) { return serverError(); } catch (GenericServiceException e) { e.printStackTrace(); return badRequest(); } if(result.get("responseMessage").equals("error")) { return badRequest(); } return successful(result); } @RequestMapping(method = RequestMethod.POST, value = "/getallproducts") public ResponseEntity<Map<String, Object>> getallproducts(HttpSession session, @RequestParam(value="ID", required=false) String ID, @RequestParam(value="Name", required=false) String Name) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("ID",ID); paramMap.put("Name",Name); paramMap.put("userLogin", session.getAttribute("userLogin")); Map<String, Object> result = new HashMap<>(); LocalDispatcher dispatcher = (LocalDispatcher) session.getServletContext().getAttribute("dispatcher"); try { result = dispatcher.runSync("getallproducts", paramMap); } catch (ServiceAuthException e) { e.printStackTrace(); return unauthorized(); } catch (ServiceValidationException e) { return serverError(); } catch (GenericServiceException e) { e.printStackTrace(); return badRequest(); } if(result.get("responseMessage").equals("error")) { return badRequest(); } return successful(result); } @RequestMapping(method = RequestMethod.POST, value = "/createOfbizDemoByJavaService") public ResponseEntity<Map<String, Object>> createOfbizDemoByJavaService(HttpSession session) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("userLogin", session.getAttribute("userLogin")); Map<String, Object> result = new HashMap<>(); LocalDispatcher dispatcher = (LocalDispatcher) session.getServletContext().getAttribute("dispatcher"); try { result = dispatcher.runSync("createOfbizDemoByJavaService", paramMap); } catch (ServiceAuthException e) { e.printStackTrace(); return unauthorized(); } catch (ServiceValidationException e) { return serverError(); } catch (GenericServiceException e) { e.printStackTrace(); return badRequest(); } if(result.get("responseMessage").equals("error")) { return badRequest(); } return successful(result); } @RequestMapping(method = RequestMethod.POST, value = "/testservicedie2te") public ResponseEntity<Map<String, Object>> testservicedie2te(HttpSession session, @RequestParam(value="name", required=false) String name, @RequestParam(value="Id", required=false) String Id) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("name",name); paramMap.put("Id",Id); paramMap.put("userLogin", session.getAttribute("userLogin")); Map<String, Object> result = new HashMap<>(); LocalDispatcher dispatcher = (LocalDispatcher) session.getServletContext().getAttribute("dispatcher"); try { result = dispatcher.runSync("testservicedie2te", paramMap); } catch (ServiceAuthException e) { e.printStackTrace(); return unauthorized(); } catch (ServiceValidationException e) { return serverError(); } catch (GenericServiceException e) { e.printStackTrace(); return badRequest(); } if(result.get("responseMessage").equals("error")) { return badRequest(); } return successful(result); } @RequestMapping(method = RequestMethod.POST, value = "/createSkytalaPlugin") public ResponseEntity<Map<String, Object>> createSkytalaPlugin(HttpSession session) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("userLogin", session.getAttribute("userLogin")); Map<String, Object> result = new HashMap<>(); LocalDispatcher dispatcher = (LocalDispatcher) session.getServletContext().getAttribute("dispatcher"); try { result = dispatcher.runSync("createSkytalaPlugin", paramMap); } catch (ServiceAuthException e) { e.printStackTrace(); return unauthorized(); } catch (ServiceValidationException e) { return serverError(); } catch (GenericServiceException e) { e.printStackTrace(); return badRequest(); } if(result.get("responseMessage").equals("error")) { return badRequest(); } return successful(result); } @RequestMapping(method = RequestMethod.POST, value = "/simpletest") public ResponseEntity<Map<String, Object>> simpletest(HttpSession session, @RequestParam(value="eingabe", required=false) String eingabe) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("eingabe",eingabe); paramMap.put("userLogin", session.getAttribute("userLogin")); Map<String, Object> result = new HashMap<>(); LocalDispatcher dispatcher = (LocalDispatcher) session.getServletContext().getAttribute("dispatcher"); try { result = dispatcher.runSync("simpletest", paramMap); } catch (ServiceAuthException e) { e.printStackTrace(); return unauthorized(); } catch (ServiceValidationException e) { return serverError(); } catch (GenericServiceException e) { e.printStackTrace(); return badRequest(); } if(result.get("responseMessage").equals("error")) { return badRequest(); } return successful(result); } }
skynode-integration/skynode-codebox
packages/editor/src/index.js
<filename>packages/editor/src/index.js require("./stylesheets/main.less"); var ace = require("./ace"); var aceModes = ace.require("ace/ext/modelist"); var Tab = require("./tab"); var settings = require("./settings"); var editorCommands = require("./commands"); var Q = codebox.require("q"); var _ = codebox.require("hr.utils"); var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var File = codebox.require("models/file"); var openFile = function(f) { if (f.isDirectory()) return Q.reject(new Error("Could not open a folder")); return codebox.tabs.add(Tab, { model: f }, { type: "editor", title: f.get("name"), uniqueId: "editor://"+f.get("path"), context: { file: f } }); }; var openNewfile = function() { var f = File.buffer("untitled", ""); openFile(f); }; // Default tab is an empty buffer codebox.tabs.on("tabs:opennew", openNewfile); openNewfile(); // Add command to open a file commands.register({ id: "file.open", title: "File: Open", run: function(args, ctx) { return Q() .then(function() { if (args.file) return args.file; if (args.path) return File.get(args.path); return File.buffer("untitled", ""); }) .then(openFile) .then(function(tag) { // Set line if (args.line || args.column) { tag.moveCursor(args.column || 0, args.line || 0); } }); } }); // Save the file commands.register({ id: "editor.save", title: "File: Save", shortcuts: [ "mod+s" ], context: ["editor"], run: function(args, ctx) { return ctx.editor.save(); } }); // Save all files commands.register({ id: "editor.save.all", title: "File: Save All", shortcuts: [ "mod+alt+s" ], run: function(args) { return codebox.tabs.tabs.reduce(function(prev, tab) { if (tab.get("type") != "editor") return prev; return prev.then(function() { return tab.view.save(); }) }, Q()); } }); // Map ace commands commands.register(editorCommands); // Set syntax commands.register(_.map(aceModes.modesByName, function(mode) { return { id: "editor.syntax."+mode.name, title: "Set Syntax: "+mode.caption, context: ["editor"], run: function(args, ctx) { ctx.editor.setMode(mode.name); } } })); // Syntax menu codebox.menubar.createMenu("view", { id: "syntax", caption: "Syntax", position: 10, items: _.map(aceModes.modesByName, function(mode) { return { command: "editor.syntax."+mode.name, caption: mode.caption } }) }); codebox.editor = require("./api");
chandu0101/scalajs-tfjs
src/main/scala/io/brunk/deeplearnjs/math/backends/kernel_registry.scala
/* * Copyright 2017 <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 io.brunk.deeplearnjs.math.backends import io.brunk.deeplearnjs.math.{ DataType, NDArray, Rank } import io.brunk.deeplearnjs.math.backends.types._ import scala.scalajs.js import scala.scalajs.js.annotation._ @js.native trait KernelConfigRegistry extends js.Object { var MatMul: MatMulNode = js.native var Clone: UnaryNode[NDArray[DataType, Rank]] = js.native var Slice1D: Slice1DNode = js.native var Slice2D: Slice2DNode = js.native var Slice3D: Slice3DNode = js.native var Slice4D: Slice4DNode = js.native var Reverse4D: Reverse4DNode = js.native var Concat1D: Concat1DNode = js.native var Concat2D: Concat2DNode = js.native var Concat3D: Concat3DNode = js.native var Concat4D: Concat4DNode = js.native var Neg: UnaryNode[NDArray[DataType, Rank]] = js.native var Add: BinaryNode = js.native var Sub: BinaryNode = js.native var Mul: BinaryNode = js.native var Div: BinaryNode = js.native var Sum: SumNode[DataType] = js.native var ArgMax: ArgMaxNode = js.native var ArgMin: ArgMinNode = js.native var Equal: EqualNode = js.native var NotEqual: EqualNode = js.native var LessEqual: EqualNode = js.native var Greater: EqualNode = js.native var GreaterEqual: EqualNode = js.native var LogicalOr: LogicalOrNode = js.native var TopKValues: TopKValuesNode[DataType, NDArray[DataType, Rank]] = js.native var TopKIndices: TopKIndicesNode = js.native var Min: MinNode[DataType] = js.native var Minimum: MinimumNode[DataType] = js.native var Max: MaxNode[DataType] = js.native var Maximum: MaximumNode[DataType] = js.native var Ceil: UnaryNode[NDArray[DataType, Rank]] = js.native var Floor: UnaryNode[NDArray[DataType, Rank]] = js.native var Pow: PowNode[NDArray[DataType, Rank]] = js.native var Exp: UnaryNode[NDArray[DataType, Rank]] = js.native var Log: UnaryNode[NDArray[DataType, Rank]] = js.native var Sqrt: UnaryNode[NDArray[DataType, Rank]] = js.native var Square: UnaryNode[NDArray[DataType, Rank]] = js.native var Relu: UnaryNode[NDArray[DataType, Rank]] = js.native var LeakyRelu: LeakyReluNode[NDArray[DataType, Rank]] = js.native var PReLU: PReLUNode[NDArray[DataType, Rank]] = js.native var PReLUDer: PReLUNode[NDArray[DataType, Rank]] = js.native var Reshape: ReshapeNode = js.native var Cast: CastNode = js.native var Elu: UnaryNode[NDArray[DataType, Rank]] = js.native var EluDer: UnaryNode[NDArray[DataType, Rank]] = js.native var Selu: UnaryNode[NDArray[DataType, Rank]] = js.native var Abs: UnaryNode[NDArray[DataType, Rank]] = js.native var Sigmoid: UnaryNode[NDArray[DataType, Rank]] = js.native var Step: StepNode[NDArray[DataType, Rank]] = js.native var Sin: UnaryNode[NDArray[DataType, Rank]] = js.native var Cos: UnaryNode[NDArray[DataType, Rank]] = js.native var Tan: UnaryNode[NDArray[DataType, Rank]] = js.native var Asin: UnaryNode[NDArray[DataType, Rank]] = js.native var Acos: UnaryNode[NDArray[DataType, Rank]] = js.native var Atan: UnaryNode[NDArray[DataType, Rank]] = js.native var Sinh: UnaryNode[NDArray[DataType, Rank]] = js.native var Cosh: UnaryNode[NDArray[DataType, Rank]] = js.native var Tanh: UnaryNode[NDArray[DataType, Rank]] = js.native var Clip: ClipNode[NDArray[DataType, Rank]] = js.native var Transpose: TransposeNode[NDArray[DataType, Rank]] = js.native var Pad1D: Pad1DNode = js.native var Pad2D: Pad2DNode = js.native var Tile: TileNode[NDArray[DataType, Rank]] = js.native var Conv2D: Conv2DNode = js.native var Conv2DDerInput: Conv2DDerInputNode = js.native var Conv2DDerFilter: Conv2DDerFilterNode = js.native var Conv2DDerBias: Conv2DDerBiasNode = js.native var DepthwiseConv2D: Conv2DNode = js.native var MaxPool: PoolNode = js.native var MaxPoolBackprop: PoolBackpropNode = js.native var AvgPool: PoolNode = js.native var AvgPoolBackprop: PoolBackpropNode = js.native var MinPool: PoolNode = js.native var ResizeBilinear3D: ResizeBilinear3DNode = js.native var BatchNorm4D: BatchNorm4DNode = js.native var BatchNorm3D: BatchNorm3DNode = js.native var BatchNorm2D: BatchNorm2DNode = js.native var LRN4D: LRN4DNode = js.native var Multinomial: MultinomialNode = js.native var OneHot: OneHotNode = js.native } @js.native @JSGlobalScope object Kernel_registry extends js.Object { def executeKernel[K <: String, R <: js.Any](backend: MathBackend, kernelName: K, config: js.Any): R = js.native }
Cy4Shot/Better-Dungeons-Mod
src/main/java/com/cy4/betterdungeons/client/screen/util/AbilitySelectionWidget.java
<reponame>Cy4Shot/Better-Dungeons-Mod package com.cy4.betterdungeons.client.screen.util; import com.cy4.betterdungeons.BetterDungeons; import com.cy4.betterdungeons.client.helper.Rectangle; import com.cy4.betterdungeons.client.overlay.AbilitiesOverlay; import com.cy4.betterdungeons.common.upgrade.UpgradeNode; import com.cy4.betterdungeons.common.upgrade.UpgradeStyle; import com.cy4.betterdungeons.core.config.DungeonsConfig; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.AbstractGui; import net.minecraft.client.gui.widget.Widget; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.StringTextComponent; public class AbilitySelectionWidget extends Widget { public static final ResourceLocation HUD_RESOURCE = new ResourceLocation(BetterDungeons.MOD_ID, "textures/gui/ability_hud.png"); private static final ResourceLocation ABILITIES_RESOURCE = new ResourceLocation(BetterDungeons.MOD_ID, "textures/gui/upgrade_sprites.png"); protected UpgradeNode<?> abilityNode; public AbilitySelectionWidget(int x, int y, UpgradeNode<?> abilityNode) { super(x, y, 24, 24, new StringTextComponent(abilityNode.getName())); this.abilityNode = abilityNode; } public UpgradeNode<?> getUpgradeNode() { return abilityNode; } public Rectangle getBounds() { Rectangle bounds = new Rectangle(); bounds.x0 = x - 12; bounds.y0 = y - 12; bounds.setWidth(width); bounds.setHeight(height); return bounds; } @Override public boolean isMouseOver(double mouseX, double mouseY) { return getBounds().contains((int) mouseX, (int) mouseY); } @SuppressWarnings("deprecation") @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { Rectangle bounds = getBounds(); Minecraft minecraft = Minecraft.getInstance(); UpgradeStyle abilityStyle = DungeonsConfig.UPGRADES_GUI.getStyles().get(abilityNode.getGroup().getParentName()); int abilityIndex = AbilitiesOverlay.learnedAbilities.indexOf(abilityNode); int cooldown = AbilitiesOverlay.cooldowns.getOrDefault(abilityIndex, 0); if (AbilitiesOverlay.focusedIndex == abilityIndex) { GlStateManager.color4f(0.7f, 0.7f, 0.7f, 0.3f); } else { GlStateManager.color4f(1f, 1f, 1f, 1f); } RenderSystem.enableBlend(); minecraft.getTextureManager().bindTexture(HUD_RESOURCE); blit(matrixStack, bounds.x0 + 1, bounds.y0 + 1, 28, 36, 22, 22); minecraft.getTextureManager().bindTexture(ABILITIES_RESOURCE); blit(matrixStack, bounds.x0 + 4, bounds.y0 + 4, abilityStyle.u, abilityStyle.v, 16, 16); if (cooldown > 0) { GlStateManager.color4f(0.7f, 0.7f, 0.7f, 0.5f); float cooldownPercent = (float) cooldown / DungeonsConfig.UPGRADES.cooldownOf(abilityNode); int cooldownHeight = (int) (16 * cooldownPercent); AbstractGui.fill(matrixStack, bounds.x0 + 4, bounds.y0 + 4 + (16 - cooldownHeight), bounds.x0 + 4 + 16, bounds.y0 + 4 + 16, 0x99_FFFFFF); RenderSystem.enableBlend(); } if (AbilitiesOverlay.focusedIndex == abilityIndex) { minecraft.getTextureManager().bindTexture(HUD_RESOURCE); blit(matrixStack, bounds.x0, bounds.y0, 64 + 25, 13, 24, 24); } else if (bounds.contains(mouseX, mouseY)) { GlStateManager.color4f(1f, 1f, 1f, 1f); minecraft.getTextureManager().bindTexture(HUD_RESOURCE); blit(matrixStack, bounds.x0, bounds.y0, 64 + (cooldown > 0 ? 50 : 0), 13, 24, 24); } } }
sireliah/polish-python
Lib/shlex.py
"""A lexical analyzer klasa dla simple shell-like syntaxes.""" # Module oraz documentation by <NAME>, 21 Dec 1998 # Input stacking oraz error message cleanup added by ESR, March 2000 # push_source() oraz pop_source() made explicit by ESR, January 2001. # Posix compliance, split(), string arguments, oraz # iterator interface by <NAME>, April 2003. zaimportuj os zaimportuj re zaimportuj sys z collections zaimportuj deque z io zaimportuj StringIO __all__ = ["shlex", "split", "quote"] klasa shlex: "A lexical analyzer klasa dla simple shell-like syntaxes." def __init__(self, instream=Nic, infile=Nic, posix=Nieprawda): jeżeli isinstance(instream, str): instream = StringIO(instream) jeżeli instream jest nie Nic: self.instream = instream self.infile = infile inaczej: self.instream = sys.stdin self.infile = Nic self.posix = posix jeżeli posix: self.eof = Nic inaczej: self.eof = '' self.commenters = '#' self.wordchars = ('abcdfeghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') jeżeli self.posix: self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ') self.whitespace = ' \t\r\n' self.whitespace_split = Nieprawda self.quotes = '\'"' self.escape = '\\' self.escapedquotes = '"' self.state = ' ' self.pushback = deque() self.lineno = 1 self.debug = 0 self.token = '' self.filestack = deque() self.source = Nic def push_token(self, tok): "Push a token onto the stack popped by the get_token method" jeżeli self.debug >= 1: print("shlex: pushing token " + repr(tok)) self.pushback.appendleft(tok) def push_source(self, newstream, newfile=Nic): "Push an input source onto the lexer's input source stack." jeżeli isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 jeżeli self.debug: jeżeli newfile jest nie Nic: print('shlex: pushing to file %s' % (self.infile,)) inaczej: print('shlex: pushing to stream %s' % (self.instream,)) def pop_source(self): "Pop the input source stack." self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() jeżeli self.debug: print('shlex: popping to %s, line %d' \ % (self.instream, self.lineno)) self.state = ' ' def get_token(self): "Get a token z the input stream (or z stack jeżeli it's nonempty)" jeżeli self.pushback: tok = self.pushback.popleft() jeżeli self.debug >= 1: print("shlex: popping token " + repr(tok)) zwróć tok # No pushback. Get a token. raw = self.read_token() # Handle inclusions jeżeli self.source jest nie Nic: dopóki raw == self.source: spec = self.sourcehook(self.read_token()) jeżeli spec: (newfile, newstream) = spec self.push_source(newstream, newfile) raw = self.get_token() # Maybe we got EOF instead? dopóki raw == self.eof: jeżeli nie self.filestack: zwróć self.eof inaczej: self.pop_source() raw = self.get_token() # Neither inclusion nor EOF jeżeli self.debug >= 1: jeżeli raw != self.eof: print("shlex: token=" + repr(raw)) inaczej: print("shlex: token=EOF") zwróć raw def read_token(self): quoted = Nieprawda escapedstate = ' ' dopóki Prawda: nextchar = self.instream.read(1) jeżeli nextchar == '\n': self.lineno = self.lineno + 1 jeżeli self.debug >= 3: print("shlex: w state", repr(self.state), \ "I see character:", repr(nextchar)) jeżeli self.state jest Nic: self.token = '' # past end of file przerwij albo_inaczej self.state == ' ': jeżeli nie nextchar: self.state = Nic # end of file przerwij albo_inaczej nextchar w self.whitespace: jeżeli self.debug >= 2: print("shlex: I see whitespace w whitespace state") jeżeli self.token albo (self.posix oraz quoted): przerwij # emit current token inaczej: kontynuuj albo_inaczej nextchar w self.commenters: self.instream.readline() self.lineno = self.lineno + 1 albo_inaczej self.posix oraz nextchar w self.escape: escapedstate = 'a' self.state = nextchar albo_inaczej nextchar w self.wordchars: self.token = nextchar self.state = 'a' albo_inaczej nextchar w self.quotes: jeżeli nie self.posix: self.token = nextchar self.state = nextchar albo_inaczej self.whitespace_split: self.token = nextchar self.state = 'a' inaczej: self.token = nextchar jeżeli self.token albo (self.posix oraz quoted): przerwij # emit current token inaczej: kontynuuj albo_inaczej self.state w self.quotes: quoted = Prawda jeżeli nie nextchar: # end of file jeżeli self.debug >= 2: print("shlex: I see EOF w quotes state") # XXX what error should be podnieśd here? podnieś ValueError("No closing quotation") jeżeli nextchar == self.state: jeżeli nie self.posix: self.token = self.token + nextchar self.state = ' ' przerwij inaczej: self.state = 'a' albo_inaczej self.posix oraz nextchar w self.escape oraz \ self.state w self.escapedquotes: escapedstate = self.state self.state = nextchar inaczej: self.token = self.token + nextchar albo_inaczej self.state w self.escape: jeżeli nie nextchar: # end of file jeżeli self.debug >= 2: print("shlex: I see EOF w escape state") # XXX what error should be podnieśd here? podnieś ValueError("No escaped character") # In posix shells, only the quote itself albo the escape # character may be escaped within quotes. jeżeli escapedstate w self.quotes oraz \ nextchar != self.state oraz nextchar != escapedstate: self.token = self.token + self.state self.token = self.token + nextchar self.state = escapedstate albo_inaczej self.state == 'a': jeżeli nie nextchar: self.state = Nic # end of file przerwij albo_inaczej nextchar w self.whitespace: jeżeli self.debug >= 2: print("shlex: I see whitespace w word state") self.state = ' ' jeżeli self.token albo (self.posix oraz quoted): przerwij # emit current token inaczej: kontynuuj albo_inaczej nextchar w self.commenters: self.instream.readline() self.lineno = self.lineno + 1 jeżeli self.posix: self.state = ' ' jeżeli self.token albo (self.posix oraz quoted): przerwij # emit current token inaczej: kontynuuj albo_inaczej self.posix oraz nextchar w self.quotes: self.state = nextchar albo_inaczej self.posix oraz nextchar w self.escape: escapedstate = 'a' self.state = nextchar albo_inaczej nextchar w self.wordchars albo nextchar w self.quotes \ albo self.whitespace_split: self.token = self.token + nextchar inaczej: self.pushback.appendleft(nextchar) jeżeli self.debug >= 2: print("shlex: I see punctuation w word state") self.state = ' ' jeżeli self.token: przerwij # emit current token inaczej: kontynuuj result = self.token self.token = '' jeżeli self.posix oraz nie quoted oraz result == '': result = Nic jeżeli self.debug > 1: jeżeli result: print("shlex: raw token=" + repr(result)) inaczej: print("shlex: raw token=EOF") zwróć result def sourcehook(self, newfile): "Hook called on a filename to be sourced." jeżeli newfile[0] == '"': newfile = newfile[1:-1] # This implements cpp-like semantics dla relative-path inclusion. jeżeli isinstance(self.infile, str) oraz nie os.path.isabs(newfile): newfile = os.path.join(os.path.dirname(self.infile), newfile) zwróć (newfile, open(newfile, "r")) def error_leader(self, infile=Nic, lineno=Nic): "Emit a C-compiler-like, Emacs-friendly error-message leader." jeżeli infile jest Nic: infile = self.infile jeżeli lineno jest Nic: lineno = self.lineno zwróć "\"%s\", line %d: " % (infile, lineno) def __iter__(self): zwróć self def __next__(self): token = self.get_token() jeżeli token == self.eof: podnieś StopIteration zwróć token def split(s, comments=Nieprawda, posix=Prawda): lex = shlex(s, posix=posix) lex.whitespace_split = Prawda jeżeli nie comments: lex.commenters = '' zwróć list(lex) _find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search def quote(s): """Return a shell-escaped version of the string *s*.""" jeżeli nie s: zwróć "''" jeżeli _find_unsafe(s) jest Nic: zwróć s # use single quotes, oraz put single quotes into double quotes # the string $'b jest then quoted jako '$'"'"'b' zwróć "'" + s.replace("'", "'\"'\"'") + "'" def _print_tokens(lexer): dopóki 1: tt = lexer.get_token() jeżeli nie tt: przerwij print("Token: " + repr(tt)) jeżeli __name__ == '__main__': jeżeli len(sys.argv) == 1: _print_tokens(shlex()) inaczej: fn = sys.argv[1] przy open(fn) jako f: _print_tokens(shlex(f, fn))
rinceyuan/WeFe
fusion/fusion-service/src/main/java/com/welab/wefe/data/fusion/service/dto/entity/TaskOutput.java
/** * Copyright 2021 Tianmian Tech. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.welab.wefe.data.fusion.service.dto.entity; import com.welab.wefe.data.fusion.service.dto.entity.bloomfilter.BloomfilterOutputModel; import com.welab.wefe.data.fusion.service.dto.entity.dataset.DataSetOutputModel; import com.welab.wefe.data.fusion.service.enums.AlgorithmType; import com.welab.wefe.data.fusion.service.enums.DataResourceType; import com.welab.wefe.data.fusion.service.enums.PSIActuatorRole; import com.welab.wefe.data.fusion.service.enums.TaskStatus; import java.util.List; /** * @author hunter.zhao */ public class TaskOutput extends AbstractOutputModel{ private String businessId; String name; TaskStatus status; String error; String partnerId; String partnerName; String dataResourceId; String dataResourceName; DataResourceType dataResourceType; /** * Whether the trace */ public boolean isTrace; /** * Traces the field */ public String traceColumn; /** * Number of rows of data resources */ int rowCount; PSIActuatorRole psiActuatorRole; AlgorithmType algorithm; /** * Number of aligned samples */ public int dataCount; /** * Number of fusion */ public int fusionCount; public long spend; private String description; /** * Data set list */ private List<DataSetOutputModel> dataSetList; /** * bloomFilterList */ private List<BloomfilterOutputModel> bloomFilterList; /** * partners */ private List<PartnerOutputModel> partnerList; public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public TaskStatus getStatus() { return status; } public void setStatus(TaskStatus status) { this.status = status; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getPartnerId() { return partnerId; } public void setPartnerId(String partnerId) { this.partnerId = partnerId; } public String getPartnerName() { return partnerName; } public void setPartnerName(String partnerName) { this.partnerName = partnerName; } public String getDataResourceId() { return dataResourceId; } public void setDataResourceId(String dataResourceId) { this.dataResourceId = dataResourceId; } public String getDataResourceName() { return dataResourceName; } public void setDataResourceName(String dataResourceName) { this.dataResourceName = dataResourceName; } public DataResourceType getDataResourceType() { return dataResourceType; } public void setDataResourceType(DataResourceType dataResourceType) { this.dataResourceType = dataResourceType; } public int getRowCount() { return rowCount; } public void setRowCount(int rowCount) { this.rowCount = rowCount; } public PSIActuatorRole getPsiActuatorRole() { return psiActuatorRole; } public void setPsiActuatorRole(PSIActuatorRole psiActuatorRole) { this.psiActuatorRole = psiActuatorRole; } public AlgorithmType getAlgorithm() { return algorithm; } public void setAlgorithm(AlgorithmType algorithm) { this.algorithm = algorithm; } public int getDataCount() { return dataCount; } public void setDataCount(int dataCount) { this.dataCount = dataCount; } public int getFusionCount() { return fusionCount; } public void setFusionCount(int fusionCount) { this.fusionCount = fusionCount; } public long getSpend() { return spend; } public void setSpend(long spend) { this.spend = spend; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<DataSetOutputModel> getDataSetList() { return dataSetList; } public void setDataSetList(List<DataSetOutputModel> dataSetList) { this.dataSetList = dataSetList; } public List<BloomfilterOutputModel> getBloomFilterList() { return bloomFilterList; } public void setBloomFilterList(List<BloomfilterOutputModel> bloomFilterList) { this.bloomFilterList = bloomFilterList; } public List<PartnerOutputModel> getPartnerList() { return partnerList; } public void setPartnerList(List<PartnerOutputModel> partnerList) { this.partnerList = partnerList; } public boolean isTrace() { return isTrace; } public void setTrace(boolean trace) { isTrace = trace; } public String getTraceColumn() { return traceColumn; } public void setTraceColumn(String traceColumn) { this.traceColumn = traceColumn; } }
kmorales13/redux-and-the-rest
rollup.config.js
<reponame>kmorales13/redux-and-the-rest import babel from '@rollup/plugin-babel'; import replace from '@rollup/plugin-replace'; import { terser } from 'rollup-plugin-terser'; import license from 'rollup-plugin-license'; import path from 'path'; export default { input: 'src/index.js', output: { format: 'cjs', file: process.env.NODE_ENV === 'production' ? 'cjs/redux-and-the-rest.production.min.js' : 'cjs/redux-and-the-rest.development.js', exports: 'named' }, external: [ 'query-string', 'pluralize' ], plugins: [ babel({ exclude: 'node_modules/**', babelHelpers: 'bundled' }), replace({ exclude: 'node_modules/**', ENV: JSON.stringify(process.env.NODE_ENV || 'development') }), (process.env.NODE_ENV === 'production' && terser()), license({ banner: { content: { file: path.join(__dirname, 'LICENSE') } } }) ] };
lhw362950217/sqlflow
go/log/log.go
// Copyright 2020 The SQLFlow Authors. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package log import ( "github.com/google/uuid" "github.com/sirupsen/logrus" ) // Logger wraps logrus.Entry. It is the final or intermediate Logrus // logging entry. It contains all the fields passed with WithField{,s}. type Logger struct { *logrus.Entry } // Fields type, used to pass to `WithFields`. type Fields = logrus.Fields // UUID always used to identify the request. func UUID() string { u, _ := uuid.NewUUID() return u.String() } // WithFields returns log.Entry func WithFields(fields Fields) *Logger { return &Logger{logrus.WithFields(fields)} } // GetDefaultLogger returns loggers without any fields func GetDefaultLogger() *Logger { return &Logger{logrus.WithFields(map[string]interface{}{})} } // Info logs a message at level Info func (l *Logger) Info(args ...interface{}) { l.Log(logrus.InfoLevel, args...) } // Infof logs a message at level Info func (l *Logger) Infof(format string, args ...interface{}) { l.Logf(logrus.InfoLevel, format, args...) } // Error logs a message at level Error func (l *Logger) Error(args ...interface{}) { l.Log(logrus.ErrorLevel, args...) } // Errorf logs a message at level Error func (l *Logger) Errorf(format string, args ...interface{}) { l.Logf(logrus.ErrorLevel, format, args...) } // Fatal logs a message at level Fatal then the process will exit with status set to 1. func (l *Logger) Fatal(args ...interface{}) { l.Log(logrus.FatalLevel, args...) } // Fatalf logs a message at level Fatal then the process will exit with status set to 1. func (l *Logger) Fatalf(format string, args ...interface{}) { l.Logf(logrus.FatalLevel, format, args...) }
GabrielSturtevant/mage
Mage.Sets/src/mage/cards/f/FallowWurm.java
<filename>Mage.Sets/src/mage/cards/f/FallowWurm.java package mage.cards.f; import java.util.UUID; import mage.MageInt; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.costs.common.DiscardCardCost; import mage.abilities.effects.common.SacrificeSourceUnlessPaysEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.common.FilterLandCard; /** * * @author LoneFox */ public final class FallowWurm extends CardImpl { public FallowWurm(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}"); this.subtype.add(SubType.WURM); this.power = new MageInt(4); this.toughness = new MageInt(4); // When Fallow Wurm enters the battlefield, sacrifice it unless you discard a land card. this.addAbility(new EntersBattlefieldTriggeredAbility(new SacrificeSourceUnlessPaysEffect(new DiscardCardCost(new FilterLandCard("a land card"))))); } private FallowWurm(final FallowWurm card) { super(card); } @Override public FallowWurm copy() { return new FallowWurm(this); } }
hilmidemirtas/A_Student_Of_JavaScript
30-Days-Of-JavaScript-Exercise/Day_01/08_day1_exercise_variables_multiple.js
<reponame>hilmidemirtas/A_Student_Of_JavaScript<gh_stars>1-10 /* Exercise 8: Declare variables to store your first name, last name, marital status, country and age in multiple lines */ let firstName = "<NAME>", lastName = "demirtaş", maritalStatus = "single", country = "Turkey", age = "28"; //multiple lines console.log(firstName, lastName, maritalStatus, country, age) //console hilmi demirtaş demirtaş single Turkey 28 //results
pmq20/jruby
spec/ruby/core/range/step_spec.rb
require File.expand_path('../../../spec_helper', __FILE__) describe "Range#step" do before :each do ScratchPad.record [] end it "returns an enumerator when no block is given" do enum = (1..10).step(4) enum.should be_an_instance_of(enumerator_class) enum.to_a.should eql([1, 5, 9]) end it "returns self" do r = 1..2 r.step { }.should equal(r) end it "raises TypeError if step" do obj = mock("mock") lambda { (1..10).step(obj) { } }.should raise_error(TypeError) end it "calls #to_int to coerce step to an Integer" do obj = mock("Range#step") obj.should_receive(:to_int).and_return(1) (1..2).step(obj) { |x| ScratchPad << x } ScratchPad.recorded.should eql([1, 2]) end it "raises a TypeError if step does not respond to #to_int" do obj = mock("Range#step non-integer") lambda { (1..2).step(obj) { } }.should raise_error(TypeError) end it "raises a TypeError if #to_int does not return an Integer" do obj = mock("Range#step non-integer") obj.should_receive(:to_int).and_return("1") lambda { (1..2).step(obj) { } }.should raise_error(TypeError) end it "coerces the argument to integer by invoking to_int" do (obj = mock("2")).should_receive(:to_int).and_return(2) res = [] (1..10).step(obj) {|x| res << x} res.should == [1, 3, 5, 7, 9] end it "raises a TypeError if the first element does not respond to #succ" do obj = mock("Range#step non-comparable") obj.should_receive(:<=>).with(obj).and_return(1) lambda { (obj..obj).step { |x| x } }.should raise_error(TypeError) end it "raises an ArgumentError if step is 0" do lambda { (-1..1).step(0) { |x| x } }.should raise_error(ArgumentError) end it "raises an ArgumentError if step is 0.0" do lambda { (-1..1).step(0.0) { |x| x } }.should raise_error(ArgumentError) end it "raises an ArgumentError if step is negative" do lambda { (-1..1).step(-2) { |x| x } }.should raise_error(ArgumentError) end describe "with inclusive end" do describe "and Integer values" do it "yields Integer values incremented by 1 and less than or equal to end when not passed a step" do (-2..2).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2, -1, 0, 1, 2]) end it "yields Integer values incremented by an Integer step" do (-5..5).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5, -3, -1, 1, 3, 5]) end it "yields Float values incremented by a Float step" do (-2..2).step(1.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -0.5, 1.0]) end end describe "and Float values" do it "yields Float values incremented by 1 and less than or equal to end when not passed a step" do (-2.0..2.0).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -1.0, 0.0, 1.0, 2.0]) end it "yields Float values incremented by an Integer step" do (-5.0..5.0).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5.0, -3.0, -1.0, 1.0, 3.0, 5.0]) end it "yields Float values incremented by a Float step" do (-1.0..1.0).step(0.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-1.0, -0.5, 0.0, 0.5, 1.0]) end ruby_bug "redmine #4576", "1.9.3" do it "returns Float values of 'step * n + begin <= end'" do (1.0..6.4).step(1.8) { |x| ScratchPad << x } (1.0..12.7).step(1.3) { |x| ScratchPad << x } ScratchPad.recorded.should eql([1.0, 2.8, 4.6, 6.4, 1.0, 2.3, 3.6, 4.9, 6.2, 7.5, 8.8, 10.1, 11.4, 12.7]) end end end describe "and Integer, Float values" do it "yields Float values incremented by 1 and less than or equal to end when not passed a step" do (-2..2.0).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -1.0, 0.0, 1.0, 2.0]) end it "yields Float values incremented by an Integer step" do (-5..5.0).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5.0, -3.0, -1.0, 1.0, 3.0, 5.0]) end it "yields Float values incremented by a Float step" do (-1..1.0).step(0.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-1.0, -0.5, 0.0, 0.5, 1.0]) end end describe "and Float, Integer values" do it "yields Float values incremented by 1 and less than or equal to end when not passed a step" do (-2.0..2).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -1.0, 0.0, 1.0, 2.0]) end it "yields Float values incremented by an Integer step" do (-5.0..5).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5.0, -3.0, -1.0, 1.0, 3.0, 5.0]) end it "yields Float values incremented by a Float step" do (-1.0..1).step(0.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-1.0, -0.5, 0.0, 0.5, 1.0]) end end describe "and String values" do it "yields String values incremented by #succ and less than or equal to end when not passed a step" do ("A".."E").step { |x| ScratchPad << x } ScratchPad.recorded.should == ["A", "B", "C", "D", "E"] end it "yields String values incremented by #succ called Integer step times" do ("A".."G").step(2) { |x| ScratchPad << x } ScratchPad.recorded.should == ["A", "C", "E", "G"] end it "raises a TypeError when passed a Float step" do lambda { ("A".."G").step(2.0) { } }.should raise_error(TypeError) end it "calls #succ on begin and each element returned by #succ" do obj = mock("Range#step String start") obj.should_receive(:<=>).exactly(3).times.and_return(-1, -1, -1, 0) obj.should_receive(:succ).exactly(2).times.and_return(obj) (obj..obj).step { |x| ScratchPad << x } ScratchPad.recorded.should == [obj, obj, obj] end end end describe "with exclusive end" do describe "and Integer values" do it "yields Integer values incremented by 1 and less than end when not passed a step" do (-2...2).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2, -1, 0, 1]) end it "yields Integer values incremented by an Integer step" do (-5...5).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5, -3, -1, 1, 3]) end it "yields Float values incremented by a Float step" do (-2...2).step(1.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -0.5, 1.0]) end end describe "and Float values" do it "yields Float values incremented by 1 and less than end when not passed a step" do (-2.0...2.0).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -1.0, 0.0, 1.0]) end it "yields Float values incremented by an Integer step" do (-5.0...5.0).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5.0, -3.0, -1.0, 1.0, 3.0]) end it "yields Float values incremented by a Float step" do (-1.0...1.0).step(0.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-1.0, -0.5, 0.0, 0.5]) end ruby_bug "redmine #4576", "1.9.3" do it "returns Float values of 'step * n + begin < end'" do (1.0...6.4).step(1.8) { |x| ScratchPad << x } (1.0...55.6).step(18.2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([1.0, 2.8, 4.6, 1.0, 19.2, 37.4]) end end end describe "and Integer, Float values" do it "yields Float values incremented by 1 and less than end when not passed a step" do (-2...2.0).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -1.0, 0.0, 1.0]) end it "yields Float values incremented by an Integer step" do (-5...5.0).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5.0, -3.0, -1.0, 1.0, 3.0]) end it "yields an Float and then Float values incremented by a Float step" do (-1...1.0).step(0.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-1.0, -0.5, 0.0, 0.5]) end end describe "and Float, Integer values" do it "yields Float values incremented by 1 and less than end when not passed a step" do (-2.0...2).step { |x| ScratchPad << x } ScratchPad.recorded.should eql([-2.0, -1.0, 0.0, 1.0]) end it "yields Float values incremented by an Integer step" do (-5.0...5).step(2) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-5.0, -3.0, -1.0, 1.0, 3.0]) end it "yields Float values incremented by a Float step" do (-1.0...1).step(0.5) { |x| ScratchPad << x } ScratchPad.recorded.should eql([-1.0, -0.5, 0.0, 0.5]) end end describe "and String values" do it "yields String values incremented by #succ and less than or equal to end when not passed a step" do ("A"..."E").step { |x| ScratchPad << x } ScratchPad.recorded.should == ["A", "B", "C", "D"] end it "yields String values incremented by #succ called Integer step times" do ("A"..."G").step(2) { |x| ScratchPad << x } ScratchPad.recorded.should == ["A", "C", "E"] end it "raises a TypeError when passed a Float step" do lambda { ("A"..."G").step(2.0) { } }.should raise_error(TypeError) end end end end
xqbase/util
util-winrm/src/main/java/com/xqbase/util/winrm/wsman/Delete.java
package com.xqbase.util.winrm.wsman; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Delete") public class Delete {/**/}
3timeslazy/ferret
pkg/drivers/cdp/dom/helpers.go
<reponame>3timeslazy/ferret package dom import ( "bytes" "context" "errors" "time" "github.com/PuerkitoBio/goquery" "github.com/mafredri/cdp" "github.com/mafredri/cdp/protocol/dom" "github.com/mafredri/cdp/protocol/page" "github.com/mafredri/cdp/protocol/runtime" "golang.org/x/net/html" "github.com/MontFerret/ferret/pkg/drivers/cdp/eval" "github.com/MontFerret/ferret/pkg/drivers/cdp/templates" "github.com/MontFerret/ferret/pkg/runtime/values" ) var emptyExpires = time.Time{} // traverseAttrs is a helper function that parses a given interleaved array of node attribute names and values, // and calls a given attribute on each key-value pair func traverseAttrs(attrs []string, predicate func(name, value string) bool) { count := len(attrs) for i := 0; i < count; i++ { if i%2 != 0 { if predicate(attrs[i-1], attrs[i]) == false { break } } } } func setInnerHTML(ctx context.Context, client *cdp.Client, exec *eval.ExecutionContext, id HTMLElementIdentity, innerHTML values.String) error { var objID *runtime.RemoteObjectID if id.ObjectID != "" { objID = &id.ObjectID } else { repl, err := client.DOM.ResolveNode(ctx, dom.NewResolveNodeArgs().SetNodeID(id.NodeID)) if err != nil { return err } if repl.Object.ObjectID == nil { return errors.New("unable to resolve node") } objID = repl.Object.ObjectID } b, err := innerHTML.MarshalJSON() if err != nil { return err } err = exec.EvalWithArguments(ctx, templates.SetInnerHTML(), runtime.CallArgument{ ObjectID: objID, }, runtime.CallArgument{ Value: b, }, ) return err } func getInnerHTML(ctx context.Context, client *cdp.Client, exec *eval.ExecutionContext, id HTMLElementIdentity, nodeType html.NodeType) (values.String, error) { // not a document if nodeType != html.DocumentNode { var objID runtime.RemoteObjectID if id.ObjectID != "" { objID = id.ObjectID } else { repl, err := client.DOM.ResolveNode(ctx, dom.NewResolveNodeArgs().SetNodeID(id.NodeID)) if err != nil { return "", err } if repl.Object.ObjectID == nil { return "", errors.New("unable to resolve node") } objID = *repl.Object.ObjectID } res, err := exec.ReadProperty(ctx, objID, "innerHTML") if err != nil { return "", err } return values.NewString(res.String()), nil } repl, err := exec.EvalWithReturnValue(ctx, "return document.documentElement.innerHTML") if err != nil { return "", err } return values.NewString(repl.String()), nil } func setInnerText(ctx context.Context, client *cdp.Client, exec *eval.ExecutionContext, id HTMLElementIdentity, innerText values.String) error { var objID *runtime.RemoteObjectID if id.ObjectID != "" { objID = &id.ObjectID } else { repl, err := client.DOM.ResolveNode(ctx, dom.NewResolveNodeArgs().SetNodeID(id.NodeID)) if err != nil { return err } if repl.Object.ObjectID == nil { return errors.New("unable to resolve node") } objID = repl.Object.ObjectID } b, err := innerText.MarshalJSON() if err != nil { return err } err = exec.EvalWithArguments(ctx, templates.SetInnerText(), runtime.CallArgument{ ObjectID: objID, }, runtime.CallArgument{ Value: b, }, ) return err } func getInnerText(ctx context.Context, client *cdp.Client, exec *eval.ExecutionContext, id HTMLElementIdentity, nodeType html.NodeType) (values.String, error) { // not a document if nodeType != html.DocumentNode { var objID runtime.RemoteObjectID if id.ObjectID != "" { objID = id.ObjectID } else { repl, err := client.DOM.ResolveNode(ctx, dom.NewResolveNodeArgs().SetNodeID(id.NodeID)) if err != nil { return "", err } if repl.Object.ObjectID == nil { return "", errors.New("unable to resolve node") } objID = *repl.Object.ObjectID } res, err := exec.ReadProperty(ctx, objID, "innerText") if err != nil { return "", err } return values.NewString(res.String()), err } repl, err := exec.EvalWithReturnValue(ctx, "return document.documentElement.innerText") if err != nil { return "", err } return values.NewString(repl.String()), nil } func parseInnerText(innerHTML string) (values.String, error) { buff := bytes.NewBuffer([]byte(innerHTML)) parsed, err := goquery.NewDocumentFromReader(buff) if err != nil { return values.EmptyString, err } return values.NewString(parsed.Text()), nil } func createChildrenArray(nodes []dom.Node) []HTMLElementIdentity { children := make([]HTMLElementIdentity, len(nodes)) for idx, child := range nodes { child := child children[idx] = HTMLElementIdentity{ NodeID: child.NodeID, } } return children } func resolveFrame(ctx context.Context, client *cdp.Client, frameID page.FrameID) (dom.Node, runtime.ExecutionContextID, error) { worldRepl, err := client.Page.CreateIsolatedWorld(ctx, page.NewCreateIsolatedWorldArgs(frameID)) if err != nil { return dom.Node{}, -1, err } evalRes, err := client.Runtime.Evaluate( ctx, runtime.NewEvaluateArgs(eval.PrepareEval("return document")). SetContextID(worldRepl.ExecutionContextID), ) if err != nil { return dom.Node{}, -1, err } if evalRes.ExceptionDetails != nil { exception := *evalRes.ExceptionDetails return dom.Node{}, -1, errors.New(exception.Text) } if evalRes.Result.ObjectID == nil { return dom.Node{}, -1, errors.New("failed to resolve frame document") } req, err := client.DOM.RequestNode(ctx, dom.NewRequestNodeArgs(*evalRes.Result.ObjectID)) if err != nil { return dom.Node{}, -1, err } if req.NodeID == 0 { return dom.Node{}, -1, errors.New("framed document is resolved with empty node id") } desc, err := client.DOM.DescribeNode( ctx, dom. NewDescribeNodeArgs(). SetNodeID(req.NodeID). SetDepth(1), ) if err != nil { return dom.Node{}, -1, err } // Returned node, by some reason, does not contain the NodeID // So, we have to set it manually desc.Node.NodeID = req.NodeID return desc.Node, worldRepl.ExecutionContextID, nil }
xiaoweiruby/Elastos.RT
Sources/Sample/HelloCarDemo/Android/HelloElastosDemo/app/src/main/jni/elastos/include/elastos/utility/Arrays.h
<gh_stars>1-10 //========================================================================= // 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. //========================================================================= #ifndef __ELASTOS_UTILITY_ARRAYS_H__ #define __ELASTOS_UTILITY_ARRAYS_H__ //#include "elastos/utility/AbstractList.h" #include "Elastos.CoreLibrary.Utility.h" #include "elastos/core/Object.h" #include "elastos/core/StringBuilder.h" #include "elastos/core/Math.h" #include "elastos/utility/DualPivotQuicksort.h" #include "elastos/utility/ComparableTimSort.h" #include "elastos/utility/TimSort.h" #include "elastos/utility/logging/Logger.h" using Elastos::Core::IComparator; using Elastos::Core::IComparable; using Elastos::Core::StringBuilder; using Elastos::Core::IArrayOf; using Elastos::IO::ISerializable; //using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Utility { class ECO_PUBLIC Arrays { private: // class ArrayList // : public AbstractList // , public ISerializable // , public IRandomAccess // { // public: // CAR_INTERFACE_DECL() // ArrayList( // /* [in] */ ArrayOf<IInterface *> * storage); // CARAPI Contains( // /* [in] */ IInterface * object, // /* [out] */ Boolean* result); // CARAPI Get( // /* [in] */ Int32 location, // /* [out] */ IInterface ** result); // CARAPI IndexOf( // /* [in] */ IInterface * object, // /* [out] */ Int32* result); // CARAPI LastIndexOf( // /* [in] */ IInterface * object, // /* [out] */ Int32* index); // CARAPI Set( // /* [in] */ Int32 location, // /* [in] */ IInterface * object, // /* [out] */ IInterface ** result); // CARAPI GetSize( // /* [out] */ Int32* size); // CARAPI ToArray( // /* [out] */ ArrayOf<IInterface *> ** outArray); // CARAPI ToArray( // /* [in] */ ArrayOf<IInterface *> * contents, // /* [out] */ ArrayOf<IInterface *> ** outArray); // private: // AutoPtr<ArrayOf<IInterface *> > mA; // }; public: template<typename T> static CARAPI FromList( /* [in] */ IList* inList, /* [out, callee] */ ArrayOf<T*> ** array); template<typename T> static CARAPI AsList( /* [in] */ ArrayOf<T> * array, /* [out] */ IList** outList); template<typename T> static CARAPI AsList( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [out] */ IList** outList); // Notes: there is not implementation for converting ArrayOf<Boolean> to IList. // static CARAPI AsList( /* [in] */ ArrayOf<Byte> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Char32> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Int16> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Int32> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Int64> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Float> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Double> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<String> * array, /* [out] */ IList** outList); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive). * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ static CARAPI BinarySearch( /* [in] */ ArrayOf<String>* array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ const String& value, /* [out] */ Int32* index); static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<String> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ const String& value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. */ static CARAPI BinarySearch( /* [in] */ ArrayOf<String>* array, /* [in] */ const String& value, /* [out] */ Int32* index); static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<String> > & array, /* [in] */ const String& value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive). * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ T value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive). * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T * value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T * value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive), * using {@code comparator} to compare elements. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @param comparator the {@code Comparator} used to compare the elements. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * using {@code comparator} to compare elements. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @param comparator the {@code Comparator} used to compare the elements. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); /** * Fills the specified array with the specified element. * * @param array * the {@code byte} array to fill. * @param value * the {@code byte} element. */ template<typename T> static CARAPI Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ T value); template<typename T> static CARAPI Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value); /** * Fills the specified range in the array with the specified element. * * @param array * the {@code byte} array to fill. * @param start * the first index to fill. * @param end * the last + 1 index to fill. * @param value * the {@code byte} element. * @throws IllegalArgumentException * if {@code start > end}. * @throws ArrayIndexOutOfBoundsException * if {@code start < 0} or {@code end > array.length}. */ template<typename T> static CARAPI Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value); template<typename T> static CARAPI Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value); /** * Returns a hash code based on the contents of the given array. For any two * {@code boolean} arrays {@code a} and {@code b}, if * {@code Arrays.equals(a, b)} returns {@code true}, it means * that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}. * <p> * The value returned by this method is the same value as the * {@link List#hashCode()} method which is invoked on a {@link List} * containing a sequence of {@link Boolean} instances representing the * elements of array in the same order. If the array is {@code null}, the return * value is 0. * * @param array * the array whose hash code to compute. * @return the hash code for {@code array}. */ template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<T>* array); template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T> > & array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Boolean>* array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Int64>* array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Float>* array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Double>* array); template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T *> > & array); template<typename T> static CARAPI_(Int32) DeepGetHashCode( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI_(Int32) DeepGetHashCode( /* [in] */ T * element); template<typename T> static CARAPI_(Int32) DeepGetHashCode( /* [in] */ const AutoPtr<T> & element); /** * Compares the two arrays. * * @param array1 * the first {@code byte} array. * @param array2 * the second {@code byte} array. * @return {@code true} if both arrays are {@code null} or if the arrays have the * same length and the elements at each index in the two arrays are * equal, {@code false} otherwise. */ template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<T>* array1, /* [in] */ ArrayOf<T>* array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2); static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<Float>* array1, /* [in] */ ArrayOf<Float>* array2); static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<Double>* array1, /* [in] */ ArrayOf<Double>* array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ ArrayOf<T *> * array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ ArrayOf<T *> * array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ ArrayOf<T> * array1, /* [in] */ ArrayOf<T> * array2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ T * e1, /* [in] */ T * e2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ T * e2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ T * e1, /* [in] */ const AutoPtr<T> & e2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ const AutoPtr<T> & e2); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T>* array); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ IComparator* comparator); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ IComparator* comparator); template<typename T> static CARAPI_(String) ToString( /* [in] */ ArrayOf<T> * array); template<typename T> static CARAPI_(String) ToString( /* [in] */ const AutoPtr<ArrayOf<T> > & array); static CARAPI_(String) ToString( /* [in] */ ArrayOf<Char32> * array); template<typename T> static CARAPI_(String) DeepToString( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI_(String) DeepToString( /* [in] */ const AutoPtr<ArrayOf<T *> > & array); template<typename T> static CARAPI CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result); template<typename T> static CARAPI CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result); template<typename T> static CARAPI CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result); template<typename T> static CARAPI CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result); template<typename T, typename U> static CARAPI CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result); template<typename T, typename U> static CARAPI CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result); template<typename T, typename U> static CARAPI CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result); template<typename T, typename U> static CARAPI CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result); public: static CARAPI CheckStartAndEnd( /* [in] */ Int32 len, /* [in] */ Int32 start, /* [in] */ Int32 end); static CARAPI CheckOffsetAndCount( /* [in] */ Int32 arrayLength, /* [in] */ Int32 offset, /* [in] */ Int32 count); private: static CARAPI_(AutoPtr<IList>) CreateArrayList( /* [in] */ Int32 length); static CARAPI CheckBinarySearchBounds( /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ Int32 length); template<typename T> ECO_LOCAL static CARAPI DeepToString( /* [in] */ T * obj, /* [in] */ ArrayOf<T*> * origArrays, /* [in] */ StringBuilder& sb); template<typename T> ECO_LOCAL static CARAPI_(Boolean) DeepToStringContains( /* [in] */ ArrayOf<T *> * origArray, /* [in] */ T * obj); template<typename T> ECO_LOCAL static CARAPI DeepToString( /* [in] */ T * obj, /* [in] */ IArrayOf * origArrays, /* [in] */ StringBuilder& sb); template<typename T> ECO_LOCAL static CARAPI_(Boolean) DeepToStringContains( /* [in] */ IArrayOf * origArray, /* [in] */ T * obj); ECO_LOCAL static CARAPI DeepToString( /* [in] */ IInterface * obj, /* [in] */ IArrayOf * origArray, /* [in] */ StringBuilder& sb); ECO_LOCAL static CARAPI_(Boolean) DeepToStringContains( /* [in] */ IArrayOf * origArray, /* [in] */ IInterface * obj); private: ECO_LOCAL Arrays(); ECO_LOCAL Arrays(const Arrays&); }; //========================================================================= // template methods implementation //========================================================================= template<typename T> ECode Arrays::FromList( /* [in] */ IList* list, /* [out, callee] */ ArrayOf<T*> ** array) { VALIDATE_NOT_NULL(array) *array = NULL; VALIDATE_NOT_NULL(list) Int32 size; list->GetSize(&size); AutoPtr<ArrayOf<T*> > temp = ArrayOf<T*>::Alloc(size); if (size > 0) { AutoPtr<IIterator> it; list->GetIterator((IIterator**)&it); Boolean hasNext; Int32 i = 0; while (it->HasNext(&hasNext), hasNext) { AutoPtr<IInterface> obj; it->GetNext((IInterface**)&obj); temp->Set(i++, T::Probe(obj)); } } *array = temp; REFCOUNT_ADD(*array) return NOERROR; } template<typename T> ECode Arrays::AsList( /* [in] */ ArrayOf<T> * array, /* [out] */ IList** outList) { VALIDATE_NOT_NULL(outList) *outList = NULL; if (array) { AutoPtr<IList> l = CreateArrayList(array->GetLength()); for (Int32 i = 0; i < array->GetLength(); ++i) { l->Add(i, TO_IINTERFACE((*array)[i])); } *outList = l; REFCOUNT_ADD(*outList) } return NOERROR; } template<typename T> ECode Arrays::AsList( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [out] */ IList** outList) { return AsList(array.Get(), outList); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) ECode ec = CheckBinarySearchBounds(startIndex, endIndex, array->GetLength()); if (FAILED(ec)) { printf("Arrays", "BinarySearch: error %08x, startIndex: %d, endIndex: %d, array length: %d", ec, startIndex, endIndex, array->GetLength()); return ec; } Int32 lo = startIndex; Int32 hi = endIndex - 1; Int32 mid; T midVal; while (lo <= hi) { mid = (UInt32(lo + hi)) >> 1; midVal = (*array)[mid]; if (midVal < value) { lo = mid + 1; } else if (midVal > value) { hi = mid - 1; } else { *index = mid; // value found return NOERROR; } } *index = ~lo; // value not present return NOERROR; } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ T value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array, 0, array->GetLength(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index) { return BinarySearch(array.Get(), startIndex, endIndex, value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value, /* [out] */ Int32* index) { return BinarySearch(array.Get(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) ECode ec = CheckBinarySearchBounds(startIndex, endIndex, array->GetLength()); if (FAILED(ec)) { printf("Arrays", "BinarySearch: error %08x, startIndex: %d, endIndex: %d, array length: %d", ec, startIndex, endIndex, array->GetLength()); return ec; } Int32 lo = startIndex; Int32 hi = endIndex - 1; Int32 mid, midValCmp; IComparable* comp; while (lo <= hi) { mid = (UInt32(lo + hi)) >> 1; comp = IComparable::Probe((*array)[mid]); if (comp == NULL) { printf("Arrays", "BinarySearch: object at %d does not implement IComparable.", mid); } assert(comp != NULL); comp->CompareTo(TO_IINTERFACE(value), &midValCmp); if (midValCmp < 0) { lo = mid + 1; } else if (midValCmp > 0) { hi = mid - 1; } else { *index = mid; // value found return NOERROR; } } *index = ~lo; // value not present return NOERROR; } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index) { return BinarySearch(array.Get(), startIndex, endIndex, value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T * value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array, 0, array->GetLength(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T * value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array.Get(), 0, array->GetLength(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) if (comparator == NULL) { return BinarySearch(array, startIndex, endIndex, value, index); } FAIL_RETURN(CheckBinarySearchBounds(startIndex, endIndex, array->GetLength())); Int32 lo = startIndex; Int32 hi = endIndex - 1; Int32 mid, midValCmp; while (lo <= hi) { mid = (UInt32(lo + hi)) >> 1; comparator->Compare(TO_IINTERFACE((*array)[mid]), value, &midValCmp); if (midValCmp < 0) { lo = mid + 1; } else if (midValCmp > 0) { hi = mid - 1; } else { *index = mid; // value found return NOERROR; } } *index = ~lo; // value not present return NOERROR; } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { return BinarySearch(array.Get(), startIndex, endIndex, value, comparator, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array, 0, array->GetLength(), value, comparator, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array.Get(), 0, array->GetLength(), value, comparator, index); } template<typename T> ECode Arrays::Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value) { assert(array != NULL); VALIDATE_NOT_NULL(array); FAIL_RETURN(CheckStartAndEnd(array->GetLength(), start, end)); for (Int32 i = start; i < end; i++) { array->Set(i, value); } return NOERROR; } template<typename T> ECode Arrays::Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ T value) { assert(array != NULL); VALIDATE_NOT_NULL(array); for (Int32 i = 0; i < array->GetLength(); i++) { array->Set(i, value); } return NOERROR; } template<typename T> ECode Arrays::Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value) { return Fill(array.Get(), start, end, value); } template<typename T> ECode Arrays::Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value) { return Fill(array.Get(), value); } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ ArrayOf<T>* array) { if (array == NULL) { return 0; } Int32 hashCode = 1; for (Int32 i = 0; i < array->GetLength(); i++) { hashCode = 31 * hashCode + (Int32)(*array)[i]; } return hashCode; } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T> > & array) { return GetHashCode(array.Get()); } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ ArrayOf<T *> * array) { if (array == NULL) { return 0; } Int32 hashCode = 1; T* element; for (Int32 i = 0; i < array->GetLength(); i++) { element = (*array)[i]; hashCode = 31 * hashCode + Object::GetHashCode(element); } return hashCode; } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T *> > & array) { return GetHashCode(array.Get()); } template<typename T> Int32 Arrays::DeepGetHashCode( /* [in] */ ArrayOf<T *> * array) { if (array == NULL) { return 0; } Int32 hashCode = 1, elementHashCode; for (Int32 i = 0; i < array->GetLength(); i++) { elementHashCode = DeepGetHashCode((*array)[i]); hashCode = 31 * hashCode + elementHashCode; } return hashCode; } template<typename T> Int32 Arrays::DeepGetHashCode( /* [in] */ T* element) { if (element == NULL) { return 0; } if (IArrayOf::Probe(element) == NULL) { return Object::GetHashCode(element); } /* * element is an array */ Int32 length; AutoPtr<IArrayOf> array = IArrayOf::Probe(element); array->GetLength(&length); Int32 hashCode = 1, elementHashCode; for (Int32 i = 0; i < length; ++i) { AutoPtr<IInterface> object; array->Get(i, (IInterface**)&object); elementHashCode = DeepGetHashCode(object.Get()); hashCode = 31 * hashCode + elementHashCode; } return hashCode; } template<typename T> Int32 Arrays::DeepGetHashCode( /* [in] */ const AutoPtr<T> & element) { return DeepGetHashCode(element.Get()); } template<typename T> Boolean Arrays::Equals( /* [in] */ ArrayOf<T>* array1, /* [in] */ ArrayOf<T>* array2) { if (array1 == array2) { return TRUE; } if (array1 == NULL || array2 == NULL || array1->GetLength() != array2->GetLength()) { return FALSE; } for (Int32 i = 0; i < array1->GetLength(); i++) { if ((*array1)[i] != (*array2)[i]) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::Equals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2) { return Equals(array1.Get(), array2.Get()); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ ArrayOf<T> * array1, /* [in] */ ArrayOf<T> * array2) { if (array1 == array2) { return TRUE; } if (array1 == NULL || array2 == NULL || array1->GetLength() != array2->GetLength()) { return FALSE; } for (Int32 i = 0; i < array1->GetLength(); i++) { if (!DeepEquals(TO_IINTERFACE((*array1)[i]), TO_IINTERFACE((*array2)[i]))) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2) { return DeepEquals(array1.Get(), array2.Get()); } template<typename T> Boolean Arrays::Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ ArrayOf<T *> * array2) { if (array1 == array2) { return TRUE; } if (array1 == NULL || array2 == NULL || array1->GetLength() != array2->GetLength()) { return FALSE; } T *e1, *e2; for (Int32 i = 0; i < array1->GetLength(); i++) { e1 = (*array1)[i]; e2 = (*array2)[i]; if (!(e1 == NULL ? e2 == NULL : Object::Equals(e1, e2))) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ ArrayOf<T *> * array2) { return Equals(array1.Get(), array2); } template<typename T> Boolean Arrays::Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2) { return Equals(array1, array2.Get()); } template<typename T> Boolean Arrays::Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2) { return Equals(array1.Get(), array2.Get()); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ T* e1, /* [in] */ T* e2) { if (e1 == NULL && e2 == NULL) { return TRUE; } if (e1 == NULL || e2 == NULL) { return FALSE; } if (e1->Probe(EIID_IInterface) == e2->Probe(EIID_IInterface)) { return TRUE; } if (IArrayOf::Probe(e1) == NULL || IArrayOf::Probe(e2) == NULL) { return Object::Equals(e1, e2); } /* * compare as arrays */ AutoPtr<IArrayOf> a1 = IArrayOf::Probe(e1); AutoPtr<IArrayOf> a2 = IArrayOf::Probe(e2); Int32 len1, len2; a1->GetLength(&len1); a2->GetLength(&len2); if (len1 != len2) { return FALSE; } for (Int32 i = 0; i < len1; ++i) { AutoPtr<IInterface> o1, o2; a1->Get(i, (IInterface**)&o1); a2->Get(i, (IInterface**)&o2); if (DeepEquals(o1, o2) == FALSE) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ T* e2) { return Arrays::DeepEquals(e1.Get(), e2); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ T* e1, /* [in] */ const AutoPtr<T> & e2) { return Arrays::DeepEquals(e1, e2.Get()); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ const AutoPtr<T> & e2) { return Arrays::DeepEquals(e1.Get(), e2.Get()); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T> * array) { return DualPivotQuicksort::Sort(array); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array) { return DualPivotQuicksort::Sort(array.Get()); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T> * array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return DualPivotQuicksort::Sort(array, start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return DualPivotQuicksort::Sort(array.Get(), start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array) { return ComparableTimSort<T>::Sort(array); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array) { return ComparableTimSort<T>::Sort(array.Get()); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return ComparableTimSort<T>::Sort(array, start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return ComparableTimSort<T>::Sort(array.Get(), start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array, start, end, comparator); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array.Get(), start, end, comparator); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array, comparator); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array.Get(), comparator); } template<typename T> String Arrays::ToString( /* [in] */ ArrayOf<T>* array) { if (array == NULL) { return String("NULL"); } if (array->GetLength() == 0) { return String("[]"); } StringBuilder sb(array->GetLength() * 7); sb.AppendChar('['); sb.Append((*array)[0]); for (Int32 i = 1; i < array->GetLength(); i++) { sb.Append(", "); sb.Append((*array)[i]); } sb.AppendChar(']'); return sb.ToString(); } template<typename T> String Arrays::ToString( /* [in] */ const AutoPtr<ArrayOf<T> > & array) { return ToString(array.Get()); } template<typename T> Boolean Arrays::DeepToStringContains( /* [in] */ IArrayOf * origArray, /* [in] */ T * obj) { if (origArray == NULL) { return FALSE; } IInterface * object = TO_IINTERFACE(obj); Int32 length; origArray->GetLength(&length); for (Int32 i = 0; i < length; ++i) { AutoPtr<IInterface> element; origArray->Get(i, (IInterface**)&element); if (element.Get() == object) { return TRUE; } } return FALSE; } template<typename T> ECode Arrays::DeepToString( /* [in] */ T * obj, /* [in] */ IArrayOf * origArray, /* [in] */ StringBuilder& sb) { IArrayOf* array = IArrayOf::Probe(obj); if (array == NULL) { String info = Object::ToString(obj); sb.Append(info); return NOERROR; } if (DeepToStringContains(origArray, obj)) { sb.Append("[...]"); } else { sb.AppendChar('['); Int32 length; array->GetLength(&length); for (Int32 i = 0; i < length; ++i) { if (i != 0) sb += ", "; AutoPtr<IInterface> element; array->Get(i, (IInterface**)&element); DeepToString(element.Get(), origArray, sb); } sb.AppendChar(']'); } return NOERROR; } template<typename T> Boolean Arrays::DeepToStringContains( /* [in] */ ArrayOf<T *> * origArray, /* [in] */ T* array) { if (origArray == NULL || origArray->GetLength() == 0) { return FALSE; } for (Int32 i = 0; i < origArray->GetLength(); ++i) { if (TO_IINTERFACE((*origArray)[i]) == array) { return TRUE; } } return FALSE; } template<typename T> ECode Arrays::DeepToString( /* [in] */ T * obj, /* [in] */ ArrayOf<T*> * origArray, /* [in] */ StringBuilder& sb) { IArrayOf* array = IArrayOf::Probe(obj); if (array == NULL) { String info = Object::ToString(obj); sb.Append(info); return NOERROR; } if (DeepToStringContains(origArray, obj)) { sb.Append("[...]"); } else { sb.AppendChar('['); Int32 length; array->GetLength(&length); for (Int32 i = 0; i < length; ++i) { if (i != 0) sb += ", "; AutoPtr<IInterface> element; array->Get(i, (IInterface**)&element); DeepToString(element.Get(), origArray, sb); } sb.AppendChar(']'); } return NOERROR; } template<typename T> String Arrays::DeepToString( /* [in] */ ArrayOf<T *> * array) { // Special case null to prevent NPE if (array == NULL) { return String("NULL"); } // delegate this to the recursive method StringBuilder sb(array->GetLength() * 9); sb.AppendChar('['); for (Int32 i = 0; i < array->GetLength(); ++i) { if (i != 0) sb += ", "; DeepToString((*array)[i], array, sb); } sb.AppendChar(']'); return sb.ToString(); } template<typename T> String Arrays::DeepToString( /* [in] */ const AutoPtr<ArrayOf<T *> > & array) { return DeepToString(array.Get()); } template<typename T> ECode Arrays::CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result) { VALIDATE_NOT_NULL(result) *result = NULL; assert(original); VALIDATE_NOT_NULL(original) if (start > end) { printf("Arrays", "CopyOfRange: error, E_ILLEGAL_ARGUMENT_EXCEPTION, start %d, end %d", start, end); return E_ILLEGAL_ARGUMENT_EXCEPTION; } Int32 originalLength = original->GetLength(); if (start < 0 || start > originalLength) { printf("Arrays", "CopyOfRange: error, E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, start %d, originalLength %d", start, originalLength); return E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION; } Int32 resultLength = end - start; Int32 copyLength = Elastos::Core::Math::Min(resultLength, originalLength - start); AutoPtr<ArrayOf<T> > array = ArrayOf<T>::Alloc(resultLength); array->Copy(original, start, copyLength); *result = array; REFCOUNT_ADD(*result) return NOERROR; } template<typename T> ECode Arrays::CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result) { if (newLength < 0) { printf("Arrays", "CopyOf: error, E_NAGATIVE_ARRAY_SIZE_EXCEPTION, newLength %d", newLength); return E_NAGATIVE_ARRAY_SIZE_EXCEPTION; } return CopyOfRange(original, 0, newLength, result); } template<typename T> ECode Arrays::CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result) { return CopyOfRange(original.Get(), start, end, result); } template<typename T> ECode Arrays::CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result) { return CopyOf(original.Get(), newLength, result); } template<typename T, typename U> ECode Arrays::CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result) { VALIDATE_NOT_NULL(result) *result = NULL; assert(original); VALIDATE_NOT_NULL(original) if (start > end) { printf("Arrays", "CopyOfRange: error, E_ILLEGAL_ARGUMENT_EXCEPTION, start %d, end %d", start, end); return E_ILLEGAL_ARGUMENT_EXCEPTION; } Int32 originalLength = original->GetLength(); if (start < 0 || start > originalLength) { printf("Arrays", "CopyOfRange: error, E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, start %d, originalLength %d", start, originalLength); return E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION; } Int32 resultLength = end - start; Int32 copyLength = Elastos::Core::Math::Min(resultLength, originalLength - start); AutoPtr<ArrayOf<U> > array = ArrayOf<U>::Alloc(resultLength); for (Int32 i = 0; i < original->GetLength(); ++i) { array->Set(i, (U)(*original)[i]); // TODO: only work with primitives } *result = result; REFCOUNT_ADD(*result) return NOERROR; } template<typename T, typename U> ECode Arrays::CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result) { if (newLength < 0) { printf("Arrays", "CopyOf: error, E_NAGATIVE_ARRAY_SIZE_EXCEPTION, newLength %d", newLength); return E_NAGATIVE_ARRAY_SIZE_EXCEPTION; } return CopyOfRange(original, 0, newLength, result); } template<typename T, typename U> ECode Arrays::CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result) { return CopyOfRange(original.Get(), start, end, result); } template<typename T, typename U> ECode Arrays::CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result) { return CopyOf(original, newLength, result); } } // namespace Utility } // namespace Elastos #endif // __ELASTOS_UTILITY_ARRAYS_H__
antonmedv/year
packages/2002/06/26/index.js
<gh_stars>1-10 module.exports = new Date(2002, 5, 26)
stanislavus/showcases
grpc/packages/server/index.js
<reponame>stanislavus/showcases import { CONTRACTS, Server } from '@grpc-example/contracts'; import UserModel from './UserModel.js'; const server = new Server({ [CONTRACTS.HELLO]: { sayHello: (call, callback) => callback(null, {message: `Hello, ${call.request.name || 'user'}`}), }, [CONTRACTS.USER]: UserModel, }); server.bind('30043'); server.start();
kighie/so.ontolog
0.0.1/ontolog-utils/src/main/java/so/ontolog/data/binding/tools/BeanPrinter.java
/* * Copyright (c) 2012 <NAME> <EMAIL> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package so.ontolog.data.binding.tools; import java.lang.reflect.Type; import java.util.Collection; import java.util.Map; import so.ontolog.data.binding.metadata.BeanMetadata; import so.ontolog.data.binding.metadata.BeanProperty; import so.ontolog.data.binding.metadata.factory.BeanMetadataFactory; import so.ontolog.data.type.TypeKind; import so.ontolog.data.type.TypeSpec; import so.ontolog.data.type.TypeUtils; /** * <pre></pre> * @author <NAME> * */ public class BeanPrinter { private BeanMetadataFactory factory; public BeanPrinter(BeanMetadataFactory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public <T> String print(T bean) { StringBuilder builder = new StringBuilder(); print(bean, (BeanMetadata<T>)factory.create(bean.getClass()), builder, ""); return builder.toString(); } public <T> String print(T bean, BeanMetadata<T> metadata) { StringBuilder builder = new StringBuilder(); print(bean, metadata, builder, ""); return builder.toString(); } @SuppressWarnings("unchecked") public <T> void printProperty(T bean, BeanProperty<?> property, StringBuilder builder, String indent) { if( TypeUtils.isSimpleValueType(bean.getClass()) ){ builder.append(bean); } else if(bean instanceof Collection){ printCollection((Collection<?>)bean, property.getGenericParamType(0), builder, indent); } else if(bean instanceof Map){ printMap((Map<?,?>)bean, property.getGenericParamType(0),property.getGenericParamType(1),builder, indent); } else if(bean.getClass().isArray()){ printArray((Object[])bean, bean.getClass().getComponentType(), builder, indent); } else { print(bean, (BeanMetadata<T>)factory.create(bean.getClass()), builder, indent); } } @SuppressWarnings("unchecked") public <T> void printProperty(T bean, StringBuilder builder, String indent) { if( TypeUtils.isSimpleValueType(bean.getClass()) ){ builder.append(bean); } else if(bean instanceof Collection){ printCollection((Collection<?>)bean,null, builder, indent); } else if(bean instanceof Map){ printMap((Map<?,?>)bean, null,null,builder, indent); } else if(bean.getClass().isArray()){ printArray((Object[])bean, bean.getClass().getComponentType(), builder, indent); } else { print(bean, (BeanMetadata<T>)factory.create(bean.getClass()), builder, indent); } } public void printMap(Map<?,?> map, Type keyParamType, Type valueParamType, StringBuilder builder, String indent) { builder.append(" ").append(map.size()).append(" {"); if (valueParamType == null || !TypeUtils.isSimpleValueType(valueParamType)) { for (Map.Entry<?, ?> entry : map.entrySet()) { builder.append("\t").append(entry.getKey()).append("="); Object value = entry.getValue(); if(value != null){ printProperty(value, builder, indent+"\t"); } else { builder.append("null"); } builder.append("\n").append(indent); } } else { for (Map.Entry<?, ?> entry : map.entrySet()) { builder.append("\t").append(entry.getKey()).append("="); builder.append(entry.getValue()); builder.append("\n").append(indent); } } builder.append("\t}"); } public void printCollection(Collection<?> collection, Type genericParamType, StringBuilder builder, String indent) { builder.append(" ").append(collection.size()).append(" ["); Class<?>elementClass = null; if((genericParamType != null) && genericParamType instanceof Class){ elementClass = (Class<?>)genericParamType; } if (elementClass == null || !TypeUtils.isSimpleValueType(elementClass)) { for (Object value : collection) { if(value != null){ printProperty(value, builder, indent+"\t"); } else { builder.append("null"); } builder.append("\n").append(indent).append("\t"); } builder.append("]"); } else { boolean first = true; for (Object value : collection) { if(first){ first = false; } else { builder.append(","); } if (value == null) { builder.append("null"); } else if (value instanceof CharSequence) { builder.append("\"").append(value).append("\""); } else { builder.append(value); } } builder.append("]"); } } public void printArray(Object arrayObj, Class<?> compType, StringBuilder builder, String indent) { if (arrayObj != null) { Iterable<?> array = TypeUtils.toArrayIterable(arrayObj, compType); builder.append(" ").append(TypeUtils.getArrayLength(arrayObj)).append(" ["); if (TypeUtils.isSimpleValueType(compType)) { // builder.append("\n\t").append(indent); boolean first = true; for (Object value : array) { if(first){ first = false; } else { builder.append(","); } if (value == null) { builder.append("null"); } else if (CharSequence.class.isAssignableFrom(compType)) { builder.append("\"").append(value).append("\""); } else { builder.append(value); } } builder.append("]"); } else { BeanMetadata<?> childMeta = factory.create(compType); for (Object child : array) { print(child, childMeta, builder, indent + "\t"); } builder.append("\n").append(indent).append("\t]"); } } } @SuppressWarnings({ "rawtypes"}) public void print(Object bean, BeanMetadata<?> metadata, StringBuilder builder, String indent) { builder.append("\n").append(indent).append(metadata.type()).append("{"); for (BeanProperty<?> property : metadata) { try { builder.append("\n").append(indent); builder.append(" ").append(property.name()); builder.append(": "); TypeSpec fieldType = property.typeSpec(); if (fieldType.isSimpleValueType()) { Object val = property.get(bean); if (val == null) { builder.append("null"); } else if (fieldType.isText()) { builder.append("\"").append(val).append("\""); } else { builder.append(val); } } else if (fieldType.getTypeKind() == TypeKind.Collection) { Collection collection = (Collection)property.get(bean); if (collection != null) { printCollection(collection, property.getGenericParamType(0), builder, indent+"\t"); } } else if (fieldType.getTypeKind() == TypeKind.Array) { printArray(property.get(bean), fieldType.getComponentType().getBaseType(), builder, indent); } else if (fieldType.getTypeKind() == TypeKind.Map) { Map map = (Map)property.get(bean); if (map != null) { printMap(map, property.getGenericParamType(0),property.getGenericParamType(1),builder, indent+"\t"); } } else if (fieldType.getTypeKind() == TypeKind.Object) { Object child = property.get(bean); if (child != null) { printProperty(child, property, builder, indent + "\t"); } else { builder.append("null"); } } else { Object value = property.get(bean); builder.append(value); } } catch (Throwable e) { builder.append("\nERROR :: ").append(e.toString()).append("\n"); e.printStackTrace(); } } builder.append("\n").append(indent).append("}"); } }
Garfonso/loadable-frameworks
globalization/test/phone_format_tests_au.js
<gh_stars>0 // @@@LICENSE // // Copyright (c) 2010-2013 LG Electronics, 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. // // LICENSE@@@ /*globals Globalization, Assert, console */ var webos = IMPORTS.require("webos"); webos.include("test/loadall.js"); function PhoneFormatTestsAU() { } PhoneFormatTestsAU.prototype.testFormatStyle0 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "34523434" }; var expected = "(02) 3452 3434"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle1 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "34523434" }; var expected = "02 3452 3434"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 1); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "34523434" }; var expected = "02 34523434"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 2); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatInternational = function() { var formatted; var parsed = { iddPrefix: "+", countryCode: "61", trunkAccess: "0", areaCode: "2", subscriberNumber: "12345678" }; var expected = "+61 2 1234 5678"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatInternationalAccessCode = function() { var formatted; var parsed = { iddPrefix: "0011", countryCode: "61", areaCode: "2", subscriberNumber: "12345678" }; var expected = "0011 61 2 1234 5678"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatMobile = function() { var formatted; var parsed = { trunkAccess: "0", mobilePrefix: "4192", subscriberNumber: "12345" }; var expected = "0419 212 345"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatMobileInternational = function() { var formatted; var parsed = { iddPrefix: "+", countryCode: "61", trunkAccess: "0", mobilePrefix: "4192", subscriberNumber: "12345" }; var expected = "+61 419 212 345"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatService = function() { var formatted; var parsed = { serviceCode: "1800", subscriberNumber: "123456" }; var expected = "1800 123 456"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatIEIDD = function() { var formatted; var parsed = { iddPrefix: "+", countryCode: "353", trunkAccess: "0", areaCode: "1", subscriberNumber: "1234567" }; var expected = "+353 1 123 4567"; formatted = Globalization.Format.formatPhoneNumber(parsed, "en_au", 0); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial0 = function() { var formatted; var parsed = { trunkAccess: "0" }; var expected = "0"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial1 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2" }; var expected = "(02) "; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial2 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "8" }; var expected = "(02) 8"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial3 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "87" }; var expected = "(02) 87"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial4 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "876" }; var expected = "(02) 876"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial5 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "8765" }; var expected = "(02) 8765"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial6 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "87654" }; var expected = "(02) 8765 4"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial7 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "876543" }; var expected = "(02) 8765 43"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial8 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "8765432" }; var expected = "(02) 8765 432"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial9 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "87654321" }; var expected = "(02) 8765 4321"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0Partial10 = function() { var formatted; var parsed = { trunkAccess: "0", areaCode: "2", subscriberNumber: "876543210" // too long }; var expected = "02876543210"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal1 = function() { var formatted; var parsed = { subscriberNumber: "8" }; var expected = "8"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal2 = function() { var formatted; var parsed = { subscriberNumber: "87" }; var expected = "87"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal3 = function() { var formatted; var parsed = { subscriberNumber: "876" }; var expected = "876"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal4 = function() { var formatted; var parsed = { subscriberNumber: "8765" }; var expected = "8765"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal5 = function() { var formatted; var parsed = { subscriberNumber: "87654" }; var expected = "8765 4"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal6 = function() { var formatted; var parsed = { subscriberNumber: "876543" }; var expected = "8765 43"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal7 = function() { var formatted; var parsed = { subscriberNumber: "8765432" }; var expected = "8765 432"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal8 = function() { var formatted; var parsed = { subscriberNumber: "87654321" }; var expected = "8765 4321"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle0PartialLocal9 = function() { var formatted; var parsed = { subscriberNumber: "876543210" // too long }; var expected = "876543210"; // use last resort rule formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "default"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal1 = function() { var formatted; var parsed = { subscriberNumber: "4" }; var expected = "4"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal2 = function() { var formatted; var parsed = { subscriberNumber: "45" }; var expected = "45"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal3 = function() { var formatted; var parsed = { subscriberNumber: "456" }; var expected = "456"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal4 = function() { var formatted; var parsed = { subscriberNumber: "4563" }; var expected = "4563"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal5 = function() { var formatted; var parsed = { subscriberNumber: "45634" }; var expected = "45634"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal6 = function() { var formatted; var parsed = { subscriberNumber: "456345" }; var expected = "456345"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal7 = function() { var formatted; var parsed = { subscriberNumber: "4563453" }; var expected = "4563453"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal8 = function() { var formatted; var parsed = { subscriberNumber: "45634534" }; var expected = "45634534"; formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; }; PhoneFormatTestsAU.prototype.testFormatStyle2PartialLocal9 = function() { var formatted; var parsed = { subscriberNumber: "456345345" // too long }; var expected = "456345345"; // use last resort rule formatted = Globalization.Format.formatPhoneNumber(parsed, {locale: "en_au", partial: true, style: "compressed"}); UnitTest.requireEqual(expected, formatted); return UnitTest.passed; };
Asurada2015/TFAPI_translation
NeuralNekworks_function/Normalization/tf_nn_l2_normalize.py
"""归一化(标准化)的目标之一在于将输入保持在一个可接受的范围内 例如将输入归一化到[0.0,1.0]区间内使输入中所有可能的分量归一化为一个大于等于0.0小于等于1.0的值""" """ tf.nn.l2_normalize(x, dim, epsilon=1e-12, name=None) 解释:这个函数的作用是利用 L2 范数对指定维度 dim 进行标准化。 比如,对于一个一维的张量,指定维度 dim = 0,那么计算结果为: output = x / sqrt( max( sum( x ** 2 ) , epsilon ) ) 假设 x 是多维度的,那么标准化只会独立的对维度 dim 进行,不会影响到别的维度。""" import numpy as np import tensorflow as tf input_data = tf.Variable(np.arange(1, 7).reshape(2, 3), dtype=tf.float32) output = tf.nn.l2_normalize(input_data, dim=0) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) print(sess.run(tf.shape(input_data))) print(sess.run(input_data)) print(sess.run(output)) print(sess.run(tf.shape(output))) # [2 3] # [[1. 2. 3.] # [4. 5. 6.]] # [[0.24253564 0.37139067 0.44721359] # [0.97014254 0.92847669 0.89442718]] # [2 3] """输入参数: ● x: 一个Tensor。 ● dim: 需要标准化的维度。 ● epsilon: 一个很小的值,确定标准化的下边界。如果 norm < sqrt(epsilon),那么我们将使用 sqrt(epsilon) 进行标准化。 ● name: (可选)为这个操作取一个名字。 输出参数: 一个 Tensor ,数据维度和 x 相同。"""
Chorro/normalizer
service/src/test/java/io/wizzie/normalizer/mocks/MockKeyValueStore.java
package io.wizzie.normalizer.mocks; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.state.KeyValueIterator; import org.apache.kafka.streams.state.KeyValueStore; import java.util.HashMap; import java.util.List; import java.util.Map; public class MockKeyValueStore<K, V> implements KeyValueStore<K, V> { private Map<K, V> cache = new HashMap<>(); @Override public V get(K key) { return cache.get(key); } @Override public void put(K key, V value) { cache.put(key, value); } @Override public V putIfAbsent(K key, V value) { V lastValue = cache.get(key); if(lastValue == null) cache.put(key, value); return lastValue; } @Override public void putAll(List<KeyValue<K, V>> entries) { for(KeyValue<K, V> entry : entries) cache.put(entry.key, entry.value); } @Override public V delete(K key) { return cache.remove(key); } @Override public KeyValueIterator<K, V> range(K from, K to) { return null; } @Override public KeyValueIterator<K, V> all() { return null; } @Override public long approximateNumEntries() { return 0; } @Override public String name() { return "mock-key-value-store"; } @Override public void init(ProcessorContext context, StateStore root) { } @Override public void flush() { } @Override public void close() { cache.clear(); } @Override public boolean persistent() { return false; } @Override public boolean isOpen() { return false; } }
matt-deboer/kuill
pkg/ui/src/utils/LogFollower.js
import { TextDecoder } from 'text-encoding-utf-8' import { addError } from '../state/actions/errors' // const escape = parseInt('033', 8); const colorCodes = [153,215,230,147,14,10,11,159,255].map(val => `\x1B[38;5;${val}m`) const logSuffix = `\x1B[0m` class LogBuffer extends Array { constructor(maxSize=2500) { super(0) this._maxSize = maxSize this._colorIndex = 0 } push = (e) => { // if an 'onPush' is defined, and it returns false, don't // add the element to the array if (typeof this.onPush === 'function') { if (!this.onPush(e)) { return } } let size = Array.prototype.push.call(this, e) if (size >= this._maxSize) { this.splice(0, size - this._maxSize) } } nextColor = () => { this._colorIndex = (this._colorIndex + 1) % colorCodes.length return colorCodes[this._colorIndex] } } export default class LogFollower { static Buffer = LogBuffer constructor(props) { this.props = props this.firstLine = true this.maxLines = props.maxLines || 1500 this.logs = props.logs this.dispatch = props.dispatch this.logColor = props.logs.nextColor() let { pod, namespace, container } = props this.logPrefix = `${props.logs.nextColor()}` let loc = window.location let scheme = (loc.protocol === 'https:' ? 'wss' : 'ws') this.url = `${scheme}://${loc.host}/proxy/api/v1/namespaces/${namespace}/pods/${pod}/log?follow=true&container=${container}&tailLines=${this.maxLines}` this.initSocket(this.url) } initSocket = (url) => { let tries = (this.socket && this.socket.tries) || 0 let socket = new WebSocket(url) socket.binaryType = 'arraybuffer' socket.tries = tries let that = this socket.onerror = function (e) { if (socket.readyState !== WebSocket.OPEN) { if (socket.tries < 3) { ++socket.tries window.setTimeout(that.reload.bind(that, url), 2000) } else { socket.tries = 0 that.dispatch(addError(e,'error',`Error occurred following logs for: ${url}`, 'Retry', that.reload.bind(that,url))) that.destroy() } } } socket.onmessage = this.onEvent this.socket = socket } reload = (url) => { let socket = this.socket if (socket) { socket.close() this.initSocket(url) } } onEvent = (event) => { let line = new TextDecoder("utf-8").decode(event.data) if (!!line) { line = this.logPrefix + line if (line.endsWith('\n')) { line = line.slice(0, -1) + logSuffix } else { line += logSuffix } this.logs.push(line) } } destroy = () => { if (this.socket) { this.socket.close() this.socket.onmessage = null this.socket.onerror = null this.socket = null this.logs = null } } }
kimonito98/tudat
src/math/interpolators/cubicSplineInterpolator.cpp
#include "tudat/math/interpolators/cubicSplineInterpolator.h" namespace tudat { namespace interpolators { template class CubicSplineInterpolator< double, Eigen::VectorXd >; template class CubicSplineInterpolator< double, Eigen::Vector6d >; template class CubicSplineInterpolator< double, Eigen::MatrixXd >; #if( TUDAT_BUILD_WITH_EXTENDED_PRECISION_PROPAGATION_TOOLS ) template class CubicSplineInterpolator< Time, Eigen::VectorXd, long double >; template class CubicSplineInterpolator< Time, Eigen::Vector6d, long double >; template class CubicSplineInterpolator< Time, Eigen::MatrixXd, long double >; template class CubicSplineInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, 1 > >; template class CubicSplineInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, 6 > >; template class CubicSplineInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, Eigen::Dynamic > >; template class CubicSplineInterpolator< Time, Eigen::Matrix< long double, Eigen::Dynamic, 1 >, long double >; template class CubicSplineInterpolator< Time, Eigen::Matrix< long double, Eigen::Dynamic, 6 >, long double >; template class CubicSplineInterpolator< Time, Eigen::Matrix< long double, Eigen::Dynamic, Eigen::Dynamic >, long double >; #endif } // namespace interpolators } // namespace tudat
SymmetricChaos/FiniteFields
Computation/RootFinding/SchoolyardMethod.py
# A schoolyard method for finding the input of a function that gives a # particular output. The first guess is the output itself and the step size is # half of that. If the function evaluates to more than the value we want then # subtract the step size and check again. If the sign has flipped divide the # step size in half and begin again. def schoolyard_method(x,f,step=1,tol=.01,max_iter=100): """When does f(x) = val?""" s = step for i in range(max_iter): if abs(f(x)-0) < tol: return x if f(x) > 0: x -= s if f(x) < 0: s = s/2 if f(x) < 0: x += s if f(x) > 0: s = s/2 return x def schoolyard_method_convergents(x,f,step=1,tol=.01,max_iter=100): """When does f(x) = val?""" s = step for i in range(max_iter): yield x if abs(f(x)-0) < tol: return x if f(x) > 0: x -= s if f(x) < 0: s = s/2 if f(x) < 0: x += s if f(x) > 0: s = s/2 #from math import log2, sqrt # #N = 1835 #def f1(x): # return x**2 - N # #def f2(x): # return 2**x - N # #print(schoolyard_method(0,f1)) #print(sqrt(N)) # #print(schoolyard_method(0,f2)) #print(log2(N)) # #
curtislb/ProjectEuler
py/problem_148.py
<filename>py/problem_148.py #!/usr/bin/env python3 """problem_148.py Problem 148: Exploring Pascal's triangle We can easily verify that none of the entries in the first seven rows of Pascal's triangle are divisible by 7: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 However, if we check the first one hundred rows, we will find that only 2361 of the 5050 entries are not divisible by 7. Find the number of entries which are not divisible by PRIME in the first ROW_COUNT rows of Pascal's triangle. """ __author__ = '<NAME>' import math import common.sequences as seqs # PARAMETERS ################################################################## PRIME = 7 # default: 7 ROW_COUNT = 10**9 # default: 10**9 # SOLUTION #################################################################### def solve() -> int: # count number of entries up to nearest power of PRIME log_p = int(math.log(ROW_COUNT, PRIME)) tri_p = seqs.triangular(PRIME) power = PRIME**log_p nonzero = tri_p**log_p # count remaining entries not divisible by PRIME count = 0 remaining = ROW_COUNT while remaining > 0: msd, remaining = divmod(remaining, power) count += nonzero * seqs.triangular(msd) power //= PRIME nonzero = nonzero * (msd + 1) // tri_p return count if __name__ == '__main__': print(solve())
adithyap/coursework
OperatingSystems/MMU/options.cpp
#include "options.hpp" bool Options::_ohhh; bool Options::_page_table; bool Options::_frame_table; bool Options::_summary; bool Options::_dbg_page_table; bool Options::_dbg_frame_table; bool Options::_dbg_aging; void Options::init_options(char *options) { _ohhh = false; _page_table = false; _frame_table = false; _summary = false; _dbg_aging = false; _dbg_page_table = false; _dbg_frame_table = false; if (options == NULL) { printf("Options::parse_options - input string is NULL"); return; } int len = strlen(options); for ( int i = 0; i < len; i++ ) { switch(options[i]) { case 'o': case 'O': _ohhh = true; break; case 'p': _dbg_page_table = true; break; case 'P': _page_table = true; break; case 'f': _dbg_frame_table = true; break; case 'F': _frame_table = true; break; case 's': case 'S': _summary = true; break; case 'a': case 'A': _dbg_aging = true; break; default: printf("Options::init_options - Unknown argument %c, will ignore\n", options[i]); break; } } } bool Options::ohhh() { return _ohhh; } bool Options::page_table() { return _page_table; } bool Options::frame_table() { return _frame_table; } bool Options::summary() { return _summary; } bool Options::dbg_page_table() { return _dbg_page_table; } bool Options::dbg_frame_table() { return _dbg_frame_table; } bool Options::dbg_aging() { return _dbg_aging; }
yangzhaofeng/huaweicloud-sdk-cpp-v3
evs/src/v2/model/ListSnapshotsRequest.cpp
#include "huaweicloud/evs/v2/model/ListSnapshotsRequest.h" namespace HuaweiCloud { namespace Sdk { namespace Evs { namespace V2 { namespace Model { ListSnapshotsRequest::ListSnapshotsRequest() { offset_ = 0; offsetIsSet_ = false; limit_ = 0; limitIsSet_ = false; name_ = ""; nameIsSet_ = false; status_ = ""; statusIsSet_ = false; volumeId_ = ""; volumeIdIsSet_ = false; availabilityZone_ = ""; availabilityZoneIsSet_ = false; id_ = ""; idIsSet_ = false; dedicatedStorageName_ = ""; dedicatedStorageNameIsSet_ = false; dedicatedStorageId_ = ""; dedicatedStorageIdIsSet_ = false; serviceType_ = ""; serviceTypeIsSet_ = false; enterpriseProjectId_ = ""; enterpriseProjectIdIsSet_ = false; } ListSnapshotsRequest::~ListSnapshotsRequest() = default; void ListSnapshotsRequest::validate() { } web::json::value ListSnapshotsRequest::toJson() const { web::json::value val = web::json::value::object(); if(offsetIsSet_) { val[utility::conversions::to_string_t("offset")] = ModelBase::toJson(offset_); } if(limitIsSet_) { val[utility::conversions::to_string_t("limit")] = ModelBase::toJson(limit_); } if(nameIsSet_) { val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_); } if(statusIsSet_) { val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_); } if(volumeIdIsSet_) { val[utility::conversions::to_string_t("volume_id")] = ModelBase::toJson(volumeId_); } if(availabilityZoneIsSet_) { val[utility::conversions::to_string_t("availability_zone")] = ModelBase::toJson(availabilityZone_); } if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(dedicatedStorageNameIsSet_) { val[utility::conversions::to_string_t("dedicated_storage_name")] = ModelBase::toJson(dedicatedStorageName_); } if(dedicatedStorageIdIsSet_) { val[utility::conversions::to_string_t("dedicated_storage_id")] = ModelBase::toJson(dedicatedStorageId_); } if(serviceTypeIsSet_) { val[utility::conversions::to_string_t("service_type")] = ModelBase::toJson(serviceType_); } if(enterpriseProjectIdIsSet_) { val[utility::conversions::to_string_t("enterprise_project_id")] = ModelBase::toJson(enterpriseProjectId_); } return val; } bool ListSnapshotsRequest::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("offset"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("offset")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOffset(refVal); } } if(val.has_field(utility::conversions::to_string_t("limit"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("limit")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setLimit(refVal); } } if(val.has_field(utility::conversions::to_string_t("name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setName(refVal); } } if(val.has_field(utility::conversions::to_string_t("status"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setStatus(refVal); } } if(val.has_field(utility::conversions::to_string_t("volume_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("volume_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVolumeId(refVal); } } if(val.has_field(utility::conversions::to_string_t("availability_zone"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("availability_zone")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setAvailabilityZone(refVal); } } if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("dedicated_storage_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("dedicated_storage_name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDedicatedStorageName(refVal); } } if(val.has_field(utility::conversions::to_string_t("dedicated_storage_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("dedicated_storage_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDedicatedStorageId(refVal); } } if(val.has_field(utility::conversions::to_string_t("service_type"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("service_type")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setServiceType(refVal); } } if(val.has_field(utility::conversions::to_string_t("enterprise_project_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("enterprise_project_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setEnterpriseProjectId(refVal); } } return ok; } int32_t ListSnapshotsRequest::getOffset() const { return offset_; } void ListSnapshotsRequest::setOffset(int32_t value) { offset_ = value; offsetIsSet_ = true; } bool ListSnapshotsRequest::offsetIsSet() const { return offsetIsSet_; } void ListSnapshotsRequest::unsetoffset() { offsetIsSet_ = false; } int32_t ListSnapshotsRequest::getLimit() const { return limit_; } void ListSnapshotsRequest::setLimit(int32_t value) { limit_ = value; limitIsSet_ = true; } bool ListSnapshotsRequest::limitIsSet() const { return limitIsSet_; } void ListSnapshotsRequest::unsetlimit() { limitIsSet_ = false; } std::string ListSnapshotsRequest::getName() const { return name_; } void ListSnapshotsRequest::setName(const std::string& value) { name_ = value; nameIsSet_ = true; } bool ListSnapshotsRequest::nameIsSet() const { return nameIsSet_; } void ListSnapshotsRequest::unsetname() { nameIsSet_ = false; } std::string ListSnapshotsRequest::getStatus() const { return status_; } void ListSnapshotsRequest::setStatus(const std::string& value) { status_ = value; statusIsSet_ = true; } bool ListSnapshotsRequest::statusIsSet() const { return statusIsSet_; } void ListSnapshotsRequest::unsetstatus() { statusIsSet_ = false; } std::string ListSnapshotsRequest::getVolumeId() const { return volumeId_; } void ListSnapshotsRequest::setVolumeId(const std::string& value) { volumeId_ = value; volumeIdIsSet_ = true; } bool ListSnapshotsRequest::volumeIdIsSet() const { return volumeIdIsSet_; } void ListSnapshotsRequest::unsetvolumeId() { volumeIdIsSet_ = false; } std::string ListSnapshotsRequest::getAvailabilityZone() const { return availabilityZone_; } void ListSnapshotsRequest::setAvailabilityZone(const std::string& value) { availabilityZone_ = value; availabilityZoneIsSet_ = true; } bool ListSnapshotsRequest::availabilityZoneIsSet() const { return availabilityZoneIsSet_; } void ListSnapshotsRequest::unsetavailabilityZone() { availabilityZoneIsSet_ = false; } std::string ListSnapshotsRequest::getId() const { return id_; } void ListSnapshotsRequest::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool ListSnapshotsRequest::idIsSet() const { return idIsSet_; } void ListSnapshotsRequest::unsetid() { idIsSet_ = false; } std::string ListSnapshotsRequest::getDedicatedStorageName() const { return dedicatedStorageName_; } void ListSnapshotsRequest::setDedicatedStorageName(const std::string& value) { dedicatedStorageName_ = value; dedicatedStorageNameIsSet_ = true; } bool ListSnapshotsRequest::dedicatedStorageNameIsSet() const { return dedicatedStorageNameIsSet_; } void ListSnapshotsRequest::unsetdedicatedStorageName() { dedicatedStorageNameIsSet_ = false; } std::string ListSnapshotsRequest::getDedicatedStorageId() const { return dedicatedStorageId_; } void ListSnapshotsRequest::setDedicatedStorageId(const std::string& value) { dedicatedStorageId_ = value; dedicatedStorageIdIsSet_ = true; } bool ListSnapshotsRequest::dedicatedStorageIdIsSet() const { return dedicatedStorageIdIsSet_; } void ListSnapshotsRequest::unsetdedicatedStorageId() { dedicatedStorageIdIsSet_ = false; } std::string ListSnapshotsRequest::getServiceType() const { return serviceType_; } void ListSnapshotsRequest::setServiceType(const std::string& value) { serviceType_ = value; serviceTypeIsSet_ = true; } bool ListSnapshotsRequest::serviceTypeIsSet() const { return serviceTypeIsSet_; } void ListSnapshotsRequest::unsetserviceType() { serviceTypeIsSet_ = false; } std::string ListSnapshotsRequest::getEnterpriseProjectId() const { return enterpriseProjectId_; } void ListSnapshotsRequest::setEnterpriseProjectId(const std::string& value) { enterpriseProjectId_ = value; enterpriseProjectIdIsSet_ = true; } bool ListSnapshotsRequest::enterpriseProjectIdIsSet() const { return enterpriseProjectIdIsSet_; } void ListSnapshotsRequest::unsetenterpriseProjectId() { enterpriseProjectIdIsSet_ = false; } } } } } }
TamataOcean/Workshop-Electronic
libraries/LaCOOLBoard/extras/doxygenDocs/html/class_cool_s_i114_x.js
<reponame>TamataOcean/Workshop-Electronic var class_cool_s_i114_x = [ [ "Begin", "class_cool_s_i114_x.html#a206b36aca7049f63be1d11088c30a09f", null ], [ "DeInit", "class_cool_s_i114_x.html#a6840abd53a2e3d71a6bb918077c6d6e6", null ], [ "ReadByte", "class_cool_s_i114_x.html#acc20f8037e156ec4aadcbe90780b1e8b", null ], [ "ReadHalfWord", "class_cool_s_i114_x.html#a1d25c9e137874af529804c2ec796a6b9", null ], [ "ReadIR", "class_cool_s_i114_x.html#abc536ee7ae8e3ba9d1069acc3889a2cf", null ], [ "ReadParamData", "class_cool_s_i114_x.html#a33cf431103c722442f6a0cc93848d640", null ], [ "ReadProximity", "class_cool_s_i114_x.html#a194fede1105508c7803dbb567cbdcc67", null ], [ "ReadResponseReg", "class_cool_s_i114_x.html#a869d3825147831d707f7ef324a665646", null ], [ "ReadUV", "class_cool_s_i114_x.html#a14ced664d74e93438440b0274109c111", null ], [ "ReadVisible", "class_cool_s_i114_x.html#a42e0e574256341443c647a4c0eda87d5", null ], [ "Reset", "class_cool_s_i114_x.html#a9d9f9c9129c0c29ed497f8563f3dd823", null ], [ "WriteByte", "class_cool_s_i114_x.html#ac5c8dc5ade604da7a1c8cd1586feefc2", null ], [ "WriteParamData", "class_cool_s_i114_x.html#abf45eb10a6de1be16e68a51624fa2608", null ] ];
giantswarm/app-operator
service/controller/app/resource/status/delete.go
package status import "context" func (r *Resource) EnsureDeleted(ctx context.Context, obj interface{}) error { return nil }
TAJORE/supinfo3
src/Web/AdminBundle/Resources/public/js/apputils.js
/** * Created by root on 7/26/17. */ var app = { formatNumber: function(number){ return number < 10 ? "0"+number : number.toString(); }, parseDate : function(date) { var d = new Date(date), result = ""; result += app.formatNumber(d.getDate()) + '/'; result += app.formatNumber(d.getMonth()) + '/'; result += d.getFullYear() + ' à '; result += app.formatNumber(d.getHours()) + ':'; result += app.formatNumber(d.getMinutes()); return result; } };
solisbrian/FLAP
src/app/modules/fsa2/machine/util/sipserTestsDFAs.test.js
<reponame>solisbrian/FLAP<filename>src/app/modules/fsa2/machine/util/sipserTestsDFAs.test.js import FSA, { EMPTY_SYMBOL } from '../FSA.js'; import { solveFSA, convertToDFA } from '../FSAUtils.js'; import FSAGraph from 'modules/fsa2/graph/FSAGraph.js'; import FSABuilder from 'modules/fsa2/machine/FSABuilder.js'; function testSolveFSA(machine, testString, expectedResult=true) { test("test string \'" + testString + "\'", () => { expect(solveFSA(machine, testString)).toBe(expectedResult); }); } //Exmples describe("Example 1.7 Page 37", () => { const dfa = new FSA(false); const graph = new FSAGraph(); const builder = new FSABuilder(); const q1 = dfa.createState("q1"); const q2 = dfa.createState("q2"); dfa.addTransition(q1,q1,"0"); dfa.addTransition(q1,q2,"1"); dfa.addTransition(q2,q2,"1"); dfa.addTransition(q2,q1,"0"); dfa.setFinalState(q2); builder.getMachine().copy(dfa); builder.attemptBuildGraph(dfa, graph); test("start state is correct?", () => { expect(graph.getStartNode().getNodeLabel()).toBe("q1"); expect(graph.getNodesByLabel("q2")[0].getNodeAccept()).toBe(true); expect(dfa.validate()).toBe(true); expect(dfa.isValid()).toBe(true); }); }); //Exercises describe("Exercise 1.1", () => { const dfa = new FSA(false); const graph = new FSAGraph(); const builder = new FSABuilder(); const q1 = dfa.createState("q1"); const q2 = dfa.createState("q2"); const q3 = dfa.createState("q3"); dfa.addTransition(q1,q1,"b"); dfa.addTransition(q1,q2,"a"); dfa.addTransition(q2,q3,"a"); dfa.addTransition(q2,q3,"b"); dfa.addTransition(q3,q2,"a"); dfa.addTransition(q3,q1,"b"); dfa.setFinalState(q2); builder.getMachine().copy(dfa); builder.attemptBuildGraph(dfa, graph); test("start state is correct?", () => { expect(graph.getStartNode().getNodeLabel()).toBe("q1"); expect(dfa.validate()).toBe(true); expect(dfa.isValid()).toBe(true); }); });
YuriyAM/what-front
src/utils/helpers/index.js
export { Cookie } from './cookie.js'; export { commonHelpers } from './common-helpers.js';
attineos/atti-components
packages/atti-components/src/components/InputPopdown/styles.js
<filename>packages/atti-components/src/components/InputPopdown/styles.js<gh_stars>10-100 import styled from 'styled-components' const StyledInputPopdownContainer = styled.div` position: relative; display: inline-block; ` const StyledInputPopdown = styled.div` display: ${({ isOpen }) => (isOpen ? 'block' : 'none')}; opacity: ${({ isOpen }) => (isOpen ? '1' : '0')}; position: absolute; left: 0; right: 0; width: 100%; z-index: 100; ` const StyledInputPopdownEnhancerContainer = styled.div` display: inline-block; min-width: 100%; ${({ theme }) => ` background: ${theme.components.inputPopdown.colors.background}; box-shadow: ${theme.components.inputPopdown.boxShadows.boxShadow}; border-radius: ${theme.components.inputPopdown.borders.radius}; `} ` export { StyledInputPopdownContainer, StyledInputPopdown, StyledInputPopdownEnhancerContainer }
jjuiddong/KarlSims
SampleFramework/renderer/src/d3d9/D3D9RendererTarget.cpp
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // suppress LNK4221 on Xbox namespace {char dummySymbol; } #include <RendererConfig.h> #include "D3D9RendererTarget.h" #if defined(RENDERER_ENABLE_DIRECT3D9) && defined(RENDERER_ENABLE_DIRECT3D9_TARGET) #include <RendererTargetDesc.h> #include "D3D9RendererTexture2D.h" using namespace SampleRenderer; D3D9RendererTarget::D3D9RendererTarget(IDirect3DDevice9 &d3dDevice, const RendererTargetDesc &desc) : m_d3dDevice(d3dDevice) { m_d3dLastSurface = 0; m_d3dLastDepthStencilSurface = 0; m_d3dDepthStencilSurface = 0; for(PxU32 i=0; i<desc.numTextures; i++) { D3D9RendererTexture2D &texture = *static_cast<D3D9RendererTexture2D*>(desc.textures[i]); m_textures.push_back(&texture); } m_depthStencilSurface = static_cast<D3D9RendererTexture2D*>(desc.depthStencilSurface); RENDERER_ASSERT(m_depthStencilSurface && m_depthStencilSurface->m_d3dTexture, "Invalid Target Depth Stencil Surface!"); onDeviceReset(); } D3D9RendererTarget::~D3D9RendererTarget(void) { if(m_d3dDepthStencilSurface) m_d3dDepthStencilSurface->Release(); } void D3D9RendererTarget::bind(void) { RENDERER_ASSERT(m_d3dLastSurface==0 && m_d3dLastDepthStencilSurface==0, "Render Target in bad state!"); if(m_d3dDepthStencilSurface && !m_d3dLastSurface && !m_d3dLastDepthStencilSurface) { m_d3dDevice.GetRenderTarget(0, &m_d3dLastSurface); m_d3dDevice.GetDepthStencilSurface(&m_d3dLastDepthStencilSurface); const PxU32 numTextures = (PxU32)m_textures.size(); for(PxU32 i=0; i<numTextures; i++) { IDirect3DSurface9 *d3dSurcace = 0; D3D9RendererTexture2D &texture = *m_textures[i]; /* HRESULT result = */ texture.m_d3dTexture->GetSurfaceLevel(0, &d3dSurcace); RENDERER_ASSERT(d3dSurcace, "Cannot get Texture Surface!"); if(d3dSurcace) { m_d3dDevice.SetRenderTarget(i, d3dSurcace); d3dSurcace->Release(); } } m_d3dDevice.SetDepthStencilSurface(m_d3dDepthStencilSurface); const DWORD flags = D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER; m_d3dDevice.Clear(0, 0, flags, 0x00000000, 1.0f, 0); } float depthBias = 0.0001f; float biasSlope = 1.58f; #if RENDERER_ENABLE_DRESSCODE depthBias = dcParam("depthBias", depthBias, 0.0f, 0.01f); biasSlope = dcParam("biasSlope", biasSlope, 0.0f, 5.0f); #endif m_d3dDevice.SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias); m_d3dDevice.SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&biasSlope); } void D3D9RendererTarget::unbind(void) { RENDERER_ASSERT(m_d3dLastSurface && m_d3dLastDepthStencilSurface, "Render Target in bad state!"); if(m_d3dDepthStencilSurface && m_d3dLastSurface && m_d3dLastDepthStencilSurface) { m_d3dDevice.SetDepthStencilSurface(m_d3dLastDepthStencilSurface); m_d3dDevice.SetRenderTarget(0, m_d3dLastSurface); const PxU32 numTextures = (PxU32)m_textures.size(); for(PxU32 i=1; i<numTextures; i++) { m_d3dDevice.SetRenderTarget(i, 0); } m_d3dLastSurface->Release(); m_d3dLastSurface = 0; m_d3dLastDepthStencilSurface->Release(); m_d3dLastDepthStencilSurface = 0; } float depthBias = 0; float biasSlope = 0; m_d3dDevice.SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias); m_d3dDevice.SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&biasSlope); } void D3D9RendererTarget::onDeviceLost(void) { RENDERER_ASSERT(m_d3dLastDepthStencilSurface==0, "Render Target in bad state!"); RENDERER_ASSERT(m_d3dDepthStencilSurface, "Render Target in bad state!"); if(m_d3dDepthStencilSurface) { m_d3dDepthStencilSurface->Release(); m_d3dDepthStencilSurface = 0; } } void D3D9RendererTarget::onDeviceReset(void) { RENDERER_ASSERT(m_d3dDepthStencilSurface==0, "Render Target in bad state!"); if(!m_d3dDepthStencilSurface && m_depthStencilSurface && m_depthStencilSurface->m_d3dTexture) { bool ok = m_depthStencilSurface->m_d3dTexture->GetSurfaceLevel(0, &m_d3dDepthStencilSurface) == D3D_OK; if(!ok) { RENDERER_ASSERT(ok, "Failed to create Render Target Depth Stencil Surface."); } } } #endif //#if defined(RENDERER_ENABLE_DIRECT3D9) && defined(RENDERER_ENABLE_DIRECT3D9_TARGET)
fabianoflorentino/python-CursoIntensivoDePython
Parte1/Cap2/exercicios/numero_oito.py
print(int(5) + int(3)) print(int(2) * int(4)) print(int(16) / int(2)) print(int(16) - int(8))
Y-sir/spark-cn
sql/core/target/java/org/apache/spark/sql/execution/adaptive/ReduceNumShufflePartitions.java
<gh_stars>0 package org.apache.spark.sql.execution.adaptive; /** * A rule to adjust the post shuffle partitions based on the map output statistics. * <p> * The strategy used to determine the number of post-shuffle partitions is described as follows. * To determine the number of post-shuffle partitions, we have a target input size for a * post-shuffle partition. Once we have size statistics of all pre-shuffle partitions, we will do * a pass of those statistics and pack pre-shuffle partitions with continuous indices to a single * post-shuffle partition until adding another pre-shuffle partition would cause the size of a * post-shuffle partition to be greater than the target size. * <p> * For example, we have two stages with the following pre-shuffle partition size statistics: * stage 1: [100 MiB, 20 MiB, 100 MiB, 10MiB, 30 MiB] * stage 2: [10 MiB, 10 MiB, 70 MiB, 5 MiB, 5 MiB] * assuming the target input size is 128 MiB, we will have four post-shuffle partitions, * which are: * - post-shuffle partition 0: pre-shuffle partition 0 (size 110 MiB) * - post-shuffle partition 1: pre-shuffle partition 1 (size 30 MiB) * - post-shuffle partition 2: pre-shuffle partition 2 (size 170 MiB) * - post-shuffle partition 3: pre-shuffle partition 3 and 4 (size 50 MiB) */ public class ReduceNumShufflePartitions extends org.apache.spark.sql.catalyst.rules.Rule<org.apache.spark.sql.execution.SparkPlan> implements scala.Product, scala.Serializable { static public java.lang.String toString () { throw new RuntimeException(); } public org.apache.spark.sql.internal.SQLConf conf () { throw new RuntimeException(); } // not preceding public ReduceNumShufflePartitions (org.apache.spark.sql.internal.SQLConf conf) { throw new RuntimeException(); } public org.apache.spark.sql.execution.SparkPlan apply (org.apache.spark.sql.execution.SparkPlan plan) { throw new RuntimeException(); } /** * Estimates partition start indices for post-shuffle partitions based on * mapOutputStatistics provided by all pre-shuffle stages. * @param mapOutputStatistics (undocumented) * @return (undocumented) */ int[] estimatePartitionStartIndices (org.apache.spark.MapOutputStatistics[] mapOutputStatistics) { throw new RuntimeException(); } }
Bounty556/ChangeOfSeasons
controllers/userController.js
<filename>controllers/userController.js const db = require('../models'); const bcrypt = require('bcryptjs'); function hashPassword(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null); } module.exports = { getUser: id => { return new Promise((resolve, reject) => { db.User.findById(id) .then(dbModel => resolve(dbModel.toJSON())) .catch(err => reject(err)); }); }, createUser: (req, res) => { req.body.password = <PASSWORD>(req.body.password); db.User.create(req.body) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, setUserAvatar: (req, res) => { db.User.updateOne({ _id: req.params.id }, { avatar: req.params.avatar }) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, getDeck: (req, res) => { db.User.findById(req.params.id) .then(user => { db.Card.find({ cardId: { $in: user.cardIds } }) .then(cards => res.json(cards)) .catch(err => res.status(422).json(err)); }) .catch(err => res.status(422).json(err)); }, setDeck: (req, res) => { db.Card.find({ season: req.params.season }) .then(cards => { const cardIds = cards.map(x => x.cardId); db.User.findByIdAndUpdate(req.params.id, { cardIds: cardIds }) .then(user => res.json(user)) .catch(err => res.status(422).json(err)); }) .catch(err => res.status(422).json(err)); }, addWin: (req, res) => { db.User.updateOne({ _id: req.params.id }, { $inc: { wins: 1 } }) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, addLoss: (req, res) => { db.User.updateOne({ _id: req.params.id }, { $inc: { losses: 1 } }) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); } };
bobbyLXArt/v8
test/mjsunit/maglev/05.js
<reponame>bobbyLXArt/v8<filename>test/mjsunit/maglev/05.js // Copyright 2022 the V8 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. // // Flags: --allow-natives-syntax --maglev function f(i, end) { do { do { i = end; } while (end); end = i; } while (i); return 10; } %PrepareFunctionForOptimization(f); assertEquals(10, f(false, false)); %OptimizeMaglevOnNextCall(f); assertEquals(10, f(false, false));
KevinOneLedger/protocol
service/ethereum/prepareERC20Lock.go
<filename>service/ethereum/prepareERC20Lock.go package ethereum import ( "github.com/google/uuid" "github.com/Oneledger/protocol/action" "github.com/Oneledger/protocol/action/eth" "github.com/Oneledger/protocol/serialize" codes "github.com/Oneledger/protocol/status_codes" ) func (svc *Service) PrepareOLTERC20Lock(req *OLTERC20LockRequest, out *OLTReply) error { erc20lock := eth.ERC20Lock{ Locker: req.Address, ETHTxn: req.RawTx, } data, err := erc20lock.Marshal() if err != nil { svc.logger.Error(err, codes.ErrPreparingErc20OLTLock.ErrorMsg()) return codes.ErrPreparingErc20OLTLock } uuidNew, _ := uuid.NewUUID() fee := action.Fee{req.Fee, req.Gas} tx := &action.RawTx{ Type: action.ERC20_LOCK, Data: data, Fee: fee, Memo: uuidNew.String(), } packets, err := serialize.GetSerializer(serialize.NETWORK).Serialize(tx) if err != nil { return codes.ErrSerialization } *out = OLTReply{ RawTX: packets, } return nil }
willfarrell/angular-io
src/scripts/ie.js
// alternative - http://www.pinlady.net/PluginDetect/IE/ // IE version, undefined if not IE. Used for HTML5 polyfills. var IE = /*@cc_on!@*/!1; if (IE) { IE = parseFloat((/MSIE[\s]*([\d\.]+)/).exec(navigator.appVersion)[1]); // Check if chromeframe, reset IE var if so if(IE < 10 && (/chromeframe/).test(navigator.appVersion)) { IE = 0; } }
jessy1092/react-valid
__test__/validators/isNumeric.test.js
import React from 'react'; import { mount } from 'enzyme'; import { createValle } from '../../src'; import isNumeric from '../../src/validators/isNumeric'; import Input from '../fakeComponent/Input'; test('It sould be invalid if input does not contains only number', done => { const valle = createValle(); valle.addMethods(isNumeric); const ValidInput = valle.connect(Input); const onInvalid = (wrapper, value) => { expect(value).toEqual('Hi'); expect(wrapper.state('valid')).toEqual(false); expect(wrapper.state('message')).toEqual( 'Hi does not contain only numbers. Please check your value and try again.', ); expect(wrapper.render()).toMatchSnapshot(); done(); }; const wrapper = mount(<ValidInput isNumeric onInvalid={value => onInvalid(wrapper, value)} />); wrapper.find('input').simulate('change', { target: { value: 'Hi', }, }); }); test('It sould be valid if input contains only number', done => { const valle = createValle(); valle.addMethods(isNumeric); const ValidInput = valle.connect(Input); const onValid = (wrapper, value) => { expect(value).toEqual('0000768123'); expect(wrapper.state('valid')).toEqual(true); expect(wrapper.state('message')).toEqual(''); expect(wrapper.render()).toMatchSnapshot(); done(); }; const wrapper = mount(<ValidInput isNumeric onValid={value => onValid(wrapper, value)} />); wrapper.find('input').simulate('change', { target: { value: '0000768123', }, }); }); test('It sould be valid if input is empty', done => { const valle = createValle(); valle.addMethods(isNumeric); const ValidInput = valle.connect(Input); const onValid = (wrapper, value) => { expect(value).toEqual(''); expect(wrapper.state('valid')).toEqual(true); expect(wrapper.state('message')).toEqual(''); expect(wrapper.render()).toMatchSnapshot(); done(); }; const wrapper = mount(<ValidInput isNumeric onValid={value => onValid(wrapper, value)} />); wrapper.find('input').simulate('change', { target: { value: '', }, }); });
magicmarvman/serenity
Libraries/LibJS/Tests/Array.prototype.join.js
load("test-common.js"); try { assert(Array.prototype.join.length === 1); assert(["hello", "friends"].join() === "hello,friends"); assert(["hello", "friends"].join(" ") === "hello friends"); assert([].join() === ""); assert([null].join() === ""); assert([undefined].join() === ""); assert([undefined, null, ""].join() === ",,"); assert([1, null, 2, undefined, 3].join() === "1,,2,,3"); assert(Array(3).join() === ",,"); console.log("PASS"); } catch (e) { console.log("FAIL: " + e); }