max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
5,964
// This file is generated // Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef protocol_HeapProfiler_h #define protocol_HeapProfiler_h #include "platform/inspector_protocol/Platform.h" #include "platform/inspector_protocol/Array.h" #include "platform/inspector_protocol/BackendCallback.h" #include "platform/inspector_protocol/DispatcherBase.h" #include "platform/inspector_protocol/ErrorSupport.h" #include "platform/inspector_protocol/FrontendChannel.h" #include "platform/inspector_protocol/Maybe.h" #include "platform/inspector_protocol/Object.h" #include "platform/inspector_protocol/Platform.h" #include "platform/inspector_protocol/String16.h" #include "platform/inspector_protocol/Values.h" #include "platform/inspector_protocol/ValueConversions.h" // For each imported domain we generate a ValueConversions struct instead of a full domain definition // and include Domain::API version from there. #include "platform\v8_inspector\protocol/Runtime.h" namespace blink { namespace protocol { namespace HeapProfiler { // ------------- Forward and enum declarations. // Heap snapshot object id. using HeapSnapshotObjectId = String16; // Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. class SamplingHeapProfileNode; // Profile. class SamplingHeapProfile; // ------------- Type and builder declarations. // Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. class PLATFORM_EXPORT SamplingHeapProfileNode { PROTOCOL_DISALLOW_COPY(SamplingHeapProfileNode); public: static std::unique_ptr<SamplingHeapProfileNode> parse(protocol::Value* value, ErrorSupport* errors); ~SamplingHeapProfileNode() { } protocol::Runtime::CallFrame* getCallFrame() { return m_callFrame.get(); } void setCallFrame(std::unique_ptr<protocol::Runtime::CallFrame> value) { m_callFrame = std::move(value); } double getSelfSize() { return m_selfSize; } void setSelfSize(double value) { m_selfSize = value; } protocol::Array<protocol::HeapProfiler::SamplingHeapProfileNode>* getChildren() { return m_children.get(); } void setChildren(std::unique_ptr<protocol::Array<protocol::HeapProfiler::SamplingHeapProfileNode>> value) { m_children = std::move(value); } std::unique_ptr<protocol::DictionaryValue> serialize() const; std::unique_ptr<SamplingHeapProfileNode> clone() const; template<int STATE> class SamplingHeapProfileNodeBuilder { public: enum { NoFieldsSet = 0, CallFrameSet = 1 << 1, SelfSizeSet = 1 << 2, ChildrenSet = 1 << 3, AllFieldsSet = (CallFrameSet | SelfSizeSet | ChildrenSet | 0)}; SamplingHeapProfileNodeBuilder<STATE | CallFrameSet>& setCallFrame(std::unique_ptr<protocol::Runtime::CallFrame> value) { static_assert(!(STATE & CallFrameSet), "property callFrame should not be set yet"); m_result->setCallFrame(std::move(value)); return castState<CallFrameSet>(); } SamplingHeapProfileNodeBuilder<STATE | SelfSizeSet>& setSelfSize(double value) { static_assert(!(STATE & SelfSizeSet), "property selfSize should not be set yet"); m_result->setSelfSize(value); return castState<SelfSizeSet>(); } SamplingHeapProfileNodeBuilder<STATE | ChildrenSet>& setChildren(std::unique_ptr<protocol::Array<protocol::HeapProfiler::SamplingHeapProfileNode>> value) { static_assert(!(STATE & ChildrenSet), "property children should not be set yet"); m_result->setChildren(std::move(value)); return castState<ChildrenSet>(); } std::unique_ptr<SamplingHeapProfileNode> build() { static_assert(STATE == AllFieldsSet, "state should be AllFieldsSet"); return std::move(m_result); } private: friend class SamplingHeapProfileNode; SamplingHeapProfileNodeBuilder() : m_result(new SamplingHeapProfileNode()) { } template<int STEP> SamplingHeapProfileNodeBuilder<STATE | STEP>& castState() { return *reinterpret_cast<SamplingHeapProfileNodeBuilder<STATE | STEP>*>(this); } std::unique_ptr<protocol::HeapProfiler::SamplingHeapProfileNode> m_result; }; static SamplingHeapProfileNodeBuilder<0> create() { return SamplingHeapProfileNodeBuilder<0>(); } private: SamplingHeapProfileNode() { m_selfSize = 0; } std::unique_ptr<protocol::Runtime::CallFrame> m_callFrame; double m_selfSize; std::unique_ptr<protocol::Array<protocol::HeapProfiler::SamplingHeapProfileNode>> m_children; }; // Profile. class PLATFORM_EXPORT SamplingHeapProfile { PROTOCOL_DISALLOW_COPY(SamplingHeapProfile); public: static std::unique_ptr<SamplingHeapProfile> parse(protocol::Value* value, ErrorSupport* errors); ~SamplingHeapProfile() { } protocol::HeapProfiler::SamplingHeapProfileNode* getHead() { return m_head.get(); } void setHead(std::unique_ptr<protocol::HeapProfiler::SamplingHeapProfileNode> value) { m_head = std::move(value); } std::unique_ptr<protocol::DictionaryValue> serialize() const; std::unique_ptr<SamplingHeapProfile> clone() const; template<int STATE> class SamplingHeapProfileBuilder { public: enum { NoFieldsSet = 0, HeadSet = 1 << 1, AllFieldsSet = (HeadSet | 0)}; SamplingHeapProfileBuilder<STATE | HeadSet>& setHead(std::unique_ptr<protocol::HeapProfiler::SamplingHeapProfileNode> value) { static_assert(!(STATE & HeadSet), "property head should not be set yet"); m_result->setHead(std::move(value)); return castState<HeadSet>(); } std::unique_ptr<SamplingHeapProfile> build() { static_assert(STATE == AllFieldsSet, "state should be AllFieldsSet"); return std::move(m_result); } private: friend class SamplingHeapProfile; SamplingHeapProfileBuilder() : m_result(new SamplingHeapProfile()) { } template<int STEP> SamplingHeapProfileBuilder<STATE | STEP>& castState() { return *reinterpret_cast<SamplingHeapProfileBuilder<STATE | STEP>*>(this); } std::unique_ptr<protocol::HeapProfiler::SamplingHeapProfile> m_result; }; static SamplingHeapProfileBuilder<0> create() { return SamplingHeapProfileBuilder<0>(); } private: SamplingHeapProfile() { } std::unique_ptr<protocol::HeapProfiler::SamplingHeapProfileNode> m_head; }; // ------------- Backend interface. class PLATFORM_EXPORT Backend { public: virtual void enable(ErrorString*) = 0; virtual void disable(ErrorString*) = 0; virtual void startTrackingHeapObjects(ErrorString*, const Maybe<bool>& in_trackAllocations) = 0; virtual void stopTrackingHeapObjects(ErrorString*, const Maybe<bool>& in_reportProgress) = 0; virtual void takeHeapSnapshot(ErrorString*, const Maybe<bool>& in_reportProgress) = 0; virtual void collectGarbage(ErrorString*) = 0; virtual void getObjectByHeapObjectId(ErrorString*, const String16& in_objectId, const Maybe<String16>& in_objectGroup, std::unique_ptr<protocol::Runtime::RemoteObject>* out_result) = 0; virtual void addInspectedHeapObject(ErrorString*, const String16& in_heapObjectId) = 0; virtual void getHeapObjectId(ErrorString*, const String16& in_objectId, String16* out_heapSnapshotObjectId) = 0; virtual void startSampling(ErrorString*, const Maybe<double>& in_samplingInterval) = 0; virtual void stopSampling(ErrorString*, std::unique_ptr<protocol::HeapProfiler::SamplingHeapProfile>* out_profile) = 0; protected: virtual ~Backend() { } }; // ------------- Frontend interface. class PLATFORM_EXPORT Frontend { public: Frontend(FrontendChannel* frontendChannel) : m_frontendChannel(frontendChannel) { } void addHeapSnapshotChunk(const String16& chunk); void resetProfiles(); void reportHeapSnapshotProgress(int done, int total, const Maybe<bool>& finished = Maybe<bool>()); void lastSeenObjectId(int lastSeenObjectId, double timestamp); void heapStatsUpdate(std::unique_ptr<protocol::Array<int>> statsUpdate); void flush() { m_frontendChannel->flushProtocolNotifications(); } private: FrontendChannel* m_frontendChannel; }; // ------------- Dispatcher. class PLATFORM_EXPORT Dispatcher { public: static void wire(UberDispatcher*, blink::protocol::HeapProfiler::Backend*); private: Dispatcher() { } }; // ------------- Metainfo. class PLATFORM_EXPORT Metainfo { public: using BackendClass = Backend; using FrontendClass = Frontend; using DispatcherClass = Dispatcher; static const char domainName[]; static const char commandPrefix[]; }; } // namespace HeapProfiler } // namespace protocol } // namespace blink #endif // !defined(protocol_HeapProfiler_h)
3,335
2,338
<gh_stars>1000+ template <class T> void bar(int X) { if (X) { X *= 4; } } void a(); void b();
50
5,156
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #include "util.h" volatile int dummy; int main(void) { int i = 0; atomic_puts("ready"); atomic_puts("EXIT-SUCCESS"); struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); while (1) { dummy += i % (1 << 20); dummy += i % (79 * (1 << 20)); } return 0; }
161
1,338
<filename>src/bin/network/ftpd/extern.h /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)extern.h 8.2 (Berkeley) 4/4/94 * $FreeBSD: src/libexec/ftpd/extern.h,v 1.19 2002/02/04 01:23:44 kris Exp $ */ #include <sys/types.h> #include <sys/socket.h> void blkfree(char **); char **copyblk(char **); void cwd(char *); void delete(char *); void dologout(int); void fatalerror(char *); void ftpd_logwtmp(char *, char *, struct sockaddr *addr); int ftpd_pclose(FILE *); FILE *ftpd_popen(char *, char *); int *ftpd_getline(char *, int, FILE *); void lreply(int, const char *, ...) __printflike(2, 3); void makedir(char *); void nack(char *); void pass(char *); void passive(void); void long_passive(char *, int); void perror_reply(int, char *); void pwd(void); void removedir(char *); void renamecmd(char *, char *); char *renamefrom(char *); void reply(int, const char *, ...) __printflike(2, 3); void retrieve(char *, char *); void send_file_list(char *); void statcmd(void); void statfilecmd(char *); void store(char *, char *, int); void upper(char *); void user(char *); void yyerror(char *); int yyparse(void); int ls_main(int, char **); struct sockaddr_in; struct sockaddr_in6; union sockunion { struct sockinet { u_char si_len; u_char si_family; u_short si_port; } su_si; struct sockaddr_in su_sin; struct sockaddr_in6 su_sin6; }; #define su_len su_si.si_len #define su_family su_si.si_family #define su_port su_si.si_port
1,108
2,329
<filename>shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/cache/UpstreamCacheManager.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shenyu.loadbalancer.cache; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.collections4.CollectionUtils; import org.apache.shenyu.common.concurrent.ShenyuThreadFactory; import org.apache.shenyu.common.config.ShenyuConfig; import org.apache.shenyu.common.config.ShenyuConfig.UpstreamCheck; import org.apache.shenyu.common.utils.Singleton; import org.apache.shenyu.loadbalancer.entity.Upstream; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * this is upstream . */ public final class UpstreamCacheManager { private static final UpstreamCacheManager INSTANCE = new UpstreamCacheManager(); private static final Map<String, List<Upstream>> UPSTREAM_MAP = Maps.newConcurrentMap(); private UpstreamCheckTask task; /** * health check parameters. */ private Boolean checkEnable; private int checkTimeout; private int checkInterval; private int healthyThreshold; private int unhealthyThreshold; /** * healthy upstream print parameters. */ private Boolean printEnable; private Integer printInterval; private UpstreamCacheManager() { initHealthCheck(); } private void initHealthCheck() { ShenyuConfig shenyuConfig = Optional.ofNullable(Singleton.INST.get(ShenyuConfig.class)).orElse(new ShenyuConfig()); UpstreamCheck upstreamCheck = shenyuConfig.getUpstreamCheck(); checkEnable = upstreamCheck.getEnabled(); checkTimeout = upstreamCheck.getTimeout(); healthyThreshold = upstreamCheck.getHealthyThreshold(); unhealthyThreshold = upstreamCheck.getUnhealthyThreshold(); checkInterval = upstreamCheck.getInterval(); printEnable = upstreamCheck.getPrintEnabled(); printInterval = upstreamCheck.getPrintInterval(); createTask(); scheduleHealthCheck(); } private void createTask() { task = new UpstreamCheckTask(checkInterval); task.setCheckTimeout(checkTimeout); task.setHealthyThreshold(healthyThreshold); task.setUnhealthyThreshold(unhealthyThreshold); } private void scheduleHealthCheck() { if (checkEnable) { task.schedule(); // executor for log print if (printEnable) { ThreadFactory printFactory = ShenyuThreadFactory.create("upstream-health-print", true); new ScheduledThreadPoolExecutor(1, printFactory) .scheduleWithFixedDelay(task::print, printInterval, printInterval, TimeUnit.MILLISECONDS); } } } /** * Gets instance. * * @return the instance */ public static UpstreamCacheManager getInstance() { return INSTANCE; } /** * Find upstream list by selector id list. * * @param selectorId the selector id * @return the list */ public List<Upstream> findUpstreamListBySelectorId(final String selectorId) { return task.getHealthyUpstream().get(selectorId); } /** * Remove by key. * * @param key the key */ public void removeByKey(final String key) { UPSTREAM_MAP.remove(key); task.triggerRemoveAll(key); } /** * Submit. * * @param selectorId the selector id * @param upstreamList the upstream list */ public void submit(final String selectorId, final List<Upstream> upstreamList) { List<Upstream> validUpstreamList = upstreamList.stream().filter(upstream -> upstream.isStatus()).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(validUpstreamList)) { List<Upstream> existUpstream = UPSTREAM_MAP.computeIfAbsent(selectorId, k -> Lists.newArrayList()); existUpstream.stream().filter(upstream -> !validUpstreamList.contains(upstream)) .forEach(upstream -> task.triggerRemoveOne(selectorId, upstream)); validUpstreamList.stream().filter(upstream -> !existUpstream.contains(upstream)) .forEach(upstream -> task.triggerAddOne(selectorId, upstream)); UPSTREAM_MAP.put(selectorId, validUpstreamList); } else { UPSTREAM_MAP.remove(selectorId); task.triggerRemoveAll(selectorId); } } }
1,943
1,449
#include <QSharedPointer> #include <QStringList> #include "models/image.h" #include "tags/tag.h" #include "catch.h" #include "integration-helpers.h" TEST_CASE("Derpibooru") { SECTION("Html") { QList<QSharedPointer<Image>> images = getImages("Philomena", "derpibooru.org", "regex", "safe", "results.html"); // Convert results QList<qulonglong> ids; ids.reserve(images.count()); for (const auto &img : images) { ids.append(img->id()); } // Check results ids = ids.mid(0, 3); QList<qulonglong> expected = QList<qulonglong>() << 1752855 << 1752854 << 1752853; REQUIRE(images.count() == 15); REQUIRE(ids == expected); } SECTION("Json") { QList<QSharedPointer<Image>> images = getImages("Philomena", "derpibooru.org", "json", "safe", "results.json"); // Convert results QList<qulonglong> ids; ids.reserve(images.count()); for (const auto &img : images) { ids.append(img->id()); } // Check results ids = ids.mid(0, 3); QList<qulonglong> expected = QList<qulonglong>() << 2316404 << 2316401 << 2316400; REQUIRE(images.count() == 5); REQUIRE(ids == expected); } SECTION("HtmlTags") { QList<Tag> tags = getTags("Philomena", "derpibooru.org", "regex", "tags.html"); REQUIRE(tags.count() == 250); REQUIRE(tags[1].text() == QString("solo")); REQUIRE(tags[1].count() == 599506); REQUIRE(tags[1].type().isUnknown() == true); } SECTION("JsonTags") { QList<Tag> tags = getTags("Philomena", "derpibooru.org", "json", "tags.json"); REQUIRE(tags.count() == 10); REQUIRE(tags[1].id() == 42350); REQUIRE(tags[1].text() == QString("solo")); REQUIRE(tags[1].count() == 938816); REQUIRE(tags[1].type().isUnknown() == true); } }
720
3,503
<reponame>Puzer/SiamMask<filename>data/ytb_vos/download_from_gdrive.py<gh_stars>1000+ #!/usr/bin/env python from __future__ import print_function import argparse import os import os.path as osp import re import shutil import sys import tempfile import requests import six import tqdm # BORROWED FROM GDOWN CHUNK_SIZE = 512 * 1024 # 512KB def get_url_from_gdrive_confirmation(contents): url = '' for line in contents.splitlines(): m = re.search('href="(\/uc\?export=download[^"]+)', line) if m: url = 'https://docs.google.com' + m.groups()[0] url = url.replace('&amp;', '&') return url m = re.search('confirm=([^;&]+)', line) if m: confirm = m.groups()[0] url = re.sub(r'confirm=([^;&]+)', r'confirm='+confirm, url) return url m = re.search('"downloadUrl":"([^"]+)', line) if m: url = m.groups()[0] url = url.replace('\\u003d', '=') url = url.replace('\\u0026', '&') return url def is_google_drive_url(url): m = re.match('^https?://drive.google.com/uc\?id=.*$', url) return m is not None def download(url, output, quiet): url_origin = url sess = requests.session() is_gdrive = is_google_drive_url(url) while True: res = sess.get(url, stream=True) if 'Content-Disposition' in res.headers: # This is the file break if not is_gdrive: break # Need to redirect with confiramtion url = get_url_from_gdrive_confirmation(res.text) if url is None: print('Permission denied: %s' % url_origin, file=sys.stderr) print("Maybe you need to change permission over " "'Anyone with the link'?", file=sys.stderr) return if output is None: if is_gdrive: m = re.search('filename="(.*)"', res.headers['Content-Disposition']) output = m.groups()[0] else: output = osp.basename(url) output_is_path = isinstance(output, six.string_types) if not quiet: print('Downloading...', file=sys.stderr) print('From:', url_origin, file=sys.stderr) print('To:', osp.abspath(output) if output_is_path else output, file=sys.stderr) if output_is_path: tmp_file = tempfile.mktemp( suffix=tempfile.template, prefix=osp.basename(output), dir=osp.dirname(output), ) f = open(tmp_file, 'wb') else: tmp_file = None f = output try: total = res.headers.get('Content-Length') if total is not None: total = int(total) if not quiet: pbar = tqdm.tqdm(total=total, unit='B', unit_scale=True) for chunk in res.iter_content(chunk_size=CHUNK_SIZE): f.write(chunk) if not quiet: pbar.update(len(chunk)) if not quiet: pbar.close() if tmp_file: f.close() shutil.copy(tmp_file, output) except IOError as e: print(e, file=sys.stderr) return finally: try: if tmp_file: os.remove(tmp_file) except OSError: pass return output def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'url_or_id', help='url or file id (with --id) to download file from') parser.add_argument('-O', '--output', help='output filename') parser.add_argument('-q', '--quiet', action='store_true', help='suppress standard output') parser.add_argument('--id', action='store_true', help='flag to specify file id instead of url') args = parser.parse_args() print(args) if args.output == '-': if six.PY3: args.output = sys.stdout.buffer else: args.output = sys.stdout download(args.url_or_id, args.output, args.quiet) if __name__ == '__main__': main()
2,049
1,144
/* * FFmpegMediaPlayer: A unified interface for playing audio files and streams. * * Copyright 2016 <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. */ #ifndef _RMEDIAPLAYER_H_ #define _RMEDIAPLAYER_H_ #include <pthread.h> #include "Utils.h" #if ROKIDOS_FEATURES_HAS_EQ_CTRL #include <eq_ctrl/eq_ctrl.h> #else typedef enum { EQ_TYPE_INIT = 0, /* normal type*/ EQ_TYPE_DANCE, EQ_TYPE_JAZZ, EQ_TYPE_POP, EQ_TYPE_ROCK, EQ_TYPE_BALLED, EQ_TYPE_NOEQ, EQ_TYPE_LIGHT, EQ_TYPE_CLASSIC, EQ_TYPE_LOUD, EQ_TYPE_TEST, EQ_TYPE_NUM, }rk_eq_type_t; #endif struct RPlayer; typedef int status_t; /** * MediaPlayer listener. * */ class MediaPlayerListener { public: /** * notify from rplayer. * * @param msg * message type, valid type is defined in enum media_event_type in rk_ffplay.h. * * @param ext1 * extra message, for MEDIA_BLOCK_PAUSE_MODE means status of block pause mode * defined in enum block_pause_mode_status in rk_ffplay.h; for MEDIA_PLAYING_STATUS * means time interval; for MEDIA_ERROR means error type in Util.h. * * @param ext2 * extra message, for MEDIA_PLAYING_STATUS means decoded frame time. * * @param fromThread * from rplayer or not. * */ virtual void notify(int msg, int ext1, int ext2, int fromThread) = 0; }; class MediaPlayer { public: /** * Default MediaPlayer Construction. * */ MediaPlayer(); /** * Construct MediaPlayer with volume stream type name. * * @param mediaTag * volume stream type name, valid name includes "audio", "tts", "ring", "voiceCall", * "alarm", "playback", "system". */ MediaPlayer(const char *mediaTag); /** * Construct MediaPlayer with volume stream type name and block pause mode setting. * * @param mediaTag * volume stream type name, valid name includes "audio", "tts", "ring", "voiceCall", * "alarm", "playback", "system". * @param cacheDuration * the cache size under block pause mode, unit is second. * * @param cacheMode * enable/disable the block pause mode, default is false. */ MediaPlayer(const char *mediaTag, double cacheDuration, bool cacheMode = false); /** * Default MediaPlayer destruction. * */ ~MediaPlayer(); /** * Initialize rplayer. * * @deprecated */ static void globalInit(void); /** * Deinitialize rplayer. * * @deprecated */ static void globalUninit(void); /** * Stop rplayer. * * @deprecated */ void disconnect(); /** * Set data source for rplayer to play, should be called before prepare() or prepareAsync(). * * @param url * the data source path. * * @param headers * deprecated. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setDataSource(const char *url, const char *headers); /** * Set data source for rplayer to play, should be called before prepare() or prepareAsync(). * * @param url * the data source path. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setDataSource(const char *url); /** * Set MediaPlayer listener. * * @param listener * MediaPlayerListener realized by user. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setListener(MediaPlayerListener *listener); /** * Get MediaPlayer listener. * * @return MediaPlayerListener * return MediaPlayerListener. */ MediaPlayerListener *getListener(); /** * Enable display. * * @deprecated * unsupported. */ void enableDisplay(int enabled); /** * Set loop play mode. * * @param loop * > 0 : enable loop mode, <= 0 : disable loop mode. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setLooping(int loop); /** * Setup ffmpeg and sdl environment, synchronous interface. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t prepare(); /** * Setup ffmpeg and sdl environment, asynchronous interface. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t prepareAsync(); /** * Start to play. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t start(); /** * Stop playing, synchronous interface. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t stop(); /** * Stop playing, asynchronous interface. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t stopAsync(); /** * Pause playing. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t pause(); /** * Resume playing. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t resume(); /** * Check the playing status. * * @return bool * return the status, false : no playing, true : playing. */ bool isPlaying(); /** * Check the paused status. * * @return bool * return the status, false : no paused, true : paused. */ bool isPaused(); /** * Seek to specified playing position to play. * * @param msec * the new playing position, unit is ms. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t seekTo(int msec); /** * Get current playing position. * * @param msec * current playing position, unit is ms. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t getCurrentPosition(int *msec); /** * Get current playing position. * * @return long * return current playing position, unit is ms. */ long getCurrentPosition(void); /** * Get the total duration of current playing item. * * @param msec * duration, unit is ms. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t getDuration(int *msec); /** * Get the total duration of current playing item. * * @return long * return duration, unit is ms. */ long getDuration(void); /** * Reset the rplayer status, should be called after stop() or stopAsync(). * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t reset(); /** * Set audio stream type. * * @deprecated */ status_t setAudioStreamType(int type); /** * Check the loop mode. * * @return bool * return the status, false : loop mode is off, true : loop mode is on. */ bool isLooping(); /** * Set volume. * * @param leftVolume * volume, 0~100. * * @param rightVolume * volume, 0~100, useless. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setVolume(float leftVolume, float rightVolume); /** * Set volume. * * @param volume * volume, 0~100. * * @return long * return the volume. */ int setVolume(int volume); /** * Get volume. * * @return int * return the volume, 0~100. */ int getVolume(void); /** * Set audio session id. * * @deprecated */ status_t setAudioSessionId(int sessionId); /** * Get audio session id. * * @deprecated */ int getAudioSessionId(); /** * Set aux effect level. * * @deprecated */ status_t setAuxEffectSendLevel(float level); /** * Attach aux effect. * * @deprecated */ int attachAuxEffect(int effectId); /** * Set next MediaPlayer. * * @deprecated */ status_t setNextMediaPlayer(const MediaPlayer *player); /** * Get video width. * * @deprecated */ status_t getVideoWidth(int *w); /** * Get video height. * * @deprecated */ status_t getVideoHeight(int *h); /** * notify from rplayer. * * @param msg * message type, valid type is defined in enum media_event_type in rk_ffplay.h. * * @param ext1 * extra message, for MEDIA_BLOCK_PAUSE_MODE means status of block pause mode * defined in enum block_pause_mode_status in rk_ffplay.h; for MEDIA_PLAYING_STATUS * means time interval. * * @param ext2 * extra message, for MEDIA_PLAYING_STATUS means decoded frame time. * * @param fromThread * from rplayer or not. * */ void notify(int msg, int ext1, int ext, int fromThread); /** * Set the tcp receiving buffer size during playing online music, * should be called before prepare() or perpareAsync(). * * @param size * cache size, unit is Byte, default is 20480Byte. * */ void setRecvBufSize(int size); /** * Enable block pause mode. * * @param enabled * enable/disable block pause mode. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t enableCacheMode(bool enabled); /** * Set the playback speed. * * @param tempoDelta * playback speed, -50.0~100.0 means 0.5~2 speed. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setTempoDelta(float tempoDelta); /** * Enable reconnection at end of playing item, should be called before prepare() or perpareAsync(). * * @param enabled * enable/disable reconnection. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t enableReconnectAtEOF(int enabled); /** * Set max delay time of reconnection, if delay time exceeds this time, rplayer will report media error. Should be * called before prepare() or perpareAsync(). * * @param seconds * max delay time of reconnection, unit is second, default is 120s. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setReconnectDelayMax(int seconds); /** * Set eq mode, defined in enum rk_eq_type_t in eq_ctrl.h. * * @param type * eq mode. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t setEqMode(rk_eq_type_t type); /** * Get current eq mode, defined in enum rk_eq_type_t in eq_ctrl.h. * * @param type * eq mode. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t getCurEqMode(rk_eq_type_t *type); /** * Get supported eq mode. * * @param atype * supported eq array. * * @return int * return supported eq count. */ static int getSupporteqMode(rk_eq_type_t **atype); private: /** Pointer to internal RPlayer */ RPlayer *mPlayer; /** current eq mode */ rk_eq_type_t mCurEQType; /** * Clear. * * @deprecated */ void clear_l(); /** * Seek to specified playing position to play. * * @param msec * the new playing position, unit is ms. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t seekTo_l(int msec); /** * Setup ffmpeg and sdl environment, asynchronous interface. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t prepareAsync_l(); /** * Get the total duration of current playing item. * * @param msec * duration, unit is ms. * * @return status_t * return the status, 0 : success, < 0 : failure. */ status_t getDuration_l(int *msec); /** * Set data source for rplayer to play. * * @deprecated */ status_t setDataSource(RPlayer *state); /** Pointer to MediaPlayer listener */ MediaPlayerListener *mListener; /** Pointer to data source path */ char *mUrl; }; #endif // _RMEDIAPLAYER_H_
5,921
422
/* Challenge Activity 1 - Circle Class * * In this challenge activity, I've created the main routine which uses a circle * class. you must complete the implementation of the class by wirting the methods * * PROGRAM OUTPUT: * C1 ==> Radius : 9.000000; Area : 254.469005; Circumference : 56.548668 * C2 ==> Radius : 4.000000; Area : 50.265482; Circumference : 25.132741 */ package circleclass; public class CircleClass { public static void main(String[] args) { Circle c1 = new Circle(9); Circle c2 = new Circle(); c2.setRadius(4); System.out.printf("C1 ==> Radius : %f; Area : %f; Circumference : %f\n" ,c1.getRadius(),c1.area(), c1.circ()); System.out.printf("C2 ==> Radius : %f; Area : %f; Circumference : %f\n" ,c2.getRadius(),c2.area(), c2.circ()); } }
337
6,036
<gh_stars>1000+ #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. #-------------------------------------------------------------------------- import numpy as np from logging import getLogger from onnx import helper, numpy_helper, TensorProto from onnx_model import OnnxModel from fusion_base import Fusion from fusion_utils import FusionUtils logger = getLogger(__name__) class FusionGptAttentionPastBase(Fusion): """Base class for GPT Attention Fusion with past state """ def __init__(self, model: OnnxModel, num_heads: int): super().__init__(model, "Attention", "LayerNormalization", "with past") self.num_heads = num_heads self.utils = FusionUtils(model) self.casted_attention_mask = {} # map from name of attention mask to the name that casted to int32 def match_past_pattern_1(self, concat_k, concat_v, output_name_to_node): # Pattern 1: # {past} # / \ # / \ # Gather(axes=0, indices=0) Gather(indices=1) # | | # Transpose (perm=0,1,3,2) | # | | # Concat_k Concat_v # | / # Transpose (perm=0,1,3,2) / # | / # Unsqueeze Unsqueeze # \ / # \ / # Concat # | # {present} gather = self.model.get_parent(concat_v, 0, output_name_to_node) if gather.op_type != 'Gather': logger.debug("match_past_pattern_1: expect Gather for past") return None if not self.model.find_constant_input(gather, 1) == 1: logger.debug("match_past_pattern_1: expect indices=1 for Gather of past") return None past = gather.input[0] past_k_nodes = self.model.match_parent_path(concat_k, ['Transpose', 'Gather'], [0, 0]) if past_k_nodes is None: logger.debug("match_past_pattern_1: failed match Transpose and Gather") return None gather_past_k = past_k_nodes[-1] if not self.model.find_constant_input(gather_past_k, 0) == 1: logger.debug("match_past_pattern_1: expect indices=0 for Gather k of past") return None past_k = gather_past_k.input[0] if past != past_k: logger.debug("match_past_pattern_1: expect past to be same") return None return past def match_past_pattern_2(self, concat_k, concat_v, output_name_to_node): # Pattern 2: # Split (QKV) # / | | # / | +----------------------+ # | | # | {past} | # | | | # Reshape Split Reshape # | / \ | # Transpose_k Squeeze Squeeze Transpose_v # | | \ / # +------|---+ \ / # | | \ / # Concat_k Concat_v # | | # Unsqueeze Unsqueeze # \ / # Concat # | # {present} # squeeze = self.model.get_parent(concat_v, 0, output_name_to_node) if squeeze.op_type != 'Squeeze': logger.debug("match_past_pattern_2: expect Squeeze as parent of concat_v") return None split = self.model.get_parent(squeeze, 0, output_name_to_node) if split.op_type != "Split": logger.debug("match_past_pattern_2: expect Split for past path") return None opset_version = self.model.get_opset_version() if opset_version < 13: if not FusionUtils.check_node_attribute(squeeze, 'axes', [0]): logger.debug("match_past_pattern_2: axes != [0] for Squeeze in past path") return None if not FusionUtils.check_node_attribute(split, 'split', [1, 1]): logger.debug("match_past_pattern_2: split != [1, 1] for Split in past path") return None else: if not self.utils.check_node_input_value(squeeze, 1, [0]): logger.debug("match_past_pattern_2: axes != [0] for Squeeze in past path") return None if not self.utils.check_node_input_value(split, 1, [1, 1]): logger.debug("match_past_pattern_2: split != [1, 1] for Split in past path") return None if not FusionUtils.check_node_attribute(split, 'axis', 0, default_value=0): logger.debug("match_past_pattern_2: attribute axis of Split are not expected in past path") return None past = split.input[0] past_k_nodes = self.model.match_parent_path(concat_k, ['Squeeze', 'Split'], [0, 0]) if past_k_nodes is None: logger.debug("match_past_pattern_2: failed to match past_k_nodes path") return None past_k = past_k_nodes[-1].input[0] if past != past_k: logger.info("match_past_pattern_2: expect past to be same") return None return past def match_present(self, concat_v, input_name_to_nodes): unsqueeze_present_v = self.model.find_first_child_by_type(concat_v, 'Unsqueeze', input_name_to_nodes, recursive=False) if not unsqueeze_present_v: logger.info("expect unsqueeze for present") return None concat_present = self.model.find_first_child_by_type(unsqueeze_present_v, 'Concat', input_name_to_nodes, recursive=False) if not concat_present: logger.info("expect concat for present") return None present = concat_present.output[0] return present def cast_attention_mask(self, input_name): if input_name in self.casted_attention_mask: attention_mask_input_name = self.casted_attention_mask[input_name] elif self.model.find_graph_input(input_name): casted, attention_mask_input_name = self.utils.cast_graph_input_to_int32(input_name) self.casted_attention_mask[input_name] = attention_mask_input_name else: attention_mask_input_name, cast_node = self.utils.cast_input_to_int32(input_name) self.casted_attention_mask[input_name] = attention_mask_input_name return attention_mask_input_name class FusionGptAttention(FusionGptAttentionPastBase): """ Fuse GPT-2 Attention with past state subgraph into one Attention node. """ def __init__(self, model: OnnxModel, num_heads: int): super().__init__(model, num_heads) def create_attention_node(self, fc_weight, fc_bias, gemm_qkv, past, present, input, output, mask, is_unidirectional): attention_node_name = self.model.create_node_name('GptAttention') attention_node = helper.make_node('Attention', inputs=[input, fc_weight, fc_bias, mask, past], outputs=[attention_node_name + "_output", present], name=attention_node_name) attention_node.domain = "com.microsoft" attention_node.attribute.extend([ helper.make_attribute("num_heads", self.num_heads), helper.make_attribute("unidirectional", 1 if is_unidirectional else 0) ]) matmul_node = helper.make_node('MatMul', inputs=[attention_node_name + "_output", gemm_qkv.input[1]], outputs=[attention_node_name + "_matmul_output"], name=attention_node_name + "_matmul") add_node = helper.make_node('Add', inputs=[attention_node_name + "_matmul_output", gemm_qkv.input[2]], outputs=[output], name=attention_node_name + "_add") self.nodes_to_add.extend([attention_node, matmul_node, add_node]) self.node_name_to_graph_name[attention_node.name] = self.this_graph_name self.node_name_to_graph_name[matmul_node.name] = self.this_graph_name self.node_name_to_graph_name[add_node.name] = self.this_graph_name def fuse(self, normalize_node, input_name_to_nodes, output_name_to_node): past = None present = None return_indice = [] qkv_nodes = self.model.match_parent_path( normalize_node, ['Add', 'Reshape', 'Gemm', 'Reshape', 'Reshape', 'Transpose', 'MatMul'], [0, None, 0, 0, 0, 0, 0], output_name_to_node=output_name_to_node, return_indice=return_indice ) # yapf: disable if qkv_nodes is None: return (add_qkv, reshape_qkv, gemm_qkv, reshape_1, reshape_2, transpose_qkv, matmul_qkv) = qkv_nodes another_input = add_qkv.input[1 - return_indice[0]] v_nodes = self.model.match_parent_path(matmul_qkv, ['Concat', 'Transpose', 'Reshape', 'Split'], [1, 1, 0, 0]) if v_nodes is None: logger.debug("fuse_attention: failed to match v path") return (concat_v, transpose_v, reshape_v, split_fc) = v_nodes fc_nodes = self.model.match_parent_path(split_fc, ['Reshape', 'Gemm', 'Reshape', 'LayerNormalization'], [0, 0, 0, 0], output_name_to_node) if fc_nodes is None: fc_nodes = self.model.match_parent_path(split_fc, ['Add', 'MatMul', 'LayerNormalization'], [0, None, 0], output_name_to_node) if fc_nodes is None: logger.debug("fuse_attention: failed to match fc path") return fc_weight = fc_nodes[1].input[1] i, _ = self.model.get_constant_input(fc_nodes[0]) fc_bias = fc_nodes[0].input[i] else: fc_weight = fc_nodes[1].input[1] fc_bias = fc_nodes[1].input[2] layernorm_before_attention = fc_nodes[-1] if not another_input in layernorm_before_attention.input: logger.debug("Add and LayerNormalization shall have one same input") return is_unidirectional = True slice_mask = None input_mask_nodes = None concat_k_to_match = None qk_nodes = self.model.match_parent_path(matmul_qkv, ['Softmax', 'Sub', 'Mul', 'Div', 'MatMul'], [0, 0, 0, 0, 0]) if qk_nodes is not None: (softmax_qk, sub_qk, mul_qk, div_qk, matmul_qk) = qk_nodes mask_nodes = self.model.match_parent_path( sub_qk, ['Mul', 'Sub', 'Slice', 'Slice', 'Unsqueeze', 'Sub', 'Squeeze', 'Slice', 'Shape', 'Div'], [1, 0, 1, 0, 1, 0, 0, 0, 0, 0]) # yapf: disable if mask_nodes is None: logger.debug("fuse_attention: failed to match unidirectional mask path") return div_mask = mask_nodes[-1] slice_mask = mask_nodes[3] if div_qk != div_mask: logger.debug("fuse_attention: skip since div_qk != div_mask") return else: # New pattern for gpt2 from PyTorch 1.5.0 and Transformers 2.9.0. i, qk_nodes, _ = self.model.match_parent_paths( matmul_qkv, [(['Softmax', 'Where', 'Div', 'MatMul'], [0, 0, 1, 0]), (['Softmax', 'Add', 'Where', 'Div', 'MatMul'], [0, 0, None, 1, 0])], output_name_to_node) if qk_nodes is None: logger.debug("fuse_attention: failed to match qk nodes") return where_qk = qk_nodes[-3] div_qk = qk_nodes[-2] matmul_qk = qk_nodes[-1] if i == 1: add_qk = qk_nodes[1] _, input_mask_nodes, _ = self.model.match_parent_paths( add_qk, [ (['Mul', 'Sub', 'Cast', 'Unsqueeze', 'Unsqueeze', 'Reshape'], [None, 0, 1, 0, 0, 0]), (['Mul', 'Sub', 'Unsqueeze', 'Unsqueeze', 'Reshape'], [None, 0, 1, 0, 0]), (['Mul', 'Sub', 'Unsqueeze', 'Unsqueeze'], [None, 0, 1, 0]), # useless cast and reshape are removed. ], output_name_to_node) # yapf: disable if input_mask_nodes is None: logger.debug("fuse_attention: failed to match input attention mask path") return mask_nodes = self.model.match_parent_path( where_qk, ['Cast', 'Slice', 'Slice', 'Unsqueeze', 'Sub', 'Squeeze', 'Slice', 'Shape'], [ 0, 0, 0, 1, 0, 0, 0, 0], output_name_to_node) # yapf: disable if mask_nodes is None: # TODO: match mask path for GPT2LMHeadModel_BeamSearchStep. logger.debug("fuse_attention: failed to match mask path") return slice_mask = mask_nodes[2] div_or_concat = self.model.get_parent(mask_nodes[-1], 0, output_name_to_node) if div_or_concat.op_type == "Div": div_mask = div_or_concat if div_qk != div_mask: logger.debug("fuse_attention: skip since div_qk != div_mask") return elif div_or_concat.op_type == "Concat": concat_k_to_match = div_or_concat else: logger.debug("fuse_attention: failed to match mask path") # Validate that the mask data is either lower triangular (unidirectional) or all ones mask_data = numpy_helper.to_array(self.model.get_initializer(slice_mask.input[0])) if not (len(mask_data.shape) == 4 and mask_data.shape[:2] == (1, 1) and mask_data.shape[2] == mask_data.shape[3]): logger.debug("fuse_attention: skip since mask shape is not 1x1xWxW") return if np.allclose(mask_data, np.ones_like(mask_data)): is_unidirectional = False elif not np.allclose(mask_data, np.tril(np.ones_like(mask_data))): logger.debug("fuse_attention: skip since mask is neither lower triangular nor ones") return q_nodes = self.model.match_parent_path(matmul_qk, ['Transpose', 'Reshape', 'Split'], [0, 0, 0]) if q_nodes is None: logger.debug("fuse_attention: failed to match q path") return (transpose_q, reshape_q, split_q) = q_nodes if split_fc != split_q: logger.debug("fuse_attention: skip since split_fc != split_q") return k_nodes = self.model.match_parent_path(matmul_qk, ['Concat', 'Transpose', 'Reshape', 'Split'], [1, 1, 0, 0]) if k_nodes is None: # This pattern is from pytorch 1.7.1 and transformers 4.6.1 k_nodes = self.model.match_parent_path(matmul_qk, ['Transpose', 'Concat', 'Transpose', 'Reshape', 'Split'], [1, 0, 1, 0, 0]) if k_nodes is None: logger.debug("fuse_attention: failed to match k path") return else: (_, concat_k, transpose_k, reshape_k, split_k) = k_nodes else: (concat_k, transpose_k, reshape_k, split_k) = k_nodes if split_fc != split_k: logger.debug("fuse_attention: skip since split_fc != split_k") return if concat_k_to_match and concat_k != concat_k_to_match: logger.debug("fuse_attention: skip since concat_k != concat_k_to_match") return attention_mask_input_name = '' if input_mask_nodes is not None: input_name = input_mask_nodes[-1].input[0] attention_mask_input_name = self.cast_attention_mask(input_name) # Match past and present paths past = self.match_past_pattern_1(concat_k, concat_v, output_name_to_node) or \ self.match_past_pattern_2(concat_k, concat_v, output_name_to_node) if past is None: logger.info("fuse_attention: failed to match past path") return if not self.model.find_graph_input(past): logger.debug("past is not graph input.") # For GPT2LMHeadModel_BeamSearchStep, there is an extra Gather node to select beam index so it is not graph input. present = self.match_present(concat_v, input_name_to_nodes) if present is None: logger.info("fuse_attention: failed to match present path") return if not self.model.find_graph_output(present): logger.info("expect present to be graph output") return self.create_attention_node(fc_weight, fc_bias, gemm_qkv, past, present, layernorm_before_attention.output[0], reshape_qkv.output[0], attention_mask_input_name, is_unidirectional) # we rely on prune_graph() to clean old subgraph nodes: # qk_nodes + q_nodes + k_nodes + v_nodes + mask_nodes + [reshape_qkv, transpose_qkv, matmul_qkv] self.prune_graph = True
9,755
364
/* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.ui.base.dialog; import android.app.Activity; import android.app.Dialog; import android.graphics.Rect; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import net.bither.R; import net.bither.bitherj.AbstractApp; import net.bither.bitherj.BitherjSettings; import net.bither.bitherj.crypto.PasswordSeed; import net.bither.bitherj.crypto.SecureCharSequence; import net.bither.bitherj.runnable.EditPasswordThread; import net.bither.bitherj.utils.Utils; import net.bither.model.Check; import net.bither.preference.AppSharedPreference; import net.bither.ui.base.DropdownMessage; import net.bither.ui.base.keyboard.password.PasswordEntryKeyboardView; import net.bither.util.BackupUtil; import net.bither.util.CheckUtil; import net.bither.util.PasswordStrengthUtil; import net.bither.util.ThreadUtil; import net.bither.util.UIUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ExecutorService; public class DialogEditPassword extends Dialog implements Check.CheckListener, Check.ICheckAction, View.OnClickListener, EditPasswordThread.EditPasswordListener, TextView.OnEditorActionListener { private Activity activity; private View container; private LinearLayout llInput; private LinearLayout llEditing; private TextView tvError; private EditText etOldPassword; private EditText etNewPassword; private EditText etNewPasswordConfirm; private TextView tvPasswordStrength; private FrameLayout flPasswordStrength; private FrameLayout flPasswordStrengthContainer; private ProgressBar pbPasswordStrength; private Button btnOk; private PasswordEntryKeyboardView kv; private PasswordSeed passwordSeed; private Check passwordCheck = new Check("", this); private ExecutorService executor; public DialogEditPassword(Activity context) { super(context, R.style.password_dialog); activity = context; setContentView(R.layout.dialog_edit_password); setCanceledOnTouchOutside(false); setCancelable(false); passwordSeed = getPasswordSeed(); initView(); } private PasswordSeed getPasswordSeed() { return PasswordSeed.getPasswordSeed(); } private void initView() { container = findViewById(R.id.fl_container); llInput = (LinearLayout) findViewById(R.id.ll_input); llEditing = (LinearLayout) findViewById(R.id.ll_editing); tvError = (TextView) findViewById(R.id.tv_error); etOldPassword = (EditText) findViewById(R.id.et_old_password); etNewPassword = (EditText) findViewById(R.id.et_new_password); etNewPasswordConfirm = (EditText) findViewById(R.id.et_new_password_confirm); btnOk = (Button) findViewById(R.id.btn_ok); tvPasswordStrength = (TextView) findViewById(R.id.tv_password_strength); pbPasswordStrength = (ProgressBar) findViewById(R.id.pb_password_strength); flPasswordStrength = (FrameLayout) findViewById(R.id.fl_password_strength); flPasswordStrengthContainer = (FrameLayout) findViewById(R.id .fl_password_strength_container); kv = (PasswordEntryKeyboardView) findViewById(R.id.kv); PasswordWatcher watcher = new PasswordWatcher(); etOldPassword.addTextChangedListener(watcher); etNewPassword.addTextChangedListener(watcher); etNewPasswordConfirm.addTextChangedListener(watcher); btnOk.setOnClickListener(this); findViewById(R.id.btn_cancel).setOnClickListener(this); btnOk.setEnabled(false); passwordCheck.setCheckListener(this); etOldPassword.setImeActionLabel(null, EditorInfo.IME_ACTION_NEXT); etNewPassword.setImeActionLabel(null, EditorInfo.IME_ACTION_NEXT); etNewPasswordConfirm.setImeActionLabel(null, EditorInfo.IME_ACTION_DONE); etNewPasswordConfirm.setOnEditorActionListener(this); kv.registerEditText(etOldPassword, etNewPassword, etNewPasswordConfirm); } @Override public void show() { if (passwordSeed != null) { super.show(); } else if (activity != null) { DropdownMessage.showDropdownMessage(activity, R.string.private_key_is_empty); } } @Override public void onClick(View v) { if (v.getId() == R.id.btn_ok) { SecureCharSequence oldP = new SecureCharSequence(etOldPassword.getText()); SecureCharSequence newP = new SecureCharSequence(etNewPassword.getText()); SecureCharSequence newCP = new SecureCharSequence(etNewPasswordConfirm.getText()); if (!newP.equals(newCP)) { shake(); tvError.setText(R.string.add_address_generate_address_password_not_same); tvError.setVisibility(View.VISIBLE); etNewPasswordConfirm.requestFocus(); oldP.wipe(); newP.wipe(); newCP.wipe(); return; } if (oldP.equals(newP)) { shake(); tvError.setText(R.string.edit_password_new_old_same); tvError.setVisibility(View.VISIBLE); etNewPasswordConfirm.requestFocus(); oldP.wipe(); newP.wipe(); newCP.wipe(); return; } if (AppSharedPreference.getInstance().getPasswordStrengthCheck()) { PasswordStrengthUtil.PasswordStrength strength = PasswordStrengthUtil .checkPassword(newP); oldP.wipe(); newP.wipe(); newCP.wipe(); if (!strength.passed()) { etNewPassword.requestFocus(); shakeStrength(); return; } if (strength.warning()) { new DialogConfirmTask(getContext(), String.format(getContext().getString(R .string.password_strength_warning), strength.getName()), new Runnable () { @Override public void run() { executor = CheckUtil.runChecks(Arrays.asList(new Check[]{passwordCheck}), 1); } }).show(); return; } } oldP.wipe(); newP.wipe(); newCP.wipe(); if (passwordSeed != null) { ArrayList<Check> checks = new ArrayList<Check>(); checks.add(passwordCheck); executor = CheckUtil.runChecks(checks, 1); } else { dismiss(); } } else { dismiss(); } } private void shake() { Animation shake = AnimationUtils.loadAnimation(getContext(), R.anim.password_wrong_warning); container.startAnimation(shake); } private void shakeStrength() { Animation shake = AnimationUtils.loadAnimation(getContext(), R.anim.password_wrong_warning); flPasswordStrength.startAnimation(shake); } @Override public boolean check() { if (passwordSeed != null) { SecureCharSequence password = new SecureCharSequence(etOldPassword.getText()); boolean result = passwordSeed.checkPassword(password); password.wipe(); return result; } else { return true; } } @Override public void onCheckBegin(Check check) { llEditing.setVisibility(View.VISIBLE); llInput.setVisibility(View.INVISIBLE); kv.hideKeyboard(); } @Override public void onCheckEnd(Check check, boolean success) { if (executor != null) { executor.shutdown(); executor = null; } if (success) { editPassword(); } else { llEditing.setVisibility(View.GONE); llInput.setVisibility(View.VISIBLE); etOldPassword.setText(""); checkValid(); tvError.setText(R.string.password_wrong); tvError.setVisibility(View.VISIBLE); shake(); kv.showKeyboard(); } } private void editPassword() { new EditPasswordThread(new SecureCharSequence(etOldPassword.getText()), new SecureCharSequence(etNewPassword.getText()), this).start(); } private void checkValid() { btnOk.setEnabled(false); int passwordOldLength = etOldPassword.length(); int passwordLength = etNewPassword.length(); if (passwordOldLength >= 6 && passwordOldLength <= getContext().getResources().getInteger (R.integer.password_length_max)) { if (passwordLength >= 6 && passwordLength <= getContext().getResources().getInteger(R .integer.password_length_max)) { int passwordConfirmLength = etNewPasswordConfirm.length(); if (passwordConfirmLength >= 6 && passwordConfirmLength <= getContext() .getResources().getInteger(R.integer.password_length_max)) { btnOk.setEnabled(true); } } } if (passwordLength > 0) { ViewGroup.LayoutParams lp = flPasswordStrengthContainer.getLayoutParams(); if (lp.height < etNewPassword.getHeight() + flPasswordStrength.getHeight() + UIUtil .dip2pix(5)) { lp.height = etNewPassword.getHeight() + flPasswordStrength.getHeight() + UIUtil .dip2pix(5); flPasswordStrengthContainer.requestLayout(); } flPasswordStrength.setVisibility(View.VISIBLE); PasswordStrengthUtil.PasswordStrength strength = PasswordStrengthUtil.checkPassword (etNewPassword.getText()); if (pbPasswordStrength.getProgress() != strength.getProgress()) { Rect bounds = pbPasswordStrength.getProgressDrawable().getBounds(); pbPasswordStrength.setProgressDrawable(strength.getDrawable()); pbPasswordStrength.getProgressDrawable().setBounds(bounds); pbPasswordStrength.setProgress(strength.getProgress()); tvPasswordStrength.setText(strength.getNameRes()); } } else { ViewGroup.LayoutParams lp = flPasswordStrengthContainer.getLayoutParams(); if (lp.height > etNewPassword.getHeight() + UIUtil.dip2pix(5)) { lp.height = etNewPassword.getHeight() + UIUtil.dip2pix(5); flPasswordStrengthContainer.requestLayout(); } flPasswordStrength.setVisibility(View.INVISIBLE); } } @Override public void onSuccess() { ThreadUtil.runOnMainThread(new Runnable() { @Override public void run() { dismiss(); DropdownMessage.showDropdownMessage(activity, R.string.edit_password_success); new Thread(new Runnable() { @Override public void run() { if (AbstractApp.bitherjSetting.getAppMode() == BitherjSettings.AppMode.COLD) { BackupUtil.backupColdKey(false); } else { BackupUtil.backupHotKey(); } } }).start(); } }); } @Override public void onFailed() { ThreadUtil.runOnMainThread(new Runnable() { @Override public void run() { dismiss(); DropdownMessage.showDropdownMessage(activity, R.string.edit_password_fail); } }); } @Override public void dismiss() { super.dismiss(); etOldPassword.setText(""); etNewPassword.setText(""); etNewPasswordConfirm.setText(""); } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (v == etNewPasswordConfirm && btnOk.isEnabled()) { onClick(btnOk); return true; } return false; } private class PasswordWatcher implements TextWatcher { private SecureCharSequence passwordOld; private SecureCharSequence passwordNew; private SecureCharSequence passwordNewConfirm; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (passwordOld != null) { passwordOld.wipe(); } if (passwordNew != null) { passwordNew.wipe(); } if (passwordNewConfirm != null) { passwordNewConfirm.wipe(); } passwordOld = new SecureCharSequence(etOldPassword.getText()); passwordNew = new SecureCharSequence(etNewPassword.getText()); passwordNewConfirm = new SecureCharSequence(etNewPasswordConfirm.getText()); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { tvError.setVisibility(View.GONE); SecureCharSequence p = new SecureCharSequence(etNewPassword.getText()); if (p.length() > 0) { if (!Utils.validPassword(p)) { etNewPassword.setText(passwordNew); } } p.wipe(); SecureCharSequence pc = new SecureCharSequence(etNewPasswordConfirm.getText()); if (pc.length() > 0) { if (!Utils.validPassword(pc)) { etNewPasswordConfirm.setText(passwordNewConfirm); } } pc.wipe(); SecureCharSequence po = new SecureCharSequence(etOldPassword.getText()); if (po.length() > 0) { if (!Utils.validPassword(po)) { etOldPassword.setText(passwordOld); } } po.wipe(); checkValid(); passwordOld.wipe(); passwordNew.wipe(); passwordNewConfirm.wipe(); } } }
6,992
118,175
<filename>android/ReactCommon/react/renderer/components/text/RawTextShadowNode.h /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <react/renderer/components/text/RawTextProps.h> #include <react/renderer/core/ConcreteShadowNode.h> namespace facebook { namespace react { extern const char RawTextComponentName[]; /* * `ShadowNode` for <RawText> component, represents a purely regular string * object in React. In a code fragment `<Text>Hello!</Text>`, "Hello!" part * is represented as `<RawText text="Hello!"/>`. * <RawText> component must not have any children. */ class RawTextShadowNode : public ConcreteShadowNode< RawTextComponentName, ShadowNode, RawTextProps> { public: using ConcreteShadowNode::ConcreteShadowNode; static ShadowNodeTraits BaseTraits() { auto traits = ConcreteShadowNode::BaseTraits(); traits.set(ShadowNodeTraits::Trait::RawText); return traits; } }; template <> inline RawTextShadowNode const &traitCast<RawTextShadowNode const &>( ShadowNode const &shadowNode) { bool castable = shadowNode.getTraits().check(ShadowNodeTraits::Trait::RawText); react_native_assert(castable); (void)castable; return static_cast<RawTextShadowNode const &>(shadowNode); } template <> inline RawTextShadowNode const *traitCast<RawTextShadowNode const *>( ShadowNode const *shadowNode) { if (!shadowNode) { return nullptr; } bool castable = shadowNode->getTraits().check(ShadowNodeTraits::Trait::RawText); if (!castable) { return nullptr; } return static_cast<RawTextShadowNode const *>(shadowNode); } } // namespace react } // namespace facebook
653
337
import base64 import os import re import time from threading import Thread import serial from src.utility.settings import Settings from src.connection.connection import Connection from src.helpers.pyinstaller_helper import PyInstallerHelper from src.logic.file_transfer import FileTransfer, FileTransferError from src.utility.exceptions import OperationError class SerialConnection(Connection): def __init__(self, port, baud_rate, terminal=None, reset=False): Connection.__init__(self, terminal) self._port = port self._baud_rate = baud_rate try: self._serial = serial.Serial(None, self._baud_rate, timeout=0, write_timeout=0.2) self._serial.dtr = False self._serial.rts = False self._serial.port = port self._serial.open() kill_and_wait = not reset if reset: self._serial.rts = True time.sleep(0.1) self._serial.rts = False try: # Give board time to reset (10 seconds should be enough) self.read_to_next_prompt(10) except TimeoutError: # If we still get time out, a script was probably # started automatically and needs to be killed kill_and_wait = True if kill_and_wait: self.send_kill() self.read_to_next_prompt() except (OSError, serial.SerialException) as e: self._serial = None return except Exception as e: return self._reader_thread = Thread(target=self._reader_thread_routine) self._reader_thread.start() def is_connected(self): return self._serial is not None def disconnect(self): if self.is_connected(): if self._reader_thread.is_alive(): self._reader_running = False self._reader_thread.join() self._serial.close() self._serial = None def send_line(self, line_text, ending="\r\n"): assert isinstance(line_text, str) assert isinstance(ending, str) self._serial.write((line_text + ending).encode('utf-8')) self._serial.flush() time.sleep(Settings().send_sleep) def send_character(self, char): assert isinstance(char, str) self._serial.write(char.encode('utf-8')) time.sleep(Settings().send_sleep) def send_bytes(self, binary): self._serial.write(binary) time.sleep(Settings().send_sleep) def read_line(self): x = self._serial.readline() if x and self._terminal is not None: if x == b'\x08\x1b[K': x = b'\x08' self._terminal.add(x.decode("utf-8", errors="replace")) return x def _break_device_read(self): time.sleep(1) self.send_kill() def read_with_timeout(self, count, timeout_s=2.0): period = 0.005 data = bytearray() for i in range(0, int(timeout_s / period)): rec = self._serial.read(count - len(data)) if rec: data.extend(rec) if len(data) == count: return bytes(data) time.sleep(period) return None def read_all(self): buffer = "" while True: x = self._serial.read(100) if x is None or not x: break buffer += x.decode('utf-8', errors="replace") if self._terminal is not None: self._terminal.add(buffer) return buffer def read_junk(self): self.read_all() def read_one_byte(self): return self._serial.read(1) @staticmethod def escape_characters(text): ret = "" for c in text: if c == "\n": ret += "\\n" elif c == "\"": ret += "\\\"" else: ret += c return ret def check_transfer_scripts_version(self): self._auto_reader_lock.acquire() self._auto_read_enabled = False self.send_kill() self.read_junk() self.send_block("with open(\"__upload.py\") as f:\n f.readline()\n") self._serial.flush() success = True try: resp = self.read_to_next_prompt() idx = resp.find("#V") if idx < 0 or resp[idx:idx+3] != "#V2": raise ValueError self.read_junk() self.send_block("with open(\"__download.py\") as f:\n f.readline()\n") self._serial.flush() resp = self.read_to_next_prompt() idx = resp.find("#V") if idx < 0 or resp[idx:idx+3] != "#V2": raise ValueError except (TimeoutError, ValueError): success = False self._auto_read_enabled = True self._auto_reader_lock.release() return success @staticmethod def _transfer_file_path(transfer_file_name): # External transfer scripts folder should be used (use case: files need to be edited) if Settings().use_custom_transfer_scripts: path = "".join([Settings().external_transfer_scripts_folder, "/", transfer_file_name]) # Check if file exists. if os.path.isfile(path): return path else: raise FileNotFoundError return PyInstallerHelper.resource_path("mcu/" + transfer_file_name) def send_upload_file(self, file_name): with open(SerialConnection._transfer_file_path("upload.py")) as f: data = f.read() data = data.replace("file_name.py", file_name) self.send_start_paste() lines = data.split("\n") for line in lines: self.send_line(line, "\r") self.send_end_paste() def send_download_file(self, file_name): with open(SerialConnection._transfer_file_path("download.py")) as f: data = f.read() data = data.replace("file_name.py", file_name) self.send_start_paste() lines = data.split("\n") for line in lines: self.send_line(line, "\r") self.send_end_paste() def _upload_transfer_files_job(self, transfer): assert isinstance(transfer, FileTransfer) transfer.set_file_count(2) self._auto_reader_lock.acquire() self._auto_read_enabled = False try: self.send_upload_file("__upload.py") self.read_all() with open(SerialConnection._transfer_file_path("upload.py")) as f: data = f.read() data = data.replace("\"file_name.py\"", "file_name") self.send_file(data.encode('utf-8'), transfer) transfer.mark_finished() self.run_file("__upload.py", "file_name=\"{}\"".format("__download.py")) self.read_all() with open(SerialConnection._transfer_file_path("download.py")) as f: data = f.read() data = data.replace("\"file_name.py\"", "file_name") self.send_file(data.encode('utf-8'), transfer) transfer.mark_finished() except FileNotFoundError: transfer.mark_error("Couldn't locate transfer scripts.") except FileTransferError as e: transfer.mark_error(e.details) self._auto_read_enabled = True self._auto_reader_lock.release() def upload_transfer_files(self, transfer): job_thread = Thread(target=self._upload_transfer_files_job, args=[transfer]) # Set thread as daemon so in case main window is closed, this # tasks gets aborted and program will close immediately job_thread.setDaemon(True) job_thread.start() def handle_transfer_error(self, message): # Make sure that the device isn't stuck in read self._break_device_read() raise FileTransferError(message) def send_file(self, data, transfer): assert isinstance(transfer, FileTransfer) # Split data into smaller chunks idx = 0 # Using chunks of 48 bytes, encoded chunk should be at most 64 bytes n = 48 total_len = len(data) while idx < total_len: chunk = data[idx:idx + n] # Encode data to prevent special REPL sequences en_chunk = base64.b64encode(chunk) self._serial.write(b"".join([b"#", str(len(en_chunk)).zfill(2).encode("ascii"), en_chunk])) ack = self.read_with_timeout(2) error = None if not ack: error = "Device failed to respond in specified timeout." elif ack == b"#2": error = "Device didn't receive next message in time or message header got corrupted." elif ack == b"#3": error = "Device didn't receive as much data as was indicated in the message header." elif ack != b"#1": error = "Error in protocol. Expected #1 but device replied with:\n{}.".format( ack.decode(errors='ignore')) if error: error += "\n\nLast message was:\n{}.".format(chunk.decode(errors='ignore')) self.handle_transfer_error(error) idx += len(chunk) transfer.progress = idx / total_len # Mark end and check for success self._serial.write(b"#00") check = self.read_with_timeout(2) error = None if not check: error = "Device failed to respond in specified timeout." if check != b"#0": error = "Error in protocol. Expected #0 but device replied with: {}.".format( check.decode(errors='ignore')) if error: self.handle_transfer_error(error) def recv_file(self, transfer, file_size): assert isinstance(transfer, FileTransfer) result = b"" # Initiate transfer self._serial.write(b"###") while True: data = self.read_with_timeout(3) if not data or data[0] != ord("#"): self._serial.write(b"#2") break count = int(data[1:3]) if count == 0: transfer.read_result.binary_data = result return data = self.read_with_timeout(count) if data: result += base64.b64decode(data) # Send ACK self._serial.write(b"#1") else: self._serial.write(b"#3") break transfer.progress = len(result) / file_size transfer.read_result.binary_data = None self.handle_transfer_error("") def _write_file_job(self, file_name, text, transfer): if isinstance(text, str): text = text.encode('utf-8') self._auto_reader_lock.acquire() self._auto_read_enabled = False if Settings().use_transfer_scripts: self.run_file("__upload.py", "file_name=\"{}\"".format(file_name)) else: try: self.send_upload_file(file_name) except FileNotFoundError: transfer.mark_error("Couldn't locate upload transfer script.") if not transfer.error: self.read_junk() try: self.send_file(text, transfer) transfer.mark_finished() except FileTransferError as e: transfer.mark_error(e.details) self._auto_read_enabled = True self._auto_reader_lock.release() def _read_file_job(self, file_name, transfer): try: file_size = self.get_file_size(file_name) except OperationError: transfer.mark_error("Failed to determine file size.") return self._auto_reader_lock.acquire() self._auto_read_enabled = False if Settings().use_transfer_scripts: self.run_file("__download.py", "file_name=\"{}\"".format(file_name)) else: try: self.send_download_file(file_name) except FileNotFoundError: transfer.mark_error("Couldn't locate download transfer script.") if not transfer.error: self.read_junk() try: self.recv_file(transfer, file_size) transfer.mark_finished() except FileTransferError as e: transfer.mark_error(e.details) self._auto_read_enabled = True self._auto_reader_lock.release()
6,132
879
package org.zstack.utils.test; import org.junit.Test; import org.zstack.utils.DateCountCache; public class TestDateCountCache { @Test public void test() { DateCountCache cache = new DateCountCache(2019, 2019); assert cache.getCount(2019, 0, 1) == 0; assert cache.getCount(2019, 0, 2) == 0; assert cache.getCount(2020, 0, 2) == 0; assert cache.getCount(2018, 0, 2) == 0; cache.setCountUnsafe(2019, 0, 1, 2); assert cache.getCount(2019, 0, 1) == 2; assert cache.getCount(2019, 0) == 2; cache.addCountUnsafe(2019, 0, 2); assert cache.getCount(2019, 0, 2) == 1; assert cache.getCount(2019, 0) == 3; boolean exception = false; try { cache.setCountUnsafe(2020, 0, 1, 2); } catch (IndexOutOfBoundsException e) { exception = true; } assert exception; cache.expandIfNeed(2020, null); cache.expandIfNeed(2021, 2022); cache.setCountUnsafe(2020, 0, 1, 2); cache.expandIfNeed(2019, null); cache.expandIfNeed(null, 2019); cache.expandIfNeed(null, 2020); cache.setCountUnsafe(2020, 0, 1, 2); assert cache.getCount(2020, 0, 1) == 2; assert cache.getCount(2019, 0, 2) == 1; assert cache.getCount(2019, 0) == 3; } }
626
19,371
<filename>sentinel-cluster/sentinel-cluster-server-default/src/main/java/com/alibaba/csp/sentinel/cluster/flow/ConcurrentClusterFlowChecker.java /* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.cluster.flow; import com.alibaba.csp.sentinel.cluster.TokenResult; import com.alibaba.csp.sentinel.cluster.TokenResultStatus; import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterFlowRuleManager; import com.alibaba.csp.sentinel.cluster.flow.statistic.concurrent.CurrentConcurrencyManager; import com.alibaba.csp.sentinel.cluster.flow.statistic.concurrent.TokenCacheNode; import com.alibaba.csp.sentinel.cluster.flow.statistic.concurrent.TokenCacheNodeManager; import com.alibaba.csp.sentinel.cluster.server.log.ClusterServerStatLogUtil; import com.alibaba.csp.sentinel.log.RecordLog; import com.alibaba.csp.sentinel.slots.block.ClusterRuleConstant; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import java.util.concurrent.atomic.AtomicInteger; /** * @author yunfeiyanggzq */ final public class ConcurrentClusterFlowChecker { public static double calcGlobalThreshold(FlowRule rule) { double count = rule.getCount(); switch (rule.getClusterConfig().getThresholdType()) { case ClusterRuleConstant.FLOW_THRESHOLD_GLOBAL: return count; case ClusterRuleConstant.FLOW_THRESHOLD_AVG_LOCAL: default: int connectedCount = ClusterFlowRuleManager.getConnectedCount(rule.getClusterConfig().getFlowId()); return count * connectedCount; } } public static TokenResult acquireConcurrentToken(/*@Valid*/ String clientAddress, FlowRule rule, int acquireCount) { long flowId = rule.getClusterConfig().getFlowId(); AtomicInteger nowCalls = CurrentConcurrencyManager.get(flowId); if (nowCalls == null) { RecordLog.warn("[ConcurrentClusterFlowChecker] Fail to get nowCalls by flowId<{}>", flowId); return new TokenResult(TokenResultStatus.FAIL); } // check before enter the lock to improve the efficiency if (nowCalls.get() + acquireCount > calcGlobalThreshold(rule)) { ClusterServerStatLogUtil.log("concurrent|block|" + flowId, acquireCount); return new TokenResult(TokenResultStatus.BLOCKED); } // ensure the atomicity of operations // lock different nowCalls to improve the efficiency synchronized (nowCalls) { // check again whether the request can pass. if (nowCalls.get() + acquireCount > calcGlobalThreshold(rule)) { ClusterServerStatLogUtil.log("concurrent|block|" + flowId, acquireCount); return new TokenResult(TokenResultStatus.BLOCKED); } else { nowCalls.getAndAdd(acquireCount); } } ClusterServerStatLogUtil.log("concurrent|pass|" + flowId, acquireCount); TokenCacheNode node = TokenCacheNode.generateTokenCacheNode(rule, acquireCount, clientAddress); TokenCacheNodeManager.putTokenCacheNode(node.getTokenId(), node); TokenResult tokenResult = new TokenResult(TokenResultStatus.OK); tokenResult.setTokenId(node.getTokenId()); return tokenResult; } public static TokenResult releaseConcurrentToken(/*@Valid*/ long tokenId) { TokenCacheNode node = TokenCacheNodeManager.getTokenCacheNode(tokenId); if (node == null) { RecordLog.info("[ConcurrentClusterFlowChecker] Token<{}> is already released", tokenId); return new TokenResult(TokenResultStatus.ALREADY_RELEASE); } FlowRule rule = ClusterFlowRuleManager.getFlowRuleById(node.getFlowId()); if (rule == null) { RecordLog.info("[ConcurrentClusterFlowChecker] Fail to get rule by flowId<{}>", node.getFlowId()); return new TokenResult(TokenResultStatus.NO_RULE_EXISTS); } if (TokenCacheNodeManager.removeTokenCacheNode(tokenId) == null) { RecordLog.info("[ConcurrentClusterFlowChecker] Token<{}> is already released for flowId<{}>", tokenId, node.getFlowId()); return new TokenResult(TokenResultStatus.ALREADY_RELEASE); } int acquireCount = node.getAcquireCount(); AtomicInteger nowCalls = CurrentConcurrencyManager.get(node.getFlowId()); nowCalls.getAndAdd(-1 * acquireCount); ClusterServerStatLogUtil.log("concurrent|release|" + rule.getClusterConfig().getFlowId(), acquireCount); return new TokenResult(TokenResultStatus.RELEASE_OK); } }
1,922
3,934
<reponame>Jasha10/pyright<filename>packages/pyright-internal/src/tests/samples/isinstance9.py # This sample tests the isinstance narrowing when the list # of classes includes a type defined by a type variable. from typing import Any, Type, TypeVar, Union T = TypeVar("T") def func1(cls: Type[T], obj: Any) -> T: assert isinstance(obj, cls) reveal_type(obj, expected_text="T@func1") return obj v1 = func1(int, 3) reveal_type(v1, expected_text="int") def func2(klass: Type[T], obj: Union[T, int]) -> T: assert isinstance(obj, klass) reveal_type(obj, expected_text="T@func2") return obj v2 = func2(str, 3) reveal_type(v2, expected_text="str")
255
377
#pragma once //------------------------------------------------------------------------------ /** @class IO::ZipDirEntry A directory entry in a zip arcive. The ZipDirEntry class is thread-safe, all public methods can be invoked from on the same object from different threads. @copyright (C) 2006 Radon Labs GmbH (C) 2013-2020 Individual contributors, see AUTHORS file */ #include "core/types.h" #include "io/zipfs/zipfileentry.h" //------------------------------------------------------------------------------ namespace IO { class ZipDirEntry { public: /// constructor ZipDirEntry(); /// get the name of the dir entry const Util::StringAtom& GetName() const; /// find a direct child file entry, return 0 if not exists ZipFileEntry* FindFileEntry(const Util::StringAtom& name) const; /// find a direct child directory entry, return 0 if not exists ZipDirEntry* FindDirEntry(const Util::StringAtom& name) const; /// get directory entries const Util::Array<ZipDirEntry>& GetDirEntries() const; /// get file entries const Util::Array<ZipFileEntry>& GetFileEntries() const; private: friend class ZipArchive; /// set the name of the dir entry void SetName(const Util::StringAtom& n); /// add a file child entry ZipFileEntry* AddFileEntry(const Util::StringAtom& name); /// add a directory child entry ZipDirEntry* AddDirEntry(const Util::StringAtom& name); Util::StringAtom name; Util::Array<ZipFileEntry> fileEntries; Util::Array<ZipDirEntry> dirEntries; Util::Dictionary<Util::StringAtom, IndexT> fileIndexMap; Util::Dictionary<Util::StringAtom, IndexT> dirIndexMap; }; //------------------------------------------------------------------------------ /** */ inline void ZipDirEntry::SetName(const Util::StringAtom& n) { this->name = n; } //------------------------------------------------------------------------------ /** */ inline const Util::StringAtom& ZipDirEntry::GetName() const { return this->name; } //------------------------------------------------------------------------------ /** */ inline const Util::Array<ZipDirEntry>& ZipDirEntry::GetDirEntries() const { return this->dirEntries; } //------------------------------------------------------------------------------ /** */ inline const Util::Array<ZipFileEntry>& ZipDirEntry::GetFileEntries() const { return this->fileEntries; } } // namespace IO //------------------------------------------------------------------------------
757
10,225
package io.quarkus.it.rest; import javax.enterprise.context.Dependent; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.eclipse.microprofile.rest.client.annotation.RegisterClientHeaders; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; /** * Used to test default @{@link Dependent} scope defined on interface */ @RegisterRestClient @Path("/test") @RegisterClientHeaders public interface RestClientInterface { @GET @Path("/echo/{echo}") String echo(@PathParam("echo") String echo); @GET String get(); @GET @Path("/jackson") @Produces("application/json") TestResource.MyData getData(); }
260
432
<filename>pyltr/data/pandas_converter.py import pandas as pd class PandasLetorConverter(object): ''' Class Converter implements parsing from original MSLR-WEB and LETOR txt files to pandas data frame representation. ''' def __init__(self, path): ''' Arguments: path (str): path to letor txt file ''' self.path = path @property def path(self): return self._path @path.setter def path(self, p): if type(p) is not str: raise TypeError('path must be of type str') self._path = p def _load_file(self): ''' Loads and parses raw letor txt file. Return: letor txt file parsed to csv in raw format ''' return pd.read_csv(str(self._path), sep=" ", header=None) def _drop_col(self, df): ''' Drops last column, which was added in the parsing procedure due to a trailing white space for each sample in the text file Arguments: df: pandas dataframe Return: df: original df with last column dropped ''' return df.drop(df.columns[-1], axis=1) def _split_colon(self, df): ''' Splits the data on the colon and transforms it into a tabular format where columns are features and rows samples. Cells represent feature values per sample. Arguments: df: pandas dataframe object Return: df: original df with string pattern ':' removed; columns named appropriately ''' tracker = 0 # Ensures compatibility with MSLR-WEBK datasets for col in range(1,len(df.columns)): tracker += 1 if ':' in str(df.ix[:,col][0]): df.ix[:,col] = df.ix[:,col].apply(lambda x: str(x).split(':')[1]) else: break #tracker = col df.columns = ['rel', 'qid'] + [str(x) for x in range(1,len(df.columns)-1)] # renaming cols # Ensures compatibility with LETOR datasets if tracker != len(df.columns)-1: newcols = [] for col in df.columns: test = df.ix[0,col] if ('docid' in str(test)) or ('inc' in str(test)) or ('prob' in str(test)) or ('=' in str(test)): newcols.append(test) df = df.drop(str(col), axis=1) newcols = [x for x in newcols if '=' not in x] df.columns.values[-len(newcols):] = newcols return df def convert(self): ''' Performs final conversion. Return: fully converted pandas dataframe ''' df_raw = self._load_file() df_drop = self._drop_col(df_raw) return self._split_colon(df_drop)
1,357
3,294
<reponame>BaruaSourav/docs // <Snippet1> #using <System.EnterpriseServices.dll> #using <System.Web.Services.dll> using namespace System; using namespace System::Web::Services; using namespace System::Web::Services::Protocols; // Define a SOAP header by deriving from the SoapHeader base class. // The header contains just one string value. public ref class MyHeader: public SoapHeader { public: String^ MyValue; }; public ref class MyWebService { public: // Member variable to receive the contents of the MyHeader SOAP header. MyHeader^ myHeader; [WebMethod] [SoapHeader("myHeader",Direction=SoapHeaderDirection::InOut)] void Hello(){} }; // </Snippet1>
219
348
<filename>docs/data/t2/055/55452.json<gh_stars>100-1000 {"nom":"Saint-Amand-sur-Ornain","dpt":"Meuse","inscrits":69,"abs":14,"votants":55,"blancs":3,"nuls":3,"exp":49,"res":[{"panneau":"1","voix":26},{"panneau":"2","voix":23}]}
99
1,176
package net.osmand.util; /****************************************************************************** * * SunriseSunset.java * ******************************************************************************* * * Java Class: SunriseSunset * * This Java class is part of a collection of classes developed for the * reading and processing of oceanographic and meterological data collected * since 1970 by environmental buoys and stations. This dataset is * maintained by the National Oceanographic Data Center and is publicly * available. These Java classes were written for the US Environmental * Protection Agency's National Exposure Research Laboratory under Contract * No. GS-10F-0073K with Neptune and Company of Los Alamos, New Mexico. * * Purpose: * * This Java class performs calculations to determine the time of * sunrise and sunset given lat, long, and date. * * Inputs: * * Latitude, longitude, date/time, and time zone. * * Outputs: * * Local time of sunrise and sunset as calculated by the * program. * If no sunrise or no sunset occurs, or if the sun is up all day * or down all day, appropriate boolean values are set. * A boolean is provided to identify if the time provided is during the day. * * The above values are accessed by the following methods: * * Date getSunrise() returns date/time of sunrise * Date getSunset() returns date/time of sunset * boolean isSunrise() returns true if there was a sunrise, else false * boolean isSunset() returns true if there was a sunset, else false * boolean isSunUp() returns true if sun is up all day, else false * boolean isSunDown() returns true if sun is down all day, else false * boolean isDaytime() returns true if sun is up at the time * specified, else false * * Required classes from the Java library: * * java.util.Date * java.text.SimpleDateFormat * java.text.ParseException; * java.math.BigDecimal; * * Package of which this class is a member: * * default * * Known limitations: * * It is assumed that the data provided are within value ranges * (i.e. latitude between -90 and +90, longitude between 0 and 360, * a valid date, and time zone between -14 and +14. * * Compatibility: * * Java 1.1.8 * * References: * * The mathematical algorithms used in this program are patterned * after those debveloped by <NAME> in his BASIC program, * SUNUP.BAS, published in Sky & Telescope magazine: * Sinnott, <NAME>. "Sunrise and Sunset: A Challenge" * Sky & Telescope, August, 1994 p.84-85 * * The following is a cross-index of variables used in SUNUP.BAS. * A single definition from multiple reuse of variable names in * SUNUP.BAS was clarified with various definitions in this program. * * SUNUP.BAS this class * * A dfA * A(2) dfAA1, dfAA2 * A0 dfA0 * A2 dfA2 * A5 dfA5 * AZ Not used * C dfCosLat * C0 dfC0 * D iDay * D(2) dfDD1, dfDD2 * D0 dfD0 * D1 dfD1 * D2 dfD2 * D5 dfD5 * D7 Not used * DA dfDA * DD dfDD * G bGregorian, dfGG * H dfTimeZone * H0 dfH0 * H1 dfH1 * H2 dfH2 * H3 dfHourRise, dfHourSet * H7 Not used * J dfJ * J3 dfJ3 * K1 dfK1 * L dfLL * L0 dfL0 * L2 dfL2 * L5 dfLon * M iMonth * M3 dfMinRise, dfMinSet * N7 Not used * P dfP * S iSign, dfSinLat, dfSS * T dfT * T0 dfT0 * T3 not used * TT dfTT * U dfUU * V dfVV * V0 dfV0 * V1 dfV1 * V2 dfV2 * W dfWW * Y iYear * Z dfZenith * Z0 dfTimeZone * * * Author/Company: * * JDT: <NAME>, Neptune and Company * JMG: <NAME> * * Change log: * * date ver by description of change * _________ _____ ___ ______________________________________________ * 5 Jan 01 0.006 JDT Excised from ssapp.java v. 0.005. * 11 Jan 01 0.007 JDT Minor modifications to comments based on * material from Sinnott, 1994. * 7 Feb 01 0.008 JDT Fixed backwards time zone. The standard is that * local time zone is specified in hours EAST of * Greenwich, so that EST would be -5, for example. * For some reason, SUNUP.BAS does this backwards * (probably an americocentric perspective) and * SunriseSunset adopted that convention. Oops. * So the sign in the math is changed. * 7 Feb 01 0.009 JDT Well, that threw off the azimuth calculation... * Removed the azimuth calculations. * 14 Feb 01 0.010 JDT Added ability to accept a time (HH:mm) in * dateInput, and decide if that time is daytime * or nighttime. * 27 Feb 01 0.011 JDT Added accessor methods in place of having public * variables to get results. * 28 Feb 01 0.012 JDT Cleaned up list of imported classes. * 28 Mar 01 1.10 JDT Final version accompanying deliverable 1b. * 4 Apr 01 1.11 JDT Moved logic supporting .isDaytime into method. * Moved calculations out of constructor. * 01 May 01 1.12 JMG Added 'GMT' designation and testing lines. * 16 May 01 1.13 JDT Added setLenient( false ) and setTimeZone( tz ) * to dfmtDay, dfmtMonth, and dfmtYear in * doCalculations. * 27 Jun 01 1.14 JDT Removed reliance on StationConstants (GMT). * 13 Aug 01 1.20 JDT Final version accompanying deliverable 1c. * 6 Sep 01 1.21 JDT Thorough code and comment review. * 21 Sep 01 1.30 JDT Final version accompanying deliverable 2. * 17 Dec 01 1.40 JDT Version accompanying final deliverable. * *----------------------------------------------------------------------------*/ import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /****************************************************************************** * class: SunriseSunset class ******************************************************************************* * * This Java class performs calculations to determine the time of * sunrise and sunset given lat, long, and date. * * It is assumed that the data provided are within value ranges * (i.e. latitude between -90 and +90, longitude between 0 and 360, * a valid date, and time zone between -14 and +14. * *----------------------------------------------------------------------------*/ public class SunriseSunset { // Declare and initialize variables private double dfLat; // latitude from user private double dfLon; // latitude from user private Date dateInput; // date/time from user private double dfTimeZone; // time zone from user private Date dateSunrise; // date and time of sunrise private Date dateSunset; // date and time of sunset private boolean bSunriseToday = false; // flag for sunrise on this date private boolean bSunsetToday = false; // flag for sunset on this date private boolean bSunUpAllDay = false; // flag for sun up all day private boolean bSunDownAllDay = false; // flag for sun down all day private boolean bDaytime = false; // flag for daytime, given // hour and min in dateInput private boolean bSunrise = false; // sunrise during hour checked private boolean bSunset = false; // sunset during hour checked private boolean bGregorian = false; // flag for Gregorian calendar private int iJulian; // Julian day private int iYear; // year of date of interest private int iMonth; // month of date of interest private int iDay; // day of date of interest private int iCount; // a simple counter private int iSign; // SUNUP.BAS: S private int dfHourRise, dfHourSet; // hour of event: SUNUP.BAS H3 private int dfMinRise, dfMinSet; // minute of event: SUNUP.BAS M3 private double dfSinLat, dfCosLat; // sin and cos of latitude private double dfZenith; // SUNUP.BAS Z: Zenith // Many variables in SUNUP.BAS have undocumented meanings, // and so are translated rather directly to avoid confusion: private double dfAA1 = 0, dfAA2 = 0; // SUNUP.BAS A(2) private double dfDD1 = 0, dfDD2 = 0; // SUNUP.BAS D(2) private double dfC0; // SUNUP.BAS C0 private double dfK1; // SUNUP.BAS K1 private double dfP; // SUNUP.BAS P private double dfJ; // SUNUP.BAS J private double dfJ3; // SUNUP.BAS J3 private double dfA; // SUNUP.BAS A private double dfA0, dfA2, dfA5; // SUNUP.BAS A0, A2, A5 private double dfD0, dfD1, dfD2, dfD5; // SUNUP.BAS D0, D1, D2, D5 private double dfDA, dfDD; // SUNUP.BAS DA, DD private double dfH0, dfH1, dfH2; // SUNUP.BAS H0, H1, H2 private double dfL0, dfL2; // SUNUP.BAS L0, L2 private double dfT, dfT0, dfTT; // SUNUP.BAS T, T0, TT private double dfV0, dfV1, dfV2; // SUNUP.BAS V0, V1, V2 /****************************************************************************** * method: SunriseSunset ******************************************************************************* * * Constructor for SunriseSunset class. * *----------------------------------------------------------------------------*/ public SunriseSunset( double dfLatIn, // latitude double dfLonIn, // longitude Date dateInputIn, // date TimeZone tzIn // time zone ) { // Calculate internal representation of timezone offset as fraction of hours from GMT // Our calculations consider offsets to the West as positive, so we must invert // the signal of the values provided by the standard library double dfTimeZoneIn = 1.0 * tzIn.getOffset(dateInputIn.getTime()) / 3600000; // Copy values supplied as agruments to local variables. dfLat = dfLatIn; dfLon = dfLonIn; dateInput = dateInputIn; dfTimeZone = dfTimeZoneIn; // Call the method to do the calculations. doCalculations(); } // end of class constructor /****************************************************************************** * method: doCalculations ******************************************************************************* * * Method for performing the calculations done in SUNUP.BAS. * *----------------------------------------------------------------------------*/ private void doCalculations() { // Break out day, month, and year from date provided using local time zone. // (This is necessary for the math algorithms.) Calendar cin = Calendar.getInstance(); cin.setTime(dateInput); iYear = cin.get(Calendar.YEAR); iMonth = cin.get(Calendar.MONTH) + 1; iDay = cin.get(Calendar.DAY_OF_MONTH); // Convert time zone hours to decimal days (SUNUP.BAS line 50) dfTimeZone = dfTimeZone / 24.0; // NOTE: (7 Feb 2001) Here is a non-standard part of SUNUP.BAS: // It (and this algorithm) assumes that the time zone is // positive west, instead of the standard negative west. // Classes calling SunriseSunset will be assuming that // times zones are specified in negative west, so here the // sign is changed so that the SUNUP algorithm works: dfTimeZone = -dfTimeZone; // Convert longitude to fraction (SUNUP.BAS line 50) dfLon = dfLon / 360.0; // Convert calendar date to Julian date: // Check to see if it's later than 1583: Gregorian calendar // When declared, bGregorian is initialized to false. // ** Consider making a separate class of this function. ** if( iYear >= 1583 ) bGregorian = true; // SUNUP.BAS 1210 dfJ = -Math.floor( 7.0 // SUNUP used INT, not floor * ( Math.floor( ( iMonth + 9.0 ) / 12.0 ) + iYear ) / 4.0 ) // add SUNUP.BAS 1240 and 1250 for G = 0 + Math.floor( iMonth * 275.0 / 9.0 ) + iDay + 1721027.0 + iYear * 367.0; if ( bGregorian ) { // SUNUP.BAS 1230 if ( ( iMonth - 9.0 ) < 0.0 ) iSign = -1; else iSign = 1; dfA = Math.abs( iMonth - 9.0 ); // SUNUP.BAS 1240 and 1250 dfJ3 = -Math.floor( ( Math.floor( Math.floor( iYear + (double)iSign * Math.floor( dfA / 7.0 ) ) / 100.0 ) + 1.0 ) * 0.75 ); // correct dfJ as in SUNUP.BAS 1240 and 1250 for G = 1 dfJ = dfJ + dfJ3 + 2.0; } // SUNUP.BAS 1290 iJulian = (int)dfJ - 1; // SUNUP.BAS 60 and 70 (see also line 1290) dfT = (double)iJulian - 2451545.0 + 0.5; dfTT = dfT / 36525.0 + 1.0; // centuries since 1900 // Calculate local sidereal time at 0h in zone time // SUNUP.BAS 410 through 460 dfT0 = ( dfT * 8640184.813 / 36525.0 + 24110.5 + dfTimeZone * 86636.6 + dfLon * 86400.0 ) / 86400.0; dfT0 = dfT0 - Math.floor( dfT0 ); // NOTE: SUNUP.BAS uses INT() dfT0 = dfT0 * 2.0 * Math.PI; // SUNUP.BAS 90 dfT = dfT + dfTimeZone; // SUNUP.BAS 110: Get Sun's position for( iCount=0; iCount<=1; iCount++ ) // Loop thru only twice { // Calculate Sun's right ascension and declination // at the start and end of each day. // SUNUP.BAS 910 - 1160: Fundamental arguments // from <NAME> and Pulkkinen, 1979 // declare local temporary doubles for calculations double dfGG; // SUNUP.BAS G double dfLL; // SUNUP.BAS L double dfSS; // SUNUP.BAS S double dfUU; // SUNUP.BAS U double dfVV; // SUNUP.BAS V double dfWW; // SUNUP.BAS W dfLL = 0.779072 + 0.00273790931 * dfT; dfLL = dfLL - Math.floor( dfLL ); dfLL = dfLL * 2.0 * Math.PI; dfGG = 0.993126 + 0.0027377785 * dfT; dfGG = dfGG - Math.floor( dfGG ); dfGG = dfGG * 2.0 * Math.PI; dfVV = 0.39785 * Math.sin( dfLL ) - 0.01000 * Math.sin( dfLL - dfGG ) + 0.00333 * Math.sin( dfLL + dfGG ) - 0.00021 * Math.sin( dfLL ) * dfTT; dfUU = 1 - 0.03349 * Math.cos( dfGG ) - 0.00014 * Math.cos( dfLL * 2.0 ) + 0.00008 * Math.cos( dfLL ); dfWW = - 0.00010 - 0.04129 * Math.sin( dfLL * 2.0 ) + 0.03211 * Math.sin( dfGG ) - 0.00104 * Math.sin( 2.0 * dfLL - dfGG ) - 0.00035 * Math.sin( 2.0 * dfLL + dfGG ) - 0.00008 * Math.sin( dfGG ) * dfTT; // Compute Sun's RA and Dec; SUNUP.BAS 1120 - 1140 dfSS = dfWW / Math.sqrt( dfUU - dfVV * dfVV ); dfA5 = dfLL + Math.atan( dfSS / Math.sqrt( 1.0 - dfSS * dfSS )); dfSS = dfVV / Math.sqrt( dfUU ); dfD5 = Math.atan( dfSS / Math.sqrt( 1 - dfSS * dfSS )); // Set values and increment t if ( iCount == 0 ) // SUNUP.BAS 125 { dfAA1 = dfA5; dfDD1 = dfD5; } else // SUNUP.BAS 145 { dfAA2 = dfA5; dfDD2 = dfD5; } dfT = dfT + 1.0; // SUNUP.BAS 130 } // end of Get Sun's Position for loop if ( dfAA2 < dfAA1 ) dfAA2 = dfAA2 + 2.0 * Math.PI; // SUNUP.BAS 150 dfZenith = Math.PI * 90.833 / 180.0; // SUNUP.BAS 160 dfSinLat = Math.sin( dfLat * Math.PI / 180.0 ); // SUNUP.BAS 170 dfCosLat = Math.cos( dfLat * Math.PI / 180.0 ); // SUNUP.BAS 170 dfA0 = dfAA1; // SUNUP.BAS 190 dfD0 = dfDD1; // SUNUP.BAS 190 dfDA = dfAA2 - dfAA1; // SUNUP.BAS 200 dfDD = dfDD2 - dfDD1; // SUNUP.BAS 200 dfK1 = 15.0 * 1.0027379 * Math.PI / 180.0; // SUNUP.BAS 330 // Initialize sunrise and sunset times, and other variables // hr and min are set to impossible times to make errors obvious dfHourRise = 99; dfMinRise = 99; dfHourSet = 99; dfMinSet = 99; dfV0 = 0.0; // initialization implied by absence in SUNUP.BAS dfV2 = 0.0; // initialization implied by absence in SUNUP.BAS // Test each hour to see if the Sun crosses the horizon // and which way it is heading. for( iCount=0; iCount<24; iCount++ ) // SUNUP.BAS 210 { double tempA; // SUNUP.BAS A double tempB; // SUNUP.BAS B double tempD; // SUNUP.BAS D double tempE; // SUNUP.BAS E dfC0 = (double)iCount; dfP = ( dfC0 + 1.0 ) / 24.0; // SUNUP.BAS 220 dfA2 = dfAA1 + dfP * dfDA; // SUNUP.BAS 230 dfD2 = dfDD1 + dfP * dfDD; // SUNUP.BAS 230 dfL0 = dfT0 + dfC0 * dfK1; // SUNUP.BAS 500 dfL2 = dfL0 + dfK1; // SUNUP.BAS 500 dfH0 = dfL0 - dfA0; // SUNUP.BAS 510 dfH2 = dfL2 - dfA2; // SUNUP.BAS 510 // hour angle at half hour dfH1 = ( dfH2 + dfH0 ) / 2.0; // SUNUP.BAS 520 // declination at half hour dfD1 = ( dfD2 + dfD0 ) / 2.0; // SUNUP.BAS 530 // Set value of dfV0 only if this is the first hour, // otherwise, it will get set to the last dfV2 (SUNUP.BAS 250) if ( iCount == 0 ) // SUNUP.BAS 550 { dfV0 = dfSinLat * Math.sin( dfD0 ) + dfCosLat * Math.cos( dfD0 ) * Math.cos( dfH0 ) - Math.cos( dfZenith ); // SUNUP.BAS 560 } else dfV0 = dfV2; // That is, dfV2 from the previous hour. dfV2 = dfSinLat * Math.sin( dfD2 ) + dfCosLat * Math.cos( dfD2 ) * Math.cos( dfH2 ) - Math.cos( dfZenith ); // SUNUP.BAS 570 // if dfV0 and dfV2 have the same sign, then proceed to next hr if ( ( dfV0 >= 0.0 && dfV2 >= 0.0 ) // both are positive || // or ( dfV0 < 0.0 && dfV2 < 0.0 ) // both are negative ) { // Break iteration and proceed to test next hour dfA0 = dfA2; // SUNUP.BAS 250 dfD0 = dfD2; // SUNUP.BAS 250 continue; // SUNUP.BAS 610 } dfV1 = dfSinLat * Math.sin( dfD1 ) + dfCosLat * Math.cos( dfD1 ) * Math.cos( dfH1 ) - Math.cos( dfZenith ); // SUNUP.BAS 590 tempA = 2.0 * dfV2 - 4.0 * dfV1 + 2.0 * dfV0; // SUNUP.BAS 600 tempB = 4.0 * dfV1 - 3.0 * dfV0 - dfV2; // SUNUP.BAS 600 tempD = tempB * tempB - 4.0 * tempA * dfV0; // SUNUP.BAS 610 if ( tempD < 0.0 ) { // Break iteration and proceed to test next hour dfA0 = dfA2; // SUNUP.BAS 250 dfD0 = dfD2; // SUNUP.BAS 250 continue; // SUNUP.BAS 610 } tempD = Math.sqrt( tempD ); // SUNUP.BAS 620 // Determine occurence of sunrise or sunset. // Flags to identify occurrence during this day are // bSunriseToday and bSunsetToday, and are initialized false. // These are set true only if sunrise or sunset occurs // at any point in the hourly loop. Never set to false. // Flags to identify occurrence during this hour: bSunrise = false; // reset before test bSunset = false; // reset before test if ( dfV0 < 0.0 && dfV2 > 0.0 ) // sunrise occurs this hour { bSunrise = true; // SUNUP.BAS 640 bSunriseToday = true; // sunrise occurred today } if ( dfV0 > 0.0 && dfV2 < 0.0 ) // sunset occurs this hour { bSunset = true; // SUNUP.BAS 660 bSunsetToday = true; // sunset occurred today } tempE = ( tempD - tempB ) / ( 2.0 * tempA ); if ( tempE > 1.0 || tempE < 0.0 ) // SUNUP.BAS 670, 680 tempE = ( -tempD - tempB ) / ( 2.0 * tempA ); // Set values of hour and minute of sunset or sunrise // only if sunrise/set occurred this hour. if ( bSunrise ) { dfHourRise = (int)( dfC0 + tempE + 1.0/120.0 ); dfMinRise = (int) ( ( dfC0 + tempE + 1.0/120.0 - dfHourRise ) * 60.0 ); } if ( bSunset ) { dfHourSet = (int) ( dfC0 + tempE + 1.0/120.0 ); dfMinSet = (int)( ( dfC0 + tempE + 1.0/120.0 - dfHourSet ) * 60.0 ); } // Change settings of variables for next loop dfA0 = dfA2; // SUNUP.BAS 250 dfD0 = dfD2; // SUNUP.BAS 250 } // end of loop testing each hour for an event // After having checked all hours, set flags if no rise or set // bSunUpAllDay and bSundownAllDay are initialized as false if ( !bSunriseToday && !bSunsetToday ) { if ( dfV2 < 0.0 ) bSunDownAllDay = true; else bSunUpAllDay = true; } // Load dateSunrise with data if( bSunriseToday ) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, iYear); c.set(Calendar.MONTH, iMonth-1); c.set(Calendar.DAY_OF_MONTH, iDay); c.set(Calendar.HOUR_OF_DAY, dfHourRise); c.set(Calendar.MINUTE, dfMinRise); dateSunrise = c.getTime(); } // Load dateSunset with data if( bSunsetToday ) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, iYear); c.set(Calendar.MONTH, iMonth-1); c.set(Calendar.DAY_OF_MONTH, iDay); c.set(Calendar.HOUR_OF_DAY, dfHourSet); c.set(Calendar.MINUTE, dfMinSet); dateSunset = c.getTime(); } } /****************************************************************************** * method: getSunrise() ******************************************************************************* * * Gets the date and time of sunrise. If there is no sunrise, returns null. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public Date getSunrise() { if ( bSunriseToday ) return( dateSunrise ); else return( null ); } /****************************************************************************** * method: getSunset() ******************************************************************************* * * Gets the date and time of sunset. If there is no sunset, returns null. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public Date getSunset() { if ( bSunsetToday ) return( dateSunset ); else return( null ); } /****************************************************************************** * method: isSunrise() ******************************************************************************* * * Returns a boolean identifying if there was a sunrise. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunrise() { return( bSunriseToday ); } /****************************************************************************** * method: isSunset() ******************************************************************************* * * Returns a boolean identifying if there was a sunset. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunset() { return( bSunsetToday ); } /****************************************************************************** * method: isSunUp() ******************************************************************************* * * Returns a boolean identifying if the sun is up all day. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunUp() { return( bSunUpAllDay ); } /****************************************************************************** * method: isSunDown() ******************************************************************************* * * Returns a boolean identifying if the sun is down all day. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isSunDown() { return( bSunDownAllDay ); } /****************************************************************************** * method: isDaytime() ******************************************************************************* * * Returns a boolean identifying if it is daytime at the hour contained in * the Date object passed to SunriseSunset on construction. * * Member of SunriseSunset class * * -------------------------------------------------------------------------- */ public boolean isDaytime() { // Determine if it is daytime (at sunrise or later) // or nighttime (at sunset or later) at the location of interest // but expressed in the time zone requested. if ( bSunriseToday && bSunsetToday ) // sunrise and sunset { if ( dateSunrise.before( dateSunset ) ) // sunrise < sunset { if ( ( dateInput.after( dateSunrise ) || dateInput.equals( dateSunrise ) ) && dateInput.before( dateSunset ) ) bDaytime = true; else bDaytime = false; } else // sunrise comes after sunset (in opposite time zones) { if ( ( dateInput.after( dateSunrise ) || dateInput.equals( dateSunrise ) ) || // use OR rather than AND dateInput.before( dateSunset ) ) bDaytime = true; else bDaytime = false; } } else if ( bSunUpAllDay ) // sun is up all day bDaytime = true; else if ( bSunDownAllDay ) // sun is down all day bDaytime = false; else if ( bSunriseToday ) // sunrise but no sunset { if ( dateInput.before( dateSunrise ) ) bDaytime = false; else bDaytime = true; } else if ( bSunsetToday ) // sunset but no sunrise { if ( dateInput.before( dateSunset ) ) bDaytime = true; else bDaytime = false; } else bDaytime = false; // this should never execute return( bDaytime ); } } // end of class /*----------------------------------------------------------------------------- * end of class *----------------------------------------------------------------------------*/
10,348
852
import FWCore.ParameterSet.Config as cms from RecoEgamma.EgammaTools.cleanedEcalDrivenGsfElectronsHGC_cfi import cleanedEcalDrivenGsfElectronsHGC from RecoEgamma.EgammaTools.hgcalElectronIDValueMap_cff import hgcalElectronIDValueMap from PhysicsTools.PatAlgos.PATElectronProducer_cfi import PATElectronProducer from PhysicsTools.PatAlgos.slimming.slimmedElectrons_cfi import slimmedElectrons from RecoLocalCalo.HGCalRecProducers.hgcalRecHitMapProducer_cfi import hgcalRecHitMapProducer hgcElectronID = hgcalElectronIDValueMap.clone( electrons = "cleanedEcalDrivenGsfElectronsHGC", ) patElectronsHGC = PATElectronProducer.clone( electronSource = "cleanedEcalDrivenGsfElectronsHGC", beamLineSrc = "offlineBeamSpot", pvSrc = "offlinePrimaryVertices", addElectronID = False, addGenMatch = False, addMVAVariables = False, embedGenMatch = False, embedGsfElectronCore = True, embedGsfTrack = True, embedSuperCluster = True, embedPflowSuperCluster = False, embedSeedCluster = True, embedBasicClusters = False, embedPreshowerClusters = False, embedPflowBasicClusters = False, embedPflowPreshowerClusters= False, embedPFCandidate = False, embedTrack = True, embedRecHits = False, embedHighLevelSelection = True, userData = cms.PSet( userClasses = cms.PSet( src = cms.VInputTag('')), userFloats = cms.PSet( src = cms.VInputTag( [cms.InputTag("hgcElectronID", key) for key in hgcElectronID.variables] )), userInts = cms.PSet( src = cms.VInputTag('')), userCands = cms.PSet( src = cms.VInputTag('')), userFunctions = cms.vstring(), userFunctionLabels = cms.vstring() ), ) selectedPatElectronsHGC = cms.EDFilter("PATElectronSelector", src = cms.InputTag("patElectronsHGC"), cut = cms.string("!isEB && pt >= 10."), ) slimmedElectronsHGC = slimmedElectrons.clone( src = "selectedPatElectronsHGC", linkToPackedPFCandidates = False, saveNonZSClusterShapes = "0", modifyElectrons = False, ) slimmedElectronsHGCTask = cms.Task( cleanedEcalDrivenGsfElectronsHGC, hgcElectronID, patElectronsHGC, selectedPatElectronsHGC, slimmedElectronsHGC ) from RecoEgamma.EgammaTools.hgcalPhotonIDValueMap_cff import hgcalPhotonIDValueMap from PhysicsTools.PatAlgos.PATPhotonProducer_cfi import PATPhotonProducer from PhysicsTools.PatAlgos.slimming.slimmedPhotons_cfi import slimmedPhotons hgcPhotonID = hgcalPhotonIDValueMap.clone() patPhotonsHGC = PATPhotonProducer.clone( photonSource = "photonsHGC", electronSource = "ecalDrivenGsfElectronsHGC", beamLineSrc = "offlineBeamSpot", addPhotonID = False, addGenMatch = False, embedSuperCluster = True, embedSeedCluster = True, embedBasicClusters = False, embedPreshowerClusters = False, embedRecHits = False, saveRegressionData = False, embedGenMatch = False, isolationValues = cms.PSet(), userData = cms.PSet( userClasses = cms.PSet( src = cms.VInputTag('')), userFloats = cms.PSet( src = cms.VInputTag( [cms.InputTag("hgcPhotonID", key) for key in hgcPhotonID.variables] )), userInts = cms.PSet( src = cms.VInputTag('')), userCands = cms.PSet( src = cms.VInputTag('')), userFunctions = cms.vstring(), userFunctionLabels = cms.vstring() ), ) selectedPatPhotonsHGC = cms.EDFilter("PATPhotonSelector", src = cms.InputTag("patPhotonsHGC"), cut = cms.string("!isEB && pt >= 15."), ) slimmedPhotonsHGC = slimmedPhotons.clone( src = "selectedPatPhotonsHGC", linkToPackedPFCandidates = False, saveNonZSClusterShapes = "0", modifyPhotons = False, ) slimmedPhotonsHGCTask = cms.Task( hgcPhotonID, patPhotonsHGC, selectedPatPhotonsHGC, slimmedPhotonsHGC ) slimmedEgammaHGCTask = cms.Task( hgcalRecHitMapProducer, slimmedElectronsHGCTask, slimmedPhotonsHGCTask )
1,983
1,755
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Parameters for debugging NPts = 1000000 math = vtk.vtkMath() # create pipeline: use terrain dataset # # Read the data: a height field results demReader = vtk.vtkDEMReader() demReader.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem") demReader.Update() lo = demReader.GetOutput().GetScalarRange()[0] hi = demReader.GetOutput().GetScalarRange()[1] geom = vtk.vtkImageDataGeometryFilter() geom.SetInputConnection(demReader.GetOutputPort()) warp = vtk.vtkWarpScalar() warp.SetInputConnection(geom.GetOutputPort()) warp.SetNormal(0, 0, 1) warp.UseNormalOn() warp.SetScaleFactor(2) warp.Update() bds = warp.GetOutput().GetBounds() center = warp.GetOutput().GetCenter() # A randomized point cloud, whose attributes are set via implicit function points = vtk.vtkPoints() points.SetDataTypeToFloat() points.SetNumberOfPoints(NPts) for i in range(0,NPts): points.SetPoint(i,math.Random(bds[0],bds[1]),math.Random(bds[2],bds[3]),math.Random(bds[4],bds[5])) source = vtk.vtkPolyData() source.SetPoints(points) sphere = vtk.vtkSphere() sphere.SetCenter(center[0],center[1]-7500,center[2]) attr = vtk.vtkSampleImplicitFunctionFilter() attr.SetInputData(source) attr.SetImplicitFunction(sphere) attr.Update() # Gaussian kernel------------------------------------------------------- gaussianKernel = vtk.vtkGaussianKernel() gaussianKernel.SetSharpness(4) gaussianKernel.SetRadius(50) voronoiKernel = vtk.vtkVoronoiKernel() interpolator1 = vtk.vtkPointInterpolator2D() interpolator1.SetInputConnection(warp.GetOutputPort()) interpolator1.SetSourceConnection(attr.GetOutputPort()) #interpolator1.SetKernel(gaussianKernel) interpolator1.SetKernel(voronoiKernel) interpolator1.SetNullPointsStrategyToClosestPoint() # Time execution timer = vtk.vtkTimerLog() timer.StartTimer() interpolator1.Update() timer.StopTimer() time = timer.GetElapsedTime() print("Interpolate Terrain Points (Gaussian): {0}".format(time)) scalarRange = attr.GetOutput().GetScalarRange() intMapper1 = vtk.vtkPolyDataMapper() intMapper1.SetInputConnection(interpolator1.GetOutputPort()) intMapper1.SetScalarRange(scalarRange) intActor1 = vtk.vtkActor() intActor1.SetMapper(intMapper1) # Create an outline outline1 = vtk.vtkOutlineFilter() outline1.SetInputConnection(warp.GetOutputPort()) outlineMapper1 = vtk.vtkPolyDataMapper() outlineMapper1.SetInputConnection(outline1.GetOutputPort()) outlineActor1 = vtk.vtkActor() outlineActor1.SetMapper(outlineMapper1) # Create the RenderWindow, Renderer and both Actors # ren0 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren0) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren0.AddActor(intActor1) ren0.AddActor(outlineActor1) ren0.SetBackground(0.1, 0.2, 0.4) renWin.SetSize(250, 250) cam = ren0.GetActiveCamera() cam.SetFocalPoint(center) fp = cam.GetFocalPoint() cam.SetPosition(fp[0]+.2,fp[1]+.1,fp[2]+1) ren0.ResetCamera() iren.Initialize() # render the image # renWin.Render() iren.Start()
1,175
488
<gh_stars>100-1000 #include <featureTests.h> #ifdef ROSE_ENABLE_SOURCE_ANALYSIS #ifndef BDWY_STRUCTURE_H #define BDWY_STRUCTURE_H // ---------------------------------------------------------------------- // Structure Annotation // ---------------------------------------------------------------------- class structureTreeAnn; class structureAnn; typedef std::list<structureAnn * > structure_list; typedef structure_list::iterator structure_list_p; typedef structure_list::const_iterator structure_list_cp; typedef std::list< structureTreeAnn * > structuretree_list; typedef structuretree_list::iterator structuretree_list_p; /** @brief Structure Tree annotation * * This class is used to construct an in-memory representation of on-entry * and on-exit annotations. We post-process this tree structure into the * list of pointer operations that is actually used during analysis. * * The representation works like this: for A --> B, we create an object * for A, with a single target for B; for B { ... }, we create an object * for B with a list of the components. The operator indicates which * situation we have (although we can never have an arrow with multiple * targets. */ class structureTreeAnn : public Ann { public: typedef enum { None, Arrow, Dot } Operator; private: std::string _name; structuretree_list * _targets; Operator _operator; bool _target_is_new; bool _is_io; public: /** Multiple targets constructor */ structureTreeAnn( const parserID * name, structuretree_list * targets, Operator op, bool target_is_new); /** Single target constructor */ structureTreeAnn( const parserID * name, structureTreeAnn * target, Operator op, bool target_is_new); /** Destructor * * Recursively destroys the data structure */ ~structureTreeAnn(); inline std::string & name() { return _name; } inline structuretree_list * targets() { return _targets; } inline Operator op() const { return _operator; } inline bool is_target_new() const { return _target_is_new; } inline bool is_io() const { return _is_io; } /** @brief Print out */ void print(int depth = 0) const; private: // DQ (9/13/2011): This copy constructor was built because static analysis tools (made it private to force compile time error if used). /** @brief Private Copy Constructor */ structureTreeAnn(const structureTreeAnn & X); }; /** @brief Pointer structure annotation * * This class represents a single structure annotation (either on_entry or * on_exit). It handles both the "dot" operator and the "arrow" operator, * depending on whether the field_name is used. The actual annotation * syntax is decomposed into a list of these objects. For example: * * on_entry { A --> B { width, * height, * data --> data1, * more { stuff, * things } } } * * This introduces the following series of structure annotations: * * Source Operator Target * A --> B * B .width B.width * B .height B.height * B .data B.data * B.data --> data1 * B .more B.more * B.more .stuff B.more.stuff * B.more .things B.more.things * * This naming scheme is convenient because we can bind the names to * actual memory blocks during the processing of the on_entry annotations, * and then we never have to explicity process the "dot" operator because * it's built into the name. */ class structureAnn : public Ann { private: REF annVariable * _source; REF annVariable * _target; std::string _field_name; public: structureAnn(annVariable * source, annVariable * target, const std::string * field_name, const int line); // --- Fields inline annVariable * source() const { return _source; } inline annVariable * target() const { return _target; } inline const std::string & field_name() const { return _field_name; } // --- Output friend std::ostream& operator<<(std::ostream & o, const structureAnn & sa) { sa.print(o); return o; } void print(std::ostream & o) const; }; #endif /* */ #endif
1,508
8,649
package org.hswebframework.web.datasource.config; import java.util.List; public interface DynamicDataSourceConfigRepository<C extends DynamicDataSourceConfig> { List<C> findAll(); C findById(String dataSourceId); C add(C config); C remove(String dataSourceId); }
92
339
/* *Copyright (c) 2005-2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.ei.businessprocess.integration.common.clients.humantasks; import org.apache.axis2.AxisFault; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.ei.businessprocess.integration.common.clients.AuthenticateStubUtil; import org.wso2.carbon.humantask.stub.mgt.HumanTaskPackageManagementStub; import org.wso2.carbon.humantask.stub.mgt.PackageManagementException; import org.wso2.carbon.humantask.stub.mgt.types.*; import javax.xml.namespace.QName; import java.rmi.RemoteException; public class HumanTaskPackageManagementClient { private static final Log log = LogFactory.getLog(HumanTaskPackageManagementClient.class); protected final static String HUMANTASK_PACKAGE_MANAGEMENT_SERVICE = "HumanTaskPackageManagement"; private HumanTaskPackageManagementStub humanTaskPackageManagementStub = null; public HumanTaskPackageManagementClient(String serviceEndPoint, String sessionCookie) throws AxisFault { final String packageMgtServiceUrl = serviceEndPoint + HUMANTASK_PACKAGE_MANAGEMENT_SERVICE; humanTaskPackageManagementStub = new HumanTaskPackageManagementStub(packageMgtServiceUrl); AuthenticateStubUtil.authenticateStub(sessionCookie, humanTaskPackageManagementStub); } public HumanTaskPackageManagementClient(String serviceEndPoint, String username, String password) throws AxisFault { final String packageMgtServiceUrl = serviceEndPoint + HUMANTASK_PACKAGE_MANAGEMENT_SERVICE; humanTaskPackageManagementStub = new HumanTaskPackageManagementStub(packageMgtServiceUrl); AuthenticateStubUtil.authenticateStub(username, password, humanTaskPackageManagementStub); } public void unDeployHumanTask(String humantaskPackageName, String aTaskDefinitionName) throws PackageManagementException, InterruptedException, RemoteException { humanTaskPackageManagementStub.undeployHumanTaskPackage(humantaskPackageName); Thread.sleep(10000); //TODO Implement this logic using humanTaskPackageManagementStub.listDeployedPackagesPaginated() DeployedTaskDefinitionsPaginated deployedTaskDefinitions = humanTaskPackageManagementStub.listDeployedTaskDefinitionsPaginated(0); boolean packageUndeployed = true; if (deployedTaskDefinitions != null && deployedTaskDefinitions.getTaskDefinition() != null) { for (TaskDefinition_type0 definitionType : deployedTaskDefinitions.getTaskDefinition()) { if (definitionType != null && aTaskDefinitionName.equals(definitionType.getTaskName())) { packageUndeployed = false; log.error("Service still exists, Undeployment failed"); break; } } } if (packageUndeployed) { log.info(humantaskPackageName + " has undeployed successfully"); } } public Task_type0[] listTasksInPackage(String packageName) throws Exception { try { return humanTaskPackageManagementStub.listTasksInPackage(packageName); } catch (Exception e) { String errorMsg = "Unable to get Task list in Package for " + packageName; log.error(errorMsg, e); throw new Exception(errorMsg, e); } } public DeployedTaskDefinitionsPaginated listDeployedTaskDefinitionsPaginated(int page) throws Exception { try { return humanTaskPackageManagementStub.listDeployedTaskDefinitionsPaginated(page); } catch (Exception e) { String errorMsg = "Unable to get list Deployed Task Definitions for page " + page; log.error(errorMsg, e); throw new Exception(errorMsg, e); } } public TaskInfoType getTaskInfo(QName taskId) throws Exception { try { return humanTaskPackageManagementStub.getTaskInfo(taskId); } catch (Exception e) { String errorMsg = "Unable to get task info task ID" + taskId.toString(); log.error(errorMsg, e); throw new Exception(errorMsg, e); } } public HumanTaskPackageDownloadData downloadHumanTaskPackage(String packageName) throws Exception { try { return humanTaskPackageManagementStub.downloadHumanTaskPackage(packageName); } catch (Exception e) { String errorMsg = "Unable to get HumanTask Package DownloadData for package name " + packageName; log.error(errorMsg, e); throw new Exception(errorMsg, e); } } }
1,845
506
<gh_stars>100-1000 // https://open.kattis.com/problems/catcoat #include <algorithm> #include <iomanip> #include <iostream> #include <utility> #include <vector> using namespace std; int main() { string s, t; getline(cin, s); getline(cin, t); pair<int, int> sb, sr, sd, tb, tr, td; if (s == "Black") { sb = {3, 1}; sr = {0, 1}; sd = {3, 1}; } else if (s == "Blue") { sb = {3, 1}; sr = {0, 1}; sd = {0, 1}; } else if (s == "Chocolate") { sb = {0, 1}; sr = {0, 1}; sd = {3, 1}; } else if (s == "Lilac") { sb = {0, 1}; sr = {0, 1}; sd = {0, 1}; } else if (s == "Red") { sb = {1, 1}; sr = {1, 0}; sd = {3, 1}; } else if (s == "Cream") { sb = {1, 1}; sr = {1, 0}; sd = {0, 1}; } else if (s == "Black-Red Tortie") { sb = {3, 1}; sr = {1, 1}; sd = {3, 1}; } else if (s == "Blue-Cream Tortie") { sb = {3, 1}; sr = {1, 1}; sd = {0, 1}; } else if (s == "Chocolate-Red Tortie") { sb = {0, 1}; sr = {1, 1}; sd = {3, 1}; } else { sb = {0, 1}; sr = {1, 1}; sd = {0, 1}; } if (t == "Black") { tb = {3, 1}; tr = {0, 1}; td = {3, 1}; } else if (t == "Blue") { tb = {3, 1}; tr = {0, 1}; td = {0, 1}; } else if (t == "Chocolate") { tb = {0, 1}; tr = {0, 1}; td = {3, 1}; } else if (t == "Lilac") { tb = {0, 1}; tr = {0, 1}; td = {0, 1}; } else if (t == "Red") { tb = {1, 1}; tr = {1, 0}; td = {3, 1}; } else { tb = {1, 1}; tr = {1, 0}; td = {0, 1}; } double x[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; double q = (sb.first + sb.second) * (sr.first + sr.second) * (sd.first + sd.second) * (tb.first + tb.second) * (tr.first + tr.second) * (td.first + td.second); for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) for (int l = 0; l < 2; l++) for (int m = 0; m < 2; m++) for (int n = 0; n < 2; n++) { int p = (i ? sb.second : sb.first) * (j ? sr.second : sr.first) * (k ? sd.second : sd.first) * (l ? tb.second : tb.first) * (m ? tr.second : tr.first) * (n ? td.second : td.first); if (!p) continue; if ((i == 0 || l == 0) && j == 1 && m == 1 && (k == 0 || n == 0)) x[0] += p / q; else if ((i == 0 || l == 0) && j == 1 && m == 1 && k == 1 && n == 1) x[1] += p / q; else if (i == 1 && l == 1 && j == 1 && m == 1 && (k == 0 || n == 0)) x[2] += p / q; else if (i == 1 && l == 1 && j == 1 && m == 1 && k == 1 && n == 1) x[3] += p / q; else if (j == 0 && m == 0 && (k == 0 || n == 0)) x[4] += p / q; else if (j == 0 && m == 0 && k == 1 && n == 1) x[5] += p / q; else if ((i == 0 || l == 0) && j == 1 && m == 0 && (k == 0 || n == 0)) { x[0] += p / (q * 2); x[6] += p / (q * 2); } else if ((i == 0 || l == 0) && j == 1 && m == 0 && k == 1 && n == 1) { x[1] += p / (q * 2); x[7] += p / (q * 2); } else if (i == 1 && l == 1 && j == 1 && m == 0 && (k == 0 || n == 0)) { x[2] += p / (q * 2); x[8] += p / (q * 2); } else if (i == 1 && l == 1 && j == 1 && m == 0 && k == 1 && n == 1) { x[3] += p / (q * 2); x[9] += p / (q * 2); } else if ((i == 0 || l == 0) && j == 0 && m == 1 && (k == 0 || n == 0)) { x[4] += p / (q * 2); x[6] += p / (q * 2); } else if ((i == 0 || l == 0) && j == 0 && m == 1 && k == 1 && n == 1) { x[5] += p / (q * 2); x[7] += p / (q * 2); } else if (i == 1 && l == 1 && j == 0 && m == 1 && (k == 0 || n == 0)) { x[4] += p / (q * 2); x[8] += p / (q * 2); } else if (i == 1 && l == 1 && j == 0 && m == 1 && k == 1 && n == 1) { x[5] += p / (q * 2); x[9] += p / (q * 2); } } string n[10] = {"Black", "Blue", "Chocolate", "Lilac", "Red", "Cream", "Black-Red Tortie", "Blue-Cream Tortie", "Chocolate-Red Tortie", "Lilac-Cream Tortie"}; vector<pair<double, string>> v; for (int i = 0; i < 10; i++) if (x[i]) v.push_back({-x[i], n[i]}); sort(v.begin(), v.end()); for (auto z : v) cout << z.second << " " << fixed << setprecision(9) << -z.first << endl; }
2,225
10,786
""" To know more or get code samples, please visit my website: https://mofanpy.com/tutorials/ Or search: 莫烦Python Thank you for supporting! """ # please note, all tutorial code are running under python3.5. # If you use the version like python2.7, please modify the code accordingly # 3 - backend """ Details are showing in the video. ---------------------- Method 1: If you have run Keras at least once, you will find the Keras configuration file at: ~/.keras/keras.json If it isn't there, you can create it. The default configuration file looks like this: { "image_dim_ordering": "tf", "epsilon": 1e-07, "floatx": "float32", "backend": "theano" } Simply change the field backend to either "theano" or "tensorflow", and Keras will use the new configuration next time you run any Keras code. ---------------------------- Method 2: define this before import keras: >>> import os >>> os.environ['KERAS_BACKEND']='theano' >>> import keras Using Theano backend. """
311
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Metz","circ":"2ème circonscription","dpt":"Moselle","inscrits":17583,"abs":12265,"votants":5318,"blancs":372,"nuls":211,"exp":4735,"res":[{"nuance":"REM","nom":"<NAME>","voix":2807},{"nuance":"LR","nom":"<NAME>","voix":1928}]}
114
533
<gh_stars>100-1000 /* Copyright (c) 2018 Anakin Authors, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef ANAKIN_SABER_FUNCS_IMPL_X86_SABER_LAYER_NORM_H #define ANAKIN_SABER_FUNCS_IMPL_X86_SABER_LAYER_NORM_H #include "saber/funcs/impl/impl_layer_norm.h" namespace anakin{ namespace saber{ template <DataType OpDtype> class SaberLayerNorm<X86, OpDtype>:public ImplBase<X86, OpDtype, LayerNormParam<X86> > { public: typedef typename DataTrait<X86, OpDtype>::Dtype OpDataType; SaberLayerNorm() = default; ~SaberLayerNorm() {} virtual SaberStatus init(const std::vector<Tensor<X86>* >& inputs, std::vector<Tensor<X86>* >& outputs, LayerNormParam<X86> &param, Context<X86> &ctx) { // get context this->_ctx = &ctx; return create(inputs, outputs, param, ctx); } virtual SaberStatus create(const std::vector<Tensor<X86>* >& inputs, std::vector<Tensor<X86>* >& outputs, LayerNormParam<X86> &param, Context<X86> &ctx) { inner_size = inputs[0]->count_valid(param.axis, inputs[0]->dims()); outer_size = inputs[0]->count_valid(0, param.axis); if (param.scale_weights()->valid_size() == 0) { flag_scale = false; } else { flag_scale = true; } if (param.bias_weights()->valid_size() == 0) { flag_bias = false; } else { flag_bias = true; } return SaberSuccess; } virtual SaberStatus dispatch(const std::vector<Tensor<X86>* >& inputs, std::vector<Tensor<X86>* >& outputs, LayerNormParam<X86> &param); private: int inner_size; int outer_size; bool flag_scale{true}; bool flag_bias{true}; }; } //namespace saber } //namespace anakin #endif //ANAKIN_SABER_FUNCS_IMPL_X86_SABER_LAYER_NORM_H
1,179
1,350
/** * Copyright Microsoft Corporation * * 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.microsoft.windowsazure.services.media.models; import java.util.Date; import com.microsoft.windowsazure.services.media.implementation.ODataEntity; import com.microsoft.windowsazure.services.media.implementation.atom.EntryType; import com.microsoft.windowsazure.services.media.implementation.content.NotificationEndPointType; /** * Type containing data about notification end points. * */ public class NotificationEndPointInfo extends ODataEntity<NotificationEndPointType> { /** * Creates a new {@link NotificationEndPointInfo} wrapping the given ATOM * entry and content objects. * * @param entry * Entry containing this AccessPolicy data * @param content * Content with the AccessPolicy data */ public NotificationEndPointInfo(EntryType entry, NotificationEndPointType content) { super(entry, content); } /** * Get the notification end point id. * * @return the id. */ public String getId() { return getContent().getId(); } /** * Get the name. * * @return the name. */ public String getName() { return getContent().getName(); } /** * Get the creation date. * * @return the date. */ public Date getCreated() { return getContent().getCreated(); } /** * Get the type of the end point. * * @return the end point type. */ public EndPointType getEndPointType() { return EndPointType.fromCode(getContent().getEndPointType()); } /** * Gets the end point address. * * @return the end point address */ public String getEndPointAddress() { return getContent().getEndPointAddress(); } }
833
435
<filename>pycon-us-2021/videos/introduction-to-sprinting-workshop-chalmer-lowe.json { "copyright_text": null, "description": "", "duration": 5821, "language": "eng", "recorded": "2021-05-16", "related_urls": [ { "label": "Conference schedule", "url": "https://us.pycon.org/2021/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/rtcyQN6sx7s/hqdefault.jpg?sqp=-oaymwEcCNACELwBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLBcyrYYFvHS90a54d_L6VVmSG08Rg", "title": "Introduction to Sprinting Workshop", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=rtcyQN6sx7s" } ] }
342
485
import sensor, image, lcd, time lcd.init(freq=15000000) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.set_hmirror(1) sensor.set_vflip(1) sensor.run(1) sensor.skip_frames(30) import video v = video.open("/sd/capture.avi", audio = False, record=1, interval=200000, quality=50) tim = time.ticks_ms() for i in range(50): tim = time.ticks_ms() img = sensor.snapshot() lcd.display(img) img_len = v.record(img) # print("record",time.ticks_ms() - tim) print("record_finish") v.record_finish() v.__del__() # play your record v = video.open("/sd/capture.avi") print(v) v.volume(50) while True: if v.play() == 0: print("play end") break print("play finish") v.__del__() lcd.clear()
344
2,706
#ifndef _FCEU_DRIVER_H #define _FCEU_DRIVER_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif #include "fceu-types.h" #include "git.h" #include "debug.h" #define FCEUNPCMD_RESET 0x01 #define FCEUNPCMD_POWER 0x02 #define FCEUNPCMD_VSUNICOIN 0x07 #define FCEUNPCMD_VSUNIDIP0 0x08 #define FCEUNPCMD_FDSINSERTx 0x10 #define FCEUNPCMD_FDSINSERT 0x18 #define FCEUNPCMD_FDSEJECT 0x19 #define FCEUNPCMD_FDSSELECT 0x1A #define FCEUNPCMD_LOADSTATE 0x80 #define FCEUNPCMD_SAVESTATE 0x81 /* Sent from server to client. */ #define FCEUNPCMD_LOADCHEATS 0x82 #define FCEUNPCMD_TEXT 0x90 FILE *FCEUD_UTF8fopen(const char *fn, const char *mode); /* This makes me feel dirty for some reason. */ void FCEU_printf(char *format, ...); #define FCEUI_printf FCEU_printf /* Video interface */ void FCEUD_SetPalette(uint8 index, uint8 r, uint8 g, uint8 b); void FCEUD_GetPalette(uint8 i, uint8 *r, uint8 *g, uint8 *b); /* Displays an error. Can block or not. */ void FCEUD_PrintError(char *s); void FCEUD_Message(char *s); void FCEUD_DispMessage(char *m); #ifdef NETWORK /* Network interface */ /* Call only when a game is loaded. */ int FCEUI_NetplayStart(int nlocal, int divisor); /* Call when network play needs to stop. */ void FCEUI_NetplayStop(void); /* Note: YOU MUST NOT CALL ANY FCEUI_* FUNCTIONS WHILE IN FCEUD_SendData() or FCEUD_RecvData(). */ /* Return 0 on failure, 1 on success. */ int FCEUD_SendData(void *data, uint32 len); int FCEUD_RecvData(void *data, uint32 len); /* Display text received over the network. */ void FCEUD_NetplayText(uint8 *text); /* Encode and send text over the network. */ void FCEUI_NetplayText(uint8 *text); /* Called when a fatal error occurred and network play can't continue. This function should call FCEUI_NetplayStop() after it has deinitialized the network on the driver side. */ void FCEUD_NetworkClose(void); #endif int FCEUI_BeginWaveRecord(char *fn); int FCEUI_EndWaveRecord(void); void FCEUI_ResetNES(void); void FCEUI_PowerNES(void); void FCEUI_NTSCSELHUE(void); void FCEUI_NTSCSELTINT(void); void FCEUI_NTSCDEC(void); void FCEUI_NTSCINC(void); void FCEUI_GetNTSCTH(int *tint, int *hue); void FCEUI_SetNTSCTH(int n, int tint, int hue); void FCEUI_SetInput(int port, int type, void *ptr, int attrib); void FCEUI_SetInputFC(int type, void *ptr, int attrib); void FCEUI_DisableFourScore(int s); #define SI_UNSET -1 #define SI_NONE 0 #define SI_GAMEPAD 1 #define SI_ZAPPER 2 #define SI_POWERPADA 3 #define SI_POWERPADB 4 #define SI_ARKANOID 5 #define SI_MOUSE 6 #define SIFC_UNSET -1 #define SIFC_NONE 0 #define SIFC_ARKANOID 1 #define SIFC_SHADOW 2 #define SIFC_4PLAYER 3 #define SIFC_FKB 4 #define SIFC_SUBORKB 5 #define SIFC_PEC586KB 6 #define SIFC_HYPERSHOT 7 #define SIFC_MAHJONG 8 #define SIFC_QUIZKING 9 #define SIFC_FTRAINERA 10 #define SIFC_FTRAINERB 11 #define SIFC_OEKAKIDS 12 #define SIFC_BWORLD 13 #define SIFC_TOPRIDER 14 #define SIS_NONE 0 #define SIS_DATACH 1 #define SIS_NWC 2 #define SIS_VSUNISYSTEM 3 #define SIS_NSF 4 /* New interface functions */ /* 0 to order screen snapshots numerically(0.png), 1 to order them file base-numerically(smb3-0.png). */ void FCEUI_SetSnapName(int a); /* 0 to keep 8-sprites limitation, 1 to remove it */ void FCEUI_DisableSpriteLimitation(int a); /* -1 = no change, 0 = show, 1 = hide, 2 = internal toggle */ void FCEUI_SetRenderDisable(int sprites, int bg); #ifdef __LIBRETRO__ FCEUGI *FCEUI_LoadGame(const char *name, uint8_t *buf, size_t bufsize); #else /* name=path and file to load. returns 0 on failure, 1 on success */ FCEUGI *FCEUI_LoadGame(const char *name); #endif #ifdef COPYFAMI /* Fake UNIF board to start new CFHI instance */ FCEUGI *FCEUI_CopyFamiStart(); #endif /* allocates memory. 0 on failure, 1 on success. */ int FCEUI_Initialize(void); /* Emulates a frame. */ void FCEUI_Emulate(uint8 **, int32 **, int32 *, int); /* Closes currently loaded game */ void FCEUI_CloseGame(void); /* Deallocates all allocated memory. Call after FCEUI_Emulate() returns. */ void FCEUI_Kill(void); /* Enable/Disable game genie. a=0 disable, a=1 enable */ void FCEUI_SetGameGenie(int a); /* Set video system a=0 NTSC, a=1 PAL */ void FCEUI_SetVidSystem(int a); /* Convenience function; returns currently emulated video system(0=NTSC, 1=PAL). */ int FCEUI_GetCurrentVidSystem(int *slstart, int *slend); #ifdef FRAMESKIP /* Should be called from FCEUD_BlitScreen(). Specifies how many frames to skip until FCEUD_BlitScreen() is called. FCEUD_BlitScreenDummy() will be called instead of FCEUD_BlitScreen() when when a frame is skipped. */ void FCEUI_FrameSkip(int x); #endif /* First and last scanlines to render, for ntsc and pal emulation. */ void FCEUI_SetRenderedLines(int ntscf, int ntscl, int palf, int pall); /* Sets the base directory(save states, snapshots, etc. are saved in directories below this directory. */ void FCEUI_SetBaseDirectory(char *dir); #ifdef __LIBRETRO__ void FCEUI_SetSaveDirectory(char *sav_dir); #endif /* Tells FCE Ultra to copy the palette data pointed to by pal and use it. Data pointed to by pal needs to be 64*3 bytes in length. */ void FCEUI_SetPaletteArray(uint8 *pal); /* Sets up sound code to render sound at the specified rate, in samples per second. Only sample rates of 44100, 48000, and 96000 are currently supported. If "Rate" equals 0, sound is disabled. */ void FCEUI_Sound(int Rate); void FCEUI_SetSoundVolume(uint32 volume); void FCEUI_SetSoundQuality(int quality); void FCEUI_SelectState(int); /* "fname" overrides the default save state filename code if non-NULL. */ void FCEUI_SaveState(char *fname); void FCEUI_LoadState(char *fname); void FCEUI_SelectMovie(int); void FCEUI_SaveMovie(char *fname); void FCEUI_LoadMovie(char *fname); int32 FCEUI_GetDesiredFPS(void); void FCEUI_SaveSnapshot(void); void FCEU_DispMessage(char *format, ...); #define FCEUI_DispMessage FCEU_DispMessage int FCEUI_DecodePAR(const char *code, uint16 *a, uint8 *v, int *c, int *type); int FCEUI_DecodeGG(const char *str, uint16 *a, uint8 *v, int *c); int FCEUI_AddCheat(const char *name, uint32 addr, uint8 val, int compare, int type); int FCEUI_DelCheat(uint32 which); int FCEUI_ToggleCheat(uint32 which); int32 FCEUI_CheatSearchGetCount(void); void FCEUI_CheatSearchGetRange(uint32 first, uint32 last, int (*callb)(uint32 a, uint8 last, uint8 current)); void FCEUI_CheatSearchGet(int (*callb)(uint32 a, uint8 last, uint8 current, void *data), void *data); void FCEUI_CheatSearchBegin(void); void FCEUI_CheatSearchEnd(int type, uint8 v1, uint8 v2); void FCEUI_ListCheats(int (*callb)(char *name, uint32 a, uint8 v, int compare, int s, int type, void *data), void *data); int FCEUI_GetCheat(uint32 which, char **name, uint32 *a, uint8 *v, int *compare, int *s, int *type); int FCEUI_SetCheat(uint32 which, const char *name, int32 a, int32 v, int compare, int s, int type); void FCEUI_CheatSearchShowExcluded(void); void FCEUI_CheatSearchSetCurrentAsOriginal(void); #define FCEUIOD_STATE 0 #define FCEUIOD_SNAPS 1 #define FCEUIOD_NV 2 #define FCEUIOD_CHEATS 3 #define FCEUIOD_MISC 4 #define FCEUIOD_MOVIE 5 #define FCEUIOD__COUNT 6 void FCEUI_SetDirOverride(int which, char *n); void FCEUI_MemDump(uint16 a, int32 len, void (*callb)(uint16 a, uint8 v)); uint8 FCEUI_MemSafePeek(uint16 A); void FCEUI_MemPoke(uint16 a, uint8 v, int hl); void FCEUI_NMI(void); void FCEUI_IRQ(void); uint16 FCEUI_Disassemble(void *XA, uint16 a, char *stringo); void FCEUI_GetIVectors(uint16 *reset, uint16 *irq, uint16 *nmi); uint32 FCEUI_CRC32(uint32 crc, uint8 *buf, uint32 len); //void FCEUI_ToggleTileView(void); void FCEUI_SetLowPass(int q); void FCEUI_NSFSetVis(int mode); int FCEUI_NSFChange(int amount); int FCEUI_NSFGetInfo(uint8 *name, uint8 *artist, uint8 *copyright, int maxlen); void FCEUI_VSUniToggleDIPView(void); void FCEUI_VSUniToggleDIP(int w); uint8 FCEUI_VSUniGetDIPs(void); void FCEUI_VSUniSetDIP(int w, int state); void FCEUI_VSUniCoin(void); int FCEUI_FDSInsert(int oride); int FCEUI_FDSEject(void); void FCEUI_FDSSelect(void); int FCEUI_DatachSet(const uint8 *rcode); #ifdef __cplusplus } #endif #endif
3,290
5,421
<reponame>jayvdb/Nuitka<gh_stars>1000+ # Stub only, D support was broken with Python2.6 and unnecessary to Nuitka def generate(env): return def exists(env): return False
66
316
<gh_stars>100-1000 { "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "root": true, "env": { "node": true, "jest": true }, "parser": "@typescript-eslint/parser", "parserOptions": { "sourceType": "module", "project": "tsconfig.json" }, "plugins": [ "@typescript-eslint" ], "rules": { "@typescript-eslint/array-type": "warn", "@typescript-eslint/brace-style": "warn", "@typescript-eslint/comma-spacing": "warn", "@typescript-eslint/consistent-type-assertions": "warn", "@typescript-eslint/func-call-spacing": "warn", "@typescript-eslint/indent": ["warn", 2, { "SwitchCase": 1 }], "@typescript-eslint/member-delimiter-style": "warn", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-throw-literal": "warn", "@typescript-eslint/no-unnecessary-boolean-literal-compare": "warn", "@typescript-eslint/no-unnecessary-condition": "warn", "@typescript-eslint/prefer-for-of": "warn", "@typescript-eslint/prefer-includes": "warn", "@typescript-eslint/prefer-optional-chain": "warn", "@typescript-eslint/prefer-string-starts-ends-with": "warn", "@typescript-eslint/quotes": ["warn", "single"], "@typescript-eslint/require-array-sort-compare": "warn", "@typescript-eslint/type-annotation-spacing": "warn", "@typescript-eslint/space-before-function-paren": ["warn", { "anonymous": "always", "asyncArrow": "always", "named": "never" }], "array-bracket-spacing": "warn", "arrow-parens": ["warn", "as-needed"], "computed-property-spacing": "warn", "consistent-return": "warn", "curly": ["warn", "all"], "eol-last": "warn", "eqeqeq": "warn", "key-spacing": ["warn"], "new-cap": ["warn", { "capIsNewExceptions": [ "Global", "Injectable", "Module" ] }], "new-parens": "warn", "no-multiple-empty-lines": ["warn", { "max": 1 }], "no-nested-ternary": "warn", "no-return-assign": ["warn", "always"], "no-trailing-spaces": "warn", "no-unneeded-ternary": "warn", "object-curly-spacing": ["warn", "always"], "padded-blocks": ["warn", "never"], "quote-props": ["warn", "consistent-as-needed"], "semi-spacing": "warn", "sort-imports": "warn", "space-before-blocks": ["warn", "always"], "space-in-parens": "warn", "space-infix-ops": ["warn", { "int32Hint": true }], "space-unary-ops": "warn", "spaced-comment": ["warn", "always"], "yoda": ["warn", "always", { "onlyEquality": true }] } }
1,193
2,210
<filename>vendor/bundle/ruby/2.6.0/gems/commonmarker-0.17.13/ext/commonmarker/footnotes.h #ifndef CMARK_FOOTNOTES_H #define CMARK_FOOTNOTES_H #include "map.h" #ifdef __cplusplus extern "C" { #endif struct cmark_footnote { cmark_map_entry entry; cmark_node *node; unsigned int ix; }; typedef struct cmark_footnote cmark_footnote; void cmark_footnote_create(cmark_map *map, cmark_node *node); cmark_map *cmark_footnote_map_new(cmark_mem *mem); #ifdef __cplusplus } #endif #endif
215
688
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.recognizers.text.numberwithunit.chinese.parsers; import com.microsoft.recognizers.text.Culture; import com.microsoft.recognizers.text.CultureInfo; import com.microsoft.recognizers.text.numberwithunit.chinese.extractors.CurrencyExtractorConfiguration; import com.microsoft.recognizers.text.numberwithunit.resources.ChineseNumericWithUnit; import java.util.Map; public class CurrencyParserConfiguration extends ChineseNumberWithUnitParserConfiguration { @Override public Map<String, String> getCurrencyNameToIsoCodeMap() { return ChineseNumericWithUnit.CurrencyNameToIsoCodeMap; } @Override public Map<String, String> getCurrencyFractionCodeList() { return ChineseNumericWithUnit.FractionalUnitNameToCodeMap; } public CurrencyParserConfiguration() { this(new CultureInfo(Culture.Chinese)); } public CurrencyParserConfiguration(CultureInfo cultureInfo) { super(cultureInfo); this.bindDictionary(CurrencyExtractorConfiguration.CurrencySuffixList); this.bindDictionary(CurrencyExtractorConfiguration.CurrencyPrefixList); } }
384
363
# ============================================================================== # Copyright 2020-present NAVER Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow_hub as hub import numpy as np from tqdm import tqdm import sys sys.path.append('./') sys.path.append('../') from functions.input_fns import * from functions import data_config from utils import data_util import os try: import urllib2 as urllib except ImportError: import urllib.request as urllib """ Examples: python kd/eval_amoebanet.py """ flags.DEFINE_integer('batch_size', 32, 'The number of samples in each batch.') flags.DEFINE_string('data_dir', 'imagenet', 'path to the root directory of images') flags.DEFINE_string('gpu_to_use', '5', '') flags.DEFINE_string('data_name', 'imagenet', 'dataset name to use.') flags.DEFINE_string('preprocessing_type', 'inception_331', 'dataset name to use.') flags.DEFINE_string('model_dir', 'tmp/tfmodel/', 'Create a flag for specifying the model file directory.') FLAGS = flags.FLAGS def input_fn_amoabanet(is_training, use_random_crop, data_dir, batch_size, num_epochs=1, num_gpus=None, dtype=tf.float32, with_drawing_bbox=False, autoaugment_type=None, dataset_name=None, drop_remainder=False, preprocessing_type='imagenet', return_logits=False, dct_method="", train_regex='train*', val_regex='validation*'): filenames = data_util.get_filenames(is_training, data_dir, train_regex=train_regex, val_regex=val_regex) dataset = data_config.get_config(dataset_name) return input_fn(is_training, filenames, use_random_crop, batch_size, dataset.num_train_files, dataset.num_images['train'], dataset.shuffle_buffer, dataset.num_channels, num_epochs, num_gpus, dtype, autoaugment_type=autoaugment_type, with_drawing_bbox=with_drawing_bbox, drop_remainder=drop_remainder, preprocessing_type=preprocessing_type, return_logits=return_logits, dct_method=dct_method) def main(unused_argv): os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu_to_use dconf = data_config.get_config(FLAGS.data_name) dataset = input_fn_amoabanet(False, False, FLAGS.data_dir, FLAGS.batch_size, dataset_name=FLAGS.data_name, preprocessing_type=FLAGS.preprocessing_type) iterator = dataset.make_one_shot_iterator() images, labels = iterator.get_next() module = hub.Module("https://tfhub.dev/google/imagenet/amoebanet_a_n18_f448/classification/1") logits = module(images) # Logits with shape [batch_size, num_classes]. pred = tf.nn.softmax(logits) top1 = tf.argmax(logits, axis=1) np_preds = np.zeros(dconf.num_images['validation'], dtype=np.int64) np_labels = np.zeros(dconf.num_images['validation'], dtype=np.int64) np_i = 0 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) n_loop = dconf.num_images['validation'] // FLAGS.batch_size for _ in tqdm(range(n_loop + 1)): try: _pred, _top1, _labels = sess.run([pred, top1, labels]) np_preds[np_i:np_i + _pred.shape[0]] = _top1 np_labels[np_i:np_i + _labels.shape[0]] = _labels np_i += _pred.shape[0] except tf.errors.OutOfRangeError: break print('Accuracy:') print(np.count_nonzero(np_preds == np_labels) / dconf.num_images['validation']) if __name__ == '__main__': tf.app.run()
2,066
517
<reponame>dhruvrajan/tensorflow-java // Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/util/test_log.proto package org.tensorflow.proto.util.testlog; public interface BuildConfigurationOrBuilder extends // @@protoc_insertion_point(interface_extends:tensorflow.BuildConfiguration) com.google.protobuf.MessageOrBuilder { /** * <pre> * opt, dbg, etc * </pre> * * <code>string mode = 1;</code> */ java.lang.String getMode(); /** * <pre> * opt, dbg, etc * </pre> * * <code>string mode = 1;</code> */ com.google.protobuf.ByteString getModeBytes(); /** * <pre> * CC compiler flags, if known * </pre> * * <code>repeated string cc_flags = 2;</code> */ java.util.List<java.lang.String> getCcFlagsList(); /** * <pre> * CC compiler flags, if known * </pre> * * <code>repeated string cc_flags = 2;</code> */ int getCcFlagsCount(); /** * <pre> * CC compiler flags, if known * </pre> * * <code>repeated string cc_flags = 2;</code> */ java.lang.String getCcFlags(int index); /** * <pre> * CC compiler flags, if known * </pre> * * <code>repeated string cc_flags = 2;</code> */ com.google.protobuf.ByteString getCcFlagsBytes(int index); /** * <pre> * Bazel compilation options, if known * </pre> * * <code>repeated string opts = 3;</code> */ java.util.List<java.lang.String> getOptsList(); /** * <pre> * Bazel compilation options, if known * </pre> * * <code>repeated string opts = 3;</code> */ int getOptsCount(); /** * <pre> * Bazel compilation options, if known * </pre> * * <code>repeated string opts = 3;</code> */ java.lang.String getOpts(int index); /** * <pre> * Bazel compilation options, if known * </pre> * * <code>repeated string opts = 3;</code> */ com.google.protobuf.ByteString getOptsBytes(int index); }
834
828
/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.hasor.dataql.fx.web; import com.alibaba.fastjson.JSON; import net.hasor.core.Singleton; import net.hasor.dataql.UdfSourceAssembly; import net.hasor.utils.StringUtils; import net.hasor.web.Invoker; import net.hasor.web.invoker.HttpParameters; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * Web 函数库。函数库引入 <code>import 'net.hasor.dataql.fx.web.WebUdfSource' as webData;</code> * @author 赵永春 (<EMAIL>) * @version : 2020-03-29 */ @Singleton public class WebUdfSource implements UdfSourceAssembly { /** jsonBody */ public static Object jsonBody() { Invoker invoker = HttpParameters.localInvoker(); if (invoker == null) { return null; } return JSON.parse(invoker.getJsonBodyString()); } // -------------------------------------------------------------------------------------------- /** cookieMap */ public static Map<String, String> cookieMap() { return HttpParameters.cookieMap(); } /** cookieMap,Value是数组 */ public static Map<String, List<String>> cookieArrayMap() { return HttpParameters.cookieArrayMap(); } /** 获取Cookie */ public static String getCookie(String cookieName) { if (StringUtils.isBlank(cookieName)) { return null; } return cookieMap().get(cookieName); } /** 获取Cookie数组形态 */ public static List<String> getCookieArray(String cookieName) { if (StringUtils.isBlank(cookieName)) { return null; } return cookieArrayMap().get(cookieName); } /** 临时 Cookie。临时 Cookie 的 MaxAge = -1 */ public static boolean tempCookie(String cookieName, String value) { HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse(); Cookie cookie = new Cookie(cookieName, value); cookie.setMaxAge(-1); httpResponse.addCookie(cookie); return true; } /** 批量设置临时 Cookie。临时 Cookie 的 MaxAge = -1 */ public static boolean tempCookieAll(Map<String, String> cookieMap) { if (cookieMap != null) { cookieMap.forEach(WebUdfSource::tempCookie); return true; } return false; } /** 存储 Cookie */ public static boolean storeCookie(String cookieName, String value, int maxAge) { HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse(); Cookie cookie = new Cookie(cookieName, value); if (maxAge <= 0) { maxAge = -1; } cookie.setMaxAge(maxAge); httpResponse.addCookie(cookie); return true; } /** 批量设置 Cookie */ public static boolean storeCookieAll(Map<String, String> cookieMap, int maxAge) { if (cookieMap != null) { cookieMap.forEach((cookieName, value) -> { storeCookie(cookieName, value, maxAge); }); return true; } return false; } /** 删除 Cookie */ public static boolean removeCookie(String cookieName) { HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse(); Cookie cookie = new Cookie(cookieName, ""); cookie.setMaxAge(0); httpResponse.addCookie(cookie); return true; } // -------------------------------------------------------------------------------------------- /** headerMap */ public static Map<String, String> headerMap() { return HttpParameters.headerMap(); } /** headerMap,Value是数组 */ public static Map<String, List<String>> headerArrayMap() { return HttpParameters.headerArrayMap(); } /** 获取 Header */ public static String getHeader(String headerName) { if (StringUtils.isBlank(headerName)) { return null; } return headerMap().get(headerName); } /** 获取所有名字相同的 Header */ public static List<String> getHeaderArray(String headerName) { if (StringUtils.isBlank(headerName)) { return null; } return headerArrayMap().get(headerName); } /** 设置 Header */ public static boolean setHeader(String headerName, String value) { if (StringUtils.isBlank(headerName)) { return false; } HttpParameters.localInvoker().getHttpResponse().setHeader(headerName, value); return true; } /** 批量设置 HeaderMap */ public static boolean setHeaderAll(Map<String, String> headerMap) { if (headerMap != null) { HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse(); headerMap.forEach(httpResponse::setHeader); return true; } return false; } /** 添加 Header */ public static boolean addHeader(String headerName, String value) { if (StringUtils.isBlank(headerName)) { return false; } HttpParameters.localInvoker().getHttpResponse().addHeader(headerName, value); return true; } /** 批量添加 HeaderMap */ public static boolean addHeaderAll(Map<String, String> headerMap) { if (headerMap != null) { HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse(); headerMap.forEach(httpResponse::addHeader); return true; } return false; } // -------------------------------------------------------------------------------------------- /** session */ private static HttpSession servletSession() { Invoker invoker = HttpParameters.localInvoker(); if (invoker == null) { return null; } return invoker.getHttpRequest().getSession(); } /** sessionKeys */ public static List<String> sessionKeys() { HttpSession httpSession = servletSession(); if (httpSession == null) { return Collections.emptyList(); } Enumeration<String> attributeNames = httpSession.getAttributeNames(); List<String> names = new ArrayList<>(); while (attributeNames.hasMoreElements()) { names.add(attributeNames.nextElement()); } return names; } /** 获取Session */ public static Object getSession(String key) { if (StringUtils.isBlank(key)) { return null; } HttpSession httpSession = servletSession(); if (httpSession == null) { return null; } return httpSession.getAttribute(key); } /** 设置Session */ public static Object setSession(String key, Object newValue) { if (StringUtils.isBlank(key)) { return null; } HttpSession httpSession = servletSession(); if (httpSession == null) { httpSession = HttpParameters.localInvoker().getHttpRequest().getSession(true); } Object oldValue = httpSession.getAttribute(key); httpSession.setAttribute(key, newValue); return oldValue; } /** 删除Session */ public static boolean removeSession(String key) { if (StringUtils.isBlank(key)) { return false; } HttpSession httpSession = servletSession(); if (httpSession == null) { return false; } httpSession.removeAttribute(key); return true; } /** 删除所有Key */ public static boolean cleanSession() { HttpSession httpSession = servletSession(); if (httpSession == null) { return false; } Enumeration<String> attributeNames = httpSession.getAttributeNames(); while (attributeNames.hasMoreElements()) { httpSession.removeAttribute(attributeNames.nextElement()); } return true; } /** Invalidates this session then unbinds any objects bound to it. */ public static boolean sessionInvalidate() { HttpSession httpSession = servletSession(); if (httpSession == null) { return false; } httpSession.invalidate(); return true; } /** Session ID. */ public static String sessionId() { HttpSession httpSession = servletSession(); if (httpSession == null) { return null; } return httpSession.getId(); } /** 返回客户端发送与之关联的请求的最后一次时间. */ public static long sessionLastAccessedTime() { HttpSession httpSession = servletSession(); if (httpSession == null) { return 0; } return httpSession.getLastAccessedTime(); } }
3,806
66,985
<gh_stars>1000+ /* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.couchbase; import com.couchbase.client.core.env.IoConfig; import com.couchbase.client.core.env.TimeoutConfig; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties.Io; import org.springframework.boot.autoconfigure.couchbase.CouchbaseProperties.Timeouts; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CouchbaseProperties}. * * @author <NAME> */ class CouchbasePropertiesTests { @Test void ioHaveConsistentDefaults() { Io io = new CouchbaseProperties().getEnv().getIo(); assertThat(io.getMinEndpoints()).isEqualTo(IoConfig.DEFAULT_NUM_KV_CONNECTIONS); assertThat(io.getMaxEndpoints()).isEqualTo(IoConfig.DEFAULT_MAX_HTTP_CONNECTIONS); assertThat(io.getIdleHttpConnectionTimeout()).isEqualTo(IoConfig.DEFAULT_IDLE_HTTP_CONNECTION_TIMEOUT); } @Test void timeoutsHaveConsistentDefaults() { Timeouts timeouts = new CouchbaseProperties().getEnv().getTimeouts(); assertThat(timeouts.getConnect()).isEqualTo(TimeoutConfig.DEFAULT_CONNECT_TIMEOUT); assertThat(timeouts.getDisconnect()).isEqualTo(TimeoutConfig.DEFAULT_DISCONNECT_TIMEOUT); assertThat(timeouts.getKeyValue()).isEqualTo(TimeoutConfig.DEFAULT_KV_TIMEOUT); assertThat(timeouts.getKeyValueDurable()).isEqualTo(TimeoutConfig.DEFAULT_KV_DURABLE_TIMEOUT); assertThat(timeouts.getQuery()).isEqualTo(TimeoutConfig.DEFAULT_QUERY_TIMEOUT); assertThat(timeouts.getView()).isEqualTo(TimeoutConfig.DEFAULT_VIEW_TIMEOUT); assertThat(timeouts.getSearch()).isEqualTo(TimeoutConfig.DEFAULT_SEARCH_TIMEOUT); assertThat(timeouts.getAnalytics()).isEqualTo(TimeoutConfig.DEFAULT_ANALYTICS_TIMEOUT); assertThat(timeouts.getManagement()).isEqualTo(TimeoutConfig.DEFAULT_MANAGEMENT_TIMEOUT); } }
819
10,225
package org.jboss.resteasy.reactive.server.model; import java.util.ArrayList; import java.util.List; import org.jboss.resteasy.reactive.common.model.ResourceDynamicFeature; /** * Container for {@link javax.ws.rs.container.DynamicFeature} */ public class DynamicFeatures { private final List<ResourceDynamicFeature> resourceDynamicFeatures = new ArrayList<>(); public void addFeature(ResourceDynamicFeature resourceFeature) { resourceDynamicFeatures.add(resourceFeature); } public List<ResourceDynamicFeature> getResourceDynamicFeatures() { return resourceDynamicFeatures; } }
184
462
{ "extdesc": { "message": "Accomplir des tâches hors connexion avec la famille de produits Google Documents." }, "extname": { "message": "Google Documents hors connexion" } }
79
6,958
// // RasterExecution.hpp // MNN // // Created by MNN on 2020/07/30. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef RasterExecution_hpp #define RasterExecution_hpp #include <map> #include <memory> #include <vector> #include "backend/cuda/core/CUDABackend.hpp" #include "core/Execution.hpp" #include "core/TensorUtils.hpp" namespace MNN { namespace CUDA { class RasterExecution : public Execution { public: RasterExecution(Backend *backend); virtual ~RasterExecution(); virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; private: std::vector<std::pair<void *, Tensor::InsideDescribe::Region *>> mTempInputCopy; bool mNeedZero = false; }; } // namespace CUDA } // namespace MNN #endif
326
4,262
<filename>core/camel-main/src/main/java/org/apache/camel/main/RoutesConfigurer.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.main; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.camel.CamelContext; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.RouteConfigurationsBuilder; import org.apache.camel.RoutesBuilder; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.CamelBeanPostProcessor; import org.apache.camel.support.OrderedComparator; import org.apache.camel.util.StopWatch; import org.apache.camel.util.TimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To configure routes using {@link RoutesCollector} which collects the routes from various sources. */ public class RoutesConfigurer { private static final Logger LOG = LoggerFactory.getLogger(RoutesConfigurer.class); private RoutesCollector routesCollector; private CamelBeanPostProcessor beanPostProcessor; private List<RoutesBuilder> routesBuilders; private String packageScanRouteBuilders; private String routesBuilderClasses; private String javaRoutesExcludePattern; private String javaRoutesIncludePattern; private String routesExcludePattern; private String routesIncludePattern; public List<RoutesBuilder> getRoutesBuilders() { return routesBuilders; } public void setRoutesBuilders(List<RoutesBuilder> routesBuilders) { this.routesBuilders = routesBuilders; } public String getPackageScanRouteBuilders() { return packageScanRouteBuilders; } public void setPackageScanRouteBuilders(String packageScanRouteBuilders) { this.packageScanRouteBuilders = packageScanRouteBuilders; } public String getRoutesBuilderClasses() { return routesBuilderClasses; } public void setRoutesBuilderClasses(String routesBuilderClasses) { this.routesBuilderClasses = routesBuilderClasses; } public String getJavaRoutesExcludePattern() { return javaRoutesExcludePattern; } public void setJavaRoutesExcludePattern(String javaRoutesExcludePattern) { this.javaRoutesExcludePattern = javaRoutesExcludePattern; } public String getJavaRoutesIncludePattern() { return javaRoutesIncludePattern; } public void setJavaRoutesIncludePattern(String javaRoutesIncludePattern) { this.javaRoutesIncludePattern = javaRoutesIncludePattern; } public String getRoutesExcludePattern() { return routesExcludePattern; } public void setRoutesExcludePattern(String routesExcludePattern) { this.routesExcludePattern = routesExcludePattern; } public String getRoutesIncludePattern() { return routesIncludePattern; } public void setRoutesIncludePattern(String routesIncludePattern) { this.routesIncludePattern = routesIncludePattern; } public RoutesCollector getRoutesCollector() { return routesCollector; } public void setRoutesCollector(RoutesCollector routesCollector) { this.routesCollector = routesCollector; } public CamelBeanPostProcessor getBeanPostProcessor() { return beanPostProcessor; } public void setBeanPostProcessor(CamelBeanPostProcessor beanPostProcessor) { this.beanPostProcessor = beanPostProcessor; } /** * Collects routes and rests from the various sources (like registry or opinionated classpath locations) and injects * (adds) these into the Camel context. * * @param camelContext the Camel context */ public void configureRoutes(CamelContext camelContext) throws Exception { final List<RoutesBuilder> routes = new ArrayList<>(); if (getRoutesBuilders() != null) { routes.addAll(getRoutesBuilders()); } if (getRoutesBuilderClasses() != null) { String[] routeClasses = getRoutesBuilderClasses().split(","); for (String routeClass : routeClasses) { Class<RoutesBuilder> routeClazz = camelContext.getClassResolver().resolveClass(routeClass, RoutesBuilder.class); if (routeClazz == null) { LOG.warn("Unable to resolve class: {}", routeClass); continue; } // lets use Camel's injector so the class has some support for dependency injection RoutesBuilder builder = camelContext.getInjector().newInstance(routeClazz); routes.add(builder); } } if (getPackageScanRouteBuilders() != null) { String[] pkgs = getPackageScanRouteBuilders().split(","); Set<Class<?>> set = camelContext.adapt(ExtendedCamelContext.class) .getPackageScanClassResolver() .findImplementations(RoutesBuilder.class, pkgs); for (Class<?> routeClazz : set) { Object builder = camelContext.getInjector().newInstance(routeClazz); if (builder instanceof RoutesBuilder) { routes.add((RoutesBuilder) builder); } else { LOG.warn("Class {} is not a RouteBuilder class", routeClazz); } } } if (getRoutesCollector() != null) { try { LOG.debug("RoutesCollectorEnabled: {}", getRoutesCollector()); // add discovered routes from registry Collection<RoutesBuilder> routesFromRegistry = getRoutesCollector().collectRoutesFromRegistry( camelContext, getJavaRoutesExcludePattern(), getJavaRoutesIncludePattern()); routes.addAll(routesFromRegistry); if (LOG.isDebugEnabled() && !routesFromRegistry.isEmpty()) { LOG.debug("Discovered {} additional RoutesBuilder from registry: {}", routesFromRegistry.size(), getRoutesIncludePattern()); } // add discovered routes from directories StopWatch watch = new StopWatch(); Collection<RoutesBuilder> routesFromDirectory = getRoutesCollector().collectRoutesFromDirectory( camelContext, getRoutesExcludePattern(), getRoutesIncludePattern()); routes.addAll(routesFromDirectory); if (LOG.isDebugEnabled() && !routesFromDirectory.isEmpty()) { LOG.debug("Loaded {} additional RoutesBuilder from: {} (took {})", routesFromDirectory.size(), getRoutesIncludePattern(), TimeUtils.printDuration(watch.taken())); } } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeException(e); } } if (getBeanPostProcessor() != null) { // lets use Camel's bean post processor on any existing route builder classes // so the instance has some support for dependency injection for (RoutesBuilder routeBuilder : routes) { getBeanPostProcessor().postProcessBeforeInitialization(routeBuilder, routeBuilder.getClass().getName()); getBeanPostProcessor().postProcessAfterInitialization(routeBuilder, routeBuilder.getClass().getName()); } } // add the discovered routes addDiscoveredRoutes(camelContext, routes); // then discover and add templates Set<ConfigureRouteTemplates> set = camelContext.getRegistry().findByType(ConfigureRouteTemplates.class); for (ConfigureRouteTemplates crt : set) { LOG.debug("Configuring route templates via: {}", crt); crt.configure(camelContext); } } private void addDiscoveredRoutes(CamelContext camelContext, List<RoutesBuilder> routes) throws Exception { // sort routes according to ordered routes.sort(OrderedComparator.get()); // first add the routes configurations as they are globally for all routes for (RoutesBuilder builder : routes) { if (builder instanceof RouteConfigurationsBuilder) { RouteConfigurationsBuilder rcb = (RouteConfigurationsBuilder) builder; LOG.debug("Adding routes configurations into CamelContext from RouteConfigurationsBuilder: {}", rcb); camelContext.addRoutesConfigurations(rcb); } } // then add the routes for (RoutesBuilder builder : routes) { LOG.debug("Adding routes into CamelContext from RoutesBuilder: {}", builder); camelContext.addRoutes(builder); } } }
3,774
13,648
<reponame>learnforpractice/micropython-cpp # test equality for classes/instances to other types class A: pass class B: pass class C(A): pass print(A == None) print(None == A) print(A == A) print(A() == A) print(A() == A()) print(A == B) print(A() == B) print(A() == B()) print(A == C) print(A() == C) print(A() == C())
146
415
<gh_stars>100-1000 package io.joern.fuzzyc2cpg.ast.statements; import io.joern.fuzzyc2cpg.ast.expressions.Expression; import io.joern.fuzzyc2cpg.ast.walking.ASTNodeVisitor; // By default, Expressions holding only a single // child are replaced by their child during // consolidation. ExpressionHolders are never removed. public class ExpressionHolder extends Expression { @Override public String getEscapedCodeStr() { Expression expr = getExpression(); if (expr == null) { return ""; } setCodeStr(expr.getEscapedCodeStr()); return getCodeStr(); } public Expression getExpression() { if (children == null) { return null; } return (Expression) children.get(0); } @Override public void accept(ASTNodeVisitor visitor) { visitor.visit(this); } }
283
2,151
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.webapps; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowLooper; import org.chromium.base.FileUtils; import org.chromium.base.PathUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.Feature; import org.chromium.testing.local.CustomShadowAsyncTask; import org.chromium.webapk.lib.common.WebApkConstants; import java.io.File; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Tests that directories for WebappActivities are managed correctly. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {CustomShadowAsyncTask.class, ShadowRecordHistogram.class}) public class WebappDirectoryManagerTest { @Rule public MockWebappDataStorageClockRule mClockRule = new MockWebappDataStorageClockRule(); private static final String WEBAPP_ID_1 = "webapp_1"; private static final String WEBAPP_ID_2 = "webapp_2"; private static final String WEBAPP_ID_3 = "webapp_3"; private static final String WEBAPK_ID_1 = WebApkConstants.WEBAPK_ID_PREFIX + "webapp_1"; private static final String WEBAPK_ID_2 = WebApkConstants.WEBAPK_ID_PREFIX + "webapp_2"; private static final String WEBAPK_ID_3 = WebApkConstants.WEBAPK_ID_PREFIX + "webapp_3"; private static class TestWebappDirectoryManager extends WebappDirectoryManager { private Set<Intent> mBaseIntents = new HashSet<Intent>(); @Override protected Set<Intent> getBaseIntentsForAllTasks() { return mBaseIntents; } } /** Deletes directory and all of its children. Recreates empty directory in its place. */ private void deleteDirectoryAndRecreate(File f) { FileUtils.recursivelyDeleteFile(f); Assert.assertTrue(f.mkdirs()); } private Context mContext; private TestWebappDirectoryManager mWebappDirectoryManager; @Before public void setUp() throws Exception { mContext = RuntimeEnvironment.application; ThreadUtils.setThreadAssertsDisabledForTesting(true); PathUtils.setPrivateDataDirectorySuffix("chrome"); mWebappDirectoryManager = new TestWebappDirectoryManager(); mWebappDirectoryManager.resetForTesting(); // Set up directories. deleteDirectoryAndRecreate(mContext.getDataDir()); FileUtils.recursivelyDeleteFile(mWebappDirectoryManager.getBaseWebappDirectory(mContext)); deleteDirectoryAndRecreate(mContext.getCodeCacheDir()); } @After public void tearDown() throws Exception { FileUtils.recursivelyDeleteFile(mContext.getDataDir()); FileUtils.recursivelyDeleteFile(mContext.getCodeCacheDir()); FileUtils.recursivelyDeleteFile(mWebappDirectoryManager.getBaseWebappDirectory(mContext)); FileUtils.recursivelyDeleteFile(WebappDirectoryManager.getWebApkUpdateDirectory()); ThreadUtils.setThreadAssertsDisabledForTesting(false); } public void registerWebapp(String webappId) { WebappRegistry.getInstance().register( webappId, new WebappRegistry.FetchWebappDataStorageCallback() { @Override public void onWebappDataStorageRetrieved(WebappDataStorage storage) {} }); ShadowApplication.getInstance().runBackgroundTasks(); } @Test @Feature({"Webapps"}) public void testDeletesOwnDirectory() throws Exception { File webappDirectory = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPP_ID_1); Assert.assertTrue(webappDirectory.mkdirs()); Assert.assertTrue(webappDirectory.exists()); // Confirm that it deletes the current web app's directory. runCleanup(); Assert.assertFalse(webappDirectory.exists()); } /** * On Lollipop and higher, the {@link WebappDirectoryManager} also deletes directories for web * apps that no longer correspond to tasks in Recents. */ @Test @Feature({"Webapps"}) public void testDeletesDirectoriesForDeadTasks() throws Exception { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return; // Track the three web app directories. File directory1 = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPP_ID_1); File directory2 = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPP_ID_2); File directory3 = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPP_ID_3); // Seed the directory with folders for web apps. Assert.assertTrue(directory1.mkdirs()); Assert.assertTrue(directory2.mkdirs()); Assert.assertTrue(directory3.mkdirs()); // Indicate that another of the web apps is listed in Recents; in real usage this web app // would not be in the foreground and would have persisted its state. mWebappDirectoryManager.mBaseIntents = new HashSet<Intent>(); mWebappDirectoryManager.mBaseIntents.add( new Intent(Intent.ACTION_VIEW, Uri.parse("webapp://webapp_2"))); // Only the directory for the background web app should survive. runCleanup(); Assert.assertFalse(directory1.exists()); Assert.assertTrue(directory2.exists()); Assert.assertFalse(directory3.exists()); } /** * On Lollipop and higher, the {@link WebappDirectoryManager} also deletes directories for * *WebApks* that no longer correspond to tasks in Recents. */ @Test @Feature({"Webapps"}) public void testDeletesDirectoriesForDeadWebApkTasks() throws Exception { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return; // Track the three web app directories. File directory1 = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPK_ID_1); File directory2 = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPK_ID_2); File directory3 = new File(mWebappDirectoryManager.getBaseWebappDirectory(mContext), WEBAPK_ID_3); // Seed the directory with folders for web apps. Assert.assertTrue(directory1.mkdirs()); Assert.assertTrue(directory2.mkdirs()); Assert.assertTrue(directory3.mkdirs()); // Indicate that another of the web apps is listed in Recents; in real usage this web app // would not be in the foreground and would have persisted its state. mWebappDirectoryManager.mBaseIntents.add( new Intent(Intent.ACTION_VIEW, Uri.parse("webapp://webapk-webapp_2"))); // Only the directory for the background web app should survive. runCleanup(); Assert.assertFalse(directory1.exists()); Assert.assertTrue(directory2.exists()); Assert.assertFalse(directory3.exists()); } @Test @Feature({"Webapps"}) public void testDeletesObsoleteDirectories() throws Exception { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return; // Seed the base directory with folders that correspond to pre-L web apps. File baseDirectory = mContext.getDataDir(); File webappDirectory1 = new File(baseDirectory, "app_WebappActivity1"); File webappDirectory6 = new File(baseDirectory, "app_WebappActivity6"); File nonWebappDirectory = new File(baseDirectory, "app_ChromeDocumentActivity"); Assert.assertTrue(webappDirectory1.mkdirs()); Assert.assertTrue(webappDirectory6.mkdirs()); Assert.assertTrue(nonWebappDirectory.mkdirs()); // Make sure only the web app folders are deleted. runCleanup(); Assert.assertFalse(webappDirectory1.exists()); Assert.assertFalse(webappDirectory6.exists()); Assert.assertTrue(nonWebappDirectory.exists()); } /** * Test that WebApk.Update.NumStaleUpdateRequestFiles counts "update request" files for WebAPKs * which have been uninstalled. */ @Test @Feature({"Webapps"}) public void testCountsUpdateFilesForUninstalledWebApks() throws Exception { File directory1 = new File(WebappDirectoryManager.getWebApkUpdateDirectory(), WEBAPK_ID_1); directory1.mkdirs(); File directory2 = new File(WebappDirectoryManager.getWebApkUpdateDirectory(), WEBAPK_ID_2); directory2.mkdirs(); // No entry for WEBAPK_ID_1 and WEBAPK_ID_2 in WebappRegistry because the WebAPKs have been // uninstalled. runCleanup(); Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "WebApk.Update.NumStaleUpdateRequestFiles", 2)); } /** * Test that WebApk.Update.NumStaleUpdateRequestFiles counts "update request" files for WebAPKs * for which an update was requested a long time ago. */ @Test @Feature({"Webapps"}) public void testCountsOldWebApkUpdateFiles() throws Exception { File directory = new File(WebappDirectoryManager.getWebApkUpdateDirectory(), WEBAPK_ID_1); directory.mkdirs(); registerWebapp(WEBAPK_ID_1); WebappDataStorage storage = WebappRegistry.getInstance().getWebappDataStorage(WEBAPK_ID_1); storage.updateTimeOfLastCheckForUpdatedWebManifest(); mClockRule.advance(TimeUnit.DAYS.toMillis(30)); runCleanup(); Assert.assertEquals(1, RecordHistogram.getHistogramValueCountForTesting( "WebApk.Update.NumStaleUpdateRequestFiles", 1)); } /** * Test that WebApk.Update.NumStaleUpdateRequestFiles does not count "update request" files for * WebAPKs for which an update was recently requested. There is a 1-23 hour delay between * a WebAPK update being scheduled to the WebAPK being updated. */ @Test @Feature({"Webapps"}) public void testDoesNotCountFilesForNewlyScheduledUpdates() throws Exception { File directory = new File(WebappDirectoryManager.getWebApkUpdateDirectory(), WEBAPK_ID_1); directory.mkdirs(); registerWebapp(WEBAPK_ID_1); WebappDataStorage storage = WebappRegistry.getInstance().getWebappDataStorage(WEBAPK_ID_1); storage.updateTimeOfLastCheckForUpdatedWebManifest(); mClockRule.advance(1); runCleanup(); Assert.assertEquals(0, RecordHistogram.getHistogramValueCountForTesting( "WebApk.Update.NumStaleUpdateRequestFiles", 1)); } private void runCleanup() throws Exception { mWebappDirectoryManager.cleanUpDirectories(mContext, WEBAPP_ID_1); ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); } }
4,394
470
<reponame>wangdongyang/QMXMFunModule<gh_stars>100-1000 // // LFMovingRemoveView.h // LFMediaEditingController // // Created by LamTsanFeng on 2020/10/29. // Copyright © 2020 LamTsanFeng. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface LFMovingRemoveView : UIView @property (nonatomic, assign, getter=isSelected) BOOL selected; @end NS_ASSUME_NONNULL_END
156
402
/** * Copyright © 2018 spring-data-dynamodb (https://github.com/derjust/spring-data-dynamodb) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.socialsignin.spring.data.dynamodb.repository.support; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshaller; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter; import org.springframework.data.annotation.Id; import org.springframework.data.repository.core.support.ReflectionEntityInformation; import java.util.Map; import java.util.Optional; import java.util.Set; /** * Encapsulates minimal information needed to load DynamoDB entities that have * both hash and range key, and have a composite id attribute annotated with * {@link Id}. * * Delegates to metadata and hashKeyExtractor components for all operations. * * @author <NAME> * @author <NAME> */ public class DynamoDBIdIsHashAndRangeKeyEntityInformationImpl<T, ID> extends ReflectionEntityInformation<T, ID> implements DynamoDBIdIsHashAndRangeKeyEntityInformation<T, ID> { private DynamoDBHashAndRangeKeyExtractingEntityMetadata<T, ID> metadata; private HashAndRangeKeyExtractor<ID, ?> hashAndRangeKeyExtractor; private Optional<String> projection = Optional.empty(); private Optional<Integer> limit = Optional.empty(); public DynamoDBIdIsHashAndRangeKeyEntityInformationImpl(Class<T> domainClass, DynamoDBHashAndRangeKeyExtractingEntityMetadata<T, ID> metadata) { super(domainClass, Id.class); this.metadata = metadata; this.hashAndRangeKeyExtractor = metadata.getHashAndRangeKeyExtractor(getIdType()); } @Override public Optional<String> getProjection() { return projection; } @Override public Optional<Integer> getLimit() { return limit; } @Override public boolean isRangeKeyAware() { return true; } @Override public Object getHashKey(final ID id) { return hashAndRangeKeyExtractor.getHashKey(id); } @Override public Object getRangeKey(final ID id) { return hashAndRangeKeyExtractor.getRangeKey(id); } @Override public Optional<String> getOverriddenAttributeName(String attributeName) { return metadata.getOverriddenAttributeName(attributeName); } @Override public boolean isHashKeyProperty(String propertyName) { return metadata.isHashKeyProperty(propertyName); } @Override public boolean isCompositeHashAndRangeKeyProperty(String propertyName) { return metadata.isCompositeHashAndRangeKeyProperty(propertyName); } @Override public String getRangeKeyPropertyName() { return metadata.getRangeKeyPropertyName(); } @SuppressWarnings("deprecation") @Override public <V extends DynamoDBMarshaller<?>> V getMarshallerForProperty(String propertyName) { return metadata.getMarshallerForProperty(propertyName); } @Override public DynamoDBTypeConverter<?, ?> getTypeConverterForProperty(String propertyName) { return metadata.getTypeConverterForProperty(propertyName); } @Override public Set<String> getIndexRangeKeyPropertyNames() { return metadata.getIndexRangeKeyPropertyNames(); } @Override public String getHashKeyPropertyName() { return metadata.getHashKeyPropertyName(); } @Override public <H> HashAndRangeKeyExtractor<ID, H> getHashAndRangeKeyExtractor(Class<ID> idClass) { return metadata.getHashAndRangeKeyExtractor(idClass); } @Override public String getDynamoDBTableName() { return metadata.getDynamoDBTableName(); } @Override public Map<String, String[]> getGlobalSecondaryIndexNamesByPropertyName() { return metadata.getGlobalSecondaryIndexNamesByPropertyName(); } @Override public <H> T getHashKeyPropotypeEntityForHashKey(H hashKey) { return metadata.getHashKeyPropotypeEntityForHashKey(hashKey); } @Override public boolean isGlobalIndexHashKeyProperty(String propertyName) { return metadata.isGlobalIndexHashKeyProperty(propertyName); } @Override public boolean isGlobalIndexRangeKeyProperty(String propertyName) { return metadata.isGlobalIndexRangeKeyProperty(propertyName); } }
1,366
3,807
// Copyright 2019 Google // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Crashlytics/Crashlytics/Unwind/Dwarf/FIRCLSDwarfExpressionMachine.h" #include "Crashlytics/Crashlytics/Unwind/Dwarf/FIRCLSDataParsing.h" #include "Crashlytics/Crashlytics/Helpers/FIRCLSDefines.h" #include "Crashlytics/Crashlytics/Unwind/Dwarf/FIRCLSDwarfUnwindRegisters.h" #include "Crashlytics/Crashlytics/Unwind/FIRCLSUnwind_arch.h" #include "Crashlytics/Crashlytics/Helpers/FIRCLSUtility.h" #include "Crashlytics/third_party/libunwind/dwarf.h" #if CLS_DWARF_UNWINDING_SUPPORTED static bool FIRCLSDwarfExpressionMachineExecute_bregN(FIRCLSDwarfExpressionMachine *machine, uint8_t opcode); static bool FIRCLSDwarfExpressionMachineExecute_deref(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_plus_uconst(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_and(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_plus(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_dup(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_swap(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_deref_size(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_ne(FIRCLSDwarfExpressionMachine *machine); static bool FIRCLSDwarfExpressionMachineExecute_litN(FIRCLSDwarfExpressionMachine *machine, uint8_t opcode); #pragma mark - #pragma mark Stack Implementation void FIRCLSDwarfExpressionStackInit(FIRCLSDwarfExpressionStack *stack) { if (!FIRCLSIsValidPointer(stack)) { return; } memset(stack, 0, sizeof(FIRCLSDwarfExpressionStack)); stack->pointer = stack->buffer; } bool FIRCLSDwarfExpressionStackIsValid(FIRCLSDwarfExpressionStack *stack) { if (!FIRCLSIsValidPointer(stack)) { return false; } // check for valid stack pointer if (stack->pointer < stack->buffer) { return false; } if (stack->pointer > stack->buffer + CLS_DWARF_EXPRESSION_STACK_SIZE) { return false; } return true; } bool FIRCLSDwarfExpressionStackPush(FIRCLSDwarfExpressionStack *stack, intptr_t value) { if (!FIRCLSDwarfExpressionStackIsValid(stack)) { return false; } if (stack->pointer == stack->buffer + CLS_DWARF_EXPRESSION_STACK_SIZE) { // overflow stack->pointer = NULL; return false; } *(stack->pointer) = value; stack->pointer += 1; return true; } intptr_t FIRCLSDwarfExpressionStackPeek(FIRCLSDwarfExpressionStack *stack) { if (!FIRCLSDwarfExpressionStackIsValid(stack)) { return 0; } if (stack->pointer == stack->buffer) { // underflow stack->pointer = NULL; return 0; } return *(stack->pointer - 1); } intptr_t FIRCLSDwarfExpressionStackPop(FIRCLSDwarfExpressionStack *stack) { if (!FIRCLSDwarfExpressionStackIsValid(stack)) { return 0; } if (stack->pointer == stack->buffer) { // underflow stack->pointer = NULL; return 0; } stack->pointer -= 1; return *(stack->pointer); } #pragma mark - #pragma mark Machine API bool FIRCLSDwarfExpressionMachineInit(FIRCLSDwarfExpressionMachine *machine, const void *cursor, const FIRCLSThreadContext *registers, intptr_t stackValue) { if (!FIRCLSIsValidPointer(machine)) { return false; } memset(machine, 0, sizeof(FIRCLSDwarfExpressionMachine)); if (!FIRCLSIsValidPointer(cursor)) { return false; } machine->dataCursor = cursor; machine->registers = registers; FIRCLSDwarfExpressionStackInit(&machine->stack); return FIRCLSDwarfExpressionStackPush(&machine->stack, stackValue); } bool FIRCLSDwarfExpressionMachinePrepareForExecution(FIRCLSDwarfExpressionMachine *machine) { if (!FIRCLSIsValidPointer(machine)) { FIRCLSSDKLog("Error: invalid inputs\n"); return false; } uint64_t expressionLength = FIRCLSParseULEB128AndAdvance(&machine->dataCursor); if (expressionLength == 0) { FIRCLSSDKLog("Error: DWARF expression length is zero\n"); return false; } machine->endAddress = machine->dataCursor + expressionLength; return true; } bool FIRCLSDwarfExpressionMachineIsFinished(FIRCLSDwarfExpressionMachine *machine) { if (!FIRCLSIsValidPointer(machine)) { FIRCLSSDKLog("Error: invalid inputs\n"); return true; } if (!FIRCLSIsValidPointer(machine->endAddress) || !FIRCLSIsValidPointer(machine->dataCursor)) { FIRCLSSDKLog("Error: DWARF machine pointers invalid\n"); return true; } if (!FIRCLSDwarfExpressionStackIsValid(&machine->stack)) { FIRCLSSDKLog("Error: DWARF machine stack invalid\n"); return true; } return machine->dataCursor >= machine->endAddress; } bool FIRCLSDwarfExpressionMachineGetResult(FIRCLSDwarfExpressionMachine *machine, intptr_t *result) { if (!FIRCLSIsValidPointer(machine) || !FIRCLSIsValidPointer(result)) { return false; } if (machine->dataCursor != machine->endAddress) { FIRCLSSDKLog("Error: DWARF expression hasn't completed execution\n"); return false; } *result = FIRCLSDwarfExpressionStackPeek(&machine->stack); return FIRCLSDwarfExpressionStackIsValid(&machine->stack); } bool FIRCLSDwarfExpressionMachineExecuteNextOpcode(FIRCLSDwarfExpressionMachine *machine) { if (!FIRCLSIsValidPointer(machine)) { return false; } const uint8_t opcode = FIRCLSParseUint8AndAdvance(&machine->dataCursor); bool success = false; switch (opcode) { case DW_OP_deref: success = FIRCLSDwarfExpressionMachineExecute_deref(machine); break; case DW_OP_dup: success = FIRCLSDwarfExpressionMachineExecute_dup(machine); break; case DW_OP_and: success = FIRCLSDwarfExpressionMachineExecute_and(machine); break; case DW_OP_plus: success = FIRCLSDwarfExpressionMachineExecute_plus(machine); break; case DW_OP_swap: success = FIRCLSDwarfExpressionMachineExecute_swap(machine); break; case DW_OP_plus_uconst: success = FIRCLSDwarfExpressionMachineExecute_plus_uconst(machine); break; case DW_OP_ne: success = FIRCLSDwarfExpressionMachineExecute_ne(machine); break; case DW_OP_lit0: case DW_OP_lit1: case DW_OP_lit2: case DW_OP_lit3: case DW_OP_lit4: case DW_OP_lit5: case DW_OP_lit6: case DW_OP_lit7: case DW_OP_lit8: case DW_OP_lit9: case DW_OP_lit10: case DW_OP_lit11: case DW_OP_lit12: case DW_OP_lit13: case DW_OP_lit14: case DW_OP_lit15: case DW_OP_lit16: case DW_OP_lit17: case DW_OP_lit18: case DW_OP_lit19: case DW_OP_lit20: case DW_OP_lit21: case DW_OP_lit22: case DW_OP_lit23: case DW_OP_lit24: case DW_OP_lit25: case DW_OP_lit26: case DW_OP_lit27: case DW_OP_lit28: case DW_OP_lit29: case DW_OP_lit30: case DW_OP_lit31: success = FIRCLSDwarfExpressionMachineExecute_litN(machine, opcode); break; case DW_OP_breg0: case DW_OP_breg1: case DW_OP_breg2: case DW_OP_breg3: case DW_OP_breg4: case DW_OP_breg5: case DW_OP_breg6: case DW_OP_breg7: case DW_OP_breg8: case DW_OP_breg9: case DW_OP_breg10: case DW_OP_breg11: case DW_OP_breg12: case DW_OP_breg13: case DW_OP_breg14: case DW_OP_breg15: case DW_OP_breg16: case DW_OP_breg17: case DW_OP_breg18: case DW_OP_breg19: case DW_OP_breg20: case DW_OP_breg21: case DW_OP_breg22: case DW_OP_breg23: case DW_OP_breg24: case DW_OP_breg25: case DW_OP_breg26: case DW_OP_breg27: case DW_OP_breg28: case DW_OP_breg29: case DW_OP_breg30: case DW_OP_breg31: success = FIRCLSDwarfExpressionMachineExecute_bregN(machine, opcode); break; case DW_OP_deref_size: success = FIRCLSDwarfExpressionMachineExecute_deref_size(machine); break; default: FIRCLSSDKLog("Error: Unrecognized DWARF expression opcode 0x%x\n", opcode); return false; } return success; } #pragma mark - #pragma mark Helpers static intptr_t FIRCLSDwarfExpressionMachineStackPop(FIRCLSDwarfExpressionMachine *machine) { return FIRCLSDwarfExpressionStackPop(&machine->stack); } static bool FIRCLSDwarfExpressionMachineStackPush(FIRCLSDwarfExpressionMachine *machine, intptr_t value) { return FIRCLSDwarfExpressionStackPush(&machine->stack, value); } #pragma mark - #pragma mark Opcode Implementations static bool FIRCLSDwarfExpressionMachineExecute_bregN(FIRCLSDwarfExpressionMachine *machine, uint8_t opcode) { // find the register number, compute offset value, push const uint8_t regNum = opcode - DW_OP_breg0; if (regNum > CLS_DWARF_MAX_REGISTER_NUM) { FIRCLSSDKLog("Error: DW_OP_breg invalid register number\n"); return false; } int64_t offset = FIRCLSParseLEB128AndAdvance(&machine->dataCursor); FIRCLSSDKLog("DW_OP_breg %d value %d\n", regNum, (int)offset); const intptr_t value = FIRCLSDwarfUnwindGetRegisterValue(machine->registers, regNum) + (intptr_t)offset; return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_deref(FIRCLSDwarfExpressionMachine *machine) { // pop stack, dereference, push result intptr_t value = FIRCLSDwarfExpressionMachineStackPop(machine); FIRCLSSDKLog("DW_OP_deref value %p\n", (void *)value); if (!FIRCLSReadMemory(value, &value, sizeof(value))) { FIRCLSSDKLog("Error: DW_OP_deref failed to read memory\n"); return false; } return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_plus_uconst(FIRCLSDwarfExpressionMachine *machine) { // pop stack, add constant, push result intptr_t value = FIRCLSDwarfExpressionMachineStackPop(machine); value += FIRCLSParseULEB128AndAdvance(&machine->dataCursor); FIRCLSSDKLog("DW_OP_plus_uconst value %lu\n", value); return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_and(FIRCLSDwarfExpressionMachine *machine) { FIRCLSSDKLog("DW_OP_plus_and\n"); intptr_t value = FIRCLSDwarfExpressionMachineStackPop(machine); value = value & FIRCLSDwarfExpressionMachineStackPop(machine); return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_plus(FIRCLSDwarfExpressionMachine *machine) { FIRCLSSDKLog("DW_OP_plus\n"); intptr_t value = FIRCLSDwarfExpressionMachineStackPop(machine); value = value + FIRCLSDwarfExpressionMachineStackPop(machine); return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_dup(FIRCLSDwarfExpressionMachine *machine) { // duplicate top of stack intptr_t value = FIRCLSDwarfExpressionStackPeek(&machine->stack); FIRCLSSDKLog("DW_OP_dup value %lu\n", value); return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_swap(FIRCLSDwarfExpressionMachine *machine) { // swap top two values on the stack intptr_t valueA = FIRCLSDwarfExpressionMachineStackPop(machine); intptr_t valueB = FIRCLSDwarfExpressionMachineStackPop(machine); FIRCLSSDKLog("DW_OP_swap\n"); if (!FIRCLSDwarfExpressionMachineStackPush(machine, valueA)) { return false; } return FIRCLSDwarfExpressionMachineStackPush(machine, valueB); } static bool FIRCLSDwarfExpressionMachineExecute_deref_size(FIRCLSDwarfExpressionMachine *machine) { // pop stack, dereference variable sized value, push result const void *address = (const void *)FIRCLSDwarfExpressionMachineStackPop(machine); const uint8_t readSize = FIRCLSParseUint8AndAdvance(&machine->dataCursor); intptr_t value = 0; FIRCLSSDKLog("DW_OP_deref_size %p size %u\n", address, readSize); switch (readSize) { case 1: value = FIRCLSParseUint8AndAdvance(&address); break; case 2: value = FIRCLSParseUint16AndAdvance(&address); break; case 4: value = FIRCLSParseUint32AndAdvance(&address); break; case 8: // this is a little funky, as an 8 here really doesn't make sense for 32-bit platforms value = (intptr_t)FIRCLSParseUint64AndAdvance(&address); break; default: FIRCLSSDKLog("Error: unrecognized DW_OP_deref_size argument %x\n", readSize); return false; } return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_ne(FIRCLSDwarfExpressionMachine *machine) { FIRCLSSDKLog("DW_OP_ne\n"); intptr_t value = FIRCLSDwarfExpressionMachineStackPop(machine); value = value != FIRCLSDwarfExpressionMachineStackPop(machine); return FIRCLSDwarfExpressionMachineStackPush(machine, value); } static bool FIRCLSDwarfExpressionMachineExecute_litN(FIRCLSDwarfExpressionMachine *machine, uint8_t opcode) { const uint8_t value = opcode - DW_OP_lit0; FIRCLSSDKLog("DW_OP_lit %u\n", value); return FIRCLSDwarfExpressionMachineStackPush(machine, value); } #else INJECT_STRIP_SYMBOL(dwarf_expression_machine) #endif
5,515
320
// // Copyright (c) 2016-2019 <NAME> (kris at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/hana/tuple.hpp> #include <boost/hana/unique.hpp> #include <boost/hana/sort.hpp> namespace hana = boost::hana; int main() { using namespace hana::literals; constexpr auto types = hana::make_tuple( 1_c, 2_c, 3_c, 4_c, 5_c, 6_c, 7_c, 8_c, 9_c, 10_c, 11_c, 12_c, 13_c, 14_c, 15_c, 16_c, 17_c, 18_c, 19_c, 20_c, 21_c, 22_c, 23_c, 24_c, 25_c, 26_c, 27_c, 28_c, 29_c, 30_c, 31_c, 32_c, 33_c, 34_c, 35_c, 36_c, 37_c, 38_c, 39_c, 40_c, 41_c, 42_c, 43_c, 44_c, 45_c, 46_c, 47_c, 48_c, 49_c, 50_c, 51_c, 52_c, 53_c, 54_c, 55_c, 56_c, 57_c, 58_c, 59_c, 60_c, 61_c, 62_c, 63_c, 64_c, 1_c, 65_c, 66_c, 67_c, 68_c, 69_c, 70_c, 71_c, 72_c, 73_c, 74_c, 75_c, 76_c, 77_c, 78_c, 79_c, 80_c, 81_c, 82_c, 83_c, 84_c, 85_c, 86_c, 87_c, 88_c, 89_c, 90_c, 91_c, 92_c, 93_c, 94_c, 95_c, 96_c, 97_c, 98_c, 99_c, 100_c, 101_c, 102_c, 103_c, 104_c, 105_c, 106_c, 107_c, 108_c, 109_c, 110_c, 111_c, 112_c, 113_c, 114_c, 115_c, 116_c, 117_c, 118_c, 119_c, 120_c, 121_c, 122_c, 123_c, 124_c, 125_c, 126_c, 127_c, 128_c, 1_c); using u = decltype(hana::unique(hana::sort(types))); static_assert( std::is_same< decltype(hana::make_tuple( 1_c, 2_c, 3_c, 4_c, 5_c, 6_c, 7_c, 8_c, 9_c, 10_c, 11_c, 12_c, 13_c, 14_c, 15_c, 16_c, 17_c, 18_c, 19_c, 20_c, 21_c, 22_c, 23_c, 24_c, 25_c, 26_c, 27_c, 28_c, 29_c, 30_c, 31_c, 32_c, 33_c, 34_c, 35_c, 36_c, 37_c, 38_c, 39_c, 40_c, 41_c, 42_c, 43_c, 44_c, 45_c, 46_c, 47_c, 48_c, 49_c, 50_c, 51_c, 52_c, 53_c, 54_c, 55_c, 56_c, 57_c, 58_c, 59_c, 60_c, 61_c, 62_c, 63_c, 64_c, 65_c, 66_c, 67_c, 68_c, 69_c, 70_c, 71_c, 72_c, 73_c, 74_c, 75_c, 76_c, 77_c, 78_c, 79_c, 80_c, 81_c, 82_c, 83_c, 84_c, 85_c, 86_c, 87_c, 88_c, 89_c, 90_c, 91_c, 92_c, 93_c, 94_c, 95_c, 96_c, 97_c, 98_c, 99_c, 100_c, 101_c, 102_c, 103_c, 104_c, 105_c, 106_c, 107_c, 108_c, 109_c, 110_c, 111_c, 112_c, 113_c, 114_c, 115_c, 116_c, 117_c, 118_c, 119_c, 120_c, 121_c, 122_c, 123_c, 124_c, 125_c, 126_c, 127_c, 128_c)), u>{}, ""); }
1,536
335
{ "word": "Gnat", "definitions": [ "A small two-winged fly that resembles a mosquito. Gnats include both biting and non-biting forms, and they typically form large swarms.", "A person regarded as tiny or insignificant." ], "parts-of-speech": "Noun" }
101
3,227
<gh_stars>1000+ // Copyright (c) 2003 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // // Author(s) : <NAME> #ifndef CGAL_INTERNAL_INTERSECTIONS_POINT_3_RAY_3_DO_INTERSECT_H #define CGAL_INTERNAL_INTERSECTIONS_POINT_3_RAY_3_DO_INTERSECT_H namespace CGAL { namespace Intersections { namespace internal { template <class K> inline bool do_intersect(const typename K::Point_3& pt, const typename K::Ray_3& ray, const K& k) { return k.has_on_3_object()(ray, pt); } template <class K> inline bool do_intersect(const typename K::Ray_3& ray, const typename K::Point_3& pt, const K& k) { return k.has_on_3_object()(ray, pt); } template <class K> bool Ray_3_has_on_collinear_Point_3(const typename K::Ray_3& r, const typename K::Point_3& p, const K& k) { return k.equal_3_object()(r.source(), p) || k.equal_3_object()( k.construct_direction_3_object()( k.construct_vector_3_object()(r.source(), p)), r.direction()); } } // namespace internal } // namespace Intersections } // namespace CGAL #endif // CGAL_INTERNAL_INTERSECTIONS_POINT_3_RAY_3_DO_INTERSECT_H
643
486
<filename>docs/examples_src/raw_query_usage/field_key_name.py from odmantic import Field, Model class User(Model): name: str = Field(key_name="username") print(+User.name) #> username print(++User.name) #> $username
83
764
<reponame>dchain01/token-profile { "symbol": "NUSD", "address": "0x0C6144c16af288948C8fdB37fD8fEc94bfF3d1d9", "overview":{ "en": "Neutral Dollar (NUSD) is the world’s first metastable token backed by a basket of stablecoins. The instrument is built by Neutral." }, "email": "<EMAIL>", "website": "https://neutralproject.com/", "whitepaper": "https://neutralproject.com/", "state": "NORMAL", "published_on": "2019-05-15", "initial_price": { "USD": "1.00 USD" }, "links": { "blog": "https://blog.neutralproject.com", "twitter": "https://twitter.com/neutral_project", "telegram": "https://t.me/neutralproject", "github": "https://github.com/NeutralGroup", "facebook": "https://www.facebook.com/Neutral-Project-391548818084169/", "medium": "https://medium.com/@neutralproject" } }
339
640
<reponame>qjiang310/PRNN-GRU /*! \file KnobFile.cpp \brief The source file for the KnobFile class. */ // Persistent RNN Includes #include <prnn/detail/util/knob_file.h> #include <prnn/detail/util/string.h> #include <prnn/detail/util/knobs.h> // Standard Library Includes #include <fstream> #include <vector> #include <stdexcept> #include <iostream> namespace prnn { namespace util { KnobFile::KnobFile(const std::string& filename) : _filename(filename) { } static std::string getLine(std::istream& stream); static void parseKnobFileLine(const std::string& line); void KnobFile::loadKnobs() const { std::ifstream stream(_filename); if(!stream.is_open()) { throw std::runtime_error("Failed to open knob file '" + _filename + "' for reading."); } while(stream.good()) { auto line = getLine(stream); parseKnobFileLine(line); } } std::string getLine(std::istream& stream) { typedef std::vector<uint8_t> ByteVector; ByteVector bytes; while(stream.good()) { uint8_t byte = stream.get(); if(!stream.good()) break; if(byte == '\n') break; bytes.push_back(byte); } return std::string(bytes.begin(), bytes.end()); } void parseKnobFileLine(const std::string& line) { auto stripped = removeWhitespace(line); // discard empty lines if(stripped.empty()) return; // discard comments if(stripped[0] == '#') return; auto components = split(stripped, "="); // Knobs should be "key = value" // TODO: handle '=' in strings if(components.size() != 2) { throw std::runtime_error( "Invalid syntax in knob file line '" + line + "'"); } KnobDatabase::addKnob(removeWhitespace(components[0]), removeWhitespace(components[1])); } } }
745
2,329
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shenyu.common.utils; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test cases for PathMatchUtils. */ public final class PathMatchUtilsTest { @Test public void testPathMatch() { // test exact matching assertTrue(PathMatchUtils.match("test", "test")); assertTrue(PathMatchUtils.match("/test", "/test")); // test matching with ?'s assertTrue(PathMatchUtils.match("t?st", "test")); assertTrue(PathMatchUtils.match("??st", "test")); // test matching with *'s assertTrue(PathMatchUtils.match("*", "test")); assertTrue(PathMatchUtils.match("test*", "test")); assertTrue(PathMatchUtils.match("test*", "testTest")); assertFalse(PathMatchUtils.match("test*aaa", "testblaaab")); // test matching with **'s assertTrue(PathMatchUtils.match("/**", "/testing/testing")); assertTrue(PathMatchUtils.match("/test/**", "/test/test")); } @Test public void testPathVariableHandle() { //test filter PathVariable assertTrue(PathMatchUtils.match("{id}/{name}", "/demo/order/path/{id}/{name}".substring("/demo/order/path/{id}/{name}".indexOf("{")))); //test filter original param assertTrue(PathMatchUtils.match("1/godfje@", "/demo/order/path/1/godfje@".substring("demo/order/path/{id}/{name}".indexOf("{") + 1))); //test replaceAll result final String realPath = PathMatchUtils.replaceAll("demo/order/path/{id}/{name}", "/demo/order/path/{id}/{name}".substring("/demo/order/path/{id}/{name}".indexOf("{")), "/demo/order/path/1/godfje@".substring("demo/order/path/{id}/{name}".indexOf("{") + 1)); assertThat(realPath, is("demo/order/path/1/godfje@")); } }
1,034
4,459
#define AXTLS_VERSION "1.2.1"
18
2,194
<reponame>matiaspan/cash-strapped<filename>Pods/pop/pop/POPAnimation.h<gh_stars>1000+ /** Copyright (c) 2014-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #import <Foundation/NSObject.h> #import <POP/POPAnimationTracer.h> #import <POP/POPGeometry.h> @class CAMediaTimingFunction; /** @abstract The abstract animation base class. @discussion Instantiate and use one of the concrete animation subclasses. */ @interface POPAnimation : NSObject /** @abstract The name of the animation. @discussion Optional property to help identify the animation. */ @property (copy, nonatomic) NSString *name; /** @abstract The beginTime of the animation in media time. @discussion Defaults to 0 and starts immediately. */ @property (assign, nonatomic) CFTimeInterval beginTime; /** @abstract The animation delegate. @discussion See {@ref POPAnimationDelegate} for details. */ @property (weak, nonatomic) id delegate; /** @abstract The animation tracer. @discussion Returns the existing tracer, creating one if needed. Call start/stop on the tracer to toggle event collection. */ @property (readonly, nonatomic) POPAnimationTracer *tracer; /** @abstract Optional block called on animation completion. */ @property (copy, nonatomic) void (^completionBlock)(POPAnimation *anim, BOOL finished); /** @abstract Flag indicating whether animation should be removed on completion. @discussion Setting to NO can facilitate animation reuse. Defaults to YES. */ @property (assign, nonatomic) BOOL removedOnCompletion; /** @abstract Flag indicating whether animation is paused. @discussion A paused animation is excluded from the list of active animations. On initial creation, defaults to YES. On animation addition, the animation is implicity unpaused. On animation completion, the animation is implicity paused including for animations with removedOnCompletion set to NO. */ @property (assign, nonatomic, getter = isPaused) BOOL paused; @end /** @abstract The animation delegate. */ @protocol POPAnimationDelegate <NSObject> @optional /** @abstract Called on animation start. @param anim The relevant animation. */ - (void)pop_animationDidStart:(POPAnimation *)anim; /** @abstract Called when value meets or exceeds to value. @param anim The relevant animation. */ - (void)pop_animationDidReachToValue:(POPAnimation *)anim; /** @abstract Called on animation stop. @param anim The relevant animation. @param finished Flag indicating finished state. Flag is true if the animation reached completion before being removed. */ - (void)pop_animationDidStop:(POPAnimation *)anim finished:(BOOL)finished; /** @abstract Called each frame animation is applied. @param anim The relevant animation. */ - (void)pop_animationDidApply:(POPAnimation *)anim; @end @interface NSObject (POP) /** @abstract Add an animation to the reciver. @param anim The animation to add. @param key The key used to identify the animation. @discussion The 'key' may be any string such that only one animation per unique key is added per object. */ - (void)pop_addAnimation:(POPAnimation *)anim forKey:(NSString *)key; /** @abstract Remove all animations attached to the receiver. */ - (void)pop_removeAllAnimations; /** @abstract Remove any animation attached to the receiver for 'key'. @param key The key used to identify the animation. */ - (void)pop_removeAnimationForKey:(NSString *)key; /** @abstract Returns an array containing the keys of all animations currently attached to the receiver. @param The order of keys reflects the order in which animations will be applied. */ - (NSArray *)pop_animationKeys; /** @abstract Returns any animation attached to the receiver. @param key The key used to identify the animation. @returns The animation currently attached, or nil if no such animation exists. */ - (id)pop_animationForKey:(NSString *)key; @end
1,108
12,940
<gh_stars>1000+ { "$schema": "https://aka.ms/azure-quickstart-templates-metadata-schema#", "itemDisplayName": "Deploy an AKS cluster for Azure ML", "type": "QuickStart", "environments": [ "AzureCloud" ], "description": "This template allows you to deploy an entreprise compliant AKS cluster which can be attached to Azure ML", "summary": "This template allows you to deploy an AKS cluster can be easily integrated with entreprise-grade devops process and fullfil the condition to be attached with Azure ML as compute target resources", "githubUsername": "cloudmelon", "dateUpdated": "2021-05-27" }
182
789
<gh_stars>100-1000 package io.advantageous.qbit.meta.swagger.builders; import io.advantageous.qbit.meta.swagger.ApiInfo; import io.advantageous.qbit.meta.swagger.Contact; import io.advantageous.qbit.meta.swagger.License; public class ApiInfoBuilder { /** * Required. The title of the application. */ private String title; /** * A short description of the application. GFM syntax can be used for rich text representation. */ private String description; /** * The Terms of Service for the API. */ private String termsOfService; /** * The Contact info for the Service API. */ private Contact contact; private ContactBuilder contactBuilder; /** * The License info for the Service API. */ private License license; private LicenseBuilder licenseBuilder; /** * Required Provides the version of the application API (not to be confused with the specification version) */ private String version; public String getTitle() { return title; } public ApiInfoBuilder setTitle(String title) { this.title = title; return this; } public String getDescription() { return description; } public ApiInfoBuilder setDescription(String description) { this.description = description; return this; } public String getTermsOfService() { return termsOfService; } public ApiInfoBuilder setTermsOfService(String termsOfService) { this.termsOfService = termsOfService; return this; } public ContactBuilder getContactBuilder() { if (contactBuilder == null) { contactBuilder = new ContactBuilder(); } return contactBuilder; } public ApiInfoBuilder setContactBuilder(ContactBuilder contactBuilder) { this.contactBuilder = contactBuilder; return this; } public Contact getContact() { if (contact == null) { contact = getContactBuilder().build(); } return contact; } public ApiInfoBuilder setContact(Contact contact) { this.contact = contact; return this; } public String getVersion() { return version; } public ApiInfoBuilder setVersion(String version) { this.version = version; return this; } public License getLicense() { if (license == null) { license = getLicenseBuilder().build(); } return license; } public ApiInfoBuilder setLicense(License license) { this.license = license; return this; } public LicenseBuilder getLicenseBuilder() { if (licenseBuilder == null) { licenseBuilder = new LicenseBuilder(); } return licenseBuilder; } public ApiInfoBuilder setLicenseBuilder(LicenseBuilder licenseBuilder) { this.licenseBuilder = licenseBuilder; return this; } public ApiInfo build() { return new ApiInfo(getTitle(), getDescription(), getTermsOfService(), getContact(), getVersion(), getLicense()); } }
1,191
1,673
/* ** strqtok() is like strtok(): It finds pieces of text, in a string, that are ** surrounded by given delimiter characters. It returns each piece, in turn, ** as a string, until every piece has been found. Then, it returns NULL. But, ** strqtok() recognizes quotation marks. A mark makes delimiters look ordinary ** until another quotation mark is seen. That allows us to include delimiters ** in tokens. (This version doesn't allow escaped quotation marks.) ** ** 2014-04-19, <NAME> ** 2014-04-21, <NAME> ** 2014-04-25, <NAME> */ #include <string.h> char* __fastcall__ strqtok (register char* s1, const char* s2) { static char c; static char* start; static char* next = ""; if (s1 == NULL) { s1 = next; if (c == '\"') { goto inQuote; } } /* Search for the start of a token. */ while (strchr (s2, c = *s1)) { if (c == '\0') { /* No more tokens. */ return NULL; } ++s1; } if (c == '\"') { goto skipQuote; } /* Save the start of the token. */ start = s1; /* Search for the end of a non-quoted token. */ while ((c = *s1) != '\"' && !strchr (s2, c)) { ++s1; } if (c == '\0') { /* The end of the last token is the end of the token list; ** don't go beyond it. */ goto found; } /* (A possible begin-quote mark will be rememberred.) */ goto terminate; skipQuote: ++s1; inQuote: /* Don't let a quote mark be rememberred. */ c = '\0'; /* Save the start of the token. */ start = s1; /* Search for the end of a quoted token. */ if ((s1 = strchr (s1, '\"')) == NULL) { /* The quoted token ended with '\0'; therefore, point to a '\0', ** so that the next call will return NULL. */ next = ""; return start; } terminate: *s1 = '\0'; ++s1; found: next = s1; return start; }
851
404
<reponame>liguiming77/vizseq<filename>vizseq/scorers/_cider/__init__.py # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # Adapted from # https://github.com/tylin/coco-caption/blob/master/pycocoevalcap/cider/cider_scorer.py # (authored by <NAME> <<EMAIL>> and <NAME> # <<EMAIL>>) from typing import List, Dict, Tuple from collections import defaultdict import math from concurrent.futures import ProcessPoolExecutor, as_completed import numpy as np from tqdm import tqdm def _batch(a_list: list, n_batches: int): batch_size = len(a_list) // n_batches + int(len(a_list) % n_batches > 0) for i in range(0, len(a_list), batch_size): yield a_list[i: min(i + batch_size, len(a_list))] def _extract_sentence_n_grams(s: str, n: int = 4) -> Dict[Tuple[str], int]: """ :param s: str : sentence to be converted into n-grams :param n: int : number of n-grams for which representation is calculated :return: term frequency vector for n-grams """ words = s.split() counts = defaultdict(int) for k in range(1, n + 1): for i in range(len(words) - k + 1): ngram = tuple(words[i:i + k]) counts[ngram] += 1 return counts def _batch_extract_n_grams( sentences: List[str], n: int = 4 ) -> List[Dict[Tuple[str], int]]: return [_extract_sentence_n_grams(s, n) for s in sentences] def _multiprocess_batch_extract_n_grams( sentences: List[str], n: int = 4, n_workers: int = 1, verbose: bool = False ) -> List[Dict[Tuple[str], int]]: if n_workers == 1: return _batch_extract_n_grams(sentences, n) else: batches = list(_batch(sentences, n_batches=n_workers)) with ProcessPoolExecutor(max_workers=n_workers) as executor: futures = { executor.submit(_batch_extract_n_grams, b, n): i for i, b in enumerate(batches) } progress = as_completed(futures) if verbose: progress = tqdm(progress) tmp = {futures[future]: future.result() for future in progress} result = [] for k in sorted(tmp): result.extend(tmp[k]) return result class _CIDErScorer(object): def __init__( self, n: int = 4, sigma: float = 6.0, n_workers: int = 1, verbose: bool = False ): """ :param n: int : number of n-grams for which representation is calculated :param sigma: float : """ self.n = n self.sigma = sigma self.n_workers = n_workers self.verbose = verbose self.doc_freq = defaultdict(float) self.n_examples = 0 self.ref_len = 1. self.refs = None def _counts_to_vec( self, counts: Dict[Tuple[str], int] ) -> Tuple[List[Dict[Tuple[str], float]], List[float], int]: """ Function maps counts of ngram to vector of tf-idf weights. The function returns vec, an array of dictionary that store mapping of n-gram and tf-idf weights. The n-th entry of array denotes length of n-grams. :param counts: :return: vec (array of dict), norm (array of float), length (int) """ vec = [defaultdict(float) for _ in range(self.n)] length = 0 norm = [0.0 for _ in range(self.n)] for ngram, term_freq in counts.items(): # Give word count 1 if it doesn't appear in reference corpus cur_doc_freq = np.log(max(1.0, self.doc_freq[ngram])) # ngram index n = len(ngram) - 1 # tf (term_freq) * idf (precomputed idf) for n-grams vec[n][ngram] = float(term_freq) * (self.ref_len - cur_doc_freq) # Compute vector norm, use it for computing similarity norm[n] += pow(vec[n][ngram], 2) if n == 1: length += term_freq norm = [np.sqrt(n) for n in norm] return vec, norm, length def _get_sim( self, vec_h: List[Dict[Tuple[str], float]], vec_r: List[Dict[Tuple[str], float]], norm_h: List[float], norm_r: List[float], len_h: int, len_r: int, sigma: float ) -> np.ndarray: """ Compute the cosine similarity of two vectors. :param vec_h: array of dictionary for vector corresponding to hypothesis :param vec_r: array of dictionary for vector corresponding to reference :param norm_h: array of float for vector corresponding to hypothesis :param norm_r: array of float for vector corresponding to reference :param len_h: int containing length of hypothesis :param len_r: int containing length of reference :param sigma: float :return: array of score for each n-grams cosine similarity """ delta = float(len_h - len_r) # measure cosine similarity val = np.array([0.0 for _ in range(self.n)]) for n in range(self.n): for ngram, count in vec_h[n].items(): val[n] += min( vec_h[n][ngram], vec_r[n][ngram] ) * vec_r[n][ngram] if norm_h[n] != 0 and norm_r[n] != 0: val[n] /= norm_h[n] * norm_r[n] assert not math.isnan(val[n]) val[n] *= np.e ** (-(delta ** 2) / (2 * sigma ** 2)) return val def _get_idf(self, references: List[List[str]]): self.refs = [ _multiprocess_batch_extract_n_grams( r, n=self.n, n_workers=self.n_workers, verbose=self.verbose ) for r in references ] for cur_refs in zip(*self.refs): for ngram in set(ngram for r in cur_refs for ngram, c in r.items()): self.doc_freq[ngram] += 1 def get_sent_scores( self, hypothesis: List[str], references: List[List[str]] ) -> List[float]: self.n_examples = len(hypothesis) self.ref_len = np.log(self.n_examples) self._get_idf(references) scores = [] hypo = _multiprocess_batch_extract_n_grams( hypothesis, self.n, self.n_workers, self.verbose ) for h, cur_refs in zip(hypo, self.refs): vec_h, norm_h, len_h = self._counts_to_vec(h) score = np.array([0.0 for _ in range(self.n)]) for r in cur_refs: vec_r, norm_r, len_r = self._counts_to_vec(r) score += self._get_sim( vec_h, vec_r, norm_h, norm_r, len_h, len_r, self.sigma ) score_avg = np.mean(score) / len(cur_refs) * 10.0 scores.append(score_avg) return scores
3,233
721
<reponame>gaybro8777/nucleus<filename>nucleus/util/samplers.h<gh_stars>100-1000 /* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 THIRD_PARTY_NUCLEUS_UTIL_SAMPLERS_H_ #define THIRD_PARTY_NUCLEUS_UTIL_SAMPLERS_H_ #include <random> #include "tensorflow/core/platform/logging.h" #include "nucleus/platform/types.h" namespace nucleus { // Helper class for randomly sampling a fraction of values. // // API is simple: only a fraction_to_keep calls to Keep() will return true. // // So keeping a 10% fraction of the values in a vector<int> x is: // // FractionalSampler sampler(0.10, seed_uint); // for( int v : x ) { // if (sampler.Keep()) { // ... // } // class FractionalSampler { public: // Creates a new FractionalSampler that keeps fraction_to_keep elements on // average among N calls to Keep(). explicit FractionalSampler(double fraction_to_keep, uint64 random_seed) : fraction_to_keep_(fraction_to_keep), generator_(random_seed), uniform_(0.0, 1.0) { CHECK_GE(fraction_to_keep, 0.0) << "Must be between 0.0 and 1.0"; CHECK_LE(fraction_to_keep, 1.0) << "Must be between 0.0 and 1.0"; } // Randomly return true approximately fraction_to_keep of the time. bool Keep() const { return uniform_(generator_) <= fraction_to_keep_; } // Gets the fraction of elements that will be kept. double FractionKept() const { return fraction_to_keep_; } private: const double fraction_to_keep_; // Raw RNG, of a type compatible with STL distribution functions. mutable std::mt19937_64 generator_; // Distribution sampler, to sample uniformly from [0,1). mutable std::uniform_real_distribution<> uniform_; }; } // namespace nucleus #endif // THIRD_PARTY_NUCLEUS_UTIL_SAMPLERS_H_
768
347
<reponame>hbraha/ovirt-engine package org.ovirt.engine.core.bll; import javax.inject.Inject; import org.ovirt.engine.core.bll.context.EngineContext; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmPool; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.NameQueryParameters; import org.ovirt.engine.core.common.queries.QueryReturnValue; import org.ovirt.engine.core.common.queries.QueryType; import org.ovirt.engine.core.dao.VmPoolDao; public class GetVmDataByPoolNameQuery<P extends NameQueryParameters> extends QueriesCommandBase<P> { @Inject private VmPoolDao vmPoolDao; public GetVmDataByPoolNameQuery(P parameters, EngineContext engineContext) { super(parameters, engineContext); } @Override protected void executeQueryCommand() { VM vm = null; VmPool vmpool = vmPoolDao.getByName(getParameters().getName()); if (vmpool != null) { QueryReturnValue getVmRet = backend.runInternalQuery(QueryType.GetVmDataByPoolId, new IdQueryParameters(vmpool.getVmPoolId())); if (getVmRet != null) { vm = getVmRet.getReturnValue(); } } getQueryReturnValue().setReturnValue(vm); } }
541
349
<gh_stars>100-1000 #pragma once #include "common/util.h" #include "nes/generic/rom/rom.h" #include "nes/interfaces/mirroring.h" // NES ROM file container // Owns the raw ROM file data, and has helpful data about it / pointers into it struct ROM_File { // Raw file data const u8* data; uint data_len; struct { // ROM metadata Mirroring::Type mirror_mode; u8 mapper; bool has_battery; // Has battery backed SRAM at 0x6000 - 0x7FFF bool has_trainer; // Has 512 byte trainer at 0x7000 - 0x71FF bool is_PC10; // is a PC-10 Game bool is_VS; // is a VS. Game } meta; struct { // ROM sections struct { const u8* data; uint len; } prg, chr; // Program and Character ROMs struct { const u8* trn_rom; // Trainer const u8* pci_rom; // PlayChoice INST-ROM const u8* pc_prom; // PlayChoice PROM } misc; } rom; ~ROM_File() { delete this->data; } };
381
470
#!/usr/bin/env python import os import os.path import sys import shutil from subprocess import call import importlib import unittest import re from testcases import settings class Workspace(object): def __init__(self): self.root_dir = os.getcwd() self.build_dir = os.path.join(self.root_dir,"tmpbin"); self.log_dir = os.path.join(self.root_dir,"logs"); self.tests_dir = os.path.join(self.root_dir,"testcases"); self.examples_dir = os.path.join(self.root_dir,"../PubSubClient/examples") self.examples = [] self.tests = [] if not os.path.isdir("../PubSubClient"): raise Exception("Cannot find PubSubClient library") try: import ino except: raise Exception("ino tool not installed") def init(self): if os.path.isdir(self.build_dir): shutil.rmtree(self.build_dir) os.mkdir(self.build_dir) if os.path.isdir(self.log_dir): shutil.rmtree(self.log_dir) os.mkdir(self.log_dir) os.chdir(self.build_dir) call(["ino","init"]) shutil.copytree("../../PubSubClient","lib/PubSubClient") filenames = [] for root, dirs, files in os.walk(self.examples_dir): filenames += [os.path.join(root,f) for f in files if f.endswith(".ino")] filenames.sort() for e in filenames: self.examples.append(Sketch(self,e)) filenames = [] for root, dirs, files in os.walk(self.tests_dir): filenames += [os.path.join(root,f) for f in files if f.endswith(".ino")] filenames.sort() for e in filenames: self.tests.append(Sketch(self,e)) def clean(self): shutil.rmtree(self.build_dir) class Sketch(object): def __init__(self,wksp,fn): self.w = wksp self.filename = fn self.basename = os.path.basename(self.filename) self.build_log = os.path.join(self.w.log_dir,"%s.log"%(os.path.basename(self.filename),)) self.build_err_log = os.path.join(self.w.log_dir,"%s.err.log"%(os.path.basename(self.filename),)) self.build_upload_log = os.path.join(self.w.log_dir,"%s.upload.log"%(os.path.basename(self.filename),)) def build(self): sys.stdout.write(" Build: ") sys.stdout.flush() # Copy sketch over, replacing IP addresses as necessary fin = open(self.filename,"r") lines = fin.readlines() fin.close() fout = open(os.path.join(self.w.build_dir,"src","sketch.ino"),"w") for l in lines: if re.match(r"^byte server\[\] = {",l): fout.write("byte server[] = { %s };\n"%(settings.server_ip.replace(".",", "),)) elif re.match(r"^byte ip\[\] = {",l): fout.write("byte ip[] = { %s };\n"%(settings.arduino_ip.replace(".",", "),)) else: fout.write(l) fout.flush() fout.close() # Run build fout = open(self.build_log, "w") ferr = open(self.build_err_log, "w") rc = call(["ino","build"],stdout=fout,stderr=ferr) fout.close() ferr.close() if rc == 0: sys.stdout.write("pass") sys.stdout.write("\n") return True else: sys.stdout.write("fail") sys.stdout.write("\n") with open(self.build_err_log) as f: for line in f: print " ",line, return False def upload(self): sys.stdout.write(" Upload: ") sys.stdout.flush() fout = open(self.build_upload_log, "w") rc = call(["ino","upload"],stdout=fout,stderr=fout) fout.close() if rc == 0: sys.stdout.write("pass") sys.stdout.write("\n") return True else: sys.stdout.write("fail") sys.stdout.write("\n") with open(self.build_upload_log) as f: for line in f: print " ",line, return False def test(self): # import the matching test case, if it exists try: basename = os.path.basename(self.filename)[:-4] i = importlib.import_module("testcases."+basename) except: sys.stdout.write(" Test: no tests found") sys.stdout.write("\n") return c = getattr(i,basename) testmethods = [m for m in dir(c) if m.startswith("test_")] testmethods.sort() tests = [] for m in testmethods: tests.append(c(m)) result = unittest.TestResult() c.setUpClass() if self.upload(): sys.stdout.write(" Test: ") sys.stdout.flush() for t in tests: t.run(result) print "%d/%d"%(result.testsRun-len(result.failures)-len(result.errors),result.testsRun) if not result.wasSuccessful(): if len(result.failures) > 0: for f in result.failures: print "-- %s"%(str(f[0]),) print f[1] if len(result.errors) > 0: print " Errors:" for f in result.errors: print "-- %s"%(str(f[0]),) print f[1] c.tearDownClass() if __name__ == '__main__': run_tests = True w = Workspace() w.init() for e in w.examples: print "--------------------------------------" print "[%s]"%(e.basename,) if e.build() and run_tests: e.test() for e in w.tests: print "--------------------------------------" print "[%s]"%(e.basename,) if e.build() and run_tests: e.test() w.clean()
2,411
489
<filename>src/riotwatcher/_apis/legends_of_runeterra/urls/LorEndpoint.py from ... import Endpoint, UrlConfig class LorEndpoint: def __init__(self, url: str, **kwargs): self._url = f"/lor{url}" def __call__(self, **kwargs): final_url = f"{UrlConfig.lor_url}{self._url}" endpoint = Endpoint(final_url, **kwargs) return endpoint(**kwargs)
163
517
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =======================================================================*/ package org.tensorflow.framework.losses; import org.tensorflow.Operand; import org.tensorflow.framework.losses.impl.AbstractLoss; import org.tensorflow.framework.losses.impl.LossesHelper; import org.tensorflow.op.Ops; import org.tensorflow.types.family.TNumber; /** * Computes the Huber loss between labels and predictions. * * <p>For each value x in <code>error = labels - predictions</code>: * * <pre> * loss = 0.5 * x^2 if |x| &lt;= d * loss = 0.5 * d^2 + d * (|x| - d) if |x| &gt; d * </pre> * * <p>where d is delta. * * <p>Standalone usage: * * <pre> * Operand&lt;TFloat32&gt; labels = * tf.constant(new float[][] {{0.f, 1.f}, {0.f, 0.f}}); * Operand&lt;TFloat32&gt; predictions = * tf.constant(new float[][] {{0.6f, 0.4f}, {0.4f, 0.6f}}); * Huber huberLoss = new Huber(tf); * Operand&lt;TFloat32&gt; result = huberLoss.call(Ops tf, labels, predictions); * // produces 0.155 * </pre> * * <p>Calling with sample weight: * * <pre> * Operand&lt;TFloat32&gt; sampleWeight = tf.constant(new float[] {1.f, 0.f}); * Operand&lt;TFloat32&gt; result = huberLoss.call(Ops tf, labels, predictions, sampleWeight); * // produces 0.09f * </pre> * * <p>Using <code>SUM</code> reduction type: * * <pre> * Huber huberLoss = new Huber(tf, Reduction.SUM); * Operand&lt;TFloat32&gt; result = huberLoss.call(Ops tf, labels, predictions); * // produces 0.32f * </pre> * * <p>Using <code>NONE</code> reduction type: * * <pre> * Huber huberLoss = new Huber(tf, Reduction.NONE); * Operand&lt;TFloat32&gt; result = huberLoss.call(Ops tf, labels, predictions); * // produces [0.18f, 0.13f] * </pre> * * @see <a href="https://en.wikipedia.org/wiki/Huber_loss">Huber loss</a> */ public class Huber extends AbstractLoss { public static final float DELTA_DEFAULT = 1.0f; private final float delta; /** * Creates a Huber AbstractLoss using {@link Class#getSimpleName()} as the loss name, {@link * #DELTA_DEFAULT} as the delta and a AbstractLoss Reduction of {@link * AbstractLoss#REDUCTION_DEFAULT} */ public Huber() { this(null, DELTA_DEFAULT, Reduction.AUTO); } /** * Creates a Huber AbstractLoss using {@link #DELTA_DEFAULT} as the delta and a AbstractLoss * Reduction of {@link AbstractLoss#REDUCTION_DEFAULT} * * @param name the name of the loss, if null then {@link Class#getSimpleName()} is used. */ public Huber(String name) { this(name, DELTA_DEFAULT, Reduction.AUTO); } /** * Creates a Huber AbstractLoss using {@link Class#getSimpleName()} as the loss name and and * {@link #DELTA_DEFAULT} as the delta * * @param reduction Type of Reduction to apply to the loss. */ public Huber(Reduction reduction) { this(null, DELTA_DEFAULT, reduction); } /** * Creates a Huber AbstractLoss using {@link #DELTA_DEFAULT} as the delta * * @param name the name of the loss, if null then {@link Class#getSimpleName()} is used. * @param reduction Type of Reduction to apply to the loss. */ public Huber(String name, Reduction reduction) { this(name, DELTA_DEFAULT, reduction); } /** * Creates a Huber AbstractLoss * * @param name the name of the loss, if null then {@link Class#getSimpleName()} is used. * @param delta the point where the Huber loss function changes from quadratic to linear. * @param reduction Type of Reduction to apply to the loss. */ public Huber(String name, float delta, Reduction reduction) { super(name, reduction); this.delta = delta; } /** {@inheritDoc} */ @Override public <T extends TNumber> Operand<T> call( Ops tf, Operand<? extends TNumber> labels, Operand<T> predictions, Operand<T> sampleWeights) { Operand<T> losses = Losses.huber(tf, labels, predictions, delta); return LossesHelper.computeWeightedLoss(tf, losses, getReduction(), sampleWeights); } }
1,667
2,151
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. * */ #include <stdint.h> #include "dl/api/omxtypes.h" #include "dl/sp/api/mipsSP.h" OMXResult mips_FFTInv_CCSToR_F32_complex(const OMX_F32* pSrc, OMX_F32* pDst, const MIPSFFTSpec_R_FC32* pFFTSpec) { OMX_U32 num_transforms, step; /* Quarter, half and three-quarters of transform size. */ OMX_U32 n1_4, n1_2, n3_4; const OMX_F32* w_re_ptr; const OMX_F32* w_im_ptr; OMX_U32 fft_size = 1 << pFFTSpec->order; OMX_FC32* p_buf = (OMX_FC32*)pFFTSpec->pBuf; const OMX_FC32* p_src = (const OMX_FC32*)pSrc; OMX_FC32* p_dst; OMX_U16* p_bitrev = pFFTSpec->pBitRevInv; OMX_F32 tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, factor; OMX_F32 w_re, w_im; w_re_ptr = pFFTSpec->pTwiddle + 1; w_im_ptr = pFFTSpec->pTwiddle + (OMX_U32)(1 << (pFFTSpec->order - 2)) - 1; /* * Preliminary loop performing input adaptation due to computing real FFT * through complex FFT of half the size. */ for (uint32_t n = 1; n < fft_size / 8; ++n) { tmp1 = p_src[n].Re; tmp2 = p_src[n].Im; tmp3 = p_src[fft_size / 2 - n].Re; tmp4 = p_src[fft_size / 2 - n].Im; tmp5 = tmp1 + tmp3; tmp6 = tmp1 - tmp3; tmp7 = tmp2 + tmp4; tmp8 = tmp2 - tmp4; w_re = *w_re_ptr; w_im = *w_im_ptr; p_buf[p_bitrev[n]].Re = 0.5f * (tmp5 - w_re * tmp7 - w_im * tmp6); p_buf[p_bitrev[n]].Im = 0.5f * (tmp8 + w_re * tmp6 - w_im * tmp7); p_buf[p_bitrev[fft_size / 2 - n]].Re = 0.5f * (tmp5 + w_re * tmp7 + w_im * tmp6); p_buf[p_bitrev[fft_size / 2 - n]].Im = 0.5f * (-tmp8 + w_re * tmp6 - w_im * tmp7); tmp1 = p_src[n + fft_size / 4].Re; tmp2 = p_src[n + fft_size / 4].Im; tmp3 = p_src[fft_size / 4 - n].Re; tmp4 = p_src[fft_size / 4 - n].Im; tmp5 = tmp1 + tmp3; tmp6 = tmp1 - tmp3; tmp7 = tmp2 + tmp4; tmp8 = tmp2 - tmp4; p_buf[p_bitrev[n + fft_size / 4]].Re = 0.5f * (tmp5 + w_im * tmp7 - w_re * tmp6); p_buf[p_bitrev[n + fft_size / 4]].Im = 0.5f * (tmp8 - w_im * tmp6 - w_re * tmp7); p_buf[p_bitrev[fft_size / 4 - n]].Re = 0.5f * (tmp5 - w_im * tmp7 + w_re * tmp6); p_buf[p_bitrev[fft_size / 4 - n]].Im = 0.5f * (-tmp8 - w_im * tmp6 - w_re * tmp7); ++w_re_ptr; --w_im_ptr; } tmp1 = p_src[fft_size / 8].Re; tmp2 = p_src[fft_size / 8].Im; tmp3 = p_src[3 * fft_size / 8].Re; tmp4 = p_src[3 * fft_size / 8].Im; tmp5 = tmp1 + tmp3; tmp6 = tmp1 - tmp3; tmp7 = tmp2 + tmp4; tmp8 = tmp2 - tmp4; w_re = *w_re_ptr; w_im = *w_im_ptr; p_buf[p_bitrev[fft_size / 8]].Re = 0.5f * (tmp5 - w_re * tmp7 - w_im * tmp6); p_buf[p_bitrev[fft_size / 8]].Im = 0.5f * (tmp8 + w_re * tmp6 - w_im * tmp7); p_buf[p_bitrev[3 * fft_size / 8]].Re = 0.5f * (tmp5 + w_re * tmp7 + w_im * tmp6); p_buf[p_bitrev[3 * fft_size / 8]].Im = 0.5f * (-tmp8 + w_re * tmp6 - w_im * tmp7); p_buf[p_bitrev[0]].Re = 0.5f * (p_src[0].Re + p_src[fft_size / 2].Re); p_buf[p_bitrev[0]].Im = 0.5f * (p_src[0].Re - p_src[fft_size / 2].Re); p_buf[p_bitrev[fft_size / 4]].Re = p_src[fft_size / 4].Re; p_buf[p_bitrev[fft_size / 4]].Im = -p_src[fft_size / 4].Im; /* * Loop performing sub-transforms of size 4, * which contain 2 butterfly operations. */ num_transforms = (SUBTRANSFORM_CONST >> (17 - pFFTSpec->order)) | 1; for (uint32_t n = 0; n < num_transforms; ++n) { OMX_U32 offset = pFFTSpec->pOffset[n] << 2; OMX_FC32* p_tmp = p_buf + offset; tmp1 = p_tmp[0].Re + p_tmp[1].Re; tmp2 = p_tmp[0].Im + p_tmp[1].Im; tmp3 = p_tmp[0].Re - p_tmp[1].Re; tmp4 = p_tmp[0].Im - p_tmp[1].Im; tmp5 = p_tmp[2].Re + p_tmp[3].Re; tmp6 = p_tmp[2].Im + p_tmp[3].Im; tmp8 = p_tmp[2].Im - p_tmp[3].Im; tmp7 = p_tmp[2].Re - p_tmp[3].Re; p_tmp[0].Re = tmp1 + tmp5; p_tmp[2].Re = tmp1 - tmp5; p_tmp[0].Im = tmp2 + tmp6; p_tmp[2].Im = tmp2 - tmp6; p_tmp[1].Re = tmp3 - tmp8; p_tmp[3].Re = tmp3 + tmp8; p_tmp[1].Im = tmp4 + tmp7; p_tmp[3].Im = tmp4 - tmp7; } num_transforms = (num_transforms >> 1) | 1; /* * Loop performing sub-transforms of size 8, * which contain four butterfly operations. */ for (uint32_t n = 0; n < num_transforms; ++n) { OMX_U32 offset = pFFTSpec->pOffset[n] << 3; OMX_FC32* p_tmp = p_buf + offset; tmp1 = p_tmp[4].Re + p_tmp[5].Re; tmp3 = p_tmp[6].Re + p_tmp[7].Re; tmp2 = p_tmp[4].Im + p_tmp[5].Im; tmp4 = p_tmp[6].Im + p_tmp[7].Im; tmp5 = tmp1 + tmp3; tmp7 = tmp1 - tmp3; tmp6 = tmp2 + tmp4; tmp8 = tmp2 - tmp4; tmp1 = p_tmp[4].Re - p_tmp[5].Re; tmp2 = p_tmp[4].Im - p_tmp[5].Im; tmp3 = p_tmp[6].Re - p_tmp[7].Re; tmp4 = p_tmp[6].Im - p_tmp[7].Im; p_tmp[4].Re = p_tmp[0].Re - tmp5; p_tmp[0].Re = p_tmp[0].Re + tmp5; p_tmp[4].Im = p_tmp[0].Im - tmp6; p_tmp[0].Im = p_tmp[0].Im + tmp6; p_tmp[6].Re = p_tmp[2].Re + tmp8; p_tmp[2].Re = p_tmp[2].Re - tmp8; p_tmp[6].Im = p_tmp[2].Im - tmp7; p_tmp[2].Im = p_tmp[2].Im + tmp7; tmp5 = SQRT1_2 * (tmp1 - tmp2); tmp7 = SQRT1_2 * (tmp3 + tmp4); tmp6 = SQRT1_2 * (tmp1 + tmp2); tmp8 = SQRT1_2 * (tmp4 - tmp3); tmp1 = tmp5 + tmp7; tmp3 = tmp5 - tmp7; tmp2 = tmp6 + tmp8; tmp4 = tmp6 - tmp8; p_tmp[5].Re = p_tmp[1].Re - tmp1; p_tmp[1].Re = p_tmp[1].Re + tmp1; p_tmp[5].Im = p_tmp[1].Im - tmp2; p_tmp[1].Im = p_tmp[1].Im + tmp2; p_tmp[7].Re = p_tmp[3].Re + tmp4; p_tmp[3].Re = p_tmp[3].Re - tmp4; p_tmp[7].Im = p_tmp[3].Im - tmp3; p_tmp[3].Im = p_tmp[3].Im + tmp3; } step = 1 << (pFFTSpec->order - 4); n1_4 = 4; /* Outer loop that loops over FFT stages. */ for (uint32_t fft_stage = 4; fft_stage <= pFFTSpec->order - 2; ++fft_stage) { n1_2 = 2 * n1_4; n3_4 = 3 * n1_4; num_transforms = (num_transforms >> 1) | 1; for (uint32_t n = 0; n < num_transforms; ++n) { OMX_U32 offset = pFFTSpec->pOffset[n] << fft_stage; OMX_FC32* p_tmp = p_buf + offset; tmp1 = p_tmp[n1_2].Re + p_tmp[n3_4].Re; tmp2 = p_tmp[n1_2].Re - p_tmp[n3_4].Re; tmp3 = p_tmp[n1_2].Im + p_tmp[n3_4].Im; tmp4 = p_tmp[n1_2].Im - p_tmp[n3_4].Im; p_tmp[n1_2].Re = p_tmp[0].Re - tmp1; p_tmp[0].Re = p_tmp[0].Re + tmp1; p_tmp[n1_2].Im = p_tmp[0].Im - tmp3; p_tmp[0].Im = p_tmp[0].Im + tmp3; p_tmp[n3_4].Re = p_tmp[n1_4].Re + tmp4; p_tmp[n1_4].Re = p_tmp[n1_4].Re - tmp4; p_tmp[n3_4].Im = p_tmp[n1_4].Im - tmp2; p_tmp[n1_4].Im = p_tmp[n1_4].Im + tmp2; w_re_ptr = pFFTSpec->pTwiddle + step; w_im_ptr = pFFTSpec->pTwiddle + (OMX_U32)(1 << (pFFTSpec->order - 2)) - step; /* * Loop performing split-radix butterfly operations for one sub-transform. */ for (uint32_t i = 1; i < n1_4; ++i) { w_re = *w_re_ptr; w_im = *w_im_ptr; tmp1 = w_re * p_tmp[n1_2 + i].Re - w_im * p_tmp[n1_2 + i].Im; tmp2 = w_re * p_tmp[n1_2 + i].Im + w_im * p_tmp[n1_2 + i].Re; tmp3 = w_re * p_tmp[n3_4 + i].Re + w_im * p_tmp[n3_4 + i].Im; tmp4 = w_re * p_tmp[n3_4 + i].Im - w_im * p_tmp[n3_4 + i].Re; tmp5 = tmp1 + tmp3; tmp1 = tmp1 - tmp3; tmp6 = tmp2 + tmp4; tmp2 = tmp2 - tmp4; p_tmp[n1_2 + i].Re = p_tmp[i].Re - tmp5; p_tmp[i].Re = p_tmp[i].Re + tmp5; p_tmp[n1_2 + i].Im = p_tmp[i].Im - tmp6; p_tmp[i].Im = p_tmp[i].Im + tmp6; p_tmp[n3_4 + i].Re = p_tmp[n1_4 + i].Re + tmp2; p_tmp[n1_4 + i].Re = p_tmp[n1_4 + i].Re - tmp2; p_tmp[n3_4 + i].Im = p_tmp[n1_4 + i].Im - tmp1; p_tmp[n1_4 + i].Im = p_tmp[n1_4 + i].Im + tmp1; w_re_ptr += step; w_im_ptr -= step; } } step >>= 1; n1_4 <<= 1; } /* Last FFT stage, write data to output buffer. */ n1_2 = 2 * n1_4; n3_4 = 3 * n1_4; factor = (OMX_F32)2.0f / fft_size; p_dst = (OMX_FC32*)pDst; tmp1 = p_buf[n1_2].Re + p_buf[n3_4].Re; tmp2 = p_buf[n1_2].Re - p_buf[n3_4].Re; tmp3 = p_buf[n1_2].Im + p_buf[n3_4].Im; tmp4 = p_buf[n1_2].Im - p_buf[n3_4].Im; p_dst[n1_2].Re = factor * (p_buf[0].Re - tmp1); p_dst[0].Re = factor * (p_buf[0].Re + tmp1); p_dst[n1_2].Im = factor * (p_buf[0].Im - tmp3); p_dst[0].Im = factor * (p_buf[0].Im + tmp3); p_dst[n3_4].Re = factor * (p_buf[n1_4].Re + tmp4); p_dst[n1_4].Re = factor * (p_buf[n1_4].Re - tmp4); p_dst[n3_4].Im = factor * (p_buf[n1_4].Im - tmp2); p_dst[n1_4].Im = factor * (p_buf[n1_4].Im + tmp2); w_re_ptr = pFFTSpec->pTwiddle + step; w_im_ptr = pFFTSpec->pTwiddle + (OMX_U32)(1 << (pFFTSpec->order - 2)) - step; for (uint32_t i = 1; i < n1_4; ++i) { w_re = *w_re_ptr; w_im = *w_im_ptr; tmp1 = w_re * p_buf[n1_2 + i].Re - w_im * p_buf[n1_2 + i].Im; tmp2 = w_re * p_buf[n1_2 + i].Im + w_im * p_buf[n1_2 + i].Re; tmp3 = w_re * p_buf[n3_4 + i].Re + w_im * p_buf[n3_4 + i].Im; tmp4 = w_re * p_buf[n3_4 + i].Im - w_im * p_buf[n3_4 + i].Re; tmp5 = tmp1 + tmp3; tmp1 = tmp1 - tmp3; tmp6 = tmp2 + tmp4; tmp2 = tmp2 - tmp4; p_dst[n1_2 + i].Re = factor * (p_buf[i].Re - tmp5); p_dst[i].Re = factor * (p_buf[i].Re + tmp5); p_dst[n1_2 + i].Im = factor * (p_buf[i].Im - tmp6); p_dst[i].Im = factor * (p_buf[i].Im + tmp6); p_dst[n3_4 + i].Re = factor * (p_buf[n1_4 + i].Re + tmp2); p_dst[n1_4 + i].Re = factor * (p_buf[n1_4 + i].Re - tmp2); p_dst[n3_4 + i].Im = factor * (p_buf[n1_4 + i].Im - tmp1); p_dst[n1_4 + i].Im = factor * (p_buf[n1_4 + i].Im + tmp1); w_re_ptr += step; w_im_ptr -= step; } return OMX_Sts_NoErr; }
5,568
562
<reponame>rockandsalt/conan-center-index #include <numa.h> #include <stdio.h> int main() { printf("numa available: %d\n", numa_available()); return 0; }
65
1,338
<filename>src/kits/debugger/files/LocatableEntry.cpp /* * Copyright 2009, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "LocatableEntry.h" #include "AutoLocker.h" #include "LocatableDirectory.h" // #pragma mark - LocatableEntryOwner LocatableEntryOwner::~LocatableEntryOwner() { } // #pragma mark - LocatableEntry LocatableEntry::LocatableEntry(LocatableEntryOwner* owner, LocatableDirectory* parent) : fOwner(owner), fParent(parent), fState(LOCATABLE_ENTRY_UNLOCATED) { if (fParent != NULL) fParent->AcquireReference(); } LocatableEntry::~LocatableEntry() { if (fParent != NULL) fParent->ReleaseReference(); } void LocatableEntry::LastReferenceReleased() { fOwner->LocatableEntryUnused(this); delete this; }
270
752
<gh_stars>100-1000 import prj.main.Prj as Prj import mtm.util.MiscUtil as MiscUtil import os import mtm.ioc.Container as Container from mtm.ioc.Inject import Inject import mtm.ioc.IocAssertions as Assertions import sys import argparse from mtm.log.LogStreamConsole import LogStreamConsole from mtm.util.Platforms import Platforms import mtm.util.PlatformUtil as PlatformUtil from mtm.util.Assert import * class Runner: _scriptRunner = Inject('ScriptRunner') _log = Inject('Logger') _sys = Inject('SystemHelper') _varMgr = Inject('VarManager') _vsSolutionHelper = Inject('VisualStudioHelper') _prjVsSolutionHelper = Inject('ProjenyVisualStudioHelper') def run(self, args): self._args = args success = self._scriptRunner.runWrapper(self._runInternal) if not success: sys.exit(1) def _runInternal(self): self._log.debug("Started OpenInVisualStudio with arguments: {0}".format(" ".join(sys.argv[1:]))) project, platform = self._getProjectAndPlatformFromFilePath(self._args.filePath) self._log.debug("Determined Project = {0}, Platform = {1}", project, platform) lineNo = 1 if self._args.lineNo: lineNo = int(self._args.lineNo) if platform == None: solutionPath = None else: solutionPath = self._prjVsSolutionHelper.getCustomSolutionPath(project, platform) self._vsSolutionHelper.openFile( self._args.filePath, lineNo, solutionPath) def _getProjectAndPlatformFromFilePath(self, filePath): unityProjectsDir = self._sys.canonicalizePath(self._varMgr.expand('[UnityProjectsDir]')) filePath = self._sys.canonicalizePath(filePath) if not filePath.startswith(unityProjectsDir): raise Exception("The given file path is not within the UnityProjects directory") relativePath = filePath[len(unityProjectsDir)+1:] dirs = relativePath.split(os.path.sep) projectName = dirs[0] try: platformProjectDirName = dirs[1] platformDirName = platformProjectDirName[platformProjectDirName.rfind('-')+1:] platform = PlatformUtil.fromPlatformFolderName(platformDirName) except: platform = None return projectName, platform def addArguments(parser): parser.add_argument("filePath", help="") parser.add_argument("lineNo", nargs='?', help="") def findConfigPath(filePath): lastParentDir = None parentDir = os.path.dirname(filePath) while parentDir and parentDir != lastParentDir: configPath = os.path.join(parentDir, Prj.ConfigFileName) if os.path.isfile(configPath): return configPath lastParentDir = parentDir parentDir = os.path.dirname(parentDir) assertThat(False, "Could not find Prj config path starting at path {0}", filePath) def installBindings(args): Container.bind('LogStream').toSingle(LogStreamConsole, True, False) Prj.installBindings(findConfigPath(args.filePath)) def _main(): parser = argparse.ArgumentParser(description='Projeny Visual Studio Opener') addArguments(parser) argv = sys.argv[1:] # If it's 2 then it only has the -cfg param if len(argv) == 0: parser.print_help() sys.exit(2) args = parser.parse_args(sys.argv[1:]) installBindings(args) Runner().run(args) if __name__ == '__main__': if (sys.version_info < (3, 0)): print('Wrong version of python! Install python 3 and try again') sys.exit(2) succeeded = True try: _main() except KeyboardInterrupt as e: print('Operation aborted by user by hitting CTRL+C') succeeded = False except Exception as e: sys.stderr.write(str(e) + '\n') if not MiscUtil.isRunningAsExe(): sys.stderr.write('\n' + traceback.format_exc()) succeeded = False if not succeeded: sys.exit(1)
1,591
648
<reponame>swrobel/fhir {"resourceType":"DataElement","id":"ExplanationOfBenefit.prescription","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/ExplanationOfBenefit.prescription","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"ExplanationOfBenefit.prescription","path":"ExplanationOfBenefit.prescription","short":"Prescription authorizing services or products","definition":"Prescription to support the dispensing of Pharmacy or Vision products.","requirements":"For type=Pharmacy and Vision only.","min":0,"max":"1","type":[{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/MedicationRequest"},{"code":"Reference","targetProfile":"http://hl7.org/fhir/StructureDefinition/VisionPrescription"}]}]}
225
376
<filename>Lib/Chip/CM4/NXP/LPC408x_7x_v0.7/UART1.hpp #pragma once #include <Register/Utility.hpp> namespace Kvasir { //UART1 namespace Uart1Rbr{ ///<DLAB =0 Receiver Buffer Register. Contains the next received character to be read. using Addr = Register::Address<0x40010000,0x00000000,0x00000000,unsigned>; ///The UART1 Receiver Buffer Register contains the oldest received byte in the UART1 RX FIFO. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> rbr{}; ///Reserved, the value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Thr{ ///<DLAB =0. Transmit Holding Register. The next character to be transmitted is written here. using Addr = Register::Address<0x40010000,0x00000000,0x00000000,unsigned>; ///Writing to the UART1 Transmit Holding Register causes the data to be stored in the UART1 transmit FIFO. The byte will be sent when it reaches the bottom of the FIFO and the transmitter is available. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> thr{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Dll{ ///<DLAB =1. Divisor Latch LSB. Least significant byte of the baud rate divisor value. The full divisor is used to generate a baud rate from the fractional rate divider. using Addr = Register::Address<0x40010000,0x00000000,0x00000000,unsigned>; ///The UART1 Divisor Latch LSB Register, along with the U1DLM register, determines the baud rate of the UART1. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> dllsb{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Dlm{ ///<DLAB =1. Divisor Latch MSB. Most significant byte of the baud rate divisor value. The full divisor is used to generate a baud rate from the fractional rate divider. using Addr = Register::Address<0x40010004,0x00000000,0x00000000,unsigned>; ///The UART1 Divisor Latch MSB Register, along with the U1DLL register, determines the baud rate of the UART1. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> dlmsb{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Ier{ ///<DLAB =0. Interrupt Enable Register. Contains individual interrupt enable bits for the 7 potential UART1 interrupts. using Addr = Register::Address<0x40010004,0x00000000,0x00000000,unsigned>; ///RBR Interrupt Enable. Enables the Receive Data Available interrupt for UART1. It also controls the Character Receive Time-out interrupt. enum class RbrieVal { disableTheRdaInte=0x00000000, ///<Disable the RDA interrupts. enableTheRdaInter=0x00000001, ///<Enable the RDA interrupts. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RbrieVal> rbrie{}; namespace RbrieValC{ constexpr Register::FieldValue<decltype(rbrie)::Type,RbrieVal::disableTheRdaInte> disableTheRdaInte{}; constexpr Register::FieldValue<decltype(rbrie)::Type,RbrieVal::enableTheRdaInter> enableTheRdaInter{}; } ///THRE Interrupt Enable. Enables the THRE interrupt for UART1. The status of this interrupt can be read from LSR[5]. enum class ThreieVal { disableTheThreInt=0x00000000, ///<Disable the THRE interrupts. enableTheThreInte=0x00000001, ///<Enable the THRE interrupts. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,ThreieVal> threie{}; namespace ThreieValC{ constexpr Register::FieldValue<decltype(threie)::Type,ThreieVal::disableTheThreInt> disableTheThreInt{}; constexpr Register::FieldValue<decltype(threie)::Type,ThreieVal::enableTheThreInte> enableTheThreInte{}; } ///RX Line Interrupt Enable. Enables the UART1 RX line status interrupts. The status of this interrupt can be read from LSR[4:1]. enum class RxieVal { disableTheRxLine=0x00000000, ///<Disable the RX line status interrupts. enableTheRxLineS=0x00000001, ///<Enable the RX line status interrupts. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,RxieVal> rxie{}; namespace RxieValC{ constexpr Register::FieldValue<decltype(rxie)::Type,RxieVal::disableTheRxLine> disableTheRxLine{}; constexpr Register::FieldValue<decltype(rxie)::Type,RxieVal::enableTheRxLineS> enableTheRxLineS{}; } ///Modem Status Interrupt Enable. Enables the modem interrupt. The status of this interrupt can be read from MSR[3:0]. enum class MsieVal { disableTheModemIn=0x00000000, ///<Disable the modem interrupt. enableTheModemInt=0x00000001, ///<Enable the modem interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,MsieVal> msie{}; namespace MsieValC{ constexpr Register::FieldValue<decltype(msie)::Type,MsieVal::disableTheModemIn> disableTheModemIn{}; constexpr Register::FieldValue<decltype(msie)::Type,MsieVal::enableTheModemInt> enableTheModemInt{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,unsigned> reserved{}; ///CTS Interrupt Enable. If auto-cts mode is enabled this bit enables/disables the modem status interrupt generation on a CTS1 signal transition. If auto-cts mode is disabled a CTS1 transition will generate an interrupt if Modem Status Interrupt Enable (IER[3]) is set. In normal operation a CTS1 signal transition will generate a Modem Status Interrupt unless the interrupt has been disabled by clearing the IER[3] bit in the IER register. In auto-cts mode a transition on the CTS1 bit will trigger an interrupt only if both the IER[3] and IER[7] bits are set. enum class CtsieVal { disableTheCtsInte=0x00000000, ///<Disable the CTS interrupt. enableTheCtsInter=0x00000001, ///<Enable the CTS interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,CtsieVal> ctsie{}; namespace CtsieValC{ constexpr Register::FieldValue<decltype(ctsie)::Type,CtsieVal::disableTheCtsInte> disableTheCtsInte{}; constexpr Register::FieldValue<decltype(ctsie)::Type,CtsieVal::enableTheCtsInter> enableTheCtsInter{}; } ///Enables the end of auto-baud interrupt. enum class AbeoieVal { disableEndOfAuto=0x00000000, ///<Disable end of auto-baud Interrupt. enableEndOfAutoB=0x00000001, ///<Enable end of auto-baud Interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,AbeoieVal> abeoie{}; namespace AbeoieValC{ constexpr Register::FieldValue<decltype(abeoie)::Type,AbeoieVal::disableEndOfAuto> disableEndOfAuto{}; constexpr Register::FieldValue<decltype(abeoie)::Type,AbeoieVal::enableEndOfAutoB> enableEndOfAutoB{}; } ///Enables the auto-baud time-out interrupt. enum class AbtoieVal { disableAutoBaudTi=0x00000000, ///<Disable auto-baud time-out Interrupt. enableAutoBaudTim=0x00000001, ///<Enable auto-baud time-out Interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,AbtoieVal> abtoie{}; namespace AbtoieValC{ constexpr Register::FieldValue<decltype(abtoie)::Type,AbtoieVal::disableAutoBaudTi> disableAutoBaudTi{}; constexpr Register::FieldValue<decltype(abtoie)::Type,AbtoieVal::enableAutoBaudTim> enableAutoBaudTim{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Iir{ ///<Interrupt ID Register. Identifies which interrupt(s) are pending. using Addr = Register::Address<0x40010008,0x00000000,0x00000000,unsigned>; ///Interrupt status. Note that IIR[0] is active low. The pending interrupt can be determined by evaluating IIR[3:1]. enum class IntstatusVal { atLeastOneInterru=0x00000000, ///<At least one interrupt is pending. noInterruptIsPend=0x00000001, ///<No interrupt is pending. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,IntstatusVal> intstatus{}; namespace IntstatusValC{ constexpr Register::FieldValue<decltype(intstatus)::Type,IntstatusVal::atLeastOneInterru> atLeastOneInterru{}; constexpr Register::FieldValue<decltype(intstatus)::Type,IntstatusVal::noInterruptIsPend> noInterruptIsPend{}; } ///Interrupt identification. IER[3:1] identifies an interrupt corresponding to the UART1 Rx or TX FIFO. All other combinations of IER[3:1] not listed below are reserved (100,101,111). enum class IntidVal { rls=0x00000003, ///<1 - Receive Line Status (RLS). rda=0x00000002, ///<2a - Receive Data Available (RDA). cti=0x00000006, ///<2b - Character Time-out Indicator (CTI). thre=0x00000001, ///<3 - THRE Interrupt. modem=0x00000000, ///<4 - Modem Interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,1),Register::ReadWriteAccess,IntidVal> intid{}; namespace IntidValC{ constexpr Register::FieldValue<decltype(intid)::Type,IntidVal::rls> rls{}; constexpr Register::FieldValue<decltype(intid)::Type,IntidVal::rda> rda{}; constexpr Register::FieldValue<decltype(intid)::Type,IntidVal::cti> cti{}; constexpr Register::FieldValue<decltype(intid)::Type,IntidVal::thre> thre{}; constexpr Register::FieldValue<decltype(intid)::Type,IntidVal::modem> modem{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> reserved{}; ///Copies of FCR[0]. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> fifoenable{}; ///End of auto-baud interrupt. True if auto-baud has finished successfully and interrupt is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> abeoint{}; ///Auto-baud time-out interrupt. True if auto-baud has timed out and interrupt is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> abtoint{}; ///Reserved, the value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Fcr{ ///<FIFO Control Register. Controls UART1 FIFO usage and modes. using Addr = Register::Address<0x40010008,0x00000000,0x00000000,unsigned>; ///FIFO enable. enum class FifoenVal { mustNotBeUsedIn=0x00000000, ///<Must not be used in the application. activeHighEnableF=0x00000001, ///<Active high enable for both UART1 Rx and TX FIFOs and FCR[7:1] access. This bit must be set for proper UART1 operation. Any transition on this bit will automatically clear the UART1 FIFOs. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,FifoenVal> fifoen{}; namespace FifoenValC{ constexpr Register::FieldValue<decltype(fifoen)::Type,FifoenVal::mustNotBeUsedIn> mustNotBeUsedIn{}; constexpr Register::FieldValue<decltype(fifoen)::Type,FifoenVal::activeHighEnableF> activeHighEnableF{}; } ///RX FIFO Reset. enum class RxfiforesVal { noImpactOnEither=0x00000000, ///<No impact on either of UART1 FIFOs. writingALogic1To=0x00000001, ///<Writing a logic 1 to FCR[1] will clear all bytes in UART1 Rx FIFO, reset the pointer logic. This bit is self-clearing. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,RxfiforesVal> rxfifores{}; namespace RxfiforesValC{ constexpr Register::FieldValue<decltype(rxfifores)::Type,RxfiforesVal::noImpactOnEither> noImpactOnEither{}; constexpr Register::FieldValue<decltype(rxfifores)::Type,RxfiforesVal::writingALogic1To> writingALogic1To{}; } ///TX FIFO Reset. enum class TxfiforesVal { noImpactOnEither=0x00000000, ///<No impact on either of UART1 FIFOs. writingALogic1To=0x00000001, ///<Writing a logic 1 to FCR[2] will clear all bytes in UART1 TX FIFO, reset the pointer logic. This bit is self-clearing. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,TxfiforesVal> txfifores{}; namespace TxfiforesValC{ constexpr Register::FieldValue<decltype(txfifores)::Type,TxfiforesVal::noImpactOnEither> noImpactOnEither{}; constexpr Register::FieldValue<decltype(txfifores)::Type,TxfiforesVal::writingALogic1To> writingALogic1To{}; } ///DMA Mode Select. When the FIFO enable bit (bit 0 of this register) is set, this bit selects the DMA mode. See Section 36.6.6.1. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dmamode{}; ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> reserved{}; ///RX Trigger Level. These two bits determine how many receiver UART1 FIFO characters must be written before an interrupt is activated. enum class RxtriglvlVal { triggerLevel01C=0x00000000, ///<Trigger level 0 (1 character or 0x01). triggerLevel14C=0x00000001, ///<Trigger level 1 (4 characters or 0x04). triggerLevel28C=0x00000002, ///<Trigger level 2 (8 characters or 0x08). triggerLevel314=0x00000003, ///<Trigger level 3 (14 characters or 0x0E). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,RxtriglvlVal> rxtriglvl{}; namespace RxtriglvlValC{ constexpr Register::FieldValue<decltype(rxtriglvl)::Type,RxtriglvlVal::triggerLevel01C> triggerLevel01C{}; constexpr Register::FieldValue<decltype(rxtriglvl)::Type,RxtriglvlVal::triggerLevel14C> triggerLevel14C{}; constexpr Register::FieldValue<decltype(rxtriglvl)::Type,RxtriglvlVal::triggerLevel28C> triggerLevel28C{}; constexpr Register::FieldValue<decltype(rxtriglvl)::Type,RxtriglvlVal::triggerLevel314> triggerLevel314{}; } ///Reserved, user software should not write ones to reserved bits. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Lcr{ ///<Line Control Register. Contains controls for frame formatting and break generation. using Addr = Register::Address<0x4001000c,0x00000000,0x00000000,unsigned>; ///Word Length Select. enum class WlsVal { v5BitCharacterLeng=0x00000000, ///<5-bit character length. v6BitCharacterLeng=0x00000001, ///<6-bit character length. v7BitCharacterLeng=0x00000002, ///<7-bit character length. v8BitCharacterLeng=0x00000003, ///<8-bit character length. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,WlsVal> wls{}; namespace WlsValC{ constexpr Register::FieldValue<decltype(wls)::Type,WlsVal::v5BitCharacterLeng> v5BitCharacterLeng{}; constexpr Register::FieldValue<decltype(wls)::Type,WlsVal::v6BitCharacterLeng> v6BitCharacterLeng{}; constexpr Register::FieldValue<decltype(wls)::Type,WlsVal::v7BitCharacterLeng> v7BitCharacterLeng{}; constexpr Register::FieldValue<decltype(wls)::Type,WlsVal::v8BitCharacterLeng> v8BitCharacterLeng{}; } ///Stop Bit Select. enum class SbsVal { v1StopBit=0x00000000, ///<1 stop bit. v2StopBits15If=0x00000001, ///<2 stop bits (1.5 if LCR[1:0]=00). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SbsVal> sbs{}; namespace SbsValC{ constexpr Register::FieldValue<decltype(sbs)::Type,SbsVal::v1StopBit> v1StopBit{}; constexpr Register::FieldValue<decltype(sbs)::Type,SbsVal::v2StopBits15If> v2StopBits15If{}; } ///Parity Enable. enum class PeVal { disableParityGener=0x00000000, ///<Disable parity generation and checking. enableParityGenera=0x00000001, ///<Enable parity generation and checking. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::disableParityGener> disableParityGener{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::enableParityGenera> enableParityGenera{}; } ///Parity Select. enum class PsVal { oddParityNumberO=0x00000000, ///<Odd parity. Number of 1s in the transmitted character and the attached parity bit will be odd. evenParityNumber=0x00000001, ///<Even Parity. Number of 1s in the transmitted character and the attached parity bit will be even. forced1stickPar=0x00000002, ///<Forced 1 stick parity. forced0stickPar=0x00000003, ///<Forced 0 stick parity. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::oddParityNumberO> oddParityNumberO{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::evenParityNumber> evenParityNumber{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::forced1stickPar> forced1stickPar{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::forced0stickPar> forced0stickPar{}; } ///Break Control. enum class BcVal { disableBreakTransm=0x00000000, ///<Disable break transmission. enableBreakTransmi=0x00000001, ///<Enable break transmission. Output pin UART1 TXD is forced to logic 0 when LCR[6] is active high. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,BcVal> bc{}; namespace BcValC{ constexpr Register::FieldValue<decltype(bc)::Type,BcVal::disableBreakTransm> disableBreakTransm{}; constexpr Register::FieldValue<decltype(bc)::Type,BcVal::enableBreakTransmi> enableBreakTransmi{}; } ///Divisor Latch Access Bit (DLAB) enum class DlabVal { disableAccessToDi=0x00000000, ///<Disable access to Divisor Latches. enableAccessToDiv=0x00000001, ///<Enable access to Divisor Latches. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,DlabVal> dlab{}; namespace DlabValC{ constexpr Register::FieldValue<decltype(dlab)::Type,DlabVal::disableAccessToDi> disableAccessToDi{}; constexpr Register::FieldValue<decltype(dlab)::Type,DlabVal::enableAccessToDiv> enableAccessToDiv{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Mcr{ ///<Modem Control Register. Contains controls for flow control handshaking and loopback mode. using Addr = Register::Address<0x40010010,0x00000000,0x00000000,unsigned>; ///DTR Control. Source for modem output pin, DTR. This bit reads as 0 when modem loopback mode is active. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dtrctrl{}; ///RTS Control. Source for modem output pin RTS. This bit reads as 0 when modem loopback mode is active. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> rtsctrl{}; ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> reserved{}; ///Loopback Mode Select. The modem loopback mode provides a mechanism to perform diagnostic loopback testing. Serial data from the transmitter is connected internally to serial input of the receiver. Input pin, RXD1, has no effect on loopback and output pin, TXD1 is held in marking state. The 4 modem inputs (CTS, DSR, RI and DCD) are disconnected externally. Externally, the modem outputs (RTS, DTR) are set inactive. Internally, the 4 modem outputs are connected to the 4 modem inputs. As a result of these connections, the upper 4 bits of the MSR will be driven by the lower 4 bits of the MCR rather than the 4 modem inputs in normal mode. This permits modem status interrupts to be generated in loopback mode by writing the lower 4 bits of MCR. enum class LmsVal { disableModemLoopba=0x00000000, ///<Disable modem loopback mode. enableModemLoopbac=0x00000001, ///<Enable modem loopback mode. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,LmsVal> lms{}; namespace LmsValC{ constexpr Register::FieldValue<decltype(lms)::Type,LmsVal::disableModemLoopba> disableModemLoopba{}; constexpr Register::FieldValue<decltype(lms)::Type,LmsVal::enableModemLoopbac> enableModemLoopbac{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> reserved{}; ///RTS enable. enum class RtsenVal { disableAutoRtsFlo=0x00000000, ///<Disable auto-rts flow control. enableAutoRtsFlow=0x00000001, ///<Enable auto-rts flow control. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,RtsenVal> rtsen{}; namespace RtsenValC{ constexpr Register::FieldValue<decltype(rtsen)::Type,RtsenVal::disableAutoRtsFlo> disableAutoRtsFlo{}; constexpr Register::FieldValue<decltype(rtsen)::Type,RtsenVal::enableAutoRtsFlow> enableAutoRtsFlow{}; } ///CTS enable. enum class CtsenVal { disableAutoCtsFlo=0x00000000, ///<Disable auto-cts flow control. enableAutoCtsFlow=0x00000001, ///<Enable auto-cts flow control. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,CtsenVal> ctsen{}; namespace CtsenValC{ constexpr Register::FieldValue<decltype(ctsen)::Type,CtsenVal::disableAutoCtsFlo> disableAutoCtsFlo{}; constexpr Register::FieldValue<decltype(ctsen)::Type,CtsenVal::enableAutoCtsFlow> enableAutoCtsFlow{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Lsr{ ///<Line Status Register. Contains flags for transmit and receive status, including line errors. using Addr = Register::Address<0x40010014,0x00000000,0x00000000,unsigned>; ///Receiver Data Ready. LSR[0] is set when the RBR holds an unread character and is cleared when the UART1 RBR FIFO is empty. enum class RdrVal { empty=0x00000000, ///<The UART1 receiver FIFO is empty. notempty=0x00000001, ///<The UART1 receiver FIFO is not empty. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RdrVal> rdr{}; namespace RdrValC{ constexpr Register::FieldValue<decltype(rdr)::Type,RdrVal::empty> empty{}; constexpr Register::FieldValue<decltype(rdr)::Type,RdrVal::notempty> notempty{}; } ///Overrun Error. The overrun error condition is set as soon as it occurs. An LSR read clears LSR[1]. LSR[1] is set when UART1 RSR has a new character assembled and the UART1 RBR FIFO is full. In this case, the UART1 RBR FIFO will not be overwritten and the character in the UART1 RSR will be lost. enum class OeVal { inactive=0x00000000, ///<Overrun error status is inactive. active=0x00000001, ///<Overrun error status is active. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,OeVal> oe{}; namespace OeValC{ constexpr Register::FieldValue<decltype(oe)::Type,OeVal::inactive> inactive{}; constexpr Register::FieldValue<decltype(oe)::Type,OeVal::active> active{}; } ///Parity Error. When the parity bit of a received character is in the wrong state, a parity error occurs. An LSR read clears LSR[2]. Time of parity error detection is dependent on FCR[0]. Note: A parity error is associated with the character at the top of the UART1 RBR FIFO. enum class PeVal { inactive=0x00000000, ///<Parity error status is inactive. active=0x00000001, ///<Parity error status is active. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::inactive> inactive{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::active> active{}; } ///Framing Error. When the stop bit of a received character is a logic 0, a framing error occurs. An LSR read clears LSR[3]. The time of the framing error detection is dependent on FCR0. Upon detection of a framing error, the RX will attempt to resynchronize to the data and assume that the bad stop bit is actually an early start bit. However, it cannot be assumed that the next received byte will be correct even if there is no Framing Error. Note: A framing error is associated with the character at the top of the UART1 RBR FIFO. enum class FeVal { inactive=0x00000000, ///<Framing error status is inactive. active=0x00000001, ///<Framing error status is active. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,FeVal> fe{}; namespace FeValC{ constexpr Register::FieldValue<decltype(fe)::Type,FeVal::inactive> inactive{}; constexpr Register::FieldValue<decltype(fe)::Type,FeVal::active> active{}; } ///Break Interrupt. When RXD1 is held in the spacing state (all zeroes) for one full character transmission (start, data, parity, stop), a break interrupt occurs. Once the break condition has been detected, the receiver goes idle until RXD1 goes to marking state (all ones). An LSR read clears this status bit. The time of break detection is dependent on FCR[0]. Note: The break interrupt is associated with the character at the top of the UART1 RBR FIFO. enum class BiVal { inactive=0x00000000, ///<Break interrupt status is inactive. active=0x00000001, ///<Break interrupt status is active. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,BiVal> bi{}; namespace BiValC{ constexpr Register::FieldValue<decltype(bi)::Type,BiVal::inactive> inactive{}; constexpr Register::FieldValue<decltype(bi)::Type,BiVal::active> active{}; } ///Transmitter Holding Register Empty. THRE is set immediately upon detection of an empty UART1 THR and is cleared on a THR write. enum class ThreVal { valid=0x00000000, ///<THR contains valid data. thrIsEmpty=0x00000001, ///<THR is empty. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,ThreVal> thre{}; namespace ThreValC{ constexpr Register::FieldValue<decltype(thre)::Type,ThreVal::valid> valid{}; constexpr Register::FieldValue<decltype(thre)::Type,ThreVal::thrIsEmpty> thrIsEmpty{}; } ///Transmitter Empty. TEMT is set when both THR and TSR are empty; TEMT is cleared when either the TSR or the THR contain valid data. enum class TemtVal { valid=0x00000000, ///<THR and/or the TSR contains valid data. empty=0x00000001, ///<THR and the TSR are empty. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,TemtVal> temt{}; namespace TemtValC{ constexpr Register::FieldValue<decltype(temt)::Type,TemtVal::valid> valid{}; constexpr Register::FieldValue<decltype(temt)::Type,TemtVal::empty> empty{}; } ///Error in RX FIFO. LSR[7] is set when a character with a RX error such as framing error, parity error or break interrupt, is loaded into the RBR. This bit is cleared when the LSR register is read and there are no subsequent errors in the UART1 FIFO. enum class RxfeVal { noerror=0x00000000, ///<RBR contains no UART1 RX errors or FCR[0]=0. errors=0x00000001, ///<UART1 RBR contains at least one UART1 RX error. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,RxfeVal> rxfe{}; namespace RxfeValC{ constexpr Register::FieldValue<decltype(rxfe)::Type,RxfeVal::noerror> noerror{}; constexpr Register::FieldValue<decltype(rxfe)::Type,RxfeVal::errors> errors{}; } ///Reserved, the value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Msr{ ///<Modem Status Register. Contains handshake signal status flags. using Addr = Register::Address<0x40010018,0x00000000,0x00000000,unsigned>; ///Delta CTS. Set upon state change of input CTS. Cleared on an MSR read. enum class DctsVal { noChangeDetectedO=0x00000000, ///<No change detected on modem input, CTS. stateChangeDetecte=0x00000001, ///<State change detected on modem input, CTS. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,DctsVal> dcts{}; namespace DctsValC{ constexpr Register::FieldValue<decltype(dcts)::Type,DctsVal::noChangeDetectedO> noChangeDetectedO{}; constexpr Register::FieldValue<decltype(dcts)::Type,DctsVal::stateChangeDetecte> stateChangeDetecte{}; } ///Delta DSR. Set upon state change of input DSR. Cleared on an MSR read. enum class DdsrVal { noChangeDetectedO=0x00000000, ///<No change detected on modem input, DSR. stateChangeDetecte=0x00000001, ///<State change detected on modem input, DSR. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DdsrVal> ddsr{}; namespace DdsrValC{ constexpr Register::FieldValue<decltype(ddsr)::Type,DdsrVal::noChangeDetectedO> noChangeDetectedO{}; constexpr Register::FieldValue<decltype(ddsr)::Type,DdsrVal::stateChangeDetecte> stateChangeDetecte{}; } ///Trailing Edge RI. Set upon low to high transition of input RI. Cleared on an MSR read. enum class TeriVal { noChangeDetectedO=0x00000000, ///<No change detected on modem input, RI. lowToHighTransiti=0x00000001, ///<Low-to-high transition detected on RI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,TeriVal> teri{}; namespace TeriValC{ constexpr Register::FieldValue<decltype(teri)::Type,TeriVal::noChangeDetectedO> noChangeDetectedO{}; constexpr Register::FieldValue<decltype(teri)::Type,TeriVal::lowToHighTransiti> lowToHighTransiti{}; } ///Delta DCD. Set upon state change of input DCD. Cleared on an MSR read. enum class DdcdVal { noChangeDetectedO=0x00000000, ///<No change detected on modem input, DCD. stateChangeDetecte=0x00000001, ///<State change detected on modem input, DCD. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DdcdVal> ddcd{}; namespace DdcdValC{ constexpr Register::FieldValue<decltype(ddcd)::Type,DdcdVal::noChangeDetectedO> noChangeDetectedO{}; constexpr Register::FieldValue<decltype(ddcd)::Type,DdcdVal::stateChangeDetecte> stateChangeDetecte{}; } ///Clear To Send State. Complement of input signal CTS. This bit is connected to MCR[1] in modem loopback mode. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> cts{}; ///Data Set Ready State. Complement of input signal DSR. This bit is connected to MCR[0] in modem loopback mode. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> dsr{}; ///Ring Indicator State. Complement of input RI. This bit is connected to MCR[2] in modem loopback mode. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> ri{}; ///Data Carrier Detect State. Complement of input DCD. This bit is connected to MCR[3] in modem loopback mode. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> dcd{}; ///Reserved, the value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Scr{ ///<Scratch Pad Register. 8-bit temporary storage for software. using Addr = Register::Address<0x4001001c,0x00000000,0x00000000,unsigned>; ///A readable, writable byte. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> pad{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Acr{ ///<Auto-baud Control Register. Contains controls for the auto-baud feature. using Addr = Register::Address<0x40010020,0x00000000,0x00000000,unsigned>; ///Auto-baud start bit. This bit is automatically cleared after auto-baud completion. enum class StartVal { stop=0x00000000, ///<Auto-baud stop (auto-baud is not running). start=0x00000001, ///<Auto-baud start (auto-baud is running). Auto-baud run bit. This bit is automatically cleared after auto-baud completion. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,StartVal> start{}; namespace StartValC{ constexpr Register::FieldValue<decltype(start)::Type,StartVal::stop> stop{}; constexpr Register::FieldValue<decltype(start)::Type,StartVal::start> start{}; } ///Auto-baud mode select bit. enum class ModeVal { mode0=0x00000000, ///<Mode 0. mode1=0x00000001, ///<Mode 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,ModeVal> mode{}; namespace ModeValC{ constexpr Register::FieldValue<decltype(mode)::Type,ModeVal::mode0> mode0{}; constexpr Register::FieldValue<decltype(mode)::Type,ModeVal::mode1> mode1{}; } ///Auto-baud restart bit. enum class AutorestartVal { noRestart=0x00000000, ///<No restart restartInCaseOfT=0x00000001, ///<Restart in case of time-out (counter restarts at next UART1 Rx falling edge) }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,AutorestartVal> autorestart{}; namespace AutorestartValC{ constexpr Register::FieldValue<decltype(autorestart)::Type,AutorestartVal::noRestart> noRestart{}; constexpr Register::FieldValue<decltype(autorestart)::Type,AutorestartVal::restartInCaseOfT> restartInCaseOfT{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,3),Register::ReadWriteAccess,unsigned> reserved{}; ///End of auto-baud interrupt clear bit (write-only). enum class AbeointclrVal { writingA0HasNoI=0x00000000, ///<Writing a 0 has no impact. writingA1WillCle=0x00000001, ///<Writing a 1 will clear the corresponding interrupt in the IIR. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,AbeointclrVal> abeointclr{}; namespace AbeointclrValC{ constexpr Register::FieldValue<decltype(abeointclr)::Type,AbeointclrVal::writingA0HasNoI> writingA0HasNoI{}; constexpr Register::FieldValue<decltype(abeointclr)::Type,AbeointclrVal::writingA1WillCle> writingA1WillCle{}; } ///Auto-baud time-out interrupt clear bit (write-only). enum class AbtointclrVal { writingA0HasNoI=0x00000000, ///<Writing a 0 has no impact. writingA1WillCle=0x00000001, ///<Writing a 1 will clear the corresponding interrupt in the IIR. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,AbtointclrVal> abtointclr{}; namespace AbtointclrValC{ constexpr Register::FieldValue<decltype(abtointclr)::Type,AbtointclrVal::writingA0HasNoI> writingA0HasNoI{}; constexpr Register::FieldValue<decltype(abtointclr)::Type,AbtointclrVal::writingA1WillCle> writingA1WillCle{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Fdr{ ///<Fractional Divider Register. Generates a clock input for the baud rate divider. using Addr = Register::Address<0x40010028,0x00000000,0x00000000,unsigned>; ///Baud rate generation pre-scaler divisor value. If this field is 0, fractional baud rate generator will not impact the UART1 baud rate. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> divaddval{}; ///Baud rate pre-scaler multiplier value. This field must be greater or equal 1 for UART1 to operate properly, regardless of whether the fractional baud rate generator is used or not. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> mulval{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Ter{ ///<Transmit Enable Register. Turns off UART transmitter for use with software flow control. using Addr = Register::Address<0x40010030,0x00000000,0x00000000,unsigned>; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,0),Register::ReadWriteAccess,unsigned> reserved{}; ///When this bit is 1, as it is after a Reset, data written to the THR is output on the TXD pin as soon as any preceding data has been sent. If this bit cleared to 0 while a character is being sent, the transmission of that character is completed, but no further characters are sent until this bit is set again. In other words, a 0 in this bit blocks the transfer of characters from the THR or TX FIFO into the transmit shift register. Software can clear this bit when it detects that the a hardware-handshaking TX-permit signal (CTS) has gone false, or with software handshaking, when it receives an XOFF character (DC3). Software can set this bit again when it detects that the TX-permit signal has gone true, or when it receives an XON (DC1) character. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txen{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Rs485ctrl{ ///<RS-485/EIA-485 Control. Contains controls to configure various aspects of RS-485/EIA-485 modes. using Addr = Register::Address<0x4001004c,0x00000000,0x00000000,unsigned>; ///RS-485/EIA-485 Normal Multidrop Mode (NMM) mode select. enum class NmmenVal { disabled=0x00000000, ///<Disabled. enabledInThisMod=0x00000001, ///<Enabled. In this mode, an address is detected when a received byte causes the UART to set the parity error and generate an interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,NmmenVal> nmmen{}; namespace NmmenValC{ constexpr Register::FieldValue<decltype(nmmen)::Type,NmmenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(nmmen)::Type,NmmenVal::enabledInThisMod> enabledInThisMod{}; } ///Receive enable. enum class RxdisVal { enabled=0x00000000, ///<Enabled. disabled=0x00000001, ///<Disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,RxdisVal> rxdis{}; namespace RxdisValC{ constexpr Register::FieldValue<decltype(rxdis)::Type,RxdisVal::enabled> enabled{}; constexpr Register::FieldValue<decltype(rxdis)::Type,RxdisVal::disabled> disabled{}; } ///Auto Address Detect (AAD) enable. enum class AadenVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,AadenVal> aaden{}; namespace AadenValC{ constexpr Register::FieldValue<decltype(aaden)::Type,AadenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(aaden)::Type,AadenVal::enabled> enabled{}; } ///Direction control. enum class SelVal { rtsIfDirectionCo=0x00000000, ///<RTS. If direction control is enabled (bit DCTRL = 1), pin RTS is used for direction control. dtrIfDirectionCo=0x00000001, ///<DTR. If direction control is enabled (bit DCTRL = 1), pin DTR is used for direction control. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,SelVal> sel{}; namespace SelValC{ constexpr Register::FieldValue<decltype(sel)::Type,SelVal::rtsIfDirectionCo> rtsIfDirectionCo{}; constexpr Register::FieldValue<decltype(sel)::Type,SelVal::dtrIfDirectionCo> dtrIfDirectionCo{}; } ///Direction control enable. enum class DctrlVal { disableAutoDirecti=0x00000000, ///<Disable Auto Direction Control. enableAutoDirectio=0x00000001, ///<Enable Auto Direction Control. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DctrlVal> dctrl{}; namespace DctrlValC{ constexpr Register::FieldValue<decltype(dctrl)::Type,DctrlVal::disableAutoDirecti> disableAutoDirecti{}; constexpr Register::FieldValue<decltype(dctrl)::Type,DctrlVal::enableAutoDirectio> enableAutoDirectio{}; } ///Polarity. This bit reverses the polarity of the direction control signal on the RTS (or DTR) pin. enum class OinvVal { lowTheDirectionC=0x00000000, ///<LOW. The direction control pin will be driven to logic 0 when the transmitter has data to be sent. It will be driven to logic 1 after the last bit of data has been transmitted. highTheDirection=0x00000001, ///<HIGH. The direction control pin will be driven to logic 1 when the transmitter has data to be sent. It will be driven to logic 0 after the last bit of data has been transmitted. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,OinvVal> oinv{}; namespace OinvValC{ constexpr Register::FieldValue<decltype(oinv)::Type,OinvVal::lowTheDirectionC> lowTheDirectionC{}; constexpr Register::FieldValue<decltype(oinv)::Type,OinvVal::highTheDirection> highTheDirection{}; } ///Reserved, user software should not write ones to reserved bits. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Rs485adrmatch{ ///<RS-485/EIA-485 address match. Contains the address match value for RS-485/EIA-485 mode. using Addr = Register::Address<0x40010050,0x00000000,0x00000000,unsigned>; ///Contains the address match value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> adrmatch{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace Uart1Rs485dly{ ///<RS-485/EIA-485 direction control delay. using Addr = Register::Address<0x40010054,0x00000000,0x00000000,unsigned>; ///Contains the direction control (RTS or DTR) delay value. This register works in conjunction with an 8-bit counter. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> dly{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } }
18,771
2,693
<reponame>sergunya17/catalyst<gh_stars>1000+ from typing import List, Optional from functools import partial import torch from torch import nn from catalyst.metrics.functional import trevsky class TrevskyLoss(nn.Module): """The trevsky loss. TrevskyIndex = TP / (TP + alpha * FN + betta * FP) TrevskyLoss = 1 - TrevskyIndex """ def __init__( self, alpha: float, beta: Optional[float] = None, class_dim: int = 1, mode: str = "macro", weights: List[float] = None, eps: float = 1e-7, ): """ Args: alpha: false negative coefficient, bigger alpha bigger penalty for false negative. Must be in (0, 1) beta: false positive coefficient, bigger alpha bigger penalty for false positive. Must be in (0, 1), if None beta = (1 - alpha) class_dim: indicates class dimention (K) for ``outputs`` and ``targets`` tensors (default = 1) mode: class summation strategy. Must be one of ['micro', 'macro', 'weighted']. If mode='micro', classes are ignored, and metric are calculated generally. If mode='macro', metric are calculated separately and than are averaged over all classes. If mode='weighted', metric are calculated separately and than summed over all classes with weights. weights: class weights(for mode="weighted") eps: epsilon to avoid zero division """ super().__init__() assert mode in ["micro", "macro", "weighted"] self.loss_fn = partial( trevsky, eps=eps, alpha=alpha, beta=beta, class_dim=class_dim, threshold=None, mode=mode, weights=weights, ) def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: """Calculates loss between ``logits`` and ``target`` tensors.""" trevsky_score = self.loss_fn(outputs, targets) return 1 - trevsky_score class FocalTrevskyLoss(nn.Module): """The focal trevsky loss. TrevskyIndex = TP / (TP + alpha * FN + betta * FP) FocalTrevskyLoss = (1 - TrevskyIndex)^gamma Node: focal will use per image, so loss will pay more attention on complicated images """ def __init__( self, alpha: float, beta: Optional[float] = None, gamma: float = 4 / 3, class_dim: int = 1, mode: str = "macro", weights: List[float] = None, eps: float = 1e-7, ): """ Args: alpha: false negative coefficient, bigger alpha bigger penalty for false negative. Must be in (0, 1) beta: false positive coefficient, bigger alpha bigger penalty for false positive. Must be in (0, 1), if None beta = (1 - alpha) gamma: focal coefficient. It determines how much the weight of simple examples is reduced. class_dim: indicates class dimention (K) for ``outputs`` and ``targets`` tensors (default = 1) mode: class summation strategy. Must be one of ['micro', 'macro', 'weighted']. If mode='micro', classes are ignored, and metric are calculated generally. If mode='macro', metric are calculated separately and than are averaged over all classes. If mode='weighted', metric are calculated separately and than summed over all classes with weights. weights: class weights(for mode="weighted") eps: epsilon to avoid zero division """ super().__init__() self.gamma = gamma self.trevsky_loss = TrevskyLoss( alpha=alpha, beta=beta, class_dim=class_dim, mode=mode, weights=weights, eps=eps ) def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: """Calculates loss between ``logits`` and ``target`` tensors.""" loss = 0 batch_size = len(outputs) for output_sample, target_sample in zip(outputs, targets): output_sample = torch.unsqueeze(output_sample, dim=0) target_sample = torch.unsqueeze(target_sample, dim=0) sample_loss = self.trevsky_loss(output_sample, target_sample) loss += sample_loss ** self.gamma loss = loss / batch_size # mean over batch return loss __all__ = ["TrevskyLoss", "FocalTrevskyLoss"]
1,999
318
<filename>src/main/resources/assets/techreborn/models/item/ashes_small_dust.json { "parent": "minecraft:item/generated", "textures": { "layer0": "techreborn:item/smalldust/ashes_small_dust" } }
88
4,857
<filename>hbase-metrics/src/main/java/org/apache/hadoop/hbase/metrics/impl/MetricRegistryImpl.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.metrics.impl; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.hadoop.hbase.metrics.Counter; import org.apache.hadoop.hbase.metrics.Gauge; import org.apache.hadoop.hbase.metrics.Histogram; import org.apache.hadoop.hbase.metrics.Meter; import org.apache.hadoop.hbase.metrics.Metric; import org.apache.hadoop.hbase.metrics.MetricRegistry; import org.apache.hadoop.hbase.metrics.MetricRegistryInfo; import org.apache.hadoop.hbase.metrics.MetricSet; import org.apache.hadoop.hbase.metrics.Timer; import org.apache.hadoop.hbase.util.ConcurrentMapUtils; import org.apache.yetus.audience.InterfaceAudience; /** * Custom implementation of {@link MetricRegistry}. */ @InterfaceAudience.Private public class MetricRegistryImpl implements MetricRegistry { private final MetricRegistryInfo info; private final ConcurrentMap<String, Metric> metrics; public MetricRegistryImpl(MetricRegistryInfo info) { this.info = info; this.metrics = new ConcurrentHashMap<>(); } @Override public Timer timer(String name) { return (Timer) ConcurrentMapUtils.computeIfAbsent(metrics, name, this::createTimer); } protected Timer createTimer() { return new TimerImpl(); } @Override public Histogram histogram(String name) { return (Histogram) ConcurrentMapUtils.computeIfAbsent(metrics, name, this::createHistogram); } protected Histogram createHistogram() { return new HistogramImpl(); } @Override public Meter meter(String name) { return (Meter) ConcurrentMapUtils.computeIfAbsent(metrics, name, this::createMeter); } protected Meter createMeter() { return new DropwizardMeter(); } @Override public Counter counter(String name) { return (Counter) ConcurrentMapUtils.computeIfAbsent(metrics, name, this::createCounter); } protected Counter createCounter() { return new CounterImpl(); } @Override public Optional<Metric> get(String name) { return Optional.ofNullable(metrics.get(name)); } @Override public Metric register(String name, Metric metric) { return ConcurrentMapUtils.computeIfAbsent(metrics, name, () -> metric); } @Override public <T> Gauge<T> register(String name, Gauge<T> gauge) { return (Gauge) register(name, (Metric)gauge); } @Override public void registerAll(MetricSet metricSet) { metricSet.getMetrics().forEach(this::register); } @Override public Map<String, Metric> getMetrics() { return metrics; } @Override public boolean remove(String name) { return metrics.remove(name) != null; } @Override public MetricRegistryInfo getMetricRegistryInfo() { return info; } }
1,177
938
<gh_stars>100-1000 { "title": "Exploration", "subText": "I have located several variants of slime islands in my travels, which serve both as breeding grounds for slimes and a source of interesting flora for research. In addition, there are a few unique resources that are not discussed much in my other textbooks that I wanted to cover." }
83
742
#include <algorithm> #include <tuple> #include "ArenaTypes.h" #include "components/debug/Debug.h" #include "components/utilities/Bytes.h" void ArenaTypes::Light::init(const uint8_t *data) { this->x = Bytes::getLE16(data); this->y = Bytes::getLE16(data + 2); this->radius = Bytes::getLE16(data + 4); } void ArenaTypes::MIFHeader::init(const uint8_t *data) { this->unknown1 = *data; this->entryCount = *(data + 1); const uint16_t *startXStart = reinterpret_cast<const uint16_t*>(data + 2); const uint16_t *startXEnd = startXStart + this->startX.size(); std::copy(startXStart, startXEnd, this->startX.begin()); const uint16_t *startYStart = startXEnd; const uint16_t *startYEnd = startYStart + this->startY.size(); std::copy(startYStart, startYEnd, this->startY.begin()); this->startingLevelIndex = *(data + 18); this->levelCount = *(data + 19); this->unknown2 = *(data + 20); this->mapWidth = Bytes::getLE16(data + 21); this->mapHeight = Bytes::getLE16(data + 23); const uint8_t *unknown3Start = data + 25; const uint8_t *unknown3End = unknown3Start + this->unknown3.size(); std::copy(unknown3Start, unknown3End, this->unknown3.begin()); } void ArenaTypes::MIFLock::init(const uint8_t *data) { this->x = *data; this->y = *(data + 1); this->lockLevel = *(data + 2); } void ArenaTypes::MIFTarget::init(const uint8_t *data) { this->x = *data; this->y = *(data + 1); } void ArenaTypes::MIFTrigger::init(const uint8_t *data) { this->x = *data; this->y = *(data + 1); this->textIndex = *(data + 2); this->soundIndex = *(data + 3); } void ArenaTypes::DynamicTrigger::init(const uint8_t *data) { std::copy(data, data + this->unknown.size(), this->unknown.begin()); } void ArenaTypes::GameState::init(const uint8_t *data) { DebugNotImplemented(); } void ArenaTypes::SaveGame::init(const uint8_t *data) { const uint8_t *screenBufferStart = data; const uint8_t *screenBufferEnd = screenBufferStart + this->screenBuffer.size(); std::copy(screenBufferStart, screenBufferEnd, this->screenBuffer.begin()); const uint8_t *paletteStart = screenBufferEnd; const uint8_t *paletteEnd = paletteStart + this->palette.size(); std::copy(paletteStart, paletteEnd, this->palette.begin()); const uint8_t *gameStateStart = paletteEnd; const uint8_t *gameStateEnd = gameStateStart + GameState::SIZE; this->gameState.init(gameStateStart); const uint16_t *gameLevelStart = reinterpret_cast<const uint16_t*>(gameStateEnd); const uint16_t *gameLevelEnd = gameLevelStart + this->gameLevel.size(); std::copy(gameLevelStart, gameLevelEnd, this->gameLevel.begin()); } void ArenaTypes::InventoryItem::init(const uint8_t *data) { this->slotID = *data; this->weight = Bytes::getLE16(data + 1); this->hands = *(data + 3); this->param1 = *(data + 4); this->param2 = *(data + 5); this->health = Bytes::getLE16(data + 6); this->maxHealth = Bytes::getLE16(data + 8); this->price = Bytes::getLE32(data + 10); this->flags = *(data + 14); this->x = *(data + 15); this->material = *(data + 16); this->y = *(data + 17); this->attribute = *(data + 18); } void ArenaTypes::SaveEngine::CreatureData::init(const uint8_t *data) { std::copy(data, data + this->unknown.size(), this->unknown.begin()); } void ArenaTypes::SaveEngine::LootItem::init(const uint8_t *data) { this->unknown1 = Bytes::getLE16(data); this->containerPosition = Bytes::getLE16(data + 2); this->floor = *(data + 4); this->goldValue = Bytes::getLE16(data + 5); this->unknown2 = Bytes::getLE16(data + 7); const uint8_t *inventoryItemStart = data + 8; this->inventoryItem.init(inventoryItemStart); } void ArenaTypes::SaveEngine::NPCData::init(const uint8_t *data) { DebugNotImplemented(); } void ArenaTypes::SaveEngine::CityGenData::init(const uint8_t *data) { const char *cityNameStart = reinterpret_cast<const char*>(data); const char *cityNameEnd = cityNameStart + this->cityName.size(); std::copy(cityNameStart, cityNameEnd, this->cityName.begin()); const char *mifNameStart = cityNameEnd; const char *mifNameEnd = mifNameStart + this->mifName.size(); std::copy(mifNameStart, mifNameEnd, this->mifName.begin()); this->citySize = *(data + 33); this->blockOffset = Bytes::getLE16(data + 34); this->provinceID = *(data + 36); this->cityType = *(data + 37); this->localX = Bytes::getLE16(data + 38); this->localY = Bytes::getLE16(data + 40); this->cityID = *(data + 42); this->unknown = *(data + 43); this->absLatitude = Bytes::getLE16(data + 44); this->terrainType = *(data + 46); this->quarter = *(data + 47); this->rulerSeed = Bytes::getLE32(data + 48); this->citySeed = Bytes::getLE32(data + 52); } void ArenaTypes::SaveEngine::Buff::init(const uint8_t *data) { std::copy(data, data + this->unknown.size(), this->unknown.begin()); } void ArenaTypes::SaveEngine::NPCSprite::init(const uint8_t *data) { this->x = Bytes::getLE16(data); this->z = Bytes::getLE16(data + 2); this->y = Bytes::getLE16(data + 4); this->pDynamicLight = Bytes::getLE16(data + 6); this->speed = Bytes::getLE16(data + 8); this->angle = Bytes::getLE16(data + 10); this->flags = *(data + 12); this->frame = *(data + 13); this->param1 = *(data + 14); this->flags = Bytes::getLE16(data + 15); this->param2 = *(data + 17); this->data = Bytes::getLE16(data + 18); this->param3 = Bytes::getLE16(data + 20); this->unknown1 = Bytes::getLE16(data + 22); this->unknown2 = Bytes::getLE16(data + 24); this->param4 = Bytes::getLE16(data + 26); } void ArenaTypes::SaveEngine::BaseQuest::init(const uint8_t *data) { this->questSeed = Bytes::getLE32(data); this->location1 = Bytes::getLE16(data + 4); this->item1 = Bytes::getLE16(data + 6); this->startDate = Bytes::getLE32(data + 8); this->dueDate = Bytes::getLE32(data + 12); this->tavernData = Bytes::getLE32(data + 16); this->destinationData = Bytes::getLE32(data + 20); this->reward = Bytes::getLE32(data + 24); this->portrait = Bytes::getLE16(data + 28); this->questGiverSeed = Bytes::getLE32(data + 30); this->opponentFaction = Bytes::getLE16(data + 34); this->destinationCityID = *(data + 36); this->questCityID = *(data + 37); this->unknown = *(data + 38); this->relationship = *(data + 39); this->escorteeIsFemale = *(data + 40); } void ArenaTypes::SaveEngine::ExtQuest::init(const uint8_t *data) { const uint8_t *baseQuestStart = data; const uint8_t *baseQuestEnd = baseQuestStart + BaseQuest::SIZE; this->baseQuest.init(baseQuestStart); const uint8_t *unknownStart = baseQuestEnd; const uint8_t *unknownEnd = unknownStart + this->unknown.size(); std::copy(unknownStart, unknownEnd, this->unknown.begin()); this->faction = *(data + 46); this->npcRace = *(data + 47); this->monsterRace = *(data + 48); this->locationName = *(data + 49); this->locNameTemplate = *(data + 50); } void ArenaTypes::SaveEngine::MainQuestData::init(const uint8_t *data) { this->canHaveVision = *data; this->nextStep = *(data + 1); this->dungeonLocationKnown = *(data + 2); this->acceptedKeyQuest = *(data + 3); this->hadVision = *(data + 4); this->talkedToRuler = *(data + 5); this->stepDone = *(data + 6); this->hasKeyItem = *(data + 7); this->hasStaffPiece = *(data + 8); this->showKey = *(data + 9); } void ArenaTypes::SaveEngine::ArtifactQuestData::init(const uint8_t *data) { this->currentArtifact = *data; this->tavernLocation = Bytes::getLE32(data + 1); this->mapDungeonID = *(data + 5); this->mapProvinceID = *(data + 6); this->artifactDungeonID = *(data + 7); this->artifactProvinceID = *(data + 8); this->artifactQuestFlags = *(data + 9); this->artifactBitMask = Bytes::getLE16(data + 10); this->artifactQuestStarted = Bytes::getLE32(data + 12); this->artifactDays = *(data + 16); this->artifactPriceOrOffset = Bytes::getLE16(data + 17); } void ArenaTypes::SaveEngine::PlayerData::init(const uint8_t *data) { DebugNotImplemented(); } void ArenaTypes::SaveEngine::InternalState::init(const uint8_t *data) { std::copy(data, data + this->unknown.size(), this->unknown.begin()); } void ArenaTypes::SaveEngine::init(const uint8_t *data) { auto unscramble = [](uint8_t *data, size_t length) { uint16_t buffer = static_cast<uint16_t>(length); for (uint16_t i = 0; i < length; i++) { const uint8_t key = Bytes::ror(buffer, buffer & 0xF) & 0xFF; data[i] ^= key; buffer--; } }; // Unscramble the first two members (player and player data). Do unscrambling on the // incoming bytes so the process is unaffected by struct padding. std::array<uint8_t, NPCData::SIZE> playerBuffer; const uint8_t *playerBufferStart = data; const uint8_t *playerBufferEnd = playerBufferStart + playerBuffer.size(); std::copy(playerBufferStart, playerBufferEnd, playerBuffer.begin()); unscramble(playerBuffer.data(), playerBuffer.size()); this->player.init(playerBuffer.data()); std::array<uint8_t, PlayerData::SIZE> playerDataBuffer; const uint8_t *playerDataBufferStart = playerBufferEnd; const uint8_t *playerDataBufferEnd = playerDataBufferStart + playerDataBuffer.size(); std::copy(playerDataBufferStart, playerDataBufferEnd, playerDataBuffer.begin()); unscramble(playerDataBuffer.data(), playerDataBuffer.size()); this->playerData.init(playerDataBuffer.data()); const uint8_t *enemiesStart = playerDataBufferEnd; const uint8_t *enemiesEnd = enemiesStart + (NPCData::SIZE * this->enemies.size()); for (size_t i = 0; i < this->enemies.size(); i++) { this->enemies[i].init(enemiesStart + (NPCData::SIZE * i)); } const uint8_t *lootStart = enemiesEnd; const uint8_t *lootEnd = lootStart + (LootItem::SIZE * this->loot.size()); for (size_t i = 0; i < this->loot.size(); i++) { this->loot[i].init(lootStart + (LootItem::SIZE * i)); } const uint8_t *gameState2Start = lootEnd; this->gameState2.init(gameState2Start); } void ArenaTypes::MQLevelState::HashTable::init(const uint8_t *data) { this->triggerCount = *data; const uint8_t *triggersStart = data + 1; const uint8_t *triggersEnd = triggersStart + (MIFTrigger::SIZE * this->triggers.size()); for (size_t i = 0; i < this->triggers.size(); i++) { this->triggers[i].init(triggersStart + (MIFTrigger::SIZE * i)); } this->lockCount = *(data + 257); const uint8_t *locksStart = data + 258; for (size_t i = 0; i < this->locks.size(); i++) { this->locks[i].init(locksStart + (MIFLock::SIZE * i)); } } void ArenaTypes::MQLevelState::init(const uint8_t *data) { const uint8_t *hashTablesStart = data; for (size_t i = 0; i < this->hashTables.size(); i++) { this->hashTables[i].init(hashTablesStart + (HashTable::SIZE * i)); } } void ArenaTypes::SpellData::init(const uint8_t *data) { for (size_t i = 0; i < this->params.size(); i++) { auto &param = this->params[i]; const size_t offset = i * 6; for (size_t j = 0; j < param.size(); j++) { param[j] = Bytes::getLE16(data + offset + (j * 2)); } } this->targetType = *(data + 36); this->unknown = *(data + 37); this->element = *(data + 38); this->flags = Bytes::getLE16(data + 39); constexpr size_t arrSize = 3; for (size_t i = 0; i < arrSize; i++) { static_assert(std::tuple_size<decltype(this->effects)>::value == arrSize); static_assert(std::tuple_size<decltype(this->subEffects)>::value == arrSize); static_assert(std::tuple_size<decltype(this->affectedAttributes)>::value == arrSize); this->effects[i] = *(data + 41 + i); this->subEffects[i] = *(data + 44 + i); this->affectedAttributes[i] = *(data + 47 + i); } this->cost = Bytes::getLE16(data + 50); const char *nameStart = reinterpret_cast<const char*>(data + 52); const char *nameEnd = nameStart + this->name.size(); std::copy(nameStart, nameEnd, this->name.begin()); } void ArenaTypes::Tavern::init(const uint8_t *data) { this->remainingHours = Bytes::getLE16(data); this->timeLimit = Bytes::getLE32(data + 2); } void ArenaTypes::Repair::Job::init(const uint8_t *data) { this->valid = *data; this->dueTo = Bytes::getLE32(data + 1); this->item.init(data + 5); } void ArenaTypes::Repair::init(const uint8_t *data) { const uint8_t *jobsStart = data; for (size_t i = 0; i < this->jobs.size(); i++) { this->jobs[i].init(jobsStart + (Job::SIZE * i)); } } void ArenaTypes::Automap::FogOfWarCache::Note::init(const uint8_t *data) { this->x = Bytes::getLE16(data); this->y = Bytes::getLE16(data + 2); const char *textStart = reinterpret_cast<const char*>(data + 4); const char *textEnd = textStart + this->text.size(); std::copy(textStart, textEnd, this->text.begin()); } void ArenaTypes::Automap::FogOfWarCache::init(const uint8_t *data) { this->levelHash = Bytes::getLE32(data); const uint8_t *notesStart = data + 4; const uint8_t *notesEnd = notesStart + (Note::SIZE * this->notes.size()); for (size_t i = 0; i < this->notes.size(); i++) { this->notes[i].init(notesStart + (Note::SIZE * i)); } const uint8_t *bitmapStart = notesEnd; const uint8_t *bitmapEnd = bitmapStart + this->bitmap.size(); std::copy(bitmapStart, bitmapEnd, this->bitmap.begin()); } void ArenaTypes::Automap::init(const uint8_t *data) { const uint8_t *cachesStart = data; for (size_t i = 0; i < this->caches.size(); i++) { this->caches[i].init(cachesStart + (FogOfWarCache::SIZE * i)); } } void ArenaTypes::Log::Entry::init(const std::string &data) { // Split the title and body on the first newline (there are no carriage returns). const char delimiter = '\n'; const size_t index = data.find(delimiter); this->title = data.substr(0, index); this->body = data.substr(index + 1); } void ArenaTypes::Log::init(const std::string &data) { const std::string delimiter = " *"; size_t offset = 0; size_t index = data.find(delimiter); while (index != std::string::npos) { // Leave out the ampersand at the start of each entry. const std::string entryStr = data.substr(offset + 1, index - offset - 1); this->entries.push_back(Entry()); this->entries.back().init(entryStr); offset = index + delimiter.size(); index = data.find(delimiter, offset); } } void ArenaTypes::Names::Entry::init(const uint8_t *data) { const char *nameStart = reinterpret_cast<const char*>(data); const char *nameEnd = nameStart + this->name.size(); std::copy(nameStart, nameEnd, this->name.begin()); } void ArenaTypes::Names::init(const uint8_t *data) { const uint8_t *entriesStart = data; for (size_t i = 0; i < this->entries.size(); i++) { this->entries[i].init(entriesStart + (Entry::SIZE * i)); } }
5,434
2,707
package org.jetlinks.community.dashboard.measurements; import lombok.AllArgsConstructor; import lombok.Getter; import org.jetlinks.community.dashboard.ObjectDefinition; @Getter @AllArgsConstructor public enum MonitorObjectDefinition implements ObjectDefinition { cpu("CPU"), memory("内存"); private String name; @Override public String getId() { return name(); } }
134
2,915
from assertpy import assert_that import numpy import pytest from waves import bead_matrix from waves import sorted_eigensystem from waves import decompose EPSILON = 1e-5 def normalize(v): norm = numpy.linalg.norm(v) if norm == 0: return v return v / norm def test_bead_matrix_fail(): with pytest.raises(ValueError): bead_matrix(dimension=3) def test_bead_matrix(): expected_matrix = numpy.array( [ [-2, 1, 0, 0, 0], [1, -2, 1, 0, 0], [0, 1, -2, 1, 0], [0, 0, 1, -2, 1], [0, 0, 0, 1, -2], ] ) flattened_expected = expected_matrix.flatten() flattened_actual = bead_matrix(dimension=5).flatten() for (a, b) in zip(flattened_actual, flattened_expected): assert_that(a).is_close_to(b, EPSILON) def test_sorted_eigensystem(): matrix = numpy.array( [ [1, 1, 2], [-1, 3, 2], [-1, 2, 3], ] ) eigenvalues, eigenvectors = sorted_eigensystem(matrix) expected_eigenvalues = [4, 2, 1] expected_eigenvectors = numpy.array([ numpy.array([1, 1, 1]) / numpy.sqrt(3), numpy.array([-3, -1, -1]) / numpy.sqrt(11), numpy.array([-2, -2, 1]) / 3, ]) for (e1, e2) in zip(eigenvalues, expected_eigenvalues): assert_that(e1).is_close_to(e2, EPSILON) for (v1, v2) in zip(eigenvectors, expected_eigenvectors): for (a, b) in zip(v1, v2): assert_that(a).is_close_to(b, EPSILON) def test_decompose(): eigenvectors = numpy.array( [ numpy.array([1, 1, 1]) / numpy.sqrt(3), numpy.array([-3, -1, -1]) / numpy.sqrt(11), numpy.array([-2, -2, 1]) / 3, ] ) vector = numpy.array([1, 2, 3]) decomposition = decompose(eigenvectors, vector) expected_decomposition = { 0: (1 + 2 + 3) / 3**0.5, 1: (-3 - 2 - 3) / 11**0.5, 2: (-2 - 4 + 3) / 3, } for key in decomposition.keys(): assert_that(decomposition[key]).is_close_to( expected_decomposition[key], EPSILON)
1,100
333
<filename>k8s/images/codalab/apps/coopetitions/models.py from django.db import models class Like(models.Model): """ Base model to allow user to like a submission. """ class Meta: unique_together = (('submission', 'user'),) submission = models.ForeignKey('web.CompetitionSubmission', related_name="likes") user = models.ForeignKey('authenz.ClUser') timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s liked %s" % (self.user, self.submission) class Dislike(models.Model): """ Base model to allow authenticated user to dislike a submission """ class Meta: unique_together = (('submission', 'user'),) submission = models.ForeignKey('web.CompetitionSubmission', related_name="dislikes") user = models.ForeignKey('authenz.ClUser') timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s disliked %s" % (self.user, self.submission) class DownloadRecord(models.Model): """ Base model to keep track of the amount of times a submission has been downloaded. """ class Meta: unique_together = (('submission', 'user'),) submission = models.ForeignKey('web.CompetitionSubmission', related_name="downloads") user = models.ForeignKey('authenz.ClUser') timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s downloaded %s" % (self.user, self.submission) def save(self, **kwargs): super(DownloadRecord, self).save(**kwargs) self.submission.download_count = self.submission.downloads.all().count() self.submission.save()
602
343
/* $id: shapes.c,v 1.82 2007/12/24 04:50:36 ellson Exp $ $Revision: 1.1 $ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #include "render.h" #include "htmltable.h" #include <limits.h> #define RBCONST 12 #define RBCURVE .5 typedef struct { pointf (*size_gen) (pointf); void (*vertex_gen) (pointf*, pointf*); } poly_desc_t; static port Center = { {0, 0}, -1, 0, 0, 0, 1, 0, 0, 0 }; #define ATTR_SET(a,n) ((a) && (*(agxget(n,a->index)) != '\0')) /* Default point size = 0.05 inches or 3.6 points */ #define DEF_POINT 0.05 /* Minimum point size = 0.0003 inches or 0.02 points * This will make the radius 0.01 points, which is the smallest * non-zero number output by gvprintdouble in gvdevice.c */ #define MIN_POINT 0.0003 /* extra null character needed to avoid style emitter from thinking * there are arguments. */ static char *point_style[3] = { "invis\0", "filled\0", 0 }; /* forward declarations of functions used in shapes tables */ static void poly_init(node_t * n); static void poly_free(node_t * n); static port poly_port(node_t * n, char *portname, char *); static boolean poly_inside(inside_t * inside_context, pointf p); static int poly_path(node_t * n, port * p, int side, boxf rv[], int *kptr); static void poly_gencode(GVJ_t * job, node_t * n); static void record_init(node_t * n); static void record_free(node_t * n); static port record_port(node_t * n, char *portname, char *); static boolean record_inside(inside_t * inside_context, pointf p); static int record_path(node_t * n, port * p, int side, boxf rv[], int *kptr); static void record_gencode(GVJ_t * job, node_t * n); static void point_init(node_t * n); static void point_gencode(GVJ_t * job, node_t * n); static boolean point_inside(inside_t * inside_context, pointf p); static boolean epsf_inside(inside_t * inside_context, pointf p); static void epsf_gencode(GVJ_t * job, node_t * n); static pointf star_size (pointf); static void star_vertices (pointf*, pointf*); static boolean star_inside(inside_t * inside_context, pointf p); static poly_desc_t star_gen = { star_size, star_vertices, }; static pointf cylinder_size (pointf); static void cylinder_vertices (pointf*, pointf*); static void cylinder_draw(GVJ_t * job, pointf * AF, int sides, int style, int filled); /* static boolean cylinder_inside(inside_t * inside_context, pointf p); */ static poly_desc_t cylinder_gen = { cylinder_size, cylinder_vertices, }; /* polygon descriptions. "polygon" with 0 sides takes all user control */ /* regul perip sides orien disto skew */ static polygon_t p_polygon = { FALSE, 1, 0, 0., 0., 0. }; /* builtin polygon descriptions */ static polygon_t p_ellipse = { FALSE, 1, 1, 0., 0., 0. }; static polygon_t p_circle = { TRUE, 1, 1, 0., 0., 0. }; static polygon_t p_egg = { FALSE, 1, 1, 0., -.3, 0. }; static polygon_t p_triangle = { FALSE, 1, 3, 0., 0., 0. }; static polygon_t p_box = { FALSE, 1, 4, 0., 0., 0. }; static polygon_t p_square = { TRUE, 1, 4, 0., 0., 0. }; static polygon_t p_plaintext = { FALSE, 0, 4, 0., 0., 0. }; static polygon_t p_plain = { FALSE, 0, 4, 0., 0., 0. }; static polygon_t p_diamond = { FALSE, 1, 4, 45., 0., 0. }; static polygon_t p_trapezium = { FALSE, 1, 4, 0., -.4, 0. }; static polygon_t p_parallelogram = { FALSE, 1, 4, 0., 0., .6 }; static polygon_t p_house = { FALSE, 1, 5, 0., -.64, 0. }; static polygon_t p_pentagon = { FALSE, 1, 5, 0., 0., 0. }; static polygon_t p_hexagon = { FALSE, 1, 6, 0., 0., 0. }; static polygon_t p_septagon = { FALSE, 1, 7, 0., 0., 0. }; static polygon_t p_octagon = { FALSE, 1, 8, 0., 0., 0. }; static polygon_t p_note = { FALSE, 1, 4, 0., 0., 0., DOGEAR }; static polygon_t p_tab = { FALSE, 1, 4, 0., 0., 0., TAB }; static polygon_t p_folder = { FALSE, 1, 4, 0., 0., 0., FOLDER }; static polygon_t p_box3d = { FALSE, 1, 4, 0., 0., 0., BOX3D }; static polygon_t p_component = { FALSE, 1, 4, 0., 0., 0., COMPONENT }; static polygon_t p_underline = { FALSE, 1, 4, 0., 0., 0., UNDERLINE }; static polygon_t p_cylinder = { FALSE, 1, 19, 0., 0., 0., CYLINDER, (pointf*)&cylinder_gen }; /* redundant and undocumented builtin polygons */ static polygon_t p_doublecircle = { TRUE, 2, 1, 0., 0., 0. }; static polygon_t p_invtriangle = { FALSE, 1, 3, 180., 0., 0. }; static polygon_t p_invtrapezium = { FALSE, 1, 4, 180., -.4, 0. }; static polygon_t p_invhouse = { FALSE, 1, 5, 180., -.64, 0. }; static polygon_t p_doubleoctagon = { FALSE, 2, 8, 0., 0., 0. }; static polygon_t p_tripleoctagon = { FALSE, 3, 8, 0., 0., 0. }; static polygon_t p_Mdiamond = { FALSE, 1, 4, 45., 0., 0., DIAGONALS | AUXLABELS }; static polygon_t p_Msquare = { TRUE, 1, 4, 0., 0., 0., DIAGONALS }; static polygon_t p_Mcircle = { TRUE, 1, 1, 0., 0., 0., DIAGONALS | AUXLABELS }; /* non-convex polygons */ static polygon_t p_star = { FALSE, 1, 10, 0., 0., 0., 0, (pointf*)&star_gen }; /* biological circuit shapes, as specified by SBOLv*/ /** gene expression symbols **/ static polygon_t p_promoter = { FALSE, 1, 4, 0., 0., 0., PROMOTER }; static polygon_t p_cds = { FALSE, 1, 4, 0., 0., 0., CDS }; static polygon_t p_terminator = { FALSE, 1, 4, 0., 0., 0., TERMINATOR}; static polygon_t p_utr = { FALSE, 1, 4, 0., 0., 0., UTR}; static polygon_t p_insulator = { FALSE, 1, 4, 0., 0., 0., INSULATOR}; static polygon_t p_ribosite = { FALSE, 1, 4, 0., 0., 0., RIBOSITE}; static polygon_t p_rnastab = { FALSE, 1, 4, 0., 0., 0., RNASTAB}; static polygon_t p_proteasesite = { FALSE, 1, 4, 0., 0., 0., PROTEASESITE}; static polygon_t p_proteinstab = { FALSE, 1, 4, 0., 0., 0., PROTEINSTAB}; /** dna construction symbols **/ static polygon_t p_primersite = { FALSE, 1, 4, 0., 0., 0., PRIMERSITE}; static polygon_t p_restrictionsite = { FALSE, 1, 4, 0., 0., 0., RESTRICTIONSITE}; static polygon_t p_fivepoverhang = { FALSE, 1, 4, 0., 0., 0., FIVEPOVERHANG}; static polygon_t p_threepoverhang = { FALSE, 1, 4, 0., 0., 0., THREEPOVERHANG}; static polygon_t p_noverhang = { FALSE, 1, 4, 0., 0., 0., NOVERHANG}; static polygon_t p_assembly = { FALSE, 1, 4, 0., 0., 0., ASSEMBLY}; static polygon_t p_signature = { FALSE, 1, 4, 0., 0., 0., SIGNATURE}; static polygon_t p_rpromoter = { FALSE, 1, 4, 0., 0., 0., RPROMOTER}; static polygon_t p_rarrow = { FALSE, 1, 4, 0., 0., 0., RARROW}; static polygon_t p_larrow = { FALSE, 1, 4, 0., 0., 0., LARROW}; static polygon_t p_lpromoter = { FALSE, 1, 4, 0., 0., 0., LPROMOTER}; #define IS_BOX(n) (ND_shape(n)->polygon == &p_box) #define IS_PLAIN(n) (ND_shape(n)->polygon == &p_plain) /* True if style requires processing through round_corners. */ #define SPECIAL_CORNERS(style) ((style) & (ROUNDED | DIAGONALS | SHAPE_MASK)) /* * every shape has these functions: * * void SHAPE_init(node_t *n) * initialize the shape (usually at least its size). * void SHAPE_free(node_t *n) * free all memory used by the shape * port SHAPE_port(node_t *n, char *portname) * return the aiming point and slope (if constrained) * of a port. * int SHAPE_inside(inside_t *inside_context, pointf p, edge_t *e); * test if point is inside the node shape which is * assumed convex. * the point is relative to the node center. the edge * is passed in case the port affects spline clipping. * int SHAPE_path(node *n, edge_t *e, int pt, boxf path[], int *nbox) * create a path for the port of e that touches n, * return side * void SHAPE_gencode(GVJ_t *job, node_t *n) * generate graphics code for a node. * * some shapes, polygons in particular, use additional shape control data * * */ static shape_functions poly_fns = { poly_init, poly_free, poly_port, poly_inside, poly_path, poly_gencode }; static shape_functions point_fns = { point_init, poly_free, poly_port, point_inside, NULL, point_gencode }; static shape_functions record_fns = { record_init, record_free, record_port, record_inside, record_path, record_gencode }; static shape_functions epsf_fns = { epsf_init, epsf_free, poly_port, epsf_inside, NULL, epsf_gencode }; static shape_functions star_fns = { poly_init, poly_free, poly_port, star_inside, poly_path, poly_gencode }; static shape_functions cylinder_fns = { poly_init, poly_free, poly_port, poly_inside, poly_path, poly_gencode }; static shape_desc Shapes[] = { /* first entry is default for no such shape */ {"box", &poly_fns, &p_box}, {"polygon", &poly_fns, &p_polygon}, {"ellipse", &poly_fns, &p_ellipse}, {"oval", &poly_fns, &p_ellipse}, {"circle", &poly_fns, &p_circle}, {"point", &point_fns, &p_circle}, {"egg", &poly_fns, &p_egg}, {"triangle", &poly_fns, &p_triangle}, {"none", &poly_fns, &p_plaintext}, {"plaintext", &poly_fns, &p_plaintext}, {"plain", &poly_fns, &p_plain}, {"diamond", &poly_fns, &p_diamond}, {"trapezium", &poly_fns, &p_trapezium}, {"parallelogram", &poly_fns, &p_parallelogram}, {"house", &poly_fns, &p_house}, {"pentagon", &poly_fns, &p_pentagon}, {"hexagon", &poly_fns, &p_hexagon}, {"septagon", &poly_fns, &p_septagon}, {"octagon", &poly_fns, &p_octagon}, {"note", &poly_fns, &p_note}, {"tab", &poly_fns, &p_tab}, {"folder", &poly_fns, &p_folder}, {"box3d", &poly_fns, &p_box3d}, {"component", &poly_fns, &p_component}, {"cylinder", &cylinder_fns, &p_cylinder}, {"rect", &poly_fns, &p_box}, {"rectangle", &poly_fns, &p_box}, {"square", &poly_fns, &p_square}, {"doublecircle", &poly_fns, &p_doublecircle}, {"doubleoctagon", &poly_fns, &p_doubleoctagon}, {"tripleoctagon", &poly_fns, &p_tripleoctagon}, {"invtriangle", &poly_fns, &p_invtriangle}, {"invtrapezium", &poly_fns, &p_invtrapezium}, {"invhouse", &poly_fns, &p_invhouse}, {"underline", &poly_fns, &p_underline}, {"Mdiamond", &poly_fns, &p_Mdiamond}, {"Msquare", &poly_fns, &p_Msquare}, {"Mcircle", &poly_fns, &p_Mcircle}, /* biological circuit shapes, as specified by SBOLv*/ /** gene expression symbols **/ {"promoter", &poly_fns, &p_promoter}, {"cds", &poly_fns, &p_cds}, {"terminator", &poly_fns, &p_terminator}, {"utr", &poly_fns, &p_utr}, {"insulator", &poly_fns, &p_insulator}, {"ribosite", &poly_fns, &p_ribosite}, {"rnastab", &poly_fns, &p_rnastab}, {"proteasesite", &poly_fns, &p_proteasesite}, {"proteinstab", &poly_fns, &p_proteinstab}, /** dna construction symbols **/ {"primersite", &poly_fns, &p_primersite}, {"restrictionsite", &poly_fns, &p_restrictionsite}, {"fivepoverhang", &poly_fns, &p_fivepoverhang}, {"threepoverhang", &poly_fns, &p_threepoverhang}, {"noverhang", &poly_fns, &p_noverhang}, {"assembly", &poly_fns, &p_assembly}, {"signature", &poly_fns, &p_signature}, {"rpromoter", &poly_fns, &p_rpromoter}, {"larrow", &poly_fns, &p_larrow}, {"rarrow", &poly_fns, &p_rarrow}, {"lpromoter", &poly_fns, &p_lpromoter}, /* *** shapes other than polygons *** */ {"record", &record_fns, NULL}, {"Mrecord", &record_fns, NULL}, {"epsf", &epsf_fns, NULL}, {"star", &star_fns, &p_star}, {NULL, NULL, NULL} }; static void unrecognized(node_t * n, char *p) { agerr(AGWARN, "node %s, port %s unrecognized\n", agnameof(n), p); } static double quant(double val, double q) { int i; i = val / q; if (i * q + .00001 < val) i++; return i * q; } /* test if both p0 and p1 are on the same side of the line L0,L1 */ static int same_side(pointf p0, pointf p1, pointf L0, pointf L1) { int s0, s1; double a, b, c; /* a x + b y = c */ a = -(L1.y - L0.y); b = (L1.x - L0.x); c = a * L0.x + b * L0.y; s0 = (a * p0.x + b * p0.y - c >= 0); s1 = (a * p1.x + b * p1.y - c >= 0); return (s0 == s1); } static char* penColor(GVJ_t * job, node_t * n) { char *color; color = late_nnstring(n, N_color, ""); if (!color[0]) color = DEFAULT_COLOR; gvrender_set_pencolor(job, color); return color; } static char *findFillDflt(node_t * n, char *dflt) { char *color; color = late_nnstring(n, N_fillcolor, ""); if (!color[0]) { /* for backward compatibilty, default fill is same as pen */ color = late_nnstring(n, N_color, ""); if (!color[0]) { color = dflt; } } return color; } static char *findFill(node_t * n) { return (findFillDflt(n, DEFAULT_FILL)); } char *findAttrColor(void *obj, attrsym_t *colorattr, char *dflt){ char *color; if(colorattr != NULL) color = late_nnstring(obj, colorattr, dflt); else if(dflt != NULL && dflt[0]) color = dflt; else color = DEFAULT_FILL; return color; } static int isBox (node_t* n) { polygon_t *p; if ((p = ND_shape(n)->polygon)) { return (p->sides == 4 && (ROUND(p->orientation) % 90) == 0 && p->distortion == 0. && p->skew == 0.); } else return 0; } /* isEllipse: */ static int isEllipse(node_t* n) { polygon_t *p; if ((p = ND_shape(n)->polygon)) { return (p->sides <= 2); } else return 0; } static char **checkStyle(node_t * n, int *flagp) { char *style; char **pstyle = 0; int istyle = 0; polygon_t *poly; style = late_nnstring(n, N_style, ""); if (style[0]) { char **pp; char **qp; char *p; pp = pstyle = parse_style(style); while ((p = *pp)) { if (streq(p, "filled")) { istyle |= FILLED; pp++; } else if (streq(p, "rounded")) { istyle |= ROUNDED; qp = pp; /* remove rounded from list passed to renderer */ do { qp++; *(qp - 1) = *qp; } while (*qp); } else if (streq(p, "diagonals")) { istyle |= DIAGONALS; qp = pp; /* remove diagonals from list passed to renderer */ do { qp++; *(qp - 1) = *qp; } while (*qp); } else if (streq(p, "invis")) { istyle |= INVISIBLE; pp++; } else if (streq(p, "radial")) { istyle |= (RADIAL|FILLED); qp = pp; /* remove radial from list passed to renderer */ do { qp++; *(qp - 1) = *qp; } while (*qp); } else if (streq(p, "striped") && isBox(n)) { istyle |= STRIPED; qp = pp; /* remove striped from list passed to renderer */ do { qp++; *(qp - 1) = *qp; } while (*qp); } else if (streq(p, "wedged") && isEllipse(n)) { istyle |= WEDGED; qp = pp; /* remove wedged from list passed to renderer */ do { qp++; *(qp - 1) = *qp; } while (*qp); } else pp++; } } if ((poly = ND_shape(n)->polygon)) istyle |= poly->option; *flagp = istyle; return pstyle; } static int stylenode(GVJ_t * job, node_t * n) { char **pstyle, *s; int istyle; double penwidth; if ((pstyle = checkStyle(n, &istyle))) gvrender_set_style(job, pstyle); if (N_penwidth && ((s = agxget(n, N_penwidth)) && s[0])) { penwidth = late_double(n, N_penwidth, 1.0, 0.0); gvrender_set_penwidth(job, penwidth); } return istyle; } static void Mcircle_hack(GVJ_t * job, node_t * n) { double x, y; pointf AF[2], p; y = .7500; x = .6614; /* x^2 + y^2 = 1.0 */ p.y = y * ND_ht(n) / 2.0; p.x = ND_rw(n) * x; /* assume node is symmetric */ AF[0] = add_pointf(p, ND_coord(n)); AF[1].y = AF[0].y; AF[1].x = AF[0].x - 2 * p.x; gvrender_polyline(job, AF, 2); AF[0].y -= 2 * p.y; AF[1].y = AF[0].y; gvrender_polyline(job, AF, 2); } /* round_corners: * Handle some special graphical cases, such as rounding the shape, * adding diagonals at corners, or drawing certain non-simple figures. * Any drawing done here should assume fillcolors, pencolors, etc. * have been set by the calling routine. Normally, the drawing should * consist of a region, filled or unfilled, followed by additional line * segments. A single fill is necessary for gradient colors to work. */ void round_corners(GVJ_t * job, pointf * AF, int sides, int style, int filled) { pointf *B, C[5], *D, p0, p1; double rbconst, d, dx, dy, t; int i, seg, mode, shape; pointf* pts; shape = style & SHAPE_MASK; if (style & DIAGONALS) mode = DIAGONALS; else if (style & SHAPE_MASK) mode = shape; else mode = ROUNDED; if (mode == CYLINDER) { cylinder_draw (job, AF, sides, style, filled); return; } B = N_NEW(4 * sides + 4, pointf); i = 0; /* rbconst is distance offset from a corner of the polygon. * It should be the same for every corner, and also never * bigger than one-third the length of a side. */ rbconst = RBCONST; for (seg = 0; seg < sides; seg++) { p0 = AF[seg]; if (seg < sides - 1) p1 = AF[seg + 1]; else p1 = AF[0]; dx = p1.x - p0.x; dy = p1.y - p0.y; d = sqrt(dx * dx + dy * dy); rbconst = MIN(rbconst, d / 3.0); } for (seg = 0; seg < sides; seg++) { p0 = AF[seg]; if (seg < sides - 1) p1 = AF[seg + 1]; else p1 = AF[0]; dx = p1.x - p0.x; dy = p1.y - p0.y; d = sqrt(dx * dx + dy * dy); t = rbconst / d; if (shape == BOX3D || shape == COMPONENT) t /= 3; else if (shape == DOGEAR) t /= 2; if (mode != ROUNDED) B[i++] = p0; else B[i++] = interpolate_pointf(RBCURVE * t, p0, p1); B[i++] = interpolate_pointf(t, p0, p1); B[i++] = interpolate_pointf(1.0 - t, p0, p1); if (mode == ROUNDED) B[i++] = interpolate_pointf(1.0 - RBCURVE * t, p0, p1); } B[i++] = B[0]; B[i++] = B[1]; B[i++] = B[2]; switch (mode) { case ROUNDED: pts = N_GNEW(6 * sides + 2, pointf); i = 0; for (seg = 0; seg < sides; seg++) { pts[i++] = B[4 * seg]; pts[i++] = B[4 * seg+1]; pts[i++] = B[4 * seg+1]; pts[i++] = B[4 * seg+2]; pts[i++] = B[4 * seg+2]; pts[i++] = B[4 * seg+3]; } pts[i++] = pts[0]; pts[i++] = pts[1]; gvrender_beziercurve(job, pts+1, i-1, FALSE, FALSE, filled); free (pts); #if 0 if (filled) { pointf *pts = N_GNEW(2 * sides, pointf); pts[j++] = B[4 * seg + 1]; pts[j++] = B[4 * seg + 2]; } gvrender_polygon(job, pts, 2 * sides, filled); free(pts); for (seg = 0; seg < sides; seg++) { } } if (penc) { for (seg = 0; seg < sides; seg++) { gvrender_polyline(job, B + 4 * seg + 1, 2); gvrender_beziercurve(job, B + 4 * seg + 2, 4, FALSE, FALSE, FALSE); } } #endif break; case DIAGONALS: /* diagonals are weird. rewrite someday. */ gvrender_polygon(job, AF, sides, filled); for (seg = 0; seg < sides; seg++) { #ifdef NOTDEF C[0] = B[3 * seg]; C[1] = B[3 * seg + 3]; gvrender_polyline(job, C, 2); #endif C[0] = B[3 * seg + 2]; C[1] = B[3 * seg + 4]; gvrender_polyline(job, C, 2); } break; case DOGEAR: /* Add the cutoff edge. */ D = N_NEW(sides + 1, pointf); for (seg = 1; seg < sides; seg++) D[seg] = AF[seg]; D[0] = B[3 * (sides - 1) + 4]; D[sides] = B[3 * (sides - 1) + 2]; gvrender_polygon(job, D, sides + 1, filled); free(D); /* Draw the inner edge. */ seg = sides - 1; C[0] = B[3 * seg + 2]; C[1] = B[3 * seg + 4]; C[2].x = C[1].x + (C[0].x - B[3 * seg + 3].x); C[2].y = C[1].y + (C[0].y - B[3 * seg + 3].y); gvrender_polyline(job, C + 1, 2); C[1] = C[2]; gvrender_polyline(job, C, 2); break; case TAB: /* * Adjust the perimeter for the protrusions. * * D[3] +--+ D[2] * | | B[1] * B[3] + +----------+--+ AF[0]=B[0]=D[0] * | B[2]=D[1] | * B[4] + | * | | * B[5] + | * +----------------+ * */ /* Add the tab edges. */ D = N_NEW(sides + 2, pointf); D[0] = AF[0]; D[1] = B[2]; D[2].x = B[2].x + (B[3].x - B[4].x) / 3; D[2].y = B[2].y + (B[3].y - B[4].y) / 3; D[3].x = B[3].x + (B[3].x - B[4].x) / 3; D[3].y = B[3].y + (B[3].y - B[4].y) / 3; for (seg = 4; seg < sides + 2; seg++) D[seg] = AF[seg - 2]; gvrender_polygon(job, D, sides + 2, filled); free(D); /* Draw the inner edge. */ C[0] = B[3]; C[1] = B[2]; gvrender_polyline(job, C, 2); break; case FOLDER: /* * Adjust the perimeter for the protrusions. * * D[2] +----+ D[1] * B[3]= / \ * D[4] +--+----+ + + AF[0]=B[0]=D[0] * | B[2] D[3] B[1]| * B[4] + | * | | * B[5] + | * +----------------+ * */ /* Add the folder edges. */ D = N_NEW(sides + 3, pointf); D[0] = AF[0]; D[1].x = AF[0].x - (AF[0].x - B[1].x) / 4; D[1].y = AF[0].y + (B[3].y - B[4].y) / 3; D[2].x = AF[0].x - 2 * (AF[0].x - B[1].x); D[2].y = D[1].y; D[3].x = AF[0].x - 2.25 * (AF[0].x - B[1].x); D[3].y = B[3].y; D[4].x = B[3].x; D[4].y = B[3].y; for (seg = 4; seg < sides + 3; seg++) D[seg] = AF[seg - 3]; gvrender_polygon(job, D, sides + 3, filled); free(D); break; case BOX3D: assert(sides == 4); /* Adjust for the cutoff edges. */ D = N_NEW(sides + 2, pointf); D[0] = AF[0]; D[1] = B[2]; D[2] = B[4]; D[3] = AF[2]; D[4] = B[8]; D[5] = B[10]; gvrender_polygon(job, D, sides + 2, filled); free(D); /* Draw the inner vertices. */ C[0].x = B[1].x + (B[11].x - B[0].x); C[0].y = B[1].y + (B[11].y - B[0].y); C[1] = B[4]; gvrender_polyline(job, C, 2); C[1] = B[8]; gvrender_polyline(job, C, 2); C[1] = B[0]; gvrender_polyline(job, C, 2); break; case COMPONENT: assert(sides == 4); /* * Adjust the perimeter for the protrusions. * * D[1] +----------------+ D[0] * | | * 3+---+2 | * | | * 4+---+5 | * | | * 7+---+6 | * | | * 8+---+9 | * | | * 10+----------------+ D[11] * */ D = N_NEW(sides + 8, pointf); D[0] = AF[0]; D[1] = AF[1]; D[2].x = B[3].x + (B[4].x - B[3].x); D[2].y = B[3].y + (B[4].y - B[3].y); D[3].x = D[2].x + (B[3].x - B[2].x); D[3].y = D[2].y + (B[3].y - B[2].y); D[4].x = D[3].x + (B[4].x - B[3].x); D[4].y = D[3].y + (B[4].y - B[3].y); D[5].x = D[4].x + (D[2].x - D[3].x); D[5].y = D[4].y + (D[2].y - D[3].y); D[9].x = B[6].x + (B[5].x - B[6].x); D[9].y = B[6].y + (B[5].y - B[6].y); D[8].x = D[9].x + (B[6].x - B[7].x); D[8].y = D[9].y + (B[6].y - B[7].y); D[7].x = D[8].x + (B[5].x - B[6].x); D[7].y = D[8].y + (B[5].y - B[6].y); D[6].x = D[7].x + (D[9].x - D[8].x); D[6].y = D[7].y + (D[9].y - D[8].y); D[10] = AF[2]; D[11] = AF[3]; gvrender_polygon(job, D, sides + 8, filled); /* Draw the internal vertices. */ C[0] = D[2]; C[1].x = D[2].x - (D[3].x - D[2].x); C[1].y = D[2].y - (D[3].y - D[2].y); C[2].x = C[1].x + (D[4].x - D[3].x); C[2].y = C[1].y + (D[4].y - D[3].y); C[3] = D[5]; gvrender_polyline(job, C, 4); C[0] = D[6]; C[1].x = D[6].x - (D[7].x - D[6].x); C[1].y = D[6].y - (D[7].y - D[6].y); C[2].x = C[1].x + (D[8].x - D[7].x); C[2].y = C[1].y + (D[8].y - D[7].y); C[3] = D[9]; gvrender_polyline(job, C, 4); free(D); break; case PROMOTER: /* * L-shaped arrow on a center line, scales in the x direction * * * D[1] |\ * +----------------+ \ * | D[0] \ * | \ * | / * | D[5] / * | +-------+ / * | | |/ * +--------+ */ /* Add the tab edges. */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //the arrow's thickness is (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides + 5, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (AF[0].x - AF[1].x)/8; //x_center + width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)*3/2; //D[4].y + width D[1].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (AF[0].x - AF[1].x)/4; //x_center - 2*width D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center D[3].x = D[2].x + (B[2].x - B[3].x)/2; //D[2].x + width D[3].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center D[4].x = D[3].x; D[4].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y); //highest cds point D[5].x = D[0].x; D[5].y = D[4].y; //highest cds point D[6].x = D[0].x; D[6].y = D[4].y - (B[3].y-B[4].y)/4; //D[4].y - width/2 D[7].x = D[6].x + (B[2].x - B[3].x); //D[6].x + 2*width D[7].y = D[6].y + (B[3].y - B[4].y)/2; //D[6].y + width D[8].x = D[0].x; D[8].y = D[0].y + (B[3].y - B[4].y)/4;//D[0].y + width/2 gvrender_polygon(job, D, sides + 5, filled); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case CDS: /* * arrow without the protrusions, scales normally * * * D[1] = AF[1] * +----------------+\ * | D[0]\ * | \ * | / * | / * +----------------+/ * D[3] * */ D = N_NEW(sides + 1, pointf); D[0].x = B[1].x; D[0].y = B[1].y - (B[3].y - B[4].y)/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)/2; D[2].x = AF[2].x; D[2].y = AF[2].y + (B[3].y - B[4].y)/2; D[3].x = B[1].x; D[3].y = AF[2].y + (B[3].y - B[4].y)/2; D[4].y = AF[0].y - (AF[0].y - AF[3].y)/2; D[4].x = AF[0].x; gvrender_polygon(job, D, sides + 1, filled); free(D); break; case TERMINATOR: /* * T-shape, does not scale, always in the center * * * D[4] * +----------------+ * | D[3] * | | * | | * | D[6] D[1] | * D[5]+---+ +----+ D[2] * | | * +-------+ D[0] */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides + 4, pointf); D[0].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)/4; //x_center + width/2 D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)/2; D[2].x = D[1].x + (B[2].x-B[3].x)/2; D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[2].y + (B[3].y-B[4].y)/2; D[4].x = AF[1].x + (AF[0].x-AF[1].x)/2 - (B[2].x-B[3].x)*3/4; //D[3].y mirrowed across the center D[4].y = D[3].y; D[5].x = D[4].x; D[5].y = D[2].y; D[6].x = AF[1].x + (AF[0].x-AF[1].x)/2 - (B[2].x-B[3].x)/4; //D[1].x mirrowed across the center D[6].y = D[1].y; D[7].x = D[6].x; D[7].y = D[0].y; gvrender_polygon(job, D, sides + 4, filled); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case UTR: /* * half-octagon with line, does not scale, always in center * * D[3] * _____ D[2] * / \ * / \ D[1] * | | * ----------- * D[0] * * * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides + 2, pointf); D[0].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)*3/4; //x_center+width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)/4; //D[0].y+width/2 D[2].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)/4; //x_center+width/2 D[2].y = D[1].y + (B[3].y-B[4].y)/2; //D[1].y+width D[3].x = AF[1].x + (AF[0].x-AF[1].x)/2 - (B[2].x-B[3].x)/4; //D[2].x mirrowed across the center D[3].y = D[2].y; D[4].x = AF[1].x + (AF[0].x-AF[1].x)/2 - (B[2].x-B[3].x)*3/4; D[4].y = D[1].y; D[5].x = D[4].x; D[5].y = D[0].y; gvrender_polygon(job, D, sides + 2, filled); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case PRIMERSITE: /* * half arrow shape, scales in the x-direction * D[1] * |\ * | \ * | \ * ------------ \ * | \ * ------------------\ D[0] * * -------------------------------- * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides + 1, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (B[2].x-B[3].x);//x_center + width*2 D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/4;//y_center + 1/2 width D[1].x = D[0].x - (B[2].x-B[3].x); //x_center D[1].y = D[0].y + (B[3].y-B[4].y); D[2].x = D[1].x; D[2].y = D[0].y + (B[3].y-B[4].y)/2; D[3].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (AF[0].x - AF[1].x)/4;//x_center - 2*(scalable width) D[3].y = D[2].y; D[4].x = D[3].x; D[4].y = D[0].y; gvrender_polygon(job, D, sides + 1, filled); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case RESTRICTIONSITE: /* * zigzag shape, scales in the x-direction (only the middle section) * * * ----D[2] * | |________ D[0] * | |____ * ---------- | * D[4] --- D[7] * * * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides + 4, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (AF[0].x - AF[1].x)/8 + (B[2].x-B[3].x)/2;//x_center + scalable_width + width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/4;//y_center + 1/2 width D[1].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (AF[0].x - AF[1].x)/8; //x_center - width D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[2].x - (B[2].x-B[3].x)/2; //D[2].x - width D[3].y = D[2].y; D[4].x = D[3].x; D[4].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)/4; //y_center - 1/2(width) D[5].x = D[0].x - (B[2].x-B[3].x)/2; D[5].y = D[4].y; D[6].x = D[5].x; D[6].y = D[5].y - (B[3].y-B[4].y)/2; D[7].x = D[0].x; D[7].y = D[6].y; gvrender_polygon(job, D, sides + 4, filled); /*dsDNA line left half*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = D[4].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); /*dsDNA line right half*/ C[0].x = D[7].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case FIVEPOVERHANG: /* * does not scale, on the left side * * D[3]------D[2] * | | * D[0]------D[1] * ----- ------------ * | | * D[0]--D[1] * * * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[1].x;//the very left edge D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/8;//y_center + 1/4 width D[1].x = D[0].x + 2*(B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*second, lower shape*/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (B[2].x-B[3].x); D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)*5/8; //y_center - 5/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*dsDNA line right half*/ C[0].x = D[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case THREEPOVERHANG: /* * does not scale, on the right side * * D[2]------D[1] * | | *----------D[3]------D[0] * ----- D[1] * | | * D[3]--D[0] * * * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[0].x;//the very right edge D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/8;//y_center + 1/4 width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)/2; D[2].x = D[1].x - 2*(B[3].y-B[4].y); D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[0].y; gvrender_polygon(job, D, sides, filled); /*second, lower shape*/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[0].x - (B[2].x-B[3].x); D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)*5/8; //y_center - 5/4 width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)/2; D[2].x = D[1].x - (B[3].y-B[4].y); D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[0].y; gvrender_polygon(job, D, sides, filled); /*dsDNA line left half*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = D[3].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case NOVERHANG: /* * does not scale * * D[3]------D[2] D[3]------D[2] * | | | | * ---D[0]------D[1] D[0]------D[1]---- * D[3]------D[2] D[3]------D[2] * | | | | * D[0]------D[1] D[0]------D[1] * * * * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length /*upper left rectangle*/ D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x)*9/8; //x_center - 2*width - 1/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/8;//y_center + 1/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*lower, left rectangle*/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x)*9/8; //x_center - 2*width - 1/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)*5/8;//y_center - width - 1/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*lower, right rectangle*/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (B[2].x-B[3].x)/8; //x_center + 1/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)*5/8;//y_center - width - 1/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*upper, right rectangle*/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (B[2].x-B[3].x)/8; //x_center + 1/4*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/8;//y_center - width - 1/4 width D[1].x = D[0].x + (B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*dsDNA line right half*/ C[0].x = D[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); /*dsDNA line left half*/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x)*9/8; //D[0].x of of the left rectangles C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[1].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case ASSEMBLY: /* * does not scale * * D[3]----------D[2] * | | * D[0]----------D[1] * ---- --------- * D[3]----------D[2] * | | * D[0]----------D[1] * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x); //x_center - 2*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/8;//y_center + 1/4 width D[1].x = D[0].x + 2*(B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*second, lower shape*/ free(D); D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x); //x_center - 2*width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)*5/8;//y_center - width - 1/4 width D[1].x = D[0].x + 2*(B[2].x-B[3].x); D[1].y = D[0].y; D[2].x = D[1].x; D[2].y = D[1].y + (B[3].y-B[4].y)/2; D[3].x = D[0].x; D[3].y = D[2].y; gvrender_polygon(job, D, sides, filled); /*dsDNA line right half*/ C[0].x = D[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); /*dsDNA line left half*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = D[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case SIGNATURE: /* * * * +--------------+ * | | * |x | * |_____________ | * +--------------+ */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2; //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; //the thickness is subituted with (AF[0].x - AF[1].x)/8 to make it scalable in the y with label length D = N_NEW(sides, pointf); D[0].x = AF[0].x; D[0].y = B[1].y - (B[3].y - B[4].y)/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)/2; D[2].x = AF[2].x; D[2].y = AF[2].y + (B[3].y - B[4].y)/2; D[3].x = AF[0].x; D[3].y = AF[2].y + (B[3].y - B[4].y)/2; gvrender_polygon(job, D, sides, filled); /* "\" of the X*/ C[0].x = AF[1].x + (B[2].x-B[3].x)/4; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/8; //y_center + 1/4 width C[1].x = C[0].x + (B[2].x-B[3].x)/4;//C[0].x + width/2 C[1].y = C[0].y - (B[3].y-B[4].y)/4;//C[0].y - width/2 gvrender_polyline(job, C, 2); /*"/" of the X*/ C[0].x = AF[1].x + (B[2].x-B[3].x)/4; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[3].y-B[4].y)/8; //y_center - 1/4 width C[1].x = C[0].x + (B[2].x-B[3].x)/4;//C[0].x + width/2 C[1].y = C[0].y + (B[3].y-B[4].y)/4;//C[0].y + width/2 gvrender_polyline(job, C, 2); /*bottom line*/ C[0].x = AF[1].x + (B[2].x-B[3].x)/4; C[0].y = AF[2].y + (B[3].y-B[4].y)*3/4; C[1].x = AF[0].x - (B[2].x-B[3].x)/4; C[1].y = C[0].y; gvrender_polyline(job, C, 2); free(D); break; case INSULATOR: /* * double square * * +-----+ *--| ___ |--- * | |_| | * +-----+ * */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides, pointf); D[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (B[2].x-B[3].x)/2; //x_center+width D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[2].x-B[3].x)/2; //y_center D[1].x = D[0].x; D[1].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[2].x-B[3].x)/2; //D[0].y- width D[2].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x)/2; //x_center-width D[2].y = D[1].y; D[3].x = D[2].x; D[3].y = D[0].y; gvrender_polygon(job, D, sides, filled); free(D); /*outer square line*/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (B[2].x-B[3].x)*3/4; //x_center+1.5*width C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[2].x-B[3].x)*3/4; //y_center C[1].x = C[0].x; C[1].y = AF[2].y + (AF[1].y - AF[2].y)/2 - (B[2].x-B[3].x)*3/4; //y_center- 1.5*width C[2].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x)*3/4; //x_center-1.5*width C[2].y = C[1].y; C[3].x = C[2].x; C[3].y = C[0].y; C[4] = C[0]; gvrender_polyline(job, C, 5); /*dsDNA line right half*/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)/2 + (B[2].x-B[3].x)*3/4; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); /*dsDNA line left half*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[1].x + (AF[0].x - AF[1].x)/2 - (B[2].x-B[3].x)*3/4; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); break; case RIBOSITE: /* * X with a dashed line on the bottom * * * X * | * ------------ */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides + 12, pointf); //12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)/4; //x_center+widtht/2 , lower right corner of the x D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/2; //y_center + width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)/8; //D[0].y +width/4 D[2].x = D[0].x - (B[2].x-B[3].x)/8; //D[0].x- width/4 //right nook of the x D[2].y = D[1].y + (B[3].y-B[4].y)/8; //D[0].y+width/2 or D[1].y+width/4 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)/8; //D[2].y + width/4 D[4].x = D[0].x; D[4].y = D[3].y + (B[3].y-B[4].y)/8; //top right corner of the x D[5].x = D[2].x; D[5].y = D[4].y; D[6].x = AF[1].x + (AF[0].x - AF[1].x)/2; //x_center D[6].y = D[3].y; //top nook D[7].x = D[6].x - (B[2].x-B[3].x)/8; //D[5] mirrowed across y D[7].y = D[5].y; D[8].x = D[7].x - (B[2].x-B[3].x)/8;//top left corner D[8].y = D[7].y; D[9].x = D[8].x; D[9].y = D[3].y; D[10].x = D[8].x + (B[2].x-B[3].x)/8; D[10].y = D[2].y; D[11].x = D[8].x; D[11].y = D[1].y; D[12].x = D[8].x; D[12].y = D[0].y; D[13].x = D[10].x; D[13].y = D[12].y; D[14].x = D[6].x; //bottom nook D[14].y = D[1].y; D[15].x = D[2].x; D[15].y = D[0].y; gvrender_polygon(job, D, sides + 12, filled); //2-part dash line /*line below the x, bottom dash*/ C[0].x = D[14].x; //x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)/8; //y_center + 1/4*width gvrender_polyline(job, C, 2); /*line below the x, top dash*/ C[0].x = D[14].x; //x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/4; C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)/8; gvrender_polyline(job, C, 2); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case RNASTAB: /* * hexagon with a dashed line on the bottom * * * O * | * ------------ */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides + 4, pointf); //12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)/8; //x_center+widtht/8 , lower right corner of the hexagon D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/2; //y_center + width D[1].x = D[0].x + (B[2].x-B[3].x)/8; D[1].y = D[0].y + (B[3].y-B[4].y)/8; //D[0].y +width/4 D[2].x = D[1].x; //D[0].x- width/4 D[2].y = D[1].y + (B[3].y-B[4].y)/4; //D[1].y+width/2 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)/8; //D[2].y + width/4 D[4].x = D[3].x - (B[2].x-B[3].x)/4; D[4].y = D[3].y; //top of the hexagon D[5].x = D[4].x - (B[2].x-B[3].x)/8; D[5].y = D[2].y; D[6].x = D[5].x; D[6].y = D[1].y; //left side D[7].x = D[4].x; D[7].y = D[0].y; //bottom gvrender_polygon(job, D, sides + 4, filled); //2-part dash line /*line below the x, bottom dash*/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)/2; //x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)/8; //y_center + 1/4*width gvrender_polyline(job, C, 2); /*line below the x, top dash*/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)/2; //x_center C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/4; C[1].x = C[0].x; C[1].y = C[0].y + (B[3].y-B[4].y)/8; gvrender_polyline(job, C, 2); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case PROTEASESITE: /* * X with a solid line on the bottom * * * X * | * ------------ */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides + 12, pointf); //12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)/4; //x_center+widtht/2 , lower right corner of the x D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/2; //y_center + width D[1].x = D[0].x; D[1].y = D[0].y + (B[3].y-B[4].y)/8; //D[0].y +width/4 D[2].x = D[0].x - (B[2].x-B[3].x)/8; //D[0].x- width/4 //right nook of the x D[2].y = D[1].y + (B[3].y-B[4].y)/8; //D[0].y+width/2 or D[1].y+width/4 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)/8; //D[2].y + width/4 D[4].x = D[0].x; D[4].y = D[3].y + (B[3].y-B[4].y)/8; //top right corner of the x D[5].x = D[2].x; D[5].y = D[4].y; D[6].x = AF[1].x + (AF[0].x - AF[1].x)/2; //x_center D[6].y = D[3].y; //top nook D[7].x = D[6].x - (B[2].x-B[3].x)/8; //D[5] mirrowed across y D[7].y = D[5].y; D[8].x = D[7].x - (B[2].x-B[3].x)/8;//top left corner D[8].y = D[7].y; D[9].x = D[8].x; D[9].y = D[3].y; D[10].x = D[8].x + (B[2].x-B[3].x)/8; D[10].y = D[2].y; D[11].x = D[8].x; D[11].y = D[1].y; D[12].x = D[8].x; D[12].y = D[0].y; D[13].x = D[10].x; D[13].y = D[12].y; D[14].x = D[6].x; //bottom nook D[14].y = D[1].y; D[15].x = D[2].x; D[15].y = D[0].y; gvrender_polygon(job, D, sides + 12, filled); /*line below the x*/ C[0] = D[14]; C[1].x = C[0].x; C[1].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center gvrender_polyline(job, C, 2); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case PROTEINSTAB: /* * hexagon with a dashed line on the bottom * * * O * | * ------------ */ //x_center is AF[1].x + (AF[0].x - AF[1].x)/2 //y_center is AF[2].y + (AF[1].y - AF[2].y)/2; //width units are (B[2].x-B[3].x)/2 or (B[3].y-B[4].y)/2; D = N_NEW(sides + 4, pointf); //12-sided x D[0].x = AF[1].x + (AF[0].x-AF[1].x)/2 + (B[2].x-B[3].x)/8; //x_center+widtht/8 , lower right corner of the hexagon D[0].y = AF[2].y + (AF[1].y - AF[2].y)/2 + (B[3].y-B[4].y)/2; //y_center + width D[1].x = D[0].x + (B[2].x-B[3].x)/8; D[1].y = D[0].y + (B[3].y-B[4].y)/8; //D[0].y +width/4 D[2].x = D[1].x; //D[0].x- width/4 D[2].y = D[1].y + (B[3].y-B[4].y)/4; //D[1].y+width/2 D[3].x = D[0].x; D[3].y = D[2].y + (B[3].y-B[4].y)/8; //D[2].y + width/4 D[4].x = D[3].x - (B[2].x-B[3].x)/4; D[4].y = D[3].y; //top of the hexagon D[5].x = D[4].x - (B[2].x-B[3].x)/8; D[5].y = D[2].y; D[6].x = D[5].x; D[6].y = D[1].y; //left side D[7].x = D[4].x; D[7].y = D[0].y; //bottom gvrender_polygon(job, D, sides + 4, filled); /*line below the x*/ C[0].x = AF[1].x + (AF[0].x - AF[1].x)/2; C[0].y = D[0].y; C[1].x = C[0].x; C[1].y = AF[2].y + (AF[1].y - AF[2].y)/2; //y_center gvrender_polyline(job, C, 2); /*dsDNA line*/ C[0].x = AF[1].x; C[0].y = AF[2].y + (AF[1].y - AF[2].y)/2; C[1].x = AF[0].x; C[1].y = AF[2].y + (AF[0].y - AF[3].y)/2; gvrender_polyline(job, C, 2); free(D); break; case RPROMOTER: /* * Adjust the perimeter for the protrusions. * * * D[1] = AF[1] |\ * +----------------+ \ * | D[0] \ * | \ * | / * | / * | +-------+ / * | | |/ * +--------+ */ /* Add the tab edges. */ D = N_NEW(sides + 5, pointf); /*5 new points*/ D[0].x = B[1].x - (B[2].x - B[3].x)/2; D[0].y = B[1].y - (B[3].y - B[4].y)/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)/2; D[2].x = AF[2].x; D[2].y = AF[2].y; D[3].x = B[2].x + (B[2].x - B[3].x)/2; D[3].y = AF[2].y; D[4].x = B[2].x + (B[2].x - B[3].x)/2; D[4].y = AF[2].y + (B[3].y - B[4].y)/2; D[5].x = B[1].x - (B[2].x - B[3].x)/2; D[5].y = AF[2].y + (B[3].y - B[4].y)/2; D[6].x = B[1].x - (B[2].x - B[3].x)/2; D[6].y = AF[3].y; D[7].y = AF[0].y - (AF[0].y - AF[3].y)/2; /*triangle point */ D[7].x = AF[0].x; /*triangle point */ D[8].y = AF[0].y; D[8].x = B[1].x - (B[2].x - B[3].x)/2; gvrender_polygon(job, D, sides + 5, filled); free(D); break; case RARROW: /* * Adjust the perimeter for the protrusions. * * * D[1] = AF[1] |\ * +----------------+ \ * | D[0] \ * | \ * | / * | / * +----------------+ / * |/ * */ /* Add the tab edges. */ D = N_NEW(sides + 3, pointf); /*3 new points*/ D[0].x = B[1].x - (B[2].x - B[3].x)/2; D[0].y = B[1].y - (B[3].y - B[4].y)/2; D[1].x = B[3].x; D[1].y = B[3].y - (B[3].y - B[4].y)/2; D[2].x = AF[2].x; D[2].y = AF[2].y + (B[3].y - B[4].y)/2; D[3].x = B[1].x - (B[2].x - B[3].x)/2; D[3].y = AF[2].y + (B[3].y - B[4].y)/2; D[4].x = B[1].x - (B[2].x - B[3].x)/2; D[4].y = AF[3].y; D[5].y = AF[0].y - (AF[0].y - AF[3].y)/2;/*triangle point*/ D[5].x = AF[0].x; /*triangle point */ D[6].y = AF[0].y; D[6].x = B[1].x - (B[2].x - B[3].x)/2; gvrender_polygon(job, D, sides + 3, filled); free(D); break; case LARROW: /* * Adjust the perimeter for the protrusions. * * * /| * / +----------------+ * / | * \ | * \ +----------------+ * \| * */ /* Add the tab edges. */ D = N_NEW(sides + 3, pointf); /*3 new points*/ D[0].x = AF[0].x; D[0].y = AF[0].y - (B[3].y-B[4].y)/2; D[1].x = B[2].x + (B[2].x - B[3].x)/2; D[1].y = AF[0].y - (B[3].y-B[4].y)/2;/*D[0].y*/ D[2].x = B[2].x + (B[2].x - B[3].x)/2;/*D[1].x*/ D[2].y = B[2].y; D[3].x = AF[1].x; /*triangle point*/ D[3].y = AF[1].y - (AF[1].y - AF[2].y)/2; /*triangle point*/ D[4].x = B[2].x + (B[2].x - B[3].x)/2;/*D[1].x*/ D[4].y = AF[2].y; D[5].y = AF[2].y + (B[3].y-B[4].y)/2; D[5].x = B[2].x + (B[2].x - B[3].x)/2;/*D[1].x*/ D[6].y = AF[3].y + (B[3].y - B[4].y)/2; D[6].x = AF[0].x;/*D[0]*/ gvrender_polygon(job, D, sides + 3, filled); free(D); break; case LPROMOTER: /* * Adjust the perimeter for the protrusions. * * * /| * / +----------------+ * / D[0] * / | * \ | * \ | * \ +--------+ + * \| | | * +-------+ */ /* Add the tab edges. */ D = N_NEW(sides + 5, pointf); /*3 new points*/ D[0].x = AF[0].x; D[0].y = AF[0].y - (B[3].y-B[4].y)/2; D[1].x = B[2].x + (B[2].x - B[3].x)/2; D[1].y = AF[0].y - (B[3].y-B[4].y)/2;/*D[0].y*/ D[2].x = B[2].x + (B[2].x - B[3].x)/2;/*D[1].x*/ D[2].y = B[2].y; D[3].x = AF[1].x; /*triangle point*/ D[3].y = AF[1].y - (AF[1].y - AF[2].y)/2; /*triangle point*/ D[4].x = B[2].x + (B[2].x - B[3].x)/2;/*D[1].x*/ D[4].y = AF[2].y; D[5].y = AF[2].y + (B[3].y-B[4].y)/2; D[5].x = B[2].x + (B[2].x - B[3].x)/2;/*D[1].x*/ D[6].y = AF[3].y + (B[3].y - B[4].y)/2; D[6].x = B[1].x - (B[2].x - B[3].x)/2; D[7].x = B[1].x - (B[2].x - B[3].x)/2;/*D[6].x*/ D[7].y = AF[3].y; D[8].x = AF[3].x; D[8].y = AF[3].y; gvrender_polygon(job, D, sides + 5, filled); free(D); break; } free(B); } /*=============================poly start=========================*/ /* userSize; * Return maximum size, in points, of width and height supplied * by user, if any. Return 0 otherwise. */ static double userSize(node_t * n) { double w, h; w = late_double(n, N_width, 0.0, MIN_NODEWIDTH); h = late_double(n, N_height, 0.0, MIN_NODEHEIGHT); return POINTS(MAX(w, h)); } shape_kind shapeOf(node_t * n) { shape_desc *sh = ND_shape(n); void (*ifn) (node_t *); if (!sh) return SH_UNSET; ifn = ND_shape(n)->fns->initfn; if (ifn == poly_init) return SH_POLY; else if (ifn == record_init) return SH_RECORD; else if (ifn == point_init) return SH_POINT; else if (ifn == epsf_init) return SH_EPSF; else return SH_UNSET; } boolean isPolygon(node_t * n) { return (ND_shape(n) && (ND_shape(n)->fns->initfn == poly_init)); } static void poly_init(node_t * n) { pointf dimen, min_bb, bb; point imagesize; pointf P, Q, R; pointf *vertices; char *p, *sfile, *fxd; double temp, alpha, beta, gamma; double orientation, distortion, skew; double sectorangle, sidelength, skewdist, gdistortion, gskew; double angle, sinx, cosx, xmax, ymax, scalex, scaley; double width, height, marginx, marginy, spacex; int regular, peripheries, sides; int i, j, isBox, outp; polygon_t *poly = NEW(polygon_t); boolean isPlain = IS_PLAIN(n); regular = ND_shape(n)->polygon->regular; peripheries = ND_shape(n)->polygon->peripheries; sides = ND_shape(n)->polygon->sides; orientation = ND_shape(n)->polygon->orientation; skew = ND_shape(n)->polygon->skew; distortion = ND_shape(n)->polygon->distortion; regular |= mapbool(agget(n, "regular")); /* all calculations in floating point POINTS */ /* make x and y dimensions equal if node is regular * If the user has specified either width or height, use the max. * Else use minimum default value. * If node is not regular, use the current width and height. */ if (isPlain) { width = height = 0; } else if (regular) { double sz = userSize(n); if (sz > 0.0) width = height = sz; else { width = ND_width(n); height = ND_height(n); width = height = POINTS(MIN(width, height)); } } else { width = POINTS(ND_width(n)); height = POINTS(ND_height(n)); } peripheries = late_int(n, N_peripheries, peripheries, 0); orientation += late_double(n, N_orientation, 0.0, -360.0); if (sides == 0) { /* not for builtins */ skew = late_double(n, N_skew, 0.0, -100.0); sides = late_int(n, N_sides, 4, 0); distortion = late_double(n, N_distortion, 0.0, -100.0); } /* get label dimensions */ dimen = ND_label(n)->dimen; /* minimal whitespace around label */ if ((dimen.x > 0) || (dimen.y > 0)) { /* padding */ if (!isPlain) { if ((p = agget(n, "margin"))) { marginx = marginy = 0; i = sscanf(p, "%lf,%lf", &marginx, &marginy); if (marginx < 0) marginx = 0; if (marginy < 0) marginy = 0; if (i > 0) { dimen.x += 2 * POINTS(marginx); if (i > 1) dimen.y += 2 * POINTS(marginy); else dimen.y += 2 * POINTS(marginx); } else PAD(dimen); } else PAD(dimen); } } spacex = dimen.x - ND_label(n)->dimen.x; /* quantization */ if ((temp = GD_drawing(agraphof(n))->quantum) > 0.0) { temp = POINTS(temp); dimen.x = quant(dimen.x, temp); dimen.y = quant(dimen.y, temp); } imagesize.x = imagesize.y = 0; if (ND_shape(n)->usershape) { /* custom requires a shapefile * not custom is an adaptable user shape such as a postscript * function. */ if (streq(ND_shape(n)->name, "custom")) { sfile = agget(n, "shapefile"); imagesize = gvusershape_size(agraphof(n), sfile); if ((imagesize.x == -1) && (imagesize.y == -1)) { agerr(AGWARN, "No or improper shapefile=\"%s\" for node \"%s\"\n", (sfile ? sfile : "<nil>"), agnameof(n)); imagesize.x = imagesize.y = 0; } else { GD_has_images(agraphof(n)) = TRUE; imagesize.x += 2; /* some fixed padding */ imagesize.y += 2; } } } else if ((sfile = agget(n, "image")) && (*sfile != '\0')) { imagesize = gvusershape_size(agraphof(n), sfile); if ((imagesize.x == -1) && (imagesize.y == -1)) { agerr(AGWARN, "No or improper image=\"%s\" for node \"%s\"\n", (sfile ? sfile : "<nil>"), agnameof(n)); imagesize.x = imagesize.y = 0; } else { GD_has_images(agraphof(n)) = TRUE; imagesize.x += 2; /* some fixed padding */ imagesize.y += 2; } } /* initialize node bb to labelsize */ bb.x = MAX(dimen.x, imagesize.x); bb.y = MAX(dimen.y, imagesize.y); /* I don't know how to distort or skew ellipses in postscript */ /* Convert request to a polygon with a large number of sides */ if ((sides <= 2) && ((distortion != 0.) || (skew != 0.))) { sides = 120; } /* extra sizing depends on if label is centered vertically */ p = agget(n, "labelloc"); if (p && (p[0] == 't' || p[0] == 'b')) ND_label(n)->valign = p[0]; else ND_label(n)->valign = 'c'; isBox = (sides == 4 && (ROUND(orientation) % 90) == 0 && distortion == 0. && skew == 0.); if (isBox) { /* for regular boxes the fit should be exact */ } else if (ND_shape(n)->polygon->vertices) { poly_desc_t* pd = (poly_desc_t*)ND_shape(n)->polygon->vertices; bb = pd->size_gen(bb); } else { /* for all other shapes, compute a smallest ellipse * containing bb centered on the origin, and then pad for that. * We assume the ellipse is defined by a scaling up of bb. */ temp = bb.y * SQRT2; if (height > temp && ND_label(n)->valign == 'c') { /* if there is height to spare * and the label is centered vertically * then just pad x in proportion to the spare height */ bb.x *= sqrt(1. / (1. - SQR(bb.y / height))); } else { bb.x *= SQRT2; bb.y = temp; } #if 1 if (sides > 2) { temp = cos(M_PI / sides); bb.x /= temp; bb.y /= temp; /* FIXME - for odd-sided polygons, e.g. triangles, there would be a better fit with some vertical adjustment of the shape */ } #endif } /* at this point, bb is the minimum size of node that can hold the label */ min_bb = bb; /* increase node size to width/height if needed */ fxd = late_string(n, N_fixed, "false"); if ((*fxd == 's') && streq(fxd,"shape")) { bb.x = width; bb.y = height; poly->option |= FIXEDSHAPE; } else if (mapbool(fxd)) { /* check only label, as images we can scale to fit */ if ((width < ND_label(n)->dimen.x) || (height < ND_label(n)->dimen.y)) agerr(AGWARN, "node '%s', graph '%s' size too small for label\n", agnameof(n), agnameof(agraphof(n))); bb.x = width; bb.y = height; } else { bb.x = width = MAX(width, bb.x); bb.y = height = MAX(height, bb.y); } /* If regular, make dimensions the same. * Need this to guarantee final node size is regular. */ if (regular) { width = height = bb.x = bb.y = MAX(bb.x, bb.y); } /* Compute space available for label. Provides the justification borders */ if (!mapbool(late_string(n, N_nojustify, "false"))) { if (isBox) { ND_label(n)->space.x = MAX(dimen.x,bb.x) - spacex; } else if (dimen.y < bb.y) { temp = bb.x * sqrt(1.0 - SQR(dimen.y) / SQR(bb.y)); ND_label(n)->space.x = MAX(dimen.x,temp) - spacex; } else ND_label(n)->space.x = dimen.x - spacex; } else { ND_label(n)->space.x = dimen.x - spacex; } if ((poly->option & FIXEDSHAPE) == 0) { temp = bb.y - min_bb.y; if (dimen.y < imagesize.y) temp += imagesize.y - dimen.y; ND_label(n)->space.y = dimen.y + temp; } outp = peripheries; if (peripheries < 1) outp = 1; if (sides < 3) { /* ellipses */ sides = 2; vertices = N_NEW(outp * sides, pointf); P.x = bb.x / 2.; P.y = bb.y / 2.; vertices[0].x = -P.x; vertices[0].y = -P.y; vertices[1] = P; if (peripheries > 1) { for (j = 1, i = 2; j < peripheries; j++) { P.x += GAP; P.y += GAP; vertices[i].x = -P.x; vertices[i].y = -P.y; i++; vertices[i].x = P.x; vertices[i].y = P.y; i++; } bb.x = 2. * P.x; bb.y = 2. * P.y; } } else { /* * FIXME - this code is wrong - it doesn't work for concave boundaries. * (e.g. "folder" or "promoter") * I don't think it even needs sectorangle, or knowledge of skewed shapes. * (Concepts that only work for convex regular (modulo skew/distort) polygons.) * * I think it only needs to know inside v. outside (by always drawing * boundaries clockwise, say), and the two adjacent segments. * * It needs to find the point where the two lines, parallel to * the current segments, and outside by GAP distance, intersect. */ vertices = N_NEW(outp * sides, pointf); if (ND_shape(n)->polygon->vertices) { poly_desc_t* pd = (poly_desc_t*)ND_shape(n)->polygon->vertices; pd->vertex_gen (vertices, &bb); xmax = bb.x/2; ymax = bb.y/2; } else { sectorangle = 2. * M_PI / sides; sidelength = sin(sectorangle / 2.); skewdist = hypot(fabs(distortion) + fabs(skew), 1.); gdistortion = distortion * SQRT2 / cos(sectorangle / 2.); gskew = skew / 2.; angle = (sectorangle - M_PI) / 2.; sincos(angle, &sinx, &cosx); R.x = .5 * cosx; R.y = .5 * sinx; xmax = ymax = 0.; angle += (M_PI - sectorangle) / 2.; for (i = 0; i < sides; i++) { /*next regular vertex */ angle += sectorangle; sincos(angle, &sinx, &cosx); R.x += sidelength * cosx; R.y += sidelength * sinx; /*distort and skew */ P.x = R.x * (skewdist + R.y * gdistortion) + R.y * gskew; P.y = R.y; /*orient P.x,P.y */ alpha = RADIANS(orientation) + atan2(P.y, P.x); sincos(alpha, &sinx, &cosx); P.x = P.y = hypot(P.x, P.y); P.x *= cosx; P.y *= sinx; /*scale for label */ P.x *= bb.x; P.y *= bb.y; /*find max for bounding box */ xmax = MAX(fabs(P.x), xmax); ymax = MAX(fabs(P.y), ymax); /* store result in array of points */ vertices[i] = P; if (isBox) { /* enforce exact symmetry of box */ vertices[1].x = -P.x; vertices[1].y = P.y; vertices[2].x = -P.x; vertices[2].y = -P.y; vertices[3].x = P.x; vertices[3].y = -P.y; break; } } } /* apply minimum dimensions */ xmax *= 2.; ymax *= 2.; bb.x = MAX(width, xmax); bb.y = MAX(height, ymax); scalex = bb.x / xmax; scaley = bb.y / ymax; for (i = 0; i < sides; i++) { P = vertices[i]; P.x *= scalex; P.y *= scaley; vertices[i] = P; } if (peripheries > 1) { Q = vertices[(sides - 1)]; R = vertices[0]; beta = atan2(R.y - Q.y, R.x - Q.x); for (i = 0; i < sides; i++) { /*for each vertex find the bisector */ P = Q; Q = R; R = vertices[(i + 1) % sides]; alpha = beta; beta = atan2(R.y - Q.y, R.x - Q.x); gamma = (alpha + M_PI - beta) / 2.; /*find distance along bisector to */ /*intersection of next periphery */ temp = GAP / sin(gamma); /*convert this distance to x and y */ sincos((alpha - gamma), &sinx, &cosx); sinx *= temp; cosx *= temp; /*save the vertices of all the */ /*peripheries at this base vertex */ for (j = 1; j < peripheries; j++) { Q.x += cosx; Q.y += sinx; vertices[i + j * sides] = Q; } } for (i = 0; i < sides; i++) { P = vertices[i + (peripheries - 1) * sides]; bb.x = MAX(2. * fabs(P.x), bb.x); bb.y = MAX(2. * fabs(P.y), bb.y); } } } poly->regular = regular; poly->peripheries = peripheries; poly->sides = sides; poly->orientation = orientation; poly->skew = skew; poly->distortion = distortion; poly->vertices = vertices; if (poly->option & FIXEDSHAPE) { /* set width and height to reflect label and shape */ ND_width(n) = PS2INCH(MAX(dimen.x,bb.x)); ND_height(n) = PS2INCH(MAX(dimen.y,bb.y)); } else { ND_width(n) = PS2INCH(bb.x); ND_height(n) = PS2INCH(bb.y); } ND_shape_info(n) = (void *) poly; } static void poly_free(node_t * n) { polygon_t *p = ND_shape_info(n); if (p) { free(p->vertices); free(p); } } #define GET_PORT_BOX(n,e) ((n) == (e)->head ? ED_head_port(e).bp : ED_tail_port(e).bp) /* poly_inside: * Return true if point p is inside polygonal shape of node inside_context->s.n. * Calculations are done using unrotated node shape. Thus, if p is in a rotated * coordinate system, it is reset as P in the unrotated coordinate system. Similarly, * the ND_rw, ND_lw and ND_ht values are rotated if the graph is flipped. */ static boolean poly_inside(inside_t * inside_context, pointf p) { static node_t *lastn; /* last node argument */ static polygon_t *poly; static int last, outp, sides; static pointf O; /* point (0,0) */ static pointf *vertex; static double xsize, ysize, scalex, scaley, box_URx, box_URy; int i, i1, j, s; pointf P, Q, R; boxf *bp; node_t *n; if (!inside_context) { lastn = NULL; return FALSE; } bp = inside_context->s.bp; n = inside_context->s.n; P = ccwrotatepf(p, 90 * GD_rankdir(agraphof(n))); /* Quick test if port rectangle is target */ if (bp) { boxf bbox = *bp; return INSIDE(P, bbox); } if (n != lastn) { double n_width, n_height; poly = (polygon_t *) ND_shape_info(n); vertex = poly->vertices; sides = poly->sides; if (poly->option & FIXEDSHAPE) { boxf bb = polyBB(poly); n_width = bb.UR.x - bb.LL.x; n_height = bb.UR.y - bb.LL.y; /* get point and node size adjusted for rankdir=LR */ if (GD_flip(agraphof(n))) { ysize = n_width; xsize = n_height; } else { xsize = n_width; ysize = n_height; } } else { /* get point and node size adjusted for rankdir=LR */ if (GD_flip(agraphof(n))) { ysize = ND_lw(n) + ND_rw(n); xsize = ND_ht(n); } else { xsize = ND_lw(n) + ND_rw(n); ysize = ND_ht(n); } n_width = POINTS(ND_width(n)); n_height = POINTS(ND_height(n)); } /* scale */ if (xsize == 0.0) xsize = 1.0; if (ysize == 0.0) ysize = 1.0; scalex = n_width / xsize; scaley = n_height / ysize; box_URx = n_width / 2.0; box_URy = n_height / 2.0; /* index to outer-periphery */ outp = (poly->peripheries - 1) * sides; if (outp < 0) outp = 0; lastn = n; } /* scale */ P.x *= scalex; P.y *= scaley; /* inside bounding box? */ if ((fabs(P.x) > box_URx) || (fabs(P.y) > box_URy)) return FALSE; /* ellipses */ if (sides <= 2) return (hypot(P.x / box_URx, P.y / box_URy) < 1.); /* use fast test in case we are converging on a segment */ i = last % sides; /* in case last left over from larger polygon */ i1 = (i + 1) % sides; Q = vertex[i + outp]; R = vertex[i1 + outp]; if (!(same_side(P, O, Q, R))) /* false if outside the segment's face */ return FALSE; /* else inside the segment face... */ if ((s = same_side(P, Q, R, O)) && (same_side(P, R, O, Q))) /* true if between the segment's sides */ return TRUE; /* else maybe in another segment */ for (j = 1; j < sides; j++) { /* iterate over remaining segments */ if (s) { /* clockwise */ i = i1; i1 = (i + 1) % sides; } else { /* counter clockwise */ i1 = i; i = (i + sides - 1) % sides; } if (!(same_side(P, O, vertex[i + outp], vertex[i1 + outp]))) { /* false if outside any other segment's face */ last = i; return FALSE; } } /* inside all segments' faces */ last = i; /* in case next edge is to same side */ return TRUE; } /* poly_path: * Generate box path from port to border. * Store boxes in rv and number of boxes in kptr. * side gives preferred side of bounding box for last node. * Return actual side. Returning 0 indicates nothing done. */ static int poly_path(node_t * n, port * p, int side, boxf rv[], int *kptr) { side = 0; if (ND_label(n)->html && ND_has_port(n)) { side = html_path(n, p, side, rv, kptr); } return side; } /* invflip_side: */ static int invflip_side(int side, int rankdir) { switch (rankdir) { case RANKDIR_TB: break; case RANKDIR_BT: switch (side) { case TOP: side = BOTTOM; break; case BOTTOM: side = TOP; break; default: break; } break; case RANKDIR_LR: switch (side) { case TOP: side = RIGHT; break; case BOTTOM: side = LEFT; break; case LEFT: side = TOP; break; case RIGHT: side = BOTTOM; break; } break; case RANKDIR_RL: switch (side) { case TOP: side = RIGHT; break; case BOTTOM: side = LEFT; break; case LEFT: side = BOTTOM; break; case RIGHT: side = TOP; break; } break; } return side; } /* invflip_angle: */ static double invflip_angle(double angle, int rankdir) { switch (rankdir) { case RANKDIR_TB: break; case RANKDIR_BT: angle *= -1; break; case RANKDIR_LR: angle -= M_PI * 0.5; break; case RANKDIR_RL: if (angle == M_PI) angle = -0.5 * M_PI; else if (angle == M_PI * 0.75) angle = -0.25 * M_PI; else if (angle == M_PI * 0.5) angle = 0; /* clang complains about self assignment of double else if (angle == M_PI * 0.25) angle = angle; */ else if (angle == 0) angle = M_PI * 0.5; else if (angle == M_PI * -0.25) angle = M_PI * 0.75; else if (angle == M_PI * -0.5) angle = M_PI; /* clang complains about self assignment of double else if (angle == M_PI * -0.75) angle = angle; */ break; } return angle; } /* compassPoint: * Compute compass points for non-trivial shapes. * It finds where the ray ((0,0),(x,y)) hits the boundary and * returns it. * Assumes ictxt and ictxt->n are non-NULL. * * bezier_clip uses the shape's _inside function, which assumes the input * point is in the rotated coordinate system (as determined by rankdir), so * it rotates the point counterclockwise based on rankdir to get the node's * coordinate system. * To handle this, if rankdir is set, we rotate (x,y) clockwise, and then * rotate the answer counterclockwise. */ static pointf compassPoint(inside_t * ictxt, double y, double x) { pointf curve[4]; /* bezier control points for a straight line */ node_t *n = ictxt->s.n; graph_t* g = agraphof(n); int rd = GD_rankdir(g); pointf p; p.x = x; p.y = y; if (rd) p = cwrotatepf(p, 90 * rd); curve[0].x = curve[0].y = 0; curve[1] = curve[0]; curve[3] = curve[2] = p; bezier_clip(ictxt, ND_shape(n)->fns->insidefn, curve, 1); if (rd) curve[0] = ccwrotatepf(curve[0], 90 * rd); return curve[0]; } /* compassPort: * Attach a compass point to a port pp, and fill in remaining fields. * n is the corresponding node; bp is the bounding box of the port. * compass is the compass point * Return 1 if unrecognized compass point, in which case we * use the center. * * This function also finishes initializing the port structure, * even if no compass point is involved. * The sides value gives the set of sides shared by the port. This * is used with a compass point to indicate if the port is exposed, to * set the port's side value. * * If ictxt is NULL, we are working with a simple rectangular shape (node or * port of record of HTML label), so compass points are trivial. If ictxt is * not NULL, it provides shape information so that the compass point can be * calculated based on the shape. * * The code assumes the node has its unrotated shape to find the points, * angles, etc. At the end, the parameters are adjusted to take into account * the rankdir attribute. In particular, the first if-else statement flips * the already adjusted ND_ht, ND_lw and ND_rw back to non-flipped values. * */ static int compassPort(node_t * n, boxf * bp, port * pp, char *compass, int sides, inside_t * ictxt) { boxf b; pointf p, ctr; int rv = 0; double theta = 0.0; boolean constrain = FALSE; boolean dyna = FALSE; int side = 0; boolean clip = TRUE; boolean defined; double maxv; /* sufficiently large value outside of range of node */ if (bp) { b = *bp; p = pointfof((b.LL.x + b.UR.x) / 2, (b.LL.y + b.UR.y) / 2); defined = TRUE; } else { p.x = p.y = 0.; if (GD_flip(agraphof(n))) { b.UR.x = ND_ht(n) / 2.; b.LL.x = -b.UR.x; b.UR.y = ND_lw(n); b.LL.y = -b.UR.y; } else { b.UR.y = ND_ht(n) / 2.; b.LL.y = -b.UR.y; b.UR.x = ND_lw(n); b.LL.x = -b.UR.x; } defined = FALSE; } maxv = MAX(b.UR.x,b.UR.y); maxv *= 4.0; ctr = p; if (compass && *compass) { switch (*compass++) { case 'e': if (*compass) rv = 1; else { if (ictxt) p = compassPoint(ictxt, ctr.y, maxv); else p.x = b.UR.x; theta = 0.0; constrain = TRUE; defined = TRUE; clip = FALSE; side = sides & RIGHT; } break; case 's': p.y = b.LL.y; constrain = TRUE; clip = FALSE; switch (*compass) { case '\0': theta = -M_PI * 0.5; defined = TRUE; if (ictxt) p = compassPoint(ictxt, -maxv, ctr.x); else p.x = ctr.x; side = sides & BOTTOM; break; case 'e': theta = -M_PI * 0.25; defined = TRUE; if (ictxt) p = compassPoint(ictxt, -maxv, maxv); else p.x = b.UR.x; side = sides & (BOTTOM | RIGHT); break; case 'w': theta = -M_PI * 0.75; defined = TRUE; if (ictxt) p = compassPoint(ictxt, -maxv, -maxv); else p.x = b.LL.x; side = sides & (BOTTOM | LEFT); break; default: p.y = ctr.y; constrain = FALSE; clip = TRUE; rv = 1; break; } break; case 'w': if (*compass) rv = 1; else { if (ictxt) p = compassPoint(ictxt, ctr.y, -maxv); else p.x = b.LL.x; theta = M_PI; constrain = TRUE; defined = TRUE; clip = FALSE; side = sides & LEFT; } break; case 'n': p.y = b.UR.y; constrain = TRUE; clip = FALSE; switch (*compass) { case '\0': defined = TRUE; theta = M_PI * 0.5; if (ictxt) p = compassPoint(ictxt, maxv, ctr.x); else p.x = ctr.x; side = sides & TOP; break; case 'e': defined = TRUE; theta = M_PI * 0.25; if (ictxt) p = compassPoint(ictxt, maxv, maxv); else p.x = b.UR.x; side = sides & (TOP | RIGHT); break; case 'w': defined = TRUE; theta = M_PI * 0.75; if (ictxt) p = compassPoint(ictxt, maxv, -maxv); else p.x = b.LL.x; side = sides & (TOP | LEFT); break; default: p.y = ctr.y; constrain = FALSE; clip = TRUE; rv = 1; break; } break; case '_': dyna = TRUE; side = sides; break; case 'c': break; default: rv = 1; break; } } p = cwrotatepf(p, 90 * GD_rankdir(agraphof(n))); if (dyna) pp->side = side; else pp->side = invflip_side(side, GD_rankdir(agraphof(n))); pp->bp = bp; PF2P(p, pp->p); pp->theta = invflip_angle(theta, GD_rankdir(agraphof(n))); if ((p.x == 0) && (p.y == 0)) pp->order = MC_SCALE / 2; else { /* compute angle with 0 at north pole, increasing CCW */ double angle = atan2(p.y, p.x) + 1.5 * M_PI; if (angle >= 2 * M_PI) angle -= 2 * M_PI; pp->order = (int) ((MC_SCALE * angle) / (2 * M_PI)); } pp->constrained = constrain; pp->defined = defined; pp->clip = clip; pp->dyna = dyna; return rv; } static port poly_port(node_t * n, char *portname, char *compass) { port rv; boxf *bp; int sides; /* bitmap of which sides the port lies along */ if (portname[0] == '\0') return Center; if (compass == NULL) compass = "_"; sides = BOTTOM | RIGHT | TOP | LEFT; if ((ND_label(n)->html) && (bp = html_port(n, portname, &sides))) { if (compassPort(n, bp, &rv, compass, sides, NULL)) { agerr(AGWARN, "node %s, port %s, unrecognized compass point '%s' - ignored\n", agnameof(n), portname, compass); } } else { inside_t *ictxtp; inside_t ictxt; if (IS_BOX(n)) ictxtp = NULL; else { ictxt.s.n = n; ictxt.s.bp = NULL; ictxtp = &ictxt; } if (compassPort(n, NULL, &rv, portname, sides, ictxtp)) unrecognized(n, portname); } rv.name = NULL; return rv; } #define multicolor(f) (strchr(f,':')) /* generic polygon gencode routine */ static void poly_gencode(GVJ_t * job, node_t * n) { obj_state_t *obj = job->obj; polygon_t *poly; double xsize, ysize; int i, j, peripheries, sides, style; pointf P, *vertices; static pointf *AF; static int A_size; boolean filled; boolean usershape_p; boolean pfilled; /* true if fill not handled by user shape */ char *color, *name; int doMap = (obj->url || obj->explicit_tooltip); char* fillcolor=NULL; char* pencolor=NULL; char* clrs[2]; if (doMap && !(job->flags & EMIT_CLUSTERS_LAST)) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); poly = (polygon_t *) ND_shape_info(n); vertices = poly->vertices; sides = poly->sides; peripheries = poly->peripheries; if (A_size < sides) { A_size = sides + 5; AF = ALLOC(A_size, AF, pointf); } /* nominal label position in the center of the node */ ND_label(n)->pos = ND_coord(n); xsize = (ND_lw(n) + ND_rw(n)) / POINTS(ND_width(n)); ysize = ND_ht(n) / POINTS(ND_height(n)); style = stylenode(job, n); clrs[0] = NULL; if (ND_gui_state(n) & GUI_STATE_ACTIVE) { pencolor = late_nnstring(n, N_activepencolor, DEFAULT_ACTIVEPENCOLOR); gvrender_set_pencolor(job, pencolor); color = late_nnstring(n, N_activefillcolor, DEFAULT_ACTIVEFILLCOLOR); gvrender_set_fillcolor(job, color); filled = FILL; } else if (ND_gui_state(n) & GUI_STATE_SELECTED) { pencolor = late_nnstring(n, N_selectedpencolor, DEFAULT_SELECTEDPENCOLOR); gvrender_set_pencolor(job, pencolor); color = late_nnstring(n, N_selectedfillcolor, DEFAULT_SELECTEDFILLCOLOR); gvrender_set_fillcolor(job, color); filled = FILL; } else if (ND_gui_state(n) & GUI_STATE_DELETED) { pencolor = late_nnstring(n, N_deletedpencolor, DEFAULT_DELETEDPENCOLOR); gvrender_set_pencolor(job, pencolor); color = late_nnstring(n, N_deletedfillcolor, DEFAULT_DELETEDFILLCOLOR); gvrender_set_fillcolor(job, color); filled = FILL; } else if (ND_gui_state(n) & GUI_STATE_VISITED) { pencolor = late_nnstring(n, N_visitedpencolor, DEFAULT_VISITEDPENCOLOR); gvrender_set_pencolor(job, pencolor); color = late_nnstring(n, N_visitedfillcolor, DEFAULT_VISITEDFILLCOLOR); gvrender_set_fillcolor(job, color); filled = FILL; } else { if (style & FILLED) { float frac; fillcolor = findFill (n); if (findStopColor (fillcolor, clrs, &frac)) { gvrender_set_fillcolor(job, clrs[0]); if (clrs[1]) gvrender_set_gradient_vals(job,clrs[1],late_int(n,N_gradientangle,0,0), frac); else gvrender_set_gradient_vals(job,DEFAULT_COLOR,late_int(n,N_gradientangle,0,0), frac); if (style & RADIAL) filled = RGRADIENT; else filled = GRADIENT; } else { gvrender_set_fillcolor(job, fillcolor); filled = FILL; } } else if (style & (STRIPED|WEDGED)) { fillcolor = findFill (n); /* gvrender_set_fillcolor(job, fillcolor); */ filled = TRUE; } else { filled = FALSE; } pencolor = penColor(job, n); /* emit pen color */ } pfilled = !ND_shape(n)->usershape || streq(ND_shape(n)->name, "custom"); /* if no boundary but filled, set boundary color to transparent */ if ((peripheries == 0) && filled && pfilled) { peripheries = 1; gvrender_set_pencolor(job, "transparent"); } /* draw peripheries first */ for (j = 0; j < peripheries; j++) { for (i = 0; i < sides; i++) { P = vertices[i + j * sides]; AF[i].x = P.x * xsize + ND_coord(n).x; AF[i].y = P.y * ysize + ND_coord(n).y; } if (sides <= 2) { if ((style & WEDGED) && (j == 0) && multicolor(fillcolor)) { int rv = wedgedEllipse (job, AF, fillcolor); if (rv > 1) agerr (AGPREV, "in node %s\n", agnameof(n)); filled = 0; } gvrender_ellipse(job, AF, sides, filled); if (style & DIAGONALS) { Mcircle_hack(job, n); } } else if (style & STRIPED) { if (j == 0) { int rv = stripedBox (job, AF, fillcolor, 1); if (rv > 1) agerr (AGPREV, "in node %s\n", agnameof(n)); } gvrender_polygon(job, AF, sides, 0); } else if (style & UNDERLINE) { gvrender_set_pencolor(job, "transparent"); gvrender_polygon(job, AF, sides, filled); gvrender_set_pencolor(job, pencolor); gvrender_polyline(job, AF+2, 2); } else if (SPECIAL_CORNERS(style)) { round_corners(job, AF, sides, style, filled); } else { gvrender_polygon(job, AF, sides, filled); } /* fill innermost periphery only */ filled = FALSE; } usershape_p = FALSE; if (ND_shape(n)->usershape) { name = ND_shape(n)->name; if (streq(name, "custom")) { if ((name = agget(n, "shapefile")) && name[0]) usershape_p = TRUE; } else usershape_p = TRUE; } else if ((name = agget(n, "image")) && name[0]) { usershape_p = TRUE; } if (usershape_p) { /* get coords of innermost periphery */ for (i = 0; i < sides; i++) { P = vertices[i]; AF[i].x = P.x * xsize + ND_coord(n).x; AF[i].y = P.y * ysize + ND_coord(n).y; } /* lay down fill first */ if (filled && pfilled) { if (sides <= 2) { if ((style & WEDGED) && (j == 0) && multicolor(fillcolor)) { int rv = wedgedEllipse (job, AF, fillcolor); if (rv > 1) agerr (AGPREV, "in node %s\n", agnameof(n)); filled = 0; } gvrender_ellipse(job, AF, sides, filled); if (style & DIAGONALS) { Mcircle_hack(job, n); } } else if (style & STRIPED) { int rv = stripedBox (job, AF, fillcolor, 1); if (rv > 1) agerr (AGPREV, "in node %s\n", agnameof(n)); gvrender_polygon(job, AF, sides, 0); } else if (style & (ROUNDED | DIAGONALS)) { round_corners(job, AF, sides, style, filled); } else { gvrender_polygon(job, AF, sides, filled); } } gvrender_usershape(job, name, AF, sides, filled, late_string(n, N_imagescale, "false")); filled = FALSE; /* with user shapes, we have done the fill if needed */ } free (clrs[0]); emit_label(job, EMIT_NLABEL, ND_label(n)); if (doMap) { if (job->flags & EMIT_CLUSTERS_LAST) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); gvrender_end_anchor(job); } } /*=======================end poly======================================*/ /*===============================point start========================*/ /* point_init: * shorthand for shape=circle, style=filled, width=0.05, label="" */ static void point_init(node_t * n) { polygon_t *poly = NEW(polygon_t); int sides, outp, peripheries = ND_shape(n)->polygon->peripheries; double sz; pointf P, *vertices; int i, j; double w, h; /* set width and height, and make them equal * if user has set weight or height, use it. * if both are set, use smallest. * if neither, use default */ w = late_double(n, N_width, MAXDOUBLE, 0.0); h = late_double(n, N_height, MAXDOUBLE, 0.0); w = MIN(w, h); if ((w == MAXDOUBLE) && (h == MAXDOUBLE)) /* neither defined */ ND_width(n) = ND_height(n) = DEF_POINT; else { w = MIN(w, h); /* If w == 0, use it; otherwise, make w no less than MIN_POINT due * to the restrictions mentioned above. */ if (w > 0.0) w = MAX(w,MIN_POINT); ND_width(n) = ND_height(n) = w; } sz = ND_width(n) * POINTS_PER_INCH; peripheries = late_int(n, N_peripheries, peripheries, 0); if (peripheries < 1) outp = 1; else outp = peripheries; sides = 2; vertices = N_NEW(outp * sides, pointf); P.y = P.x = sz / 2.; vertices[0].x = -P.x; vertices[0].y = -P.y; vertices[1] = P; if (peripheries > 1) { for (j = 1, i = 2; j < peripheries; j++) { P.x += GAP; P.y += GAP; vertices[i].x = -P.x; vertices[i].y = -P.y; i++; vertices[i].x = P.x; vertices[i].y = P.y; i++; } sz = 2. * P.x; } poly->regular = 1; poly->peripheries = peripheries; poly->sides = 2; poly->orientation = 0; poly->skew = 0; poly->distortion = 0; poly->vertices = vertices; ND_height(n) = ND_width(n) = PS2INCH(sz); ND_shape_info(n) = (void *) poly; } static boolean point_inside(inside_t * inside_context, pointf p) { static node_t *lastn; /* last node argument */ static double radius; pointf P; node_t *n; if (!inside_context) { lastn = NULL; return FALSE; } n = inside_context->s.n; P = ccwrotatepf(p, 90 * GD_rankdir(agraphof(n))); if (n != lastn) { int outp; polygon_t *poly = (polygon_t *) ND_shape_info(n); /* index to outer-periphery */ outp = 2 * (poly->peripheries - 1); if (outp < 0) outp = 0; radius = poly->vertices[outp + 1].x; lastn = n; } /* inside bounding box? */ if ((fabs(P.x) > radius) || (fabs(P.y) > radius)) return FALSE; return (hypot(P.x, P.y) <= radius); } static void point_gencode(GVJ_t * job, node_t * n) { obj_state_t *obj = job->obj; polygon_t *poly; int i, j, sides, peripheries, style; pointf P, *vertices; static pointf *AF; static int A_size; boolean filled; char *color; int doMap = (obj->url || obj->explicit_tooltip); if (doMap && !(job->flags & EMIT_CLUSTERS_LAST)) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); poly = (polygon_t *) ND_shape_info(n); vertices = poly->vertices; sides = poly->sides; peripheries = poly->peripheries; if (A_size < sides) { A_size = sides + 2; AF = ALLOC(A_size, AF, pointf); } checkStyle(n, &style); if (style & INVISIBLE) gvrender_set_style(job, point_style); else gvrender_set_style(job, &point_style[1]); if (N_penwidth) gvrender_set_penwidth(job, late_double(n, N_penwidth, 1.0, 0.0)); if (ND_gui_state(n) & GUI_STATE_ACTIVE) { color = late_nnstring(n, N_activepencolor, DEFAULT_ACTIVEPENCOLOR); gvrender_set_pencolor(job, color); color = late_nnstring(n, N_activefillcolor, DEFAULT_ACTIVEFILLCOLOR); gvrender_set_fillcolor(job, color); } else if (ND_gui_state(n) & GUI_STATE_SELECTED) { color = late_nnstring(n, N_selectedpencolor, DEFAULT_SELECTEDPENCOLOR); gvrender_set_pencolor(job, color); color = late_nnstring(n, N_selectedfillcolor, DEFAULT_SELECTEDFILLCOLOR); gvrender_set_fillcolor(job, color); } else if (ND_gui_state(n) & GUI_STATE_DELETED) { color = late_nnstring(n, N_deletedpencolor, DEFAULT_DELETEDPENCOLOR); gvrender_set_pencolor(job, color); color = late_nnstring(n, N_deletedfillcolor, DEFAULT_DELETEDFILLCOLOR); gvrender_set_fillcolor(job, color); } else if (ND_gui_state(n) & GUI_STATE_VISITED) { color = late_nnstring(n, N_visitedpencolor, DEFAULT_VISITEDPENCOLOR); gvrender_set_pencolor(job, color); color = late_nnstring(n, N_visitedfillcolor, DEFAULT_VISITEDFILLCOLOR); gvrender_set_fillcolor(job, color); } else { color = findFillDflt(n, "black"); gvrender_set_fillcolor(job, color); /* emit fill color */ penColor(job, n); /* emit pen color */ } filled = TRUE; /* if no boundary but filled, set boundary color to fill color */ if (peripheries == 0) { peripheries = 1; if (color[0]) gvrender_set_pencolor(job, color); } for (j = 0; j < peripheries; j++) { for (i = 0; i < sides; i++) { P = vertices[i + j * sides]; AF[i].x = P.x + ND_coord(n).x; AF[i].y = P.y + ND_coord(n).y; } gvrender_ellipse(job, AF, sides, filled); /* fill innermost periphery only */ filled = FALSE; } if (doMap) { if (job->flags & EMIT_CLUSTERS_LAST) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); gvrender_end_anchor(job); } } /* the "record" shape is a rudimentary table formatter */ #define HASTEXT 1 #define HASPORT 2 #define HASTABLE 4 #define INTEXT 8 #define INPORT 16 #define ISCTRL(c) ((c) == '{' || (c) == '}' || (c) == '|' || (c) == '<' || (c) == '>') static char *reclblp; static void free_field(field_t * f) { int i; for (i = 0; i < f->n_flds; i++) { free_field(f->fld[i]); } free(f->id); free_label(f->lp); free(f->fld); free(f); } /* parse_error: * Clean up memory allocated in parse_reclbl, then return NULL */ static field_t *parse_error(field_t * rv, char *port) { free_field(rv); if (port) free(port); return NULL; } static field_t *parse_reclbl(node_t * n, int LR, int flag, char *text) { field_t *fp, *rv = NEW(field_t); char *tsp, *psp=NULL, *hstsp, *hspsp=NULL, *sp; char *tmpport = NULL; int maxf, cnt, mode, wflag, ishardspace, fi; textlabel_t *lbl = ND_label(n); unsigned char uc; fp = NULL; for (maxf = 1, cnt = 0, sp = reclblp; *sp; sp++) { if (*sp == '\\') { sp++; if (*sp && (*sp == '{' || *sp == '}' || *sp == '|' || *sp == '\\')) continue; } if (*sp == '{') cnt++; else if (*sp == '}') cnt--; else if (*sp == '|' && cnt == 0) maxf++; if (cnt < 0) break; } rv->fld = N_NEW(maxf, field_t *); rv->LR = LR; mode = 0; fi = 0; hstsp = tsp = text; wflag = TRUE; ishardspace = FALSE; while (wflag) { if ((uc = *(unsigned char*)reclblp) && (uc < ' ')) { /* Ignore non-0 control characters */ reclblp++; continue; } switch (*reclblp) { case '<': if (mode & (HASTABLE | HASPORT)) return parse_error(rv, tmpport); if (lbl->html) goto dotext; mode |= (HASPORT | INPORT); reclblp++; hspsp = psp = text; break; case '>': if (lbl->html) goto dotext; if (!(mode & INPORT)) return parse_error(rv, tmpport); if (psp > text + 1 && psp - 1 != hspsp && *(psp - 1) == ' ') psp--; *psp = '\000'; tmpport = strdup(text); mode &= ~INPORT; reclblp++; break; case '{': reclblp++; if (mode != 0 || !*reclblp) return parse_error(rv, tmpport); mode = HASTABLE; if (!(rv->fld[fi++] = parse_reclbl(n, NOT(LR), FALSE, text))) return parse_error(rv, tmpport); break; case '}': case '|': case '\000': if ((!*reclblp && !flag) || (mode & INPORT)) return parse_error(rv, tmpport); if (!(mode & HASTABLE)) fp = rv->fld[fi++] = NEW(field_t); if (tmpport) { fp->id = tmpport; tmpport = NULL; } if (!(mode & (HASTEXT | HASTABLE))) mode |= HASTEXT, *tsp++ = ' '; if (mode & HASTEXT) { if (tsp > text + 1 && tsp - 1 != hstsp && *(tsp - 1) == ' ') tsp--; *tsp = '\000'; fp->lp = make_label((void *) n, strdup(text), (lbl->html ? LT_HTML : LT_NONE), lbl->fontsize, lbl->fontname, lbl->fontcolor); fp->LR = TRUE; hstsp = tsp = text; } if (*reclblp) { if (*reclblp == '}') { reclblp++; rv->n_flds = fi; return rv; } mode = 0; reclblp++; } else wflag = FALSE; break; case '\\': if (*(reclblp + 1)) { if (ISCTRL(*(reclblp + 1))) reclblp++; else if ((*(reclblp + 1) == ' ') && !lbl->html) ishardspace = TRUE, reclblp++; else { *tsp++ = '\\'; mode |= (INTEXT | HASTEXT); reclblp++; } } /* falling through ... */ default: dotext: if ((mode & HASTABLE) && *reclblp != ' ') return parse_error(rv, tmpport); if (!(mode & (INTEXT | INPORT)) && *reclblp != ' ') mode |= (INTEXT | HASTEXT); if (mode & INTEXT) { if (! (*reclblp == ' ' && !ishardspace && *(tsp - 1) == ' ' && !lbl->html)) *tsp++ = *reclblp; if (ishardspace) hstsp = tsp - 1; } else if (mode & INPORT) { if (!(*reclblp == ' ' && !ishardspace && (psp == text || *(psp - 1) == ' '))) *psp++ = *reclblp; if (ishardspace) hspsp = psp - 1; } reclblp++; while (*reclblp & 128) *tsp++ = *reclblp++; break; } } rv->n_flds = fi; return rv; } static pointf size_reclbl(node_t * n, field_t * f) { int i; char *p; double marginx, marginy; pointf d, d0; pointf dimen; if (f->lp) { dimen = f->lp->dimen; /* minimal whitespace around label */ if ((dimen.x > 0.0) || (dimen.y > 0.0)) { /* padding */ if ((p = agget(n, "margin"))) { i = sscanf(p, "%lf,%lf", &marginx, &marginy); if (i > 0) { dimen.x += 2 * POINTS(marginx); if (i > 1) dimen.y += 2 * POINTS(marginy); else dimen.y += 2 * POINTS(marginx); } else PAD(dimen); } else PAD(dimen); } d = dimen; } else { d.x = d.y = 0; for (i = 0; i < f->n_flds; i++) { d0 = size_reclbl(n, f->fld[i]); if (f->LR) { d.x += d0.x; d.y = MAX(d.y, d0.y); } else { d.y += d0.y; d.x = MAX(d.x, d0.x); } } } f->size = d; return d; } static void resize_reclbl(field_t * f, pointf sz, int nojustify_p) { int i, amt; double inc; pointf d; pointf newsz; field_t *sf; /* adjust field */ d.x = sz.x - f->size.x; d.y = sz.y - f->size.y; f->size = sz; /* adjust text area */ if (f->lp && !nojustify_p) { f->lp->space.x += d.x; f->lp->space.y += d.y; } /* adjust children */ if (f->n_flds) { if (f->LR) inc = d.x / f->n_flds; else inc = d.y / f->n_flds; for (i = 0; i < f->n_flds; i++) { sf = f->fld[i]; amt = ((int) ((i + 1) * inc)) - ((int) (i * inc)); if (f->LR) newsz = pointfof(sf->size.x + amt, sz.y); else newsz = pointfof(sz.x, sf->size.y + amt); resize_reclbl(sf, newsz, nojustify_p); } } } /* pos_reclbl: * Assign position info for each field. Also, set * the sides attribute, which indicates which sides of the * record are accessible to the field. */ static void pos_reclbl(field_t * f, pointf ul, int sides) { int i, last, mask; f->sides = sides; f->b.LL = pointfof(ul.x, ul.y - f->size.y); f->b.UR = pointfof(ul.x + f->size.x, ul.y); last = f->n_flds - 1; for (i = 0; i <= last; i++) { if (sides) { if (f->LR) { if (i == 0) { if (i == last) mask = TOP | BOTTOM | RIGHT | LEFT; else mask = TOP | BOTTOM | LEFT; } else if (i == last) mask = TOP | BOTTOM | RIGHT; else mask = TOP | BOTTOM; } else { if (i == 0) { if (i == last) mask = TOP | BOTTOM | RIGHT | LEFT; else mask = TOP | RIGHT | LEFT; } else if (i == last) mask = LEFT | BOTTOM | RIGHT; else mask = LEFT | RIGHT; } } else mask = 0; pos_reclbl(f->fld[i], ul, sides & mask); if (f->LR) ul.x = ul.x + f->fld[i]->size.x; else ul.y = ul.y - f->fld[i]->size.y; } } #if DEBUG > 1 static void indent(int l) { int i; for (i = 0; i < l; i++) fputs(" ", stderr); } static void prbox(boxf b) { fprintf(stderr, "((%.5g,%.5g),(%.5g,%.5g))\n", b.LL.x, b.LL.y, b.UR.x, b.UR.y); } static void dumpL(field_t * info, int level) { int i; indent(level); if (info->n_flds == 0) { fprintf(stderr, "Label \"%s\" ", info->lp->text); prbox(info->b); } else { fprintf(stderr, "Tbl "); prbox(info->b); for (i = 0; i < info->n_flds; i++) { dumpL(info->fld[i], level + 1); } } } #endif /* syntax of labels: foo|bar|baz or foo|(recursive|label)|baz */ static void record_init(node_t * n) { field_t *info; pointf ul, sz; int flip, len; char *textbuf; /* temp buffer for storing labels */ int sides = BOTTOM | RIGHT | TOP | LEFT; /* Always use rankdir to determine how records are laid out */ flip = NOT(GD_realflip(agraphof(n))); reclblp = ND_label(n)->text; len = strlen(reclblp); /* For some forgotten reason, an empty label is parsed into a space, so * we need at least two bytes in textbuf. */ len = MAX(len, 1); textbuf = N_NEW(len + 1, char); if (!(info = parse_reclbl(n, flip, TRUE, textbuf))) { agerr(AGERR, "bad label format %s\n", ND_label(n)->text); reclblp = "\\N"; info = parse_reclbl(n, flip, TRUE, textbuf); } free(textbuf); size_reclbl(n, info); sz.x = POINTS(ND_width(n)); sz.y = POINTS(ND_height(n)); if (mapbool(late_string(n, N_fixed, "false"))) { if ((sz.x < info->size.x) || (sz.y < info->size.y)) { /* should check that the record really won't fit, e.g., there may be no text. agerr(AGWARN, "node '%s' size may be too small\n", agnameof(n)); */ } } else { sz.x = MAX(info->size.x, sz.x); sz.y = MAX(info->size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, N_nojustify, "false"))); ul = pointfof(-sz.x / 2., sz.y / 2.); /* FIXME - is this still true: suspected to introduce ronding error - see Kluge below */ pos_reclbl(info, ul, sides); ND_width(n) = PS2INCH(info->size.x); ND_height(n) = PS2INCH(info->size.y + 1); /* Kluge!! +1 to fix rounding diff between layout and rendering otherwise we can get -1 coords in output */ ND_shape_info(n) = (void *) info; } static void record_free(node_t * n) { field_t *p = ND_shape_info(n); free_field(p); } static field_t *map_rec_port(field_t * f, char *str) { field_t *rv; int sub; if (f->id && (streq(f->id, str))) rv = f; else { rv = NULL; for (sub = 0; sub < f->n_flds; sub++) if ((rv = map_rec_port(f->fld[sub], str))) break; } return rv; } static port record_port(node_t * n, char *portname, char *compass) { field_t *f; field_t *subf; port rv; int sides; /* bitmap of which sides the port lies along */ if (portname[0] == '\0') return Center; sides = BOTTOM | RIGHT | TOP | LEFT; if (compass == NULL) compass = "_"; f = (field_t *) ND_shape_info(n); if ((subf = map_rec_port(f, portname))) { if (compassPort(n, &subf->b, &rv, compass, subf->sides, NULL)) { agerr(AGWARN, "node %s, port %s, unrecognized compass point '%s' - ignored\n", agnameof(n), portname, compass); } } else if (compassPort(n, &f->b, &rv, portname, sides, NULL)) { unrecognized(n, portname); } return rv; } /* record_inside: * Note that this does not handle Mrecords correctly. It assumes * everything is a rectangle. */ static boolean record_inside(inside_t * inside_context, pointf p) { field_t *fld0; boxf *bp = inside_context->s.bp; node_t *n = inside_context->s.n; boxf bbox; /* convert point to node coordinate system */ p = ccwrotatepf(p, 90 * GD_rankdir(agraphof(n))); if (bp == NULL) { fld0 = (field_t *) ND_shape_info(n); bbox = fld0->b; } else bbox = *bp; return INSIDE(p, bbox); } /* record_path: * Generate box path from port to border. * See poly_path for constraints. */ static int record_path(node_t * n, port * prt, int side, boxf rv[], int *kptr) { int i, ls, rs; pointf p; field_t *info; if (!prt->defined) return 0; p = prt->p; info = (field_t *) ND_shape_info(n); for (i = 0; i < info->n_flds; i++) { if (!GD_flip(agraphof(n))) { ls = info->fld[i]->b.LL.x; rs = info->fld[i]->b.UR.x; } else { ls = info->fld[i]->b.LL.y; rs = info->fld[i]->b.UR.y; } if (BETWEEN(ls, p.x, rs)) { /* FIXME: I don't understand this code */ if (GD_flip(agraphof(n))) { rv[0] = flip_rec_boxf(info->fld[i]->b, ND_coord(n)); } else { rv[0].LL.x = ND_coord(n).x + ls; rv[0].LL.y = ND_coord(n).y - (ND_ht(n) / 2); rv[0].UR.x = ND_coord(n).x + rs; } rv[0].UR.y = ND_coord(n).y + (ND_ht(n) / 2); *kptr = 1; break; } } return side; } static void gen_fields(GVJ_t * job, node_t * n, field_t * f) { int i; pointf AF[2], coord; if (f->lp) { f->lp->pos = add_pointf(mid_pointf(f->b.LL, f->b.UR), ND_coord(n)); emit_label(job, EMIT_NLABEL, f->lp); penColor(job, n); } coord = ND_coord(n); for (i = 0; i < f->n_flds; i++) { if (i > 0) { if (f->LR) { AF[0] = f->fld[i]->b.LL; AF[1].x = AF[0].x; AF[1].y = f->fld[i]->b.UR.y; } else { AF[1] = f->fld[i]->b.UR; AF[0].x = f->fld[i]->b.LL.x; AF[0].y = AF[1].y; } AF[0] = add_pointf(AF[0], coord); AF[1] = add_pointf(AF[1], coord); gvrender_polyline(job, AF, 2); } gen_fields(job, n, f->fld[i]); } } static void record_gencode(GVJ_t * job, node_t * n) { obj_state_t *obj = job->obj; boxf BF; pointf AF[4]; int style; field_t *f; int doMap = (obj->url || obj->explicit_tooltip); int filled; char* clrs[2]; f = (field_t *) ND_shape_info(n); BF = f->b; BF.LL.x += ND_coord(n).x; BF.LL.y += ND_coord(n).y; BF.UR.x += ND_coord(n).x; BF.UR.y += ND_coord(n).y; if (doMap && !(job->flags & EMIT_CLUSTERS_LAST)) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); style = stylenode(job, n); penColor(job, n); clrs[0] = NULL; if (style & FILLED) { char* fillcolor = findFill (n); float frac; if (findStopColor (fillcolor, clrs, &frac)) { gvrender_set_fillcolor(job, clrs[0]); if (clrs[1]) gvrender_set_gradient_vals(job,clrs[1],late_int(n,N_gradientangle,0,0), frac); else gvrender_set_gradient_vals(job,DEFAULT_COLOR,late_int(n,N_gradientangle,0,0), frac); if (style & RADIAL) filled = RGRADIENT; else filled = GRADIENT; } else { filled = FILL; gvrender_set_fillcolor(job, fillcolor); } } else filled = FALSE; if (streq(ND_shape(n)->name, "Mrecord")) style |= ROUNDED; if (SPECIAL_CORNERS(style)) { AF[0] = BF.LL; AF[2] = BF.UR; AF[1].x = AF[2].x; AF[1].y = AF[0].y; AF[3].x = AF[0].x; AF[3].y = AF[2].y; round_corners(job, AF, 4, style, filled); } else { gvrender_box(job, BF, filled); } gen_fields(job, n, f); if (clrs[0]) free (clrs[0]); if (doMap) { if (job->flags & EMIT_CLUSTERS_LAST) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); gvrender_end_anchor(job); } } static shape_desc **UserShape; static int N_UserShape; shape_desc *find_user_shape(const char *name) { int i; if (UserShape) { for (i = 0; i < N_UserShape; i++) { if (streq(UserShape[i]->name, name)) return UserShape[i]; } } return NULL; } static shape_desc *user_shape(char *name) { int i; shape_desc *p; if ((p = find_user_shape(name))) return p; i = N_UserShape++; UserShape = ALLOC(N_UserShape, UserShape, shape_desc *); p = UserShape[i] = NEW(shape_desc); *p = Shapes[0]; p->name = strdup(name); if (Lib == NULL && !streq(name, "custom")) { agerr(AGWARN, "using %s for unknown shape %s\n", Shapes[0].name, p->name); p->usershape = FALSE; } else { p->usershape = TRUE; } return p; } shape_desc *bind_shape(char *name, node_t * np) { shape_desc *ptr, *rv = NULL; const char *str; str = safefile(agget(np, "shapefile")); /* If shapefile is defined and not epsf, set shape = custom */ if (str && !streq(name, "epsf")) name = "custom"; if (!streq(name, "custom")) { for (ptr = Shapes; ptr->name; ptr++) { if (streq(ptr->name, name)) { rv = ptr; break; } } } if (rv == NULL) rv = user_shape(name); return rv; } static boolean epsf_inside(inside_t * inside_context, pointf p) { pointf P; double x2; node_t *n = inside_context->s.n; P = ccwrotatepf(p, 90 * GD_rankdir(agraphof(n))); x2 = ND_ht(n) / 2; return ((P.y >= -x2) && (P.y <= x2) && (P.x >= -ND_lw(n)) && (P.x <= ND_rw(n))); } static void epsf_gencode(GVJ_t * job, node_t * n) { obj_state_t *obj = job->obj; epsf_t *desc; int doMap = (obj->url || obj->explicit_tooltip); desc = (epsf_t *) (ND_shape_info(n)); if (!desc) return; if (doMap && !(job->flags & EMIT_CLUSTERS_LAST)) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); if (desc) fprintf(job->output_file, "%.5g %.5g translate newpath user_shape_%d\n", ND_coord(n).x + desc->offset.x, ND_coord(n).y + desc->offset.y, desc->macro_id); ND_label(n)->pos = ND_coord(n); emit_label(job, EMIT_NLABEL, ND_label(n)); if (doMap) { if (job->flags & EMIT_CLUSTERS_LAST) gvrender_begin_anchor(job, obj->url, obj->tooltip, obj->target, obj->id); gvrender_end_anchor(job); } } #define alpha (M_PI/10.0) #define alpha2 (2*alpha) #define alpha3 (3*alpha) #define alpha4 (2*alpha2) static pointf star_size (pointf sz0) { pointf sz; double r0, r, rx, ry; rx = sz0.x/(2*cos(alpha)); ry = sz0.y/(sin(alpha) + sin(alpha3)); r0 = MAX(rx,ry); r = (r0*sin(alpha4)*cos(alpha2))/(cos(alpha)*cos(alpha4)); sz.x = 2*r*cos(alpha); sz.y = r*(1 + sin(alpha3)); return sz; } static void star_vertices (pointf* vertices, pointf* bb) { int i; pointf sz = *bb; double offset, a, aspect = (1 + sin(alpha3))/(2*cos(alpha)); double r, r0, theta = alpha; /* Scale up width or height to required aspect ratio */ a = sz.y/sz.x; if (a > aspect) { sz.x = sz.y/aspect; } else if (a < aspect) { sz.y = sz.x*aspect; } /* for given sz, get radius */ r = sz.x/(2*cos(alpha)); r0 = (r*cos(alpha)*cos(alpha4))/(sin(alpha4)*cos(alpha2)); /* offset is the y shift of circle center from bb center */ offset = (r*(1 - sin(alpha3)))/2; for (i = 0; i < 10; i += 2) { vertices[i].x = r*cos(theta); vertices[i].y = r*sin(theta) - offset; theta += alpha2; vertices[i+1].x = r0*cos(theta); vertices[i+1].y = r0*sin(theta) - offset; theta += alpha2; } *bb = sz; } static boolean star_inside(inside_t * inside_context, pointf p) { static node_t *lastn; /* last node argument */ static polygon_t *poly; static int outp, sides; static pointf *vertex; static pointf O; /* point (0,0) */ if (!inside_context) { lastn = NULL; return FALSE; } boxf *bp = inside_context->s.bp; node_t *n = inside_context->s.n; pointf P, Q, R; int i, outcnt; P = ccwrotatepf(p, 90 * GD_rankdir(agraphof(n))); /* Quick test if port rectangle is target */ if (bp) { boxf bbox = *bp; return INSIDE(P, bbox); } if (n != lastn) { poly = (polygon_t *) ND_shape_info(n); vertex = poly->vertices; sides = poly->sides; /* index to outer-periphery */ outp = (poly->peripheries - 1) * sides; if (outp < 0) outp = 0; lastn = n; } outcnt = 0; for (i = 0; i < sides; i += 2) { Q = vertex[i + outp]; R = vertex[((i+4) % sides) + outp]; if (!(same_side(P, O, Q, R))) { outcnt++; } if (outcnt == 2) { return FALSE; } } return TRUE; } /* cylinder: * Code based on PostScript version by <NAME>. * http://rhodesmill.org/brandon/2007/a-database-symbol-for-graphviz/ */ static pointf cylinder_size (pointf sz) { sz.y *= 1.375; return sz; } static void cylinder_vertices (pointf* vertices, pointf* bb) { double x = bb->x/2; double y = bb->y/2; double yr = bb->y/11; vertices[0].x = x; vertices[0].y = y-yr; vertices[1].x = x; vertices[1].y = y-(1-0.551784)*yr; vertices[2].x = 0.551784*x; vertices[2].y = y; vertices[3].x = 0; vertices[3].y = y; vertices[4].x = -0.551784*x; vertices[4].y = y; vertices[5].x = -x; vertices[5].y = vertices[1].y; vertices[6].x = -x; vertices[6].y = y-yr; vertices[7] = vertices[6]; vertices[8].x = -x; vertices[8].y = yr-y; vertices[9] = vertices[8]; vertices[10].x = -x; vertices[10].y = -vertices[1].y; vertices[11].x = vertices[4].x; vertices[11].y = -vertices[4].y; vertices[12].x = vertices[3].x; vertices[12].y = -vertices[3].y; vertices[13].x = vertices[2].x; vertices[13].y = -vertices[2].y; vertices[14].x = vertices[1].x; vertices[14].y = -vertices[1].y; vertices[15].x = vertices[0].x; vertices[15].y = -vertices[0].y; vertices[16] = vertices[15]; vertices[18] = vertices[17] = vertices[0]; } static void cylinder_draw(GVJ_t * job, pointf * AF, int sides, int style, int filled) { pointf vertices[7]; double y0 = AF[0].y; double y02 = y0+y0; vertices[0] = AF[0]; vertices[1].x = AF[1].x; vertices[1].y = y02 - AF[1].y; vertices[2].x = AF[2].x; vertices[2].y = y02 - AF[2].y; vertices[3].x = AF[3].x; vertices[3].y = y02 - AF[3].y; vertices[4].x = AF[4].x; vertices[4].y = y02 - AF[4].y; vertices[5].x = AF[5].x; vertices[5].y = y02 - AF[5].y; vertices[6] = AF[6]; gvrender_beziercurve(job, AF, sides, FALSE, FALSE, filled); gvrender_beziercurve(job, vertices, 7, FALSE, FALSE, FALSE); } #if 0 /* cylinder_inside: * At present, we use just the polygonal outline provided by vertices. * This cold be made more precise by using a finer-grained polyline path * to the spline top and bottom. Another approach might be to approximate * the top and bottom by ellipses. Then the test would involve a check if * the point is in the rectangle or one of the two ellipses. */ static boolean cylinder_inside(inside_t * inside_context, pointf p) { return TRUE; } #endif static char *side_port[] = { "s", "e", "n", "w" }; static point cvtPt(pointf p, int rankdir) { pointf q = { 0, 0 }; point Q; switch (rankdir) { case RANKDIR_TB: q = p; break; case RANKDIR_BT: q.x = p.x; q.y = -p.y; break; case RANKDIR_LR: q.y = p.x; q.x = -p.y; break; case RANKDIR_RL: q.y = p.x; q.x = p.y; break; } PF2P(q, Q); return Q; } /* closestSide: * Resolve unspecified compass-point port to best available port. * At present, this finds the available side closest to the center * of the other port. * * This could be improved: * - if other is unspecified, do them together * - if dot, bias towards bottom of one to top of another, if possible * - if line segment from port centers uses available sides, use these * or center. (This latter may require spline routing to cooperate.) */ static char *closestSide(node_t * n, node_t * other, port * oldport) { boxf b; int rkd = GD_rankdir(agraphof(n)->root); point p = { 0, 0 }; point pt = cvtPt(ND_coord(n), rkd); point opt = cvtPt(ND_coord(other), rkd); int sides = oldport->side; char *rv = NULL; int i, d, mind = 0; if ((sides == 0) || (sides == (TOP | BOTTOM | LEFT | RIGHT))) return rv; /* use center */ if (oldport->bp) { b = *oldport->bp; } else { if (GD_flip(agraphof(n))) { b.UR.x = ND_ht(n) / 2; b.LL.x = -b.UR.x; b.UR.y = ND_lw(n); b.LL.y = -b.UR.y; } else { b.UR.y = ND_ht(n) / 2; b.LL.y = -b.UR.y; b.UR.x = ND_lw(n); b.LL.x = -b.UR.x; } } for (i = 0; i < 4; i++) { if ((sides & (1 << i)) == 0) continue; switch (i) { case 0: p.y = b.LL.y; p.x = (b.LL.x + b.UR.x) / 2; break; case 1: p.x = b.UR.x; p.y = (b.LL.y + b.UR.y) / 2; break; case 2: p.y = b.UR.y; p.x = (b.LL.x + b.UR.x) / 2; break; case 3: p.x = b.LL.x; p.y = (b.LL.y + b.UR.y) / 2; break; } p.x += pt.x; p.y += pt.y; d = DIST2(p, opt); if (!rv || (d < mind)) { mind = d; rv = side_port[i]; } } return rv; } port resolvePort(node_t * n, node_t * other, port * oldport) { port rv; char *compass = closestSide(n, other, oldport); /* transfer name pointer; all other necessary fields will be regenerated */ rv.name = oldport->name; compassPort(n, oldport->bp, &rv, compass, oldport->side, NULL); return rv; } void resolvePorts(edge_t * e) { if (ED_tail_port(e).dyna) ED_tail_port(e) = resolvePort(agtail(e), aghead(e), &ED_tail_port(e)); if (ED_head_port(e).dyna) ED_head_port(e) = resolvePort(aghead(e), agtail(e), &ED_head_port(e)); } void gv_initShapes(void) { pointf p = { 0, 0 }; poly_inside(NULL, p); point_inside(NULL, p); star_inside(NULL, p); }
58,330
705
// <NAME>, <NAME>, <NAME>, <NAME> // CS1A Foothill Fall 2017 // Assignment 4 ADVANCED: Guessing Game // The 'METHODS' File public class Game_Program extends Object { public static void main(String[] args) { boolean playAgain; do { GuessingGame gg = new GuessingGame(); playAgain = gg.playGuessingGame(); } while (playAgain); } }
175
1,674
package scala.meta.pc; import org.eclipse.lsp4j.jsonrpc.CancelChecker; import java.util.concurrent.CompletionStage; /** * Extension of CancelChecker that supports registering a callback on cancellation. * * This extension was needed to interrupt the presentation compiler thread to stop * expensive typechecking operations. */ public interface CancelToken extends CancelChecker { /** * Completes to true when request has been cancelled, and completes * to false when request will never be cancelled. May never complete. */ CompletionStage<Boolean> onCancel(); }
165
399
<reponame>kosua20/Rendu #include "input/Input.hpp" #include "raycaster/Intersection.hpp" #include "resources/ResourcesManager.hpp" #include "graphics/ScreenQuad.hpp" #include "graphics/Framebuffer.hpp" #include "graphics/GPU.hpp" #include "system/Window.hpp" #include "system/System.hpp" #include "generation/Random.hpp" #include "system/Config.hpp" #include "Common.hpp" #include "AtmosphereApp.hpp" AtmosphereApp::AtmosphereApp(RenderingConfig & config) : CameraApp(config), _scattering("Scattering LUT") { _userCamera.projection(config.screenResolution[0] / config.screenResolution[1], 1.34f, 0.1f, 100.0f); // Framebuffer to store the rendered atmosphere result before tonemapping and upscaling to the window size. const glm::vec2 renderRes = _config.renderingResolution(); _atmosphereBuffer.reset(new Framebuffer(uint(renderRes[0]), uint(renderRes[1]), Layout::RGBA16F, "Atmosphere")); // Atmosphere screen quad. _atmosphere = Resources::manager().getProgram2D("atmosphere_params"); // Final tonemapping screen quad. _tonemap = Resources::manager().getProgram2D("tonemap"); // Sun direction. _lightDirection = glm::normalize(glm::vec3(0.337f, 0.174f, -0.925f)); // Populate lookup table. updateSky(); } void AtmosphereApp::draw() { // Render. const glm::mat4 camToWorld = glm::inverse(_userCamera.view()); const glm::mat4 clipToCam = glm::inverse(_userCamera.projection()); // Draw the atmosphere. GPU::setDepthState(false); GPU::setBlendState(false); GPU::setCullState(false); _atmosphereBuffer->bind(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), Framebuffer::Operation::DONTCARE, Framebuffer::Operation::DONTCARE); _atmosphereBuffer->setViewport(); _atmosphere->use(); const glm::mat4 camToWorldNoT = glm::mat4(glm::mat3(camToWorld)); const glm::mat4 clipToWorld = camToWorldNoT * clipToCam; _atmosphere->uniform("clipToWorld", clipToWorld); _atmosphere->uniform("viewPos", _userCamera.position()); _atmosphere->uniform("lightDirection", _lightDirection); _atmosphere->uniform("altitude", _altitude); // Send the atmosphere parameters. _atmosphere->uniform("atmoParams.sunColor", _atmoParams.sunColor); _atmosphere->uniform("atmoParams.kRayleigh", _atmoParams.kRayleigh); _atmosphere->uniform("atmoParams.groundRadius", _atmoParams.groundRadius); _atmosphere->uniform("atmoParams.topRadius", _atmoParams.topRadius); _atmosphere->uniform("atmoParams.sunIntensity", _atmoParams.sunIntensity); _atmosphere->uniform("atmoParams.kMie", _atmoParams.kMie); _atmosphere->uniform("atmoParams.heightRayleigh", _atmoParams.heightRayleigh); _atmosphere->uniform("atmoParams.heightMie", _atmoParams.heightMie); _atmosphere->uniform("atmoParams.gMie", _atmoParams.gMie); _atmosphere->uniform("atmoParams.sunAngularRadius", _atmoParams.sunRadius); _atmosphere->uniform("atmoParams.sunAngularRadiusCos", _atmoParams.sunRadiusCos); _atmosphere->texture(_scattering, 0); ScreenQuad::draw(); // Tonemapping and final screen. GPU::setViewport(0, 0, int(_config.screenResolution[0]), int(_config.screenResolution[1])); Framebuffer::backbuffer()->bind(Framebuffer::Operation::DONTCARE, Framebuffer::Operation::DONTCARE); _tonemap->use(); _tonemap->uniform("customExposure", 1.0f); _tonemap->uniform("apply", true); _tonemap->texture(_atmosphereBuffer->texture(), 0); ScreenQuad::draw(); } void AtmosphereApp::update() { CameraApp::update(); if(ImGui::Begin("Atmosphere")) { ImGui::Text("%.1f ms, %.1f fps", frameTime() * 1000.0f, frameRate()); // Sun parameters. ImGui::PushItemWidth(120); bool shouldUpdateSky = false; if(ImGui::DragFloat("Azimuth", &_lightAzimuth, 0.1f, 0.0f, 360.0f, "%.1f°")) { _lightAzimuth = glm::clamp(_lightAzimuth, 0.0f, 360.0f); shouldUpdateSky = true; } ImGui::SameLine(); if(ImGui::DragFloat("Elevation", &_lightElevation, 0.1f, -15.0f, 90.0f, "%.1f°")) { _lightElevation = glm::clamp(_lightElevation, -15.0f, 90.0f); shouldUpdateSky = true; } ImGui::PopItemWidth(); if(shouldUpdateSky) { const float elevRad = _lightElevation / 180 * glm::pi<float>(); const float azimRad = _lightAzimuth / 180 * glm::pi<float>(); _lightDirection = glm::vec3(std::cos(azimRad) * std::cos(elevRad), std::sin(elevRad), std::sin(azimRad) * std::cos(elevRad)); } ImGui::DragFloat("Altitude", &_altitude, 10.0f, 0.0f, 10000.0f, "%.0fm", ImGuiSliderFlags_NoRoundToFormat | ImGuiSliderFlags_Logarithmic); if(ImGui::CollapsingHeader("Atmosphere parameters")) { bool updateScattering = false; updateScattering = ImGui::InputInt("Resolution", &_tableRes) || updateScattering; updateScattering = ImGui::InputInt("Samples", &_tableSamples) || updateScattering; if(ImGui::Button("Reset")) { _atmoParams = Sky::AtmosphereParameters(); updateScattering = true; } updateScattering = ImGui::SliderFloat("Mie height", &_atmoParams.heightMie, 100.0f, 20000.0f) || updateScattering; updateScattering = ImGui::SliderFloat("Mie K", &_atmoParams.kMie, 1e-6f, 100e-6f, "%.6f") || updateScattering; updateScattering = ImGui::SliderFloat("Rayleigh height", &_atmoParams.heightRayleigh, 100.0f, 20000.0f) || updateScattering; updateScattering = ImGui::SliderFloat3("Rayleigh K", &_atmoParams.kRayleigh[0], 1e-6f, 100e-6f, "%.6f") || updateScattering; updateScattering = ImGui::SliderFloat("Ground radius", &_atmoParams.groundRadius, 1e6f, 10e6f) || updateScattering; updateScattering = ImGui::SliderFloat("Atmosphere radius", &_atmoParams.topRadius, 1e6f, 10e6f) || updateScattering; if(updateScattering) { updateSky(); } ImGui::SliderFloat("Mie G", &_atmoParams.gMie, 0.0f, 1.0f); if(ImGui::SliderFloat("Sun diameter", &_atmoParams.sunRadius, 0.0f, 0.1f)) { _atmoParams.sunRadiusCos = std::cos(_atmoParams.sunRadius); } ImGui::SliderFloat("Sun intensity", &_atmoParams.sunIntensity, 0.0f, 20.0f); } } ImGui::End(); } void AtmosphereApp::resize() { _atmosphereBuffer->resize(_config.renderingResolution()); } void AtmosphereApp::precomputeTable(const Sky::AtmosphereParameters & params, uint samples, Image & table) { // Parameters. const uint res = table.width; System::forParallel(0, res, [&](size_t y) { for(size_t x = 0; x < res; ++x) { // Move to 0,1. // No need to take care of the 0.5 shift as we are working with indices const float xf = float(x) / (res - 1.0f); const float yf = float(y) / (res - 1.0f); // Position and ray direction. // x becomes the height // y become the cosine const glm::vec3 currPos = glm::vec3(0.0f, (params.topRadius - params.groundRadius) * xf + params.groundRadius, 0.0f); const float cosA = 2.0f * yf - 1.0f; const float sinA = std::sqrt(1.0f - cosA * cosA); const glm::vec3 sunDir = -glm::normalize(glm::vec3(sinA, cosA, 0.0f)); // Check when the ray leaves the atmosphere. glm::vec2 interSecondTop; const bool didHitSecondTop = Intersection::sphere(currPos, sunDir, params.topRadius, interSecondTop); // Divide the distance traveled through the atmosphere in samplesCount parts. const float secondStepSize = didHitSecondTop ? interSecondTop.y / float(samples) : 0.0f; // Accumulate optical distance for both scatterings. float rayleighSecondDist = 0.0; float mieSecondDist = 0.0; // March along the secondary ray. for(unsigned int j = 0; j < samples; ++j) { // Compute the current position along the ray, ... const glm::vec3 currSecondPos = currPos + (float(j) + 0.5f) * secondStepSize * sunDir; // ...and its distance to the ground (as we are in planet space). const float currSecondHeight = glm::length(currSecondPos) - params.groundRadius; // Compute density based on the characteristic height of Rayleigh and Mie. const float rayleighSecondStep = exp(-currSecondHeight / params.heightRayleigh) * secondStepSize; const float mieSecondStep = exp(-currSecondHeight / params.heightMie) * secondStepSize; // Accumulate optical distances. rayleighSecondDist += rayleighSecondStep; mieSecondDist += mieSecondStep; } // Compute associated attenuation. const glm::vec3 secondaryAttenuation = exp(-(params.kMie * mieSecondDist + params.kRayleigh * rayleighSecondDist)); table.rgba(int(x), int(y)) = glm::vec4(secondaryAttenuation, 1.0f); } }); } void AtmosphereApp::updateSky() { Log::Info() << Log::Resources << "Updating sky..." << std::flush; _scattering.width = _scattering.height = uint(_tableRes); _scattering.levels = _scattering.depth = 1; _scattering.shape = TextureShape::D2; _scattering.clean(); _scattering.images.emplace_back(_scattering.width, _scattering.height, 4); // Update the lookup table. precomputeTable(_atmoParams, uint(_tableSamples), _scattering.images[0]); _scattering.upload(Layout::RGBA16F, false); Log::Info() << " done." << std::endl; }
3,640
360
<reponame>opengauss-mirror/openGauss-graph<gh_stars>100-1000 /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * --------------------------------------------------------------------------------------- * * streamConsumer.h * * * * IDENTIFICATION * src/include/distributelayer/streamConsumer.h * * --------------------------------------------------------------------------------------- */ #ifndef SRC_INCLUDE_DISTRIBUTELAYER_STREAMCONSUMER_H_ #define SRC_INCLUDE_DISTRIBUTELAYER_STREAMCONSUMER_H_ #include "distributelayer/streamCore.h" class StreamConsumer; typedef struct { StreamConsumer* consumer; int connNum; int connInfoSize; StreamConnInfo* connInfo; } StreamValue; /* Element in stream information table. */ typedef struct { StreamKey key; StreamValue* value; } StreamElement; class StreamConsumer : public StreamObj { public: StreamConsumer(MemoryContext context); ~StreamConsumer(); /* Init the consumer object. */ void init(StreamKey key, List* execProducerNodes, ParallelDesc desc, StreamTransType transType, StreamSharedContext* sharedContext); /* Deinit the consumer. */ void deInit(); /* Waiting for the producer is ready. */ void waitProducerReady(); /* Find un connect producer. */ void findUnconnectProducer(StringInfo str); /* Get nodeIdx of producer which is waited for. */ int getFirstUnconnectedProducerNodeIdx(); /* Wake up consumer and let it work. */ static bool wakeUpConsumerCallBack(CommStreamKey commKey, StreamConnInfo connInfo); /* Release comm mode stream. */ void releaseCommStream(); /* Get nodeIdx of producer by nodename. */ int getNodeIdx(const char* nodename); /* Get shared context for local stream. */ inline StreamSharedContext* getSharedContext() { return m_sharedContext; } /* * Record the orign node list in case of DN pruned in with-recursive execution * mode, store the corresponding producer connection list from which the * ExecStream will get */ List* m_originProducerNodeList; private: /* Update the stream info. */ bool updateStreamCommInfo(StreamConnInfo* connInfo); /* Update the transport info. */ void updateTransportInfo(StreamValue* val); private: /* Current producer number. */ int m_currentProducerNum; /* All producer is ready or not. */ bool m_ready; /* Expected producer info. */ StreamConnInfo* m_expectProducer; /* Mutex and condition waiting for producer is ready. */ pthread_mutex_t m_mutex; pthread_cond_t m_cond; StreamSharedContext* m_sharedContext; }; #endif /* SRC_INCLUDE_DISTRIBUTELAYER_STREAMCONSUMER_H_ */
1,068
1,718
#pragma once #include <torchaudio/csrc/rnnt/macros.h> namespace torchaudio { namespace rnnt { namespace math { template <typename DTYPE> FORCE_INLINE HOST_AND_DEVICE DTYPE max(DTYPE x, DTYPE y) { if (x > y) return x; else return y; } template <typename DTYPE> FORCE_INLINE HOST_AND_DEVICE DTYPE min(DTYPE x, DTYPE y) { if (x > y) return y; else return x; } // log_sum_exp template <typename DTYPE> FORCE_INLINE HOST_AND_DEVICE DTYPE lse(DTYPE x, DTYPE y); template <> FORCE_INLINE HOST_AND_DEVICE float lse(float x, float y) { if (y > x) { return y + log1pf(expf(x - y)); } else { return x + log1pf(expf(y - x)); } } } // namespace math } // namespace rnnt } // namespace torchaudio
321
11,356
<gh_stars>1000+ # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Provides a factory class for generating dynamic messages. The easiest way to use this class is if you have access to the FileDescriptor protos containing the messages you want to create you can just do the following: message_classes = message_factory.GetMessages(iterable_of_file_descriptors) my_proto_instance = message_classes['some.proto.package.MessageName']() """ __author__ = '<EMAIL> (<NAME>)' from google.protobuf import descriptor_pool from google.protobuf import message from google.protobuf import reflection class MessageFactory(object): """Factory for creating Proto2 messages from descriptors in a pool.""" def __init__(self, pool=None): """Initializes a new factory.""" self.pool = pool or descriptor_pool.DescriptorPool() # local cache of all classes built from protobuf descriptors self._classes = {} def GetPrototype(self, descriptor): """Builds a proto2 message class based on the passed in descriptor. Passing a descriptor with a fully qualified name matching a previous invocation will cause the same class to be returned. Args: descriptor: The descriptor to build from. Returns: A class describing the passed in descriptor. """ if descriptor.full_name not in self._classes: descriptor_name = descriptor.name if str is bytes: # PY2 descriptor_name = descriptor.name.encode('ascii', 'ignore') result_class = reflection.GeneratedProtocolMessageType( descriptor_name, (message.Message,), {'DESCRIPTOR': descriptor, '__module__': None}) # If module not set, it wrongly points to the reflection.py module. self._classes[descriptor.full_name] = result_class for field in descriptor.fields: if field.message_type: self.GetPrototype(field.message_type) for extension in result_class.DESCRIPTOR.extensions: if extension.containing_type.full_name not in self._classes: self.GetPrototype(extension.containing_type) extended_class = self._classes[extension.containing_type.full_name] extended_class.RegisterExtension(extension) return self._classes[descriptor.full_name] def GetMessages(self, files): """Gets all the messages from a specified file. This will find and resolve dependencies, failing if the descriptor pool cannot satisfy them. Args: files: The file names to extract messages from. Returns: A dictionary mapping proto names to the message classes. This will include any dependent messages as well as any messages defined in the same file as a specified message. """ result = {} for file_name in files: file_desc = self.pool.FindFileByName(file_name) for desc in file_desc.message_types_by_name.values(): result[desc.full_name] = self.GetPrototype(desc) # While the extension FieldDescriptors are created by the descriptor pool, # the python classes created in the factory need them to be registered # explicitly, which is done below. # # The call to RegisterExtension will specifically check if the # extension was already registered on the object and either # ignore the registration if the original was the same, or raise # an error if they were different. for extension in file_desc.extensions_by_name.values(): if extension.containing_type.full_name not in self._classes: self.GetPrototype(extension.containing_type) extended_class = self._classes[extension.containing_type.full_name] extended_class.RegisterExtension(extension) return result _FACTORY = MessageFactory() def GetMessages(file_protos): """Builds a dictionary of all the messages available in a set of files. Args: file_protos: A sequence of file protos to build messages out of. Returns: A dictionary mapping proto names to the message classes. This will include any dependent messages as well as any messages defined in the same file as a specified message. """ for file_proto in file_protos: _FACTORY.pool.Add(file_proto) return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])
1,825
6,224
/** * Copyright (c) 2019 <NAME> * * SPDX-License-Identifier: Apache-2.0 */ /** * @brief Service B.3 * * This code is auto-generated from the Excel Workbook * 'GATT_Test_Databases.xlsm' Sheet: 'Large Database 1' */ #ifndef SERVICE_B_3_1_H #define SERVICE_B_3_1_H #ifdef __cplusplus extern "C" { #endif void service_b_3_1_init(void); void service_b_3_1_remove(void); void service_b_3_1_value_v6_notify(void); #ifdef __cplusplus } #endif #endif /* SERVICE_B_3_1_H */
205
429
#include <unistd.h> #include <errno.h> #include <syscall.h> #include <syscall_nums.h> DEFN_SYSCALL3(readlink, SYS_READLINK, char *, char *, int); ssize_t readlink(const char * name, char * buf, size_t len) { __sets_errno(syscall_readlink((char*)name, buf, len)); }
116
10,608
<filename>datasets/dyk/dataset_infos.json {"default": {"description": "The Did You Know (pol. Czy wiesz?) dataset consists of human-annotated question-answer pairs. The task is to predict if the answer is correct. We chose the negatives which have the largest token overlap with a question.\n", "citation": "@inproceedings{marcinczuk2013open,\ntitle={Open dataset for development of Polish Question Answering systems},\nauthor={Marcinczuk, Micha{\\l} and Ptak, Marcin and Radziszewski, <NAME>},\nbooktitle={Proceedings of the 6th Language \\& Technology Conference: Human Language Technologies as a Challenge for Computer Science and Linguistics, Wydawnictwo Poznanskie, Fundacja Uniwersytetu im. Adama Mickiewicza},\nyear={2013}\n}\n", "homepage": "http://nlp.pwr.wroc.pl/en/tools-and-resources/resources/czy-wiesz-question-answering-dataset", "license": "CC BY-SA 3.0", "features": {"q_id": {"dtype": "string", "id": null, "_type": "Value"}, "question": {"dtype": "string", "id": null, "_type": "Value"}, "answer": {"dtype": "string", "id": null, "_type": "Value"}, "target": {"num_classes": 2, "names": ["0", "1"], "names_file": null, "id": null, "_type": "ClassLabel"}}, "post_processed": null, "supervised_keys": null, "builder_name": "dyk", "config_name": "default", "version": {"version_str": "1.1.0", "description": null, "major": 1, "minor": 1, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 1388690, "num_examples": 4154, "dataset_name": "dyk"}, "test": {"name": "test", "num_bytes": 353643, "num_examples": 1029, "dataset_name": "dyk"}}, "download_checksums": {"https://klejbenchmark.com/static/data/klej_dyk.zip": {"num_bytes": 685462, "checksum": "7c5acaf3244c7eecbac1283a32a1aa64ac0f56c5318baa10a84665463c4be0b9"}}, "download_size": 685462, "post_processing_size": null, "dataset_size": 1742333, "size_in_bytes": 2427795}}
655
647
/* PURPOSE: (Monte carlo structures) REFERENCE: (Trick Users Guide) ASSUMPTIONS AND LIMITATIONS: (None) PROGRAMMERS: ((<NAME>) (LinCom) (7/2003)) */ #ifndef MONTEVAR_HH #define MONTEVAR_HH #include <string> namespace Trick { /** * Abstract base class for Monte Carlo variables. * * @author <NAME> * @author <NAME> * @author <NAME> * * @date August 2010 */ class MonteVar { public: /** Name. */ std::string name; /**< \n trick_units(--) */ /** Units. */ std::string unit; /**< \n trick_units(--) */ /** Value. */ std::string value; /**< \n trick_units(--) */ /** Destructor. */ virtual ~MonteVar() {}; /** * Sets the unit * * @param in_unit this variable's units */ void set_unit(std::string in_unit) { this->unit = in_unit; } // Composite the various elements of this MonteVar. virtual std::string describe_variable() = 0; /** Class MonteCarlo is a friend so it can use the get_next_value method. * The get_next_value method needs to be protected so users cannot use it in the input file */ friend class MonteCarlo ; protected: /** * Gets this variable's next value. * * @return the next value */ virtual std::string get_next_value() = 0; }; }; #endif
701
581
struct Adder { virtual int add(int, int) = 0; }; struct R { int mult(int a, int b) { return a * b; } }; struct S : Adder { virtual int add(int a, int b) override { return a + b; } int sub(int a, int b) { return a - b; } }; struct T : Adder { virtual int add(int a, int b) override { return 2 * a + b; } }; Adder *makeAdder() { return new S; } int add(int a, int b) { return a + b; } int (*F)(int, int) = &add; Adder *A = makeAdder(); int (R::* M)(int, int) = &R::mult; int main() { int a = add(4, 5); int x = A->add(1, 2); int y = F(1, 2); R r; int z = (r.*M)(2, 3); return 0; }
269
19,628
// // DoraemonEntryWindow.h // DoraemonKit // // Created by yixiang on 2017/12/11. // Copyright © 2017年 yixiang. All rights reserved. // #import <UIKit/UIKit.h> /// 入口滑动浮窗(默认记录上次坐标) @interface DoraemonEntryWindow : UIWindow /// 是否自动停靠,默认为YES @property (nonatomic, assign) BOOL autoDock; // 定制位置 - (instancetype)initWithStartPoint:(CGPoint)startingPosition; - (void)show; - (void)configEntryBtnBlingWithText:(NSString *)text backColor:(UIColor *)backColor; @end
239
395
package com.vijay.jsonwizard.customviews; import android.content.Context; import android.util.AttributeSet; import com.rey.material.drawable.CheckBoxDrawable; public class CheckBox extends CompoundButton { public CheckBox(Context context) { super(context); init(context, null, 0, 0); } public CheckBox(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public CheckBox(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } public CheckBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, defStyleRes); } private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { applyStyle(context, attrs, defStyleAttr, defStyleRes); } public void applyStyle(int resId) { applyStyle(getContext(), null, 0, resId); } private void applyStyle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { CheckBoxDrawable drawable = new CheckBoxDrawable.Builder(context, attrs, defStyleAttr, defStyleRes).build(); drawable.setInEditMode(isInEditMode()); drawable.setAnimEnable(false); setButtonDrawable(null); setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); drawable.setAnimEnable(true); } /** * Change the checked state of this button immediately without showing * animation. * * @param checked * The checked state. */ public void setCheckedImmediately(boolean checked) { if (mButtonDrawable instanceof CheckBoxDrawable) { CheckBoxDrawable drawable = (CheckBoxDrawable) mButtonDrawable; drawable.setAnimEnable(false); setChecked(checked); drawable.setAnimEnable(true); } else setChecked(checked); } }
823