max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
655
package com.samourai.wallet.util; import android.content.Context; import androidx.recyclerview.widget.LinearLayoutManager; public class LinearLayoutManagerWrapper extends LinearLayoutManager { public LinearLayoutManagerWrapper(Context context) { super(context); } @Override public boolean supportsPredictiveItemAnimations() { // fix for inconsistency issues return false; } }
136
3,999
/UpdataConfig.dat;http.referer=added1;tags=firstmatch /x/xx/xxxxxxxxxxxxxxxxxxx/x/xxxxxx/xxxxxxxxxxxxxxx;http.user-agent=added2;tags=secondmatch
52
1,056
<reponame>timfel/netbeans /* * 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.netbeans.modules.web.beans.analysis.analyzer.method; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeMirror; import org.netbeans.api.java.source.CompilationController; import org.netbeans.api.java.source.ElementHandle; import org.netbeans.modules.j2ee.metadata.model.api.support.annotation.AnnotationHelper; import org.netbeans.modules.web.beans.analysis.CdiEditorAnalysisFactory; import org.netbeans.modules.web.beans.analysis.analyzer.AbstractDecoratorAnalyzer; import org.netbeans.modules.web.beans.analysis.analyzer.AnnotationUtil; import org.netbeans.modules.web.beans.analysis.analyzer.MethodModelAnalyzer.MethodAnalyzer; import org.netbeans.modules.web.beans.analysis.analyzer.ModelAnalyzer.Result; import org.netbeans.modules.web.beans.analysis.analyzer.field.InjectionPointAnalyzer; import org.netbeans.modules.web.beans.api.model.CdiException; import org.netbeans.modules.web.beans.api.model.DependencyInjectionResult; import org.netbeans.modules.web.beans.api.model.DependencyInjectionResult.ResultKind; import org.netbeans.modules.web.beans.api.model.InjectionPointDefinitionError; import org.netbeans.modules.web.beans.api.model.WebBeansModel; import org.netbeans.modules.web.beans.hints.EditorAnnotationsHelper; import org.netbeans.spi.editor.hints.Severity; import org.openide.util.NbBundle; /** * @author ads * */ public class InjectionPointParameterAnalyzer extends AbstractDecoratorAnalyzer<ExecutableElement> implements MethodAnalyzer { /* (non-Javadoc) * @see org.netbeans.modules.web.beans.analysis.analyzer.MethodModelAnalyzer.MethodAnalyzer#analyze(javax.lang.model.element.ExecutableElement, javax.lang.model.type.TypeMirror, javax.lang.model.element.TypeElement, org.netbeans.modules.web.beans.api.model.WebBeansModel, java.util.concurrent.atomic.AtomicBoolean, org.netbeans.modules.web.beans.analysis.analyzer.ModelAnalyzer.Result) */ @Override public void analyze( ExecutableElement element, TypeMirror returnType, TypeElement parent, WebBeansModel model , AtomicBoolean cancel , Result result ) { for (VariableElement var : element.getParameters()) { if (cancel.get()) { return; } try { if (model.isInjectionPoint(var)) { boolean isDelegate = false; result.requireCdiEnabled(element, model); if ( cancel.get() ){ return; } if (!model.isDynamicInjectionPoint(var)) { isDelegate =AnnotationUtil.isDelegate(var, parent, model); if (!checkBuiltInBeans(var, getParameterType(var, element, parent, model.getCompilationController()), model, cancel)) { DependencyInjectionResult res = model .lookupInjectables(var, (DeclaredType) parent.asType(), cancel); checkResult(res, element, var, model, result); if (isDelegate) { analyzeDecoratedBeans(res, var, element, parent, model, result); } } } if ( cancel.get()){ return; } checkName(element, var, model,result ); if ( cancel.get()){ return; } checkInjectionPointMetadata( var, element, parent , model , cancel , result ); if ( isDelegate || AnnotationUtil.hasAnnotation(element, AnnotationUtil.DELEGATE_FQN, model.getCompilationController())) { return; } else { VariableElement param = CdiEditorAnalysisFactory. resolveParameter(var, element, result.getInfo()); EditorAnnotationsHelper helper = EditorAnnotationsHelper. getInstance(result); if ( helper != null ){ helper.addInjectionPoint(result, param); } } } } catch( InjectionPointDefinitionError e ){ result.requireCdiEnabled(element, model); informInjectionPointDefError(e, element, model, result ); } } } /* (non-Javadoc) * @see org.netbeans.modules.web.beans.analysis.analyzer.AbstractDecoratorAnalyzer#addClassError(javax.lang.model.element.VariableElement, java.lang.Object, javax.lang.model.element.TypeElement, org.netbeans.modules.web.beans.api.model.WebBeansModel, org.netbeans.api.java.source.CompilationInfo, java.util.List) */ @Override protected void addClassError( VariableElement element, ExecutableElement method, TypeElement decoratedBean, WebBeansModel model, Result result ) { result.addError( element , method, model, NbBundle.getMessage(InjectionPointParameterAnalyzer.class, "ERR_FinalDecoratedBean", // NOI18N decoratedBean.getQualifiedName().toString())); } /* (non-Javadoc) * @see org.netbeans.modules.web.beans.analysis.analyzer.AbstractDecoratorAnalyzer#addMethodError(javax.lang.model.element.VariableElement, java.lang.Object, javax.lang.model.element.TypeElement, javax.lang.model.element.Element, org.netbeans.modules.web.beans.api.model.WebBeansModel, org.netbeans.modules.web.beans.analysis.analyzer.ModelAnalyzer.Result) */ @Override protected void addMethodError( VariableElement element, ExecutableElement method, TypeElement decoratedBean, Element decoratedMethod, WebBeansModel model, Result result ) { result.addError( element, method, model, NbBundle.getMessage( InjectionPointParameterAnalyzer.class, "ERR_FinalMethodDecoratedBean", // NOI18N decoratedBean.getQualifiedName().toString(), decoratedMethod.getSimpleName().toString())); } private TypeMirror getParameterType( VariableElement var, ExecutableElement element, TypeElement parent , CompilationController controller ) { ExecutableType method = (ExecutableType)controller.getTypes().asMemberOf( (DeclaredType)parent.asType(), element); List<? extends TypeMirror> parameterTypes = method.getParameterTypes(); List<? extends VariableElement> parameters = element.getParameters(); int paramIndex = parameters.indexOf(var); return parameterTypes.get(paramIndex); } private void checkInjectionPointMetadata( VariableElement var, ExecutableElement method, TypeElement parent, WebBeansModel model, AtomicBoolean cancel , Result result ) { TypeElement injectionPointType = model.getCompilationController() .getElements().getTypeElement(AnnotationUtil.INJECTION_POINT); if (injectionPointType == null) { return; } Element varElement = model.getCompilationController().getTypes() .asElement(var.asType()); if (!injectionPointType.equals(varElement)) { return; } if (cancel.get()) { return; } List<AnnotationMirror> qualifiers = model.getQualifiers(varElement, true); AnnotationHelper helper = new AnnotationHelper( model.getCompilationController()); Map<String, ? extends AnnotationMirror> qualifiersFqns = helper .getAnnotationsByType(qualifiers); boolean hasDefault = model.hasImplicitDefaultQualifier(varElement); if (!hasDefault && qualifiersFqns.keySet().contains(AnnotationUtil.DEFAULT_FQN)) { hasDefault = true; } if (!hasDefault || cancel.get()) { return; } try { String scope = model.getScope(parent); if (scope != null && !AnnotationUtil.DEPENDENT.equals(scope)) { result.addError(var, method, model, NbBundle.getMessage(InjectionPointParameterAnalyzer.class,"ERR_WrongQualifierInjectionPointMeta")); // NOI18N } } catch (CdiException e) { // this exception will be handled in the appropriate scope analyzer return; } } private void checkName( ExecutableElement element, VariableElement var, WebBeansModel model, Result result) { AnnotationMirror annotation = AnnotationUtil.getAnnotationMirror( var , AnnotationUtil.NAMED, model.getCompilationController()); if ( annotation!= null){ result.addNotification( Severity.WARNING , var, element , model, NbBundle.getMessage(InjectionPointAnalyzer.class, "WARN_NamedInjectionPoint")); // NOI18N if ( annotation.getElementValues().size() == 0 ){ result.addError(var, element, model, NbBundle.getMessage( InjectionPointParameterAnalyzer.class, "ERR_ParameterNamedInjectionPoint")); // NOI18N } } } private void checkResult( DependencyInjectionResult res , ExecutableElement method , VariableElement element, WebBeansModel model, Result result ) { if ( res instanceof DependencyInjectionResult.Error ){ ResultKind kind = res.getKind(); Severity severity = Severity.WARNING; if ( kind == DependencyInjectionResult.ResultKind.DEFINITION_ERROR){ severity = Severity.ERROR; } String message = ((DependencyInjectionResult.Error)res).getMessage(); result.addNotification(severity, element , method , model, message); } } private void informInjectionPointDefError(InjectionPointDefinitionError exception , Element element, WebBeansModel model, Result result ) { result.addError(element, model, exception.getMessage()); } }
5,384
1,695
<filename>core/trino-main/src/main/java/io/trino/operator/scalar/InvokeFunction.java /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.operator.scalar; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Primitives; import io.trino.metadata.BoundSignature; import io.trino.metadata.FunctionMetadata; import io.trino.metadata.Signature; import io.trino.metadata.SqlScalarFunction; import io.trino.spi.type.Type; import io.trino.spi.type.TypeSignature; import io.trino.sql.gen.lambda.LambdaFunctionInterface; import java.lang.invoke.MethodHandle; import java.util.Optional; import static io.trino.spi.function.InvocationConvention.InvocationArgumentConvention.FUNCTION; import static io.trino.spi.function.InvocationConvention.InvocationReturnConvention.NULLABLE_RETURN; import static io.trino.spi.type.TypeSignature.functionType; import static io.trino.util.Reflection.methodHandle; /** * This scalar function exists primarily to test lambda expression support. */ public final class InvokeFunction extends SqlScalarFunction { public static final InvokeFunction INVOKE_FUNCTION = new InvokeFunction(); private static final MethodHandle METHOD_HANDLE = methodHandle(InvokeFunction.class, "invoke", InvokeLambda.class); private InvokeFunction() { super(FunctionMetadata.scalarBuilder() .signature(Signature.builder() .name("invoke") .typeVariable("T") .returnType(new TypeSignature("T")) .argumentType(functionType(new TypeSignature("T"))) .build()) .nullable() .hidden() .description("lambda invoke function") .build()); } @Override protected ScalarFunctionImplementation specialize(BoundSignature boundSignature) { Type returnType = boundSignature.getReturnType(); return new ChoicesScalarFunctionImplementation( boundSignature, NULLABLE_RETURN, ImmutableList.of(FUNCTION), ImmutableList.of(InvokeLambda.class), METHOD_HANDLE.asType( METHOD_HANDLE.type() .changeReturnType(Primitives.wrap(returnType.getJavaType()))), Optional.empty()); } public static Object invoke(InvokeLambda function) { return function.apply(); } @FunctionalInterface public interface InvokeLambda extends LambdaFunctionInterface { Object apply(); } }
1,244
1,063
[ { "category": "s3", "description": "Fixed an issue where the request path was set incorrectly if access point name was present in key path.", "type": "bugfix" } ]
61
14,425
<gh_stars>1000+ /** * 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.ipc; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.ProcessingDetails.Timing; import org.junit.Before; import org.junit.Test; import static org.apache.hadoop.ipc.WeightedTimeCostProvider.DEFAULT_LOCKEXCLUSIVE_WEIGHT; import static org.apache.hadoop.ipc.WeightedTimeCostProvider.DEFAULT_LOCKFREE_WEIGHT; import static org.apache.hadoop.ipc.WeightedTimeCostProvider.DEFAULT_LOCKSHARED_WEIGHT; import static org.junit.Assert.assertEquals; /** Tests for {@link WeightedTimeCostProvider}. */ public class TestWeightedTimeCostProvider { private static final int QUEUE_TIME = 3; private static final int LOCKFREE_TIME = 5; private static final int LOCKSHARED_TIME = 7; private static final int LOCKEXCLUSIVE_TIME = 11; private WeightedTimeCostProvider costProvider; private ProcessingDetails processingDetails; @Before public void setup() { costProvider = new WeightedTimeCostProvider(); processingDetails = new ProcessingDetails(TimeUnit.MILLISECONDS); processingDetails.set(Timing.QUEUE, QUEUE_TIME); processingDetails.set(Timing.LOCKFREE, LOCKFREE_TIME); processingDetails.set(Timing.LOCKSHARED, LOCKSHARED_TIME); processingDetails.set(Timing.LOCKEXCLUSIVE, LOCKEXCLUSIVE_TIME); } @Test(expected = AssertionError.class) public void testGetCostBeforeInit() { costProvider.getCost(null); } @Test public void testGetCostDefaultWeights() { costProvider.init("foo", new Configuration()); long actualCost = costProvider.getCost(processingDetails); long expectedCost = DEFAULT_LOCKFREE_WEIGHT * LOCKFREE_TIME + DEFAULT_LOCKSHARED_WEIGHT * LOCKSHARED_TIME + DEFAULT_LOCKEXCLUSIVE_WEIGHT * LOCKEXCLUSIVE_TIME; assertEquals(expectedCost, actualCost); } @Test public void testGetCostConfiguredWeights() { Configuration conf = new Configuration(); int queueWeight = 1000; int lockfreeWeight = 10000; int locksharedWeight = 100000; conf.setInt("foo.weighted-cost.queue", queueWeight); conf.setInt("foo.weighted-cost.lockfree", lockfreeWeight); conf.setInt("foo.weighted-cost.lockshared", locksharedWeight); conf.setInt("bar.weighted-cost.lockexclusive", 0); // should not apply costProvider.init("foo", conf); long actualCost = costProvider.getCost(processingDetails); long expectedCost = queueWeight * QUEUE_TIME + lockfreeWeight * LOCKFREE_TIME + locksharedWeight * LOCKSHARED_TIME + DEFAULT_LOCKEXCLUSIVE_WEIGHT * LOCKEXCLUSIVE_TIME; assertEquals(expectedCost, actualCost); } }
1,105
2,674
from .purify import *
7
5,169
<filename>Specs/d/d/5/SafexPay/1.0.7/SafexPay.podspec.json { "name": "SafexPay", "version": "1.0.7", "summary": "SafexPay framework", "homepage": "https://bitbucket.org/safexpayment/safexpay_ios/src/master/", "description": "SafexPay framework for payments.", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "swift_versions": "5.0", "source": { "git": "https://[email protected]/safexpayment/safexpay_ios.git", "tag": "1.0.7" }, "requires_arc": true, "vendored_frameworks": "SafexPay.framework", "exclude_files": "Classes/Exclude", "user_target_xcconfig": { "EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64" }, "pod_target_xcconfig": { "EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64" }, "swift_version": "5.0" }
404
1,057
<reponame>alexrs/linux-tracing-workshop<filename>nhttpslower.py #!/usr/bin/env python # # nhttpslower Snoops and prints Node.js HTTP requests slower than a threshold. # This tool is experimental and designed for teaching purposes # only; it is neither tested nor suitable for production work. # # NOTE: Node http__client* probes are not accurate in that they do not report # the fd, remote, and port. This makes it impossible to correlate request # and response probes, and a result the tool does not work correctly if # there are multiple client requests in flight in parallel. # # Copyright (C) <NAME>, 2017 import argparse import ctypes as ct import sys from bcc import BPF, USDT, DEBUG_PREPROCESSOR # TODO This can also be done by using uprobes -- explore what it would take # TODO Filter by HTTP method, or by URL prefix/substring parser = argparse.ArgumentParser(description="Snoops and prints Node.js HTTP " + "requests and responses (client and server) slower than a threshold. " + "Requires Node.js built with --enable-dtrace (confirm by using tplist).") parser.add_argument("pid", type=int, help="the Node.js process id") parser.add_argument("threshold", type=int, nargs="?", default=0, help="print only requests slower than this threshold (ms)") parser.add_argument("-S", "--stack", action="store_true", help="capture a stack trace for each event") parser.add_argument("--client", action="store_true", help="client events only (outgoing requests)") parser.add_argument("--server", action="store_true", help="server events only (incoming requests)") parser.add_argument("-d", "--debug", action="store_true", help="print the BPF program (for debugging purposes)") args = parser.parse_args() text = """ #include <uapi/linux/ptrace.h> struct val_t { u64 start_ns; u64 duration_ns; int type; // CLIENT, SERVER #ifdef NEED_STACK int stackid; #endif char method[16]; char url[128]; }; struct data_t { u64 start_ns; u64 duration_ns; int port; int type; int stackid; char method[16]; char url[128]; char remote[128]; }; struct key_t { // TODO nhttpsnoop correlates by remote and port, while we use fd and port int fd; int port; }; #define CLIENT 0 #define SERVER 1 BPF_PERF_OUTPUT(events); BPF_STACK_TRACE(stacks, 1024); BPF_HASH(starts, struct key_t, struct val_t); #define THRESHOLD """ + str(args.threshold*1000000) + "\n" probe = """ int PROBE_start(struct pt_regs *ctx) { struct val_t val = {0}; struct key_t key = {0}; char *str; bpf_usdt_readarg(7, ctx, &key.fd); bpf_usdt_readarg(4, ctx, &key.port); bpf_usdt_readarg(5, ctx, &str); bpf_probe_read(val.method, sizeof(val.method), str); bpf_usdt_readarg(6, ctx, &str); bpf_probe_read(val.url, sizeof(val.url), str); val.start_ns = bpf_ktime_get_ns(); val.type = TYPE; #ifdef NEED_STACK val.stackid = stacks.get_stackid(ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK); #endif starts.update(&key, &val); return 0; } int PROBE_end(struct pt_regs *ctx) { struct key_t key = {0}; struct val_t *valp; struct data_t data = {0}; u64 duration; char *remote; bpf_usdt_readarg(4, ctx, &key.fd); bpf_usdt_readarg(3, ctx, &key.port); valp = starts.lookup(&key); if (!valp) return 0; // Missed the start event for this request duration = bpf_ktime_get_ns() - valp->start_ns; if (duration < THRESHOLD) goto EXIT; data.start_ns = valp->start_ns; data.duration_ns = duration; data.port = key.port; data.type = valp->type; #ifdef NEED_STACK data.stackid = valp->stackid; #endif __builtin_memcpy(data.method, valp->method, sizeof(data.method)); __builtin_memcpy(data.url, valp->url, sizeof(data.url)); bpf_usdt_readarg(2, ctx, &remote); bpf_probe_read(&data.remote, sizeof(data.remote), remote); events.perf_submit(ctx, &data, sizeof(data)); EXIT: starts.delete(&key); return 0; } """ if not args.server: text += probe.replace("PROBE", "client").replace("TYPE", "CLIENT") if not args.client: text += probe.replace("PROBE", "server").replace("TYPE", "SERVER") CLIENT = 0 SERVER = 1 if args.stack: text = "#define NEED_STACK\n" + text usdt = USDT(pid=args.pid) if not args.server: usdt.enable_probe("http__client__request", "client_start") usdt.enable_probe("http__client__response", "client_end") if not args.client: usdt.enable_probe("http__server__request", "server_start") usdt.enable_probe("http__server__response", "server_end") bpf = BPF(text=text, usdt_contexts=[usdt], debug=DEBUG_PREPROCESSOR if args.debug else 0) class Data(ct.Structure): _fields_ = [ ("start_ns", ct.c_ulong), ("duration_ns", ct.c_ulong), ("port", ct.c_int), ("type", ct.c_int), ("stackid", ct.c_int), ("method", ct.c_char * 16), ("url", ct.c_char * 128), ("remote", ct.c_char * 128) ] delta = 0 prev_ts = 0 def print_event(cpu, data, size): global delta, prev_ts event = ct.cast(data, ct.POINTER(Data)).contents typ = "CLI" if event.type == CLIENT else "SVR" if prev_ts != 0: delta += event.start_ns - prev_ts prev_ts = event.start_ns print("%-14.9f %3s %11.3f %-16s %-5d %-8s %s" % (delta/1e9, typ, event.duration_ns/1e6, event.remote, event.port, event.method, event.url)) if args.stack: for addr in stacks.walk(event.stackid): print("\t%s" % bpf.sym(addr, args.pid, show_offset=True)) print("") bpf["events"].open_perf_buffer(print_event) if args.stack: stacks = bpf["stacks"] print("Snooping HTTP requests in Node process %d, Ctrl+C to quit." % args.pid) print("%-14s %3s %-11s %-16s %-5s %-8s %s" % ("TIME_s", "TYP", "DURATION_ms", "REMOTE", "PORT", "METHOD", "URL")) while 1: bpf.kprobe_poll()
2,610
589
// // KKJSBridgeConfig.h // KKJSBridge // // Created by <NAME> on 2019/7/25. // Copyright © 2019 karosli. All rights reserved. // #import <Foundation/Foundation.h> #import "KKJSBridgeAjaxDelegate.h" NS_ASSUME_NONNULL_BEGIN @class KKJSBridgeEngine; /** 配置 JSBridge 的行为,统一管理 Native 和 H5 侧对 JSBridge 的配置。 */ @interface KKJSBridgeConfig : NSObject - (instancetype)initWithEngine:(KKJSBridgeEngine *)engine; #pragma mark - 用于记录外部设置 /** 是否开启 ajax hook,默认是不开启的 讨论: 1、当需要关闭 ajax hook 时,建议联动取消 WKWebView 对 http/https 的注册,这样可以避免有些场景下 ajax hook 引起了严重不兼容的问题。 2、同时建议可以考虑建立黑名单机制,让服务器端下发黑名单对部分页面关闭该开关,宁可关闭对离线包的支持,也不能让这个页面不可用。 */ @property (nonatomic, assign, getter=isEnableAjaxHook) BOOL enableAjaxHook; /** 是否开启 cookie set hook,默认是开启的 讨论: 1、当开启 cookie set hook 时,document.cookie 的修改会通过异步 JSBridge 调用保存到 NSHTTPCookieStorage。 2、建议是开启的,因为任何场景下都是需要把手动设置的 cookie 同步给 NSHTTPCookieStorage。 Cookie 管理的理解: NSHTTPCookieStorage 是唯一读取和存储 Cookie 的仓库,此时是可以不用保证 WKWebView Cookie 是否是最新的,只需要保证 NSHTTPCookieStorage 是最新的,并且每个请求从 NSHTTPCookieStorage 读取 Cookie 即可。因为既然已经代理了请求,就应该全权使用 NSHTTPCookieStorage 存储的 Cookie,来避免 WKWebView 的 Cookie 不是最新的问题。 */ @property (nonatomic, assign, getter=isEnableCookieSetHook) BOOL enableCookieSetHook; /** 是否开启 cookie get hook,默认是开启的 讨论: 1、当同时开启了 ajax hook 和 cookie get hook,才需要把 document.cookie 的读取通过同步 JSBridge 调用从 NSHTTPCookieStorage 中读取 cookie。因为当非 ajax hook 情况下,说明是纯 WKWebView 的场景,那么 ajax 响应头里 Set-Cookie 只会存储在 WKCookie 里,所以此时是只能直接从 WKCookie 里读取 cookie 的。 2、这里单独把 cookie get hook 作为开关,是因为并不是所有的 H5 项目都是通过 document.cookie 去读取最新的 cookie,并做一些业务判断的,所以在这个情况下,是可以不用 hook cookie get 方法的。建议根据自己项目实际情况来决定是否需要开启 cookie get hook。 */ @property (nonatomic, assign, getter=isEnableCookieGetHook) BOOL enableCookieGetHook; /** ajax 请求回调管理器,一旦指定,JSBridge 引擎内部不会发送请求,而是把发送请求控制权交给该代理。前提是必须先开启 ajax hook。 请求代理没有必要一个 JSBridge 对应一个,而是所有 JSBridge 共用一个 */ @property (class, nonatomic, weak) id<KKJSBridgeAjaxDelegateManager> ajaxDelegateManager; @end NS_ASSUME_NONNULL_END
1,665
796
<reponame>mehrdad-shokri/backdoorme<gh_stars>100-1000 #This is a template for your use to add additional modules. Modules are used to make a backdoor more potent, stealthy, or dangerous, but feel free to add anything you think might help! Places you need to input are designated by ~tildes~. from .module import * class ~NAME~(Module): def __init__(self, target, command, core): self.core = core self.target = target self.name = "~NAME~" self.command = command self.options = { #~Add options to make your module more potent.~ } def exploit(self): #~ADD YOUR INSTRUCTIONS HERE. If you need th command, it is self.backdoor.get_command().~ print(GOOD + self.name + " module success") #Please add this to the backdoorme/modules/__init__.py file following the established convention.
296
453
<reponame>Public-Cloud-Projects/Zenko import socket import requests import requests.exceptions import pytest S3_ENDPOINTS = [ 's3.us-east-2.amazonaws.com', 's3-us-east-2.amazonaws.com', # TODO Extend this list, based on # https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region ] @pytest.mark.nondestructive @pytest.mark.conformance @pytest.mark.parametrize('s3_endpoint', S3_ENDPOINTS) def test_resolve_s3_endpoint(s3_endpoint): try: socket.gethostbyname(s3_endpoint) except socket.gaierror as exc: # Note: we use xfail here because it *may* be fine for resolving to # fail in some very restricted networks. # However, we want to report this when running conformance or # nondestructive testing. pytest.xfail('Failed to resolve host: {!r}'.format(exc)) @pytest.mark.nondestructive @pytest.mark.conformance @pytest.mark.parametrize('s3_endpoint', S3_ENDPOINTS) def test_tls_connect_s3_endpoint(s3_endpoint): try: requests.get('https://{}/'.format(s3_endpoint), verify=True) except socket.gaierror as exc: pytest.xfail('Failed to resolve host: {!r}'.format(exc)) except requests.exceptions.ConnectionError as exc: pytest.xfail('Failed to connect to host: {!r}'.format(exc))
536
1,539
{ "x-restler-global-annotations": [ { "producer_endpoint": "/service/user", "producer_method": "POST", "producer_resource_name": "user-id", "consumer_param": "user-id" } ] }
99
8,238
<filename>erts/lib_src/yielding_c_fun/ycf_lists.h /* * %CopyrightBegin% * * Copyright Ericsson AB and <NAME> 2019. 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. * * %CopyrightEnd% */ /* * Author: <NAME> */ #ifndef YIELDING_C_FUN_LISTS_H #define YIELDING_C_FUN_LISTS_H #include <stdlib.h> #include <stdio.h> #define INIT_LIST(L) \ do{ \ (L)->head = NULL; \ (L)->last = NULL; \ }while(0) #define APPEND_LIST(L,E) \ do{ \ void* e = E; \ if((L)->head == NULL){ \ (L)->head = e; \ } else { \ (L)->last->next = e; \ } \ (L)->last = e; \ }while(0) #define PREPEND_LIST(T,L,E) \ do{ \ T* e = E; \ if((L)->head == NULL){ \ (L)->last = e; \ } else { \ e->next = (L)->head; \ } \ (L)->head = e; \ }while(0) #define CONCAT_LIST(T,L1,L2) \ do{ \ T* current = (L2)->head; \ while(current != NULL){ \ APPEND_LIST(L1, current); \ current = current->next; \ } \ }while(0) #define PRINT_LIST(T,L, NAME) \ do{ \ printf("NAME %s\n", NAME); \ printf("HEAD %p\n", (L)->head); \ printf("LAST %p\n", (L)->last); \ printf("ELEMS:\n"); \ T* current = (L)->head; \ while(current != NULL){ \ printf("E: %p\n", current); \ current = current->next; \ } \ }while(0) #define REMOVE_LIST(T,L,E) \ do{ \ T* prev = NULL; \ T* rl_current = (L)->head; \ T* e = E; \ while(rl_current != e && rl_current != NULL){ \ prev = rl_current ; \ rl_current = rl_current ->next; \ } \ if(rl_current == NULL){ \ exit(1); \ } \ if(prev == NULL){ \ if((L)->head == (L)->last){ \ (L)->last = NULL; \ } \ (L)->head = (L)->head->next; \ }else{ \ if(rl_current == (L)->last){ \ (L)->last = prev; \ } \ prev->next = rl_current ->next; \ } \ }while(0) #define INSERT_AFTER_LIST(T,L,E,TO_INSERT) \ do{ \ T* current_y = (L)->head; \ T* elem_x = E; \ T* to_insert2 = TO_INSERT; \ if(elem_x == NULL){ \ PREPEND_LIST(T,L,to_insert2); \ break; \ }else if(elem_x == (L)->last){ \ APPEND_LIST(L,to_insert2); \ break; \ } \ while(current_y != elem_x && current_y != NULL){ \ current_y = current_y->next; \ } \ if(current_y == NULL){ \ printf("CANNOT INSERT AFTER NONEXISTING\n"); \ exit(1); \ } \ to_insert2->next = current_y->next; \ current_y->next = to_insert2; \ }while(0) #define INSERT_BEFORE_LIST(T,L,E_BEFORE,TO_INSERT) \ do{ \ T* prev_x = NULL; \ T* current_x = (L)->head; \ T* to_insert_x = TO_INSERT; \ T* e_before_x = E_BEFORE; \ while(current_x != e_before_x && current_x != NULL){ \ prev_x = current_x; \ current_x = current_x->next; \ } \ if(current_x == NULL){ \ printf("CANNOT INSERT AFTER NONEXISTING\n"); \ exit(1); \ } \ INSERT_AFTER_LIST(T,L,prev_x,to_insert_x); \ }while(0) #define REPLACE_LIST(T,L,OLD,NEW) \ do{ \ T* old = OLD; \ T* new = NEW; \ T* prev_old_next = old->next; \ INSERT_AFTER_LIST(T,L,old,new); \ REMOVE_LIST(T,L,old); \ old->next = prev_old_next; \ }while(0) /* list functions */ #define GENERATE_LIST_FUNCTIONS(NODE_TYPE) \ \ NODE_TYPE##_list NODE_TYPE##_list_empty(){ \ NODE_TYPE##_list list; \ INIT_LIST(&list); \ return list; \ } \ \ NODE_TYPE* NODE_TYPE##_shallow_copy(NODE_TYPE* n){ \ NODE_TYPE* new = ycf_malloc(sizeof(NODE_TYPE)); \ *new = *n; \ new->next = NULL; \ return new; \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_shallow_copy(NODE_TYPE##_list n){ \ NODE_TYPE##_list new; \ NODE_TYPE* current = n.head; \ INIT_LIST(&new); \ while(current != NULL){ \ APPEND_LIST(&new, NODE_TYPE##_shallow_copy(current)); \ current = current->next; \ } \ return new; \ } \ \ int NODE_TYPE##_list_get_item_position(NODE_TYPE##_list* list, NODE_TYPE* node){ \ NODE_TYPE* current = list->head; \ int pos = 0; \ while(current != NULL){ \ if(current == node){ \ return pos; \ } \ pos = pos + 1; \ current = current->next; \ } \ return -1; \ } \ \ NODE_TYPE* NODE_TYPE##_list_get_item_at_position(NODE_TYPE##_list* list, int pos){ \ NODE_TYPE* current = list->head; \ int current_pos = 0; \ while(current != NULL){ \ if(current_pos == pos){ \ return current; \ } \ current_pos = current_pos + 1; \ current = current->next; \ } \ return NULL; \ } \ \ void NODE_TYPE##_list_append(NODE_TYPE##_list* list, NODE_TYPE* node){ \ APPEND_LIST(list, node); \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_copy_append(NODE_TYPE##_list list, NODE_TYPE* node){ \ NODE_TYPE##_list list_copy = NODE_TYPE##_list_shallow_copy(list); \ NODE_TYPE* node_copy = NODE_TYPE##_shallow_copy(node); \ NODE_TYPE##_list_append(&list_copy, node_copy); \ return list_copy; \ } \ \ void NODE_TYPE##_list_prepend(NODE_TYPE##_list* list, NODE_TYPE* node){ \ PREPEND_LIST(NODE_TYPE, list, node); \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_copy_prepend(NODE_TYPE##_list list, NODE_TYPE* node){ \ NODE_TYPE##_list list_copy = NODE_TYPE##_list_shallow_copy(list); \ NODE_TYPE* node_copy = NODE_TYPE##_shallow_copy(node); \ NODE_TYPE##_list_prepend(&list_copy, node_copy); \ return list_copy; \ } \ \ void NODE_TYPE##_list_insert_before(NODE_TYPE##_list* list, NODE_TYPE* before_this, NODE_TYPE* to_insert_z){ \ INSERT_BEFORE_LIST(NODE_TYPE, list, before_this, to_insert_z); \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_copy_insert_before(NODE_TYPE##_list list, NODE_TYPE* before_this, NODE_TYPE* to_insert){ \ int pos = NODE_TYPE##_list_get_item_position(&list, before_this); \ NODE_TYPE##_list list_copy = NODE_TYPE##_list_shallow_copy(list);; \ NODE_TYPE* actual_this = NODE_TYPE##_list_get_item_at_position(&list_copy, pos); \ NODE_TYPE* to_insert_copy = NODE_TYPE##_shallow_copy(to_insert); \ NODE_TYPE##_list_insert_before(&list_copy, actual_this, to_insert_copy); \ return list_copy; \ } \ \ void NODE_TYPE##_list_insert_after(NODE_TYPE##_list* list, NODE_TYPE* after_this, NODE_TYPE* to_insert_z){ \ INSERT_AFTER_LIST(NODE_TYPE, list, after_this, to_insert_z); \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_copy_insert_after(NODE_TYPE##_list list, NODE_TYPE* after_this, NODE_TYPE* to_insert){ \ int pos = NODE_TYPE##_list_get_item_position(&list, after_this); \ NODE_TYPE##_list list_copy = NODE_TYPE##_list_shallow_copy(list); \ NODE_TYPE* actual_this = NODE_TYPE##_list_get_item_at_position(&list_copy, pos); \ NODE_TYPE* to_insert_copy = NODE_TYPE##_shallow_copy(to_insert); \ NODE_TYPE##_list_insert_after(&list_copy, actual_this, to_insert_copy); \ return list_copy; \ } \ \ void NODE_TYPE##_list_remove(NODE_TYPE##_list* list, NODE_TYPE* to_remove){ \ REMOVE_LIST(NODE_TYPE, list, to_remove); \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_copy_remove(NODE_TYPE##_list list, NODE_TYPE* to_remove){ \ int pos = NODE_TYPE##_list_get_item_position(&list, to_remove); \ NODE_TYPE##_list list_copy = NODE_TYPE##_list_shallow_copy(list); \ NODE_TYPE* actual_this = NODE_TYPE##_list_get_item_at_position(&list_copy, pos); \ NODE_TYPE##_list_remove(&list_copy, actual_this); \ return list_copy; \ } \ \ void NODE_TYPE##_list_replace(NODE_TYPE##_list* list, NODE_TYPE* to_replace, NODE_TYPE* replace_with){ \ REPLACE_LIST(NODE_TYPE, list, to_replace, replace_with); \ } \ \ NODE_TYPE##_list NODE_TYPE##_list_copy_replace(NODE_TYPE##_list list, NODE_TYPE* to_replace, NODE_TYPE* replace_with){ \ int pos = NODE_TYPE##_list_get_item_position(&list, to_replace); \ NODE_TYPE##_list list_copy = NODE_TYPE##_list_shallow_copy(list); \ NODE_TYPE* actual_this = NODE_TYPE##_list_get_item_at_position(&list_copy, pos); \ NODE_TYPE* replace_with_copy = NODE_TYPE##_shallow_copy(replace_with); \ NODE_TYPE##_list_replace(&list_copy, actual_this, replace_with_copy); \ return list_copy; \ } \ \ void NODE_TYPE##_list_concat(NODE_TYPE##_list* list1, NODE_TYPE##_list* list2){ \ CONCAT_LIST(NODE_TYPE, list1, list2); \ } \ NODE_TYPE##_list NODE_TYPE##_list_copy_concat(NODE_TYPE##_list list1, NODE_TYPE##_list list2){ \ NODE_TYPE##_list list1_copy = NODE_TYPE##_list_shallow_copy(list1); \ NODE_TYPE##_list list2_copy = NODE_TYPE##_list_shallow_copy(list2); \ CONCAT_LIST(NODE_TYPE, &list1_copy, &list2_copy); \ return list1_copy; \ } \ \ size_t NODE_TYPE##_list_length(NODE_TYPE##_list list){ \ NODE_TYPE* current = list.head; \ size_t count = 0; \ while(current != NULL){ \ count = count + 1; \ current = current->next; \ } \ return count; \ } /* void print_string_list(string_list n){ */ /* string_list_item* current = n.head; */ /* printf("START\n"); */ /* while(current != NULL){ */ /* printf("%s\n", current->str); */ /* current = current->next; */ /* } */ /* printf("END\n"); */ /* } */ #endif //YIELDING_C_FUN_LISTS_H
12,934
145,614
""" Implementation of regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). """ def match_pattern(input_string: str, pattern: str) -> bool: """ uses bottom-up dynamic programming solution for matching the input string with a given pattern. Runtime: O(len(input_string)*len(pattern)) Arguments -------- input_string: str, any string which should be compared with the pattern pattern: str, the string that represents a pattern and may contain '.' for single character matches and '*' for zero or more of preceding character matches Note ---- the pattern cannot start with a '*', because there should be at least one character before * Returns ------- A Boolean denoting whether the given string follows the pattern Examples ------- >>> match_pattern("aab", "c*a*b") True >>> match_pattern("dabc", "*abc") False >>> match_pattern("aaa", "aa") False >>> match_pattern("aaa", "a.a") True >>> match_pattern("aaab", "aa*") False >>> match_pattern("aaab", ".*") True >>> match_pattern("a", "bbbb") False >>> match_pattern("", "bbbb") False >>> match_pattern("a", "") False >>> match_pattern("", "") True """ len_string = len(input_string) + 1 len_pattern = len(pattern) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. dp = [[0 for i in range(len_pattern)] for j in range(len_string)] # since string of zero length match pattern of zero length dp[0][0] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1, len_string): dp[i][0] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1, len_pattern): dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1, len_string): for j in range(1, len_pattern): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: dp[i][j] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): dp[i][j] = dp[i - 1][j] else: dp[i][j] = 0 else: dp[i][j] = 0 return bool(dp[-1][-1]) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") input_string = "aab" pattern = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"{input_string} matches the given pattern {pattern}") else: print(f"{input_string} does not match with the given pattern {pattern}")
1,322
718
<reponame>plutoyuxie/mmgeneration _base_ = ['../singan/singan_fish.py'] model = dict( type='PESinGAN', generator=dict( type='SinGANMSGeneratorPE', interp_pad=True, noise_with_pad=True), discriminator=dict(norm_cfg=None)) train_cfg = dict(fixed_noise_with_pad=True) data = dict( train=dict( img_path='./data/singan/fish-crop.jpg', min_size=25, max_size=300, )) dist_params = dict(backend='nccl')
209
852
import FWCore.ParameterSet.Config as cms from CommonTools.ParticleFlow.Isolation.photonPFIsolationDepositsPFBRECO_cff import * from CommonTools.ParticleFlow.Isolation.photonPFIsolationValuesPFBRECO_cff import * pfPhotonIsolationPFBRECOTask = cms.Task( photonPFIsolationDepositsPFBRECOTask , photonPFIsolationValuesPFBRECOTask ) pfPhotonIsolationPFBRECOSequence = cms.Sequence(pfPhotonIsolationPFBRECOTask)
156
998
<filename>Source/Voxel/Private/VoxelRender/VoxelProcMeshBuffers.cpp // Copyright 2021 Phyronnaz #include "VoxelRender/VoxelProcMeshBuffers.h" #include "VoxelRender/IVoxelRenderer.h" #include "VoxelRender/VoxelRenderUtilities.h" DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelProcMeshMemory); DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelProcMeshMemory_Indices); DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelProcMeshMemory_Positions); DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelProcMeshMemory_Colors); DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelProcMeshMemory_Adjacency); DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelProcMeshMemory_UVsAndTangents); DECLARE_DWORD_ACCUMULATOR_STAT(TEXT("Num Voxel Proc Mesh Buffers"), STAT_NumVoxelProcMeshBuffers, STATGROUP_VoxelCounters); FVoxelProcMeshBuffers::FVoxelProcMeshBuffers() { INC_DWORD_STAT(STAT_NumVoxelProcMeshBuffers); } FVoxelProcMeshBuffers::~FVoxelProcMeshBuffers() { DEC_DWORD_STAT(STAT_NumVoxelProcMeshBuffers); DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelProcMeshMemory, LastAllocatedSize); #define UPDATE(Name) \ DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelProcMeshMemory_ ## Name, LastAllocatedSize_ ## Name); UPDATE(Indices); UPDATE(Positions); UPDATE(Colors); UPDATE(Adjacency); UPDATE(UVsAndTangents); #undef UPDATE } uint32 FVoxelProcMeshBuffers::GetAllocatedSize() const { return Guids.GetAllocatedSize() + VertexBuffers.StaticMeshVertexBuffer.GetResourceSize() + VertexBuffers.PositionVertexBuffer.GetNumVertices() * VertexBuffers.PositionVertexBuffer.GetStride() + VertexBuffers.ColorVertexBuffer.GetNumVertices() * VertexBuffers.ColorVertexBuffer.GetStride() + IndexBuffer.GetAllocatedSize() + AdjacencyIndexBuffer.GetAllocatedSize() + CollisionCubes.GetAllocatedSize(); } void FVoxelProcMeshBuffers::UpdateStats() { DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelProcMeshMemory, LastAllocatedSize); LastAllocatedSize = GetAllocatedSize(); INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelProcMeshMemory, LastAllocatedSize); #define UPDATE(Name, Size) \ DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelProcMeshMemory_ ## Name, LastAllocatedSize_ ## Name); \ LastAllocatedSize_ ## Name = Size; \ INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelProcMeshMemory_ ## Name, LastAllocatedSize_ ## Name); \ UPDATE(Indices, IndexBuffer.GetAllocatedSize()); UPDATE(Positions, VertexBuffers.PositionVertexBuffer.GetNumVertices() * VertexBuffers.PositionVertexBuffer.GetStride()); UPDATE(Colors, VertexBuffers.ColorVertexBuffer.GetNumVertices() * VertexBuffers.ColorVertexBuffer.GetStride()); UPDATE(Adjacency, AdjacencyIndexBuffer.GetAllocatedSize()); UPDATE(UVsAndTangents, VertexBuffers.StaticMeshVertexBuffer.GetResourceSize()); #undef UPDATE }
1,090
1,139
<gh_stars>1000+ package com.journaldev.io.readfile; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileUsingBufferedReader { public static void main(String[] args) { BufferedReader reader; char[] buffer = new char[10]; try { reader = new BufferedReader(new FileReader( "/Users/pankaj/Downloads/myfile.txt")); while (reader.read(buffer) != -1) { System.out.print(new String(buffer)); buffer = new char[10]; } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
225
322
<reponame>sumanth143/datepicker // // ViewController.h // // Created by <NAME> on 10.01.2015. // Copyright (c) 2015 Hydra Softworks. // Released under an MIT license: http://opensource.org/licenses/MIT // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
102
2,151
<gh_stars>1000+ // Copyright 2014 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. #include "content/renderer/media/webrtc/webrtc_uma_histograms.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; namespace content { class MockPerSessionWebRTCAPIMetrics : public PerSessionWebRTCAPIMetrics { public: MockPerSessionWebRTCAPIMetrics() {} using PerSessionWebRTCAPIMetrics::LogUsageOnlyOnce; MOCK_METHOD1(LogUsage, void(blink::WebRTCAPIName)); }; TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingGetUserMedia) { MockPerSessionWebRTCAPIMetrics metrics; EXPECT_CALL(metrics, LogUsage(_)).Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kGetUserMedia); } TEST(PerSessionWebRTCAPIMetrics, CallOngoingGetUserMedia) { MockPerSessionWebRTCAPIMetrics metrics; metrics.IncrementStreamCounter(); EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kGetUserMedia)).Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kGetUserMedia); } TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingGetMediaDevices) { MockPerSessionWebRTCAPIMetrics metrics; EXPECT_CALL(metrics, LogUsage(_)).Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kEnumerateDevices); } TEST(PerSessionWebRTCAPIMetrics, CallOngoingGetMediaDevices) { MockPerSessionWebRTCAPIMetrics metrics; metrics.IncrementStreamCounter(); EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kEnumerateDevices)) .Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kEnumerateDevices); } TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingRTCPeerConnection) { MockPerSessionWebRTCAPIMetrics metrics; EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection)); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); } TEST(PerSessionWebRTCAPIMetrics, NoCallOngoingMultiplePC) { MockPerSessionWebRTCAPIMetrics metrics; EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection)) .Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); } TEST(PerSessionWebRTCAPIMetrics, BeforeAfterCallMultiplePC) { MockPerSessionWebRTCAPIMetrics metrics; EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection)) .Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.IncrementStreamCounter(); metrics.IncrementStreamCounter(); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.DecrementStreamCounter(); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.DecrementStreamCounter(); EXPECT_CALL(metrics, LogUsage(blink::WebRTCAPIName::kRTCPeerConnection)) .Times(1); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); metrics.LogUsageOnlyOnce(blink::WebRTCAPIName::kRTCPeerConnection); } } // namespace content
1,190
572
from kivymd.app import MDApp from kivymd.uix.card import MDCard from kivymd.uix.floatlayout import FloatLayout from kivymd.uix.button import MDRaisedButton from kivy.lang import Builder from kivymd.uix.behaviors import FocusBehavior KV = ''' Screen: BoxLayout: orientation: 'vertical' MDToolbar: title: 'MyApp' left_action_items: [['menu', lambda x: x]] right_action_items: [['dots-vertical', lambda x: x]] TelaLogin: <SenhaCard>: id: card orientation: 'vertical' size_hint: .7, .7 pos_hint: {'center_x': .5, 'center_y': .5} MDBoxLayout: size_hint_y: .2 padding: [25, 0, 25, 0] md_bg_color: app.theme_cls.primary_color MDLabel: text: 'Mudar senha' theme_text_color: 'Custom' text_color: 1, 1, 1, 1 MDIconButton: theme_text_color: 'Custom' icon: 'close' text_color: 1, 1, 1, 1 on_release: root.fechar() MDFloatLayout: MDTextField: pos_hint: {'center_x': .5, 'center_y': .8} size_hint_x: .9 hint_text: 'Código enviado por email' MDTextField: pos_hint: {'center_x': .5, 'center_y': .6} size_hint_x: .9 hint_text: 'Nova senha:' MDTextField: pos_hint: {'center_x': .5, 'center_y': .4} size_hint_x: .9 hint_text: 'Confirmar nova senha:' ButtonFocus: pos_hint: {'center_x': .5, 'center_y': .2} size_hint_x: .9 text: 'Recadastrar!' <TelaLogin>: MDIconButton: pos_hint: {'center_x': .5, 'center_y': .8} icon: 'language-python' user_font_size: '75sp' MDTextField: size_hint_x: .9 hint_text: 'Email:' pos_hint: {'center_x': .5, 'center_y': .6} MDTextField: size_hint_x: .9 hint_text: 'Senha:' pos_hint: {'center_x': .5, 'center_y': .5} ButtonFocus: size_hint_x: .9 pos_hint: {'center_x': .5, 'center_y': .4} text: 'Login' focus_color: app.theme_cls.accent_color unfocus_color: app.theme_cls.primary_color MDLabel: pos_hint: {'center_y': .3} halign: 'center' text: 'Esqueceu sua senha?' MDTextButton: pos_hint: {'center_x': .5, 'center_y': .2} text: 'Clique Aqui!' on_release: root.abrir_card() ''' class ButtonFocus(MDRaisedButton, FocusBehavior): ... class SenhaCard(MDCard): def fechar(self): self.parent.remove_widget(self) class TelaLogin(FloatLayout): def abrir_card(self): self.add_widget(SenhaCard()) class MyApp(MDApp): def build(self): self.theme_cls.primary_palette = 'Purple' self.theme_cls.accent_palette = 'Red' self.theme_cls.primary_hue = '700' # self.theme_cls.theme_style = 'Dark' return Builder.load_string(KV) MyApp().run()
1,597
460
#include "../../../src/declarative/graphicsitems/qdeclarativeevents_p_p.h"
30
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"3ème circonscription","dpt":"Orne","inscrits":83,"abs":34,"votants":49,"blancs":6,"nuls":0,"exp":43,"res":[{"nuance":"REM","nom":"<NAME>","voix":26},{"nuance":"LR","nom":"<NAME>","voix":17}]}
107
5,964
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "EGL/egl.h" static GrGLFuncPtr angle_get_gl_proc(void* ctx, const char name[]) { GrGLFuncPtr proc = (GrGLFuncPtr) GetProcAddress((HMODULE)ctx, name); if (proc) { return proc; } return eglGetProcAddress(name); } const GrGLInterface* GrGLCreateANGLEInterface() { static HMODULE ghANGLELib = NULL; if (NULL == ghANGLELib) { // We load the ANGLE library and never let it go ghANGLELib = LoadLibrary("libGLESv2.dll"); } if (NULL == ghANGLELib) { // We can't setup the interface correctly w/o the DLL return NULL; } return GrGLAssembleGLESInterface(ghANGLELib, angle_get_gl_proc); }
377
9,959
<gh_stars>1000+ class SynchronizedNameStaticToInstanceRef { private Object read = new Object(); private static Object READ = new Object(); @lombok.Synchronized("read") static void test3() { System.out.println("three"); } }
76
642
<gh_stars>100-1000 #include <llvm-c/Core.h> #include <llvm-c/OrcBindings.h> #include <llvm-c/TargetMachine.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LegacyPassManager.h> #include "OrcJit.h" namespace llvm { DEFINE_SIMPLE_CONVERSION_FUNCTIONS(std::shared_ptr<llvm::Module>, LLVMSharedModuleRef) DEFINE_SIMPLE_CONVERSION_FUNCTIONS(llvm::TargetMachine, LLVMTargetMachineRef) } extern "C" { LLVMTargetMachineRef LLVMAxiomSelectTarget() { return llvm::wrap(llvm::EngineBuilder().selectTarget()); } // Builder utilities void LLVMAxiomSetFastMathFlags(LLVMBuilderRef builder, bool allowReassoc, bool noNans, bool noInfs, bool noSignedZeros, bool allowReciprocal, bool allowContract, bool approxFunc) { llvm::FastMathFlags flags; if (allowReassoc) flags.setAllowReassoc(); if (noNans) flags.setNoNaNs(); if (noInfs) flags.setNoInfs(); if (noSignedZeros) flags.setNoSignedZeros(); if (allowReciprocal) flags.setAllowReciprocal(); flags.setAllowContract(allowContract); if (approxFunc) flags.setApproxFunc(); llvm::unwrap(builder)->setFastMathFlags(flags); } void LLVMAxiomSetAllFastMathFlags(LLVMBuilderRef builder) { llvm::FastMathFlags flags; flags.setFast(); llvm::unwrap(builder)->setFastMathFlags(flags); } // JIT functions OrcJit *LLVMAxiomOrcCreateInstance(LLVMTargetMachineRef targetMachine) { auto jit = new OrcJit(*llvm::unwrap(targetMachine)); // libc memory functions jit->addBuiltin("memcpy", (uint64_t) & ::memcpy); jit->addBuiltin("memset", (uint64_t) & ::memset); jit->addBuiltin("realloc", (uint64_t) & ::realloc); jit->addBuiltin("free", (uint64_t) & ::free); #ifdef APPLE jit->addBuiltin("__bzero", (uint64_t) & ::bzero); #endif return jit; } void LLVMAxiomOrcAddBuiltin(OrcJit *jit, const char *name, LLVMOrcTargetAddress address) { jit->addBuiltin(name, address); } LLVMOrcModuleHandle LLVMAxiomOrcAddModule(OrcJit *jit, LLVMSharedModuleRef module) { return jit->addModule(std::move(*llvm::unwrap(module))); } void LLVMAxiomOrcRemoveModule(OrcJit *jit, LLVMOrcModuleHandle handle) { jit->removeModule(handle); } LLVMOrcTargetAddress LLVMAxiomOrcGetSymbolAddress(OrcJit *jit, const char *name) { return jit->getSymbolAddress(name); } void LLVMAxiomOrcDisposeInstance(OrcJit *jit) { delete jit; } }
998
448
<reponame>miniksa/BuildXL<filename>Public/Src/Sandbox/Windows/DetoursServices/Assertions.cpp // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "stdafx.h" _declspec(noinline) void _fail_assert() { RaiseFailFastException(nullptr, nullptr, FAIL_FAST_GENERATE_EXCEPTION_ADDRESS); __assume(0); // Unreachable }
154
787
// OJ: https://leetcode.com/problems/dice-roll-simulation/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(N) // Ref: https://leetcode.com/problems/dice-roll-simulation/discuss/403756/Java-Share-my-DP-solution class Solution { public: int dieSimulator(int n, vector<int>& A) { long mod = 1e9+7; vector<vector<long>> dp(n, vector<long>(7)); for (int i = 0; i < 6; ++i) dp[0][i] = 1; dp[0][6] = 6; for (int i = 1; i < n; ++i) { long sum = 0; for (int j = 0; j < 6; ++j) { dp[i][j] = dp[i - 1][6]; if (i < A[j]) sum = (sum + dp[i][j]) % mod; else { if (i - A[j] - 1 >= 0) dp[i][j] = (dp[i][j] - (dp[i - A[j] - 1][6] - dp[i - A[j] - 1][j]) + mod) % mod; else dp[i][j] = (dp[i][j] - 1) % mod; sum = (sum + dp[i][j]) % mod; } } dp[i][6] = sum; } return dp[n - 1][6]; } };
616
516
package org.asciidoctor.jruby.internal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.asciidoctor.Options; import org.asciidoctor.SafeMode; import org.asciidoctor.jruby.cli.AsciidoctorCliOptions; public class AsciidoctorUtils { private static final String RUNNER = "asciidoctor"; private AsciidoctorUtils() { super(); } public static boolean isOptionWithAttribute(Map<String, Object> options, String attributeName, String attributeValue) { if(options.containsKey(Options.ATTRIBUTES)) { Map<String, Object> attributes = (Map<String, Object>) options.get(Options.ATTRIBUTES); if(attributes.containsKey(attributeName)) { String configuredAttributeValue = (String) attributes.get(attributeName); if(configuredAttributeValue.equals(attributeValue)) { return true; } } } return false; } public static List<String> toAsciidoctorCommand(Map<String, Object> options, String inputPath) { List<String> command = new ArrayList<>(); command.add(RUNNER); command.addAll(getOptions(options)); command.add(inputPath); return command; } private static List<String> getOptions(Map<String, Object> options) { List<String> optionsAndAttributes = new ArrayList<>(); if (options.containsKey(Options.DESTINATION_DIR)) { optionsAndAttributes.add(AsciidoctorCliOptions.DESTINATION_DIR); optionsAndAttributes.add(options.get(Options.DESTINATION_DIR).toString()); } if (options.containsKey(Options.BASEDIR)) { optionsAndAttributes.add(AsciidoctorCliOptions.BASE_DIR); optionsAndAttributes.add(options.get(Options.BASEDIR).toString()); } if (options.containsKey(Options.TEMPLATE_DIRS)) { List<String> templates = (List<String>) options.get(Options.TEMPLATE_DIRS); for (String template : templates) { optionsAndAttributes.add(AsciidoctorCliOptions.TEMPLATE_DIR); optionsAndAttributes.add(template); } } if (options.containsKey(Options.TEMPLATE_ENGINE)) { optionsAndAttributes.add(AsciidoctorCliOptions.TEMPLATE_ENGINE); optionsAndAttributes.add(options.get(Options.TEMPLATE_ENGINE).toString()); } if (options.containsKey(Options.COMPACT)) { optionsAndAttributes.add(AsciidoctorCliOptions.COMPACT); } if (options.containsKey(Options.ERUBY)) { optionsAndAttributes.add(AsciidoctorCliOptions.ERUBY); optionsAndAttributes.add(options.get(Options.ERUBY).toString()); } if (options.containsKey(Options.HEADER_FOOTER)) { optionsAndAttributes.add(AsciidoctorCliOptions.NO_HEADER_FOOTER); } if (options.containsKey(Options.SAFE)) { Integer level = (Integer) options.get(Options.SAFE); SafeMode getSafeMode = SafeMode.safeMode(level); optionsAndAttributes.add(AsciidoctorCliOptions.SAFE); optionsAndAttributes.add(getSafeMode.toString()); } if (options.containsKey(Options.TO_FILE)) { optionsAndAttributes.add(AsciidoctorCliOptions.OUTFILE); optionsAndAttributes.add(options.get(Options.TO_FILE).toString()); } if (options.containsKey(Options.DOCTYPE)) { optionsAndAttributes.add(AsciidoctorCliOptions.DOCTYPE); optionsAndAttributes.add(options.get(Options.DOCTYPE).toString()); } if (options.containsKey(Options.BACKEND)) { optionsAndAttributes.add(AsciidoctorCliOptions.BACKEND); optionsAndAttributes.add(options.get(Options.BACKEND).toString()); } if (options.containsKey(Options.ATTRIBUTES)) { optionsAndAttributes.addAll(getAttributesSyntax((Map<String, Object>) options.get(Options.ATTRIBUTES))); } return optionsAndAttributes; } private static List<String> getAttributesSyntax(Map<String, Object> attributes) { List<String> attributesOutput = new ArrayList<>(); Set<Entry<String, Object>> entrySet = attributes.entrySet(); for (Entry<String, Object> entry : entrySet) { attributesOutput.addAll( getAttributeSyntax(entry.getKey(), entry.getValue())); } return attributesOutput; } private static List<String> getAttributeSyntax(String attributeName, Object attributeValue) { List<String> attribute = new ArrayList<>(); attribute.add("-a"); StringBuilder argument = new StringBuilder(attributeName); if (attributeValue != null && !"".equals(attributeValue.toString().trim())) { argument.append("="); argument.append(attributeValue.toString()); } if(attributeValue == null) { argument.append("!"); } attribute.add(argument.toString()); return attribute; } }
2,378
578
<filename>resources/profile_generator/profile_test.py<gh_stars>100-1000 import os import sys import string import shutil import random profile_number = 50 root_name = 'duck_test' if os.path.isdir(root_name): shutil.rmtree(root_name) os.mkdir(root_name) color_pool = [8, 16, 32, 64] def get_random_name(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=5)) def get_random_colors(): ret = '' for item in random.choices(color_pool, k=3): ret += str(item) + ' ' return ret root_dir = os.path.join(".", root_name) for x in range(1, profile_number + 1): profile_dir_name = os.path.join(root_dir, 'profile' + str(x) + "_" + get_random_name()) os.mkdir(profile_dir_name) config_name = os.path.join(profile_dir_name, 'config.txt') config_content = '' for y in range(1, 16): config_content += 'z' + str(y) + ' ' + get_random_name() + "\n" for y in range(1, 16): config_content += 'SWCOLOR_' + str(y) + ' ' + get_random_colors() + "\n" print(config_content) with open(config_name, 'w') as config_file: config_file.write(config_content) for y in range(1, 16): script_name = os.path.join(profile_dir_name, 'key' + str(y) + '.txt') script_content = 'STRING ' + get_random_name() + '\nENTER\n' with open(script_name, 'w') as script_file: script_file.write(script_content)
531
324
<reponame>wuxianxingkong/octo-ns /* * Copyright (c) 2011-2018, <NAME>. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.meituan.octo.mns; import com.meituan.octo.mns.model.SGAgentClient; import com.meituan.octo.mns.util.IpUtil; import com.octo.naming.common.thrift.model.SGService; import com.octo.naming.service.thrift.model.ServiceAgent; import org.apache.commons.lang3.StringUtils; import org.apache.thrift.TException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RegistryManager { private static final Logger LOG = LoggerFactory.getLogger(RegistryManager.class); private final ServiceAgent.Iface tempClient = new InvokeProxy(SGAgentClient.ClientType.temp).getProxy(); private ExecutorService executors = Executors.newFixedThreadPool(1); public void registerServiceWithCmd(final int cmd, final SGService sgService) throws TException { if (!isSGServiceValid(sgService)) { return; } executors.submit(new Runnable() { @Override public void run() { try { synchronized (tempClient) { LOG.info("Mns service provider registration, cmd ={} | param = {}", cmd, sgService.toString()); tempClient.registServicewithCmd(cmd, sgService); } } catch (Exception e) { LOG.error(e.getMessage(), e); } } }); } public void unRegisterService(final SGService sgService) throws TException { if (!isSGServiceValid(sgService)) { return; } executors.submit(new Runnable() { @Override public void run() { try { synchronized (tempClient) { LOG.info("Mns service provider unRegistration, param = {}", sgService.toString()); tempClient.unRegistService(sgService); } } catch (Exception e) { LOG.error(e.getMessage(), e); } } }); } private static boolean isSGServiceValid(SGService service) { if (null == service) { LOG.error("Cannot register null."); return false; } int port = service.getPort(); String appkey = service.getAppkey(); String ip = service.getIp(); if (port < 1) { LOG.error("Invalid port: port|" + port + "|appkey:" + appkey); return false; } if (StringUtils.isEmpty(appkey)) { LOG.error("Invalid appKey: appkey|" + appkey); return false; } if (!IpUtil.checkIP(ip)) { LOG.error("Invalid ip: ip|" + ip + "|appkey:" + appkey); return false; } return true; } }
1,628
4,345
<reponame>awesome-archive/Coding-iOS // // FileInfoViewController.h // Coding_iOS // // Created by Ease on 15/8/20. // Copyright (c) 2015年 Coding. All rights reserved. // #import "BaseViewController.h" #import "ProjectFile.h" @interface FileInfoViewController : BaseViewController + (instancetype)vcWithFile:(ProjectFile *)file; @end
121
1,707
<gh_stars>1000+ #pragma once //------------------------------------------------------------------------------ /** @brief Cocoa input-related defines (taken from and compatible with GLFW) */ #define ORYOL_OSXBRIDGE_WHEEL_DELTA 120 #define ORYOL_OSXBRIDGE_MOD_SHIFT 0x0001 #define ORYOL_OSXBRIDGE_MOD_CONTROL 0x0002 #define ORYOL_OSXBRIDGE_MOD_ALT 0x0004 #define ORYOL_OSXBRIDGE_MOD_SUPER 0x0008 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_1 0 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_2 1 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_3 2 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_4 3 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_5 4 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_6 5 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_7 6 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_8 7 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_LAST ORYOL_OSXBRIDGE_MOUSE_BUTTON_8 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_LEFT ORYOL_OSXBRIDGE_MOUSE_BUTTON_1 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_RIGHT ORYOL_OSXBRIDGE_MOUSE_BUTTON_2 #define ORYOL_OSXBRIDGE_MOUSE_BUTTON_MIDDLE ORYOL_OSXBRIDGE_MOUSE_BUTTON_3 #define ORYOL_OSXBRIDGE_RELEASE 0 #define ORYOL_OSXBRIDGE_PRESS 1 #define ORYOL_OSXBRIDGE_REPEAT 2 #define ORYOL_OSXBRIDGE_CURSOR 0x00033001 #define ORYOL_OSXBRIDGE_STICKY_KEYS 0x00033002 #define ORYOL_OSXBRIDGE_STICKY_MOUSE_BUTTONS 0x00033003 #define ORYOL_OSXBRIDGE_CURSOR_NORMAL 0x00034001 #define ORYOL_OSXBRIDGE_CURSOR_HIDDEN 0x00034002 #define ORYOL_OSXBRIDGE_CURSOR_DISABLED 0x00034003 #define ORYOL_OSXBRIDGE_KEY_INVALID -2 #define ORYOL_OSXBRIDGE_KEY_UNKNOWN -1 #define ORYOL_OSXBRIDGE_KEY_SPACE 32 #define ORYOL_OSXBRIDGE_KEY_APOSTROPHE 39 /* ' */ #define ORYOL_OSXBRIDGE_KEY_COMMA 44 /* , */ #define ORYOL_OSXBRIDGE_KEY_MINUS 45 /* - */ #define ORYOL_OSXBRIDGE_KEY_PERIOD 46 /* . */ #define ORYOL_OSXBRIDGE_KEY_SLASH 47 /* / */ #define ORYOL_OSXBRIDGE_KEY_0 48 #define ORYOL_OSXBRIDGE_KEY_1 49 #define ORYOL_OSXBRIDGE_KEY_2 50 #define ORYOL_OSXBRIDGE_KEY_3 51 #define ORYOL_OSXBRIDGE_KEY_4 52 #define ORYOL_OSXBRIDGE_KEY_5 53 #define ORYOL_OSXBRIDGE_KEY_6 54 #define ORYOL_OSXBRIDGE_KEY_7 55 #define ORYOL_OSXBRIDGE_KEY_8 56 #define ORYOL_OSXBRIDGE_KEY_9 57 #define ORYOL_OSXBRIDGE_KEY_SEMICOLON 59 /* ; */ #define ORYOL_OSXBRIDGE_KEY_EQUAL 61 /* = */ #define ORYOL_OSXBRIDGE_KEY_A 65 #define ORYOL_OSXBRIDGE_KEY_B 66 #define ORYOL_OSXBRIDGE_KEY_C 67 #define ORYOL_OSXBRIDGE_KEY_D 68 #define ORYOL_OSXBRIDGE_KEY_E 69 #define ORYOL_OSXBRIDGE_KEY_F 70 #define ORYOL_OSXBRIDGE_KEY_G 71 #define ORYOL_OSXBRIDGE_KEY_H 72 #define ORYOL_OSXBRIDGE_KEY_I 73 #define ORYOL_OSXBRIDGE_KEY_J 74 #define ORYOL_OSXBRIDGE_KEY_K 75 #define ORYOL_OSXBRIDGE_KEY_L 76 #define ORYOL_OSXBRIDGE_KEY_M 77 #define ORYOL_OSXBRIDGE_KEY_N 78 #define ORYOL_OSXBRIDGE_KEY_O 79 #define ORYOL_OSXBRIDGE_KEY_P 80 #define ORYOL_OSXBRIDGE_KEY_Q 81 #define ORYOL_OSXBRIDGE_KEY_R 82 #define ORYOL_OSXBRIDGE_KEY_S 83 #define ORYOL_OSXBRIDGE_KEY_T 84 #define ORYOL_OSXBRIDGE_KEY_U 85 #define ORYOL_OSXBRIDGE_KEY_V 86 #define ORYOL_OSXBRIDGE_KEY_W 87 #define ORYOL_OSXBRIDGE_KEY_X 88 #define ORYOL_OSXBRIDGE_KEY_Y 89 #define ORYOL_OSXBRIDGE_KEY_Z 90 #define ORYOL_OSXBRIDGE_KEY_LEFT_BRACKET 91 /* [ */ #define ORYOL_OSXBRIDGE_KEY_BACKSLASH 92 /* \ */ #define ORYOL_OSXBRIDGE_KEY_RIGHT_BRACKET 93 /* ] */ #define ORYOL_OSXBRIDGE_KEY_GRAVE_ACCENT 96 /* ` */ #define ORYOL_OSXBRIDGE_KEY_WORLD_1 161 /* non-US #1 */ #define ORYOL_OSXBRIDGE_KEY_WORLD_2 162 /* non-US #2 */ #define ORYOL_OSXBRIDGE_KEY_ESCAPE 256 #define ORYOL_OSXBRIDGE_KEY_ENTER 257 #define ORYOL_OSXBRIDGE_KEY_TAB 258 #define ORYOL_OSXBRIDGE_KEY_BACKSPACE 259 #define ORYOL_OSXBRIDGE_KEY_INSERT 260 #define ORYOL_OSXBRIDGE_KEY_DELETE 261 #define ORYOL_OSXBRIDGE_KEY_RIGHT 262 #define ORYOL_OSXBRIDGE_KEY_LEFT 263 #define ORYOL_OSXBRIDGE_KEY_DOWN 264 #define ORYOL_OSXBRIDGE_KEY_UP 265 #define ORYOL_OSXBRIDGE_KEY_PAGE_UP 266 #define ORYOL_OSXBRIDGE_KEY_PAGE_DOWN 267 #define ORYOL_OSXBRIDGE_KEY_HOME 268 #define ORYOL_OSXBRIDGE_KEY_END 269 #define ORYOL_OSXBRIDGE_KEY_CAPS_LOCK 280 #define ORYOL_OSXBRIDGE_KEY_SCROLL_LOCK 281 #define ORYOL_OSXBRIDGE_KEY_NUM_LOCK 282 #define ORYOL_OSXBRIDGE_KEY_PRINT_SCREEN 283 #define ORYOL_OSXBRIDGE_KEY_PAUSE 284 #define ORYOL_OSXBRIDGE_KEY_F1 290 #define ORYOL_OSXBRIDGE_KEY_F2 291 #define ORYOL_OSXBRIDGE_KEY_F3 292 #define ORYOL_OSXBRIDGE_KEY_F4 293 #define ORYOL_OSXBRIDGE_KEY_F5 294 #define ORYOL_OSXBRIDGE_KEY_F6 295 #define ORYOL_OSXBRIDGE_KEY_F7 296 #define ORYOL_OSXBRIDGE_KEY_F8 297 #define ORYOL_OSXBRIDGE_KEY_F9 298 #define ORYOL_OSXBRIDGE_KEY_F10 299 #define ORYOL_OSXBRIDGE_KEY_F11 300 #define ORYOL_OSXBRIDGE_KEY_F12 301 #define ORYOL_OSXBRIDGE_KEY_F13 302 #define ORYOL_OSXBRIDGE_KEY_F14 303 #define ORYOL_OSXBRIDGE_KEY_F15 304 #define ORYOL_OSXBRIDGE_KEY_F16 305 #define ORYOL_OSXBRIDGE_KEY_F17 306 #define ORYOL_OSXBRIDGE_KEY_F18 307 #define ORYOL_OSXBRIDGE_KEY_F19 308 #define ORYOL_OSXBRIDGE_KEY_F20 309 #define ORYOL_OSXBRIDGE_KEY_F21 310 #define ORYOL_OSXBRIDGE_KEY_F22 311 #define ORYOL_OSXBRIDGE_KEY_F23 312 #define ORYOL_OSXBRIDGE_KEY_F24 313 #define ORYOL_OSXBRIDGE_KEY_F25 314 #define ORYOL_OSXBRIDGE_KEY_KP_0 320 #define ORYOL_OSXBRIDGE_KEY_KP_1 321 #define ORYOL_OSXBRIDGE_KEY_KP_2 322 #define ORYOL_OSXBRIDGE_KEY_KP_3 323 #define ORYOL_OSXBRIDGE_KEY_KP_4 324 #define ORYOL_OSXBRIDGE_KEY_KP_5 325 #define ORYOL_OSXBRIDGE_KEY_KP_6 326 #define ORYOL_OSXBRIDGE_KEY_KP_7 327 #define ORYOL_OSXBRIDGE_KEY_KP_8 328 #define ORYOL_OSXBRIDGE_KEY_KP_9 329 #define ORYOL_OSXBRIDGE_KEY_KP_DECIMAL 330 #define ORYOL_OSXBRIDGE_KEY_KP_DIVIDE 331 #define ORYOL_OSXBRIDGE_KEY_KP_MULTIPLY 332 #define ORYOL_OSXBRIDGE_KEY_KP_SUBTRACT 333 #define ORYOL_OSXBRIDGE_KEY_KP_ADD 334 #define ORYOL_OSXBRIDGE_KEY_KP_ENTER 335 #define ORYOL_OSXBRIDGE_KEY_KP_EQUAL 336 #define ORYOL_OSXBRIDGE_KEY_LEFT_SHIFT 340 #define ORYOL_OSXBRIDGE_KEY_LEFT_CONTROL 341 #define ORYOL_OSXBRIDGE_KEY_LEFT_ALT 342 #define ORYOL_OSXBRIDGE_KEY_LEFT_SUPER 343 #define ORYOL_OSXBRIDGE_KEY_RIGHT_SHIFT 344 #define ORYOL_OSXBRIDGE_KEY_RIGHT_CONTROL 345 #define ORYOL_OSXBRIDGE_KEY_RIGHT_ALT 346 #define ORYOL_OSXBRIDGE_KEY_RIGHT_SUPER 347 #define ORYOL_OSXBRIDGE_KEY_MENU 348 #define ORYOL_OSXBRIDGE_KEY_LAST ORYOL_OSXBRIDGE_KEY_MENU
4,919
365
<filename>extern/audaspace/include/fx/Envelope.h /******************************************************************************* * Copyright 2009-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. ******************************************************************************/ #pragma once /** * @file Envelope.h * @ingroup fx * The Envelope class. */ #include "fx/Effect.h" AUD_NAMESPACE_BEGIN class CallbackIIRFilterReader; struct EnvelopeParameters; /** * This sound creates an envelope follower reader. */ class AUD_API Envelope : public Effect { private: /** * The attack value in seconds. */ const float m_attack; /** * The release value in seconds. */ const float m_release; /** * The threshold value. */ const float m_threshold; /** * The attack/release threshold value. */ const float m_arthreshold; // delete copy constructor and operator= Envelope(const Envelope&) = delete; Envelope& operator=(const Envelope&) = delete; public: /** * Creates a new envelope sound. * \param sound The input sound. * \param attack The attack value in seconds. * \param release The release value in seconds. * \param threshold The threshold value. * \param arthreshold The attack/release threshold value. */ Envelope(std::shared_ptr<ISound> sound, float attack, float release, float threshold, float arthreshold); virtual std::shared_ptr<IReader> createReader(); /** * The envelopeFilter function implements the doFilterIIR callback * for the callback IIR filter. * @param reader The CallbackIIRFilterReader that executes the callback. * @param param The envelope parameters. * @return The filtered sample. */ static sample_t AUD_LOCAL envelopeFilter(CallbackIIRFilterReader* reader, EnvelopeParameters* param); /** * The endEnvelopeFilter function implements the endFilterIIR callback * for the callback IIR filter. * @param param The envelope parameters. */ static void AUD_LOCAL endEnvelopeFilter(EnvelopeParameters* param); }; AUD_NAMESPACE_END
725
2,260
#ifndef AISTATEMACHINE_H_ #define AISTATEMACHINE_H_ #include "AIState.h" namespace gameplay { class AIAgent; /** * Defines a simple AI state machine that can be used to program logic * for an AIAgent in a game. * * A state machine uses AIState objects to represent different states * of an object in the game. The state machine provides access to the * current state of an AI agent and it controls state changes as well. * When a new state is set, the stateExited event will be called for the * previous state, the stateEntered event will be called for the new state * and then the stateUpdate event will begin to be called each frame * while the new state is active. * * Communication of state changes is facilitated through the AIMessage class. * Messages are dispatched by the AIController and can be used for purposes * other than state changes as well. Messages may be sent to the state * machines of any other agents in a game and can contain any arbitrary * information. This mechanism provides a simple, flexible and easily * debuggable method for communicating between AI objects in a game. */ class AIStateMachine { friend class AIAgent; friend class AIState; public: /** * Returns the AIAgent that owns this state machine. * * @return The AIAgent that owns this state machine. */ AIAgent* getAgent() const; /** * Creates and adds a new state to the state machine. * * @param id ID of the new state. * * @return The newly created and added state. */ AIState* addState(const char* id); /** * Adds a state to the state machine. * * The specified state may be shared by other state machines. * Its reference count is increased while it is held by * this state machine. * * @param state The state to add. */ void addState(AIState* state); /** * Removes a state from the state machine. * * @param state The state to remove. */ void removeState(AIState* state); /** * Returns a state registered with this state machine. * * @param id The ID of the state to return. * * @return The state with the given ID, or NULL if no such state exists. */ AIState* getState(const char* id) const; /** * Returns the active state for this state machine. * * @return The active state for this state machine. */ AIState* getActiveState() const; /** * Changes the state of this state machine to the given state. * * If no state with the given ID exists within this state machine, * this method does nothing. * * @param id The ID of the new state. * * @return The new state, or NULL if no matching state could be found. */ AIState* setState(const char* id); /** * Changes the state of this state machine to the given state. * * If the given state is not registered with this state machine, * this method does nothing. * * @param state The new state. * * @return true if the state is successfully changed, false otherwise. */ bool setState(AIState* state); private: /** * Constructor. */ AIStateMachine(AIAgent* agent); /** * Destructor. */ ~AIStateMachine(); /** * Hidden copy constructor. */ AIStateMachine(const AIStateMachine&); /** * Hidden copy assignment operator. */ AIStateMachine& operator=(const AIStateMachine&); /** * Sends a message to change the state of this state machine. */ void sendChangeStateMessage(AIState* newState); /** * Changes the active state of the state machine. */ void setStateInternal(AIState* state); /** * Determines if the specified state exists within this state machine. */ bool hasState(AIState* state) const; /** * Called by AIController to update the state machine each frame. */ void update(float elapsedTime); AIAgent* _agent; AIState* _currentState; std::list<AIState*> _states; }; } #endif
1,397
1,540
<filename>testng-core/src/test/java/test/ignore/ignorePackage/IgnorePackageSample.java package test.ignore.ignorePackage; import org.testng.annotations.Test; public class IgnorePackageSample { @Test public void test() {} @Test public void test2() {} }
83
1,986
<reponame>PleXone2019/-esp32-snippets /** * Create a new BLE server. */ #include "BLEDevice.h" #include "BLEServer.h" #include "BLEUtils.h" #include "BLE2902.h" #include "BLEHIDDevice.h" #include "HIDKeyboardTypes.h" #include <esp_log.h> #include <string> #include <Task.h> #include "sdkconfig.h" static char LOG_TAG[] = "SampleHIDDevice"; static BLEHIDDevice* hid; BLECharacteristic* input; BLECharacteristic* output; /* * This callback is connect with output report. In keyboard output report report special keys changes, like CAPSLOCK, NUMLOCK * We can add digital pins with LED to show status * bit 1 - NUM LOCK * bit 2 - CAPS LOCK * bit 3 - SCROLL LOCK */ class MyOutputCallbacks : public BLECharacteristicCallbacks { void onWrite(BLECharacteristic* me){ uint8_t* value = (uint8_t*)(me->getValue().c_str()); ESP_LOGI(LOG_TAG, "special keys: %d", *value); } }; class MyTask : public Task { void run(void*){ vTaskDelay(5000/portTICK_PERIOD_MS); // wait 5 seconds before send first message while(1){ const char* hello = "Hello world from esp32 hid keyboard!!!\n"; while(*hello){ KEYMAP map = keymap[(uint8_t)*hello]; /* * simulate keydown, we can send up to 6 keys */ uint8_t a[] = {map.modifier, 0x0, map.usage, 0x0,0x0,0x0,0x0,0x0}; input->setValue(a,sizeof(a)); input->notify(); /* * simulate keyup */ uint8_t v[] = {0x0, 0x0, 0x0, 0x0,0x0,0x0,0x0,0x0}; input->setValue(v, sizeof(v)); input->notify(); hello++; vTaskDelay(10/portTICK_PERIOD_MS); } vTaskDelay(2000/portTICK_PERIOD_MS); // simulate write message every 2 seconds } } }; MyTask *task; class MyCallbacks : public BLEServerCallbacks { void onConnect(BLEServer* pServer){ task->start(); } void onDisconnect(BLEServer* pServer){ task->stop(); } }; class MainBLEServer: public Task { void run(void *data) { ESP_LOGD(LOG_TAG, "Starting BLE work!"); task = new MyTask(); BLEDevice::init("ESP32"); BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyCallbacks()); /* * Instantiate hid device */ hid = new BLEHIDDevice(pServer); input = hid->inputReport(1); // <-- input REPORTID from report map output = hid->outputReport(1); // <-- output REPORTID from report map output->setCallbacks(new MyOutputCallbacks()); /* * Set manufacturer name (OPTIONAL) * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.manufacturer_name_string.xml */ std::string name = "esp-community"; hid->manufacturer()->setValue(name); /* * Set pnp parameters (MANDATORY) * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.pnp_id.xml */ hid->pnp(0x02, 0xe502, 0xa111, 0x0210); /* * Set hid informations (MANDATORY) * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.hid_information.xml */ hid->hidInfo(0x00,0x01); /* * Keyboard */ const uint8_t reportMap[] = { USAGE_PAGE(1), 0x01, // Generic Desktop Ctrls USAGE(1), 0x06, // Keyboard COLLECTION(1), 0x01, // Application REPORT_ID(1), 0x01, // REPORTID USAGE_PAGE(1), 0x07, // Kbrd/Keypad USAGE_MINIMUM(1), 0xE0, USAGE_MAXIMUM(1), 0xE7, LOGICAL_MINIMUM(1), 0x00, LOGICAL_MAXIMUM(1), 0x01, REPORT_SIZE(1), 0x01, // 1 byte (Modifier) REPORT_COUNT(1), 0x08, INPUT(1), 0x02, // Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position REPORT_COUNT(1), 0x01, // 1 byte (Reserved) REPORT_SIZE(1), 0x08, INPUT(1), 0x01, // Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position REPORT_COUNT(1), 0x05, // 5 bits (Num lock, Caps lock, Scroll lock, Compose, Kana) REPORT_SIZE(1), 0x01, USAGE_PAGE(1), 0x08, // LEDs USAGE_MINIMUM(1), 0x01, // Num Lock USAGE_MAXIMUM(1), 0x05, // Kana OUTPUT(1), 0x02, // Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile REPORT_COUNT(1), 0x01, // 3 bits (Padding) REPORT_SIZE(1), 0x03, OUTPUT(1), 0x01, // Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile REPORT_COUNT(1), 0x06, // 6 bytes (Keys) REPORT_SIZE(1), 0x08, LOGICAL_MINIMUM(1), 0x00, LOGICAL_MAXIMUM(1), 0x65, // 101 keys USAGE_PAGE(1), 0x07, // Kbrd/Keypad USAGE_MINIMUM(1), 0x00, USAGE_MAXIMUM(1), 0x65, INPUT(1), 0x00, // Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position END_COLLECTION(0) }; /* * Set report map (here is initialized device driver on client side) (MANDATORY) * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.report_map.xml */ hid->reportMap((uint8_t*)reportMap, sizeof(reportMap)); /* * We are prepared to start hid device services. Before this point we can change all values and/or set parameters we need. * Also before we start, if we want to provide battery info, we need to prepare battery service. * We can setup characteristics authorization */ hid->startServices(); /* * Its good to setup advertising by providing appearance and advertised service. This will let clients find our device by type */ BLEAdvertising *pAdvertising = pServer->getAdvertising(); pAdvertising->setAppearance(HID_KEYBOARD); pAdvertising->addServiceUUID(hid->hidService()->getUUID()); pAdvertising->start(); BLESecurity *pSecurity = new BLESecurity(); pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND); ESP_LOGD(LOG_TAG, "Advertising started!"); delay(1000000); } }; void SampleHID(void) { //esp_log_level_set("*", ESP_LOG_DEBUG); MainBLEServer* pMainBleServer = new MainBLEServer(); pMainBleServer->setStackSize(20000); pMainBleServer->start(); } // app_main
2,666
348
<reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t2/029/02906205.json {"nom":"Plounévézel","circ":"6ème circonscription","dpt":"Finistère","inscrits":914,"abs":376,"votants":538,"blancs":35,"nuls":4,"exp":499,"res":[{"nuance":"REM","nom":"<NAME>","voix":385},{"nuance":"LR","nom":"<NAME>","voix":114}]}
131
746
package org.protege.editor.owl.ui.breadcrumb; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.semanticweb.owlapi.model.OWLObject; import java.util.Optional; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.mockito.Mockito.mock; @RunWith(MockitoJUnitRunner.class) public class Breadcrumb_TestCase { private Breadcrumb breadcrumb; @Mock private OWLObject object; @Mock private Object parentRelationship; @Before public void setUp() { breadcrumb = new Breadcrumb(object, parentRelationship); } @SuppressWarnings("ConstantConditions") @Test(expected = NullPointerException.class) public void shouldThrowNullPointerExceptionIf_object_IsNull() { new Breadcrumb(null, parentRelationship); } @Test public void shouldReturnSupplied_object() { assertThat(breadcrumb.getObject(), is(this.object)); } @Test public void shouldReturnSupplied_parentRelationship() { assertThat(breadcrumb.getParentRelationship(), is(Optional.of(this.parentRelationship))); } @Test public void shouldBeEqualToSelf() { assertThat(breadcrumb, is(breadcrumb)); } @Test @SuppressWarnings("ObjectEqualsNull") public void shouldNotBeEqualToNull() { assertThat(breadcrumb.equals(null), is(false)); } @Test public void shouldBeEqualToOther() { assertThat(breadcrumb, is(new Breadcrumb(object, parentRelationship))); } @Test public void shouldNotBeEqualToOtherThatHasDifferent_object() { assertThat(breadcrumb, is(not(new Breadcrumb(mock(OWLObject.class), parentRelationship)))); } @Test public void shouldNotBeEqualToOtherThatHasDifferent_parentRelationship() { assertThat(breadcrumb, is(not(new Breadcrumb(object, mock(Object.class))))); } @Test public void shouldBeEqualToOtherHashCode() { assertThat(breadcrumb.hashCode(), is(new Breadcrumb(object, parentRelationship).hashCode())); } @Test public void shouldImplementToString() { assertThat(breadcrumb.toString(), Matchers.startsWith("Breadcrumb")); } }
923
467
from urllib.request import urlopen import urllib.parse import webbrowser from sys import platform import os if platform == "linux" or platform == "linux2": chrome_path = '/usr/bin/google-chrome' elif platform == "darwin": chrome_path = 'open -a /Applications/Google\ Chrome.app' elif platform == "win32": chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' else: print('Unsupported OS') exit(1) webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path)) def youtube(textToSearch): query = urllib.parse.quote(textToSearch) url = "https://www.youtube.com/results?search_query=" + query webbrowser.get('chrome').open_new_tab(url) if __name__ == '__main__': youtube('any text')
264
1,442
<filename>ion/src/device/n0100/kernel/drivers/config/led.h #ifndef ION_DEVICE_N0100_KERNEL_DRIVERS_CONFIG_LED_H #define ION_DEVICE_N0100_KERNEL_DRIVERS_CONFIG_LED_H #include <regs/regs.h> namespace Ion { namespace Device { namespace LED { namespace Config { using namespace Regs; static constexpr int RedChannel = 2; static constexpr int GreenChannel = 4; static constexpr int BlueChannel = 3; constexpr static AFGPIOPin RGBPins[] = { AFGPIOPin(GPIOC, 7, GPIO::AFR::AlternateFunction::AF2, GPIO::PUPDR::Pull::None, GPIO::OSPEEDR::OutputSpeed::Low), // RED AFGPIOPin(GPIOB, 1, GPIO::AFR::AlternateFunction::AF2, GPIO::PUPDR::Pull::None, GPIO::OSPEEDR::OutputSpeed::Low), // GREEN AFGPIOPin(GPIOB, 0, GPIO::AFR::AlternateFunction::AF2, GPIO::PUPDR::Pull::None, GPIO::OSPEEDR::OutputSpeed::Low) // BLUE }; } } } } #endif
331
435
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. */ #import <Foundation/Foundation.h> /** View Controller put into FBMemoryProfilerContainerViewController should implement this protocol. It's what container will use to interact with the view controller, inform him when it's being moved, etc. */ @protocol FBMemoryProfilerMovableViewController <NSObject> /** Container will move view controller (either by pan or pinch). */ - (void)containerWillMove:(nonnull UIViewController *)container; /** Should view should stretch on pinch? */ - (BOOL)shouldStretchInMovableContainer; /** @return minimum height that view controllers must have */ - (CGFloat)minimumHeightInMovableContainer; @end
230
1,350
<filename>sdk/digitaltwins/azure-digitaltwins-core/src/test/java/com/azure/digitaltwins/core/EventRoutesTestBase.java<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.digitaltwins.core; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.logging.ClientLogger; import com.azure.digitaltwins.core.models.DigitalTwinsEventRoute; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; /** * This abstract test class defines all the tests that both the sync and async event route test classes need to implement. It also * houses some event route test specific helper functions. */ public abstract class EventRoutesTestBase extends DigitalTwinsTestBase { private final ClientLogger logger = new ClientLogger(EventRoutesTestBase.class); static final String EVENT_ROUTE_ENDPOINT_NAME = "someEventHubEndpoint"; static final String FILTER = "$eventType = 'DigitalTwinTelemetryMessages' or $eventType = 'DigitalTwinLifecycleNotification'"; @Test public abstract void eventRouteLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) throws InterruptedException; @Test public abstract void getEventRouteThrowsIfEventRouteDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion); @Test public abstract void createEventRouteThrowsIfFilterIsMalformed(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion); @Test public abstract void listEventRoutesPaginationWorks(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion); // Azure Digital Twins instances have a low cap on the number of event routes allowed, so we need to delete the existing // event routes before each test to make sure that we can add an event route in each test. @BeforeEach public void removeAllEventRoutes() { // Using sync client for simplicity. This function isn't testing the clients, so no need to use both sync and async clients for cleanup DigitalTwinsClient client = getDigitalTwinsClientBuilder(null, DigitalTwinsServiceVersion.getLatest()).buildClient(); PagedIterable<DigitalTwinsEventRoute> listedEventRoutes = client.listEventRoutes(); List<String> currentEventRouteIds = new ArrayList<>(); for (DigitalTwinsEventRoute listedEventRoute : listedEventRoutes) { currentEventRouteIds.add(listedEventRoute.getEventRouteId()); } for (String eventRouteId : currentEventRouteIds) { logger.info("Deleting event route " + eventRouteId + " before running the next test"); client.deleteEventRoute(eventRouteId); } } // Note that only service returned eventRoute instances have their Id field set. When a user builds an instance locally, // there is no way to assign an Id to it. protected static void assertEventRoutesEqual(DigitalTwinsEventRoute expected, String expectedId, DigitalTwinsEventRoute actual) { assertEquals(expectedId, actual.getEventRouteId()); assertEquals(expected.getEndpointName(), actual.getEndpointName()); assertEquals(expected.getFilter(), actual.getFilter()); } }
1,039
2,151
<filename>native_client/tests/pnacl_dynamic_loading/test_pll_tls.c /* * Copyright (c) 2016 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* This is an example library, for testing the ConvertToPSO pass. */ /* Test thread-local variables (TLS) */ extern int module_a_var; /* * Test zero-initialized (BSS) variables. Test that they are placed at the * end of the TLS template even if they appear first in the IR or source. */ __thread int tls_bss_var1; __thread int tls_bss_var_aligned __attribute__((aligned(256))); __thread int tls_var1 = 123; __thread int *tls_var2 = &module_a_var; __thread int tls_var_aligned __attribute__((aligned(256))) = 345; extern __thread int tls_var_exported1; extern __thread int tls_var_exported2; int *get_tls_bss_var1(void) { return &tls_bss_var1; } int *get_tls_bss_var_aligned(void) { return &tls_bss_var_aligned; } int *get_tls_var1(void) { return &tls_var1; } /* Test handling of ConstantExprs. */ int *get_tls_var1_addend(void) { return &tls_var1 + 1; } int **get_tls_var2(void) { return &tls_var2; } int *get_tls_var_aligned(void) { return &tls_var_aligned; } int *get_tls_var_exported1(void) { return &tls_var_exported1; } int *get_tls_var_exported2(void) { return &tls_var_exported2; }
539
332
<reponame>ericrbg/lean<filename>src/checker/text_import.cpp /* Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #include "checker/text_import.h" #include "kernel/environment.h" #include "kernel/inductive/inductive.h" #include "kernel/type_checker.h" #include "util/sstream.h" #include <string> #include <iostream> #include <unordered_map> #include "kernel/quotient/quotient.h" #include "checker/simple_pp.h" #include "kernel/ext_exception.h" namespace lean { template <typename Fn> void wrap_exception(name const & decl_name, environment const & env, Fn const & fn) { try { fn(); } catch (ext_exception & ex) { throw throwable(sstream() << decl_name << ": " << ex.pp(formatter(options(), [&] (expr const & e, options const &) { return simple_pp(env, e, lowlevel_notations()); }))); } } struct text_importer { std::unordered_map<unsigned, expr> m_expr; std::unordered_map<unsigned, name> m_name; std::unordered_map<unsigned, level> m_level; lowlevel_notations m_notations; environment m_env; bool m_verbose; text_importer(environment const & env, bool verbose) : m_env(env), m_verbose(verbose) { m_level[0] = {}; m_name[0] = {}; } levels read_levels(std::istream & in) { unsigned idx; buffer<level> ls; while (in >> idx) { ls.push_back(m_level.at(idx)); } in.clear(); return to_list(ls); } level_param_names read_level_params(std::istream & in) { unsigned idx; buffer<name> ls; while (in >> idx) { ls.push_back(m_name.at(idx)); } in.clear(); return to_list(ls); } void handle_ind(std::istream & in) { auto start = std::chrono::steady_clock::now(); unsigned num_params, name_idx, type_idx, num_intros; in >> num_params >> name_idx >> type_idx >> num_intros; buffer<inductive::intro_rule> intros; for (unsigned i = 0; i < num_intros; i++) { unsigned name_idx, type_idx; in >> name_idx >> type_idx; intros.push_back(inductive::mk_intro_rule(m_name.at(name_idx), m_expr.at(type_idx))); } auto ls = read_level_params(in); inductive::inductive_decl decl(m_name.at(name_idx), ls, num_params, m_expr.at(type_idx), to_list(intros)); wrap_exception(decl.m_name, m_env, [&] { m_env = inductive::add_inductive(m_env, decl, true).first; }); if (m_verbose) { auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff_s = end - start; std::cerr << diff_s.count() << " s: " << decl.m_name << std::endl; } } void handle_def(std::istream & in) { auto start = std::chrono::steady_clock::now(); unsigned name_idx, type_idx, val_idx; in >> name_idx >> type_idx >> val_idx; auto ls = read_level_params(in); name n = m_name.at(name_idx); wrap_exception(n, m_env, [&] { auto decl = type_checker(m_env).is_prop(m_expr.at(type_idx)) ? mk_theorem(n, ls, m_expr.at(type_idx), m_expr.at(val_idx)) : mk_definition(m_env, n, ls, m_expr.at(type_idx), m_expr.at(val_idx), true, true); m_env = m_env.add(check(m_env, decl, true)); }); if (m_verbose) { auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff_s = end - start; std::cerr << diff_s.count() << " s: " << n << std::endl; } } void handle_ax(std::istream & in) { auto start = std::chrono::steady_clock::now(); unsigned name_idx, type_idx; in >> name_idx >> type_idx; auto ls = read_level_params(in); name n = m_name.at(name_idx); wrap_exception(n, m_env, [&] { m_env = m_env.add(check(m_env, mk_axiom(n, ls, m_expr.at(type_idx)))); }); if (m_verbose) { auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff_s = end - start; std::cerr << diff_s.count() << " s: " << n << std::endl; } } void handle_notation(std::istream & in, lowlevel_notation_kind kind) { unsigned name_idx, prec; in >> name_idx >> prec; std::string token; std::getline(in, token); if (!token.empty() && token.front()) token.erase(token.begin()); if (!token.empty() && token.back() == '\n') token.erase(token.end() - 1); m_notations[m_name.at(name_idx)] = { kind, token, prec }; } binder_info read_binder_info(std::string const & tok) { if (tok == "#BI") { return mk_implicit_binder_info(); } else if (tok == "#BS") { return mk_strict_implicit_binder_info(); } else if (tok == "#BC") { return mk_inst_implicit_binder_info(); } else if (tok == "#BD") { return {}; } else { throw exception(sstream() << "unknown binder info: " << tok); } } void handle_line(std::string const & line) { std::istringstream in(line); unsigned idx; std::string cmd; in >> cmd; if (cmd == "#IND") { handle_ind(in); } else if (cmd == "#DEF") { handle_def(in); } else if (cmd == "#AX") { handle_ax(in); } else if (cmd == "#QUOT") { m_env = declare_quotient(m_env); } else if (cmd == "#PREFIX") { handle_notation(in, lowlevel_notation_kind::Prefix); } else if (cmd == "#POSTFIX") { handle_notation(in, lowlevel_notation_kind::Postfix); } else if (cmd == "#INFIX") { handle_notation(in, lowlevel_notation_kind::Infix); } else if (std::istringstream(cmd) >> idx) { std::string kind; in >> kind; if (kind == "#NS") { unsigned p; std::string limb; in >> p >> std::skipws >> limb; m_name[idx] = name(m_name.at(p), limb.c_str()); } else if (kind == "#NI") { unsigned p, limb; in >> p >> limb; m_name[idx] = name(m_name.at(p), limb); } else if (kind == "#US") { unsigned l1; in >> l1; m_level[idx] = mk_succ(m_level.at(l1)); } else if (kind == "#UM") { unsigned l1, l2; in >> l1 >> l2; m_level[idx] = mk_max(m_level.at(l1), m_level.at(l2)); } else if (kind == "#UIM") { unsigned l1, l2; in >> l1 >> l2; m_level[idx] = mk_imax(m_level.at(l1), m_level.at(l2)); } else if (kind == "#UP") { unsigned i1; in >> i1; m_level[idx] = mk_param_univ(m_name.at(i1)); } else if (kind == "#EV") { unsigned v; in >> v; m_expr[idx] = mk_var(v); } else if (kind == "#ES") { unsigned l; in >> l; m_expr[idx] = mk_sort(m_level.at(l)); } else if (kind == "#EC") { unsigned n; in >> n; auto ls = read_levels(in); m_expr[idx] = mk_constant(m_name.at(n), ls); } else if (kind == "#EA") { unsigned e1, e2; in >> e1 >> e2; m_expr[idx] = mk_app(m_expr.at(e1), m_expr.at(e2)); } else if (kind == "#EZ") { unsigned n, t, v, b; in >> n >> t >> v >> b; m_expr[idx] = mk_let(m_name.at(n), m_expr.at(t), m_expr.at(v), m_expr.at(b)); } else if (kind == "#EL") { unsigned n, t, e; std::string b; in >> b >> n >> t >> e; m_expr[idx] = mk_lambda(m_name.at(n), m_expr.at(t), m_expr.at(e), read_binder_info(b)); } else if (kind == "#EP") { unsigned n, t, e; std::string b; in >> b >> n >> t >> e; m_expr[idx] = mk_pi(m_name.at(n), m_expr.at(t), m_expr.at(e), read_binder_info(b)); } else { throw exception(sstream() << "unknown term definition kind: " << kind); } } else { throw exception(sstream() << "unknown command: " << cmd); } if (!in.eof()) in >> std::ws; if (in.fail() || !in.eof()) { throw exception(sstream() << "parse error"); } } }; void import_from_text(std::istream & in, environment & env, lowlevel_notations & notations, bool verbose) { text_importer importer(env, verbose); std::string line; unsigned line_num = 0; while (std::getline(in, line)) { line_num++; try { importer.handle_line(line); } catch (throwable & t) { throw exception(sstream() << "line " << line_num << ": " << t.what()); } catch (std::exception & e) { throw exception(sstream() << "line " << line_num << ": " << e.what()); } } env = importer.m_env; notations = std::move(importer.m_notations); } }
4,734
1,102
/****************************************************************************** Created by <NAME>, 2016, <EMAIL> This file is part of the LibBoolEE library. This program is free software: you can redistribute it and/or modify it under the terms of the GNU lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "LibBoolEE.h" std::vector<std::string> LibBoolEE::singleParse(const std::string & formula, const char op, ErrorReport* errorReport) { int start_pos = -1; int parity_count = 0; std::vector<std::string> subexpressions; for (int i = 0; i < static_cast<int>(formula.size()); i++) { if (formula[i] == ')') { parity_count--; } else if (formula[i] == '(') { parity_count++; if (start_pos == -1) { start_pos = i; } } else if (parity_count == 0) { if (start_pos == -1) { if (belongsToName(formula[i]) || formula[i] == '!') { start_pos = i; } } else if (!(belongsToName(formula[i]) || formula[i] == '!')) { if (op == formula[i]) { subexpressions.push_back(formula.substr(start_pos, i - start_pos)); start_pos = i+1; } else if (formula[i] != '&' && formula[i] != '|') { if (errorReport) { errorReport->type = ErrorReport::ErrorType::EmptySubExpression; errorReport->vecUserData.emplace_back(std::string(1, formula[i])); errorReport->vecUserData.emplace_back(formula); errorReport->strDevData = "invalid-verifier-unknown-operator-in-expression"; } throw std::runtime_error("Unknown operator '" + std::string(1, formula[i]) + "' in the (sub)expression '" + formula + "'."); } } } } if (start_pos != -1) { subexpressions.push_back(formula.substr(start_pos, formula.size() - start_pos)); } if (parity_count != 0) { if (errorReport) { errorReport->type = ErrorReport::ErrorType::ParenthesisParity; errorReport->vecUserData.emplace_back(formula); errorReport->strDevData = "invalid-verifier-parenthesis-parity"; } throw std::runtime_error("Wrong parenthesis parity in the (sub)expression '" + formula + "'."); } return subexpressions; } bool LibBoolEE::resolve(const std::string &source, const Vals & valuation, ErrorReport* errorReport) { return resolveRec(removeWhitespaces(source), valuation, errorReport); } bool LibBoolEE::resolveRec(const std::string &source, const Vals & valuation, ErrorReport* errorReport) { if (source.empty()) { if (errorReport) { errorReport->type = ErrorReport::ErrorType::EmptySubExpression; errorReport->vecUserData.emplace_back(source); errorReport->strDevData = "bad-txns-null-verifier-empty-sub-expression"; } throw std::runtime_error("An empty subexpression was encountered"); } std::string formula = source; char current_op = '|'; // Try to divide by | std::vector<std::string> subexpressions = singleParse(source, current_op, errorReport); // No | on the top level if (subexpressions.size() == 1) { current_op = '&'; subexpressions = singleParse(source, current_op, errorReport); } // No valid name found if (subexpressions.size() == 0) { if (errorReport) { errorReport->type = ErrorReport::ErrorType::InvalidQualifierName; errorReport->vecUserData.emplace_back(source); errorReport->strDevData = "bad-txns-null-verifier-no-sub-expressions"; } throw std::runtime_error("The subexpression " + source + " is not a valid formula."); } // No binary top level operator found else if (subexpressions.size() == 1) { if (source[0] == '!') { return !resolve(source.substr(1), valuation, errorReport); } else if (source[0] == '(') { return resolve(source.substr(1, source.size() - 2), valuation, errorReport); } else if (source == "1") { return true; } else if (source == "0") { return false; } else if (valuation.count(source) == 0) { if (errorReport) { errorReport->type = ErrorReport::ErrorType::VariableNotFound; errorReport->vecUserData.emplace_back(source); errorReport->strDevData = "bad-txns-null-verifier-variable-not-found"; } throw std::runtime_error("Variable '" + source + "' not found in the interpretation."); } else { return valuation.at(source); } } else { if (current_op == '|') { bool result = false; for (std::vector<std::string>::iterator it = subexpressions.begin(); it != subexpressions.end(); it++) { result |= resolve(*it, valuation, errorReport); } return result; } else { // The operator was set to & bool result = true; for (std::vector<std::string>::iterator it = subexpressions.begin(); it != subexpressions.end(); it++) { result &= resolve(*it, valuation, errorReport); } return result; } } } std::string LibBoolEE::trim(const std::string &source) { static const std::string WHITESPACES = " \n\r\t\v\f"; const size_t front = source.find_first_not_of(WHITESPACES); return source.substr(front, source.find_last_not_of(WHITESPACES) - front + 1); } bool LibBoolEE::belongsToName(const char ch) { return isalnum(ch) || ch == '_' || ch == '#' || ch == '.'; } std::string LibBoolEE::removeWhitespaces(const std::string &source) { std::string result; for (int i = 0; i < static_cast<int>(source.size()); i++) { if (!isspace(source.at(i))) { result += source.at(i); } } return result; } std::string LibBoolEE::removeCharacter(const std::string &source, const char ch) { std::string result; for (int i = 0; i < static_cast<int>(source.size()); i++) { if (ch != source.at(i)) { result += source.at(i); } } return result; }
3,036
1,047
<gh_stars>1000+ #include "pch.h" #include "MeshSync/SceneGraph/msScene.h" #include "MeshSync/SceneGraph/msAnimation.h" namespace ms { template<class T> struct Equals { bool operator()(const T& a, const T& b) const { return mu::near_equal(a, b); } }; template<> struct Equals<int> { bool operator()(int a, int b) const { return a == b; } }; template<class T> static size_t GetSize(const AnimationCurve& self) { TAnimationCurve<T> data(self); return data.size(); } template<> size_t GetSize<void>(const AnimationCurve& /*self*/) { return 0; } template<class T> static void* At(const AnimationCurve& self, size_t i) { TAnimationCurve<T> data(self); return &data[i]; } template<> void* At<void>(const AnimationCurve& /*self*/, size_t /*i*/) { return nullptr; } template<class T> static void ReserveKeyframes(AnimationCurve& self, size_t n) { TAnimationCurve<T> data(self); data.reserve(n); } template<> void ReserveKeyframes<void>(AnimationCurve& /*self*/, size_t /*n*/) {} template<class T> static void ReduceKeyframes(AnimationCurve& self, bool keep_flat_curve) { TAnimationCurve<T> data(self); if (data.size() <= 1) return; auto last_key = data.back(); while (data.size() >= 2) { if (Equals<T>()(data[data.size()-2].value, data.back().value)) data.pop_back(); else break; } if (data.size() == 1) { if (keep_flat_curve) data.push_back(last_key); // keep at least 2 keys to prevent Unity's warning else data.clear(); } } template<> void ReduceKeyframes<void>(AnimationCurve& /*self*/, bool /*keep_flat_curve*/) {} struct AnimationCurveFunctionSet { size_t(*size)(const AnimationCurve& self); void*(*at)(const AnimationCurve& self, size_t i); void(*reserve_keyframes)(AnimationCurve& self, size_t n); void(*reduce_keyframes)(AnimationCurve& self, bool keep_flat_curve); }; #define EachDataTypes(Body)\ Body(void) Body(int) Body(float) Body(mu::float2) Body(mu::float3) Body(mu::float4) Body(mu::quatf) #define DefFunctionSet(T) {&GetSize<T>, &At<T>, &ReserveKeyframes<T>, &ReduceKeyframes<T>}, static AnimationCurveFunctionSet g_curve_fs[] = { EachDataTypes(DefFunctionSet) }; #undef DefFunctionSet std::shared_ptr<AnimationCurve> AnimationCurve::create(std::istream& is) { auto ret = AnimationCurve::create(); ret->deserialize(is); return ret; } AnimationCurve::AnimationCurve() {} AnimationCurve::~AnimationCurve() {} #define EachMember(F) F(name) F(data) F(data_type) F(data_flags) void AnimationCurve::serialize(std::ostream& os) const { EachMember(msWrite); } void AnimationCurve::deserialize(std::istream& is) { EachMember(msRead); } void AnimationCurve::clear() { name.clear(); data.clear(); data_type = DataType::Unknown; data_flags = {}; idata.clear(); } uint64_t AnimationCurve::hash() const { uint64_t ret = 0; ret += vhash(data); return ret; } template<> inline uint64_t csum(const AnimationCurve::DataFlags& v) { return (uint32_t&)v; } uint64_t AnimationCurve::checksum() const { uint64_t ret = 0; EachMember(msCSum); return ret; } size_t AnimationCurve::size() const { return g_curve_fs[(int)data_type].size(*this); } bool AnimationCurve::empty() const { return data.empty(); } template<class T> TVP<T>& AnimationCurve::at(size_t i) { return *(TVP<T>*)g_curve_fs[(int)data_type].at(*this, i); } #define Instantiate(T) template TVP<T>& AnimationCurve::at(size_t i); EachDataTypes(Instantiate) #undef Instantiate void AnimationCurve::reserve(size_t size) { g_curve_fs[(int)data_type].reserve_keyframes(*this, size); } #undef EachMember std::shared_ptr<Animation> Animation::create(std::istream & is) { auto ret = Animation::create(); ret->deserialize(is); return ret; } Animation::Animation() {} Animation::~Animation() {} void Animation::serialize(std::ostream & os) const { write(os, entity_type); write(os, path); write(os, curves); } void Animation::deserialize(std::istream & is) { read(is, entity_type); read(is, path); read(is, curves); } void Animation::clear() { entity_type = EntityType::Unknown; path.clear(); curves.clear(); } uint64_t Animation::hash() const { uint64_t ret = 0; for (auto& c : curves) ret += c->hash(); return ret; } uint64_t Animation::checksum() const { uint64_t ret = 0; for (auto& c : curves) ret += c->checksum(); return ret; } bool Animation::empty() const { return curves.empty(); } void Animation::reserve(size_t n) { for (auto& c : curves) c->reserve(n); } bool Animation::isRoot() const { return path.find_last_of('/') == 0; } AnimationCurvePtr Animation::findCurve(const char *name) const { auto it = std::lower_bound(curves.begin(), curves.end(), name, [](auto& curve, auto name) { return std::strcmp(curve->name.c_str(), name) < 0; }); if (it != curves.end() && (*it)->name == name) return *it; return nullptr; } AnimationCurvePtr Animation::findCurve(const std::string& name) const { return findCurve(name.c_str()); } AnimationCurvePtr Animation::findCurve(const char *name, DataType type) const { auto ret = findCurve(name); if (ret && ret->data_type == type) return ret; return nullptr; } AnimationCurvePtr Animation::findCurve(const std::string& name, DataType type) const { return findCurve(name.c_str(), type); } AnimationCurvePtr Animation::addCurve(const char *name, DataType type) { auto it = std::lower_bound(curves.begin(), curves.end(), name, [](auto& curve, auto name) { return std::strcmp(curve->name.c_str(), name) < 0; }); if (it != curves.end() && (*it)->name == name) { auto& ret = *it; // clear existing one ret->data.clear(); ret->data_type = type; return ret; } else { auto ret = AnimationCurve::create(); ret->name = name; ret->data_type = type; curves.insert(it, ret); return ret; } } AnimationCurvePtr Animation::addCurve(const std::string& name, DataType type) { return addCurve(name.c_str(), type); } AnimationCurvePtr Animation::getCurve(const char *name, DataType type) { auto it = std::lower_bound(curves.begin(), curves.end(), name, [](auto& curve, auto name) { return std::strcmp(curve->name.c_str(), name) < 0; }); if (it != curves.end() && (*it)->name == name) return *it; auto ret = AnimationCurve::create(); ret->name = name; ret->data_type = type; curves.insert(it, ret); return ret; } AnimationCurvePtr Animation::getCurve(const std::string& name, DataType type) { return getCurve(name.c_str(), type); } bool Animation::eraseCurve(const AnimationCurve *curve) { auto it = std::find_if(curves.begin(), curves.end(), [&](auto& c) {return c.get() == curve; }); if (it != curves.end()) { curves.erase(it); return true; } return false; } void Animation::clearEmptyCurves() { curves.erase( std::remove_if(curves.begin(), curves.end(), [](auto& c) { return c->empty(); }), curves.end()); } void Animation::validate(AnimationPtr& anim) { switch (anim->entity_type) { case EntityType::Transform: TransformAnimation::create(anim)->validate(); break; case EntityType::Camera: CameraAnimation::create(anim)->validate(); break; case EntityType::Light: LightAnimation::create(anim)->validate(); break; case EntityType::Mesh: MeshAnimation::create(anim)->validate(); break; case EntityType::Points: // no PointsAnimation for now TransformAnimation::create(anim)->validate(); break; default: break; } anim->clearEmptyCurves(); } #define EachMember(F) F(frame_rate) F(animations) std::shared_ptr<AnimationClip> AnimationClip::create(std::istream& is) { return std::static_pointer_cast<AnimationClip>(Asset::create(is)); } AnimationClip::AnimationClip() {} AnimationClip::~AnimationClip() {} AssetType AnimationClip::getAssetType() const { return AssetType::Animation; } void AnimationClip::serialize(std::ostream& os) const { super::serialize(os); EachMember(msWrite); } void AnimationClip::deserialize(std::istream& is) { super::deserialize(is); EachMember(msRead); } #undef EachMember void AnimationClip::clear() { super::clear(); animations.clear(); } uint64_t AnimationClip::hash() const { uint64_t ret = super::hash(); for (auto& anim : animations) ret += anim->hash(); return ret; } uint64_t AnimationClip::checksum() const { uint64_t ret = super::checksum(); for (auto& anim : animations) ret += anim->checksum(); return ret; } bool AnimationClip::empty() const { return animations.empty(); } void AnimationClip::addAnimation(AnimationPtr v) { if (v) animations.push_back(v); } void AnimationClip::addAnimation(TransformAnimationPtr v) { if (v) addAnimation(v->host); } void AnimationClip::clearEmptyAnimations() { animations.erase( std::remove_if(animations.begin(), animations.end(), [](auto& c) { return c->empty(); }), animations.end()); } template<class T> static inline std::shared_ptr<T> CreateTypedAnimation(AnimationPtr host) { if (!host) { auto ret = std::make_shared<T>(Animation::create()); ret->setupCurves(true); return ret; } else { auto ret = std::make_shared<T>(host); ret->setupCurves(false); return ret; } } static AnimationCurvePtr GetCurve(AnimationPtr& host, const char *name, AnimationCurve::DataType type, bool create_if_not_exist) { if (create_if_not_exist) return host->getCurve(name, type); else return host->findCurve(name, type); } std::shared_ptr<TransformAnimation> TransformAnimation::create(AnimationPtr host) { return CreateTypedAnimation<TransformAnimation>(host); } TransformAnimation::TransformAnimation(AnimationPtr h) : host(h) , path(host->path) { host->entity_type = EntityType::Transform; } TransformAnimation::~TransformAnimation() { } void TransformAnimation::setupCurves(bool create_if_not_exist) { translation = GetCurve(host, mskTransformTranslation, DataType::Float3, create_if_not_exist); rotation = GetCurve(host, mskTransformRotation, DataType::Quaternion, create_if_not_exist); scale = GetCurve(host, mskTransformScale, DataType::Float3, create_if_not_exist); visible = GetCurve(host, mskTransformVisible, DataType::Int, create_if_not_exist); if (create_if_not_exist) { translation.curve->data_flags.affect_handedness = true; translation.curve->data_flags.affect_scale = true; rotation.curve->data_flags.affect_handedness = true; scale.curve->data_flags.affect_handedness = true; scale.curve->data_flags.ignore_negate = true; visible.curve->data_flags.force_constant = true; } } void TransformAnimation::reserve(size_t n) { host->reserve(n); } void TransformAnimation::validate() { auto check_and_erase = [this](auto& curve, auto v) { if (curve && curve.equal_all(v)) host->eraseCurve(curve.curve); }; check_and_erase(translation, mu::inf<mu::float3>()); check_and_erase(rotation, mu::inf<mu::quatf>()); check_and_erase(scale, mu::inf<mu::float3>()); if(visible && !visible.empty()) check_and_erase(visible, visible.front().value); } std::shared_ptr<CameraAnimation> CameraAnimation::create(AnimationPtr host) { return CreateTypedAnimation<CameraAnimation>(host); } CameraAnimation::CameraAnimation(AnimationPtr host) : super(host) { host->entity_type = EntityType::Camera; } void CameraAnimation::setupCurves(bool create_if_not_exist) { super::setupCurves(create_if_not_exist); fov = GetCurve(host, mskCameraFieldOfView, DataType::Float, create_if_not_exist); near_plane = GetCurve(host, mskCameraNearPlane, DataType::Float, create_if_not_exist); far_plane = GetCurve(host, mskCameraFarPlane, DataType::Float, create_if_not_exist); focal_length = GetCurve(host, mskCameraFocalLength, DataType::Float, create_if_not_exist); sensor_size = GetCurve(host, mskCameraSensorSize, DataType::Float2, create_if_not_exist); lens_shift = GetCurve(host, mskCameraLensShift, DataType::Float2, create_if_not_exist); if (create_if_not_exist) { near_plane.curve->data_flags.affect_scale = true; far_plane.curve->data_flags.affect_scale = true; } } void CameraAnimation::validate() { super::validate(); auto check_and_erase = [this](auto& curve, auto v) { if (curve && curve.equal_all(v)) host->eraseCurve(curve.curve); }; check_and_erase(fov, 0.0f); check_and_erase(near_plane, 0.0f); check_and_erase(far_plane, 0.0f); check_and_erase(focal_length, 0.0f); check_and_erase(sensor_size, mu::float2::zero()); check_and_erase(lens_shift, mu::float2::zero()); } std::shared_ptr<LightAnimation> LightAnimation::create(AnimationPtr host) { return CreateTypedAnimation<LightAnimation>(host); } LightAnimation::LightAnimation(AnimationPtr host) : super(host) { host->entity_type = EntityType::Light; } void LightAnimation::setupCurves(bool create_if_not_exist) { super::setupCurves(create_if_not_exist); color = GetCurve(host, mskLightColor, DataType::Float4, create_if_not_exist); intensity = GetCurve(host, mskLightIntensity, DataType::Float, create_if_not_exist); range = GetCurve(host, mskLightRange, DataType::Float, create_if_not_exist); spot_angle = GetCurve(host, mskLightSpotAngle, DataType::Float, create_if_not_exist); if (create_if_not_exist) { range.curve->data_flags.affect_scale = true; } } void LightAnimation::validate() { super::validate(); auto check_and_erase = [this](auto& curve, auto v) { if (curve.equal_all(v)) host->eraseCurve(curve.curve); }; check_and_erase(color, mu::inf<mu::float4>()); check_and_erase(intensity, mu::inf<float>()); check_and_erase(range, mu::inf<float>()); check_and_erase(spot_angle, mu::inf<float>()); } std::shared_ptr<MeshAnimation> MeshAnimation::create(AnimationPtr host) { return CreateTypedAnimation<MeshAnimation>(host); } MeshAnimation::MeshAnimation(AnimationPtr host) : super(host) { host->entity_type = EntityType::Mesh; } void MeshAnimation::setupCurves(bool create_if_not_exist) { super::setupCurves(create_if_not_exist); } TAnimationCurve<float> MeshAnimation::getBlendshapeCurve(const char *name) { char buf[512]; sprintf(buf, mskMeshBlendshape ".%s", name); return host->getCurve(buf, DataType::Float); } TAnimationCurve<float> MeshAnimation::getBlendshapeCurve(const std::string& name) { return getBlendshapeCurve(name.c_str()); } } // namespace ms
6,023
3,400
<reponame>yshgit/aeron /* * Copyright 2014-2021 Real Logic Limited. * * 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 io.aeron.cluster; import io.aeron.test.InterruptAfter; import io.aeron.test.InterruptingTestCallback; import io.aeron.test.SlowTest; import io.aeron.test.SystemTestWatcher; import io.aeron.test.cluster.TestCluster; import io.aeron.test.cluster.TestNode; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import static io.aeron.test.cluster.TestCluster.aCluster; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.WRITE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.*; @SlowTest @ExtendWith(InterruptingTestCallback.class) class ClusterToolTest { @RegisterExtension final SystemTestWatcher systemTestWatcher = new SystemTestWatcher(); @Test @InterruptAfter(30) void shouldHandleSnapshotOnLeaderOnly() { final TestCluster cluster = aCluster().withStaticNodes(3).start(); systemTestWatcher.cluster(cluster); final TestNode leader = cluster.awaitLeader(); final long initialSnapshotCount = leader.consensusModule().context().snapshotCounter().get(); final CapturingPrintStream capturingPrintStream = new CapturingPrintStream(); assertTrue(ClusterTool.snapshot( leader.consensusModule().context().clusterDir(), capturingPrintStream.resetAndGetPrintStream())); assertThat( capturingPrintStream.flushAndGetContent(), containsString("SNAPSHOT applied successfully")); final long expectedSnapshotCount = initialSnapshotCount + 1; cluster.awaitSnapshotCount(expectedSnapshotCount); for (final TestNode follower : cluster.followers()) { assertFalse(ClusterTool.snapshot( follower.consensusModule().context().clusterDir(), capturingPrintStream.resetAndGetPrintStream())); assertThat( capturingPrintStream.flushAndGetContent(), containsString("Current node is not the leader")); } } @Test @InterruptAfter(30) void shouldNotSnapshotWhenSuspendedOnly() { final TestCluster cluster = aCluster().withStaticNodes(3).start(); systemTestWatcher.cluster(cluster); final TestNode leader = cluster.awaitLeader(); final long initialSnapshotCount = leader.consensusModule().context().snapshotCounter().get(); final CapturingPrintStream capturingPrintStream = new CapturingPrintStream(); assertTrue(ClusterTool.suspend( leader.consensusModule().context().clusterDir(), capturingPrintStream.resetAndGetPrintStream())); assertThat( capturingPrintStream.flushAndGetContent(), containsString("SUSPEND applied successfully")); assertFalse(ClusterTool.snapshot( leader.consensusModule().context().clusterDir(), capturingPrintStream.resetAndGetPrintStream())); final String expectedMessage = "Unable to SNAPSHOT as the state of the consensus module is SUSPENDED, but needs to be ACTIVE"; assertThat(capturingPrintStream.flushAndGetContent(), containsString(expectedMessage)); assertEquals(initialSnapshotCount, leader.consensusModule().context().snapshotCounter().get()); } @Test @InterruptAfter(30) void shouldSuspendAndResume() { final TestCluster cluster = aCluster().withStaticNodes(3).start(); systemTestWatcher.cluster(cluster); final TestNode leader = cluster.awaitLeader(); final CapturingPrintStream capturingPrintStream = new CapturingPrintStream(); assertTrue(ClusterTool.suspend( leader.consensusModule().context().clusterDir(), capturingPrintStream.resetAndGetPrintStream())); assertThat( capturingPrintStream.flushAndGetContent(), containsString("SUSPEND applied successfully")); assertTrue(ClusterTool.resume( leader.consensusModule().context().clusterDir(), capturingPrintStream.resetAndGetPrintStream())); assertThat( capturingPrintStream.flushAndGetContent(), containsString("RESUME applied successfully")); } @Test void shouldFailIfMarkFileUnavailable(final @TempDir Path emptyClusterDir) { final CapturingPrintStream capturingPrintStream = new CapturingPrintStream(); assertFalse(ClusterTool.snapshot(emptyClusterDir.toFile(), capturingPrintStream.resetAndGetPrintStream())); assertThat( capturingPrintStream.flushAndGetContent(), containsString("cluster-mark.dat does not exist")); } @Test void sortRecordingLogIsANoOpIfRecordLogIsEmpty(final @TempDir Path emptyClusterDir) throws IOException { final File clusterDir = emptyClusterDir.toFile(); final Path logFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME); final boolean result = ClusterTool.sortRecordingLog(clusterDir); assertFalse(result); assertArrayEquals(new byte[0], Files.readAllBytes(logFile)); } @Test void sortRecordingLogIsANoOpIfRecordLogIsAlreadySorted(final @TempDir Path emptyClusterDir) throws IOException { final File clusterDir = emptyClusterDir.toFile(); final Path logFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME); try (RecordingLog recordingLog = new RecordingLog(clusterDir)) { recordingLog.appendTerm(21, 0, 100, 100); recordingLog.appendSnapshot(0, 0, 0, 0, 200, 0); recordingLog.appendTerm(21, 1, 1024, 200); } final byte[] originalBytes = Files.readAllBytes(logFile); assertNotEquals(0, originalBytes.length); final boolean result = ClusterTool.sortRecordingLog(clusterDir); assertFalse(result); assertArrayEquals(originalBytes, Files.readAllBytes(logFile)); } @Test void sortRecordingLogShouldRearrangeDataOnDisc(final @TempDir Path emptyClusterDir) throws IOException { final File clusterDir = emptyClusterDir.toFile(); final Path logFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME); final List<RecordingLog.Entry> sortedEntries = new ArrayList<>(); try (RecordingLog recordingLog = new RecordingLog(clusterDir)) { recordingLog.appendTerm(21, 2, 100, 100); recordingLog.appendSnapshot(1, 2, 50, 60, 42, 89); recordingLog.appendTerm(21, 1, 1024, 200); recordingLog.appendSnapshot(0, 0, 0, 0, 200, 0); final List<RecordingLog.Entry> entries = recordingLog.entries(); for (int i = 0, size = entries.size(); i < size; i++) { final RecordingLog.Entry entry = entries.get(i); assertNotEquals(i, entry.entryIndex); sortedEntries.add(new RecordingLog.Entry( entry.recordingId, entry.leadershipTermId, entry.termBaseLogPosition, entry.logPosition, entry.timestamp, entry.serviceId, entry.type, entry.isValid, i)); } } final byte[] originalBytes = Files.readAllBytes(logFile); assertNotEquals(0, originalBytes.length); final boolean result = ClusterTool.sortRecordingLog(clusterDir); assertTrue(result); assertFalse(Arrays.equals(originalBytes, Files.readAllBytes(logFile))); assertArrayEquals(new String[]{ RecordingLog.RECORDING_LOG_FILE_NAME }, clusterDir.list()); try (RecordingLog recordingLog = new RecordingLog(clusterDir)) { final List<RecordingLog.Entry> entries = recordingLog.entries(); assertEquals(sortedEntries, entries); } } @Test void seedRecordingLogFromSnapshotShouldDeleteOriginalRecordingLogFileIfThereAreNoValidSnapshots( final @TempDir Path emptyClusterDir) throws IOException { final File clusterDir = emptyClusterDir.toFile(); final Path logFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME); final Path backupLogFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME + ".bak"); try (RecordingLog recordingLog = new RecordingLog(clusterDir)) { recordingLog.appendTerm(1, 1, 0, 100); recordingLog.appendSnapshot(1, 1, 1000, 256, 300, 0); recordingLog.appendSnapshot(1, 1, 1000, 256, 300, ConsensusModule.Configuration.SERVICE_ID); recordingLog.appendTerm(1, 2, 2000, 400); recordingLog.appendSnapshot(2, 5, 56, 111, 500, 5); assertTrue(recordingLog.invalidateLatestSnapshot()); } assertTrue(Files.exists(logFile)); assertFalse(Files.exists(backupLogFile)); final byte[] logContents = Files.readAllBytes(logFile); ClusterTool.seedRecordingLogFromSnapshot(clusterDir); assertFalse(Files.exists(logFile)); assertTrue(Files.exists(backupLogFile)); assertArrayEquals(logContents, Files.readAllBytes(backupLogFile)); } @Test void seedRecordingLogFromSnapshotShouldCreateANewRecordingLogFromALatestValidSnapshot( final @TempDir Path emptyClusterDir) throws IOException { testSeedRecordingLogFromSnapshot(emptyClusterDir, ClusterTool::seedRecordingLogFromSnapshot); } @Test void seedRecordingLogFromSnapshotShouldCreateANewRecordingLogFromALatestValidSnapshotCommandLine( final @TempDir Path emptyClusterDir) throws IOException { testSeedRecordingLogFromSnapshot( emptyClusterDir, clusterDir -> ClusterTool.main(new String[]{ clusterDir.toString(), "seed-recording-log-from-snapshot" })); } private void testSeedRecordingLogFromSnapshot(final Path emptyClusterDir, final Consumer<File> truncateAction) throws IOException { final Path logFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME); final Path backupLogFile = emptyClusterDir.resolve(RecordingLog.RECORDING_LOG_FILE_NAME + ".bak"); Files.write(backupLogFile, new byte[]{ 0x1, -128, 0, 1, -1, 127 }, CREATE_NEW, WRITE); Files.setLastModifiedTime(backupLogFile, FileTime.fromMillis(0)); final File clusterDir = emptyClusterDir.toFile(); final List<RecordingLog.Entry> truncatedEntries = new ArrayList<>(); try (RecordingLog recordingLog = new RecordingLog(clusterDir)) { recordingLog.appendTerm(1, 0, 0, 0); recordingLog.appendSnapshot(1, 3, 4000, 4000, 600, 2); recordingLog.appendTerm(1, 3, 3000, 500); recordingLog.appendSnapshot(1, 2, 2900, 2200, 400, 2); recordingLog.appendSnapshot(1, 2, 2900, 2200, 400, 1); recordingLog.appendSnapshot(1, 2, 2900, 2200, 400, 0); recordingLog.appendSnapshot(1, 2, 2900, 2200, 400, ConsensusModule.Configuration.SERVICE_ID); recordingLog.appendTerm(1, 2, 2000, 300); recordingLog.appendSnapshot(1, 1, 1800, 1000, 200, ConsensusModule.Configuration.SERVICE_ID); recordingLog.appendSnapshot(1, 1, 1800, 1000, 200, 0); recordingLog.appendSnapshot(1, 1, 1800, 1000, 200, 1); recordingLog.appendTerm(1, 1, 1000, 100); assertTrue(recordingLog.invalidateLatestSnapshot()); final List<RecordingLog.Entry> entries = recordingLog.entries(); for (int i = 2; i < 5; i++) { final RecordingLog.Entry entry = entries.get(i); truncatedEntries.add(new RecordingLog.Entry( entry.recordingId, entry.leadershipTermId, 0, 0, entry.timestamp, entry.serviceId, entry.type, entry.isValid, i - 2)); } } final byte[] logContents = Files.readAllBytes(logFile); final FileTime logLastModifiedTime = Files.getLastModifiedTime(logFile); truncateAction.accept(clusterDir); try (RecordingLog recordingLog = new RecordingLog(clusterDir)) { assertEquals(truncatedEntries, recordingLog.entries()); } assertArrayEquals(logContents, Files.readAllBytes(backupLogFile)); // compare up to millis, because upon copy file timestamp seems to be truncated // e.g. expected: <2021-09-27T09:49:22.756944756Z> but was: <2021-09-27T09:49:22.756944Z> assertEquals(logLastModifiedTime.toMillis(), Files.getLastModifiedTime(backupLogFile).toMillis()); } static class CapturingPrintStream { private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); private final PrintStream printStream = new PrintStream(byteArrayOutputStream); PrintStream resetAndGetPrintStream() { byteArrayOutputStream.reset(); return printStream; } String flushAndGetContent() { printStream.flush(); try { return byteArrayOutputStream.toString(US_ASCII.name()); } catch (final UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } } }
5,951
435
<reponame>allen91wu/data { "description": "At System1, data scientists are faced with the task of predicting\nrevenue and cost per click across millions of unique keywords that drive\ntraffic to our sites or monetize on a pay per click basis. This talk\nwill show a variety of techniques we use to extract the most information\nfrom categorical variables, especially anonymized, sparse, high\ncardinality categorical variables, like search terms.\n\nCategorical variables are easily interpretable by data scientists and\nnon- technical people, but they can also be difficult to translate into\nmachine learning algorithms. Categorical variables need to be converted\nto quantitative values to be used in machine learning models and can\nvery quickly explode the feature space of a model, add noise or\nunintended signals to the data, or simply not include all the meaning\nand predictive power that feature provides for the dependent variable.\nThere are many popular and effective libraries that abstract categorical\nvariable feature creation. However, if a model is sensitive from a\nfinancial, data ethics, or some level of public visibility standpoint,\nor simply prone to overfitting, it is vital to understand how the model\nis capturing all features and how to tune model parameters or input\ndata. Furthermore, if dealing with personal or sensitive data, machines\nneed to be able to handle anonymized categories while still allowing a\nhuman to interpret the source data. One of the problems we face at\nSystem1 is that individual keywords can receive very little traffic,\nsometimes less than a click per day; however, across millions of\nkeywords, these long- tail keywords comprise significant revenue.\nFurthermore, data science models need to be proactive and adjust bids\nand traffic based on seasonal components even if there is no data from\nthe prior season. This talk will present a variety of practical\ntechniques to extract and retain information and predictive power for\ncategorical variables. We will talk about model selection, feature\ncreation and techniques for converting categorical variables to\nquantitative values for modeling. Finally, the talk will present an\ninteresting technique that utilizes embedding layers and transfer\nlearning in a neural network framework to predict cost per click values\non search terms.\n", "duration": 2111, "language": "eng", "published_at": "2019-12-29T22:30:13.000Z", "recorded": "2019-12-05", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/icmjDyNaj2E/hqdefault.jpg", "title": "Modeling Search Term Revenue: Using Embedding Layers to Manage High Cardinality Categorical Data", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=icmjDyNaj2E" } ] }
703
389
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.lang.parser; import java.util.HashMap; public class ExternalSymbolMapForMap extends ExternalSymbolMapBase { private HashMap<String, ISymbol> _externalSymbols; public ExternalSymbolMapForMap( HashMap<String, ISymbol> externalSymbols) { this(externalSymbols, false); } public ExternalSymbolMapForMap( HashMap<String, ISymbol> externalSymbols, boolean assumeSymbolsRequireExternalSymbolMapArgument) { super(assumeSymbolsRequireExternalSymbolMapArgument); _externalSymbols = externalSymbols; } public ISymbol getSymbol(String name) { return _externalSymbols.get( name ); } public boolean isExternalSymbol(String name) { return _externalSymbols.containsKey( name ); } public HashMap<String, ISymbol> getMap() { return _externalSymbols; } }
285
1,056
<filename>ide/projectuiapi/src/org/netbeans/modules/project/uiapi/OpenProjectsListener.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.netbeans.modules.project.uiapi; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import org.netbeans.api.project.Project; import org.netbeans.api.project.ui.OpenProjects; import org.openide.windows.TopComponentGroup; import org.openide.windows.WindowManager; /** * * @author <NAME> */ class OpenProjectsListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if( OpenProjects.PROPERTY_OPEN_PROJECTS.equals(evt.getPropertyName()) ) { // open/close navigator and task list windows when project is opened/closed openCloseWindowGroup(); } } private void openCloseWindowGroup() { final Project[] projects = OpenProjects.getDefault().getOpenProjects(); Runnable r = new Runnable() { @Override public void run() { TopComponentGroup projectsGroup = WindowManager.getDefault().findTopComponentGroup("OpenedProjects"); //NOI18N if( null == projectsGroup ) Logger.getLogger(OpenProjectsListener.class.getName()).log( Level.FINE, "OpenedProjects TopComponent Group not found." ); TopComponentGroup taskListGroup = WindowManager.getDefault().findTopComponentGroup("TaskList"); //NOI18N if( null == taskListGroup ) Logger.getLogger(OpenProjectsListener.class.getName()).log( Level.FINE, "TaskList TopComponent Group not found." ); boolean show = projects.length > 0; if( show ) { if( null != projectsGroup ) projectsGroup.open(); if( null != taskListGroup && supportsTaskList(projects) ) taskListGroup.open(); } else { if( null != projectsGroup ) projectsGroup.close(); if( null != taskListGroup ) taskListGroup.close(); } } }; if( SwingUtilities.isEventDispatchThread() ) r.run(); else SwingUtilities.invokeLater(r); } private boolean supportsTaskList(Project[] projects) { boolean res = false; for( Project p : projects ) { //#184291 - don't show task list for cnd MakeProjects, see also #185488 if( !p.getClass().getName().equals("org.netbeans.modules.cnd.makeproject.MakeProject") ) { //NOI18N res = true; break; } } return res; } }
1,452
650
/* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #include "ProfileModel.h" #include "Profile.h" #include <LibGUI/FileIconProvider.h> #include <LibSymbolication/Symbolication.h> #include <stdio.h> namespace Profiler { ProfileModel::ProfileModel(Profile& profile) : m_profile(profile) { m_user_frame_icon.set_bitmap_for_size(16, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/inspector-object.png")); m_kernel_frame_icon.set_bitmap_for_size(16, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/inspector-object-red.png")); } ProfileModel::~ProfileModel() { } GUI::ModelIndex ProfileModel::index(int row, int column, const GUI::ModelIndex& parent) const { if (!parent.is_valid()) { if (m_profile.roots().is_empty()) return {}; return create_index(row, column, m_profile.roots().at(row).ptr()); } auto& remote_parent = *static_cast<ProfileNode*>(parent.internal_data()); return create_index(row, column, remote_parent.children().at(row).ptr()); } GUI::ModelIndex ProfileModel::parent_index(const GUI::ModelIndex& index) const { if (!index.is_valid()) return {}; auto& node = *static_cast<ProfileNode*>(index.internal_data()); if (!node.parent()) return {}; // NOTE: If the parent has no parent, it's a root, so we have to look among the roots. if (!node.parent()->parent()) { for (size_t row = 0; row < m_profile.roots().size(); ++row) { if (m_profile.roots()[row].ptr() == node.parent()) { return create_index(row, index.column(), node.parent()); } } VERIFY_NOT_REACHED(); return {}; } for (size_t row = 0; row < node.parent()->parent()->children().size(); ++row) { if (node.parent()->parent()->children()[row].ptr() == node.parent()) return create_index(row, index.column(), node.parent()); } VERIFY_NOT_REACHED(); return {}; } int ProfileModel::row_count(const GUI::ModelIndex& index) const { if (!index.is_valid()) return m_profile.roots().size(); auto& node = *static_cast<ProfileNode*>(index.internal_data()); return node.children().size(); } int ProfileModel::column_count(const GUI::ModelIndex&) const { return Column::__Count; } String ProfileModel::column_name(int column) const { switch (column) { case Column::SampleCount: return m_profile.show_percentages() ? "% Samples" : "# Samples"; case Column::SelfCount: return m_profile.show_percentages() ? "% Self" : "# Self"; case Column::ObjectName: return "Object"; case Column::StackFrame: return "Stack Frame"; case Column::SymbolAddress: return "Symbol Address"; default: VERIFY_NOT_REACHED(); return {}; } } GUI::Variant ProfileModel::data(const GUI::ModelIndex& index, GUI::ModelRole role) const { auto* node = static_cast<ProfileNode*>(index.internal_data()); if (role == GUI::ModelRole::TextAlignment) { if (index.column() == Column::SampleCount || index.column() == Column::SelfCount) return Gfx::TextAlignment::CenterRight; } if (role == GUI::ModelRole::Icon) { if (index.column() == Column::StackFrame) { if (node->is_root()) { return GUI::FileIconProvider::icon_for_executable(node->process().executable); } auto maybe_kernel_base = Symbolication::kernel_base(); if (maybe_kernel_base.has_value() && node->address() >= maybe_kernel_base.value()) return m_kernel_frame_icon; return m_user_frame_icon; } return {}; } if (role == GUI::ModelRole::Display) { if (index.column() == Column::SampleCount) { if (m_profile.show_percentages()) return ((float)node->event_count() / (float)m_profile.filtered_event_indices().size()) * 100.0f; return node->event_count(); } if (index.column() == Column::SelfCount) { if (m_profile.show_percentages()) return ((float)node->self_count() / (float)m_profile.filtered_event_indices().size()) * 100.0f; return node->self_count(); } if (index.column() == Column::ObjectName) return node->object_name(); if (index.column() == Column::StackFrame) { if (node->is_root()) { return String::formatted("{} ({})", node->process().basename, node->process().pid); } return node->symbol(); } if (index.column() == Column::SymbolAddress) { if (node->is_root()) return ""; auto library = node->process().library_metadata.library_containing(node->address()); if (!library) return ""; return String::formatted("{:p} (offset {:p})", node->address(), node->address() - library->base); } return {}; } return {}; } Vector<GUI::ModelIndex> ProfileModel::matches(StringView const& searching, unsigned flags, GUI::ModelIndex const& parent) { RemoveReference<decltype(m_profile.roots())>* nodes { nullptr }; if (!parent.is_valid()) nodes = &m_profile.roots(); else nodes = &static_cast<ProfileNode*>(parent.internal_data())->children(); if (!nodes) return {}; Vector<GUI::ModelIndex> found_indices; for (auto it = nodes->begin(); !it.is_end(); ++it) { GUI::ModelIndex index = this->index(it.index(), StackFrame, parent); if (!string_matches(data(index, GUI::ModelRole::Display).as_string(), searching, flags)) continue; found_indices.append(index); if (flags & FirstMatchOnly) break; } return found_indices; } }
2,456
317
<reponame>kodefear/CS6200_Sushant_Pritmani<gh_stars>100-1000 package com.googlecode.totallylazy.functions; import com.googlecode.totallylazy.Quadruple; public interface Function4<A, B, C, D, E> { E call(A a, B b, C c, D d) throws Exception; default E apply(final A a, final B b, final C c, final D d) { return Functions.call(this, a, b, c, d); } default Function1<Quadruple<A, B, C, D>, E> quadruple() { return Functions.quadruple(this); } }
209
302
<reponame>vadkasevas/BAS #include "languagechooserdevelopmentwidget.h" #include "ui_languagechooserdevelopmentwidget.h" #include <QMessageBox> #include <QPushButton> #include "flowlayout.h" #include "every_cpp.h" LanguageChooserDevelopmentWidget::LanguageChooserDevelopmentWidget(QWidget *parent) : QDialog(parent), ui(new Ui::LanguageChooserDevelopmentWidget) { ui->setupUi(this); ui->supportedLanguages->setLayout(new FlowLayout(ui->supportedLanguages)); ui->switchTo->setLayout(new FlowLayout(ui->switchTo)); connect(this,SIGNAL(accepted()),this,SLOT(AcceptedSlot())); correcting = false; } void LanguageChooserDevelopmentWidget::AcceptedSlot() { QList<int> SelectedIndexes; int index = 0; foreach(QCheckBox* c, CheckBoxes) { if(c->isChecked()) { SelectedIndexes.append(index); } index++; } LanguageModel->SetScriptAvailableLanguages(SelectedIndexes); } void LanguageChooserDevelopmentWidget::SetLanguageModel(ILanguageModel *LanguageModel) { this->LanguageModel = LanguageModel; int index = 0; QList<int> AvailableLanguages = LanguageModel->GetScriptAvailableLanguages(); foreach(QString lang, LanguageModel->GetEngineAvailableLanguages()) { QCheckBox*check = new QCheckBox(this); connect(check,SIGNAL(toggled(bool)),this,SLOT(CheckBoxClicked())); check->setText(lang); check->setIcon(QIcon(QString(":/engine/images/flags/%1.png").arg(lang))); if(AvailableLanguages.contains(index)) check->setChecked(true); ui->supportedLanguages->layout()->addWidget(check); QPushButton *button = new QPushButton(this); if(AvailableLanguages.contains(index)) connect(button,SIGNAL(clicked()),this,SLOT(ButtonClicked())); else button->setEnabled(false); button->setText(lang); ui->switchTo->layout()->addWidget(button); CheckBoxes.append(check); index++; } } void LanguageChooserDevelopmentWidget::ButtonClicked() { QPushButton *button = qobject_cast<QPushButton*>(sender()); LanguageModel->ChangeDefaultLanguage(button->text()); } void LanguageChooserDevelopmentWidget::CheckBoxClicked() { if(correcting) return; foreach(QCheckBox* c, CheckBoxes) { if(c->isChecked()) return; } QCheckBox * check = qobject_cast<QCheckBox*>(sender()); if(!check->isChecked()) { correcting = true; check->setChecked(true); correcting = false; QMessageBox msgBox; msgBox.setWindowTitle(tr("At least one language should be present")); msgBox.setText(tr("At least one language should be present")); msgBox.setIcon(QMessageBox::Critical); msgBox.setWindowIcon(QIcon(":/engine/images/language.png")); msgBox.setInformativeText(""); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); } } void LanguageChooserDevelopmentWidget::changeEvent(QEvent *e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } LanguageChooserDevelopmentWidget::~LanguageChooserDevelopmentWidget() { delete ui; }
1,351
476
<gh_stars>100-1000 /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.sql.planner; import com.google.common.collect.ImmutableMap; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.plan.Symbol; import io.prestosql.spi.predicate.NullableValue; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static io.prestosql.sql.planner.SymbolUtils.toSymbolReference; import static java.util.Objects.requireNonNull; public class LookupSymbolResolver implements SymbolResolver { private final Map<Symbol, ColumnHandle> assignments; private final Map<ColumnHandle, NullableValue> bindings; public LookupSymbolResolver(Map<Symbol, ColumnHandle> assignments, Map<ColumnHandle, NullableValue> bindings) { requireNonNull(assignments, "assignments is null"); requireNonNull(bindings, "bindings is null"); this.assignments = ImmutableMap.copyOf(assignments); this.bindings = ImmutableMap.copyOf(bindings); } @Override public Object getValue(Symbol symbol) { ColumnHandle column = assignments.get(symbol); checkArgument(column != null, "Missing column assignment for %s", symbol); if (!bindings.containsKey(column)) { return toSymbolReference(symbol); } return bindings.get(column).getValue(); } }
640
348
<gh_stars>100-1000 {"nom":"<NAME>","circ":"3ème circonscription","dpt":"Eure-et-Loir","inscrits":2007,"abs":1067,"votants":940,"blancs":52,"nuls":25,"exp":863,"res":[{"nuance":"LR","nom":"<NAME>","voix":559},{"nuance":"RDG","nom":"<NAME>","voix":304}]}
105
420
<reponame>hiliving/DelegationAdapter { "msgs": [ { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "看来我不应该来", "pic": "" }, { "user": { "type": 1, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zxxz.png" }, "type": 1, "text": "现在才知道太晚了", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "留下点回忆行不行?", "pic": "" }, { "user": { "type": 1, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zxxz.png" }, "type": 1, "text": "我不要回忆,要的话,留下你的人", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "这样子只得到我的肉体,并不能得到我的灵魂,我已经有爱人了,我们不会有结果,你让我走吧!", "pic": "" }, { "user": { "type": 1, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zxxz.png" }, "type": 1, "text": "好,我让你走,不过临走前你要亲我一下", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "我再怎么说也是一个夕阳武士,你叫我亲我就亲,那我的形象不是全毁了", "pic": "" }, { "user": { "type": 1, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zxxz.png" }, "type": 1, "text": "你说谎,你不敢亲我,因为你还喜欢我,我告诉你,如果这次你拒绝我的话,你会后悔一辈子的", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "后悔我也不会亲,只能怪相逢恨晚,造物弄人啊", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "我这辈子都不会再走了,我爱你", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "干什么?", "pic": "" }, { "user": { "type": 1, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zxxz.png" }, "type": 1, "text": "那个人样子好怪哦", "pic": "" }, { "user": { "type": 1, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zxxz.png" }, "type": 2, "text": "http://wx4.sinaimg.cn/wap720/69cc290fly1fkci073wfxj218g0qoq6y.jpg", "pic": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/ngrhxytg.jpg" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "我也看到了", "pic": "" }, { "user": { "type": 2, "avatar": "https://raw.githubusercontent.com/xuehuayous/DelegationAdapter/master/sample/pic/zzb.png" }, "type": 1, "text": "他好像条狗啊!", "pic": "" } ] }
2,340
715
#include <stdio.h> #include <limits.h> using namespace std; #define dir true #define n_dir false class grafo{ private: struct head_graph{ int **matriz_ad; int numvert; int numares; bool direct; }; bool criado = false; head_graph g; public: void create_graph(int tmax, bool tipo){ g.matriz_ad = new int*[tmax]; for(int i = 0; i < tmax; i++){ g.matriz_ad[i] = new int[tmax]; } g.numares = 0; g.numvert = tmax; g.direct = tipo; criado = true; for(int i = 0; i <tmax; i++){ for(int j = 0; j<tmax; j++){ if(i != j){ g.matriz_ad[i][j] = INT_MAX; } else{ g.matriz_ad[i][j] = 0; } } } } void floyd_warshall(){ for(int k = 0; k < g.numvert; k++){ for(int i = 0; i < g.numvert; i++){ for(int j = 0; j <g.numvert; j++){ if((g.matriz_ad[i][k]!= INT_MAX) &&(g.matriz_ad[k][j] != INT_MAX) &&(g.matriz_ad[i][j] > g.matriz_ad[i][k] +g.matriz_ad[k][j])){ g.matriz_ad[i][j] = g.matriz_ad[i][k] +g.matriz_ad[k][j]; } } } } } void add_edge(int u, int v, int peso){ if(criado){ g.numares++; g.matriz_ad[u][v] = peso; if(!g.direct){ g.matriz_ad[v][u] = peso; } } } void matriz_ad(){ for(int i = 0; i < g.numvert; i++){ for(int j = 0; j< g.numvert; j++){ if(g.matriz_ad[i][j] == INT_MAX){ printf("I "); }else{ printf("%d ", g.matriz_ad[i][j]); } } printf("\n"); } } }; int main(){ grafo g; g.create_graph(4,dir); g.add_edge(1,0,2); g.add_edge(0,2,3); g.add_edge(2,3,1); g.add_edge(3,0,6); g.add_edge(2,1,7); printf("initial matriz of adjacency(I is infinity)\n"); g.matriz_ad(); g.floyd_warshall(); printf("end matriz of adjacency\n"); g.matriz_ad(); return 0; }
1,724
777
<gh_stars>100-1000 // Copyright (c) 2012 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. #include "net/proxy/proxy_config.h" #include "net/proxy/proxy_config_service_common_unittest.h" #include "net/proxy/proxy_info.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { void ExpectProxyServerEquals(const char* expectation, const ProxyList& proxy_servers) { if (expectation == NULL) { EXPECT_TRUE(proxy_servers.IsEmpty()); } else { EXPECT_EQ(expectation, proxy_servers.ToPacString()); } } TEST(ProxyConfigTest, Equals) { // Test |ProxyConfig::auto_detect|. ProxyConfig config1; config1.set_auto_detect(true); ProxyConfig config2; config2.set_auto_detect(false); EXPECT_FALSE(config1.Equals(config2)); EXPECT_FALSE(config2.Equals(config1)); config2.set_auto_detect(true); EXPECT_TRUE(config1.Equals(config2)); EXPECT_TRUE(config2.Equals(config1)); // Test |ProxyConfig::pac_url|. config2.set_pac_url(GURL("http://wpad/wpad.dat")); EXPECT_FALSE(config1.Equals(config2)); EXPECT_FALSE(config2.Equals(config1)); config1.set_pac_url(GURL("http://wpad/wpad.dat")); EXPECT_TRUE(config1.Equals(config2)); EXPECT_TRUE(config2.Equals(config1)); // Test |ProxyConfig::proxy_rules|. config2.proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY; config2.proxy_rules().single_proxies.SetSingleProxyServer( ProxyServer::FromURI("myproxy:80", ProxyServer::SCHEME_HTTP)); EXPECT_FALSE(config1.Equals(config2)); EXPECT_FALSE(config2.Equals(config1)); config1.proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY; config1.proxy_rules().single_proxies.SetSingleProxyServer( ProxyServer::FromURI("myproxy:100", ProxyServer::SCHEME_HTTP)); EXPECT_FALSE(config1.Equals(config2)); EXPECT_FALSE(config2.Equals(config1)); config1.proxy_rules().single_proxies.SetSingleProxyServer( ProxyServer::FromURI("myproxy", ProxyServer::SCHEME_HTTP)); EXPECT_TRUE(config1.Equals(config2)); EXPECT_TRUE(config2.Equals(config1)); // Test |ProxyConfig::bypass_rules|. config2.proxy_rules().bypass_rules.AddRuleFromString("*.google.com"); EXPECT_FALSE(config1.Equals(config2)); EXPECT_FALSE(config2.Equals(config1)); config1.proxy_rules().bypass_rules.AddRuleFromString("*.google.com"); EXPECT_TRUE(config1.Equals(config2)); EXPECT_TRUE(config2.Equals(config1)); // Test |ProxyConfig::proxy_rules.reverse_bypass|. config2.proxy_rules().reverse_bypass = true; EXPECT_FALSE(config1.Equals(config2)); EXPECT_FALSE(config2.Equals(config1)); config1.proxy_rules().reverse_bypass = true; EXPECT_TRUE(config1.Equals(config2)); EXPECT_TRUE(config2.Equals(config1)); } TEST(ProxyConfigTest, ParseProxyRules) { const struct { const char* proxy_rules; ProxyConfig::ProxyRules::Type type; // These will be PAC-stle strings, eg 'PROXY foo.com' const char* single_proxy; const char* proxy_for_http; const char* proxy_for_https; const char* proxy_for_ftp; const char* fallback_proxy; } tests[] = { // One HTTP proxy for all schemes. { "myproxy:80", ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY, "PROXY myproxy:80", NULL, NULL, NULL, NULL, }, // Multiple HTTP proxies for all schemes. { "myproxy:80,https://myotherproxy", ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY, "PROXY myproxy:80;HTTPS myotherproxy:443", NULL, NULL, NULL, NULL, }, // Only specify a proxy server for "http://" urls. { "http=myproxy:80", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "PROXY myproxy:80", NULL, NULL, NULL, }, // Specify an HTTP proxy for "ftp://" and a SOCKS proxy for "https://" urls. { "ftp=ftp-proxy ; https=socks4://foopy", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, NULL, "SOCKS foopy:1080", "PROXY ftp-proxy:80", NULL, }, // Give a scheme-specific proxy as well as a non-scheme specific. // The first entry "foopy" takes precedance marking this list as // TYPE_SINGLE_PROXY. { "foopy ; ftp=ftp-proxy", ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY, "PROXY foopy:80", NULL, NULL, NULL, NULL, }, // Give a scheme-specific proxy as well as a non-scheme specific. // The first entry "ftp=ftp-proxy" takes precedance marking this list as // TYPE_PROXY_PER_SCHEME. { "ftp=ftp-proxy ; foopy", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, NULL, NULL, "PROXY ftp-proxy:80", NULL, }, // Include a list of entries for a single scheme. { "ftp=ftp1,ftp2,ftp3", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, NULL, NULL, "PROXY ftp1:80;PROXY ftp2:80;PROXY ftp3:80", NULL, }, // Include multiple entries for the same scheme -- they accumulate. { "http=http1,http2; http=http3", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "PROXY http1:80;PROXY http2:80;PROXY http3:80", NULL, NULL, NULL, }, // Include lists of entries for multiple schemes. { "ftp=ftp1,ftp2,ftp3 ; http=http1,http2; ", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "PROXY http1:80;PROXY http2:80", NULL, "PROXY ftp1:80;PROXY ftp2:80;PROXY ftp3:80", NULL, }, // Include non-default proxy schemes. { "http=https://secure_proxy; ftp=socks4://socks_proxy; https=socks://foo", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "HTTPS secure_proxy:443", "SOCKS5 foo:1080", "SOCKS socks_proxy:1080", NULL, }, // Only SOCKS proxy present, others being blank. { "socks=foopy", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, NULL, NULL, NULL, "SOCKS foopy:1080", }, // SOCKS proxy present along with other proxies too { "http=httpproxy ; https=httpsproxy ; ftp=ftpproxy ; socks=foopy ", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "PROXY httpproxy:80", "PROXY httpsproxy:80", "PROXY ftpproxy:80", "SOCKS foopy:1080", }, // SOCKS proxy (with modifier) present along with some proxies // (FTP being blank) { "http=httpproxy ; https=httpsproxy ; socks=socks5://foopy ", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "PROXY httpproxy:80", "PROXY httpsproxy:80", NULL, "SOCKS5 foopy:1080", }, // Include unsupported schemes -- they are discarded. { "crazy=foopy ; foo=bar ; https=myhttpsproxy", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, NULL, "PROXY myhttpsproxy:80", NULL, NULL, }, // direct:// as first option for a scheme. { "http=direct://,myhttpproxy; https=direct://", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "DIRECT;PROXY myhttpproxy:80", "DIRECT", NULL, NULL, }, // direct:// as a second option for a scheme. { "http=myhttpproxy,direct://", ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME, NULL, "PROXY myhttpproxy:80;DIRECT", NULL, NULL, NULL, }, }; ProxyConfig config; for (size_t i = 0; i < arraysize(tests); ++i) { config.proxy_rules().ParseFromString(tests[i].proxy_rules); EXPECT_EQ(tests[i].type, config.proxy_rules().type); ExpectProxyServerEquals(tests[i].single_proxy, config.proxy_rules().single_proxies); ExpectProxyServerEquals(tests[i].proxy_for_http, config.proxy_rules().proxies_for_http); ExpectProxyServerEquals(tests[i].proxy_for_https, config.proxy_rules().proxies_for_https); ExpectProxyServerEquals(tests[i].proxy_for_ftp, config.proxy_rules().proxies_for_ftp); ExpectProxyServerEquals(tests[i].fallback_proxy, config.proxy_rules().fallback_proxies); } } TEST(ProxyConfigTest, ProxyRulesSetBypassFlag) { // Test whether the did_bypass_proxy() flag is set in proxy info correctly. ProxyConfig::ProxyRules rules; ProxyInfo result; rules.ParseFromString("http=httpproxy:80"); rules.bypass_rules.AddRuleFromString(".com"); rules.Apply(GURL("http://example.com"), &result); EXPECT_TRUE(result.is_direct_only()); EXPECT_TRUE(result.did_bypass_proxy()); rules.Apply(GURL("http://example.org"), &result); EXPECT_FALSE(result.is_direct()); EXPECT_FALSE(result.did_bypass_proxy()); // Try with reversed bypass rules. rules.reverse_bypass = true; rules.Apply(GURL("http://example.org"), &result); EXPECT_TRUE(result.is_direct_only()); EXPECT_TRUE(result.did_bypass_proxy()); rules.Apply(GURL("http://example.com"), &result); EXPECT_FALSE(result.is_direct()); EXPECT_FALSE(result.did_bypass_proxy()); } static const char kWsUrl[] = "ws://example.com/echo"; static const char kWssUrl[] = "wss://example.com/echo"; class ProxyConfigWebSocketTest : public ::testing::Test { protected: void ParseFromString(const std::string& rules) { rules_.ParseFromString(rules); } void Apply(const GURL& gurl) { rules_.Apply(gurl, &info_); } std::string ToPacString() const { return info_.ToPacString(); } static GURL WsUrl() { return GURL(kWsUrl); } static GURL WssUrl() { return GURL(kWssUrl); } ProxyConfig::ProxyRules rules_; ProxyInfo info_; }; // If a single proxy is set for all protocols, WebSocket uses it. TEST_F(ProxyConfigWebSocketTest, UsesProxy) { ParseFromString("proxy:3128"); Apply(WsUrl()); EXPECT_EQ("PROXY proxy:3128", ToPacString()); } // See RFC6455 Section 4.1. item 3, "_Proxy Usage_". TEST_F(ProxyConfigWebSocketTest, PrefersSocks) { ParseFromString( "http=proxy:3128 ; https=sslproxy:3128 ; socks=socksproxy:1080"); Apply(WsUrl()); EXPECT_EQ("SOCKS socksproxy:1080", ToPacString()); } TEST_F(ProxyConfigWebSocketTest, PrefersHttpsToHttp) { ParseFromString("http=proxy:3128 ; https=sslproxy:3128"); Apply(WssUrl()); EXPECT_EQ("PROXY sslproxy:3128", ToPacString()); } TEST_F(ProxyConfigWebSocketTest, PrefersHttpsEvenForWs) { ParseFromString("http=proxy:3128 ; https=sslproxy:3128"); Apply(WsUrl()); EXPECT_EQ("PROXY sslproxy:3128", ToPacString()); } TEST_F(ProxyConfigWebSocketTest, PrefersHttpToDirect) { ParseFromString("http=proxy:3128"); Apply(WssUrl()); EXPECT_EQ("PROXY proxy:3128", ToPacString()); } TEST_F(ProxyConfigWebSocketTest, IgnoresFtpProxy) { ParseFromString("ftp=ftpproxy:3128"); Apply(WssUrl()); EXPECT_EQ("DIRECT", ToPacString()); } TEST_F(ProxyConfigWebSocketTest, ObeysBypassRules) { ParseFromString("http=proxy:3128 ; https=sslproxy:3128"); rules_.bypass_rules.AddRuleFromString(".chromium.org"); Apply(GURL("wss://codereview.chromium.org/feed")); EXPECT_EQ("DIRECT", ToPacString()); } TEST_F(ProxyConfigWebSocketTest, ObeysLocalBypass) { ParseFromString("http=proxy:3128 ; https=sslproxy:3128"); rules_.bypass_rules.AddRuleFromString("<local>"); Apply(GURL("ws://localhost/feed")); EXPECT_EQ("DIRECT", ToPacString()); } } // namespace } // namespace net
4,879
852
<gh_stars>100-1000 #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "DataFormats/Provenance/interface/ModuleDescription.h" #include "FWCore/ServiceRegistry/interface/ActivityRegistry.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/ModuleCallingContext.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/MessageLogger/interface/JobReport.h" #include "TFile.h" #include "TROOT.h" #include <map> #include <unistd.h> const std::string TFileService::kSharedResource = "TFileService"; thread_local TFileDirectory TFileService::tFileDirectory_; TFileService::TFileService(const edm::ParameterSet& cfg, edm::ActivityRegistry& r) : file_(nullptr), fileName_(cfg.getParameter<std::string>("fileName")), fileNameRecorded_(false), closeFileFast_(cfg.getUntrackedParameter<bool>("closeFileFast", false)) { tFileDirectory_ = TFileDirectory("", "", TFile::Open(fileName_.c_str(), "RECREATE"), ""); file_ = tFileDirectory_.file_; // activities to monitor in order to set the proper directory r.watchPreModuleConstruction(this, &TFileService::setDirectoryName); r.watchPreModuleBeginJob(this, &TFileService::setDirectoryName); r.watchPreModuleEndJob(this, &TFileService::setDirectoryName); r.watchPreModuleEvent(this, &TFileService::preModuleEvent); r.watchPostModuleEvent(this, &TFileService::postModuleEvent); r.watchPreModuleGlobalBeginRun(this, &TFileService::preModuleGlobal); r.watchPostModuleGlobalBeginRun(this, &TFileService::postModuleGlobal); r.watchPreModuleGlobalEndRun(this, &TFileService::preModuleGlobal); r.watchPostModuleGlobalEndRun(this, &TFileService::postModuleGlobal); r.watchPreModuleGlobalBeginLumi(this, &TFileService::preModuleGlobal); r.watchPostModuleGlobalBeginLumi(this, &TFileService::postModuleGlobal); r.watchPreModuleGlobalEndLumi(this, &TFileService::preModuleGlobal); r.watchPostModuleGlobalEndLumi(this, &TFileService::postModuleGlobal); // delay writing into JobReport after BeginJob r.watchPostBeginJob(this, &TFileService::afterBeginJob); } TFileService::~TFileService() { file_->Write(); if (closeFileFast_) gROOT->GetListOfFiles()->Remove(file_); file_->Close(); delete file_; } void TFileService::setDirectoryName(const edm::ModuleDescription& desc) { tFileDirectory_.file_ = file_; tFileDirectory_.dir_ = desc.moduleLabel(); tFileDirectory_.descr_ = tFileDirectory_.dir_ + " (" + desc.moduleName() + ") folder"; } void TFileService::preModuleEvent(edm::StreamContext const&, edm::ModuleCallingContext const& mcc) { setDirectoryName(*mcc.moduleDescription()); } void TFileService::postModuleEvent(edm::StreamContext const&, edm::ModuleCallingContext const& mcc) { edm::ModuleCallingContext const* previous_mcc = mcc.previousModuleOnThread(); if (previous_mcc) { setDirectoryName(*previous_mcc->moduleDescription()); } } void TFileService::preModuleGlobal(edm::GlobalContext const&, edm::ModuleCallingContext const& mcc) { setDirectoryName(*mcc.moduleDescription()); } void TFileService::postModuleGlobal(edm::GlobalContext const&, edm::ModuleCallingContext const& mcc) { edm::ModuleCallingContext const* previous_mcc = mcc.previousModuleOnThread(); if (previous_mcc) { setDirectoryName(*previous_mcc->moduleDescription()); } } void TFileService::afterBeginJob() { if (!fileName_.empty()) { if (!fileNameRecorded_) { std::string fullName(1024, '\0'); while (getcwd(&fullName[0], fullName.size()) == nullptr) { if (errno != ERANGE) { throw cms::Exception("TFileService") << "Failed to get current directory (errno=" << errno << "): " << strerror(errno); } fullName.resize(fullName.size() * 2, '\0'); } fullName.resize(fullName.find('\0')); fullName += "/" + fileName_; std::map<std::string, std::string> fileData; fileData.insert(std::make_pair("Source", "TFileService")); edm::Service<edm::JobReport> reportSvc; reportSvc->reportAnalysisFile(fullName, fileData); fileNameRecorded_ = true; } } }
1,442
507
<gh_stars>100-1000 # terrascript/resource/grafana.py __all__ = []
28
443
<reponame>alichry/revsh /* * This file contains the constants defining the inner workings of the message bus. This also seems to be an * appropriate space to describe network communication, from the initialization routine through to the expected * form of bytes on the message bus. This probably wont ever be formal enough to be a proper API, but this should * get us most of the way there. * * Each of the stages of the process are detailed below. * */ #define PROTOCOL_MAJOR_VERSION 1 #define PROTOCOL_MINOR_VERSION 0 /********************************************************************************************************************** * * Network connection: * * 1) TCP connection: Normally, the target node connects back to the control node. In bindshell mode, this * will be reversed. * * 2) SSL connection: Regardless of who initiated the TCP connection, the control host is authoritative over * the SSL connection. It will decide which forms of SSL are appropriate, and disconnect if the target doesn't * agree. * * At this point the network is connected and the two nodes can communicate. * **********************************************************************************************************************/ /********************************************************************************************************************** * * Basic negotiation: * * 1) Protocol version: Both sides send their Major/Minor versions as network order unsigned shorts. Afterwards, they * receive the Major/Minor versions from the opposing node and compare. While used for reporting, no further checks * are made based on network protocol, though that may change in the future. * * 2) Message size: Both nodes send their desired message size. This is sent as an unsigned short in network order. * If either side receives a desired message size from their peer that is less than the MINIMUM_MESSAGE_SIZE * defined below, then it will immediately close the connection and exit. If both nodes decide to proceed, then * the max message size for all messages going forward will be the smaller of the two desired message sizes. * * At this point the messaging bus is active, and all future communication will be as messages (described in more * detail later in this document. * **********************************************************************************************************************/ /* This is the smallest message size we will respect when asked by the remote connection. */ #define MINIMUM_MESSAGE_SIZE 1024 /********************************************************************************************************************** * * Message bus initialization: * * Notes: * - The specifics of the message bus are described in detail at the end of this document. * - All messages in this section will use the DT_INIT data_type. Order is important. We aren't in a multiplexed * situation yet, so the messages in this section can (and must) occur in the order described here. * * 1) Interactive mode: Normally, a connection will be in interactive mode (i.e with a human sitting at a keyboard.) * A non-interactive mode is also supported. This allows for file / data transfer instead of terminal access. In * this phase of initialization both sides will send a message detailing if they plan on an interactive session or * not. This data is represented as a single unsigned char. 1 is interactive, 0 is non-interactive. If either end * requests non-interactive, then the entire communication will be non-interactive. If a non-interactive connection * is determined, no further initialization will take place, but rather the program will move straight into the * broker() loop. Once there it will pass its data along the message bus as data type DT_TTY. Behavior upon receipt * of a data_type other than DT_TTY is undefined. * * 2) Shell: The control node will send a message to the target instructing it which shell it should launch, as a * string. (The string may or may not be null terminated. It should be read in by its data_len argument.) If the * control node doesn't have a specification, then it will send an empty string (data_len = 0) at which point the * target node may choose which shell to spawn. * * 3) Environment: Some environment variables (such as TERM and LANG) are so core to how the terminal will function * that they are read from the operators environment on the control node and sent to the target node. As such, the * control node will send a message to the target node with this data. The data will be formatted as a single * string, whitespace delimited, null terminated. (It should still be read in by its data_len argument.) * E.g. "TERM=xterm LANG=en_US.utf8" It is expected that the target will then set these variables in the * environment appropriately. * * 4) Window size: The control node will send a message with the window size information relating to the operators * current window, as read with the TIOCGWINSZ ioctl(). The data will be the ws_row and ws_col fields from the * winsize struct. ("man tty_ioctl" for more info.) The ws_row and ws_col data will be stored in network order, * back to back in the data field. (Extract using data_len as always.) It is expected the target will inform the * pseudoterminal of the associated window size with a TIOCSWINSZ ioctl(). * * At this point, the system has been initialized and we are ready to enter the broker() loop for normal multiplexed * io handling. * **********************************************************************************************************************/ /********************************************************************************************************************** * * Message Bus Protocol Specification * * What follows is a description of the bytes expected to be set for the message bus to work. Every message is made * up of a header and a body. header_len, data_type, data_len are mandatory for the header, and data is mandatory for * the body. Depending on the data_type, there may be other headers as well. As always, the order listed here for * header and body components is important. Note, while header_len is mandatory, the programmer doesn't need to set * it manually. The header_len var is calculated before sending the message base off the data / header types. * * Header: * - header_len : unsigned short (network order) : Size of the remaining header data. * - data_type : unsigned char * - data_len : unsigned short (network order) * - Other data_type specific headers, if applicable, as noted below. * * Other headers used with DT_PROXY and DT_CONNECTION: * - header_type : unsigned short (network order) * - header_origin : unsigned short (network order) : Lists if control or target is the owner. * - header_id : unsigned short (network order) : FD of the connection at it's origin. * - header_proxy_type : unsigned short (network order) : Used during DT_PROXY_HT_CREATE, DT_PROXY_HT_REPORT, * and DT_CONNECTION_HT_CREATE to relay proxy type. * * Note: (header_origin, header_id) together form a tuple that acts as a unique identifier for the connection this * message refers to. * * Body: * - data : void * * **********************************************************************************************************************/ // The naming convention below is DT for "Data Type" and HT for "Header Type". // At some point in the future I may dive through the code and detail how each of these messages should look. As I said // above though, this isn't a real API specification yet. For now, go look at the specific handler code in handler.c // and examine the source for each of the message cases if you need more detail. /* Data Types */ /* DT_INIT: Initialization sequence data. */ #define DT_INIT 0 /* DT_TTY: TTY interaction data. */ /* This message type is always given priority because, despite added functionality, we are still a shell at heart. */ /* This will also be the data type used for passing data in the non-interactive mode. */ #define DT_TTY 1 /* DT_WINRESIZE: Window re-size event data. */ #define DT_WINRESIZE 2 /* DT_PROXY: Proxy meta-data. (e.g. setup, teardown, etc.) */ #define DT_PROXY 3 #define DT_PROXY_HT_CREATE 0 #define DT_PROXY_HT_DESTROY 1 // Used for sending data about listening proxies to the control node for reporting. #define DT_PROXY_HT_REPORT 2 /* DT_CONNECTION: Information related to established connections. */ #define DT_CONNECTION 4 #define DT_CONNECTION_HT_CREATE 0 #define DT_CONNECTION_HT_DESTROY 1 /* Normal data to be brokered back and forth. */ #define DT_CONNECTION_HT_DATA 2 /* * DT_CONNECTION_HT_DORMANT is used when a fd would block for writing, and our message queue is getting deep. * Tells the other side to stop reading from the associated remote fd until otherwise notified. Reset to normal * with DT_CONNECTION_HT_ACTIVE once the message write queue for this connection is empty. */ #define DT_CONNECTION_HT_DORMANT 3 #define DT_CONNECTION_HT_ACTIVE 4 /* DT_NOP: No Operation dummy message used for network keep-alive. */ #define DT_NOP 5 /* DT_ERROR: Used to send error reporting back to the control node for logging. */ // Note, this message type is generally indicative of some sort of... well... error. // As such, this reporting is typically handled as a best effort without guarantee of delivery. #define DT_ERROR 6 /* * Other protocol constants used in messaging. */ /* Proxy types. Set in message->header_proxy_type for DT_PROXY_HT_CREATE messages. */ #define PROXY_STATIC 0 #define PROXY_DYNAMIC 1 #define PROXY_TUN 2 #define PROXY_TAP 3 /* String representations of the proxy types above for reporting purposes. */ #define PROXY_STATIC_STRING "Static" #define PROXY_DYNAMIC_STRING "Dynamic" #define PROXY_TUN_STRING "Tun" #define PROXY_TAP_STRING "Tap"
2,672
400
import os import sys import torch import cflearn from cflearn.misc.toolkit import eval_context from cflearn.misc.toolkit import download_reference # prepare folder = os.path.dirname(__file__) repo_name = "stylegan2-ada-pytorch-main" repo_path = os.path.join(folder, repo_name) url = "https://github.com/NVlabs/stylegan2-ada-pytorch/archive/refs/heads/main.zip" os.system(f"wget {url}") os.system(f"mv main.zip {repo_name}.zip") os.system(f"unzip {repo_name}.zip -d {folder}") sys.path.insert(0, repo_path) import legacy torch.manual_seed(142857) z = torch.randn(1, 512) for src in [ "afhqcat", "afhqdog", "afhqwild", "brecahad", "ffhq", "metfaces", ]: with open(download_reference(src), "rb") as f: g = legacy.load_network_pkl(f)["G_ema"] cf_model_name = f"generator/style_gan2_generator.{src}" cfg = cflearn.DLZoo.load_model(cf_model_name, pretrained=True) print(f"=== checking {src} ===") with eval_context(g): o = g(z, None, force_fp32=True, noise_mode="const") with eval_context(cfg): cfo = cfg(0, {"input": z}, noise_mode="const")["predictions"] assert torch.allclose(o, cfo, atol=1.0e-4)
519
371
<reponame>js882829/tars from django.contrib import admin from tars.application import models class ApplicationAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(models.Application, ApplicationAdmin) class PackageAdmin(admin.ModelAdmin): list_display = ('name', 'version', 'application') admin.site.register(models.Package, PackageAdmin)
110
388
<gh_stars>100-1000 # Lint as: python3 # Copyright 2019 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. # ============================================================================== """Divider operation implementation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import numpy as np class IDividerImpl(abc.ABC): """abstract class for divider.""" def __init__(self, numerator_quantizer, denominator_quantizer, output_quantizer): self.numerator_quantizier = numerator_quantizer self.denominator_quantizer = denominator_quantizer self.output = output_quantizer @staticmethod @abc.abstractmethod def implemented_as(): pass class FloatingPointDivider(IDividerImpl): """floating point divider.""" def __init__(self, numerator_quantizer, denominator_quantizer, output_quantizer): super().__init__(numerator_quantizer, denominator_quantizer, output_quantizer) if self.output.bits is None: # decide f16/f32 according to numerator/denominator type bits = 0 if numerator_quantizer.is_floating_point: bits = max(bits, numerator_quantizer.bits) if denominator_quantizer.is_floating_point: bits = max(bits, denominator_quantizer.bits) self.output.bits = bits self.gate_bits = self.output.bits self.gate_factor = 1 @staticmethod def implemented_as(): # TODO(lishanok): change cost from "mul" to "divide" return "mul" class Shifter(IDividerImpl): """shifter type.""" # other_datatype/po2 def __init__(self, numerator_quantizer, denominator_quantizer, output_quantizer): super().__init__(numerator_quantizer, denominator_quantizer, output_quantizer) qbit_quantizer = numerator_quantizer po2_quantizer = denominator_quantizer (min_exp, max_exp) = po2_quantizer.get_min_max_exp() # since it's a divider, min_exp and max_exp swap # for calculating right and left shift tmp = min_exp min_exp = max_exp max_exp = tmp qbits_bits = qbit_quantizer.bits qbits_int_bits = qbit_quantizer.int_bits self.output.bits = int(qbits_bits + max_exp + min_exp) if (not qbit_quantizer.is_signed) and po2_quantizer.is_signed: # if qbit is signed, qbits_bits already has the sign_bit, # no need to +1, # if qbit is un_signed, po2 is unsigned, no need to +1 # if qbit is un_signed, po2 is signed, min_exp and max_exp # didnot include sign_bit, # therefore need to +1 self.output.bits += 1 self.output.int_bits = int(qbits_int_bits + max_exp) self.output.is_signed = qbit_quantizer.is_signed |\ po2_quantizer.is_signed self.output.is_floating_point = False if po2_quantizer.inference_value_counts > 0: # during qbn inference, count number of unique values self.gate_factor = po2_quantizer.inference_value_counts * 0.3 self.gate_bits = qbits_bits else: # programmable shifter, similar to sum gate self.gate_factor = 1 b = np.sqrt(2 ** po2_quantizer.bits * qbits_bits) self.gate_bits = b * np.log10(b) @staticmethod def implemented_as(): return "shifter" class Subtractor(IDividerImpl): """subtractor quantizer.""" # subtractor is only possible when numerator and denominator # are both po2 quantizers. def __init__(self, numerator_quantizer, denominator_quantizer, output_quantizer): super().__init__(numerator_quantizer, denominator_quantizer, output_quantizer) self.output.bits = max(numerator_quantizer.bits, denominator_quantizer.bits) + 1 self.output.int_bits = max(numerator_quantizer.int_bits, denominator_quantizer.int_bits) + 1 self.output.is_signed = 1 self.output.is_floating_point = False self.output.is_po2 = 1 if (numerator_quantizer.max_val_po2 == -1 or denominator_quantizer.max_val_po2 == -1): self.output.max_val_po2 = -1 else: # Adder is two po2_value multiply with each other self.output.max_val_po2 = numerator_quantizer.max_val_po2 /\ denominator_quantizer.max_val_po2 if "po2" in output_quantizer.name: # po2 * po2 if self.output.is_signed: output_quantizer.name = "quantized_po2" else: output_quantizer.name = "quantized_relu_po2" self.gate_bits = self.output.bits self.gate_factor = 1 @staticmethod def implemented_as(): return "add"
2,040
709
#include "platform.h" C_Errno_t(C_Int_t) Posix_FileSys_chdir(NullString8_t p) { return chdir((const char *) p); }
54
2,748
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.rpc.boot.runtime.adapter.processor; import com.alipay.sofa.rpc.common.utils.StringUtils; import com.alipay.sofa.rpc.config.AbstractInterfaceConfig; import com.alipay.sofa.rpc.config.ConsumerConfig; import com.alipay.sofa.rpc.config.ProviderConfig; import com.alipay.sofa.rpc.dynamic.DynamicConfigKeys; /** * @author zhaowang * @version : DynamicConfigProcessor.java, v 0.1 2020年03月11日 11:55 上午 zhaowang Exp $ */ public class DynamicConfigProcessor implements ConsumerConfigProcessor, ProviderConfigProcessor { private String dynamicConfig; public DynamicConfigProcessor(String dynamicConfig) { this.dynamicConfig = dynamicConfig; } @Override public void processorConsumer(ConsumerConfig consumerConfig) { setDynamicConfig(consumerConfig); } @Override public void processorProvider(ProviderConfig providerConfig) { setDynamicConfig(providerConfig); } private void setDynamicConfig(AbstractInterfaceConfig config) { String configAlias = config.getParameter(DynamicConfigKeys.DYNAMIC_ALIAS); if (StringUtils.isBlank(configAlias) && StringUtils.isNotBlank(dynamicConfig)) { config.setParameter(DynamicConfigKeys.DYNAMIC_ALIAS, dynamicConfig); } } public String getDynamicConfig() { return dynamicConfig; } public void setDynamicConfig(String dynamicConfig) { this.dynamicConfig = dynamicConfig; } }
717
1,178
<filename>avionics/motor/firmware/svpwm.c /* * Copyright 2020 Makani Technologies 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. */ #include "avionics/motor/firmware/svpwm.h" #include <assert.h> #include <float.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include "avionics/common/fast_math/fast_math.h" #include "avionics/common/strings.h" #include "avionics/firmware/cpu/peripherals.h" #include "avionics/firmware/cpu/registers.h" #include "avionics/motor/firmware/config_params.h" #include "avionics/motor/firmware/nhet.h" #define N2HET1_LRPFC 5 // Loop Resolution Prescaler Factor Code #define N2HET1_LR (1 << N2HET1_LRPFC) // N2HET Loop Resolution prescaler. #define MIN_GATE_HOLD_TIME 1.0e-6f // Min time between gate transitions [s]. // Period at which the ISR is called. float g_svpwm_isr_period; // Maximum value of a = v_ref / v_bus that can be achieved given a particular // minimum high / low gate driver time. 1 / sqrt(3) is derived from gamma = // sector angle = pi/6 where t1 + t2 is at a maximum. float g_svpwm_vref_vbus_limit = 0.577350269f; // 1 / sqrt(3) // This initialization assumes HR = 1 and uses a LR = N2HET1_LR. The pin // numbers provided here should all be even as the NHET uses the XOR function // for symmetrical PWM. void SvpwmInit(float svpwm_freq, int32_t pwm_per_isr) { // Start N2HET1 clock. PeripheralEnable(kPeripheralN2Het1); // Copy blank instructions from svpwm_nhet.c to N2HET1 RAM. vmemcpy(&HET1RAM, kHetInitSvpwm, sizeof(kHetInitSvpwm)); float f_vclk2 = (float)PeripheralGetClockFreq(kPeripheralN2Het1); // Set SVPWM frequency and store the achieved period. HET1RAM.REAL_CNT.MAX_COUNT = nearbyint(f_vclk2 / (N2HET1_LR * svpwm_freq)) - 1; float pwm_period = (float)(N2HET1_LR * (HET1RAM.REAL_CNT.MAX_COUNT + 1)) / f_vclk2; // Set ISR frequency and store the achieved period. HET1RAM.START.MAX_COUNT = pwm_per_isr * (HET1RAM.REAL_CNT.MAX_COUNT + 1) - 1; g_svpwm_isr_period = (float)(N2HET1_LR * (HET1RAM.START.MAX_COUNT + 1)) / f_vclk2; assert(fabsf(g_svpwm_isr_period - pwm_per_isr * pwm_period) < 10.0f * FLT_EPSILON * g_svpwm_isr_period); // Set the max duty cycle. g_svpwm_vref_vbus_limit = (1.0f - 2.0f * MIN_GATE_HOLD_TIME / pwm_period) / sqrtf(3.0f); assert(g_svpwm_vref_vbus_limit >= 0.0f && g_svpwm_vref_vbus_limit <= 1.0f / sqrtf(3.0f) + 5.0f * FLT_EPSILON); // Set the loop resolution prescaler. N2HET(1).HETPFR.LRPFC = N2HET1_LRPFC; // N2HET1 Pin ECMP Instruction // ---------- ---------------- // N2HET1[04] YAN1 ZAN1 // N2HET1[05] YAN2 ZAN2 // N2HET1[14] YB1 ZB1 // N2HET1[15] YB2 ZB2 // N2HET1[16] YBN1 ZBN1 // N2HET1[17] YBN2 ZBN2 // N2HET1[18] YC1 ZC1 // N2HET1[19] YC2 ZC2 // N2HET1[20] YCN1 ZCN1 // N2HET1[21] YCN2 ZCN2 // N2HET1[22] YA1 ZA1 // N2HET1[23] YA2 ZA2 // Set pins to output. N2HET(1).HETDIR.HETDIR4 = 1; N2HET(1).HETDIR.HETDIR14 = 1; N2HET(1).HETDIR.HETDIR16 = 1; N2HET(1).HETDIR.HETDIR18 = 1; N2HET(1).HETDIR.HETDIR20 = 1; N2HET(1).HETDIR.HETDIR22 = 1; // Set XOR pairs. N2HET(1).HETXOR.XORSHARE_5_4 = 1; N2HET(1).HETXOR.XORSHARE_15_14 = 1; N2HET(1).HETXOR.XORSHARE_17_16 = 1; N2HET(1).HETXOR.XORSHARE_19_18 = 1; N2HET(1).HETXOR.XORSHARE_21_20 = 1; N2HET(1).HETXOR.XORSHARE_23_22 = 1; // Enable DMA request. N2HET(1).REQENS.REQENA4 = 1; N2HET(1).REQDS.TDS4 = 1; // Ignore suspend. N2HET(1).HETGCR.IS = 1; // Set N2HET1 to master. N2HET(1).HETGCR.CMS = 1; } bool SvpwmCheckHetPinEna(void) { bool het_pin_ena = N2HET(1).HETGCR.HETPINENA; if (!het_pin_ena) N2HET(1).HETGCR.HETPINENA = 1; return het_pin_ena; } void SvpwmStart(void) { // Start N2HET1. N2HET(1).HETGCR.TO = 1; } // Set SVPWM times. Sets the individual phase on and off times // depending on which sector of the hexagon (see header file) we are // in. Representative timing diagrams for the first two sectors are // shown below. Note that the order of t1 and t2 swap, when starting // from (000), in the even sectors. The other sectors follow a // similar pattern. // // Sector I: // // t0/2 : t1 : t2 : t0 : t2 : t1 : t0/2 // :__________________________________________: // A _____| : : : : |______ // :____________________________: // B ____________| : : |_____________ // :______________: // C ___________________| |____________________ // // (000) (100) (110) (111) (110) (100) (000) // // // Sector II: // // t0/2 : t1 : t2 : t0 : t2 : t1 : t0/2 // ____________: : : :_____________ // A : |____________________________| : // ___________________: :____________________ // B : : |______________| : : // _____: : : : : :______ // C |__________________________________________| // // (111) (110) (010) (000) (010) (110) (000) // // The times t1 and t2 are consistent with Broeck (1988) with the // exception that they have already been scaled by the switching // period, i.e. they range from 0 to 1. static void SvpwmSetTimes(int32_t sector, float t1, float t2) { assert(1 <= sector && sector <= 6); assert(0.0f <= t1 && t1 <= 1.0f); assert(0.0f <= t2 && t2 <= 1.0f - t1); // Calculate time periods. Total period is MAX_COUNT multiplied by N2HET1_LR. int32_t t_total_counts = (HET1RAM.REAL_CNT.MAX_COUNT + 1) * N2HET1_LR; int32_t tz_counts = t_total_counts / 2; int32_t t1_counts = (int32_t)(t1 * (float)tz_counts); int32_t t2_counts = (int32_t)(t2 * (float)tz_counts); // Coerce values into valid range. if (t1_counts < 0) { t1_counts = 0; } else if (t1_counts > tz_counts) { t1_counts = tz_counts; } if (t2_counts < 0) { t2_counts = 0; } else if (t2_counts > tz_counts) { t2_counts = tz_counts; } int32_t t0_counts = tz_counts - t1_counts - t2_counts; if (t0_counts < 0) { t1_counts += t0_counts / 2; t2_counts = tz_counts - t1_counts; t0_counts = 0; } // Determine switching order from sector. Because of symmetrical // PWM t1 and t2 switch for even sectors. int32_t ta_counts, tb_counts, tc_counts; switch (sector) { case 1: ta_counts = t0_counts / 2; tb_counts = ta_counts + t1_counts; tc_counts = tb_counts + t2_counts; break; case 2: tb_counts = t0_counts / 2; ta_counts = tb_counts + t2_counts; tc_counts = ta_counts + t1_counts; break; case 3: tb_counts = t0_counts / 2; tc_counts = tb_counts + t1_counts; ta_counts = tc_counts + t2_counts; break; case 4: tc_counts = t0_counts / 2; tb_counts = tc_counts + t2_counts; ta_counts = tb_counts + t1_counts; break; case 5: tc_counts = t0_counts / 2; ta_counts = tc_counts + t1_counts; tb_counts = ta_counts + t2_counts; break; case 6: ta_counts = t0_counts / 2; tc_counts = ta_counts + t2_counts; tb_counts = tc_counts + t1_counts; break; default: assert(false); return; } // Select Y or Z buffer. LAST_CHK data is 1 when Z is in use and 0 // when Y is in use. volatile EcmpInstruction *phase_a_cmp; volatile EcmpInstruction *phase_b_cmp; volatile EcmpInstruction *phase_c_cmp; if (HET1RAM.LAST_CHK.DATA == 1) { // Y buffer. phase_a_cmp = &HET1RAM.YA1; phase_b_cmp = &HET1RAM.YB1; phase_c_cmp = &HET1RAM.YC1; } else { // Z buffer. phase_a_cmp = &HET1RAM.ZA1; phase_b_cmp = &HET1RAM.ZB1; phase_c_cmp = &HET1RAM.ZC1; } // If phase A and C are physically swapped, swap here. if (kMotorConfigParams->phase_swap == kMotorPhaseSwapAc) { volatile EcmpInstruction *temp_cmp = phase_a_cmp; phase_a_cmp = phase_c_cmp; phase_c_cmp = temp_cmp; } // Calculate absolute switching times. // LR = 32, so shift the HR data compare value by 2 [TRM Table 23-6]. // Instruction order: XX1, XX2, XXN1, XXN2. (phase_a_cmp + 0)->raw.data = ta_counts << 2; (phase_a_cmp + 2)->raw.data = ta_counts << 2; (phase_a_cmp + 1)->raw.data = (t_total_counts - ta_counts) << 2; (phase_a_cmp + 3)->raw.data = (t_total_counts - ta_counts) << 2; (phase_b_cmp + 0)->raw.data = tb_counts << 2; (phase_b_cmp + 2)->raw.data = tb_counts << 2; (phase_b_cmp + 1)->raw.data = (t_total_counts - tb_counts) << 2; (phase_b_cmp + 3)->raw.data = (t_total_counts - tb_counts) << 2; (phase_c_cmp + 0)->raw.data = tc_counts << 2; (phase_c_cmp + 2)->raw.data = tc_counts << 2; (phase_c_cmp + 1)->raw.data = (t_total_counts - tc_counts) << 2; (phase_c_cmp + 3)->raw.data = (t_total_counts - tc_counts) << 2; } // Latch opposite PWM buffer for next NHET cycle. static void SvpwmLatchTimes(void) { if (HET1RAM.LAST_CHK.DATA == 0) { HET1RAM.LAST_CHK.DATA = 1; // Y buffer. } else { HET1RAM.LAST_CHK.DATA = 0; // Z buffer. } } // Determines sector, sector angle, and the t1 and t2 PWM times. void SvpwmSetReference(float angle, float v_ref, float v_bus) { assert(v_ref >= 0.0f); assert(v_bus >= 0.0f); int32_t sector; float sector_angle; if (angle >= 0.0f) { sector = (int32_t)(angle * (3.0f / PI_F)); sector_angle = angle - sector * (PI_F / 3.0f); sector = 1 + sector % 6; } else { sector = (int32_t)(-angle * (3.0f / PI_F)); sector_angle = angle + (sector + 1) * (PI_F / 3.0f); sector = 6 - sector % 6; } // Find normalized vector length. Limit solution to circle // inscribed in space vector hexagon. float a = g_svpwm_vref_vbus_limit; if (v_bus > 0.0f) { a = Saturatef(v_ref / v_bus, 0.0f, g_svpwm_vref_vbus_limit); } float sin_pi3_angle = SinLookup(PI_F / 3.0f - sector_angle); float sin_angle = SinLookup(sector_angle); // t1 and t2 are normalized by tz (the PWM half-period). Note that // without the saturation, it is possible for these to go very // slightly negative due to numerical errors in the sector_angle // calculation. float t1 = Maxf(a * sin_pi3_angle * ((3.0f / 2.0f) / sinf(PI_F / 3.0f)), 0.0f); float t2 = Maxf(a * sin_angle * ((3.0f / 2.0f) / sinf(PI_F / 3.0f)), 0.0f); SvpwmSetTimes(sector, t1, t2); SvpwmLatchTimes(); }
5,141
501
package springboot.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import springboot.client.handler.HttpClientInitializer; import java.net.InetSocketAddress; public class HttpClient { public void start() throws Exception{ EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new HttpClientInitializer()); // 发起异步连接 ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 3560)); // 当客户端链路关闭 future.channel().closeFuture().sync(); }finally { // 优雅退出,释放NIO线程组 group.shutdownGracefully(); } } public static void main(String args[])throws Exception{ new HttpClient().start(); } }
551
852
#ifndef SimHcalNoiseStorage_h #define SimHcalNoiseStorage_h /** \class HcalNoiseStorage * * DataMixingModule is the EDProducer subclass * that overlays rawdata events on top of MC, * using real data for pileup simulation * This class is used to pass noise hits from the individual * Hcal channels to the new digitization code. * * \author <NAME>, University of Notre Dame * * \version 1st Version February 2009 * ************************************************************/ #include "CalibFormats/CaloObjects/interface/CaloSamples.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/HcalDigi/interface/HBHEDataFrame.h" #include "DataFormats/HcalDigi/interface/HFDataFrame.h" #include "DataFormats/HcalDigi/interface/HODataFrame.h" #include "DataFormats/HcalDigi/interface/HcalDigiCollections.h" #include "DataFormats/Provenance/interface/ProductID.h" #include "SimCalorimetry/CaloSimAlgos/interface/CaloVNoiseSignalGenerator.h" #include <map> #include <string> #include <vector> namespace CLHEP { class HepRandomEngine; } namespace edm { class HcalNoiseStorage : public CaloVNoiseSignalGenerator { public: HcalNoiseStorage(){}; ~HcalNoiseStorage() override{}; /** standard constructor*/ // explicit HcalNoiseStorage(); /**Default destructor*/ // virtual ~HcalNoiseStorage(); void fillNoiseSignals(CLHEP::HepRandomEngine *) override{}; private: }; } // namespace edm #endif // SimHcalNoiseStorage_h
494
408
<filename>src/main/python/rlbot/parsing/directory_scanner.py import glob import os from configparser import NoSectionError, MissingSectionHeaderError, NoOptionError, ParsingError from typing import Set from rlbot.parsing.bot_config_bundle import BotConfigBundle, ScriptConfigBundle, get_bot_config_bundle, get_script_config_bundle def scan_directory_for_bot_configs(root_dir) -> Set[BotConfigBundle]: """ Recursively scans a directory for all valid bot configs. :param root_dir: Directory to scan. :return: The set of bot configs that were found. """ configs = set() for filename in glob.iglob(os.path.join(root_dir, '**/*.cfg'), recursive=True): try: bundle = get_bot_config_bundle(filename) configs.add(bundle) except (NoSectionError, MissingSectionHeaderError, NoOptionError, AttributeError, ParsingError, FileNotFoundError) as ex: pass return configs def scan_directory_for_script_configs(root_dir) -> Set[ScriptConfigBundle]: """ Recursively scans a directory for all valid script configs. :param root_dir: Directory to scan. :return: The set of script configs that were found. """ configs = set() for filename in glob.iglob(os.path.join(root_dir, '**/*.cfg'), recursive=True): try: bundle = get_script_config_bundle(filename) configs.add(bundle) except (NoSectionError, MissingSectionHeaderError, NoOptionError, AttributeError, ParsingError, FileNotFoundError): pass return configs
575
348
<gh_stars>100-1000 {"nom":"Sarnois","circ":"2ème circonscription","dpt":"Oise","inscrits":272,"abs":110,"votants":162,"blancs":9,"nuls":4,"exp":149,"res":[{"nuance":"FN","nom":"<NAME>","voix":91},{"nuance":"REM","nom":"<NAME>","voix":58}]}
97
2,576
/* * Copyright (c) 2010-2020. Axon Framework * * 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.axonframework.eventhandling; import org.axonframework.eventhandling.tokenstore.TokenStore; import java.util.Objects; import java.util.OptionalLong; /** * Interface describing the status of a {@link Segment} of a {@link TrackingEventProcessor}. * * @author <NAME> * @since 3.2 */ public interface EventTrackerStatus { /** * The segment for which this status is valid. * * @return segment for which this status is valid */ Segment getSegment(); /** * Whether the Segment of this status has caught up with the head of the event stream. Note that this is no * guarantee that this segment is still processing at (or near) real-time events. It merely indicates that this * segment has been at the head of the stream since it started processing. It may have fallen back since then. * * @return whether the Segment of this status has caught up with the head of the event stream */ boolean isCaughtUp(); /** * Indicates whether this Segment is still replaying previously processed Events. * <p> * Note that this method will only recognize a replay if the tokens have been reset using {@link * TrackingEventProcessor#resetTokens()}. Removing tokens directly from the underlying {@link TokenStore} will not * be recognized as a replay. * * @return {@code true} if this segment is replaying historic events after a {@link * TrackingEventProcessor#resetTokens() reset}, otherwise {@code false} */ boolean isReplaying(); /** * Indicates whether this Segment is still merging two (or more) Segments. The merging process will be done once all * Segments have reached the same position. * * @return {@code true} if this segment is merging Segments, otherwise {@code false} */ boolean isMerging(); /** * Return the estimated relative token position this Segment will have after a merge operation is complete. Will * return a non-empty result as long as {@link EventTrackerStatus#isMerging()} } returns true. In case no estimation * can be given or no merge in progress, an {@code OptionalLong.empty()} will be returned. * * @return return the estimated relative position this Segment will reach after a merge operation is complete. */ OptionalLong mergeCompletedPosition(); /** * The tracking token of the last event that has been seen by this Segment. * <p> * The returned tracking token represents the position of this segment in the event stream. In case of a recent * merge of segments, the token represents the lowest position of the two merged segments. * * @return tracking token of the last event that has been seen by this Segment */ TrackingToken getTrackingToken(); /** * Indicates whether this status represents an error. When this method return {@code true}, the {@link #getError()} * will return the exception that caused the failure. * * @return {@code true} if an error was reported, otherwise {@code false} */ boolean isErrorState(); /** * Returns the exception that caused processing to fail, if present. If the segment is being processed normally, * this method returns {@code null}. * * @return the exception that caused processing to fail, or {@code null} when processing normally */ Throwable getError(); /** * Return the estimated relative current token position this Segment represents. In case of replay is active, return * the estimated relative position reached by merge operation. In case of merge is active, return the estimated * relative position reached by merge operation. In case no estimation can be given, or no replay or merge in * progress, an {@code OptionalLong.empty()} will be returned. * * @return return the estimated relative current token position this Segment represents */ OptionalLong getCurrentPosition(); /** * Return the relative position at which a reset was triggered for this Segment. In case a replay finished or no * replay is active, an {@code OptionalLong.empty()} will be returned. * * @return the relative position at which a reset was triggered for this Segment */ OptionalLong getResetPosition(); /** * Returns a {@code boolean} describing whether this {@link EventTrackerStatus} is starting it's progress for the * first time. Particularly useful if the {@link EventTrackerStatusChangeListener} should react to added status'. * * @return {@code true} if this {@link EventTrackerStatus} just started, {@code false} otherwise */ default boolean trackerAdded() { return false; } /** * Returns a {@code boolean} describing whether this {@link EventTrackerStatus} has just stopped it's progress. * Particularly useful if the {@link EventTrackerStatusChangeListener} should react to removed status'. * * @return {@code true} if this {@link EventTrackerStatus} was just removed, {@code false} otherwise */ default boolean trackerRemoved() { return false; } /** * Check whether {@code this} {@link EventTrackerStatus} is different from {@code that}. * * @param that the other {@link EventTrackerStatus} to validate the difference with * @return {@code true} if both {@link EventTrackerStatus}'s are different, {@code false} otherwise */ default boolean isDifferent(EventTrackerStatus that) { return isDifferent(that, true); } /** * Check whether {@code this} {@link EventTrackerStatus} is different from {@code that}. * * @param that the other {@link EventTrackerStatus} to validate the difference with * @param validatePositions flag dictating whether {@link #matchPositions(EventTrackerStatus)} should be taken into * account when matching * @return {@code true} if both {@link EventTrackerStatus}'s are different, {@code false} otherwise */ default boolean isDifferent(EventTrackerStatus that, boolean validatePositions) { if (this == that) { return false; } if (that == null || this.getClass() != that.getClass()) { return true; } boolean matchingStates = matchStates(that); boolean matchingPositions = !validatePositions || matchPositions(that); return !matchingStates || !matchingPositions; } /** * Match the boolean state fields of {@code this} and {@code that}. This means {@link #isCaughtUp()}, {@link * #isReplaying()}, {@link #isMerging()} and {@link #isErrorState()} are taken into account. * * @param that the other {@link EventTrackerStatus} to match with * @return {@code true} if the boolean fields of {@code this} and {@code that} match, otherwise {@code false} */ default boolean matchStates(EventTrackerStatus that) { return Objects.equals(this.isCaughtUp(), that.isCaughtUp()) && Objects.equals(this.isReplaying(), that.isReplaying()) && Objects.equals(this.isMerging(), that.isMerging()) && Objects.equals(this.isErrorState(), that.isErrorState()); } /** * Match the position fields of {@code this} and {@code that}. This means {@link #getCurrentPosition()}, {@link * #getResetPosition()} and {@link #mergeCompletedPosition()} ()} are taken into account. * * @param that the other {@link EventTrackerStatus} to match with * @return {@code true} if the positions fields of {@code this} and {@code that} match, otherwise {@code false} */ default boolean matchPositions(EventTrackerStatus that) { return Objects.equals(this.getCurrentPosition(), that.getCurrentPosition()) && Objects.equals(this.getResetPosition(), that.getResetPosition()) && Objects.equals(this.mergeCompletedPosition(), that.mergeCompletedPosition()); } }
2,746
787
<reponame>zhuohuwu0603/leetcode_cpp_lzl124631x<gh_stars>100-1000 // OJ: https://leetcode.com/problems/tallest-billboard // Author: github.com/lzl124631x // Time: O(NS) where N is the length of `rods`, // and S is the maximum of `sum(rods[i..j])` // Space: O(NS) // Ref: https://leetcode.com/articles/tallest-billboard/ class Solution { private: vector<vector<int>> dp; int dfs(vector<int>& rods, int i, int s) { if (i == rods.size()) return s == 5000 ? 0 : INT_MIN; if (dp[i][s] != INT_MIN) return dp[i][s]; int ans = dfs(rods, i + 1, s); ans = max(ans, dfs(rods, i + 1, s - rods[i])); ans = max(ans, rods[i] + dfs(rods, i + 1, s + rods[i])); return dp[i][s] = ans; } public: int tallestBillboard(vector<int>& rods) { int N = rods.size(); dp = vector<vector<int>>(N, vector<int>(10001, INT_MIN)); return dfs(rods, 0, 5000); } };
449
360
<reponame>Yanci0/openGauss-server /* -------------------------------------------------------------------- * guc_storage.h * * External declarations pertaining to backend/utils/misc/guc-file.l * and backend/utils/misc/guc/guc_storage.cpp * * Copyright (c) 2000-2012, PostgreSQL Global Development Group * Written by <NAME> <<EMAIL>>. * * src/include/utils/guc_storage.h * -------------------------------------------------------------------- */ #ifndef GUC_STORAGE_H #define GUC_STORAGE_H extern void InitStorageConfigureNames(); extern bool check_enable_gtm_free(bool* newval, void** extra, GucSource source); extern void InitializeNumLwLockPartitions(void); #endif /* GUC_STORAGE_H */
207
4,772
package example.repo; import example.model.Customer1916; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1916Repository extends CrudRepository<Customer1916, Long> { List<Customer1916> findByLastName(String lastName); }
87
14,668
<reponame>zealoussnow/chromium<filename>third_party/blink/tools/blinkpy/web_tests/try_flag_unittest.py # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from blinkpy.common.host_mock import MockHost from blinkpy.common.net.git_cl import TryJobStatus from blinkpy.common.net.git_cl_mock import MockGitCL from blinkpy.common.net.results_fetcher import Build from blinkpy.common.net.web_test_results import WebTestResults from blinkpy.common.path_finder import PathFinder from blinkpy.web_tests.try_flag import TryFlag class TryFlagTest(unittest.TestCase): def __init__(self, *args, **kwargs): self.linux_build = Build('linux-rel', 100) self.mac_build = Build('mac-rel', 101) self.win_build = Build('win7-rel', 102) self.mock_try_results = { self.linux_build: TryJobStatus('COMPLETED', 'SUCCESS'), self.win_build: TryJobStatus('COMPLETED', 'SUCCESS'), self.mac_build: TryJobStatus('COMPLETED', 'SUCCESS') } super(TryFlagTest, self).__init__(*args, **kwargs) def _run_trigger_test(self, regenerate): host = MockHost() git = host.git() git_cl = MockGitCL(host) finder = PathFinder(host.filesystem) flag_file = finder.path_from_web_tests( 'additional-driver-flag.setting') flag_expectations_file = finder.path_from_web_tests( 'FlagExpectations', 'foo') cmd = ['trigger', '--flag=--foo'] if regenerate: cmd.append('--regenerate') TryFlag(cmd, host, git_cl).run() expected_added_paths = {flag_file} expected_commits = [[ 'Flag try job: force --foo for run_web_tests.py.' ]] if regenerate: expected_added_paths.add(flag_expectations_file) expected_commits.append( ['Flag try job: clear expectations for --foo.']) self.assertEqual(git.added_paths, expected_added_paths) self.assertEqual(git.local_commits(), expected_commits) self.assertEqual(git_cl.calls, [[ 'git', 'cl', 'upload', '--bypass-hooks', '-f', '-m', 'Flag try job for --foo.' ], [ 'git', 'cl', 'try', '-B', 'luci.chromium.try', '-b', 'linux-rel' ], [ 'git', 'cl', 'try', '-B', 'luci.chromium.try', '-b', 'mac-rel' ], ['git', 'cl', 'try', '-B', 'luci.chromium.try', '-b', 'win7-rel']]) def test_trigger(self): self._run_trigger_test(regenerate=False) self._run_trigger_test(regenerate=True) def _setup_mock_results(self, results_fetcher): results_fetcher.set_results( self.linux_build, WebTestResults({ 'tests': { 'something': { 'fail-everywhere.html': { 'expected': 'FAIL', 'actual': 'FAIL', 'is_unexpected': True }, 'fail-win-and-linux.html': { 'expected': 'FAIL', 'actual': 'FAIL', 'is_unexpected': True } } } })) results_fetcher.set_results( self.win_build, WebTestResults({ 'tests': { 'something': { 'fail-everywhere.html': { 'expected': 'FAIL', 'actual': 'FAIL', 'is_unexpected': True }, 'fail-win-and-linux.html': { 'expected': 'FAIL', 'actual': 'FAIL', 'is_unexpected': True } } } })) results_fetcher.set_results( self.mac_build, WebTestResults({ 'tests': { 'something': { 'pass-unexpectedly-mac.html': { 'expected': 'FAIL', 'actual': 'PASS', 'is_unexpected': True }, 'fail-everywhere.html': { 'expected': 'FAIL', 'actual': 'FAIL', 'is_unexpected': True } } } })) def test_update(self): host = MockHost() filesystem = host.filesystem finder = PathFinder(filesystem) flag_expectations_file = finder.path_from_web_tests( 'FlagExpectations', 'foo') filesystem.write_text_file( flag_expectations_file, '# results: [ Failure ]\nsomething/pass-unexpectedly-mac.html [ Failure ]' ) self._setup_mock_results(host.results_fetcher) cmd = ['update', '--flag=--foo'] TryFlag(cmd, host, MockGitCL(host, self.mock_try_results)).run() def results_url(build): return '%s/%s/%s/%s/layout-test-results/results.html' % ( 'https://test-results.appspot.com/data/layout_results', build.builder_name, build.build_number, 'blink_web_tests%20%28with%20patch%29') self.assertEqual( host.stdout.getvalue(), '\n'.join([ 'Fetching results...', '-- Linux: %s' % results_url(self.linux_build), '-- Mac: %s' % results_url(self.mac_build), '-- Win: %s' % results_url(self.win_build), '', '### 1 unexpected passes:', '', '[ Mac ] something/pass-unexpectedly-mac.html [ Pass ]', '', '### 5 unexpected failures:', '', '[ Linux ] something/fail-everywhere.html [ Failure ]', '[ Mac ] something/fail-everywhere.html [ Failure ]', '[ Win ] something/fail-everywhere.html [ Failure ]', '[ Linux ] something/fail-win-and-linux.html [ Failure ]', '[ Win ] something/fail-win-and-linux.html [ Failure ]', '' ])) def test_update_irrelevant_unexpected_pass(self): host = MockHost() filesystem = host.filesystem finder = PathFinder(filesystem) flag_expectations_file = finder.path_from_web_tests( 'FlagExpectations', 'foo') self._setup_mock_results(host.results_fetcher) cmd = ['update', '--flag=--foo'] # Unexpected passes that don't have flag-specific failure expectations # should not be reported. filesystem.write_text_file(flag_expectations_file, '') TryFlag(cmd, host, MockGitCL(host, self.mock_try_results)).run() self.assertTrue('### 0 unexpected passes' in host.stdout.getvalue()) def test_invalid_action(self): host = MockHost() cmd = ['invalid', '--flag=--foo'] TryFlag(cmd, host, MockGitCL(host)).run() self.assertEqual(host.stderr.getvalue(), 'specify "trigger" or "update"\n')
3,886
3,212
<filename>nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowSnippet.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.controller; import org.apache.nifi.controller.exception.ProcessorInstantiationException; import org.apache.nifi.controller.flow.FlowManager; import org.apache.nifi.groups.ProcessGroup; public interface FlowSnippet { /** * Validates that the FlowSnippet can be added to the given ProcessGroup * @param group the group to add the snippet to */ void validate(final ProcessGroup group); /** * Verifies that the components referenced within the snippet are valid * * @throws IllegalStateException if any component within the snippet can is not a known extension */ void verifyComponentTypesInSnippet(); /** * Instantiates this snippet, adding it to the given Process Group * * @param flowManager the FlowManager * @param flowController the FlowController * @param group the group to add the snippet to * @throws ProcessorInstantiationException if unable to instantiate any of the Processors within the snippet * @throws org.apache.nifi.controller.exception.ControllerServiceInstantiationException if unable to instantiate any of the Controller Services within the snippet */ void instantiate(FlowManager flowManager, FlowController flowController, ProcessGroup group) throws ProcessorInstantiationException; }
629
369
/** @file @brief Header @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef INCLUDED_EyeTrackerRemoteFactory_h_GUID_6788A8FD_F38F_419F_D2F2_6FCA976CADB4 #define INCLUDED_EyeTrackerRemoteFactory_h_GUID_6788A8FD_F38F_419F_D2F2_6FCA976CADB4 // Internal Includes #include "VRPNConnectionCollection.h" #include <osvr/Common/InterfaceList.h> #include <osvr/Common/OriginalSource.h> #include <osvr/Util/SharedPtr.h> #include <osvr/Client/RemoteHandler.h> #include <osvr/Common/ClientContext.h> // Library/third-party includes // - none // Standard includes // - none namespace osvr { namespace client { class EyeTrackerRemoteFactory { public: EyeTrackerRemoteFactory(VRPNConnectionCollection const &conns); template <typename T> void registerWith(T &factory) const { factory.addFactory("eyetracker", *this); } shared_ptr<RemoteHandler> operator()(common::OriginalSource const &source, common::InterfaceList &ifaces, common::ClientContext &ctx); private: VRPNConnectionCollection m_conns; }; } // namespace client } // namespace osvr #endif // INCLUDED_EyeTrackerRemoteFactory_h_GUID_6788A8FD_F38F_419F_D2F2_6FCA976CADB4
670
493
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #ifndef CACHE_STREAM_SINK_HPP #define CACHE_STREAM_SINK_HPP #include <iostream> #include <memory> #include <boost/iostreams/stream.hpp> #include <fileio/general_fstream_sink.hpp> #include <fileio/fixed_size_cache_manager.hpp> namespace graphlab { namespace fileio_impl { /** * \internal * * A boost::iostreams::sink concept implemented using cache_block as the underlying * sink device. */ class cache_stream_sink { typedef fileio::cache_id_type cache_id_type; public: typedef char char_type; struct category: public boost::iostreams::sink_tag, boost::iostreams::closable_tag, boost::iostreams::multichar_tag {}; /** * Construct the sink from a cache_id. * * Intialize the underlying data sink, either the in memory array * or the on disk cache file. */ explicit cache_stream_sink(cache_id_type cache_id); /// Destructor. CLoses the stream. ~cache_stream_sink(); /** * Attempts to write bufsize bytes into the stream from the buffer. * Returns the actual number of bytes written. Returns -1 on failure. */ std::streamsize write(const char* c, std::streamsize bufsize); /** * Returns true if the file is opened */ bool is_open() const; /** * Closes all file handles */ void close(); /** * Seeks to a different location. Will fail on compressed files. */ std::streampos seek(std::streamoff off, std::ios_base::seekdir way); /** * Returns true if the stream is good. See std::ios_base */ bool good() const; /** * Returns true if the stream is bad. See std::ios_base */ bool bad() const; /** * Returns true if a stream operation failed. See std::ios_base */ bool fail() const; private: fileio::fixed_size_cache_manager& cache_manager; std::shared_ptr<fileio::cache_block> out_block; std::shared_ptr<general_fstream_sink> out_file; }; } // end of fileio } // end of graphlab #endif
727
1,738
<filename>dev/Gems/ScriptCanvas/Code/Editor/GraphCanvas/Components/NodeDescriptors/NodeDescriptorComponent.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "precompiled.h" #include <GraphCanvas/Components/SceneBus.h> #include <Editor/GraphCanvas/Components/NodeDescriptors/NodeDescriptorComponent.h> namespace ScriptCanvasEditor { //////////////////////////// // NodeDescriptorComponent //////////////////////////// void NodeDescriptorComponent::Reflect(AZ::ReflectContext* reflect) { if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflect)) { serializeContext->Class<NodeDescriptorComponent, AZ::Component>() ->Version(0) ; } } NodeDescriptorComponent::NodeDescriptorComponent() : m_nodeDescriptorType(NodeDescriptorType::Unknown) { } NodeDescriptorComponent::NodeDescriptorComponent(NodeDescriptorType descriptorType) : m_nodeDescriptorType(descriptorType) { } void NodeDescriptorComponent::Init() { } void NodeDescriptorComponent::Activate() { NodeDescriptorRequestBus::Handler::BusConnect(GetEntityId()); GraphCanvas::NodeNotificationBus::Handler::BusConnect(GetEntityId()); } void NodeDescriptorComponent::Deactivate() { GraphCanvas::NodeNotificationBus::Handler::BusDisconnect(); NodeDescriptorRequestBus::Handler::BusDisconnect(); } void NodeDescriptorComponent::OnAddedToScene(const AZ::EntityId& sceneId) { AZ::EntityId scriptCanvasNodeId = FindScriptCanvasNodeId(); ScriptCanvas::NodeNotificationsBus::Handler::BusConnect(scriptCanvasNodeId); OnAddedToGraphCanvasGraph(sceneId, scriptCanvasNodeId); bool isEnabled = true; ScriptCanvas::NodeRequestBus::EventResult(isEnabled, scriptCanvasNodeId, &ScriptCanvas::NodeRequests::IsNodeEnabled); if (!isEnabled) { GraphCanvas::GraphId graphId; GraphCanvas::SceneMemberRequestBus::EventResult(graphId, GetEntityId(), &GraphCanvas::SceneMemberRequests::GetScene); GraphCanvas::SceneRequestBus::Event(graphId, &GraphCanvas::SceneRequests::Disable, GetEntityId()); } } void NodeDescriptorComponent::OnAddedToGraphCanvasGraph(const GraphCanvas::GraphId& graphId, const AZ::EntityId& scriptCanvasNodeId) { AZ_UNUSED(graphId); AZ_UNUSED(scriptCanvasNodeId); } AZ::EntityId NodeDescriptorComponent::FindScriptCanvasNodeId() const { AZStd::any* userData = nullptr; GraphCanvas::NodeRequestBus::EventResult(userData, GetEntityId(), &GraphCanvas::NodeRequests::GetUserData); AZ::EntityId* scNodeId = AZStd::any_cast<AZ::EntityId>(userData); if (scNodeId) { return (*scNodeId); } return AZ::EntityId(); } }
1,277
372
<reponame>yoshi-code-bot/google-api-java-client-services /* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudchannel.v1.model; /** * Specifies transfer eligibility of a SKU. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Channel API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudChannelV1TransferEligibility extends com.google.api.client.json.GenericJson { /** * Localized description if reseller is not eligible to transfer the SKU. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * Specified the reason for ineligibility. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ineligibilityReason; /** * Whether reseller is eligible to transfer the SKU. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean isEligible; /** * Localized description if reseller is not eligible to transfer the SKU. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * Localized description if reseller is not eligible to transfer the SKU. * @param description description or {@code null} for none */ public GoogleCloudChannelV1TransferEligibility setDescription(java.lang.String description) { this.description = description; return this; } /** * Specified the reason for ineligibility. * @return value or {@code null} for none */ public java.lang.String getIneligibilityReason() { return ineligibilityReason; } /** * Specified the reason for ineligibility. * @param ineligibilityReason ineligibilityReason or {@code null} for none */ public GoogleCloudChannelV1TransferEligibility setIneligibilityReason(java.lang.String ineligibilityReason) { this.ineligibilityReason = ineligibilityReason; return this; } /** * Whether reseller is eligible to transfer the SKU. * @return value or {@code null} for none */ public java.lang.Boolean getIsEligible() { return isEligible; } /** * Whether reseller is eligible to transfer the SKU. * @param isEligible isEligible or {@code null} for none */ public GoogleCloudChannelV1TransferEligibility setIsEligible(java.lang.Boolean isEligible) { this.isEligible = isEligible; return this; } @Override public GoogleCloudChannelV1TransferEligibility set(String fieldName, Object value) { return (GoogleCloudChannelV1TransferEligibility) super.set(fieldName, value); } @Override public GoogleCloudChannelV1TransferEligibility clone() { return (GoogleCloudChannelV1TransferEligibility) super.clone(); } }
1,167
3,508
<gh_stars>1000+ package com.fishercoder; import com.fishercoder.solutions._1588; import org.junit.BeforeClass; import org.junit.Test; import static junit.framework.TestCase.assertEquals; public class _1588Test { private static _1588.Solution1 solution1; @BeforeClass public static void setup() { solution1 = new _1588.Solution1(); } @Test public void test1() { assertEquals(58, solution1.sumOddLengthSubarrays(new int[]{1, 4, 2, 5, 3})); } }
196
3,102
<reponame>LambdaMan/clang //====-- unittests/Frontend/PCHPreambleTest.cpp - FrontendAction tests ---====// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/FrontendOptions.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "gtest/gtest.h" using namespace llvm; using namespace clang; namespace { class ReadCountingInMemoryFileSystem : public vfs::InMemoryFileSystem { std::map<std::string, unsigned> ReadCounts; public: ErrorOr<std::unique_ptr<vfs::File>> openFileForRead(const Twine &Path) override { SmallVector<char, 128> PathVec; Path.toVector(PathVec); llvm::sys::path::remove_dots(PathVec, true); ++ReadCounts[std::string(PathVec.begin(), PathVec.end())]; return InMemoryFileSystem::openFileForRead(Path); } unsigned GetReadCount(const Twine &Path) const { auto it = ReadCounts.find(Path.str()); return it == ReadCounts.end() ? 0 : it->second; } }; class PCHPreambleTest : public ::testing::Test { IntrusiveRefCntPtr<ReadCountingInMemoryFileSystem> VFS; StringMap<std::string> RemappedFiles; std::shared_ptr<PCHContainerOperations> PCHContainerOpts; FileSystemOptions FSOpts; public: void SetUp() override { ResetVFS(); } void TearDown() override {} void ResetVFS() { VFS = new ReadCountingInMemoryFileSystem(); // We need the working directory to be set to something absolute, // otherwise it ends up being inadvertently set to the current // working directory in the real file system due to a series of // unfortunate conditions interacting badly. // What's more, this path *must* be absolute on all (real) // filesystems, so just '/' won't work (e.g. on Win32). VFS->setCurrentWorkingDirectory("//./"); } void AddFile(const std::string &Filename, const std::string &Contents) { ::time_t now; ::time(&now); VFS->addFile(Filename, now, MemoryBuffer::getMemBufferCopy(Contents, Filename)); } void RemapFile(const std::string &Filename, const std::string &Contents) { RemappedFiles[Filename] = Contents; } std::unique_ptr<ASTUnit> ParseAST(const std::string &EntryFile) { PCHContainerOpts = std::make_shared<PCHContainerOperations>(); std::shared_ptr<CompilerInvocation> CI(new CompilerInvocation); CI->getFrontendOpts().Inputs.push_back( FrontendInputFile(EntryFile, FrontendOptions::getInputKindForExtension( llvm::sys::path::extension(EntryFile).substr(1)))); CI->getTargetOpts().Triple = "i386-unknown-linux-gnu"; CI->getPreprocessorOpts().RemappedFileBuffers = GetRemappedFiles(); PreprocessorOptions &PPOpts = CI->getPreprocessorOpts(); PPOpts.RemappedFilesKeepOriginalName = true; IntrusiveRefCntPtr<DiagnosticsEngine> Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions, new DiagnosticConsumer)); FileManager *FileMgr = new FileManager(FSOpts, VFS); std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation( CI, PCHContainerOpts, Diags, FileMgr, false, CaptureDiagsKind::None, /*PrecompilePreambleAfterNParses=*/1); return AST; } bool ReparseAST(const std::unique_ptr<ASTUnit> &AST) { bool reparseFailed = AST->Reparse(PCHContainerOpts, GetRemappedFiles(), VFS); return !reparseFailed; } unsigned GetFileReadCount(const std::string &Filename) const { return VFS->GetReadCount(Filename); } private: std::vector<std::pair<std::string, llvm::MemoryBuffer *>> GetRemappedFiles() const { std::vector<std::pair<std::string, llvm::MemoryBuffer *>> Remapped; for (const auto &RemappedFile : RemappedFiles) { std::unique_ptr<MemoryBuffer> buf = MemoryBuffer::getMemBufferCopy( RemappedFile.second, RemappedFile.first()); Remapped.emplace_back(RemappedFile.first(), buf.release()); } return Remapped; } }; TEST_F(PCHPreambleTest, ReparseReusesPreambleWithUnsavedFileNotExistingOnDisk) { std::string Header1 = "//./header1.h"; std::string MainName = "//./main.cpp"; AddFile(MainName, R"cpp( #include "//./header1.h" int main() { return ZERO; } )cpp"); RemapFile(Header1, "#define ZERO 0\n"); // Parse with header file provided as unsaved file, which does not exist on // disk. std::unique_ptr<ASTUnit> AST(ParseAST(MainName)); ASSERT_TRUE(AST.get()); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); // Reparse and check that the preamble was reused. ASSERT_TRUE(ReparseAST(AST)); ASSERT_EQ(AST->getPreambleCounterForTests(), 1U); } TEST_F(PCHPreambleTest, ReparseReusesPreambleAfterUnsavedFileWasCreatedOnDisk) { std::string Header1 = "//./header1.h"; std::string MainName = "//./main.cpp"; AddFile(MainName, R"cpp( #include "//./header1.h" int main() { return ZERO; } )cpp"); RemapFile(Header1, "#define ZERO 0\n"); // Parse with header file provided as unsaved file, which does not exist on // disk. std::unique_ptr<ASTUnit> AST(ParseAST(MainName)); ASSERT_TRUE(AST.get()); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); // Create the unsaved file also on disk and check that preamble was reused. AddFile(Header1, "#define ZERO 0\n"); ASSERT_TRUE(ReparseAST(AST)); ASSERT_EQ(AST->getPreambleCounterForTests(), 1U); } TEST_F(PCHPreambleTest, ReparseReusesPreambleAfterUnsavedFileWasRemovedFromDisk) { std::string Header1 = "//./foo/header1.h"; std::string MainName = "//./main.cpp"; std::string MainFileContent = R"cpp( #include "//./foo/header1.h" int main() { return ZERO; } )cpp"; AddFile(MainName, MainFileContent); AddFile(Header1, "#define ZERO 0\n"); RemapFile(Header1, "#define ZERO 0\n"); // Parse with header file provided as unsaved file, which exists on disk. std::unique_ptr<ASTUnit> AST(ParseAST(MainName)); ASSERT_TRUE(AST.get()); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); ASSERT_EQ(AST->getPreambleCounterForTests(), 1U); // Remove the unsaved file from disk and check that the preamble was reused. ResetVFS(); AddFile(MainName, MainFileContent); ASSERT_TRUE(ReparseAST(AST)); ASSERT_EQ(AST->getPreambleCounterForTests(), 1U); } TEST_F(PCHPreambleTest, ReparseWithOverriddenFileDoesNotInvalidatePreamble) { std::string Header1 = "//./header1.h"; std::string Header2 = "//./header2.h"; std::string MainName = "//./main.cpp"; AddFile(Header1, ""); AddFile(Header2, "#pragma once"); AddFile(MainName, "#include \"//./foo/../header1.h\"\n" "#include \"//./foo/../header2.h\"\n" "int main() { return ZERO; }"); RemapFile(Header1, "static const int ZERO = 0;\n"); std::unique_ptr<ASTUnit> AST(ParseAST(MainName)); ASSERT_TRUE(AST.get()); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); unsigned initialCounts[] = { GetFileReadCount(MainName), GetFileReadCount(Header1), GetFileReadCount(Header2) }; ASSERT_TRUE(ReparseAST(AST)); ASSERT_NE(initialCounts[0], GetFileReadCount(MainName)); ASSERT_EQ(initialCounts[1], GetFileReadCount(Header1)); ASSERT_EQ(initialCounts[2], GetFileReadCount(Header2)); } TEST_F(PCHPreambleTest, ParseWithBom) { std::string Header = "//./header.h"; std::string Main = "//./main.cpp"; AddFile(Header, "int random() { return 4; }"); AddFile(Main, "\xef\xbb\xbf" "#include \"//./header.h\"\n" "int main() { return random() -2; }"); std::unique_ptr<ASTUnit> AST(ParseAST(Main)); ASSERT_TRUE(AST.get()); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); unsigned HeaderReadCount = GetFileReadCount(Header); ASSERT_TRUE(ReparseAST(AST)); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); // Check preamble PCH was really reused ASSERT_EQ(HeaderReadCount, GetFileReadCount(Header)); // Remove BOM RemapFile(Main, "#include \"//./header.h\"\n" "int main() { return random() -2; }"); ASSERT_TRUE(ReparseAST(AST)); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); ASSERT_LE(HeaderReadCount, GetFileReadCount(Header)); HeaderReadCount = GetFileReadCount(Header); // Add BOM back RemapFile(Main, "\xef\xbb\xbf" "#include \"//./header.h\"\n" "int main() { return random() -2; }"); ASSERT_TRUE(ReparseAST(AST)); ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred()); ASSERT_LE(HeaderReadCount, GetFileReadCount(Header)); } } // anonymous namespace
3,236
378
<filename>test/stack_torture1.c<gh_stars>100-1000 /* -*- Mode: c; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #include <string.h> #include <assert.h> #include <concurrent/concurrent.h> #include <concurrent/shortname.h> void test_generator(struct concurrent_ctx *ctx) { yield_value(ctx, "pong"); } int main(void) { int i; srand(time(NULL)); concurrent_init(); for (i = 0; i < 1000; i++) { size_t stack_size = 1024 + 16 + (rand() % 16); size_t torture_offset = rand() % 16; struct concurrent_ctx *ctx; uint8_t *stack; concurrent_status status; ctx = malloc(ctx_sizeof()); stack = malloc(sizeof(*stack) * stack_size); status = ctx_construct(ctx, stack + torture_offset, stack_size - torture_offset, test_generator, NULL); assert(status == CONCURRENT_SUCCESS); assert(strcmp(resume(ctx), "pong") == 0); ctx_destruct(ctx); free(stack); free(ctx); } concurrent_fin(); return 0; }
584
5,169
{ "name": "OMChainKit", "version": "1.0.0", "summary": "A complete API wrapper for Omnicha.in", "description": "Creating applications for Omnicoin couldn't be made simpler with this library.This library allows full access to the Omnicha.in API using delegates that make interactionswith the site very simple and easy to use.", "homepage": "http://www.github.com/ZaneH/OMChainKit", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/ZaneHelton", "platforms": { "ios": "5.0", "osx": "10.7" }, "source": { "git": "https://github.com/ZaneH/OMChainKit.git", "tag": "1.0.0" }, "source_files": "OMChainKit/OMChainKit/Source/OMChainWallet.h", "public_header_files": "OMChainKit/OMChainKit/Source/*.h", "requires_arc": true }
325
368
package ezvcard.property; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import ezvcard.VCard; import ezvcard.VCardVersion; import ezvcard.ValidationWarning; import ezvcard.parameter.KeyType; /* Copyright (c) 2012-2021, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ /** * <p> * Defines a public encryption key. * </p> * * <p> * <b>Code sample (creating)</b> * </p> * * <pre class="brush:java"> * VCard vcard = new VCard(); * * //URL * Key key = new Key("http://www.mywebsite.com/my-public-key.pgp", KeyType.PGP); * vcard.addKey(key); * * //URI * Key key = new Key("<KEY>ABAF11C65A2970B130ABE3C479BE3E4300411886", null); * vcard.addKey(key); * * //binary data * byte data[] = ... * key = new Key(data, KeyType.PGP); * vcard.addKey(key); * * //plain text value * key = new Key(); * key.setText("...", KeyType.PGP); * vcard.addKey(key); * </pre> * * <p> * <b>Code sample (retrieving)</b> * </p> * * <pre class="brush:java"> * VCard vcard = ... * for (Key key : vcard.getKeys()) { * KeyType contentType = key.getContentType(); //e.g. "application/pgp-keys" * * String url = key.getUrl(); * if (url != null) { * //property value is a URL * continue; * } * * byte[] data = key.getData(); * if (data != null) { * //property value is binary data * continue; * } * * String text = key.getText(); * if (text != null) { * //property value is plain-text * continue; * } * } * </pre> * * <p> * <b>Property name:</b> {@code KEY} * </p> * <p> * <b>Supported versions:</b> {@code 2.1, 3.0, 4.0} * </p> * @author <NAME> * @see <a href="http://tools.ietf.org/html/rfc6350#page-48">RFC 6350 p.48</a> * @see <a href="http://tools.ietf.org/html/rfc2426#page-26">RFC 2426 p.26</a> * @see <a href="http://www.imc.org/pdi/vcard-21.doc">vCard 2.1 p.22</a> */ public class Key extends BinaryProperty<KeyType> { private String text; /** * Creates an empty key property. */ public Key() { super(); } /** * Creates a key property. * @param data the binary data * @param type the type of key (e.g. PGP) */ public Key(byte data[], KeyType type) { super(data, type); } /** * Creates a key property. * @param url the URI or URL to the key * @param type the type of key (e.g. PGP) or null if the type can be * identified from the URI */ public Key(String url, KeyType type) { super(url, type); } /** * Creates a key property. * @param in an input stream to the binary data (will be closed) * @param type the content type (e.g. PGP) * @throws IOException if there's a problem reading from the input stream */ public Key(InputStream in, KeyType type) throws IOException { super(in, type); } /** * Creates a key property. * @param file the key file * @param type the content type (e.g. PGP) * @throws IOException if there's a problem reading from the file */ public Key(File file, KeyType type) throws IOException { super(file, type); } /** * Copy constructor. * @param original the property to make a copy of */ public Key(Key original) { super(original); text = original.text; } /** * Sets a plain text representation of the key. * @param text the key in plain text * @param type the key type */ public void setText(String text, KeyType type) { this.text = text; data = null; url = null; setContentType(type); } /** * Gets the plain text representation of the key. * @return the key in plain text */ public String getText() { return text; } /** * Sets the URL or URI of the key. * @param url the URL or URI of the key * @param type the type of key (e.g. PGP) or null if the type can be * identified from the URI */ @Override public void setUrl(String url, KeyType type) { super.setUrl(url, type); text = null; } /** * Gets the URL or URI of the key. * @return the URL/URI or null if there is none */ @Override public String getUrl() { return super.getUrl(); } @Override public void setData(byte[] data, KeyType type) { super.setData(data, type); text = null; } @Override protected void _validate(List<ValidationWarning> warnings, VCardVersion version, VCard vcard) { if (url == null && data == null && text == null) { warnings.add(new ValidationWarning(8)); } if (url != null && (version == VCardVersion.V2_1 || version == VCardVersion.V3_0)) { warnings.add(new ValidationWarning(15)); } } @Override protected Map<String, Object> toStringValues() { Map<String, Object> values = super.toStringValues(); values.put("text", text); return values; } @Override public Key copy() { return new Key(this); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; Key other = (Key) obj; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } }
2,347
1,529
<reponame>IgiArdiyanto/PINTO_model_zoo<gh_stars>1000+ import cv2 import time import numpy as np from openvino.inference_engine import IECore import os class Msg_chn_wacv20(): def __init__(self, model_path, device='CPU'): # Initialize model self.model = self.initialize_model(model_path, device) def __call__(self, image, sparse_depth, max_depth = 10.0): return self.estimate_depth(image, sparse_depth, max_depth) def initialize_model(self, model_path, device): self.ie = IECore() self.net = self.ie.read_network(model_path, os.path.splitext(model_path)[0] + ".bin") self.exec_net = self.ie.load_network(network=self.net, device_name=device, num_requests=2) # Get model info self.getModel_input_details() self.getModel_output_details() def estimate_depth(self, image, sparse_depth, max_depth = 10.0): self.max_depth = max_depth input_rgb_tensor = self.prepare_rgb(image) input_depth_tensor = self.prepare_depth(sparse_depth) outputs = self.inference(input_rgb_tensor, input_depth_tensor) depth_map = self.process_output(outputs) return depth_map def prepare_rgb(self, img): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.img_height, self.img_width, self.img_channels = img.shape img_input = cv2.resize(img, (self.input_width,self.input_height)) img_input = img_input/255 img_input = img_input.transpose(2, 0, 1) img_input = img_input[np.newaxis,:,:,:] return img_input.astype(np.float32) def prepare_depth(self, img): img_input = cv2.resize(img, (self.input_width,self.input_height), interpolation = cv2.INTER_NEAREST) img_input = img_input/self.max_depth*256 img_input = img_input[np.newaxis,np.newaxis,:,:] return img_input.astype(np.float32) def inference(self, input_rgb_tensor, input_depth_tensor): start = time.time() outputs = self.exec_net.infer( inputs={ self.rgb_input_name: input_rgb_tensor, self.depth_input_name:input_depth_tensor } ) print(f'{1.0 / (time.time() - start)} FPS') return outputs def process_output(self, outputs): depth_map = np.squeeze(outputs[self.output_names[0]])/256*self.max_depth return cv2.resize(depth_map, (self.img_width, self.img_height)) def getModel_input_details(self): key_iter = iter(self.net.input_info) self.depth_input_name = next(key_iter) self.rgb_input_name = next(key_iter) self.input_shape = self.net.input_info[self.depth_input_name].input_data.shape self.input_height = self.input_shape[2] self.input_width = self.input_shape[3] def getModel_output_details(self): key_iter = iter(self.net.outputs) self.output_names = [ next(key_iter), next(key_iter), next(key_iter), ] self.output_shape = self.net.outputs[self.output_names[0]].shape self.output_height = self.output_shape[2] self.output_width = self.output_shape[3] if __name__ == '__main__': from utils import make_depth_sparse, draw_depth, update_depth_density depth_density = 10 depth_density_rate = 0.2 max_depth = 10 model_path='../models/saved_model_480x640/openvino/FP16/msg_chn_wacv20_480x640.xml' depth_estimator = Msg_chn_wacv20(model_path) cap_depth = cv2.VideoCapture("../outdoor_example/depthmap/depth_frame%03d.png", cv2.CAP_IMAGES) cap_rgb = cv2.VideoCapture("../outdoor_example/left_video.avi") while cap_rgb.isOpened() and cap_depth.isOpened(): # Read frame from the videos ret, rgb_frame = cap_rgb.read() ret, depth_frame = cap_depth.read() if not ret: break depth_frame = depth_frame/1000 # to m # Make the depth map sparse depth_density, depth_density_rate = update_depth_density(depth_density, depth_density_rate, 1, 10) sparse_depth = make_depth_sparse(depth_frame, depth_density) # Fill the sparse depth map estimated_depth = depth_estimator(rgb_frame, sparse_depth) # Color depth maps color_gt_depth = draw_depth(depth_frame, max_depth) color_sparse_depth = draw_depth(sparse_depth, max_depth) color_estimated_depth = draw_depth(estimated_depth, max_depth) combined_img = np.vstack((np.hstack((rgb_frame, color_sparse_depth)),np.hstack((color_gt_depth,color_estimated_depth)))) cv2.putText(combined_img,f'Density:{depth_density:.1f}%',(combined_img.shape[1]-500,100), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2, cv2.LINE_AA) cv2.namedWindow("Estimated depth", cv2.WINDOW_NORMAL) cv2.imshow("Estimated depth", combined_img) cv2.waitKey(1)
2,197
2,023
"""Command-line tool for making self-extracting Python file. Call this program from your command line with one argument: (1) the file that you want to pack and compress (2) the output will be a file with a pyw ending The output can run on Windows where Python is installed.""" ################################################################################ import sys import os.path import bz2 import zlib import base64 ################################################################################ def main(): "Extract the command-line arguments and run the packer." try: pack(sys.argv[1]) except (IndexError, AssertionError): print('Usage: {} <filename>'.format(os.path.basename(sys.argv[0]))) def pack(path): "Get the source, compress it, and create a packed file." data = read_file(path) builder, data = optimize(data) with open(os.path.splitext(path)[0] + '.pyw', 'w') as file: builder(os.path.basename(path), base64.b64encode(data), file) def read_file(path): "Read the entire file content from path in binary mode." assert os.path.isfile(path) with open(path, 'rb') as file: return file.read() def optimize(data): "Compress the data and select the best method to write." bz2_data = bz2.compress(data, 9) zlib_data = zlib.compress(data, 9) sizes = tuple(map(len, (data, bz2_data, zlib_data))) smallest = sizes.index(min(sizes)) if smallest == 1: return build_bz2_extractor, bz2_data if smallest == 2: return build_zlib_extractor, zlib_data return build_b64_extractor, data ################################################################################ def build_bz2_extractor(filename, data, file): "Write a Python program that uses bz2 data compression." print("import base64, bz2, os", file=file) print("data =", data, file=file) print("with open({!r}, 'wb') as file:".format(filename), file=file) print(" file.write(bz2.decompress(base64.b64decode(data)))", file=file) print("os.startfile({!r})".format(filename), file=file) def build_zlib_extractor(filename, data, file): "Pack data into a self-extractor with zlib compression." print("import base64, zlib, os", file=file) print("data =", data, file=file) print("with open({!r}, 'wb') as file:".format(filename), file=file) print(" file.write(zlib.decompress(base64.b64decode(data)))", file=file) print("os.startfile({!r})".format(filename), file=file) def build_b64_extractor(filename, data, file): "Create a Python file that may not utilize compression." print("import base64, os", file=file) print("data =", data, file=file) print("with open({!r}, 'wb') as file:".format(filename), file=file) print(" file.write(base64.b64decode(data))", file=file) print("os.startfile({!r})".format(filename), file=file) ################################################################################ if __name__ == '__main__': main() # Small Program Version # import bz2,base64 as a,os.path as b,sys,zlib;c=sys.argv[1] # with open(c,'rb') as d:d=d.read();e,f=bz2.compress(d),zlib.compress(d,9);g=list(map(len,(d,e,f)));g,h,i,j,k,l=g.index(min(g)),'import base64 as a,os','\nwith open({0!r},"wb") as b:b.write(','.decompress(','a.b64decode({1}))',';os.startfile({0!r})' # if g==1:d,e=e,h+',bz2'+i+'bz2'+j+k+')'+l # elif g==2:d,e=f,h+',zlib'+i+'zlib'+j+k+')'+l # else:e=h+i+k+l # with open(b.splitext(c)[0]+'.pyw','w') as f:f.write(e.format(b.basename(c),a.b64encode(d)))
1,341
322
<filename>torch_ipex_py/cpu/runtime/runtime_utils.py import subprocess def get_num_nodes(): return int(subprocess.check_output('lscpu | grep Socket | awk \'{print $2}\'', shell=True)) def get_num_cores_per_node(): return int(subprocess.check_output('lscpu | grep Core | awk \'{print $4}\'', shell=True)) def get_core_list_of_node_id(node_id): num_of_nodes = get_num_nodes() assert node_id < num_of_nodes, "input node_id:{0} must less than system number of nodes:{1}".format(node_id, num_of_nodes) num_cores_per_node = get_num_cores_per_node() return list(range(num_cores_per_node * node_id, num_cores_per_node * (node_id + 1)))
266
12,718
#define r0 0 #define r1 1 #define r2 2 #define r3 3 #define r4 4 #define r5 5 #define r6 6 #define r7 7 #define r8 8 #define r9 9 #define r10 10 #define r11 11 #define r12 12 #define r13 13 #define r14 14 #define r15 15 #define r16 16 #define r17 17 #define r18 18 #define r19 19 #define r20 20 #define r21 21 #define r22 22 #define r23 23 #define r24 24 #define r25 25 #define r26 26 #define r27 27 #define r28 28 #define r29 29 #define r30 30 #define r31 31 #define f0 0 #define f1 1 #define f2 2 #define f3 3 #define f4 4 #define f5 5 #define f6 6 #define f7 7 #define f8 8 #define f9 9 #define f10 10 #define f11 11 #define f12 12 #define f13 13 #define f14 14 #define f15 15 #define f16 16 #define f17 17 #define f18 18 #define f19 19 #define f20 20 #define f21 21 #define f22 22 #define f23 23 #define f24 24 #define f25 25 #define f26 26 #define f27 27 #define f28 28 #define f29 29 #define f30 30 #define f31 31 #define v0 0 #define v1 1 #define v2 2 #define v3 3 #define v4 4 #define v5 5 #define v6 6 #define v7 7 #define v8 8 #define v9 9 #define v10 10 #define v11 11 #define v12 12 #define v13 13 #define v14 14 #define v15 15 #define v16 16 #define v17 17 #define v18 18 #define v19 19 #define v20 20 #define v21 21 #define v22 22 #define v23 23 #define v24 24 #define v25 25 #define v26 26 #define v27 27 #define v28 28 #define v29 29 #define v30 30 #define v31 31
576
10,225
package io.quarkus.vertx.http.testrunner.metaannotations; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import io.quarkus.test.junit.QuarkusTest; @QuarkusTest public class MetaET { @UnitTest public void t1() { given() .when().get("/hello/greeting/foo") .then() .statusCode(200) .body(is("hello foo")); } @UnitTest public void t2() { given() .when().get("/hello/greeting/foo") .then() .statusCode(200) .body(is("hello foo")); } }
342
4,879
#pragma once #include "generator/feature_builder.hpp" #include "geometry/region2d.hpp" #include "geometry/tree4d.hpp" #include <string> #include <utility> #include <vector> namespace generator { class BoundaryPostcodesEnricher { public: explicit BoundaryPostcodesEnricher(std::string const & boundaryPostcodesFilename); void Enrich(feature::FeatureBuilder & fb) const; private: std::vector<std::pair<std::string, m2::RegionD>> m_boundaryPostcodes; m4::Tree<size_t> m_boundariesTree; }; } // namespace generator
184
1,144
<gh_stars>1000+ /* SPDX-License-Identifier: GPL-2.0+ */ /* * (C) Copyright 2016 - <NAME> <<EMAIL>> */ #ifndef __PINCTRL_MESON_H__ #define __PINCTRL_MESON_H__ #include <linux/types.h> struct meson_pmx_group { const char *name; const unsigned int *pins; unsigned int num_pins; bool is_gpio; unsigned int reg; unsigned int bit; }; struct meson_pmx_func { const char *name; const char * const *groups; unsigned int num_groups; }; struct meson_pinctrl_data { const char *name; struct meson_pmx_group *groups; struct meson_pmx_func *funcs; struct meson_bank *banks; unsigned int pin_base; unsigned int num_pins; unsigned int num_groups; unsigned int num_funcs; unsigned int num_banks; }; struct meson_pinctrl { struct meson_pinctrl_data *data; void __iomem *reg_mux; void __iomem *reg_gpio; }; /** * struct meson_reg_desc - a register descriptor * * @reg: register offset in the regmap * @bit: bit index in register * * The structure describes the information needed to control pull, * pull-enable, direction, etc. for a single pin */ struct meson_reg_desc { unsigned int reg; unsigned int bit; }; /** * enum meson_reg_type - type of registers encoded in @meson_reg_desc */ enum meson_reg_type { REG_PULLEN, REG_PULL, REG_DIR, REG_OUT, REG_IN, NUM_REG, }; /** * struct meson bank * * @name: bank name * @first: first pin of the bank * @last: last pin of the bank * @regs: array of register descriptors * * A bank represents a set of pins controlled by a contiguous set of * bits in the domain registers. The structure specifies which bits in * the regmap control the different functionalities. Each member of * the @regs array refers to the first pin of the bank. */ struct meson_bank { const char *name; unsigned int first; unsigned int last; struct meson_reg_desc regs[NUM_REG]; }; #define PIN(x, b) (b + x) #define GROUP(grp, r, b) \ { \ .name = #grp, \ .pins = grp ## _pins, \ .num_pins = ARRAY_SIZE(grp ## _pins), \ .reg = r, \ .bit = b, \ } #define GPIO_GROUP(gpio, b) \ { \ .name = #gpio, \ .pins = (const unsigned int[]){ PIN(gpio, b) }, \ .num_pins = 1, \ .is_gpio = true, \ } #define FUNCTION(fn) \ { \ .name = #fn, \ .groups = fn ## _groups, \ .num_groups = ARRAY_SIZE(fn ## _groups), \ } #define BANK(n, f, l, per, peb, pr, pb, dr, db, or, ob, ir, ib) \ { \ .name = n, \ .first = f, \ .last = l, \ .regs = { \ [REG_PULLEN] = { per, peb }, \ [REG_PULL] = { pr, pb }, \ [REG_DIR] = { dr, db }, \ [REG_OUT] = { or, ob }, \ [REG_IN] = { ir, ib }, \ }, \ } #define MESON_PIN(x, b) PINCTRL_PIN(PIN(x, b), #x) extern const struct pinctrl_ops meson_pinctrl_ops; int meson_pinctrl_probe(struct udevice *dev); #endif /* __PINCTRL_MESON_H__ */
1,312
3,182
<reponame>1337c0der/lombok-intellij-plugin import lombok.AccessLevel; import lombok.Setter; class Test { @Setter private float b; @Setter(AccessLevel.PROTECTED) private double c; @Setter(AccessLevel.PRIVATE) private String d; }
97
501
#!/usr/bin/env python ''' Use multi-grid to accelerate DFT numerical integration. ''' import numpy from pyscf.pbc import gto, dft from pyscf.pbc.dft import multigrid cell = gto.M( verbose = 4, a = numpy.eye(3)*3.5668, atom = '''C 0. 0. 0. C 0.8917 0.8917 0.8917 C 1.7834 1.7834 0. C 2.6751 2.6751 0.8917 C 1.7834 0. 1.7834 C 2.6751 0.8917 2.6751 C 0. 1.7834 1.7834 C 0.8917 2.6751 2.6751''', basis = 'sto3g', #basis = 'ccpvdz', #basis = 'gth-dzvp', #pseudo = 'gth-pade' ) mf = dft.UKS(cell) mf.xc = 'lda,vwn' # # There are two ways to enable multigrid numerical integration # # Method 1: use multigrid.multigrid function to update SCF object # mf = multigrid.multigrid(mf) mf.kernel() # # Method 2: MultiGridFFTDF is a DF object. It can be enabled by overwriting # the default with_df object. # kpts = cell.make_kpts([4,4,4]) mf = dft.KRKS(cell, kpts) mf.xc = 'lda,vwn' mf.with_df = multigrid.MultiGridFFTDF(cell, kpts) mf.kernel() # # MultiGridFFTDF can be used with second order SCF solver. # mf = mf.newton() mf.kernel()
668
6,224
/* * Xilinx Processor System Gigabit Ethernet controller (GEM) driver * * Copyright (c) 2021, Weidmueller Interface GmbH & Co. KG * SPDX-License-Identifier: Apache-2.0 * * Known current limitations / TODOs: * - Only supports 32-bit addresses in buffer descriptors, therefore * the ZynqMP APU (Cortex-A53 cores) may not be fully supported. * - Hardware timestamps not considered. * - VLAN tags not considered. * - Wake-on-LAN interrupt not supported. * - Send function is not SMP-capable (due to single TX done semaphore). * - Interrupt-driven PHY management not supported - polling only. * - No explicit placement of the DMA memory area(s) in either a * specific memory section or at a fixed memory location yet. This * is not an issue as long as the controller is used in conjunction * with the Cortex-R5 QEMU target or an actual R5 running without the * MPU enabled. * - No detailed error handling when evaluating the Interrupt Status, * RX Status and TX Status registers. */ #include <zephyr.h> #include <device.h> #include <devicetree.h> #include <sys/__assert.h> #include <net/net_if.h> #include <net/ethernet.h> #include <ethernet/eth_stats.h> #include "eth_xlnx_gem_priv.h" #define LOG_MODULE_NAME eth_xlnx_gem #define LOG_LEVEL CONFIG_ETHERNET_LOG_LEVEL #include <logging/log.h> LOG_MODULE_REGISTER(LOG_MODULE_NAME); static int eth_xlnx_gem_dev_init(const struct device *dev); static void eth_xlnx_gem_iface_init(struct net_if *iface); static void eth_xlnx_gem_isr(const struct device *dev); static int eth_xlnx_gem_send(const struct device *dev, struct net_pkt *pkt); static int eth_xlnx_gem_start_device(const struct device *dev); static int eth_xlnx_gem_stop_device(const struct device *dev); static enum ethernet_hw_caps eth_xlnx_gem_get_capabilities(const struct device *dev); #if defined(CONFIG_NET_STATISTICS_ETHERNET) static struct net_stats_eth *eth_xlnx_gem_stats(const struct device *dev); #endif static void eth_xlnx_gem_reset_hw(const struct device *dev); static void eth_xlnx_gem_configure_clocks(const struct device *dev); static void eth_xlnx_gem_set_initial_nwcfg(const struct device *dev); static void eth_xlnx_gem_set_nwcfg_link_speed(const struct device *dev); static void eth_xlnx_gem_set_mac_address(const struct device *dev); static void eth_xlnx_gem_set_initial_dmacr(const struct device *dev); static void eth_xlnx_gem_init_phy(const struct device *dev); static void eth_xlnx_gem_poll_phy(struct k_work *item); static void eth_xlnx_gem_configure_buffers(const struct device *dev); static void eth_xlnx_gem_rx_pending_work(struct k_work *item); static void eth_xlnx_gem_handle_rx_pending(const struct device *dev); static void eth_xlnx_gem_tx_done_work(struct k_work *item); static void eth_xlnx_gem_handle_tx_done(const struct device *dev); static const struct ethernet_api eth_xlnx_gem_apis = { .iface_api.init = eth_xlnx_gem_iface_init, .get_capabilities = eth_xlnx_gem_get_capabilities, .send = eth_xlnx_gem_send, .start = eth_xlnx_gem_start_device, .stop = eth_xlnx_gem_stop_device, #if defined(CONFIG_NET_STATISTICS_ETHERNET) .get_stats = eth_xlnx_gem_stats, #endif }; /* * Insert the configuration & run-time data for all GEM instances which * are enabled in the device tree of the current target board. */ DT_INST_FOREACH_STATUS_OKAY(ETH_XLNX_GEM_INITIALIZE) /** * @brief GEM device initialization function * Initializes the GEM itself, the DMA memory area used by the GEM and, * if enabled, an associated PHY attached to the GEM's MDIO interface. * * @param dev Pointer to the device data * @retval 0 if the device initialization completed successfully */ static int eth_xlnx_gem_dev_init(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); uint32_t reg_val; /* Precondition checks using assertions */ /* Valid PHY address and polling interval, if PHY is to be managed */ if (dev_conf->init_phy) { __ASSERT((dev_conf->phy_mdio_addr_fix >= 0 && dev_conf->phy_mdio_addr_fix <= 32), "%s invalid PHY address %u, must be in range " "1 to 32, or 0 for auto-detection", dev->name, dev_conf->phy_mdio_addr_fix); __ASSERT(dev_conf->phy_poll_interval > 0, "%s has an invalid zero PHY status polling " "interval", dev->name); } /* Valid max. / nominal link speed value */ __ASSERT((dev_conf->max_link_speed == LINK_10MBIT || dev_conf->max_link_speed == LINK_100MBIT || dev_conf->max_link_speed == LINK_1GBIT), "%s invalid max./nominal link speed value %u", dev->name, (uint32_t)dev_conf->max_link_speed); /* MDC clock divider validity check, SoC dependent */ #if defined(CONFIG_SOC_XILINX_ZYNQMP) __ASSERT(dev_conf->mdc_divider <= MDC_DIVIDER_48, "%s invalid MDC clock divider value %u, must be in " "range 0 to %u", dev->name, dev_conf->mdc_divider, (uint32_t)MDC_DIVIDER_48); #elif defined(CONFIG_SOC_SERIES_XILINX_ZYNQ7000) __ASSERT(dev_conf->mdc_divider <= MDC_DIVIDER_224, "%s invalid MDC clock divider value %u, must be in " "range 0 to %u", dev->name, dev_conf->mdc_divider, (uint32_t)MDC_DIVIDER_224); #endif /* AMBA AHB configuration options */ __ASSERT((dev_conf->amba_dbus_width == AMBA_AHB_DBUS_WIDTH_32BIT || dev_conf->amba_dbus_width == AMBA_AHB_DBUS_WIDTH_64BIT || dev_conf->amba_dbus_width == AMBA_AHB_DBUS_WIDTH_128BIT), "%s AMBA AHB bus width configuration is invalid", dev->name); __ASSERT((dev_conf->ahb_burst_length == AHB_BURST_SINGLE || dev_conf->ahb_burst_length == AHB_BURST_INCR4 || dev_conf->ahb_burst_length == AHB_BURST_INCR8 || dev_conf->ahb_burst_length == AHB_BURST_INCR16), "%s AMBA AHB burst length configuration is invalid", dev->name); /* HW RX buffer size */ __ASSERT((dev_conf->hw_rx_buffer_size == HWRX_BUFFER_SIZE_8KB || dev_conf->hw_rx_buffer_size == HWRX_BUFFER_SIZE_4KB || dev_conf->hw_rx_buffer_size == HWRX_BUFFER_SIZE_2KB || dev_conf->hw_rx_buffer_size == HWRX_BUFFER_SIZE_1KB), "%s hardware RX buffer size configuration is invalid", dev->name); /* HW RX buffer offset */ __ASSERT(dev_conf->hw_rx_buffer_offset <= 3, "%s hardware RX buffer offset %u is invalid, must be in " "range 0 to 3", dev->name, dev_conf->hw_rx_buffer_offset); /* * RX & TX buffer sizes * RX Buffer size must be a multiple of 64, as the size of the * corresponding DMA receive buffer in AHB system memory is * expressed as n * 64 bytes in the DMA configuration register. */ __ASSERT(dev_conf->rx_buffer_size % 64 == 0, "%s RX buffer size %u is not a multiple of 64 bytes", dev->name, dev_conf->rx_buffer_size); __ASSERT((dev_conf->rx_buffer_size != 0 && dev_conf->rx_buffer_size <= 16320), "%s RX buffer size %u is invalid, should be >64, " "must be 16320 bytes maximum.", dev->name, dev_conf->rx_buffer_size); __ASSERT((dev_conf->tx_buffer_size != 0 && dev_conf->tx_buffer_size <= 16380), "%s TX buffer size %u is invalid, should be >64, " "must be 16380 bytes maximum.", dev->name, dev_conf->tx_buffer_size); /* Checksum offloading limitations of the QEMU GEM implementation */ #ifdef CONFIG_QEMU_TARGET __ASSERT(!dev_conf->enable_rx_chksum_offload, "TCP/UDP/IP hardware checksum offloading is not " "supported by the QEMU GEM implementation"); __ASSERT(!dev_conf->enable_tx_chksum_offload, "TCP/UDP/IP hardware checksum offloading is not " "supported by the QEMU GEM implementation"); #endif /* * Initialization procedure as described in the Zynq-7000 TRM, * chapter 16.3.x. */ eth_xlnx_gem_reset_hw(dev); /* Chapter 16.3.1 */ eth_xlnx_gem_set_initial_nwcfg(dev); /* Chapter 16.3.2 */ eth_xlnx_gem_set_mac_address(dev); /* Chapter 16.3.2 */ eth_xlnx_gem_set_initial_dmacr(dev); /* Chapter 16.3.2 */ /* Enable MDIO -> set gem.net_ctrl[mgmt_port_en] */ if (dev_conf->init_phy) { reg_val = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); reg_val |= ETH_XLNX_GEM_NWCTRL_MDEN_BIT; sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); } eth_xlnx_gem_configure_clocks(dev); /* Chapter 16.3.3 */ if (dev_conf->init_phy) { eth_xlnx_gem_init_phy(dev); /* Chapter 16.3.4 */ } eth_xlnx_gem_configure_buffers(dev); /* Chapter 16.3.5 */ return 0; } /** * @brief GEM associated interface initialization function * Initializes the interface associated with a GEM device. * * @param iface Pointer to the associated interface data struct */ static void eth_xlnx_gem_iface_init(struct net_if *iface) { const struct device *dev = net_if_get_device(iface); const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); /* Set the initial contents of the current instance's run-time data */ dev_data->iface = iface; net_if_set_link_addr(iface, dev_data->mac_addr, 6, NET_LINK_ETHERNET); ethernet_init(iface); net_if_flag_set(iface, NET_IF_NO_AUTO_START); /* * Initialize the (delayed) work items for RX pending, TX done * and PHY status polling handlers */ k_work_init(&dev_data->tx_done_work, eth_xlnx_gem_tx_done_work); k_work_init(&dev_data->rx_pend_work, eth_xlnx_gem_rx_pending_work); k_work_init_delayable(&dev_data->phy_poll_delayed_work, eth_xlnx_gem_poll_phy); /* Initialize TX completion semaphore */ k_sem_init(&dev_data->tx_done_sem, 0, 1); /* * Initialize semaphores in the RX/TX BD rings which have not * yet been initialized */ k_sem_init(&dev_data->txbd_ring.ring_sem, 1, 1); /* RX BD ring semaphore is not required at the time being */ /* Initialize the device's interrupt */ dev_conf->config_func(dev); /* Submit initial PHY status polling delayed work */ k_work_reschedule(&dev_data->phy_poll_delayed_work, K_NO_WAIT); } /** * @brief GEM interrupt service routine * GEM interrupt service routine. Checks for indications of errors * and either immediately handles RX pending / TX complete notifications * or defers them to the system work queue. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_isr(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t reg_val; /* Read the interrupt status register */ reg_val = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_ISR_OFFSET); /* * TODO: handling if one or more error flag(s) are set in the * interrupt status register. -> For now, just log them */ if (reg_val & ETH_XLNX_GEM_IXR_ERRORS_MASK) { LOG_ERR("%s error bit(s) set in Interrupt Status Reg.: 0x%08X", dev->name, reg_val); } /* * Check for the following indications by the controller: * reg_val & 0x00000080 -> gem.intr_status bit [7] = Frame TX complete * reg_val & 0x00000002 -> gem.intr_status bit [1] = Frame received * comp. Zynq-7000 TRM, Chapter B.18, p. 1289/1290. * If the respective condition's handling is configured to be deferred * to the work queue thread, submit the corresponding job to the work * queue, otherwise, handle the condition immediately. */ if ((reg_val & ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT) != 0) { sys_write32(ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IDR_OFFSET); sys_write32(ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT, dev_conf->base_addr + ETH_XLNX_GEM_ISR_OFFSET); if (dev_conf->defer_txd_to_queue) { k_work_submit(&dev_data->tx_done_work); } else { eth_xlnx_gem_handle_tx_done(dev); } } if ((reg_val & ETH_XLNX_GEM_IXR_FRAME_RX_BIT) != 0) { sys_write32(ETH_XLNX_GEM_IXR_FRAME_RX_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IDR_OFFSET); sys_write32(ETH_XLNX_GEM_IXR_FRAME_RX_BIT, dev_conf->base_addr + ETH_XLNX_GEM_ISR_OFFSET); if (dev_conf->defer_rxp_to_queue) { k_work_submit(&dev_data->rx_pend_work); } else { eth_xlnx_gem_handle_rx_pending(dev); } } /* * Clear all interrupt status bits so that the interrupt is de-asserted * by the GEM. -> TXSR/RXSR are read/cleared by either eth_xlnx_gem_- * handle_tx_done or eth_xlnx_gem_handle_rx_pending if those actions * are not deferred to the system's work queue for the current inter- * face. If the latter is the case, those registers will be read/ * cleared whenever the corresponding work item submitted from within * this ISR is being processed. */ sys_write32((0xFFFFFFFF & ~(ETH_XLNX_GEM_IXR_FRAME_RX_BIT | ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT)), dev_conf->base_addr + ETH_XLNX_GEM_ISR_OFFSET); } /** * @brief GEM data send function * GEM data send function. Blocks until a TX complete notification has been * received & processed. * * @param dev Pointer to the device data * @param pkt Pointer to the data packet to be sent * @retval -EINVAL in case of invalid parameters, e.g. zero data length * @retval -EIO in case of: * (1) the attempt to TX data while the device is stopped, * the interface is down or the link is down, * (2) the attempt to TX data while no free buffers are available * in the DMA memory area, * (3) the transmission completion notification timing out * @retval 0 if the packet was transmitted successfully */ static int eth_xlnx_gem_send(const struct device *dev, struct net_pkt *pkt) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint16_t tx_data_length; uint16_t tx_data_remaining; void *tx_buffer_offs; uint8_t bds_reqd; uint8_t curr_bd_idx; uint8_t first_bd_idx; uint32_t reg_ctrl; uint32_t reg_val; int sem_status; if (!dev_data->started || dev_data->eff_link_speed == LINK_DOWN || (!net_if_flag_is_set(dev_data->iface, NET_IF_UP))) { #ifdef CONFIG_NET_STATISTICS_ETHERNET dev_data->stats.tx_dropped++; #endif return -EIO; } tx_data_length = tx_data_remaining = net_pkt_get_len(pkt); if (tx_data_length == 0) { LOG_ERR("%s cannot TX, zero packet length", dev->name); #ifdef CONFIG_NET_STATISTICS_ETHERNET dev_data->stats.errors.tx++; #endif return -EINVAL; } /* * Check if enough buffer descriptors are available for the amount * of data to be transmitted, update the free BD count if this is * the case. Update the 'next to use' BD index in the TX BD ring if * sufficient space is available. If TX done handling, where the BD * ring's data is accessed as well, is performed via the system work * queue, protect against interruptions during the update of the BD * ring's data by taking the ring's semaphore. If TX done handling * is performed within the ISR, protect against interruptions by * disabling the TX done interrupt source. */ bds_reqd = (uint8_t)((tx_data_length + (dev_conf->tx_buffer_size - 1)) / dev_conf->tx_buffer_size); if (dev_conf->defer_txd_to_queue) { k_sem_take(&(dev_data->txbd_ring.ring_sem), K_FOREVER); } else { sys_write32(ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IDR_OFFSET); } if (bds_reqd > dev_data->txbd_ring.free_bds) { LOG_ERR("%s cannot TX, packet length %hu requires " "%hhu BDs, current free count = %hhu", dev->name, tx_data_length, bds_reqd, dev_data->txbd_ring.free_bds); if (dev_conf->defer_txd_to_queue) { k_sem_give(&(dev_data->txbd_ring.ring_sem)); } else { sys_write32(ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IER_OFFSET); } #ifdef CONFIG_NET_STATISTICS_ETHERNET dev_data->stats.tx_dropped++; #endif return -EIO; } curr_bd_idx = first_bd_idx = dev_data->txbd_ring.next_to_use; reg_ctrl = (uint32_t)(&dev_data->txbd_ring.first_bd[curr_bd_idx].ctrl); dev_data->txbd_ring.next_to_use = (first_bd_idx + bds_reqd) % dev_conf->txbd_count; dev_data->txbd_ring.free_bds -= bds_reqd; if (dev_conf->defer_txd_to_queue) { k_sem_give(&(dev_data->txbd_ring.ring_sem)); } else { sys_write32(ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IER_OFFSET); } /* * Scatter the contents of the network packet's buffer to * one or more DMA buffers. */ net_pkt_cursor_init(pkt); do { /* Calculate the base pointer of the target TX buffer */ tx_buffer_offs = (void *)(dev_data->first_tx_buffer + (dev_conf->tx_buffer_size * curr_bd_idx)); /* Copy packet data to DMA buffer */ net_pkt_read(pkt, (void *)tx_buffer_offs, (tx_data_remaining < dev_conf->tx_buffer_size) ? tx_data_remaining : dev_conf->tx_buffer_size); /* Update current BD's control word */ reg_val = sys_read32(reg_ctrl) & (ETH_XLNX_GEM_TXBD_WRAP_BIT | ETH_XLNX_GEM_TXBD_USED_BIT); reg_val |= (tx_data_remaining < dev_conf->tx_buffer_size) ? tx_data_remaining : dev_conf->tx_buffer_size; sys_write32(reg_val, reg_ctrl); if (tx_data_remaining > dev_conf->tx_buffer_size) { /* Switch to next BD */ curr_bd_idx = (curr_bd_idx + 1) % dev_conf->txbd_count; reg_ctrl = (uint32_t)(&dev_data->txbd_ring.first_bd[curr_bd_idx].ctrl); } tx_data_remaining -= (tx_data_remaining < dev_conf->tx_buffer_size) ? tx_data_remaining : dev_conf->tx_buffer_size; } while (tx_data_remaining > 0); /* Set the 'last' bit in the current BD's control word */ reg_val |= ETH_XLNX_GEM_TXBD_LAST_BIT; /* * Clear the 'used' bits of all BDs involved in the current * transmission. In accordance with chapter 16.3.8 of the * Zynq-7000 TRM, the 'used' bits shall be cleared in reverse * order, so that the 'used' bit of the first BD is cleared * last just before the transmission is started. */ reg_val &= ~ETH_XLNX_GEM_TXBD_USED_BIT; sys_write32(reg_val, reg_ctrl); while (curr_bd_idx != first_bd_idx) { curr_bd_idx = (curr_bd_idx != 0) ? (curr_bd_idx - 1) : (dev_conf->txbd_count - 1); reg_ctrl = (uint32_t)(&dev_data->txbd_ring.first_bd[curr_bd_idx].ctrl); reg_val = sys_read32(reg_ctrl); reg_val &= ~ETH_XLNX_GEM_TXBD_USED_BIT; sys_write32(reg_val, reg_ctrl); } /* Set the start TX bit in the gem.net_ctrl register */ reg_val = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); reg_val |= ETH_XLNX_GEM_NWCTRL_STARTTX_BIT; sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); #ifdef CONFIG_NET_STATISTICS_ETHERNET dev_data->stats.bytes.sent += tx_data_length; dev_data->stats.pkts.tx++; #endif /* Block until TX has completed */ sem_status = k_sem_take(&dev_data->tx_done_sem, K_MSEC(100)); if (sem_status < 0) { LOG_ERR("%s TX confirmation timed out", dev->name); #ifdef CONFIG_NET_STATISTICS_ETHERNET dev_data->stats.tx_timeout_count++; #endif return -EIO; } return 0; } /** * @brief GEM device start function * GEM device start function. Clears all status registers and any * pending interrupts, enables RX and TX, enables interrupts. If * no PHY is managed by the current driver instance, this function * also declares the physical link up at the configured nominal * link speed. * * @param dev Pointer to the device data * @retval 0 upon successful completion */ static int eth_xlnx_gem_start_device(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t reg_val; if (dev_data->started) { return 0; } dev_data->started = true; /* Disable & clear all the MAC interrupts */ sys_write32(ETH_XLNX_GEM_IXR_ALL_MASK, dev_conf->base_addr + ETH_XLNX_GEM_IDR_OFFSET); sys_write32(ETH_XLNX_GEM_IXR_ALL_MASK, dev_conf->base_addr + ETH_XLNX_GEM_ISR_OFFSET); /* Clear RX & TX status registers */ sys_write32(0xFFFFFFFF, dev_conf->base_addr + ETH_XLNX_GEM_TXSR_OFFSET); sys_write32(0xFFFFFFFF, dev_conf->base_addr + ETH_XLNX_GEM_RXSR_OFFSET); /* RX and TX enable */ reg_val = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); reg_val |= (ETH_XLNX_GEM_NWCTRL_RXEN_BIT | ETH_XLNX_GEM_NWCTRL_TXEN_BIT); sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); /* Enable all the MAC interrupts */ sys_write32(ETH_XLNX_GEM_IXR_ALL_MASK, dev_conf->base_addr + ETH_XLNX_GEM_IER_OFFSET); /* Submit the delayed work for polling the link state */ if (k_work_delayable_remaining_get(&dev_data->phy_poll_delayed_work) == 0) { k_work_reschedule(&dev_data->phy_poll_delayed_work, K_NO_WAIT); } LOG_DBG("%s started", dev->name); return 0; } /** * @brief GEM device stop function * GEM device stop function. Disables all interrupts, disables * RX and TX, clears all status registers. If no PHY is managed * by the current driver instance, this function also declares * the physical link down. * * @param dev Pointer to the device data * @retval 0 upon successful completion */ static int eth_xlnx_gem_stop_device(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t reg_val; if (!dev_data->started) { return 0; } dev_data->started = false; /* Cancel the delayed work that polls the link state */ if (k_work_delayable_remaining_get(&dev_data->phy_poll_delayed_work) != 0) { k_work_cancel_delayable(&dev_data->phy_poll_delayed_work); } /* RX and TX disable */ reg_val = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); reg_val &= (~(ETH_XLNX_GEM_NWCTRL_RXEN_BIT | ETH_XLNX_GEM_NWCTRL_TXEN_BIT)); sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); /* Disable & clear all the MAC interrupts */ sys_write32(ETH_XLNX_GEM_IXR_ALL_MASK, dev_conf->base_addr + ETH_XLNX_GEM_IDR_OFFSET); sys_write32(ETH_XLNX_GEM_IXR_ALL_MASK, dev_conf->base_addr + ETH_XLNX_GEM_ISR_OFFSET); /* Clear RX & TX status registers */ sys_write32(0xFFFFFFFF, dev_conf->base_addr + ETH_XLNX_GEM_TXSR_OFFSET); sys_write32(0xFFFFFFFF, dev_conf->base_addr + ETH_XLNX_GEM_RXSR_OFFSET); LOG_DBG("%s stopped", dev->name); return 0; } /** * @brief GEM capability request function * Returns the capabilities of the GEM controller as an enumeration. * All of the data returned is derived from the device configuration * of the current GEM device instance. * * @param dev Pointer to the device data * @return Enumeration containing the current GEM device's capabilities */ static enum ethernet_hw_caps eth_xlnx_gem_get_capabilities( const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); enum ethernet_hw_caps caps = (enum ethernet_hw_caps)0; if (dev_conf->max_link_speed == LINK_1GBIT) { if (dev_conf->phy_advertise_lower) { caps |= (ETHERNET_LINK_1000BASE_T | ETHERNET_LINK_100BASE_T | ETHERNET_LINK_10BASE_T); } else { caps |= ETHERNET_LINK_1000BASE_T; } } else if (dev_conf->max_link_speed == LINK_100MBIT) { if (dev_conf->phy_advertise_lower) { caps |= (ETHERNET_LINK_100BASE_T | ETHERNET_LINK_10BASE_T); } else { caps |= ETHERNET_LINK_100BASE_T; } } else { caps |= ETHERNET_LINK_10BASE_T; } if (dev_conf->enable_rx_chksum_offload) { caps |= ETHERNET_HW_RX_CHKSUM_OFFLOAD; } if (dev_conf->enable_tx_chksum_offload) { caps |= ETHERNET_HW_TX_CHKSUM_OFFLOAD; } if (dev_conf->enable_fdx) { caps |= ETHERNET_DUPLEX_SET; } if (dev_conf->copy_all_frames) { caps |= ETHERNET_PROMISC_MODE; } return caps; } #ifdef CONFIG_NET_STATISTICS_ETHERNET /** * @brief GEM statistics data request function * Returns a pointer to the statistics data of the current GEM controller. * * @param dev Pointer to the device data * @return Pointer to the current GEM device's statistics data */ static struct net_stats_eth *eth_xlnx_gem_stats(const struct device *dev) { return &(DEV_DATA(dev)->stats); } #endif /** * @brief GEM Hardware reset function * Resets the current GEM device. Called from within the device * initialization function. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_reset_hw(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); /* * Controller reset sequence as described in the Zynq-7000 TRM, * chapter 16.3.1. */ /* Clear the NWCTRL register */ sys_write32(0x00000000, dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); /* Clear the statistics counters */ sys_write32(ETH_XLNX_GEM_STATCLR_MASK, dev_conf->base_addr + ETH_XLNX_GEM_NWCTRL_OFFSET); /* Clear the RX/TX status registers */ sys_write32(ETH_XLNX_GEM_TXSRCLR_MASK, dev_conf->base_addr + ETH_XLNX_GEM_TXSR_OFFSET); sys_write32(ETH_XLNX_GEM_RXSRCLR_MASK, dev_conf->base_addr + ETH_XLNX_GEM_RXSR_OFFSET); /* Disable all interrupts */ sys_write32(ETH_XLNX_GEM_IDRCLR_MASK, dev_conf->base_addr + ETH_XLNX_GEM_IDR_OFFSET); /* Clear the buffer queues */ sys_write32(0x00000000, dev_conf->base_addr + ETH_XLNX_GEM_RXQBASE_OFFSET); sys_write32(0x00000000, dev_conf->base_addr + ETH_XLNX_GEM_TXQBASE_OFFSET); } /** * @brief GEM clock configuration function * Calculates the pre-scalers for the TX clock to match the current * (if an associated PHY is managed) or nominal link speed. Called * from within the device initialization function. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_configure_clocks(const struct device *dev) { /* * Clock source configuration for the respective GEM as described * in the Zynq-7000 TRM, chapter 16.3.3, is not tackled here. This * is performed by the PS7Init code. Only the DIVISOR and DIVISOR1 * values for the respective GEM's TX clock are calculated here. */ const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t div0; uint32_t div1; uint32_t target = 2500000; /* default prevents 'may be uninitialized' warning */ uint32_t tmp; uint32_t clk_ctrl_reg; if ((!dev_conf->init_phy) || dev_data->eff_link_speed == LINK_DOWN) { /* * Run-time data indicates 'link down' or PHY management * is disabled for the current device -> this indicates the * initial device initialization. Once the PHY status polling * delayed work handler has picked up the result of the auto- * negotiation (if enabled), this if-statement will evaluate * to false. */ if (dev_conf->max_link_speed == LINK_10MBIT) { target = 2500000; /* Target frequency: 2.5 MHz */ } else if (dev_conf->max_link_speed == LINK_100MBIT) { target = 25000000; /* Target frequency: 25 MHz */ } else if (dev_conf->max_link_speed == LINK_1GBIT) { target = 125000000; /* Target frequency: 125 MHz */ } } else if (dev_data->eff_link_speed != LINK_DOWN) { /* * Use the effective link speed instead of the maximum/nominal * link speed for clock configuration. */ if (dev_data->eff_link_speed == LINK_10MBIT) { target = 2500000; /* Target frequency: 2.5 MHz */ } else if (dev_data->eff_link_speed == LINK_100MBIT) { target = 25000000; /* Target frequency: 25 MHz */ } else if (dev_data->eff_link_speed == LINK_1GBIT) { target = 125000000; /* Target frequency: 125 MHz */ } } /* * Caclculate the divisors for the target frequency. * The frequency of the PLL to which the divisors shall be applied are * provided in the respective GEM's device tree data. */ for (div0 = 1; div0 < 64; div0++) { for (div1 = 1; div1 < 64; div1++) { tmp = ((dev_conf->pll_clock_frequency / div0) / div1); if (tmp >= (target - 10) && tmp <= (target + 10)) { break; } } if (tmp >= (target - 10) && tmp <= (target + 10)) { break; } } #if defined(CONFIG_SOC_XILINX_ZYNQMP) /* * ZynqMP register crl_apb.GEMx_REF_CTRL: * RX_CLKACT bit [26] * CLKACT bit [25] * div0 bits [13..8], div1 bits [21..16] * Unlock CRL_APB write access if the write protect bit * is currently set, restore it afterwards. */ clk_ctrl_reg = sys_read32(dev_conf->clk_ctrl_reg_address); clk_ctrl_reg &= ~((ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR_MASK << ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR0_SHIFT) | (ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR_MASK << ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR1_SHIFT)); clk_ctrl_reg |= ((div0 & ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR_MASK) << ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR0_SHIFT) | ((div1 & ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR_MASK) << ETH_XLNX_CRL_APB_GEMX_REF_CTRL_DIVISOR1_SHIFT); clk_ctrl_reg |= ETH_XLNX_CRL_APB_GEMX_REF_CTRL_RX_CLKACT_BIT | ETH_XLNX_CRL_APB_GEMX_REF_CTRL_CLKACT_BIT; /* * Unlock CRL_APB write access if the write protect bit * is currently set, restore it afterwards. */ tmp = sys_read32(ETH_XLNX_CRL_APB_WPROT_REGISTER_ADDRESS); if ((tmp & ETH_XLNX_CRL_APB_WPROT_BIT) > 0) { sys_write32((tmp & ~ETH_XLNX_CRL_APB_WPROT_BIT), ETH_XLNX_CRL_APB_WPROT_REGISTER_ADDRESS); } sys_write32(clk_ctrl_reg, dev_conf->clk_ctrl_reg_address); if ((tmp & ETH_XLNX_CRL_APB_WPROT_BIT) > 0) { sys_write32(tmp, ETH_XLNX_CRL_APB_WPROT_REGISTER_ADDRESS); } # elif defined(CONFIG_SOC_SERIES_XILINX_ZYNQ7000) clk_ctrl_reg = sys_read32(dev_conf->clk_ctrl_reg_address); clk_ctrl_reg &= ~((ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR_MASK << ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR0_SHIFT) | (ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR_MASK << ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR1_SHIFT)); clk_ctrl_reg |= ((div0 & ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR_MASK) << ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR0_SHIFT) | ((div1 & ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR_MASK) << ETH_XLNX_SLCR_GEMX_CLK_CTRL_DIVISOR1_SHIFT); /* * SLCR must be unlocked prior to and locked after writing to * the clock configuration register. */ sys_write32(ETH_XLNX_SLCR_UNLOCK_KEY, ETH_XLNX_SLCR_UNLOCK_REGISTER_ADDRESS); sys_write32(clk_ctrl_reg, dev_conf->clk_ctrl_reg_address); sys_write32(ETH_XLNX_SLCR_LOCK_KEY, ETH_XLNX_SLCR_LOCK_REGISTER_ADDRESS); #endif /* CONFIG_SOC_XILINX_ZYNQMP / CONFIG_SOC_SERIES_XILINX_ZYNQ7000 */ LOG_DBG("%s set clock dividers div0/1 %u/%u for target " "frequency %u Hz", dev->name, div0, div1, target); } /** * @brief GEM initial Network Configuration Register setup function * Writes the contents of the current GEM device's Network Configuration * Register (NWCFG / gem.net_cfg). Called from within the device * initialization function. Implementation differs depending on whether * the current target is a Zynq-7000 or a ZynqMP. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_set_initial_nwcfg(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); uint32_t reg_val = 0; if (dev_conf->ignore_ipg_rxer) { /* [30] ignore IPG rx_er */ reg_val |= ETH_XLNX_GEM_NWCFG_IGNIPGRXERR_BIT; } if (dev_conf->disable_reject_nsp) { /* [29] disable rejection of non-standard preamble */ reg_val |= ETH_XLNX_GEM_NWCFG_BADPREAMBEN_BIT; } if (dev_conf->enable_ipg_stretch) { /* [28] enable IPG stretch */ reg_val |= ETH_XLNX_GEM_NWCFG_IPG_STRETCH_BIT; } if (dev_conf->enable_sgmii_mode) { /* [27] SGMII mode enable */ reg_val |= ETH_XLNX_GEM_NWCFG_SGMIIEN_BIT; } if (dev_conf->disable_reject_fcs_crc_errors) { /* [26] disable rejection of FCS/CRC errors */ reg_val |= ETH_XLNX_GEM_NWCFG_FCSIGNORE_BIT; } if (dev_conf->enable_rx_halfdup_while_tx) { /* [25] RX half duplex while TX enable */ reg_val |= ETH_XLNX_GEM_NWCFG_HDRXEN_BIT; } if (dev_conf->enable_rx_chksum_offload) { /* [24] enable RX IP/TCP/UDP checksum offload */ reg_val |= ETH_XLNX_GEM_NWCFG_RXCHKSUMEN_BIT; } if (dev_conf->disable_pause_copy) { /* [23] Do not copy pause Frames to memory */ reg_val |= ETH_XLNX_GEM_NWCFG_PAUSECOPYDI_BIT; } /* [22..21] Data bus width */ reg_val |= (((uint32_t)(dev_conf->amba_dbus_width) & ETH_XLNX_GEM_NWCFG_DBUSW_MASK) << ETH_XLNX_GEM_NWCFG_DBUSW_SHIFT); /* [20..18] MDC clock divider */ reg_val |= (((uint32_t)dev_conf->mdc_divider & ETH_XLNX_GEM_NWCFG_MDC_MASK) << ETH_XLNX_GEM_NWCFG_MDC_SHIFT); if (dev_conf->discard_rx_fcs) { /* [17] Discard FCS from received frames */ reg_val |= ETH_XLNX_GEM_NWCFG_FCSREM_BIT; } if (dev_conf->discard_rx_length_errors) { /* [16] RX length error discard */ reg_val |= ETH_XLNX_GEM_NWCFG_LENGTHERRDSCRD_BIT; } /* [15..14] RX buffer offset */ reg_val |= (((uint32_t)dev_conf->hw_rx_buffer_offset & ETH_XLNX_GEM_NWCFG_RXOFFS_MASK) << ETH_XLNX_GEM_NWCFG_RXOFFS_SHIFT); if (dev_conf->enable_pause) { /* [13] Enable pause TX */ reg_val |= ETH_XLNX_GEM_NWCFG_PAUSEEN_BIT; } if (dev_conf->enable_tbi) { /* [11] enable TBI instead of GMII/MII */ reg_val |= ETH_XLNX_GEM_NWCFG_TBIINSTEAD_BIT; } if (dev_conf->ext_addr_match) { /* [09] External address match enable */ reg_val |= ETH_XLNX_GEM_NWCFG_EXTADDRMATCHEN_BIT; } if (dev_conf->enable_1536_frames) { /* [08] Enable 1536 byte frames reception */ reg_val |= ETH_XLNX_GEM_NWCFG_1536RXEN_BIT; } if (dev_conf->enable_ucast_hash) { /* [07] Receive unicast hash frames */ reg_val |= ETH_XLNX_GEM_NWCFG_UCASTHASHEN_BIT; } if (dev_conf->enable_mcast_hash) { /* [06] Receive multicast hash frames */ reg_val |= ETH_XLNX_GEM_NWCFG_MCASTHASHEN_BIT; } if (dev_conf->disable_bcast) { /* [05] Do not receive broadcast frames */ reg_val |= ETH_XLNX_GEM_NWCFG_BCASTDIS_BIT; } if (dev_conf->copy_all_frames) { /* [04] Copy all frames */ reg_val |= ETH_XLNX_GEM_NWCFG_COPYALLEN_BIT; } if (dev_conf->discard_non_vlan) { /* [02] Receive only VLAN frames */ reg_val |= ETH_XLNX_GEM_NWCFG_NVLANDISC_BIT; } if (dev_conf->enable_fdx) { /* [01] enable Full duplex */ reg_val |= ETH_XLNX_GEM_NWCFG_FDEN_BIT; } if (dev_conf->max_link_speed == LINK_100MBIT) { /* [00] 10 or 100 Mbps */ reg_val |= ETH_XLNX_GEM_NWCFG_100_BIT; } else if (dev_conf->max_link_speed == LINK_1GBIT) { /* [10] Gigabit mode enable */ reg_val |= ETH_XLNX_GEM_NWCFG_1000_BIT; } /* * No else-branch for 10Mbit/s mode: * in 10 Mbit/s mode, both bits [00] and [10] remain 0 */ /* Write the assembled register contents to gem.net_cfg */ sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_NWCFG_OFFSET); } /** * @brief GEM Network Configuration Register link speed update function * Updates only the link speed-related bits of the Network Configuration * register. This is called from within #eth_xlnx_gem_poll_phy. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_set_nwcfg_link_speed(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t reg_val; /* * Read the current gem.net_cfg register contents and mask out * the link speed-related bits */ reg_val = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_NWCFG_OFFSET); reg_val &= ~(ETH_XLNX_GEM_NWCFG_1000_BIT | ETH_XLNX_GEM_NWCFG_100_BIT); /* No bits to set for 10 Mbps. 100 Mbps and 1 Gbps set one bit each. */ if (dev_data->eff_link_speed == LINK_100MBIT) { reg_val |= ETH_XLNX_GEM_NWCFG_100_BIT; } else if (dev_data->eff_link_speed == LINK_1GBIT) { reg_val |= ETH_XLNX_GEM_NWCFG_1000_BIT; } /* Write the assembled register contents to gem.net_cfg */ sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_NWCFG_OFFSET); } /** * @brief GEM MAC address setup function * Acquires the MAC address to be assigned to the current GEM device * from the device configuration data which in turn acquires it from * the device tree data, then writes it to the gem.spec_addr1_bot/LADDR1L * and gem.spec_addr1_top/LADDR1H registers. Called from within the device * initialization function. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_set_mac_address(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t regval_top; uint32_t regval_bot; regval_bot = (dev_data->mac_addr[0] & 0xFF); regval_bot |= (dev_data->mac_addr[1] & 0xFF) << 8; regval_bot |= (dev_data->mac_addr[2] & 0xFF) << 16; regval_bot |= (dev_data->mac_addr[3] & 0xFF) << 24; regval_top = (dev_data->mac_addr[4] & 0xFF); regval_top |= (dev_data->mac_addr[5] & 0xFF) << 8; sys_write32(regval_bot, dev_conf->base_addr + ETH_XLNX_GEM_LADDR1L_OFFSET); sys_write32(regval_top, dev_conf->base_addr + ETH_XLNX_GEM_LADDR1H_OFFSET); LOG_DBG("%s MAC %02X:%02X:%02X:%02X:%02X:%02X", dev->name, dev_data->mac_addr[0], dev_data->mac_addr[1], dev_data->mac_addr[2], dev_data->mac_addr[3], dev_data->mac_addr[4], dev_data->mac_addr[5]); } /** * @brief GEM initial DMA Control Register setup function * Writes the contents of the current GEM device's DMA Control Register * (DMACR / gem.dma_cfg). Called from within the device initialization * function. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_set_initial_dmacr(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); uint32_t reg_val = 0; /* * gem.dma_cfg register bit (field) definitions: * comp. Zynq-7000 TRM, p. 1278 ff. */ if (dev_conf->disc_rx_ahb_unavail) { /* [24] Discard RX packet when AHB unavailable */ reg_val |= ETH_XLNX_GEM_DMACR_DISCNOAHB_BIT; } /* * [23..16] DMA RX buffer size in AHB system memory * e.g.: 0x02 = 128, 0x18 = 1536, 0xA0 = 10240 */ reg_val |= (((dev_conf->rx_buffer_size / 64) & ETH_XLNX_GEM_DMACR_RX_BUF_MASK) << ETH_XLNX_GEM_DMACR_RX_BUF_SHIFT); if (dev_conf->enable_tx_chksum_offload) { /* [11] TX TCP/UDP/IP checksum offload to GEM */ reg_val |= ETH_XLNX_GEM_DMACR_TCP_CHKSUM_BIT; } if (dev_conf->tx_buffer_size_full) { /* [10] TX buffer memory size select */ reg_val |= ETH_XLNX_GEM_DMACR_TX_SIZE_BIT; } /* * [09..08] RX packet buffer memory size select * 0 = 1kB, 1 = 2kB, 2 = 4kB, 3 = 8kB */ reg_val |= (((uint32_t)dev_conf->hw_rx_buffer_size << ETH_XLNX_GEM_DMACR_RX_SIZE_SHIFT) & ETH_XLNX_GEM_DMACR_RX_SIZE_MASK); if (dev_conf->enable_ahb_packet_endian_swap) { /* [07] AHB packet data endian swap enable */ reg_val |= ETH_XLNX_GEM_DMACR_ENDIAN_BIT; } if (dev_conf->enable_ahb_md_endian_swap) { /* [06] AHB mgmt descriptor endian swap enable */ reg_val |= ETH_XLNX_GEM_DMACR_DESCR_ENDIAN_BIT; } /* * [04..00] AHB fixed burst length for DMA ops. * 00001 = single AHB bursts, * 001xx = attempt to use INCR4 bursts, * 01xxx = attempt to use INCR8 bursts, * 1xxxx = attempt to use INCR16 bursts */ reg_val |= ((uint32_t)dev_conf->ahb_burst_length & ETH_XLNX_GEM_DMACR_AHB_BURST_LENGTH_MASK); /* Write the assembled register contents */ sys_write32(reg_val, dev_conf->base_addr + ETH_XLNX_GEM_DMACR_OFFSET); } /** * @brief GEM associated PHY detection and setup function * If the current GEM device shall manage an associated PHY, its detection * and configuration is performed from within this function. Called from * within the device initialization function. This function refers to * functionality implemented in the phy_xlnx_gem module. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_init_phy(const struct device *dev) { struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); int detect_rc; LOG_DBG("%s attempting to initialize associated PHY", dev->name); /* * The phy_xlnx_gem_detect function checks if a valid PHY * ID is returned when reading the corresponding high / low * ID registers for all valid MDIO addresses. If a compatible * PHY is detected, the function writes a pointer to the * vendor-specific implementations of the PHY management * functions to the run-time device data struct, along with * the ID and the MDIO address of the detected PHY (dev_data-> * phy_id, dev_data->phy_addr, dev_data->phy_access_api). */ detect_rc = phy_xlnx_gem_detect(dev); if (detect_rc == 0 && dev_data->phy_id != 0x00000000 && dev_data->phy_id != 0xFFFFFFFF && dev_data->phy_access_api != NULL) { /* A compatible PHY was detected -> reset & configure it */ dev_data->phy_access_api->phy_reset_func(dev); dev_data->phy_access_api->phy_configure_func(dev); } else { LOG_WRN("%s no compatible PHY detected", dev->name); } } /** * @brief GEM associated PHY status polling function * This handler of a delayed work item is called from the context of * the system work queue. It is always scheduled at least once during the * interface initialization. If the current driver instance manages a * PHY, the delayed work item will be re-scheduled in order to continuously * monitor the link state and speed while the device is active. Link state * and link speed changes are polled, which may result in the link state * change being propagated (carrier on/off) and / or the TX clock being * reconfigured to match the current link speed. If PHY management is dis- * abled for the current driver instance or no compatible PHY was detected, * the work item will not be re-scheduled and default link speed and link * state values are applied. This function refers to functionality imple- * mented in the phy_xlnx_gem module. * * @param work Pointer to the delayed work item which facilitates * access to the current device's configuration data */ static void eth_xlnx_gem_poll_phy(struct k_work *work) { struct k_work_delayable *dwork = k_work_delayable_from_work(work); struct eth_xlnx_gem_dev_data *dev_data = CONTAINER_OF(dwork, struct eth_xlnx_gem_dev_data, phy_poll_delayed_work); const struct device *dev = net_if_get_device(dev_data->iface); const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); uint16_t phy_status; uint8_t link_status; if (dev_data->phy_access_api != NULL) { /* A supported PHY is managed by the driver */ phy_status = dev_data->phy_access_api->phy_poll_status_change_func(dev); if ((phy_status & ( PHY_XLNX_GEM_EVENT_LINK_SPEED_CHANGED | PHY_XLNX_GEM_EVENT_LINK_STATE_CHANGED | PHY_XLNX_GEM_EVENT_AUTONEG_COMPLETE)) != 0) { /* * Get the PHY's link status. Handling a 'link down' * event the simplest possible case. */ link_status = dev_data->phy_access_api->phy_poll_link_status_func(dev); if (link_status == 0) { /* * Link is down -> propagate to the Ethernet * layer that the link has gone down. */ dev_data->eff_link_speed = LINK_DOWN; net_eth_carrier_off(dev_data->iface); LOG_WRN("%s link down", dev->name); } else { /* * A link has been detected, which, depending * on the driver's configuration, might have * a different speed than the previous link. * Therefore, the clock dividers must be ad- * justed accordingly. */ dev_data->eff_link_speed = dev_data->phy_access_api->phy_poll_link_speed_func(dev); eth_xlnx_gem_configure_clocks(dev); eth_xlnx_gem_set_nwcfg_link_speed(dev); net_eth_carrier_on(dev_data->iface); LOG_INF("%s link up, %s", dev->name, (dev_data->eff_link_speed == LINK_1GBIT) ? "1 GBit/s" : (dev_data->eff_link_speed == LINK_100MBIT) ? "100 MBit/s" : (dev_data->eff_link_speed == LINK_10MBIT) ? "10 MBit/s" : "undefined / link down"); } } /* * Re-submit the delayed work using the interval from the device * configuration data. */ k_work_reschedule(&dev_data->phy_poll_delayed_work, K_MSEC(dev_conf->phy_poll_interval)); } else { /* * The current driver instance doesn't manage a PHY or no * supported PHY was detected -> pretend the configured max. * link speed is the effective link speed and that the link * is up. The delayed work item won't be re-scheduled, as * there isn't anything to poll for. */ dev_data->eff_link_speed = dev_conf->max_link_speed; eth_xlnx_gem_configure_clocks(dev); eth_xlnx_gem_set_nwcfg_link_speed(dev); net_eth_carrier_on(dev_data->iface); LOG_WRN("%s PHY not managed by the driver or no compatible " "PHY detected, assuming link up at %s", dev->name, (dev_conf->max_link_speed == LINK_1GBIT) ? "1 GBit/s" : (dev_conf->max_link_speed == LINK_100MBIT) ? "100 MBit/s" : (dev_conf->max_link_speed == LINK_10MBIT) ? "10 MBit/s" : "undefined"); } } /** * @brief GEM DMA memory area setup function * Sets up the DMA memory area to be used by the current GEM device. * Called from within the device initialization function or from within * the context of the PHY status polling delayed work handler. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_configure_buffers(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); struct eth_xlnx_gem_bd *bdptr; uint32_t buf_iter; /* Initial configuration of the RX/TX BD rings */ DT_INST_FOREACH_STATUS_OKAY(ETH_XLNX_GEM_INIT_BD_RING) /* * Set initial RX BD data -> comp. Zynq-7000 TRM, Chapter 16.3.5, * "Receive Buffer Descriptor List". The BD ring data other than * the base RX/TX buffer pointers will be set in eth_xlnx_gem_- * iface_init() */ bdptr = dev_data->rxbd_ring.first_bd; for (buf_iter = 0; buf_iter < (dev_conf->rxbd_count - 1); buf_iter++) { /* Clear 'used' bit -> BD is owned by the controller */ bdptr->ctrl = 0; bdptr->addr = (uint32_t)dev_data->first_rx_buffer + (buf_iter * (uint32_t)dev_conf->rx_buffer_size); ++bdptr; } /* * For the last BD, bit [1] must be OR'ed in the buffer memory * address -> this is the 'wrap' bit indicating that this is the * last BD in the ring. This location is used as bits [1..0] can't * be part of the buffer address due to alignment requirements * anyways. Watch out: TX BDs handle this differently, their wrap * bit is located in the BD's control word! */ bdptr->ctrl = 0; /* BD is owned by the controller */ bdptr->addr = ((uint32_t)dev_data->first_rx_buffer + (buf_iter * (uint32_t)dev_conf->rx_buffer_size)) | ETH_XLNX_GEM_RXBD_WRAP_BIT; /* * Set initial TX BD data -> comp. Zynq-7000 TRM, Chapter 16.3.5, * "Transmit Buffer Descriptor List". TX BD ring data has already * been set up in eth_xlnx_gem_iface_init() */ bdptr = dev_data->txbd_ring.first_bd; for (buf_iter = 0; buf_iter < (dev_conf->txbd_count - 1); buf_iter++) { /* Set up the control word -> 'used' flag must be set. */ bdptr->ctrl = ETH_XLNX_GEM_TXBD_USED_BIT; bdptr->addr = (uint32_t)dev_data->first_tx_buffer + (buf_iter * (uint32_t)dev_conf->tx_buffer_size); ++bdptr; } /* * For the last BD, set the 'wrap' bit indicating to the controller * that this BD is the last one in the ring. -> For TX BDs, the 'wrap' * bit isn't located in the address word, but in the control word * instead */ bdptr->ctrl = (ETH_XLNX_GEM_TXBD_WRAP_BIT | ETH_XLNX_GEM_TXBD_USED_BIT); bdptr->addr = (uint32_t)dev_data->first_tx_buffer + (buf_iter * (uint32_t)dev_conf->tx_buffer_size); /* Set free count/current index in the RX/TX BD ring data */ dev_data->rxbd_ring.next_to_process = 0; dev_data->rxbd_ring.next_to_use = 0; dev_data->rxbd_ring.free_bds = dev_conf->rxbd_count; dev_data->txbd_ring.next_to_process = 0; dev_data->txbd_ring.next_to_use = 0; dev_data->txbd_ring.free_bds = dev_conf->txbd_count; /* Write pointers to the first RX/TX BD to the controller */ sys_write32((uint32_t)dev_data->rxbd_ring.first_bd, dev_conf->base_addr + ETH_XLNX_GEM_RXQBASE_OFFSET); sys_write32((uint32_t)dev_data->txbd_ring.first_bd, dev_conf->base_addr + ETH_XLNX_GEM_TXQBASE_OFFSET); } /** * @brief GEM RX data pending handler wrapper for the work queue * Wraps the RX data pending handler, eth_xlnx_gem_handle_rx_pending, * for the scenario in which the current GEM device is configured * to defer RX pending / TX done indication handling to the system * work queue. In this case, the work item received by this wrapper * function will be enqueued from within the ISR if the corresponding * bit is set within the controller's interrupt status register * (gem.intr_status). * * @param item Pointer to the work item enqueued by the ISR which * facilitates access to the current device's data */ static void eth_xlnx_gem_rx_pending_work(struct k_work *item) { struct eth_xlnx_gem_dev_data *dev_data = CONTAINER_OF(item, struct eth_xlnx_gem_dev_data, rx_pend_work); const struct device *dev = net_if_get_device(dev_data->iface); eth_xlnx_gem_handle_rx_pending(dev); } /** * @brief GEM RX data pending handler * This handler is called either from within the ISR or from the * context of the system work queue whenever the RX data pending bit * is set in the controller's interrupt status register (gem.intr_status). * No further RX data pending interrupts will be triggered until this * handler has been executed, which eventually clears the corresponding * interrupt status bit. This function acquires the incoming packet * data from the DMA memory area via the RX buffer descriptors and copies * the data to a packet which will then be handed over to the network * stack. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_handle_rx_pending(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t reg_addr; uint32_t reg_ctrl; uint32_t reg_val; uint32_t reg_val_rxsr; uint8_t first_bd_idx; uint8_t last_bd_idx; uint8_t curr_bd_idx; uint32_t rx_data_length; uint32_t rx_data_remaining; struct net_pkt *pkt; /* Read the RX status register */ reg_val_rxsr = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_RXSR_OFFSET); /* * TODO Evaluate error flags from RX status register word * here for proper error handling. */ while (1) { curr_bd_idx = dev_data->rxbd_ring.next_to_process; first_bd_idx = last_bd_idx = curr_bd_idx; reg_addr = (uint32_t)(&dev_data->rxbd_ring.first_bd[first_bd_idx].addr); reg_ctrl = (uint32_t)(&dev_data->rxbd_ring.first_bd[first_bd_idx].ctrl); /* * Basic precondition checks for the current BD's * address and control words */ reg_val = sys_read32(reg_addr); if ((reg_val & ETH_XLNX_GEM_RXBD_USED_BIT) == 0) { /* * No new data contained in the current BD * -> break out of the RX loop */ break; } reg_val = sys_read32(reg_ctrl); if ((reg_val & ETH_XLNX_GEM_RXBD_START_OF_FRAME_BIT) == 0) { /* * Although the current BD is marked as 'used', it * doesn't contain the SOF bit. */ LOG_ERR("%s unexpected missing SOF bit in RX BD [%u]", dev->name, first_bd_idx); break; } /* * As long as the current BD doesn't have the EOF bit set, * iterate forwards until the EOF bit is encountered. Only * the BD containing the EOF bit also contains the length * of the received packet which spans multiple buffers. */ do { reg_ctrl = (uint32_t)(&dev_data->rxbd_ring.first_bd[last_bd_idx].ctrl); reg_val = sys_read32(reg_ctrl); rx_data_length = rx_data_remaining = (reg_val & ETH_XLNX_GEM_RXBD_FRAME_LENGTH_MASK); if ((reg_val & ETH_XLNX_GEM_RXBD_END_OF_FRAME_BIT) == 0) { last_bd_idx = (last_bd_idx + 1) % dev_conf->rxbd_count; } } while ((reg_val & ETH_XLNX_GEM_RXBD_END_OF_FRAME_BIT) == 0); /* * Store the position of the first BD behind the end of the * frame currently being processed as 'next to process' */ dev_data->rxbd_ring.next_to_process = (last_bd_idx + 1) % dev_conf->rxbd_count; /* * Allocate a destination packet from the network stack * now that the total frame length is known. */ pkt = net_pkt_rx_alloc_with_buffer(dev_data->iface, rx_data_length, AF_UNSPEC, 0, K_NO_WAIT); if (pkt == NULL) { LOG_ERR("RX packet buffer alloc failed: %u bytes", rx_data_length); #ifdef CONFIG_NET_STATISTICS_ETHERNET dev_data->stats.errors.rx++; dev_data->stats.error_details.rx_no_buffer_count++; #endif } /* * Copy data from all involved RX buffers into the allocated * packet's data buffer. If we don't have a packet buffer be- * cause none are available, we still have to iterate over all * involved BDs in order to properly release them for re-use * by the controller. */ do { if (pkt != NULL) { net_pkt_write(pkt, (const void *) (dev_data->rxbd_ring.first_bd[curr_bd_idx].addr & ETH_XLNX_GEM_RXBD_BUFFER_ADDR_MASK), (rx_data_remaining < dev_conf->rx_buffer_size) ? rx_data_remaining : dev_conf->rx_buffer_size); } rx_data_remaining -= (rx_data_remaining < dev_conf->rx_buffer_size) ? rx_data_remaining : dev_conf->rx_buffer_size; /* * The entire packet data of the current BD has been * processed, on to the next BD -> preserve the RX BD's * 'wrap' bit & address, but clear the 'used' bit. */ reg_addr = (uint32_t)(&dev_data->rxbd_ring.first_bd[curr_bd_idx].addr); reg_val = sys_read32(reg_addr); reg_val &= ~ETH_XLNX_GEM_RXBD_USED_BIT; sys_write32(reg_val, reg_addr); curr_bd_idx = (curr_bd_idx + 1) % dev_conf->rxbd_count; } while (curr_bd_idx != ((last_bd_idx + 1) % dev_conf->rxbd_count)); /* Propagate the received packet to the network stack */ if (pkt != NULL) { if (net_recv_data(dev_data->iface, pkt) < 0) { LOG_ERR("%s RX packet hand-over to IP stack failed", dev->name); net_pkt_unref(pkt); } #ifdef CONFIG_NET_STATISTICS_ETHERNET else { dev_data->stats.bytes.received += rx_data_length; dev_data->stats.pkts.rx++; } #endif } } /* Clear the RX status register */ sys_write32(0xFFFFFFFF, dev_conf->base_addr + ETH_XLNX_GEM_RXSR_OFFSET); /* Re-enable the frame received interrupt source */ sys_write32(ETH_XLNX_GEM_IXR_FRAME_RX_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IER_OFFSET); } /** * @brief GEM TX done handler wrapper for the work queue * Wraps the TX done handler, eth_xlnx_gem_handle_tx_done, * for the scenario in which the current GEM device is configured * to defer RX pending / TX done indication handling to the system * work queue. In this case, the work item received by this wrapper * function will be enqueued from within the ISR if the corresponding * bit is set within the controller's interrupt status register * (gem.intr_status). * * @param item Pointer to the work item enqueued by the ISR which * facilitates access to the current device's data */ static void eth_xlnx_gem_tx_done_work(struct k_work *item) { struct eth_xlnx_gem_dev_data *dev_data = CONTAINER_OF(item, struct eth_xlnx_gem_dev_data, tx_done_work); const struct device *dev = net_if_get_device(dev_data->iface); eth_xlnx_gem_handle_tx_done(dev); } /** * @brief GEM TX done handler * This handler is called either from within the ISR or from the * context of the system work queue whenever the TX done bit is set * in the controller's interrupt status register (gem.intr_status). * No further TX done interrupts will be triggered until this handler * has been executed, which eventually clears the corresponding * interrupt status bit. Once this handler reaches the end of its * execution, the eth_xlnx_gem_send call which effectively triggered * it is unblocked by posting to the current GEM's TX done semaphore * on which the send function is blocking. * * @param dev Pointer to the device data */ static void eth_xlnx_gem_handle_tx_done(const struct device *dev) { const struct eth_xlnx_gem_dev_cfg *dev_conf = DEV_CFG(dev); struct eth_xlnx_gem_dev_data *dev_data = DEV_DATA(dev); uint32_t reg_ctrl; uint32_t reg_val; uint32_t reg_val_txsr; uint8_t curr_bd_idx; uint8_t first_bd_idx; uint8_t bds_processed = 0; uint8_t bd_is_last; /* Read the TX status register */ reg_val_txsr = sys_read32(dev_conf->base_addr + ETH_XLNX_GEM_TXSR_OFFSET); /* * TODO Evaluate error flags from TX status register word * here for proper error handling */ if (dev_conf->defer_txd_to_queue) { k_sem_take(&(dev_data->txbd_ring.ring_sem), K_FOREVER); } curr_bd_idx = first_bd_idx = dev_data->txbd_ring.next_to_process; reg_ctrl = (uint32_t)(&dev_data->txbd_ring.first_bd[curr_bd_idx].ctrl); reg_val = sys_read32(reg_ctrl); do { ++bds_processed; /* * TODO Evaluate error flags from current BD control word * here for proper error handling */ /* * Check if the BD we're currently looking at is the last BD * of the current transmission */ bd_is_last = ((reg_val & ETH_XLNX_GEM_TXBD_LAST_BIT) != 0) ? 1 : 0; /* * Reset control word of the current BD, clear everything but * the 'wrap' bit, then set the 'used' bit */ reg_val &= ETH_XLNX_GEM_TXBD_WRAP_BIT; reg_val |= ETH_XLNX_GEM_TXBD_USED_BIT; sys_write32(reg_val, reg_ctrl); /* Move on to the next BD or break out of the loop */ if (bd_is_last == 1) { break; } curr_bd_idx = (curr_bd_idx + 1) % dev_conf->txbd_count; reg_ctrl = (uint32_t)(&dev_data->txbd_ring.first_bd[curr_bd_idx].ctrl); reg_val = sys_read32(reg_ctrl); } while (bd_is_last == 0 && curr_bd_idx != first_bd_idx); if (curr_bd_idx == first_bd_idx && bd_is_last == 0) { LOG_WRN("%s TX done handling wrapped around", dev->name); } dev_data->txbd_ring.next_to_process = (dev_data->txbd_ring.next_to_process + bds_processed) % dev_conf->txbd_count; dev_data->txbd_ring.free_bds += bds_processed; if (dev_conf->defer_txd_to_queue) { k_sem_give(&(dev_data->txbd_ring.ring_sem)); } /* Clear the TX status register */ sys_write32(0xFFFFFFFF, dev_conf->base_addr + ETH_XLNX_GEM_TXSR_OFFSET); /* Re-enable the TX complete interrupt source */ sys_write32(ETH_XLNX_GEM_IXR_TX_COMPLETE_BIT, dev_conf->base_addr + ETH_XLNX_GEM_IER_OFFSET); /* Indicate completion to a blocking eth_xlnx_gem_send() call */ k_sem_give(&dev_data->tx_done_sem); } /* EOF */
23,547
979
<reponame>risingphoenix/SublimePHPCompanion import sublime import sublime_plugin import re class GotoDefinitionScopeCommand(sublime_plugin.TextCommand): def run(self, edit): run = GTDRun(self.view, self.view.window()) run.do() class GTDRun: def __init__(self, view, window): self.view = view self.window = window self.selected_region = self.view.word(self.view.sel()[0]) def do(self): if self.in_class_scope(): selected_str = self.view.substr(self.selected_region) for symbol in self.view.symbols(): if symbol[1] == selected_str: self.view.sel().clear() self.view.sel().add(symbol[0]) self.view.show(symbol[0]) return # falls back to the original functionality self.window.run_command("goto_definition") def in_class_scope(self): selected_point = self.selected_region.begin() # the search area is 60 pts wide, maybe it is not enough search_str = self.view.substr(sublime.Region(selected_point - 60,selected_point)) return re.search("(\$this->|self::|static::)(\s)*$", search_str) != None
547
4,538
<reponame>wstong999/AliOS-Things /* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <poll.h> #include <aos/hal/adc.h> #include <vfsdev/adc_dev.h> #include <devicevfs/devicevfs.h> #ifdef CONFIG_ADC_NUM #define PLATFORM_ADC_NUM CONFIG_ADC_NUM #else #define PLATFORM_ADC_NUM 4 #endif #if (PLATFORM_ADC_NUM > 0) // ADC device node will be named with "/dev/adc<x>", where <x> is adc port id #define ADC_DEV_NAME_FORMAT "adc%d" typedef struct vfs_adc { int ref_cnt; adc_dev_t dev; } vfs_adc_t; int adc_device_ioctl (file_t *f, int cmd, unsigned long arg) { int ret = 0; io_adc_arg_t adc_arg; io_adc_arg_t *p_adc_arg = NULL; char *fname = f->node->i_name; vfs_adc_t *vd = (vfs_adc_t *)f->node->i_arg; adc_dev_t *adc_dev = &vd->dev; // arg is channel info ddkc_dbg("cmd:0x%x, arg:0x%lx\r\n", cmd, arg); switch (cmd) { case IOC_ADC_GET_VALUE: p_adc_arg = (io_adc_arg_t *)arg; BUG_ON_MSG(!p_adc_arg, "IOC_ADC_GET_VALUE - arg should not be NULL\r\n"); /* copy timeout config from user */ aos_ipc_copy(&adc_arg, p_adc_arg, sizeof(io_adc_arg_t)); ret = hal_adc_value_get(adc_dev, &adc_arg.value, adc_arg.timeout); /* copy value back to user */ aos_ipc_copy(p_adc_arg, &adc_arg, sizeof(io_adc_arg_t)); ddkc_info("IOC_ADC_GET_VALUE, adc_arg.value:%d, ret:%d\r\n", adc_arg.value, ret); break; case IOC_ADC_START: ddkc_dbg("IOC_ADC_START, arg:%ld\r\n", arg); adc_dev->config.sampling_cycle = arg; ret = vd->ref_cnt ? 0 : hal_adc_init(adc_dev); if (ret) { ddkc_err("%s starts failed, port:%d, ref_cnt:%d\r\n", fname, adc_dev->port, vd->ref_cnt); } else { vd->ref_cnt++; ddkc_dbg("%s starts success, port:%d, ref_cnt:%d\r\n", fname, adc_dev->port, vd->ref_cnt); } break; case IOC_ADC_STOP: vd->ref_cnt--; ret = vd->ref_cnt ? 0 : hal_adc_finalize(adc_dev); if (ret) { ddkc_err("%s stop failed, port:%d\r\n", fname, adc_dev->port); } else { ddkc_dbg("%s stop success, port:%d\r\n", fname, adc_dev->port); } break; default: ddkc_err("invalid cmd:%d\r\n", cmd); break; } return ret; } int adc_device_open (inode_t *node, file_t *f) { ddkc_info("device:%s open succeed\r\n", node->i_name); return 0; } int adc_device_close (file_t *f) { ddkc_info("device:%s close succeed\r\n", f->node->i_name); return 0; } /************************** device ****************************/ subsys_file_ops_t adc_device_fops = { .open = adc_device_open, .close = adc_device_close, .read = NULL, .write = NULL, .ioctl = adc_device_ioctl, .poll = NULL, }; int adc_device_init (struct u_platform_device *pdev) { // make sure 0 is returned if init operation success // or aos_dev_reg procedure will break and no device node will be registered ddkc_dbg("%s\r\n", __func__); return 0; } int adc_device_deinit (struct u_platform_device *pdev) { ddkc_dbg("%s\r\n", __func__); return 0; } int adc_device_pm (struct u_platform_device *pdev, u_pm_ops_t state) { ddkc_dbg("%s\r\n", __func__); return 0; } struct subsys_drv adc_device_drv = { .drv_name = "adc", .init = adc_device_init, .deinit = adc_device_deinit, .pm = adc_device_pm, }; struct subsys_dev *g_adc_device_array[PLATFORM_ADC_NUM]; int vfs_adc_drv_init (void) { int i = 0; int j = 0; int ret = 0; int node_name_len = 0; struct subsys_dev **ppsdev = NULL; ddkc_dbg("adc vfs driver init starts\r\n"); node_name_len = strlen(ADC_DEV_NAME_FORMAT) + 1; memset(g_adc_device_array, 0, sizeof(g_adc_device_array)); ppsdev = g_adc_device_array; for (i = 0; i < PLATFORM_ADC_NUM; i++) { vfs_adc_t *vd = malloc(sizeof(vfs_adc_t)); *ppsdev = malloc(sizeof(struct subsys_dev) + node_name_len); if (!(*ppsdev) || !vd) { ddkc_err("malloc failed, *ppsdev:%p, vd:%p\r\n", *ppsdev, vd); if (*ppsdev) { free(*ppsdev); *ppsdev = NULL; } if (vd) free(vd); goto err; } memset(*ppsdev, 0, sizeof(struct subsys_dev) + node_name_len); memset(vd, 0, sizeof(*vd)); // vfs_adc_t's port should be remained during the whole driver life vd->dev.port = i; (*ppsdev)->node_name = (char *)((*ppsdev) + 1); snprintf((*ppsdev)->node_name, node_name_len, ADC_DEV_NAME_FORMAT, i); ddkc_dbg("*ppsdev:%p, node_name:%s, (*ppsdev) + 1:%p, sizeof(struct subsys_dev):%d\r\n", *ppsdev, (*ppsdev)->node_name, (*ppsdev) + 1, sizeof(struct subsys_dev)); (*ppsdev)->permission = 0; // please refer to definitions in enum SUBSYS_BUS_TYPE (*ppsdev)->type = BUS_TYPE_PLATFORM; // user_data will be passed to open operation via node->i_arg (*ppsdev)->user_data = vd; ret = aos_dev_reg(*ppsdev, &adc_device_fops, &adc_device_drv); if (ret) { ddkc_err("aos_dev_reg for adc%d failed, ret:%d\r\n", i, ret); free(vd); free(*ppsdev); *ppsdev = NULL; goto err; } ppsdev++; } ddkc_dbg("adc vfs driver init finish, ret:%d\r\n", ret); return 0; err: ppsdev = g_adc_device_array; for (j = 0; j < i; j++) { // shall uninstall adc devices who are already registered if (*ppsdev) { aos_dev_unreg(*ppsdev); ddkc_info("free memory for adc%d\r\n", j); if ((*ppsdev)->user_data) free((*ppsdev)->user_data); free(*ppsdev); *ppsdev = NULL; } ppsdev++; } ddkc_err("adc vfs driver init failed, ret:%d\r\n", ret); return ret; } VFS_DRIVER_ENTRY(vfs_adc_drv_init) #endif
3,251