max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
839
/** * 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.cxf.jaxws.spi; import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Set; import org.apache.cxf.Bus; import org.apache.cxf.common.spi.GeneratedClassClassLoader; import org.apache.cxf.common.util.PackageUtils; import org.apache.cxf.common.util.StringUtils; import org.apache.cxf.jaxws.WrapperClassGenerator; import org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean; import org.apache.cxf.service.model.InterfaceInfo; import org.apache.cxf.service.model.MessageInfo; import org.apache.cxf.service.model.MessagePartInfo; import org.apache.cxf.service.model.OperationInfo; import org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean; /** If class has been generated during build time * (use @see org.apache.cxf.common.spi.GeneratedClassClassLoaderCapture capture to save bytes) * you can set class loader to avoid class generation during runtime: * bus.setExtension(new GeneratedWrapperClassLoader(bus), WrapperClassCreator.class); * @author <NAME> */ public class WrapperClassLoader extends GeneratedClassClassLoader implements WrapperClassCreator { public WrapperClassLoader(Bus bus) { super(bus); } @Override public Set<Class<?>> generate(JaxWsServiceFactoryBean factory, InterfaceInfo interfaceInfo, boolean q) { Set<Class<?>> wrapperBeans = new LinkedHashSet<>(); for (OperationInfo opInfo : interfaceInfo.getOperations()) { if (opInfo.isUnwrappedCapable()) { Method method = (Method)opInfo.getProperty(ReflectionServiceFactoryBean.METHOD); if (method == null) { continue; } MessagePartInfo inf = opInfo.getInput().getFirstMessagePart(); if (inf.getTypeClass() == null) { MessageInfo messageInfo = opInfo.getUnwrappedOperation().getInput(); wrapperBeans.add(createWrapperClass(inf, messageInfo, opInfo, method, true, factory)); } MessageInfo messageInfo = opInfo.getUnwrappedOperation().getOutput(); if (messageInfo != null) { inf = opInfo.getOutput().getFirstMessagePart(); if (inf.getTypeClass() == null) { wrapperBeans.add(createWrapperClass(inf, messageInfo, opInfo, method, false, factory)); } } } } return wrapperBeans; } private Class<?> createWrapperClass(MessagePartInfo wrapperPart, MessageInfo messageInfo, OperationInfo op, Method method, boolean isRequest, JaxWsServiceFactoryBean factory) { boolean anonymous = factory.getAnonymousWrapperTypes(); String pkg = getPackageName(method) + ".jaxws_asm" + (anonymous ? "_an" : ""); String className = pkg + "." + StringUtils.capitalize(op.getName().getLocalPart()); if (!isRequest) { className = className + "Response"; } Class<?> def = findClass(className, method.getDeclaringClass()); String origClassName = className; int count = 0; while (def != null) { Boolean b = messageInfo.getProperty("parameterized", Boolean.class); if (b != null && b) { className = origClassName + (++count); def = findClass(className, method.getDeclaringClass()); } else { wrapperPart.setTypeClass(def); return def; } } //throw new ClassNotFoundException(origClassName); return null; } private String getPackageName(Method method) { String pkg = PackageUtils.getPackageName(method.getDeclaringClass()); return pkg.length() == 0 ? WrapperClassGenerator.DEFAULT_PACKAGE_NAME : pkg; } }
2,245
1,702
/* * Copyright 2019-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.nativex.domain.reflect; /** * * @author <NAME> */ public abstract class MemberDescriptor { protected String name; MemberDescriptor() { } MemberDescriptor(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } protected void buildToStringProperty(StringBuilder string, String property, Object value) { if (value != null) { string.append(" ").append(property).append(":").append(value); } } protected boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return o1.equals(o2); } protected int nullSafeHashCode(Object o) { return (o != null) ? o.hashCode() : 0; } }
471
460
<reponame>MANICX100/peerblock // (C) Copyright <NAME> 2005. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_IS_MEMBER_OBJECT_POINTER_HPP_INCLUDED #define BOOST_TT_IS_MEMBER_OBJECT_POINTER_HPP_INCLUDED #include <boost/type_traits/config.hpp> #include <boost/type_traits/is_member_pointer.hpp> #include <boost/type_traits/is_member_function_pointer.hpp> #include <boost/type_traits/detail/ice_and.hpp> #include <boost/type_traits/detail/ice_not.hpp> // should be the last #include #include <boost/type_traits/detail/bool_trait_def.hpp> namespace boost { namespace detail{ template <typename T> struct is_member_object_pointer_impl { BOOST_STATIC_CONSTANT( bool, value = (::boost::type_traits::ice_and< ::boost::is_member_pointer<T>::value, ::boost::type_traits::ice_not< ::boost::is_member_function_pointer<T>::value >::value >::value )); }; } // namespace detail BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_member_object_pointer,T,::boost::detail::is_member_object_pointer_impl<T>::value) } // namespace boost #include <boost/type_traits/detail/bool_trait_undef.hpp> #endif // BOOST_TT_IS_MEMBER_FUNCTION_POINTER_HPP_INCLUDED
632
390
<gh_stars>100-1000 // // TGTopicNewM.h // baisibudejie // // Created by targetcloud on 2017/5/30. // Copyright © 2017年 targetcloud. All rights reserved. // #import <Foundation/Foundation.h> @class TGUserNewM; @class TGCommentNewM; @interface TGTopicNewM : NSObject @property (nonatomic, copy) NSString *ID; @property (nonatomic, copy) NSString *type;//audio image video gif text @property (nonatomic, assign) NSInteger status; @property (nonatomic, assign) NSInteger up; @property (nonatomic, assign) NSInteger down; @property (nonatomic, assign) NSInteger forward; @property (nonatomic, assign) NSInteger comment; @property (nonatomic, copy) NSString *share_url; @property (nonatomic, copy) NSString *passtime; @property (nonatomic, assign) NSInteger bookmark; @property (nonatomic, copy) NSString *text; @property (nonatomic, strong) TGUserNewM *u; @property (nonatomic, assign) NSInteger video_playfcount; @property (nonatomic, assign) NSInteger video_width; @property (nonatomic, assign) NSInteger video_height; @property (nonatomic, copy) NSString *video_uri; @property (nonatomic, assign) NSInteger video_duration; @property (nonatomic, assign) NSInteger video_playcount; @property (nonatomic, copy) NSString * video_thumbnail; @property (nonatomic, copy) NSString * video_thumbnail_small; @property (nonatomic, strong) NSArray<TGCommentNewM *> *top_comments; @property (nonatomic, copy) NSString * image_medium; @property (nonatomic, copy) NSString * image_big; @property (nonatomic, assign) NSInteger image_height; @property (nonatomic, assign) NSInteger image_width; @property (nonatomic, copy) NSString * image_small; @property (nonatomic, copy) NSString * image_thumbnail_small; @property (nonatomic, copy) NSString * images_gif; @property (nonatomic, assign) NSInteger gif_width; @property (nonatomic, copy) NSString * gif_thumbnail; @property (nonatomic, assign) NSInteger gif_height; @property (nonatomic, assign) NSInteger audio_playfcount; @property (nonatomic, assign) NSInteger audio_height; @property (nonatomic, assign) NSInteger audio_width; @property (nonatomic, assign) NSInteger audio_duration; @property (nonatomic, assign) NSInteger audio_playcount; @property (nonatomic, copy) NSString * audio_uri; @property (nonatomic, copy) NSString * audio_thumbnail; @property (nonatomic, copy) NSString * audio_thumbnail_small; @property (nonatomic, assign,readonly) NSInteger width; @property (nonatomic, assign,readonly) NSInteger height; @property (nonatomic, copy,readonly) NSString * image; @property (nonatomic, assign,readonly) CGFloat cellHeight; @property (nonatomic, assign,readonly) CGFloat middleY;//用于收缩展开 @property (nonatomic, assign,readonly) CGFloat defaultHeight;//用于收缩展开 @property (nonatomic, assign,readonly) CGFloat textHeight;//用于收缩展开 @property (nonatomic, assign) CGRect middleFrame; @property (nonatomic, assign, getter=isBigPicture) BOOL bigPicture; @property (nonatomic, assign, getter=isShowAllWithoutComment) BOOL showAllWithoutComment;//用于评论VC @property (nonatomic, assign,readonly) CGFloat cellHeightWithoutComment;//用于评论VC @property (nonatomic, assign) CGFloat picProgress; @property (nonatomic, assign,getter=is_voicePlaying) BOOL voicePlaying; @property (nonatomic, assign,getter=is_videoPlaying) BOOL videoPlaying; @property (nonatomic, assign,readonly) CGFloat commentVH; @property (nonatomic, copy,readonly) NSMutableAttributedString * attrStrM; @property (nonatomic, assign, getter=isUpSelected) BOOL upSelected; @property (nonatomic, assign, getter=isDownSelected) BOOL downSelected; @property (nonatomic, assign, getter=isLikeSelected) BOOL likeSelected; @property (nonatomic, assign, getter=isAnimated) BOOL animated; @end
1,204
372
<filename>bnsf/src/main/java/io/fastjson/bnsf/holders/basic/DecimalHolder.java package io.fastjson.bnsf.holders.basic; import io.fastjson.bnsf.WireValueType; import io.fastjson.bnsf.holders.WireValueHolder; import java.math.BigDecimal; /** * Created by Richard on 9/25/14. */ public class DecimalHolder extends Number implements WireValueHolder { private BigDecimal value; @Override public int intValue() { return value.intValue(); } @Override public long longValue() { return value.longValue(); } @Override public float floatValue() { return value.floatValue(); } @Override public double doubleValue() { return value.doubleValue(); } @Override public WireValueType type() { return WireValueType.DECIMAL; } public BigDecimal getValue() { return value; } public void setValue(BigDecimal value) { this.value = value; } }
378
782
<filename>main/boofcv-ip/src/main/java/boofcv/alg/filter/derivative/impl/HessianThreeDeterminant_Border.java /* * Copyright (c) 2011-2019, <NAME>. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.filter.derivative.impl; import boofcv.struct.border.ImageBorder_F32; import boofcv.struct.border.ImageBorder_S32; import boofcv.struct.image.GrayF32; import boofcv.struct.image.GrayS16; import boofcv.struct.image.GrayU8; /** * Hessian-Three derivative which processes the outer image border only * * @see boofcv.alg.filter.derivative.HessianThreeDeterminant * * @author <NAME> */ public class HessianThreeDeterminant_Border { public static void process(GrayU8 input, GrayS16 output, ImageBorder_S32<GrayU8> border ) { border.setImage(input); final byte[] src = input.data; final short[] dst = output.data; final int width = input.getWidth(); final int height = input.getHeight(); final int stride = input.stride; for (int y = 0; y < 2; y++) { int idxSrc = input.startIndex + stride * y; int idxDst = output.startIndex + stride * y; for (int x = 0; x < width; x++, idxSrc++) { int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst++] = (short)(Lxx*Lyy-Lxy*Lxy); } } for (int y = height-2; y < height; y++) { int idxSrc = input.startIndex + stride * y; int idxDst = output.startIndex + stride * y; for (int x = 0; x < width; x++, idxSrc++) { int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst++] = (short)(Lxx*Lyy-Lxy*Lxy); } } for (int y = 2; y < height-2; y++) { for (int x = 0; x < 2; x++) { int idxSrc = input.startIndex + stride * y+x; int idxDst = output.startIndex + stride * y+x; int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst] = (short)(Lxx*Lyy-Lxy*Lxy); } for (int x = width-2; x < width; x++) { int idxSrc = input.startIndex + stride * y+x; int idxDst = output.startIndex + stride * y+x; int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst] = (short)(Lxx*Lyy-Lxy*Lxy); } } } public static void process(GrayU8 input, GrayF32 output, ImageBorder_S32<GrayU8> border) { border.setImage(input); final byte[] src = input.data; final float[] dst = output.data; final int width = input.getWidth(); final int height = input.getHeight(); final int stride = input.stride; for (int y = 0; y < 2; y++) { int idxSrc = input.startIndex + stride * y; int idxDst = output.startIndex + stride * y; for (int x = 0; x < width; x++, idxSrc++) { int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst++] = Lxx*Lyy-Lxy*Lxy; } } for (int y = height-2; y < height; y++) { int idxSrc = input.startIndex + stride * y; int idxDst = output.startIndex + stride * y; for (int x = 0; x < width; x++, idxSrc++) { int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst++] = Lxx*Lyy-Lxy*Lxy; } } for (int y = 2; y < height-2; y++) { for (int x = 0; x < 2; x++) { int idxSrc = input.startIndex + stride * y+x; int idxDst = output.startIndex + stride * y+x; int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst] = Lxx*Lyy-Lxy*Lxy; } for (int x = width-2; x < width; x++) { int idxSrc = input.startIndex + stride * y+x; int idxDst = output.startIndex + stride * y+x; int center = src[idxSrc]&0xFF; int Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); int Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); int Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst] = Lxx*Lyy-Lxy*Lxy; } } } public static void process(GrayF32 input, GrayF32 output, ImageBorder_F32 border) { border.setImage(input); final float[] src = input.data; final float[] dst = output.data; final int width = input.getWidth(); final int height = input.getHeight(); final int stride = input.stride; for (int y = 0; y < 2; y++) { int idxSrc = input.startIndex + stride * y; int idxDst = output.startIndex + stride * y; for (int x = 0; x < width; x++, idxSrc++) { float center = src[idxSrc]; float Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); float Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); float Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst++] = Lxx*Lyy-Lxy*Lxy; } } for (int y = height-2; y < height; y++) { int idxSrc = input.startIndex + stride * y; int idxDst = output.startIndex + stride * y; for (int x = 0; x < width; x++, idxSrc++) { float center = src[idxSrc]; float Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); float Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); float Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst++] = Lxx*Lyy-Lxy*Lxy; } } for (int y = 2; y < height-2; y++) { for (int x = 0; x < 2; x++) { int idxSrc = input.startIndex + stride * y+x; int idxDst = output.startIndex + stride * y+x; float center = src[idxSrc]; float Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); float Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); float Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst] = Lxx*Lyy-Lxy*Lxy; } for (int x = width-2; x < width; x++) { int idxSrc = input.startIndex + stride * y+x; int idxDst = output.startIndex + stride * y+x; float center = src[idxSrc]; float Lxx = border.get(x-2,y) - 2*center + border.get(x+2,y); float Lyy = border.get(x,y-2) - 2*center + border.get(x,y+2); float Lxy = border.get(x-1,y-1) + border.get(x+1,y+1); Lxy -= border.get(x+1,y-1) + border.get(x-1,y+1); dst[idxDst] = Lxx*Lyy-Lxy*Lxy; } } } }
3,869
1,510
/* * 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.drill.exec.record.metadata.schema; import org.apache.drill.exec.planner.sql.handlers.SchemaHandler; import org.apache.drill.exec.planner.sql.parser.SqlSchema; import org.apache.drill.exec.store.dfs.WorkspaceSchemaFactory; import org.apache.hadoop.fs.Path; import java.io.IOException; /** * Factory class responsible for creating different instances of schema provider based on given parameters. */ public class SchemaProviderFactory { /** * Creates schema provider for sql schema commands. * * @param sqlSchema sql schema call * @param schemaHandler schema handler * @return schema provider instance * @throws IOException if unable to init schema provider */ public static SchemaProvider create(SqlSchema sqlSchema, SchemaHandler schemaHandler) throws IOException { if (sqlSchema.hasTable()) { String tableName = sqlSchema.getTableName(); WorkspaceSchemaFactory.WorkspaceSchema wsSchema = schemaHandler.getWorkspaceSchema(sqlSchema.getSchemaPath(), tableName); return new FsMetastoreSchemaProvider(wsSchema, tableName); } else { return new PathSchemaProvider(new Path(sqlSchema.getPath())); } } /** * Creates schema provider based table function schema parameter. * * @param parameterValue schema parameter value * @return schema provider instance * @throws IOException if unable to init schema provider */ public static SchemaProvider create(String parameterValue) throws IOException { String[] split = parameterValue.split("=", 2); if (split.length < 2) { throw new IOException("Incorrect parameter value format: " + parameterValue); } ProviderType providerType = ProviderType.valueOf(split[0].trim().toUpperCase()); String value = split[1].trim(); switch (providerType) { case INLINE: return new InlineSchemaProvider(value); case PATH: char c = value.charAt(0); // if path starts with any type of quotes, strip them if (c == '\'' || c == '"' || c == '`') { value = value.substring(1, value.length() - 1); } return new PathSchemaProvider(new Path(value)); default: throw new IOException("Unexpected provider type: " + providerType); } } /** * Indicates provider type will be used to provide schema. */ private enum ProviderType { INLINE, PATH } }
995
1,062
// // Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57). // // Copyright (C) 1997-2019 <NAME>. // #import "NSObject-Protocol.h" @class CALayer, NSView, StackController; @protocol StackDataSource <NSObject> @property(readonly, nonatomic) NSView *stackContainerView; - (void)stackController:(StackController *)arg1 loadDataForItem:(id)arg2 inLayer:(CALayer *)arg3; - (BOOL)stackController:(StackController *)arg1 isDataLoadedForItem:(id)arg2 inLayer:(CALayer *)arg3; - (CALayer *)stackController:(StackController *)arg1 layerForItem:(id)arg2; - (CALayer *)stackContainerLayerForStackController:(StackController *)arg1; @end
223
748
<reponame>MattJDavidson/aoc2021<gh_stars>100-1000 def euler_walk(n, adj): deg = [0] * n for i in range(n): for j in range(n): deg[i] += adj[i][j] first = 0 while deg[first] == 0: first += 1 v1, v2 = -1, -1 bad = False for i in range(n): if deg[i] % 2 == 1: if v1 == -1: v1 = i elif v2 == -1: v2 = i else: bad = True if v1 != -1: adj[v1][v2] += 1 adj[v2][v1] += 1 st, res = [first], [] while st: v = st[-1] flag = False for i in range(n): if adj[v][i]: flag = True break if flag: adj[v][i] -= 1 adj[i][v] -= 1 st.append(i) else: res.append(v) st.pop() if v1 != -1: for i in range(len(res) - 1): if ((res[i] == v1) and (res[i + 1] == v2)) or ((res[i] == v2) and (res[i + 1] == v1)): res = [res[j] for j in range(i + 1, len(res))] + [res[j] for j in range(1, i + 1)] break for i in range(n): for j in range(n): if adj[i][j]: bad = True if bad: return None return res
808
8,360
<reponame>AK391/PaddleHub # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from pathlib import Path import sys import numpy as np from paddlehub.env import MODULE_HOME from paddlehub.module.module import moduleinfo, serving from paddlehub.utils.log import logger from paddle.utils.download import get_path_from_url try: import swig_decoders except ModuleNotFoundError as e: logger.error(e) logger.info('The module requires additional dependencies: swig_decoders. ' 'please install via:\n\'git clone https://github.com/PaddlePaddle/DeepSpeech.git ' '&& cd DeepSpeech && git reset --hard b53171694e7b87abe7ea96870b2f4d8e0e2b1485 ' '&& cd deepspeech/decoders/ctcdecoder/swig && sh setup.sh\'') sys.exit(1) import paddle import soundfile as sf # TODO: Remove system path when deepspeech can be installed via pip. sys.path.append(os.path.join(MODULE_HOME, 'deepspeech2_librispeech')) from deepspeech.exps.deepspeech2.config import get_cfg_defaults from deepspeech.utils.utility import UpdateConfig from .deepspeech_tester import DeepSpeech2Tester LM_URL = 'https://deepspeech.bj.bcebos.com/en_lm/common_crawl_00.prune01111.trie.klm' LM_MD5 = '099a601759d467cd0a8523ff939819c5' @moduleinfo( name="deepspeech2_librispeech", version="1.0.0", summary="", author="Baidu", author_email="", type="audio/asr") class DeepSpeech2(paddle.nn.Layer): def __init__(self): super(DeepSpeech2, self).__init__() # resource res_dir = os.path.join(MODULE_HOME, 'deepspeech2_librispeech', 'assets') conf_file = os.path.join(res_dir, 'conf/deepspeech2.yaml') checkpoint = os.path.join(res_dir, 'checkpoints/avg_1.pdparams') # Download LM manually cause its large size. lm_path = os.path.join(res_dir, 'data', 'lm') lm_file = os.path.join(lm_path, LM_URL.split('/')[-1]) if not os.path.isfile(lm_file): logger.info(f'Downloading lm from {LM_URL}.') get_path_from_url(url=LM_URL, root_dir=lm_path, md5sum=LM_MD5) # config self.model_type = 'offline' self.config = get_cfg_defaults(self.model_type) self.config.merge_from_file(conf_file) # TODO: Remove path updating snippet. with UpdateConfig(self.config): self.config.collator.mean_std_filepath = os.path.join(res_dir, self.config.collator.mean_std_filepath) self.config.collator.vocab_filepath = os.path.join(res_dir, self.config.collator.vocab_filepath) self.config.collator.augmentation_config = os.path.join(res_dir, self.config.collator.augmentation_config) self.config.decoding.lang_model_path = os.path.join(res_dir, self.config.decoding.lang_model_path) # model self.tester = DeepSpeech2Tester(self.config) self.tester.setup_model() self.tester.resume(checkpoint) @staticmethod def check_audio(audio_file): sig, sample_rate = sf.read(audio_file) assert sample_rate == 16000, 'Excepting sample rate of input audio is 16000, but got {}'.format(sample_rate) @serving def speech_recognize(self, audio_file, device='cpu'): assert os.path.isfile(audio_file), 'File not exists: {}'.format(audio_file) self.check_audio(audio_file) paddle.set_device(device) return self.tester.test(audio_file)[0]
1,572
348
{"nom":"Saint-Ouen-Marchefroy","circ":"2ème circonscription","dpt":"Eure-et-Loir","inscrits":253,"abs":116,"votants":137,"blancs":2,"nuls":0,"exp":135,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":71},{"nuance":"LR","nom":"M. <NAME>","voix":64}]}
104
531
<reponame>samypr100/jfxtras /** * Copyright (c) 2011-2021, JFXtras * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL JFXTRAS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jfxtras.icalendarfx.components; import jfxtras.icalendarfx.VParent; import jfxtras.icalendarfx.VParentBase; import jfxtras.icalendarfx.components.VComponent; import jfxtras.icalendarfx.components.VComponentBase; import jfxtras.icalendarfx.components.VComponentElement; import jfxtras.icalendarfx.content.MultiLineContent;; /** * <p>Base class implementation of a {@link VComponent}</p> * * @author <NAME> */ public abstract class VComponentBase<T> extends VParentBase<T> implements VComponent { protected VParent parent; @Override public void setParent(VParent parent) { this.parent = parent; } @Override public VParent getParent() { return parent; } final private VComponentElement componentType; @Override public String name() { return componentType.toString(); } /* * CONSTRUCTORS */ /** * Create default component by setting {@link componentName}, and setting content line generator. */ VComponentBase() { super(); componentType = VComponentElement.fromClass(this.getClass()); contentLineGenerator = new MultiLineContent( orderer, BEGIN + name(), END + name(), 400); } /** * Creates a deep copy of a component */ VComponentBase(VComponentBase<T> source) { super(source); componentType = VComponentElement.fromClass(this.getClass()); contentLineGenerator = new MultiLineContent( orderer, BEGIN + name(), END + name(), 400); setParent(source.getParent()); } /** * Hook to add subcomponent such as {@link #VAlarm}, {@link #StandardTime} and {@link #DaylightSavingTime} * * @param subcomponent */ void addSubcomponent(VComponent subcomponent) { // no opp by default } @Override protected boolean isContentValid(String valueContent) { boolean isElementValid = super.isContentValid(valueContent); if (! isElementValid) return false; boolean isBeginPresent = valueContent.startsWith(BEGIN + name()); if (! isBeginPresent) return false; int lastLineIndex = valueContent.lastIndexOf(System.lineSeparator()); if (lastLineIndex == -1) return false; boolean isEndPresent = valueContent .substring(lastLineIndex) .startsWith(END + name()); return ! isEndPresent; } // /** // * Creates a new VComponent by parsing a String of iCalendar content text // * @param <T> // * // * @param content the text to parse, not null // * @return the parsed DaylightSavingTime // */ // public static <T extends VComponentBase<?>> T parse(String content) // { // boolean isMultiLineElement = content.startsWith("BEGIN"); // if (! isMultiLineElement) // { // throw new IllegalArgumentException("VComponent must begin with BEGIN [" + content + "]"); // } // int firstLineBreakIndex = content.indexOf(System.lineSeparator()); // String name = content.substring(6,firstLineBreakIndex); // T component = (T) Elements.newEmptyVElement(VComponent.class, name); // List<Message> messages = component.parseContent(content); // throwMessageExceptions(messages); // return component; // } }
1,741
345
#include "pch.h" #include "App_Feature_EffectApplicationDelayLogger.h" #include "App_ConfigRepository.h" #include "App_Misc_Logger.h" #include "App_Network_SocketHook.h" #include "App_Network_Structures.h" struct App::Feature::EffectApplicationDelayLogger::Implementation { class SingleConnectionHandler { const std::shared_ptr<Config> m_config; public: Implementation* m_pImpl; Network::SingleConnection& conn; SingleConnectionHandler(Implementation* pImpl, Network::SingleConnection& conn) : m_config(Config::Acquire()) , m_pImpl(pImpl) , conn(conn) { using namespace Network::Structures; const auto& config = m_config->Game; conn.AddIncomingFFXIVMessageHandler(this, [&](auto pMessage) { if (pMessage->Type == MessageType::Ipc && pMessage->Data.Ipc.Type == IpcType::InterestedType) { if (config.S2C_ActionEffects[0] == pMessage->Data.Ipc.SubType || config.S2C_ActionEffects[1] == pMessage->Data.Ipc.SubType || config.S2C_ActionEffects[2] == pMessage->Data.Ipc.SubType || config.S2C_ActionEffects[3] == pMessage->Data.Ipc.SubType || config.S2C_ActionEffects[4] == pMessage->Data.Ipc.SubType) { const auto& actionEffect = pMessage->Data.Ipc.Data.S2C_ActionEffect; m_pImpl->m_logger->Format( LogCategory::EffectApplicationDelayLogger, "{:x}: S2C_ActionEffect({:04x}): actionId={:04x} sourceSequence={:04x} wait={}ms", conn.Socket(), pMessage->Data.Ipc.SubType, actionEffect.ActionId, actionEffect.SourceSequence, static_cast<int>(1000 * actionEffect.AnimationLockDuration)); } else if (pMessage->Data.Ipc.SubType == config.S2C_EffectResult5) { const auto& effectResult = pMessage->Data.Ipc.Data.S2C_EffectResult5; std::string effects; for (int i = 0; i < effectResult.EffectCount; ++i) { const auto& entry = effectResult.Effects[i]; effects += std::format( "\n\teffectId={:04x} duration={:.3f} sourceActorId={:08x}", entry.EffectId, entry.Duration, entry.SourceActorId ); } m_pImpl->m_logger->Format( LogCategory::EffectApplicationDelayLogger, "{:x}: S2C_EffectResult5: relatedActionSequence={:08x} actorId={:08x} HP={}/{} MP={} shield={}{}", conn.Socket(), effectResult.RelatedActionSequence, effectResult.ActorId, effectResult.CurrentHp, effectResult.MaxHp, effectResult.CurentMp, effectResult.DamageShield, effects ); } else if (pMessage->Data.Ipc.SubType == config.S2C_EffectResult6) { const auto& effectResult = pMessage->Data.Ipc.Data.S2C_EffectResult6; std::string effects; for (int i = 0; i < effectResult.EffectCount; ++i) { const auto& entry = effectResult.Effects[i]; effects += std::format( "\n\teffectId={:04x} duration={:.3f} sourceActorId={:08x}", entry.EffectId, entry.Duration, entry.SourceActorId ); } m_pImpl->m_logger->Format( LogCategory::EffectApplicationDelayLogger, "{:x}: S2C_EffectResult6: relatedActionSequence={:08x} actorId={:08x} HP={}/{} MP={} shield={}{}", conn.Socket(), effectResult.RelatedActionSequence, effectResult.ActorId, effectResult.CurrentHp, effectResult.MaxHp, effectResult.CurentMp, effectResult.DamageShield, effects ); } else if (pMessage->Data.Ipc.SubType == config.S2C_EffectResult6Basic) { const auto& effectResult = pMessage->Data.Ipc.Data.S2C_EffectResult6Basic; m_pImpl->m_logger->Format( LogCategory::EffectApplicationDelayLogger, "{:x}: S2C_EffectResult6Basic: relatedActionSequence={:08x} actorId={:08x} HP={}", conn.Socket(), effectResult.RelatedActionSequence, effectResult.ActorId, effectResult.CurrentHp ); } } return true; }); } ~SingleConnectionHandler() { conn.RemoveMessageHandlers(this); } }; const std::shared_ptr<Misc::Logger> m_logger; Network::SocketHook* const m_socketHook; std::map<Network::SingleConnection*, std::unique_ptr<SingleConnectionHandler>> m_handlers{}; Utils::CallOnDestruction::Multiple m_cleanup; Implementation(Network::SocketHook* socketHook) : m_logger(Misc::Logger::Acquire()) , m_socketHook(socketHook) { m_cleanup += m_socketHook->OnSocketFound([&](Network::SingleConnection& conn) { m_handlers.emplace(&conn, std::make_unique<SingleConnectionHandler>(this, conn)); }); m_cleanup += m_socketHook->OnSocketGone([&](Network::SingleConnection& conn) { m_handlers.erase(&conn); }); } ~Implementation() { m_handlers.clear(); } }; App::Feature::EffectApplicationDelayLogger::EffectApplicationDelayLogger(Network::SocketHook* socketHook) : m_pImpl(std::make_unique<Implementation>(socketHook)) { } App::Feature::EffectApplicationDelayLogger::~EffectApplicationDelayLogger() = default;
2,112
15,577
<filename>src/AggregateFunctions/QuantileReservoirSampler.h #pragma once #include <AggregateFunctions/ReservoirSampler.h> namespace DB { struct Settings; namespace ErrorCodes { extern const int NOT_IMPLEMENTED; } /** Quantile calculation with "reservoir sample" algorithm. * It collects pseudorandom subset of limited size from a stream of values, * and approximate quantile from it. * The result is non-deterministic. Also look at QuantileReservoirSamplerDeterministic. * * This algorithm is quite inefficient in terms of precision for memory usage, * but very efficient in CPU (though less efficient than QuantileTiming and than QuantileExact for small sets). */ template <typename Value> struct QuantileReservoirSampler { using Data = ReservoirSampler<Value, ReservoirSamplerOnEmpty::RETURN_NAN_OR_ZERO>; Data data; void add(const Value & x) { data.insert(x); } template <typename Weight> void add(const Value &, const Weight &) { throw Exception("Method add with weight is not implemented for ReservoirSampler", ErrorCodes::NOT_IMPLEMENTED); } void merge(const QuantileReservoirSampler & rhs) { data.merge(rhs.data); } void serialize(WriteBuffer & buf) const { data.write(buf); } void deserialize(ReadBuffer & buf) { data.read(buf); } /// Get the value of the `level` quantile. The level must be between 0 and 1. Value get(Float64 level) { return Value(data.quantileInterpolated(level)); } /// Get the `size` values of `levels` quantiles. Write `size` results starting with `result` address. /// indices - an array of index levels such that the corresponding elements will go in ascending order. void getMany(const Float64 * levels, const size_t * indices, size_t size, Value * result) { for (size_t i = 0; i < size; ++i) result[indices[i]] = Value(data.quantileInterpolated(levels[indices[i]])); } /// The same, but in the case of an empty state, NaN is returned. Float64 getFloat(Float64 level) { return data.quantileInterpolated(level); } void getManyFloat(const Float64 * levels, const size_t * indices, size_t size, Float64 * result) { for (size_t i = 0; i < size; ++i) result[indices[i]] = data.quantileInterpolated(levels[indices[i]]); } }; }
883
1,945
static GtkActionable *toGtkActionable(void *p) { return (GTK_ACTIONABLE(p)); }
29
348
{"nom":"<NAME>","circ":"4ème circonscription","dpt":"Ille-et-Vilaine","inscrits":389,"abs":234,"votants":155,"blancs":9,"nuls":5,"exp":141,"res":[{"nuance":"REM","nom":"<NAME>","voix":88},{"nuance":"FI","nom":"<NAME>","voix":53}]}
94
395
package timely.auth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import timely.netty.http.auth.TimelyUserDetails; public class UserDetailsService implements org.springframework.security.core.userdetails.AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> { private HashMap<String, TimelyUser> users; public Map<String, TimelyUser> getUsers() { return users; } public void setUsers(List<TimelyUser> users) { this.users = new HashMap<>(); users.forEach(u -> this.users.put(u.getName(), u)); } @Override public UserDetails loadUserDetails(final PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException { // Determine if the user is allowed to access the system, if not throw // UsernameNotFoundException String username = token.getName(); if (!users.containsKey(username)) { throw new UsernameNotFoundException(username + " not configured."); } // If allowed, populate the user details object with the authorities for // the user. return new TimelyUserDetails() { private static final long serialVersionUID = 1L; @Override public Collection<SimpleGrantedAuthority> getAuthorities() { final Collection<SimpleGrantedAuthority> auths = new ArrayList<>(); users.get(username).getAuths().forEach(a -> { auths.add(new SimpleGrantedAuthority(a)); }); return auths; } @Override public Collection<String> getRoles() { final Collection<String> roles = new ArrayList<>(); roles.addAll(users.get(username).getRoles()); return roles; } @Override public String getPassword() { return ""; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }; } }
1,259
560
<gh_stars>100-1000 /* * Copyright (c) 2018 <NAME> <<EMAIL>> * All Rights Reserved. */ package me.zhanghai.android.douya.reflected; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class ReflectedClass { @NonNull private final String mClassName; @Nullable private Class<?> mClass; @NonNull private final Object mClassLock = new Object(); public ReflectedClass(@NonNull String className) { mClassName = className; } @NonNull public Class get() throws ReflectedException { synchronized (mClassLock) { if (mClass == null) { mClass = ReflectedAccessor.getClass(mClassName); } return mClass; } } }
307
335
<reponame>Safal08/Hacktoberfest-1<gh_stars>100-1000 { "word": "Suppurate", "definitions": [ "undergo the formation of pus; fester", "to form or discharge pus" ], "parts-of-speech": "Verb" }
102
736
#pragma once namespace FSecure::Loader { /// Calculate VA from base address and RVA /// @tparam T - type of return value /// @param baseAddress /// @param RVA /// @returns VA template<typename T, typename V, typename U> T Rva2Va(V baseAddress, U rva) { return reinterpret_cast<T>(reinterpret_cast<ULONG_PTR&>(baseAddress) + rva); } /// Get DOS header from dll base address /// @param base address of dll /// @returns DOS header of dll PIMAGE_DOS_HEADER GetDosHeader(UINT_PTR baseAddress); /// Get NT headers from dll base address /// @param base address of dll /// @returns NT headers of dll PIMAGE_NT_HEADERS GetNtHeaders(UINT_PTR baseAddress); /// Get size of image from NT headers /// @param baseAddress - base address of PE file image /// @returns size of image specified image DWORD GetSizeOfImage(UINT_PTR baseAddress); /// Get memory range of dll section /// @param dllbase - base address of dll /// @param section name - name of section to find /// @returns pair of pointers - memory range of section std::pair<void*, void*> GetSectionRange(void* dllBase, std::string const& sectionName); /// Align value up /// @param value to align /// @param alignment required, must be a power of 2 /// @returns value aligned to requirement static inline size_t AlignValueUp(size_t value, size_t alignment) { return (value + alignment - 1) & ~(alignment - 1); } }
461
5,169
<reponame>Gantios/Specs<filename>Specs/a/9/2/ARLogging/1.4.1/ARLogging.podspec.json { "name": "ARLogging", "version": "1.4.1", "summary": "A short description of ARLogging.", "platforms": { "ios": "11.0" }, "description": "TODO: Add long description of the pod here.", "homepage": "https://github.com/pioneersquarelabs/ARMetricsFramework", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/pioneersquarelabs/ARMetricsFramework.git", "tag": "1.4.1" }, "pod_target_xcconfig": { "SWIFT_INCLUDE_PATHS": "$(SRCROOT)/ARLogging/ARLogging/Classes/minizip/**", "LIBRARY_SEARCH_PATHS": "$(SRCROOT)/ARLogging/ARLogging/Classes/" }, "source_files": [ "ARLogging/Classes/**/*", "ARLogging/Classes/*.{swift,h}", "ARLogging/Classes/minizip/*.{c,h}", "ARLogging/Classes/minizip/zip.h", "ARLogging/Classes/minizip/zip.c", "ARLogging/Classes/minizip/unzip.h", "ARLogging/Classes/minizip/unzip.c", "ARLogging/Classes/minizip/aes/*.{c,h}" ], "requires_arc": true, "preserve_paths": "ARLogging/Classes/minizip/module.modulemap", "pushed_with_swift_version": "3.2" }
547
348
{"nom":"Saint-Georges-Antignac","circ":"4ème circonscription","dpt":"Charente-Maritime","inscrits":299,"abs":157,"votants":142,"blancs":4,"nuls":9,"exp":129,"res":[{"nuance":"REM","nom":"<NAME>","voix":66},{"nuance":"LR","nom":"<NAME>","voix":63}]}
97
3,227
<reponame>ffteja/cgal #include <iostream> #include <CGAL/config.h> #include <CGAL/use.h> #include <CGAL/Arithmetic_kernel.h> #include <CGAL/Quotient.h> #include <CGAL/Test/_test_algebraic_structure.h> #include <CGAL/Test/_test_real_embeddable.h> #include <CGAL/Test/_test_fraction_traits.h> #include <CGAL/Test/_test_rational_traits.h> template< class AT > void test_quotient() { { typedef CGAL::Quotient< typename AT::Integer > NT; typedef CGAL::Field_tag Tag; typedef CGAL::Tag_true Is_exact; CGAL::test_algebraic_structure<NT,Tag, Is_exact>(); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(-6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(-6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(6),NT(-15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(6), NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(-6),NT(-15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(-6),NT(-15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>( NT(5,74), NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(-NT(5,74), NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>( NT(5,74),-NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(-NT(5,74),-NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>( NT(5,74), NT(3,25),-NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(-NT(5,74), NT(3,25),-NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>( NT(5,74),-NT(3,25),-NT(7,3)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(-NT(5,74),-NT(3,25),-NT(7,3)); CGAL::test_real_embeddable<NT>(); CGAL::test_fraction_traits<NT>(); // backward compatiblity CGAL::test_rational_traits<NT>(); } /* // Quotient for inexact types not implemented { typedef CGAL::Quotient< leda_bigfloat > NT; typedef CGAL::Field_with_sqrt_tag Tag; CGAL::test_algebraic_structure<NT,Tag>(); CGAL::test_algebraic_structure<NT,Tag>( NT(5,74), NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>(-NT(5,74), NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>( NT(5,74),-NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>(-NT(5,74),-NT(3,25), NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>( NT(5,74), NT(3,25),-NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>(-NT(5,74), NT(3,25),-NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>( NT(5,74),-NT(3,25),-NT(7,3)); CGAL::test_algebraic_structure<NT,Tag>(-NT(5,74),-NT(3,25),-NT(7,3)); CGAL::test_real_embeddable<NT>(); } */ { // see also Coercion_traits_test.C typedef typename AT::Integer I ; typedef CGAL::Quotient<typename AT::Integer> QI; typedef CGAL::Coercion_traits<I,QI> CT; CGAL_USE_TYPE(CT); CGAL_static_assertion((boost::is_same< typename CT::Are_explicit_interoperable,CGAL::Tag_true>::value)); CGAL_static_assertion((boost::is_same< typename CT::Are_implicit_interoperable,CGAL::Tag_true>::value)); CGAL_static_assertion((boost::is_same< typename CT::Type,QI>::value)); } } int main() { #ifdef CGAL_HAS_LEDA_ARITHMETIC_KERNEL test_quotient<CGAL::LEDA_arithmetic_kernel>(); #endif #ifdef CGAL_HAS_CORE_ARITHMETIC_KERNEL test_quotient<CGAL::CORE_arithmetic_kernel>(); #endif #ifdef CGAL_HAS_GMP_ARITHMETIC_KERNEL test_quotient<CGAL::GMP_arithmetic_kernel>(); #endif return 0; }
1,791
799
{ "defaultIncidentType": "G Suite Security Alert Center", "description": "Classifies G Suite Security Alert Center Incidents.", "feed": false, "id": "G Suite Security Alert Center - Classifier", "keyTypeMap": { "type.googleapis.com/google.apps.alertcenter.type.AccountWarning": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.ActivityRule": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.AppMakerSqlSetupNotification": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.BadWhitelist": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.DeviceCompromised": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.DlpRuleViolation": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.DomainWideTakeoutInitiated": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.GoogleOperations": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.MailPhishing": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.StateSponsoredAttack": "G Suite Security Alert Center", "type.googleapis.com/google.apps.alertcenter.type.SuspiciousActivity": "G Suite Security Alert Center" }, "name": "G Suite Security Alert Center - Classifier", "propagationLabels": [ "all" ], "transformer": { "complex": { "accessor": "", "filters": [ [ { "ignoreCase": false, "left": { "isContext": true, "value": { "complex": null, "simple": "data.@type" } }, "operator": "containsGeneral", "right": { "isContext": false, "value": { "complex": null, "simple": "google.apps.alertcenter" } } } ] ], "root": "data.@type", "transformers": [ ] }, "simple": "" }, "type": "classification", "version": -1, "fromVersion": "6.0.0" }
1,316
3,227
<reponame>ffteja/cgal #include<CGAL/Exact_predicates_inexact_constructions_kernel.h> #include<CGAL/Polygon_2.h> #include<CGAL/create_offset_polygons_2.h> #include<CGAL/draw_straight_skeleton_2.h> #include <boost/shared_ptr.hpp> #include <iostream> #include <vector> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef K::Point_2 Point; typedef CGAL::Polygon_2<K> Polygon_2; typedef boost::shared_ptr<Polygon_2> PolygonPtr; void low_precision_run() { Polygon_2 poly; poly.push_back(Point(3.4641, 16.9915)); poly.push_back(Point(3.4641, 15.4955)); poly.push_back(Point(3.4641, 13.0989)); poly.push_back(Point(3.4641, 9.94113)); poly.push_back(Point(3.4641, 6.20559)); poly.push_back(Point(3.4641, 2.10939)); poly.push_back(Point(3.4641, -2.10939)); poly.push_back(Point(3.4641, -6.20559)); poly.push_back(Point(3.4641, -9.94113)); poly.push_back(Point(3.4641, -13.0989)); poly.push_back(Point(3.4641, -15.4955)); poly.push_back(Point(3.4641, -16.9915)); poly.push_back(Point(3.4641, -17.5)); poly.push_back(Point(-6.52835e-17, -19.5)); poly.push_back(Point(-6.33865e-17, -18.9334)); poly.push_back(Point(-5.78057e-17, -17.2664)); poly.push_back(Point(-4.88654e-17, -14.596)); poly.push_back(Point(-3.70853e-17, -11.0773)); poly.push_back(Point(-2.31499e-17, -6.9148)); poly.push_back(Point(-7.86906e-18, -2.35047)); poly.push_back(Point(7.86906e-18, 2.35047)); poly.push_back(Point(2.31499e-17, 6.9148)); poly.push_back(Point(3.70853e-17, 11.0773)); poly.push_back(Point(4.88654e-17, 14.596)); poly.push_back(Point(5.78057e-17, 17.2664)); poly.push_back(Point(6.33865e-17, 18.9334)); poly.push_back(Point(6.52835e-17, 19.5)); poly.push_back(Point(3.4641, 17.5)); assert(poly.is_simple()); if(poly.is_clockwise_oriented()) poly.reverse_orientation(); std::vector<PolygonPtr> exteriorSkeleton = CGAL::create_exterior_skeleton_and_offset_polygons_2(1e-5, poly); assert(exteriorSkeleton.size() == 2); assert(exteriorSkeleton[0]->size() == 4); assert(exteriorSkeleton[0]->is_simple()); assert(exteriorSkeleton[1]->is_simple()); } void high_precision_run() { Polygon_2 poly; poly.push_back(Point(3.4641015529632568, 16.991481781005859)); poly.push_back(Point(3.4641015529632568, 15.495480537414551)); poly.push_back(Point(3.4641015529632568, 13.09893798828125)); poly.push_back(Point(3.4641015529632568, 9.9411334991455078)); poly.push_back(Point(3.4641015529632568, 6.2055854797363281)); poly.push_back(Point(3.4641015529632568, 2.1093919277191162)); poly.push_back(Point(3.4641015529632568, -2.1093919277191162)); poly.push_back(Point(3.4641015529632568, -6.2055854797363281)); poly.push_back(Point(3.4641015529632568, -9.9411334991455078)); poly.push_back(Point(3.4641015529632568, -13.09893798828125)); poly.push_back(Point(3.4641015529632568, -15.495480537414551)); poly.push_back(Point(3.4641015529632568, -16.991481781005859)); poly.push_back(Point(3.4641015529632568, -17.5)); poly.push_back(Point(-6.5283512761760263e-17, -19.5)); poly.push_back(Point(-6.3386490615069335e-17, -18.933364868164063)); poly.push_back(Point(-5.7805677252904074e-17, -17.266391754150391)); poly.push_back(Point(-4.8865411228468343e-17, -14.595959663391113)); poly.push_back(Point(-3.7085263204542273e-17, -11.077262878417969)); poly.push_back(Point(-2.314985300804045e-17, -6.9147953987121582)); poly.push_back(Point(-7.8690580132517397e-18, -2.3504652976989746)); poly.push_back(Point(7.8690580132513576e-18, 2.3504652976989746)); poly.push_back(Point(2.3149853008040067e-17, 6.9147953987121582)); poly.push_back(Point(3.7085263204541891e-17, 11.077262878417969)); poly.push_back(Point(4.8865411228467961e-17, 14.595959663391113)); poly.push_back(Point(5.7805677252903704e-17, 17.266391754150391)); poly.push_back(Point(6.3386490615068965e-17, 18.933364868164063)); poly.push_back(Point(6.5283512761759894e-17, 19.5)); poly.push_back(Point(3.4641015529632568, 17.5)); assert(poly.is_simple()); if(poly.is_clockwise_oriented()) poly.reverse_orientation(); std::vector<PolygonPtr> exteriorSkeleton = CGAL::create_exterior_skeleton_and_offset_polygons_2(1e-5, poly, K()); assert(exteriorSkeleton.size() == 2); assert(exteriorSkeleton[0]->is_simple()); assert(exteriorSkeleton[0]->size() == 4); assert(exteriorSkeleton[1]->is_simple()); } int main() { std::cout << "------------------- low precision test ---------------------" << std::endl; low_precision_run(); std::cout << "------------------- high precision test ---------------------" << std::endl; high_precision_run(); return EXIT_SUCCESS; }
2,193
1,244
// Copyright 2014 runtime.js project authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #ifdef RUNTIMEJS_PLATFORM_X64 #include <kernel/x64/cpu-x64.h> #else #error Platform is not supported #endif namespace rt { class Cpu { public: /** * Pause operation for busy-wait loops */ static void WaitPause() { CpuPlatform::WaitPause(); } /** * Disable interrupts and stop execution */ __attribute__((__noreturn__)) static void HangSystem() { CpuPlatform::HangSystem(); } /** * Get current CPU index */ static uint32_t id() { return CpuPlatform::id(); } /** * Enable interrupts on current CPU */ static void EnableInterrupts() { CpuPlatform::EnableInterrupts(); } /** * Disable interrupts on current CPU */ static void DisableInterrupts() { CpuPlatform::DisableInterrupts(); } /** * Get interrupts enabled status */ static bool IsInterruptsEnabled() { return CpuPlatform::IsInterruptsEnabled(); } /** * Put CPU into sleep until next interrupt */ static void Halt() { CpuPlatform::Halt(); } }; } // namespace rt
524
5,964
<reponame>wenfeifei/miniblink49<gh_stars>1000+ // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/frame/LocalFrameLifecycleNotifier.h" #include "core/frame/LocalFrameLifecycleObserver.h" namespace blink { void LocalFrameLifecycleNotifier::notifyWillDetachFrameHost() { TemporaryChange<IterationType> scope(m_iterating, IteratingOverAll); #if !ENABLE(OILPAN) // Notifications perform unknown amounts of heap allocations, // which might trigger (conservative) GCs. This will flush out // dead observers, causing the _non-heap_ set be updated. Snapshot // the observers and explicitly check if they're still alive before // notifying. Vector<RawPtr<LocalFrameLifecycleObserver>> snapshotOfObservers; copyToVector(m_observers, snapshotOfObservers); for (LocalFrameLifecycleObserver* observer : snapshotOfObservers) { if (m_observers.contains(observer)) observer->willDetachFrameHost(); } #else for (LocalFrameLifecycleObserver* observer : m_observers) observer->willDetachFrameHost(); #endif } } // namespace blink
413
677
<gh_stars>100-1000 // Copyright 2017 The Lynx Authors. All rights reserved. #if OS_ANDROID #ifndef LYNX_RENDER_COORDINATOR_BRIDGE_H_ #define LYNX_RENDER_COORDINATOR_BRIDGE_H_ #include <string> #include <jni.h> #include "base/android/android_jni.h" namespace lynx { class JNICoordinatorBridge { public: static bool RegisterJNIUtils(JNIEnv* env); }; } // namespace jscore #endif // LYNX_RENDER_COORDINATOR_BRIDGE_H_ #endif
188
2,151
<filename>content/browser/web_package/mock_signed_exchange_handler.h // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_WEB_PACKAGE_MOCK_SIGNED_EXCHANGE_HANDLER_H_ #define CONTENT_BROWSER_WEB_PACKAGE_MOCK_SIGNED_EXCHANGE_HANDLER_H_ #include <string> #include <vector> #include "content/browser/web_package/signed_exchange_handler.h" #include "url/gurl.h" namespace content { class SignedExchangeCertFetcherFactory; class MockSignedExchangeHandler final : public SignedExchangeHandler { public: MockSignedExchangeHandler(net::Error error, const GURL& request_url, const std::string& mime_type, const std::vector<std::string>& response_headers, std::unique_ptr<net::SourceStream> body, ExchangeHeadersCallback headers_callback); ~MockSignedExchangeHandler(); private: DISALLOW_COPY_AND_ASSIGN(MockSignedExchangeHandler); }; class MockSignedExchangeHandlerFactory final : public SignedExchangeHandlerFactory { public: using ExchangeHeadersCallback = SignedExchangeHandler::ExchangeHeadersCallback; // Creates a factory that creates SignedExchangeHandler which always fires // a headers callback with the given |error|, |request_url|, |mime_type| // and |response_headers|. // |mime_type| and |response_headers| are ignored if |error| is not // net::OK. MockSignedExchangeHandlerFactory(net::Error error, const GURL& request_url, const std::string& mime_type, std::vector<std::string> response_headers); ~MockSignedExchangeHandlerFactory() override; std::unique_ptr<SignedExchangeHandler> Create( std::unique_ptr<net::SourceStream> body, ExchangeHeadersCallback headers_callback, std::unique_ptr<SignedExchangeCertFetcherFactory> cert_fetcher_factory) override; private: const net::Error error_; const GURL request_url_; const std::string mime_type_; const std::vector<std::string> response_headers_; DISALLOW_COPY_AND_ASSIGN(MockSignedExchangeHandlerFactory); }; } // namespace content #endif // CONTENT_BROWSER_WEB_PACKAGE_MOCK_SIGNED_EXCHANGE_HANDLER_H_
965
1,799
<reponame>peblue12345/Paddle-Lite<gh_stars>1000+ // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <iostream> #include <memory> #include <utility> #include <vector> #include "lite/core/op_registry.h" #ifdef LITE_WITH_ARM #include "lite/kernels/arm/sequence_expand_as_compute.h" namespace paddle { namespace lite { TEST(sequence_expand_as, retrive_op) { auto sequence_expand_as = KernelRegistry::Global().Create("sequence_expand_as"); ASSERT_FALSE(sequence_expand_as.empty()); ASSERT_TRUE(sequence_expand_as.front()); } TEST(sequence_expand_as, init) { paddle::lite::kernels::arm::SequenceExpandAsCompute sequence_expand_as; ASSERT_EQ(sequence_expand_as.precision(), PRECISION(kFloat)); ASSERT_EQ(sequence_expand_as.target(), TARGET(kARM)); } TEST(sequence_expand_as, run_test) { lite::Tensor x, y, out; std::vector<int64_t> x_shape{4, 1}; x.Resize(lite::DDim(x_shape)); std::vector<int64_t> y_shape{1, 5}; y.Resize(lite::DDim(y_shape)); std::vector<int64_t> out_shape{8, 1}; out.Resize(lite::DDim(out_shape)); auto x_data = x.mutable_data<float>(); auto y_data = y.mutable_data<float>(); for (int64_t i = 0; i < x.dims().production(); i++) { x_data[i] = static_cast<float>(i); } for (int64_t i = 0; i < y.dims().production(); i++) { y_data[i] = static_cast<float>(i); } std::vector<std::vector<uint64_t>> lod{{0, 3, 6, 7, 8}}; y.set_lod(lod); paddle::lite::kernels::arm::SequenceExpandAsCompute sequence_expand_as; operators::SequenceExpandAsParam param; param.x = &x; param.y = &y; param.out = &out; std::unique_ptr<KernelContext> ctx(new KernelContext); ctx->As<ARMContext>(); sequence_expand_as.SetContext(std::move(ctx)); sequence_expand_as.SetParam(param); sequence_expand_as.Run(); auto out_data = out.mutable_data<float>(); int index = 1; auto out_lod = param.out->lod()[0]; int lod_sum = out_lod[index] - out_lod[index - 1]; LOG(INFO) << "output: "; for (int i = 0; i < out.dims().production(); i++) { LOG(INFO) << out_data[i]; if (i >= lod_sum) { index++; lod_sum = out_lod[index]; } ASSERT_EQ(out_data[i], x_data[index - 1]); } } } // namespace lite } // namespace paddle USE_LITE_KERNEL(sequence_expand_as, kARM, kFloat, kNCHW, def); #endif
1,130
1,909
package org.knowm.xchange.test.coinsuper; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.coinsuper.CoinsuperExchange; import org.knowm.xchange.coinsuper.dto.CoinsuperResponse; import org.knowm.xchange.coinsuper.dto.account.CoinsuperUserAssetInfo; import org.knowm.xchange.coinsuper.service.CoinsuperAccountServiceRaw; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.service.account.AccountService; public class AccountServiceIntegration { public static void main(String[] args) { try { // getAssetInfoRaw(); getAssetInfo(); } catch (IOException e) { e.printStackTrace(); } } private static void getAssetInfoRaw() throws IOException { String apiKey = "<KEY>"; String secretKey = "fa3f0510-155f-4567-a3b3-3f386080efa3"; Exchange coinsuper = ExchangeFactory.INSTANCE.createExchange(CoinsuperExchange.class); ExchangeSpecification exchangeSpecification = coinsuper.getExchangeSpecification(); exchangeSpecification.setApiKey(apiKey); exchangeSpecification.setSecretKey(secretKey); coinsuper.applySpecification(exchangeSpecification); AccountService accountService = coinsuper.getAccountService(); try { raw((CoinsuperAccountServiceRaw) accountService); } catch (IOException e) { e.printStackTrace(); } } private static void raw(CoinsuperAccountServiceRaw accountService) throws IOException { Map<String, String> parameters = new HashMap<String, String>(); CoinsuperResponse<CoinsuperUserAssetInfo> coinsuperResponse = accountService.getUserAssetInfo(); System.out.println("-------------coinsuperResponse.getData().getResult()--------"); System.out.println( "BTC:" + coinsuperResponse.getData().getResult().getAsset().getBTC().getTotal()); System.out.println( "BTC:" + coinsuperResponse.getData().getResult().getAsset().getBTC().getAvailable()); System.out.println( "ETH:" + coinsuperResponse.getData().getResult().getAsset().getETH().getAvailable()); } private static void getAssetInfo() throws IOException { String apiKey = "<KEY>"; String secretKey = "fa3f0510-155f-4567-a3b3-3f386080efa3"; Exchange coinsuper = ExchangeFactory.INSTANCE.createExchange(CoinsuperExchange.class); ExchangeSpecification exchangeSpecification = coinsuper.getExchangeSpecification(); exchangeSpecification.setApiKey(apiKey); exchangeSpecification.setSecretKey(secretKey); coinsuper.applySpecification(exchangeSpecification); AccountService accountService = coinsuper.getAccountService(); try { AccountInfo accountInfo = accountService.getAccountInfo(); System.out.println(accountInfo); System.out.println(accountInfo.getWallets()); } catch (IOException e) { e.printStackTrace(); } } }
994
1,541
<filename>src/main/java/com/bwssystems/HABridge/plugins/mqtt/MQTTBroker.java package com.bwssystems.HABridge.plugins.mqtt; import com.bwssystems.HABridge.NamedIP; public class MQTTBroker { private String clientId; private String ip; public MQTTBroker(NamedIP brokerConfig) { super(); this.setIp(brokerConfig.getIp()); this.setClientId(brokerConfig.getName()); } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
278
1,350
<filename>sdk/iothub/azure-resourcemanager-iothub/src/main/java/com/azure/resourcemanager/iothub/models/IotHubs.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.iothub.models; import com.azure.core.util.Context; /** Resource collection API of IotHubs. */ public interface IotHubs { /** * Manually initiate a failover for the IoT Hub to its secondary region. To learn more, see * https://aka.ms/manualfailover. * * @param iotHubName Name of the IoT hub to failover. * @param resourceGroupName Name of the resource group containing the IoT hub resource. * @param failoverInput Region to failover to. Must be the Azure paired region. Get the value from the secondary * location in the locations property. To learn more, see https://aka.ms/manualfailover/region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by * server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ void manualFailover(String iotHubName, String resourceGroupName, FailoverInput failoverInput); /** * Manually initiate a failover for the IoT Hub to its secondary region. To learn more, see * https://aka.ms/manualfailover. * * @param iotHubName Name of the IoT hub to failover. * @param resourceGroupName Name of the resource group containing the IoT hub resource. * @param failoverInput Region to failover to. Must be the Azure paired region. Get the value from the secondary * location in the locations property. To learn more, see https://aka.ms/manualfailover/region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.iothub.models.ErrorDetailsException thrown if the request is rejected by * server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ void manualFailover(String iotHubName, String resourceGroupName, FailoverInput failoverInput, Context context); }
722
701
#pragma once #include <bal/hw/mem.h> #include <bal/task/args.h> typedef struct { BrId id; BrHandle handle; Str name; } BalTask; void bal_task_init(BalTask *task, Str name); void bal_task_deinit(BalTask *task); BrResult bal_task_exec(BalTask *task, BalMem *elf, BrRight rights, BalArgs args);
127
2,151
// Copyright 2018 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 "services/network/http_cache_data_remover.h" #include <set> #include <string> #include "base/location.h" #include "base/threading/sequenced_task_runner_handle.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/disk_cache/disk_cache.h" #include "net/http/http_cache.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #include "url/gurl.h" namespace network { namespace { bool DoesUrlMatchFilter(mojom::ClearDataFilter_Type filter_type, const std::set<url::Origin>& origins, const std::set<std::string>& domains, const GURL& url) { std::string url_registerable_domain = net::registry_controlled_domains::GetDomainAndRegistry( url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); bool found_domain = (domains.find(url_registerable_domain != "" ? url_registerable_domain : url.host()) != domains.end()); bool found_origin = (origins.find(url::Origin::Create(url)) != origins.end()); return ((found_domain || found_origin) == (filter_type == mojom::ClearDataFilter_Type::DELETE_MATCHES)); } } // namespace HttpCacheDataRemover::HttpCacheDataRemover( mojom::ClearDataFilterPtr url_filter, base::Time delete_begin, base::Time delete_end, HttpCacheDataRemoverCallback done_callback) : delete_begin_(delete_begin), delete_end_(delete_end), done_callback_(std::move(done_callback)), weak_factory_(this) { DCHECK(!done_callback_.is_null()); if (!url_filter) return; // Use the filter to create the |url_matcher_| callback. std::set<std::string> domains; domains.insert(url_filter->domains.begin(), url_filter->domains.end()); std::set<url::Origin> origins; origins.insert(url_filter->origins.begin(), url_filter->origins.end()); url_matcher_ = base::BindRepeating(&DoesUrlMatchFilter, url_filter->type, origins, domains); } HttpCacheDataRemover::~HttpCacheDataRemover() = default; // static. std::unique_ptr<HttpCacheDataRemover> HttpCacheDataRemover::CreateAndStart( net::URLRequestContext* url_request_context, mojom::ClearDataFilterPtr url_filter, base::Time delete_begin, base::Time delete_end, HttpCacheDataRemoverCallback done_callback) { DCHECK(done_callback); std::unique_ptr<HttpCacheDataRemover> remover( new HttpCacheDataRemover(std::move(url_filter), delete_begin, delete_end, std::move(done_callback))); net::HttpCache* http_cache = url_request_context->http_transaction_factory()->GetCache(); if (!http_cache) { // Some contexts might not have a cache, in which case we are done. // Notify by posting a task to avoid reentrency. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&HttpCacheDataRemover::ClearHttpCacheDone, remover->weak_factory_.GetWeakPtr(), net::OK)); return remover; } // Clear QUIC server information from memory and the disk cache. // TODO(crbug.com/817849): add a browser test to validate the QUIC information // is cleared. http_cache->GetSession() ->quic_stream_factory() ->ClearCachedStatesInCryptoConfig(remover->url_matcher_); auto backend = std::make_unique<disk_cache::Backend*>(); disk_cache::Backend** backend_ptr = backend.get(); // IMPORTANT: we have to keep the callback on the stack so that |backend| is // not deleted before this method returns, as its deletion would make // |backend_ptr| invalid and it's needed for the CacheRetrieved() call below. net::CompletionCallback callback = base::Bind(&HttpCacheDataRemover::CacheRetrieved, remover->weak_factory_.GetWeakPtr(), base::Passed(&backend)); int rv = http_cache->GetBackend(backend_ptr, callback); if (rv != net::ERR_IO_PENDING) { remover->CacheRetrieved( std::make_unique<disk_cache::Backend*>(*backend_ptr), rv); } return remover; } void HttpCacheDataRemover::CacheRetrieved( std::unique_ptr<disk_cache::Backend*> backend, int rv) { DCHECK(done_callback_); disk_cache::Backend* cache = *backend; // |cache| can be null if it cannot be initialized. if (!cache || rv != net::OK) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&HttpCacheDataRemover::ClearHttpCacheDone, weak_factory_.GetWeakPtr(), rv)); return; } if (!url_matcher_.is_null()) { deletion_helper_ = ConditionalCacheDeletionHelper::CreateAndStart( cache, url_matcher_, delete_begin_, delete_end_, base::BindOnce(&HttpCacheDataRemover::ClearHttpCacheDone, weak_factory_.GetWeakPtr(), net::OK)); return; } if (delete_begin_.is_null() && delete_end_.is_max()) { rv = cache->DoomAllEntries(base::Bind( &HttpCacheDataRemover::ClearHttpCacheDone, weak_factory_.GetWeakPtr())); } else { rv = cache->DoomEntriesBetween( delete_begin_, delete_end_, base::Bind(&HttpCacheDataRemover::ClearHttpCacheDone, weak_factory_.GetWeakPtr())); } if (rv != net::ERR_IO_PENDING) { // Notify by posting a task to avoid reentrency. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&HttpCacheDataRemover::ClearHttpCacheDone, weak_factory_.GetWeakPtr(), rv)); } } void HttpCacheDataRemover::ClearHttpCacheDone(int rv) { std::move(done_callback_).Run(this); } } // namespace network
2,348
1,738
/* * 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. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_TOOLS_RC_RESOURCECOMPILERPC_STATCGFPHYSICALIZE_H #define CRYINCLUDE_TOOLS_RC_RESOURCECOMPILERPC_STATCGFPHYSICALIZE_H #pragma once #include "CGFContent.h" #if ENABLE_CRY_PHYSICS #include "PhysWorld.h" ////////////////////////////////////////////////////////////////////////// class CPhysicsInterface { public: CPhysicsInterface(); ~CPhysicsInterface(); enum EPhysicalizeResult { ePR_Empty, ePR_Ok, ePR_Fail }; EPhysicalizeResult Physicalize(CNodeCGF* pNodeCGF, CContentCGF* pCGF); bool DeletePhysicalProxySubsets(CNodeCGF* pNodeCGF, bool bCga); void ProcessBreakablePhysics(CContentCGF* pCompiledCGF, CContentCGF* pSrcCGF); int CheckNodeBreakable(CNodeCGF* pNode, IGeometry* pGeom = 0); IGeomManager* GetGeomManager() { return m_pGeomManager; } // When node already physicalized, physicalize it again. void RephysicalizeNode(CNodeCGF* pNodeCGF, CContentCGF* pCGF); private: EPhysicalizeResult PhysicalizeGeomType(int nGeomType, CNodeCGF* pNodeCGF, CContentCGF* pCGF); IGeomManager* m_pGeomManager; CPhysWorldLoader m_physLoader; }; #endif #endif // CRYINCLUDE_TOOLS_RC_RESOURCECOMPILERPC_STATCGFPHYSICALIZE_H
659
1,338
/* * Copyright 2011-2012, Haiku, Inc. All rights reserved. * Copyright 2011, <NAME> <<EMAIL>> * Distributed under the terms of the MIT License. */ #ifndef DEFAULT_NOTIFIER_H #define DEFAULT_NOTIFIER_H #include <Notification.h> #include <String.h> #include "MailProtocol.h" #include "ErrorLogWindow.h" #include "StatusWindow.h" class DefaultNotifier : public BMailNotifier { public: DefaultNotifier(const char* accountName, bool inbound, ErrorLogWindow* errorWindow, uint32 showMode); ~DefaultNotifier(); BMailNotifier* Clone(); void ShowError(const char* error); void ShowMessage(const char* message); void SetTotalItems(uint32 items); void SetTotalItemsSize(uint64 size); void ReportProgress(uint32 messages, uint64 bytes, const char* message = NULL); void ResetProgress(const char* message = NULL); private: void _NotifyIfAllowed(int timeout = 0); private: BString fAccountName; bool fIsInbound; ErrorLogWindow* fErrorWindow; BNotification fNotification; uint32 fShowMode; uint32 fTotalItems; uint32 fItemsDone; uint64 fTotalSize; uint64 fSizeDone; }; #endif // DEFAULT_NOTIFIER_H
511
1,144
/* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2020 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 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/gpl-2.0.html>. * #L% */ package de.metas.calendar.impl; import de.metas.util.Check; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.model.I_C_Calendar; import org.compiere.model.I_C_Period; import org.compiere.model.I_C_Year; import org.compiere.model.Query; import java.sql.Timestamp; import java.util.List; import java.util.Properties; public class CalendarDAO extends AbstractCalendarDAO { @Override public List<I_C_Period> retrievePeriods( final Properties ctx, final I_C_Year year, final String trxName) { return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName) .setParameters(year.getC_Year_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Period.COLUMNNAME_StartDate) .list(I_C_Period.class); } @Override protected List<I_C_Period> retrievePeriods( final Properties ctx, final int calendarId, final Timestamp begin, final Timestamp end, final String trxName) { Check.assume(begin != null, "Param 'begin' is not null"); Check.assume(end != null, "Param 'end' is not null"); final String wc = I_C_Period.COLUMNNAME_C_Year_ID + " IN (" + " select " + I_C_Year.COLUMNNAME_C_Year_ID + " from " + I_C_Year.Table_Name + " where " + I_C_Year.COLUMNNAME_C_Calendar_ID + "=?" + ") AND " + I_C_Period.COLUMNNAME_EndDate + ">=? AND " + I_C_Period.COLUMNNAME_StartDate + "<=?"; return new Query(ctx, I_C_Period.Table_Name, wc, trxName) .setParameters(calendarId, begin, end) .setOnlyActiveRecords(true) .setClient_ID() // .setApplyAccessFilter(true) isn't required here and case cause problems when running from ad_scheduler .setOrderBy(I_C_Period.COLUMNNAME_StartDate) .list(I_C_Period.class); } @Override public List<I_C_Year> retrieveYearsOfCalendar(final I_C_Calendar calendar) { final Properties ctx = InterfaceWrapperHelper.getCtx(calendar); final String trxName = InterfaceWrapperHelper.getTrxName(calendar); final String whereClause = I_C_Year.COLUMNNAME_C_Calendar_ID + "=?"; return new Query(ctx, I_C_Year.Table_Name, whereClause, trxName) .setParameters(calendar.getC_Calendar_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Year.COLUMNNAME_C_Year_ID) .list(I_C_Year.class); } @Override public I_C_Period retrieveFirstPeriodOfTheYear(final I_C_Year year) { final Properties ctx = InterfaceWrapperHelper.getCtx(year); final String trxName = InterfaceWrapperHelper.getTrxName(year); return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName) .setParameters(year.getC_Year_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Period.COLUMNNAME_StartDate) .first(I_C_Period.class); } @Override public I_C_Period retrieveLastPeriodOfTheYear(final I_C_Year year) { final Properties ctx = InterfaceWrapperHelper.getCtx(year); final String trxName = InterfaceWrapperHelper.getTrxName(year); return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName) .setParameters(year.getC_Year_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_Period.COLUMNNAME_StartDate + " DESC ") .first(I_C_Period.class); } }
1,613
2,111
<reponame>mfkiwl/GAAS #include "FeatureFrontEndCV.h"
24
2,517
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <type_traits> #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/detail/mtl_util.hpp" #include "caf/typed_actor.hpp" namespace caf { /// Enables event-based actors to generate messages from a user-defined data /// exchange format such as JSON and to send the generated messages to another /// (typed) actor. template <class Self, class Adapter, class Reader> class event_based_mtl { public: // -- sanity checks ---------------------------------------------------------- static_assert(std::is_nothrow_copy_assignable<Adapter>::value); static_assert(std::is_nothrow_move_assignable<Adapter>::value); // -- constructors, destructors, and assignment operators -------------------- event_based_mtl() = delete; event_based_mtl(Self* self, Adapter adapter, Reader* reader) noexcept : self_(self), adapter_(std::move(adapter)), reader_(reader) { // nop } event_based_mtl(const event_based_mtl&) noexcept = default; event_based_mtl& operator=(const event_based_mtl&) noexcept = default; // -- properties ------------------------------------------------------------- auto self() { return self_; } auto& adapter() { return adapter_; } auto& reader() { return *reader_; } // -- messaging -------------------------------------------------------------- /// Tries to get a message from the reader that matches any of the accepted /// inputs of `dst` and sends the converted messages on success. /// @param dst The destination for the next message. /// @returns `true` if the adapter was able to generate and send a message, /// `false` otherwise. template <class... Fs> bool try_send(const typed_actor<Fs...>& dst) { auto dst_hdl = actor_cast<actor>(dst); return (detail::mtl_util<Fs>::send(self_, dst_hdl, adapter_, *reader_) || ...); } /// Tries to get a message from the reader that matches any of the accepted /// inputs of `dst` and sends a request message to `dst` on success. /// @param dst The destination for the next message. /// @param timeout The relative timeout for the request message. /// @param on_result The one-shot handler for the response message. This /// function object must accept *all* possible response types /// from `dst`. /// @param on_error The one-shot handler for timeout and other errors. /// @returns `true` if the adapter was able to generate and send a message, /// `false` otherwise. template <class... Fs, class Timeout, class OnResult, class OnError> bool try_request(const typed_actor<Fs...>& dst, Timeout timeout, OnResult on_result, OnError on_error) { using on_error_result = decltype(on_error(std::declval<error&>())); static_assert(std::is_same<void, on_error_result>::value); auto dst_hdl = actor_cast<actor>(dst); return (detail::mtl_util<Fs>::request(self_, dst_hdl, timeout, adapter_, *reader_, on_result, on_error) || ...); } private: Self* self_; Adapter adapter_; Reader* reader_; }; /// Creates an MTL (message translation layer) to enable an actor to exchange /// messages with non-CAF endpoints over a user-defined data exchange format /// such as JSON. /// @param self Points to an event-based or blocking actor. /// @param adapter Translates between internal and external message types. /// @param reader Points to an object that either implements the interface /// @ref deserializer directly or that provides a compatible API. template <class Self, class Adapter, class Reader> auto make_mtl(Self* self, Adapter adapter, Reader* reader) { if constexpr (std::is_base_of<non_blocking_actor_base, Self>::value) { return event_based_mtl{self, adapter, reader}; } else { static_assert(detail::always_false_v<Self>, "sorry, support for blocking actors not implemented yet"); } } } // namespace caf
1,379
1,265
<reponame>zhangzi0291/sa-token package cn.dev33.satoken.interceptor; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import cn.dev33.satoken.stp.StpLogic; import cn.dev33.satoken.stp.StpUtil; /** * 注解式鉴权 - 拦截器 * * @author kong */ public class SaAnnotationInterceptor implements HandlerInterceptor { /** * 在进行注解鉴权时使用的 StpLogic 对象 */ public StpLogic stpLogic = null; /** * @return 在进行注解鉴权时使用的 StpLogic 对象 */ public StpLogic getStpLogic() { if (stpLogic == null) { stpLogic = StpUtil.stpLogic; } return stpLogic; } /** * @param stpLogic 在进行注解鉴权时使用的 StpLogic 对象 * @return 拦截器自身 */ public SaAnnotationInterceptor setStpLogic(StpLogic stpLogic) { this.stpLogic = stpLogic; return this; } /** * 构建: 注解式鉴权 - 拦截器 */ public SaAnnotationInterceptor() { } /** * 每次请求之前触发的方法 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 获取处理method if (handler instanceof HandlerMethod == false) { return true; } Method method = ((HandlerMethod) handler).getMethod(); // 进行验证 getStpLogic().checkMethodAnnotation(method); // 通过验证 return true; } }
703
506
package com.xnx3.template.ui; import java.awt.Frame; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; public class RightMenu extends JFrame{ private JPopupMenu menu = new JPopupMenu(); public RightMenu() { setBounds(100,100,350,150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); //加上功能后,再去掉下面注释 this.init(); this.add(menu); } public void init(){ JPopupMenu menu = new JPopupMenu(); JMenuItem varItem = new JMenuItem("创建模版变量"); this.add(menu); } public static void main(String[] args) { new RightMenu(); } }
351
745
<gh_stars>100-1000 from itertools import count as itertools_count import traceback import time import gevent def subpool_map(pool_size, func, iterable): """ Starts a Gevent pool and run a map. Takes care of setting current_job and cleaning up. """ from .context import get_current_job, set_current_job, log if not pool_size: return [func(*args) for args in iterable] counter = itertools_count() current_job = get_current_job() def inner_func(*args): """ As each call to 'func' will be done in a random greenlet of the subpool, we need to register their IDs with set_current_job() to make get_current_job() calls work properly inside 'func'. """ next(counter) if current_job: set_current_job(current_job) try: ret = func(*args) except Exception as exc: trace = traceback.format_exc() exc.subpool_traceback = trace raise if current_job: set_current_job(None) return ret def inner_iterable(): """ This will be called inside the pool's main greenlet, which ID also needs to be registered """ if current_job: set_current_job(current_job) for x in iterable: yield x if current_job: set_current_job(None) start_time = time.time() pool = gevent.pool.Pool(size=pool_size) ret = pool.map(inner_func, inner_iterable()) pool.join(raise_error=True) total_time = time.time() - start_time log.debug("SubPool ran %s greenlets in %0.6fs" % (counter, total_time)) return ret def subpool_imap(pool_size, func, iterable, flatten=False, unordered=False, buffer_size=None): """ Generator version of subpool_map. Should be used with unordered=True for optimal performance """ from .context import get_current_job, set_current_job, log if not pool_size: for args in iterable: yield func(*args) counter = itertools_count() current_job = get_current_job() def inner_func(*args): """ As each call to 'func' will be done in a random greenlet of the subpool, we need to register their IDs with set_current_job() to make get_current_job() calls work properly inside 'func'. """ next(counter) if current_job: set_current_job(current_job) try: ret = func(*args) except Exception as exc: trace = traceback.format_exc() exc.subpool_traceback = trace raise if current_job: set_current_job(None) return ret def inner_iterable(): """ This will be called inside the pool's main greenlet, which ID also needs to be registered """ if current_job: set_current_job(current_job) for x in iterable: yield x if current_job: set_current_job(None) start_time = time.time() pool = gevent.pool.Pool(size=pool_size) if unordered: iterator = pool.imap_unordered(inner_func, inner_iterable(), maxsize=buffer_size or pool_size) else: iterator = pool.imap(inner_func, inner_iterable()) for x in iterator: if flatten: for y in x: yield y else: yield x pool.join(raise_error=True) total_time = time.time() - start_time log.debug("SubPool ran %s greenlets in %0.6fs" % (counter, total_time))
1,314
20,996
<filename>hphp/hack/src/third-party/inotify/inotify_stubs.c<gh_stars>1000+ /* * Copyright (C) 2006-2008 <NAME> <<EMAIL>> * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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 Lesser General Public License for more details. * * Inotify Ocaml binding - C glue */ #include <errno.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/custom.h> #include <caml/fail.h> #include <caml/signals.h> #include <caml/callback.h> #include <caml/unixsupport.h> #include <sys/inotify.h> static int inotify_flag_table[] = { IN_ACCESS, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE, IN_CREATE, IN_DELETE, IN_DELETE_SELF, IN_MODIFY, IN_MOVE_SELF, IN_MOVED_FROM, IN_MOVED_TO, IN_OPEN, IN_DONT_FOLLOW, IN_MASK_ADD, IN_ONESHOT, IN_ONLYDIR, IN_MOVE, IN_CLOSE, IN_ALL_EVENTS, 0 }; static int inotify_return_table[] = { IN_ACCESS, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE, IN_CREATE, IN_DELETE, IN_DELETE_SELF, IN_MODIFY, IN_MOVE_SELF, IN_MOVED_FROM, IN_MOVED_TO, IN_OPEN, IN_IGNORED, IN_ISDIR, IN_Q_OVERFLOW, IN_UNMOUNT, 0 }; value caml_inotify_init(value unit) { CAMLparam1(unit); int fd = inotify_init(); if (fd == -1) uerror("inotify_init", Nothing); CAMLreturn(Val_int(fd)); } value caml_inotify_add_watch(value fd, value path, value selector_flags) { CAMLparam3(fd, path, selector_flags); int selector = caml_convert_flag_list(selector_flags, inotify_flag_table); int watch = inotify_add_watch(Int_val(fd), String_val(path), selector); if (watch == -1) uerror("inotify_add_watch", path); CAMLreturn(Val_int(watch)); } value caml_inotify_rm_watch(value fd, value watch) { CAMLparam2(fd, watch); int ret = inotify_rm_watch(Int_val(fd), Int_val(watch)); if (ret == -1) uerror("inotify_rm_watch", Nothing); CAMLreturn(Val_unit); } value caml_inotify_struct_size(void) { CAMLparam0(); CAMLreturn(Val_int(sizeof(struct inotify_event))); } value caml_inotify_name_max(void) { CAMLparam0(); CAMLreturn(Val_int(NAME_MAX)); } value caml_inotify_convert(value buf) { CAMLparam1(buf); CAMLlocal3(event, list, next); list = next = Val_emptylist; struct inotify_event ievent; memcpy(&ievent, String_val(buf), sizeof(struct inotify_event)); int flag; for (flag = 0; inotify_return_table[flag]; flag++) { if (!(ievent.mask & inotify_return_table[flag])) continue; next = caml_alloc_small(2, Tag_cons); Field(next, 0) = Val_int(flag); Field(next, 1) = list; list = next; } event = caml_alloc_tuple(4); Store_field(event, 0, Val_int(ievent.wd)); Store_field(event, 1, list); Store_field(event, 2, caml_copy_int32(ievent.cookie)); Store_field(event, 3, Val_int(ievent.len)); CAMLreturn(event); }
1,311
17,702
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== from __future__ import print_function import os import sys import glob import tarfile import numpy as np from scipy.io import loadmat try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve def write_to_file(filename, base_path, img_paths, img_labels): with open(os.path.join(base_path, filename), 'w+') as f: for i in range(0, len(img_paths)): f.write('%s\t%s\n' % (os.path.join(base_path, img_paths[i]), img_labels[i])) def download_flowers_data(): dataset_folder = os.path.dirname(os.path.abspath(__file__)) if not os.path.exists(os.path.join(dataset_folder, "jpg")): print('Downloading data from http://www.robots.ox.ac.uk/~vgg/data/flowers/102/ ...') tar_filename = os.path.join(dataset_folder, "102flowers.tgz") label_filename = os.path.join(dataset_folder, "imagelabels.mat") set_filename = os.path.join(dataset_folder, "setid.mat") if not os.path.exists(tar_filename): urlretrieve("http://www.robots.ox.ac.uk/~vgg/data/flowers/102/102flowers.tgz", tar_filename) if not os.path.exists(label_filename): urlretrieve("http://www.robots.ox.ac.uk/~vgg/data/flowers/102/imagelabels.mat", label_filename) if not os.path.exists(set_filename): urlretrieve("http://www.robots.ox.ac.uk/~vgg/data/flowers/102/setid.mat", set_filename) print('Extracting ' + tar_filename + '...') tarfile.open(tar_filename).extractall(path=dataset_folder) print('Writing map files ...') # read set information from .mat file setid = loadmat(set_filename) idx_train = setid['trnid'][0] - 1 idx_test = setid['tstid'][0] - 1 idx_val = setid['valid'][0] - 1 # get image paths and 0-based image labels image_paths = np.array(sorted(glob.glob(dataset_folder + '/jpg/*.jpg'))) image_labels = loadmat(label_filename)['labels'][0] image_labels -= 1 # Confusingly the training set contains 1k images and the test set contains 6k images write_to_file('1k_img_map.txt', dataset_folder, image_paths[idx_train], image_labels[idx_train]) write_to_file('6k_img_map.txt', dataset_folder, image_paths[idx_test], image_labels[idx_test]) write_to_file('val_map.txt', dataset_folder, image_paths[idx_val], image_labels[idx_val]) # clean up os.remove(tar_filename) os.remove(label_filename) os.remove(set_filename) print('Done.') else: print('Data already available at ' + dataset_folder + '/Flowers') if __name__ == "__main__": download_flowers_data()
1,219
1,444
package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BeginningOfUpkeepTriggeredAbility; import mage.abilities.effects.common.DamageTargetEffect; import mage.constants.SubType; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.TargetController; import mage.target.common.TargetControlledCreaturePermanent; /** * * @author TheElk801 */ public final class SpitefulBully extends CardImpl { public SpitefulBully(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}"); this.subtype.add(SubType.PHYREXIAN); this.subtype.add(SubType.ZOMBIE); this.subtype.add(SubType.MERCENARY); this.power = new MageInt(3); this.toughness = new MageInt(3); // At the beginning of your upkeep, Spiteful Bully deals 3 damage to target creature you control. Ability ability = new BeginningOfUpkeepTriggeredAbility(new DamageTargetEffect(3), TargetController.YOU, false); ability.addTarget(new TargetControlledCreaturePermanent()); this.addAbility(ability); } private SpitefulBully(final SpitefulBully card) { super(card); } @Override public SpitefulBully copy() { return new SpitefulBully(this); } }
511
2,702
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package keywhiz.api; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import keywhiz.api.model.Client; import keywhiz.api.model.Group; import keywhiz.api.model.SanitizedSecret; public class GroupDetailResponse { @JsonProperty private final long id; @JsonProperty private final String name; @JsonProperty private final String description; @JsonProperty private final ApiDate creationDate; @JsonProperty private final ApiDate updateDate; @JsonProperty private final String createdBy; @JsonProperty private final String updatedBy; @JsonProperty private final ImmutableMap<String, String> metadata; @JsonProperty private final ImmutableList<SanitizedSecret> secrets; @JsonProperty private final ImmutableList<Client> clients; public GroupDetailResponse(@JsonProperty("id") long id, @JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("creationDate") ApiDate creationDate, @JsonProperty("updateDate") ApiDate updateDate, @JsonProperty("createdBy") String createdBy, @JsonProperty("updatedBy") String updatedBy, @JsonProperty("metadata") ImmutableMap<String, String> metadata, @JsonProperty("secrets") ImmutableList<SanitizedSecret> secrets, @JsonProperty("clients") ImmutableList<Client> clients) { this.id = id; this.name = name; this.description = description; this.creationDate = creationDate; this.updateDate = updateDate; this.createdBy = createdBy; this.updatedBy = updatedBy; this.metadata = metadata; this.secrets = secrets; this.clients = clients; } public static GroupDetailResponse fromGroup(Group group, ImmutableList<SanitizedSecret> secrets, ImmutableList<Client> clients) { return new GroupDetailResponse(group.getId(), group.getName(), group.getDescription(), group.getCreatedAt(), group.getUpdatedAt(), group.getCreatedBy(), group.getUpdatedBy(), group.getMetadata(), secrets, clients); } public long getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public ApiDate getCreationDate() { return creationDate; } public ApiDate getUpdateDate() { return updateDate; } public String getCreatedBy() { return createdBy; } public String getUpdatedBy() { return updatedBy; } public ImmutableMap<String, String> getMetadata() { return metadata; } /** * @return List of secrets the group has access to. The secrets do not contain content. */ public ImmutableList<SanitizedSecret> getSecrets() { return secrets; } public ImmutableList<Client> getClients() { return clients; } @Override public int hashCode() { return Objects.hashCode(id, name, description, creationDate, updateDate, createdBy, updatedBy, metadata, secrets, clients); } @Override public boolean equals(Object o) { if (o instanceof GroupDetailResponse) { GroupDetailResponse that = (GroupDetailResponse) o; return Objects.equal(this.id, that.id) && Objects.equal(this.name, that.name) && Objects.equal(this.description, that.description) && Objects.equal(this.creationDate, that.creationDate) && Objects.equal(this.updateDate, that.updateDate) && Objects.equal(this.createdBy, that.createdBy) && Objects.equal(this.updatedBy, that.updatedBy) && Objects.equal(this.metadata, that.metadata) && Objects.equal(this.secrets, that.secrets) && Objects.equal(this.clients, that.clients); } return false; } }
1,519
1,461
package com.dubboclub.dk.web.model; /** * Created by bieber on 2015/6/6. * 消费者信息 */ public class ConsumerInfo extends BasicResponse{ private String application; private String username; private String parameters; public String getParameters() { return parameters; } public void setParameters(String parameters) { this.parameters = parameters; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConsumerInfo that = (ConsumerInfo) o; if (application != null ? !application.equals(that.application) : that.application != null) return false; if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false; if (username != null ? !username.equals(that.username) : that.username != null) return false; return true; } @Override public int hashCode() { int result = application != null ? application.hashCode() : 0; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (parameters != null ? parameters.hashCode() : 0); return result; } }
570
488
<gh_stars>100-1000 #include "sage3basic.h" #include "RoseCodeEdit.h" #include <QDragEnterEvent> #include <QDropEvent> #include <QIcon> #include <QAction> #include "SgNodeUtil.h" #include "SageMimeData.h" #include <QDebug> void RoseCodeEdit::setNode(SgNode * node) { if(node==NULL) { //remove contents load(""); } if(isSgFile(node)) { loadCppFile(node->get_file_info()->get_filenameString().c_str()); return; } SgLocatedNode* sgLocNode = isSgLocatedNode(node); if(sgLocNode) { Sg_File_Info* fi = sgLocNode->get_startOfConstruct(); loadCppFile(fi->get_filenameString().c_str()); gotoPosition(fi->get_line(), fi->get_col()); } } // ---------------------- Drop Functionality ----------------------------------- void RoseCodeEdit::dragEnterEvent(QDragEnterEvent * ev) { if (ev->mimeData()->hasFormat(SG_NODE_MIMETYPE)) { if( this != ev->source()) { if(getSourceNodes(ev->mimeData()).size() > 0 ) ev->accept(); else ev->ignore(); } } } void RoseCodeEdit::dropEvent(QDropEvent *ev) { if(ev->source()==this) return; SgNodeVector nodes = getSourceNodes(ev->mimeData()); if(nodes.size()==0) return; setNode(nodes[0]); }
631
400
/* * fake_poll_thread.h - poll thread for raw image * * Copyright (c) 2014-2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: <NAME> <<EMAIL>> */ #ifndef XCAM_FAKE_POLL_THREAD_H #define XCAM_FAKE_POLL_THREAD_H #include <xcam_std.h> #include <poll_thread.h> namespace XCam { class FakePollThread : public PollThread { public: explicit FakePollThread (const char *raw_path); ~FakePollThread (); virtual XCamReturn start(); virtual XCamReturn stop (); protected: virtual XCamReturn poll_buffer_loop (); private: XCAM_DEAD_COPY (FakePollThread); virtual XCamReturn init_3a_stats_pool () { return XCAM_RETURN_ERROR_UNKNOWN; } XCamReturn init_buffer_pool (); XCamReturn read_buf (SmartPtr<VideoBuffer> &buf); private: char *_raw_path; FILE *_raw; SmartPtr<BufferPool> _buf_pool; }; }; #endif //XCAM_FAKE_POLL_THREAD_H
554
852
// This is a plugin implementation, but it is in src/ to make it possible to // derive from it in other packages. In plugins/ there is a dummy that declares // the plugin. #include "DQM/SiPixelPhase1Common/interface/SiPixelPhase1Base.h" #include "FWCore/Framework/interface/MakerMacros.h" void SiPixelPhase1Harvester::dqmEndLuminosityBlock(DQMStore::IBooker& iBooker, DQMStore::IGetter& iGetter, edm::LuminosityBlock const& lumiBlock, edm::EventSetup const& eSetup) { for (HistogramManager& histoman : histo) histoman.executePerLumiHarvesting(iBooker, iGetter, lumiBlock, eSetup); }; void SiPixelPhase1Harvester::dqmEndJob(DQMStore::IBooker& iBooker, DQMStore::IGetter& iGetter) { for (HistogramManager& histoman : histo) histoman.executeHarvesting(iBooker, iGetter); };
428
491
/* Automatically generated by create_config - do not modify */ #define TARGET_SPARC64 1 #define TARGET_NAME "sparc64" #define TARGET_SPARC 1 #define TARGET_WORDS_BIGENDIAN 1 #define CONFIG_SOFTMMU 1
70
915
<filename>core/src/main/java/org/nzbhydra/searching/dtoseventsenums/SearchMessageEvent.java /* * (C) Copyright 2017 TheOtherP (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nzbhydra.searching.dtoseventsenums; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.nzbhydra.searching.SortableMessage; import org.nzbhydra.searching.searchrequests.SearchRequest; @Data @AllArgsConstructor @NoArgsConstructor public class SearchMessageEvent { private SearchRequest searchRequest; private SortableMessage message; public SearchMessageEvent(SearchRequest searchRequest, String message) { this.searchRequest = searchRequest; this.message = new SortableMessage(message, message); } public SearchMessageEvent(SearchRequest searchRequest, String message, String messageSortValue) { this.searchRequest = searchRequest; this.message = new SortableMessage(message, messageSortValue); } }
463
344
/* * Copyright (c) 2022 <NAME>, <NAME>, and contributors * * 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 squidpony.squidgrid.zone; import squidpony.squidgrid.Direction; import squidpony.squidmath.Coord; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Abstraction over a list of {@link Coord}. This allows to use the short arrays * coming from {@link squidpony.squidmath.CoordPacker}, which are compressed for * better memory usage, regular {@link List lists of Coord}, which are often the * simplest option, or {@link squidpony.squidmath.GreasedRegion GreasedRegions}, * which are "greasy" in the fatty-food sense (they are heavier objects, and are * uncompressed) but also "greased" like greased lightning (they are very fast at * spatial transformations on their region). * <p> * Zones are {@link Serializable}, but serialization doesn't change the internal * representation (some would want to pack {@link ListZone} into * {@link CoordPackerZone}s when serializing). I find that overzealous for a * simple interface. If you want your zones to be be packed when serialized, * create {@link CoordPackerZone} yourself. In squidlib-extra, GreasedRegions are * given slightly special treatment during that JSON-like serialization so they * avoid repeating certain information, but they are still going to be larger than * compressed short arrays from CoordPacker. * </p> * <p> * While CoordPacker produces short arrays that can be wrapped in CoordPackerZone * objects, and a List of Coord can be similarly wrapped in a ListZone object, * GreasedRegion extends {@link Zone.Skeleton} and so implements Zone itself. * Unlike CoordPackerZone, which is immutable in practice (changing the short * array reference is impossible and changing the elements rarely works as * planned), GreasedRegion is mutable for performance reasons, and may need copies * to be created if you want to keep around older GreasedRegions. * </p> * * <p> * The correct method to implement a {@link Zone} efficiently is to first try * implementing the interface directly, looking at each method and thinking * whether you can do something smart for it. Once you've inspected all methods, * then extend {@link Zone.Skeleton} (instead of Object in the first place) so * that it'll fill for you the methods for which you cannot provide a smart * implementation. * </p> * * @author smelC * @see squidpony.squidmath.CoordPacker * @see squidpony.squidmath.GreasedRegion */ public interface Zone extends Serializable, Iterable<Coord> { /** * @return Whether this zone is empty. */ boolean isEmpty(); /** * @return The number of cells that this zone contains (the size * {@link #getAll()}). */ int size(); /** * @param x * @param y * @return Whether this zone contains the coordinate (x,y). */ boolean contains(int x, int y); /** * @param c * @return Whether this zone contains {@code c}. */ boolean contains(Coord c); /** * @param other * @return true if all cells of {@code other} are in {@code this}. */ boolean contains(Zone other); /** * @param other * @return true if {@code this} and {@code other} have a common cell. */ boolean intersectsWith(Zone other); /** * @return The approximate center of this zone, or null if this zone * is empty. */ /* @Nullable */ Coord getCenter(); /** * @return The distance between the leftmost cell and the rightmost cell, or * anything negative if {@code this} zone is empty; may be 0 if all cells * are in one vertical line. */ int getWidth(); /** * @return The distance between the topmost cell and the lowest cell, or * anything negative if {@code this} zone is empty; may be 0 if all cells * are in one horizontal line. */ int getHeight(); /** * @return The approximation of the zone's diagonal, using * {@link #getWidth()} and {@link #getHeight()}. */ double getDiagonal(); /** * @param smallestOrBiggest if true, finds the smallest x-coordinate value; * if false, finds the biggest. * @return The x-coordinate of the Coord within {@code this} that has the * smallest (or biggest) x-coordinate. Or -1 if the zone is empty. */ int xBound(boolean smallestOrBiggest); /** * @param smallestOrBiggest if true, finds the smallest y-coordinate value; * if false, finds the biggest. * @return The y-coordinate of the Coord within {@code this} that has the * smallest (or biggest) y-coordinate. Or -1 if the zone is empty. */ int yBound(boolean smallestOrBiggest); /** * @return All cells in this zone. */ List<Coord> getAll(); /** @return {@code this} shifted by {@code (c.x,c.y)} */ Zone translate(Coord c); /** @return {@code this} shifted by {@code (x,y)} */ Zone translate(int x, int y); /** * @return Cells in {@code this} that are adjacent to a cell not in * {@code this} */ Collection<Coord> getInternalBorder(); /** * Gets a Collection of Coord values that are not in this Zone, but are * adjacent to it, either orthogonally or diagonally. Related to the fringe() * methods in CoordPacker and GreasedRegion, but guaranteed to use 8-way * adjacency and to return a new Collection of Coord. * @return Cells adjacent to {@code this} (orthogonally or diagonally) that * aren't in {@code this} */ Collection<Coord> getExternalBorder(); /** * Gets a new Zone that contains all the Coords in {@code this} plus all * neighboring Coords, which can be orthogonally or diagonally adjacent * to any Coord this has in it. Related to the expand() methods in * CoordPacker and GreasedRegion, but guaranteed to use 8-way adjacency * and to return a new Zone. * @return A variant of {@code this} where cells adjacent to {@code this} * (orthogonally or diagonally) have been added (i.e. it's {@code this} * plus {@link #getExternalBorder()}). */ Zone extend(); /** * A convenience partial implementation. Please try for all new * implementations of {@link Zone} to be subtypes of this class. It usually * prove handy at some point to have a common superclass. * * @author smelC */ abstract class Skeleton implements Zone { private transient Coord center; protected transient int width = -2; protected transient int height = -2; private static final long serialVersionUID = 4436698111716212256L; @Override /* Convenience implementation, feel free to override */ public int size() { return getAll().size(); } @Override /* Convenience implementation, feel free to override */ public boolean contains(int x, int y) { for (Coord in : this) { if (in.x == x && in.y == y) return true; } return false; } @Override /* Convenience implementation, feel free to override */ public boolean contains(Coord c) { return contains(c.x, c.y); } @Override /* Convenience implementation, feel free to override */ public boolean contains(Zone other) { for (Coord c : other) { if (!contains(c)) return false; } return true; } @Override public boolean intersectsWith(Zone other) { final int tsz = size(); final int osz = other.size(); final Iterable<Coord> iteratedOver = tsz < osz ? this : other; final Zone other_ = tsz < osz ? other : this; for (Coord c : iteratedOver) { if (other_.contains(c)) return true; } return false; } @Override /* * Convenience implementation, feel free to override, in particular if * you can avoid allocating the list usually allocated by getAll(). */ public Iterator<Coord> iterator() { return getAll().iterator(); } @Override /* Convenience implementation, feel free to override. */ public int getWidth() { if (width == -2) width = isEmpty() ? -1 : xBound(false) - xBound(true); return width; } @Override /* Convenience implementation, feel free to override. */ public int getHeight() { if (height == -2) height = isEmpty() ? -1 : yBound(false) - yBound(true); return height; } @Override public double getDiagonal() { final int w = getWidth(); final int h = getHeight(); return Math.sqrt((w * w) + (h * h)); } @Override /* Convenience implementation, feel free to override. */ public int xBound(boolean smallestBound) { return smallestBound ? smallest(true) : biggest(true); } @Override /* Convenience implementation, feel free to override. */ public int yBound(boolean smallestBound) { return smallestBound ? smallest(false) : biggest(false); } @Override /* Convenience implementation, feel free to override. */ /* * A possible enhancement would be to check that the center is within * the zone, and if not to return the Coord closest to the center, that * is in the zone . */ public /* @Nullable */ Coord getCenter() { if (center == null) { /* Need to compute it */ if (isEmpty()) return null; int x = 0, y = 0; float nb = 0; for (Coord c : this) { x += c.x; y += c.y; nb++; } /* Remember it */ center = Coord.get(Math.round(x / nb), Math.round(y / nb)); } return center; } @Override /* Convenience implementation, feel free to override. */ public Zone translate(Coord c) { return translate(c.x, c.y); } @Override /* Convenience implementation, feel free to override. */ public Zone translate(int x, int y) { final List<Coord> initial = getAll(); final int sz = initial.size(); final List<Coord> shifted = new ArrayList<Coord>(sz); for (int i = 0; i < sz; i++) { final Coord c = initial.get(i); shifted.add(Coord.get(c.x + x, c.y + y)); } assert shifted.size() == sz; return new ListZone(shifted); } @Override /* Convenience implementation, feel free to override. */ public Collection<Coord> getInternalBorder() { return size() <= 1 ? getAll() : Helper.border(getAll(), null); } @Override /* Convenience implementation, feel free to override. */ public Collection<Coord> getExternalBorder() { final int sz = size(); final List<Coord> result = new ArrayList<Coord>(sz); final List<Coord> internalBorder = sz <= 1 ? getAll() : Helper.border(getAll(), null); final int ibsz = internalBorder.size(); for (int i = 0; i < ibsz; i++) { final Coord b = internalBorder.get(i); for (Direction dir : Direction.OUTWARDS) { final Coord borderNeighbor = b.translate(dir); if (!contains(borderNeighbor)) result.add(borderNeighbor); } } return result; } @Override /* Convenience implementation, feel free to override. */ public Zone extend() { final List<Coord> list = new ArrayList<Coord>(getAll()); list.addAll(getExternalBorder()); return new ListZone(list); } private int smallest(boolean checkX) { if (isEmpty()) return -1; int min = Integer.MAX_VALUE; for (Coord c : this) { final int val = checkX ? c.x : c.y; if (val < min) min = val; } return min; } private int biggest(boolean checkX) { int max = -1; for (Coord c : this) { final int val = checkX ? c.x : c.y; if (max < val) max = val; } return max; } } final class Helper { private static boolean hasANeighborNotIn(Coord c, Collection<Coord> others) { for (Direction dir : Direction.OUTWARDS) { if (!others.contains(c.translate(dir))) return true; } return false; } /** * An easy way to get the Coord items in a List of Coord that are at the edge of the region, using 8-way * adjacency (a corner is adjacent to both orthogonal and diagonal neighbors). This is not the most * efficient way to do this; If you find you need to do more complicated manipulations of regions or are * calling this method often, consider using {@link squidpony.squidmath.GreasedRegion}, which should be * significantly faster and has better support for more intricate alterations on an area of Coords. * @param zone a List of Coord representing a region * @param buffer The list to fill if non null (i.e. if non-null, it is * returned). If null, a fresh list will be allocated and * returned. * @return Elements in {@code zone} that are neighbors to an element not in {@code zone}. */ public static List<Coord> border(final List<Coord> zone, /* @Nullable */ List<Coord> buffer) { final int zsz = zone.size(); final List<Coord> border = buffer == null ? new ArrayList<Coord>(zsz / 4) : buffer; for (int i = 0; i < zsz; i++) { final Coord c = zone.get(i); if (hasANeighborNotIn(c, zone)) border.add(c); } return border; } } }
4,642
437
// is this app compiled for android ? #define ANDROID_VERSION // if I am not on dnroid, here's the // target resolutions to test with the app.... // HD 1080p //#define TARGET_RESOLUTION_W ( 1080*0.5 ) //#define TARGET_RESOLUTION_H ( 1920*0.5 ) // nexus 4 resolution 1280 x 768 #define TARGET_RESOLUTION_W ( 768*0.5 ) #define TARGET_RESOLUTION_H ( 1280*0.5 )
136
1,520
from __future__ import absolute_import #overrides from allennlp.common.util import JsonDict from allennlp.data import Instance from allennlp.predictors.predictor import Predictor class DecomposableAttentionPredictor(Predictor): u""" Predictor for the :class:`~allennlp.models.bidaf.DecomposableAttention` model. """ def predict(self, premise , hypothesis ) : u""" Predicts whether the hypothesis is entailed by the premise text. Parameters ---------- premise : ``str`` A passage representing what is assumed to be true. hypothesis : ``str`` A sentence that may be entailed by the premise. Returns ------- A dictionary where the key "label_probs" determines the probabilities of each of [entailment, contradiction, neutral]. """ return self.predict_json({u"premise" : premise, u"hypothesis": hypothesis}) #overrides def _json_to_instance(self, json_dict ) : u""" Expects JSON that looks like ``{"premise": "...", "hypothesis": "..."}``. """ premise_text = json_dict[u"premise"] hypothesis_text = json_dict[u"hypothesis"] return self._dataset_reader.text_to_instance(premise_text, hypothesis_text) DecomposableAttentionPredictor = Predictor.register(u'textual-entailment')(DecomposableAttentionPredictor)
580
1,510
/* * 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.drill.metastore.rdbms.transform; import org.apache.drill.metastore.metadata.MetadataType; import org.apache.drill.metastore.operate.Delete; import org.apache.drill.metastore.rdbms.operate.RdbmsOperation; import org.jooq.Record; import java.util.List; import java.util.Set; /** * Provides various methods for RDBMS Metastore data, filters, operations transformation. * * @param <T> Metastore component metadata type */ public interface Transformer<T> { /** * Returns set of metadata mappers corresponding to the given metadata types. * * @param metadataTypes set of metadata types * @return set of metadata mappers */ Set<MetadataMapper<T, ? extends Record>> toMappers(Set<MetadataType> metadataTypes); /** * Returns metadata mappers corresponding to the given metadata type. * * @param metadataType metadata type * @return metadata mapper */ MetadataMapper<T, ? extends Record> toMapper(MetadataType metadataType); /** * Converts given list of Metastore component metadata units into * RDBMS Metastore overwrite operations. * * @param units Metastore metadata units * @return list of RDBMS Metastore overwrite operations */ List<RdbmsOperation.Overwrite> toOverwrite(List<T> units); /** * Converts Metastore delete operation holder into list of * RDBMS Metastore delete operations. * * @param delete Metastore delete operation holder * @return list of RDBMS Metastore delete operations */ List<RdbmsOperation.Delete> toDelete(Delete delete); /** * Creates list of RDBMS Metastore delete operations which will * delete all data from corresponding Metastore component tables. * * @return list of RDBMS Metastore delete operations */ List<RdbmsOperation.Delete> toDeleteAll(); }
747
1,772
{ "vulnerabilities": [], "ok": true, "dependencyCount": 0, "org": "myorg", "policy": "# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.\nversion: v1.19.0\nignore: {}\npatch: {}\n", "isPrivate": true, "licensesPolicy": { "severities": {}, "orgLicenseRules": {} }, "packageManager": "maven", "ignoreSettings": { "adminOnly": false, "reasonRequired": false, "disregardFilesystemIgnores": false }, "summary": "No known vulnerabilities", "filesystemPolicy": false, "uniqueCount": 0, "projectName": "com.test:maven-profiles", "displayTargetFile": "pom.xml", "path": "C:\\workspace" }
250
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. #ifndef CHROME_BROWSER_UI_COCOA_PROFILES_AVATAR_ICON_CONTROLLER_H_ #define CHROME_BROWSER_UI_COCOA_PROFILES_AVATAR_ICON_CONTROLLER_H_ #import <AppKit/AppKit.h> #import "base/mac/scoped_nsobject.h" #import "chrome/browser/ui/cocoa/profiles/avatar_base_controller.h" class Browser; // This view controller manages the image that sits in the top of the window // frame in Incognito, the spy dude. For regular and guest profiles, // AvatarButtonController is used instead. @interface AvatarIconController : AvatarBaseController { } // Designated initializer. - (id)initWithBrowser:(Browser*)browser; @end #endif // CHROME_BROWSER_UI_COCOA_PROFILES_AVATAR_ICON_CONTROLLER_H_
308
582
#!/usr/bin/python from Qt import QtCore, QtWidgets from .stylesheet import STYLE_QMENU class BaseMenu(QtWidgets.QMenu): def __init__(self, *args, **kwargs): super(BaseMenu, self).__init__(*args, **kwargs) self.setStyleSheet(STYLE_QMENU) self.node_class = None self.graph = None # disable for issue #142 # def hideEvent(self, event): # super(BaseMenu, self).hideEvent(event) # for a in self.actions(): # if hasattr(a, 'node_id'): # a.node_id = None def get_menu(self, name, node_id=None): for action in self.actions(): menu = action.menu() if not menu: continue if menu.title() == name: return menu if node_id and menu.node_class: node = menu.graph.get_node_by_id(node_id) if isinstance(node, menu.node_class): return menu def get_menus(self, node_class): menus = [] for action in self.actions(): menu = action.menu() if menu.node_class: if issubclass(menu.node_class, node_class): menus.append(menu) return menus class GraphAction(QtWidgets.QAction): executed = QtCore.Signal(object) def __init__(self, *args, **kwargs): super(GraphAction, self).__init__(*args, **kwargs) self.graph = None self.triggered.connect(self._on_triggered) def _on_triggered(self): self.executed.emit(self.graph) def get_action(self, name): for action in self.qmenu.actions(): if not action.menu() and action.text() == name: return action class NodeAction(GraphAction): executed = QtCore.Signal(object, object) def __init__(self, *args, **kwargs): super(NodeAction, self).__init__(*args, **kwargs) self.node_id = None def _on_triggered(self): node = self.graph.get_node_by_id(self.node_id) self.executed.emit(self.graph, node)
991
412
<gh_stars>100-1000 import logging import os import re from graphbrain.cognition.agent import Agent from graphbrain.cognition.agents.txt_parser import parse_text def build_sequence_name(path, name): seq_name = '|'.join((path, name)) seq_name = seq_name.lower() seq_name = seq_name.replace('/', '|') seq_name = seq_name.replace(' ', '-') seq_name = re.sub('[^a-z0-9\_\-|]+', '', seq_name) return seq_name class DirParser(Agent): def __init__(self, name, progress_bar=True, logging_level=logging.INFO): super().__init__( name, progress_bar=progress_bar, logging_level=logging_level) self.sequences = [] def run(self): indir = self.system.get_indir(self) parser = self.system.get_parser(self) for dirpath, _, filenames in os.walk(indir): path = dirpath[len(indir) + 1:] for filename in filenames: name, extension = os.path.splitext(filename) if extension == '.txt': while extension != '': name, extension = os.path.splitext(name) sequence = build_sequence_name(path, name) self.sequences.append(sequence) infile = os.path.join(dirpath, filename) print(sequence) for op in parse_text(infile, parser, sequence): yield op def report(self): sequences = '\n'.join(self.sequences) return '{}\n\nSequences created:\n{}'.format( super().report(), sequences)
752
1,062
<filename>MailHeaders/Catalina/MailFW/_MFProgressHandlerMonitorContext.h // // Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> #import <MailFW/MFQueryProgressMonitor-Protocol.h> @class MCActivityMonitor, NSString; @protocol MFQueryProgressMonitor; @interface _MFProgressHandlerMonitorContext : NSObject <MFQueryProgressMonitor> { id <MFQueryProgressMonitor> _progressMonitor; // 8 = 0x8 MCActivityMonitor *_activityMonitor; // 16 = 0x10 } @property(nonatomic) __weak MCActivityMonitor *activityMonitor; // @synthesize activityMonitor=_activityMonitor; @property(nonatomic) __weak id <MFQueryProgressMonitor> progressMonitor; // @synthesize progressMonitor=_progressMonitor; // - (void).cxx_destruct; // IMP=0x0000000000109d12 @property(readonly, nonatomic) BOOL shouldCancel; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
352
309
<reponame>ishine/deepx_core // Copyright 2019 the deepx authors. // Author: <NAME> (<EMAIL>) // #include <deepx_core/dx_log.h> #include <deepx_core/graph/graph.h> #include <deepx_core/graph/graph_node.h> #include <deepx_core/graph/op_context.h> #include <deepx_core/graph/tensor_map.h> #include <deepx_core/tensor/data_type.h> #include <cmath> #include <iostream> #include <random> #include <vector> namespace deepx_core { namespace { class Main : public DataType { public: static int main() { std::default_random_engine engine; Graph graph; TensorMap param; // Initialize graph: self attention. int m = 2, k = 3, n = 4; InstanceNode X("X", Shape(-1, m, k), TENSOR_TYPE_TSR); VariableNode Wq("Wq", Shape(k, n), TENSOR_TYPE_TSR); VariableNode Wk("Wk", Shape(k, n), TENSOR_TYPE_TSR); VariableNode Wv("Wv", Shape(k, n), TENSOR_TYPE_TSR); ConstantNode C("C", Shape(1), 1 / std::sqrt(1.0 * n)); MatmulNode Q("Q", &X, &Wq); MatmulNode K("K", &X, &Wk); MatmulNode V("V", &X, &Wv); BatchGEMMNode Z1("Z1", &Q, &K, 0, 1); BroadcastMulNode Z2("Z2", &Z1, &C); SoftmaxNode Z3("Z3", &Z2, -1); BatchGEMMNode Z4("Z4", &Z3, &V, 0, 0); DXCHECK_THROW(graph.Compile({&Z4}, 0)); // Initialize param. auto& _Wq = param.insert<tsr_t>(Wq.name()); _Wq.resize(Wq.shape()); _Wq.randn(engine); auto& _Wk = param.insert<tsr_t>(Wk.name()); _Wk.resize(Wk.shape()); _Wk.randn(engine); auto& _Wv = param.insert<tsr_t>(Wv.name()); _Wv.resize(Wv.shape()); _Wv.randn(engine); // Initialize op context. OpContext op_context; op_context.Init(&graph, &param); DXCHECK_THROW(op_context.InitOp(std::vector<int>{0}, -1)); // Input, forward, output. for (int i = 0; i < 3; ++i) { auto& _X = op_context.mutable_inst()->insert<tsr_t>(X.name()); _X.resize(2 + i, m, k); _X.randn(engine); op_context.InitForward(); op_context.Forward(); const auto& _Z4 = op_context.hidden().get<tsr_t>(Z4.name()); std::cout << "Z4=" << _Z4 << std::endl; } return 0; } }; } // namespace } // namespace deepx_core int main() { return deepx_core::Main::main(); }
1,021
1,195
from pymatting.alpha.estimate_alpha_lkm import estimate_alpha_lkm from pymatting.alpha.estimate_alpha_lbdm import estimate_alpha_lbdm from pymatting.alpha.estimate_alpha_rw import estimate_alpha_rw from pymatting.alpha.estimate_alpha_knn import estimate_alpha_knn from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf as estimate_alpha
138
884
<gh_stars>100-1000 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. package com.microsoft.commondatamodel.objectmodel.persistence.cdmfolder.backcompentitydeclaration; import com.microsoft.commondatamodel.objectmodel.TestHelper; import com.microsoft.commondatamodel.objectmodel.cdm.CdmCorpusDefinition; import com.microsoft.commondatamodel.objectmodel.cdm.CdmManifestDefinition; import com.microsoft.commondatamodel.objectmodel.persistence.cdmfolder.ManifestPersistence; import com.microsoft.commondatamodel.objectmodel.persistence.cdmfolder.types.ManifestContent; import com.microsoft.commondatamodel.objectmodel.resolvedmodel.ResolveContext; import com.microsoft.commondatamodel.objectmodel.utilities.JMapper; import java.io.File; import java.io.IOException; import org.testng.Assert; import org.testng.annotations.Test; public class BackCompEntityDeclarationTest { /** * The path between TestDataPath and TestName. */ private final String TESTS_SUBPATH = new File( new File("persistence", "cdmfolder"), "backcompentitydeclaration" ).toString(); /** * Test load legacy entity declaration. */ @Test public void testLoadLegacyEntityDeclaration() throws IOException, InterruptedException { final String content = TestHelper.getInputFileContent( TESTS_SUBPATH, "testLoadLegacyEntityDeclaration", "entities.manifest.cdm.json"); final ManifestContent jsonContent = JMapper.MAP.readValue(content, ManifestContent.class); final CdmManifestDefinition cdmManifest = ManifestPersistence.fromObject( new ResolveContext(new CdmCorpusDefinition()), "", "", "", jsonContent); // Local entity declaration. Assert.assertEquals(cdmManifest.getEntities().get(0).getEntityPath(), "testPath"); // Referenced entity declaration. Assert.assertEquals( cdmManifest.getEntities().get(1).getEntityPath(), "Account.cdm.json/Account"); } }
716
474
/*************************************************************************** * JNI ***************************************************************************/ #include "glm/glm.hpp" #include "glm/gtc/type_ptr.hpp" #include "objects/components/bone.h" #include "util/gvr_jni.h" namespace gvr { extern "C" { JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeBone_ctor(JNIEnv * env, jobject obj); JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeBone_getComponentType(JNIEnv * env, jobject clz); JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_setName(JNIEnv * env, jobject clz, jlong ptr, jstring name); JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_setOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr, jfloatArray jOffsetMatrix); JNIEXPORT jfloatArray JNICALL Java_org_gearvrf_NativeBone_getOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr); JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_setFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr, jfloatArray jOffsetMatrix); JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_getFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr, jobject jFloatBuffer); } // extern "C" JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeBone_ctor(JNIEnv * env, jobject clz) { return reinterpret_cast<jlong>(new Bone()); } JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeBone_getComponentType(JNIEnv * env, jobject clz) { return Bone::getComponentType(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_setName(JNIEnv * env, jobject clz, jlong ptr, jstring name) { Bone* bone = reinterpret_cast<Bone*>(ptr); if (!name || !env->GetStringLength(name)) { bone->setName(""); return; } const char* charName = env->GetStringUTFChars(name, NULL); bone->setName(charName); env->ReleaseStringUTFChars(name, charName); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_setOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr, jfloatArray jOffsetMatrix) { Bone* bone = reinterpret_cast<Bone*>(ptr); if (!jOffsetMatrix) return; jfloat* mat_arr = env->GetFloatArrayElements(jOffsetMatrix, JNI_FALSE); glm::mat4 matrix = glm::make_mat4x4(mat_arr); bone->setOffsetMatrix(matrix); env->ReleaseFloatArrayElements(jOffsetMatrix, mat_arr, JNI_ABORT); } JNIEXPORT jfloatArray JNICALL Java_org_gearvrf_NativeBone_getOffsetMatrix(JNIEnv * env, jobject clz, jlong ptr) { Bone* bone = reinterpret_cast<Bone*>(ptr); glm::mat4 matrix; if (bone) { matrix = bone->getOffsetMatrix(); } jsize size = sizeof(matrix) / sizeof(jfloat); jfloatArray jmatrix = env->NewFloatArray(size); env->SetFloatArrayRegion(jmatrix, 0, size, glm::value_ptr(matrix)); return jmatrix; } JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_setFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr, jfloatArray jTransform) { Bone* bone = reinterpret_cast<Bone*>(ptr); if (!jTransform) return; jfloat* mat_arr = env->GetFloatArrayElements(jTransform, JNI_FALSE); glm::mat4 matrix(glm::make_mat4x4(mat_arr)); bone->setFinalTransformMatrix(matrix); env->ReleaseFloatArrayElements(jTransform, mat_arr, JNI_ABORT); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeBone_getFinalTransformMatrix(JNIEnv * env, jobject clz, jlong ptr, jobject buffer) { Bone* bone = reinterpret_cast<Bone*>(ptr); glm::mat4 matrix = bone->getFinalTransformMatrix(); float *ptrBuffer = static_cast<float*>(env->GetDirectBufferAddress(buffer)); std::memcpy(ptrBuffer, glm::value_ptr(matrix), sizeof matrix); } } // namespace gvr
1,483
504
/*********************************************************************** * * Copyright (c) Geoworks 1994 -- All Rights Reserved * * GEOWORKS CONFIDENTIAL * * PROJECT: TCP/IP Driver * MODULE: ICMP * FILE: icmp.h * * AUTHOR: <NAME>: Jul 6, 1994 * * REVISION HISTORY: * Date Name Description * ---- ---- ----------- * 7/ 6/94 jwu Initial version * * DESCRIPTION: * Definitions for ICMP. * * * $Id: icmp.h,v 1.1 97/04/18 11:57:05 newdeal Exp $ * ***********************************************************************/ /* * Copyright (c) 1982, 1986, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * Interface Control Message Protocol Definitions. * Per RFC 792, September 1981. */ #ifndef _TCPIPICMP_H_ #define _TCPIPICMP_H_ /* --------------------------------------------------------------------------- * * Structure of an ICMP message. * -------------------------------------------------------------------------- */ struct icmp { byte icmp_type; /* type of message */ byte icmp_code; /* type of sub code */ word icmp_cksum; /* ones complement checksum of msg */ union { byte ih_pptr; /* ICMP_PARAMPROB */ dword ih_gwaddr; /* ICMP_REDIRECT */ struct ih_idseq { word icd_id; word icd_seq; } ih_idseq; dword ih_void; /* must be zero */ } icmp_hun; /* header for ICMP data */ union { struct id_ts { /* timestamp option */ dword its_otime; /* originate timestamp */ dword its_rtime; /* receive timestamp */ dword its_ttime; /* transmit timestamp */ } id_ts; struct id_ip { /* problem with received IP datagram */ struct ip idi_ip; /* options and then 64 bits of data */ } id_ip; dword id_mask; char id_data[1]; } icmp_dun; /* data portion of ICMP message */ }; /* * some defines to simplify access to header union in ICMP struct */ #define icmp_pptr icmp_hun.ih_pptr #define icmp_gwaddr icmp_hun.ih_gwaddr #define icmp_id icmp_hun.ih_idseq.icd_id #define icmp_seq icmp_hun.ih_idseq.icd_seq #define icmp_void icmp_hun.ih_void #define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void #define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu /* some defines to simplify access to data union */ #define icmp_otime icmp_dun.id_ts.its_otime #define icmp_rtime icmp_dun.id_ts.its_rtime #define icmp_ttime icmp_dun.id_ts.its_ttime #define icmp_ip icmp_dun.id_ip.idi_ip #define icmp_mask icmp_dun.id_mask #define icmp_data icmp_dun.id_data /* --------------------------------------------------------------------------- * * Definition of ICMP type and code field values. * --------------------------------------------------------------------------- */ #define ICMP_ECHOREPLY 0 /* echo reply */ #define ICMP_UNREACH 3 /* dest unreachable, codes: */ #define ICMP_UNREACH_NET 0 /* bad net */ #define ICMP_UNREACH_HOST 1 /* bad host */ #define ICMP_UNREACH_PROTOCOL 2 /* bad protocol */ #define ICMP_UNREACH_PORT 3 /* bad port */ #define ICMP_UNREACH_NEEDFRAG 4 /* IP_DF caused drop */ #define ICMP_UNREACH_SRCFAIL 5 /* src route failed */ #define ICMP_UNREACH_NET_UNKNOWN 6 /* unknown net */ #define ICMP_UNREACH_HOST_UNKNOWN 7 /* unknown host */ #define ICMP_UNREACH_ISOLATED 8 /* src host isolated */ #define ICMP_UNREACH_NET_PROHIB 9 /* prohibited access */ #define ICMP_UNREACH_HOST_PROHIB 10 /* ditto */ #define ICMP_UNREACH_TOSNET 11 /* bad tos for net */ #define ICMP_UNREACH_TOSHOST 12 /* bad tos for host */ #define ICMP_SOURCEQUENCH 4 /* packet lost, slow down */ #define ICMP_REDIRECT 5 /* shorter route, codes: */ #define ICMP_REDIRECT_NET 0 /* for network */ #define ICMP_REDIRECT_HOST 1 /* for host */ #define ICMP_REDIRECT_TOSNET 2 /* for tos and net */ #define ICMP_REDIRECT_TOSHOST 3 /* for tos and host */ #define ICMP_ECHO 8 /* echo service */ #define ICMP_ROUTERADVERT 9 /* router advertisement */ #define ICMP_ROUTERSOLICIT 10 /* router solicitation */ #define ICMP_TIMXCEED 11 /* time exceeded, code: */ #define ICMP_TIMXCEED_INTRANS 0 /* ttl==0 in transit */ #define ICMP_TIMXCEED_REASS 1 /* ttl==0 in reass */ #define ICMP_PARAMPROB 12 /* ip header bad */ #define ICMP_PARAMPROB_OPTABSENT 1 /* req. opt. absent */ #define ICMP_TSTAMP 13 /* timestamp request */ #define ICMP_TSTAMPREPLY 14 /* timestamp reply */ #define ICMP_IREQ 15 /* information request */ #define ICMP_IREQREPLY 16 /* information reply */ #define ICMP_MASKREQ 17 /* address mask request */ #define ICMP_MASKREPLY 18 /* address mask reply */ #define ICMP_MAXTYPE 18 #define ICMP_INFOTYPE(type) \ ((type) == ICMP_ECHOREPLY || (type) == ICMP_ECHO || \ (type) == ICMP_ROUTERADVERT || (type) == ICMP_ROUTERSOLICIT || \ (type) == ICMP_TSTAMP || (type) == ICMP_TSTAMPREPLY || \ (type) == ICMP_IREQ || (type) == ICMP_IREQREPLY || \ (type) == ICMP_MASKREQ || (type) == ICMP_MASKREPLY) /* --------------------------------------------------------------------------- * * Lower bounds on packet lengths for various types. * For generating ICMP error messages in response to bad IP datagrams, * we must first ensure that the datagram is large enough to contain the * returned IP header. Only then can we do the check to see if 64 bits * of datagram data have been returned, since we need to check the returned * IP header length. * --------------------------------------------------------------------------- */ #define ICMP_MAXDATA 8 /* max data bytes to include */ #define ICMP_MINLEN 8 /* abs minimum header */ #define ICMP_TSLEN (8 + 3 * sizeof (dword)) /* timestamp */ #define ICMP_MASKLEN 12 /* address mask */ #define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) /* min */ #define ICMP_ADVLEN(p) (8 + ((p)->icmp_ip.ip_hl << 2) + 8) /* N.B.: must separately check that ip_hl >= 5 */ extern void IcmpError(MbufHeader *n, word type, word code); extern void IcmpInput(optr dataBuffer, word hlen); extern void IcmpReflect(MbufHeader *m, optr icmpBuf); extern void IcmpSend(MbufHeader *m, optr icmpBuf); extern word IcmpDecode(word code); /*---------------------------------------------------------------------- * * Variables related to this implementation of the internet control * message protocol. --------------------------------------------------------------------- */ #ifdef LOG_STATS struct icmpstat { /* statistics related to icmp packets generated */ word icps_error; /* # of calls to icmp_error */ word icps_oldicmp; /* no error 'cuz old was icmp */ word icps_outhist[ICMP_MAXTYPE + 1]; /* statistics related to input messages processed */ word icps_badcode; /* icmp_code out of range */ word icps_tooshort; /* packet < ICMP_MINLEN */ word icps_badsum; /* bad checksum */ word icps_badlen; /* calculated bound mismatch */ word icps_reflect; /* number of responses */ word icps_inhist[ICMP_MAXTYPE + 1]; word icps_packets; /* number of icmp packets rcvd or sent */ }; extern struct icmpstat icmpstat; #endif /* LOG_STATS */ #endif /* _TCPIPICMP_H_ */
3,556
1,132
#include "gb-include.h" #include "DiskPageCache.h" #include "RdbCache.h" // key = 24 bytes = 192 bits // vvvvvvvv vvvvvvvv vvvvvvvv vvvvvvvv v = vfd = unique file handle // vvvvvvvv vvvvvvvv vvvvvvvv vvvvvvvv // ffffffff ffffffff ffffffff ffffffff f = file read offset // ffffffff ffffffff ffffffff ffffffff // bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb b = bytes to read // bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb DiskPageCache::DiskPageCache () { } DiskPageCache::~DiskPageCache() { reset(); } void DiskPageCache::reset() { m_rc.reset(); } bool DiskPageCache::init ( const char *dbname , char rdbId, int64_t maxMem , int32_t pageSize ) { reset(); snprintf(m_dbname,62,"pg-%s",dbname ); m_pageSize = pageSize; m_rdbId = rdbId; m_enabled = true; // disable for now return true; return m_rc.init( maxMem , -1 , // fixedDataSize (-1->variable) false , // supportlists? // see RdbMap.h *PAGE_SIZE. it can be 1k or 32k so // we pick 4k to be in the middle maxMem / m_pageSize , // maxCacheNodes false , // usehalfkeys? m_dbname , false , // loadfromdisk? 24 , // 24 byte key 12 , // data key size? -1 ); // num ptrs max } key192_t makePCKey ( int64_t vfd , int64_t offset , int64_t readSize ) { key192_t k; k.n2 = vfd; k.n1 = readSize; k.n0 = offset; return k; } char *DiskPageCache::getPages ( int64_t vfd , int64_t offset , int64_t readSize ) { if ( ! m_enabled ) return NULL; // disable for now return NULL; // make the key key192_t k = makePCKey ( vfd , offset , readSize ); char *rec = NULL; int32_t recSize; bool found = m_rc.getRecord ( (collnum_t)0 , // collnum (char *)&k , &rec , &recSize , true , // doCopy? for now, yes -1 , // maxAge, none, permanent vfd true , // incCounts - stats hits/misses NULL , // cachedTimeptr true ); // promote rec? if ( ! found ) return NULL; // sanity if ( recSize != readSize ) { char *xx=NULL;*xx=0; } return rec; } // returns true if successfully added to the cache, false otherwise bool DiskPageCache::addPages ( int64_t vfd , int64_t offset , int64_t readSize , char *buf , char niceness ) { if ( ! m_enabled ) return false; // disable for now return true; // make the key key192_t k = makePCKey ( vfd , offset , readSize ); time_t now = getTimeLocal(); return m_rc.addRecord ( (collnum_t)0 , // collnum (char *)&k , buf , readSize , NULL , // rec2 0 , // recsize2 now , //timestamp NULL ); // return rec ptr }
1,174
631
import os import app import unittest from app.models import User class ClientTestCase(unittest.TestCase): def setUp(self): self.app = app.create_app('testing') self.app_context = self.app.app_context() self.app_context.push() app.db.create_all() self.client = self.app.test_client() def tearDown(self): app.db.session.remove() app.db.drop_all() self.app_context.pop() def add_user(self): u = User(email='<EMAIL>', password='password', confirmed=True) app.db.session.add(u) app.db.session.commit() return u def add_other_user(self): u = User( email='<EMAIL>', password='password', confirmed=True) app.db.session.add(u) app.db.session.commit() return u def login(self, email, password): return self.client.post('/auth/login', data=dict( email=email, password=password ), follow_redirects=True) def logout(self): return self.client.get('/auth/logout', follow_redirects=True)
495
980
<reponame>leekayden/jcodec package org.jcodec.codecs.vpx.vp9; public class Scan { private static final int[] default_scan_4x4 = { 0, 4, 1, 5, 8, 2, 12, 9, 3, 6, 13, 10, 7, 14, 11, 15 }; private static final int[] col_scan_4x4 = { 0, 4, 8, 1, 12, 5, 9, 2, 13, 6, 10, 3, 7, 14, 11, 15 }; private static final int[] row_scan_4x4 = { 0, 1, 4, 2, 5, 3, 6, 8, 9, 7, 12, 10, 13, 11, 14, 15, }; private static final int[] default_scan_8x8 = { 0, 8, 1, 16, 9, 2, 17, 24, 10, 3, 18, 25, 32, 11, 4, 26, 33, 19, 40, 12, 34, 27, 5, 41, 20, 48, 13, 35, 42, 28, 21, 6, 49, 56, 36, 43, 29, 7, 14, 50, 57, 44, 22, 37, 15, 51, 58, 30, 45, 23, 52, 59, 38, 31, 60, 53, 46, 39, 61, 54, 47, 62, 55, 63, }; private static final int[] col_scan_8x8 = { 0, 8, 16, 1, 24, 9, 32, 17, 2, 40, 25, 10, 33, 18, 48, 3, 26, 41, 11, 56, 19, 34, 4, 49, 27, 42, 12, 35, 20, 57, 50, 28, 5, 43, 13, 36, 58, 51, 21, 44, 6, 29, 59, 37, 14, 52, 22, 7, 45, 60, 30, 15, 38, 53, 23, 46, 31, 61, 39, 54, 47, 62, 55, 63, }; private static final int[] row_scan_8x8 = { 0, 1, 2, 8, 9, 3, 16, 10, 4, 17, 11, 24, 5, 18, 25, 12, 19, 26, 32, 6, 13, 20, 33, 27, 7, 34, 40, 21, 28, 41, 14, 35, 48, 42, 29, 36, 49, 22, 43, 15, 56, 37, 50, 44, 30, 57, 23, 51, 58, 45, 38, 52, 31, 59, 53, 46, 60, 39, 61, 47, 54, 55, 62, 63, }; private static final int[] default_scan_16x16 = { 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 64, 34, 49, 19, 65, 80, 50, 4, 35, 66, 20, 81, 96, 51, 5, 36, 82, 97, 67, 112, 21, 52, 98, 37, 83, 113, 6, 68, 128, 53, 22, 99, 114, 84, 7, 129, 38, 69, 100, 115, 144, 130, 85, 54, 23, 8, 145, 39, 70, 116, 101, 131, 160, 146, 55, 86, 24, 71, 132, 117, 161, 40, 9, 102, 147, 176, 162, 87, 56, 25, 133, 118, 177, 148, 72, 103, 41, 163, 10, 192, 178, 88, 57, 134, 149, 119, 26, 164, 73, 104, 193, 42, 179, 208, 11, 135, 89, 165, 120, 150, 58, 194, 180, 27, 74, 209, 105, 151, 136, 43, 90, 224, 166, 195, 181, 121, 210, 59, 12, 152, 106, 167, 196, 75, 137, 225, 211, 240, 182, 122, 91, 28, 197, 13, 226, 168, 183, 153, 44, 212, 138, 107, 241, 60, 29, 123, 198, 184, 227, 169, 242, 76, 213, 154, 45, 92, 14, 199, 139, 61, 228, 214, 170, 185, 243, 108, 77, 155, 30, 15, 200, 229, 124, 215, 244, 93, 46, 186, 171, 201, 109, 140, 230, 62, 216, 245, 31, 125, 78, 156, 231, 47, 187, 202, 217, 94, 246, 141, 63, 232, 172, 110, 247, 157, 79, 218, 203, 126, 233, 188, 248, 95, 173, 142, 219, 111, 249, 234, 158, 127, 189, 204, 250, 235, 143, 174, 220, 205, 159, 251, 190, 221, 175, 236, 237, 191, 206, 252, 222, 253, 207, 238, 223, 254, 239, 255, }; private static final int[] col_scan_16x16 = { 0, 16, 32, 48, 1, 64, 17, 80, 33, 96, 49, 2, 65, 112, 18, 81, 34, 128, 50, 97, 3, 66, 144, 19, 113, 35, 82, 160, 98, 51, 129, 4, 67, 176, 20, 114, 145, 83, 36, 99, 130, 52, 192, 5, 161, 68, 115, 21, 146, 84, 208, 177, 37, 131, 100, 53, 162, 224, 69, 6, 116, 193, 147, 85, 22, 240, 132, 38, 178, 101, 163, 54, 209, 117, 70, 7, 148, 194, 86, 179, 225, 23, 133, 39, 164, 8, 102, 210, 241, 55, 195, 118, 149, 71, 180, 24, 87, 226, 134, 165, 211, 40, 103, 56, 72, 150, 196, 242, 119, 9, 181, 227, 88, 166, 25, 135, 41, 104, 212, 57, 151, 197, 120, 73, 243, 182, 136, 167, 213, 89, 10, 228, 105, 152, 198, 26, 42, 121, 183, 244, 168, 58, 137, 229, 74, 214, 90, 153, 199, 184, 11, 106, 245, 27, 122, 230, 169, 43, 215, 59, 200, 138, 185, 246, 75, 12, 91, 154, 216, 231, 107, 28, 44, 201, 123, 170, 60, 247, 232, 76, 139, 13, 92, 217, 186, 248, 155, 108, 29, 124, 45, 202, 233, 171, 61, 14, 77, 140, 15, 249, 93, 30, 187, 156, 218, 46, 109, 125, 62, 172, 78, 203, 31, 141, 234, 94, 47, 188, 63, 157, 110, 250, 219, 79, 126, 204, 173, 142, 95, 189, 111, 235, 158, 220, 251, 127, 174, 143, 205, 236, 159, 190, 221, 252, 175, 206, 237, 191, 253, 222, 238, 207, 254, 223, 239, 255, }; private static final int[] row_scan_16x16 = { 0, 1, 2, 16, 3, 17, 4, 18, 32, 5, 33, 19, 6, 34, 48, 20, 49, 7, 35, 21, 50, 64, 8, 36, 65, 22, 51, 37, 80, 9, 66, 52, 23, 38, 81, 67, 10, 53, 24, 82, 68, 96, 39, 11, 54, 83, 97, 69, 25, 98, 84, 40, 112, 55, 12, 70, 99, 113, 85, 26, 41, 56, 114, 100, 13, 71, 128, 86, 27, 115, 101, 129, 42, 57, 72, 116, 14, 87, 130, 102, 144, 73, 131, 117, 28, 58, 15, 88, 43, 145, 103, 132, 146, 118, 74, 160, 89, 133, 104, 29, 59, 147, 119, 44, 161, 148, 90, 105, 134, 162, 120, 176, 75, 135, 149, 30, 60, 163, 177, 45, 121, 91, 106, 164, 178, 150, 192, 136, 165, 179, 31, 151, 193, 76, 122, 61, 137, 194, 107, 152, 180, 208, 46, 166, 167, 195, 92, 181, 138, 209, 123, 153, 224, 196, 77, 168, 210, 182, 240, 108, 197, 62, 154, 225, 183, 169, 211, 47, 139, 93, 184, 226, 212, 241, 198, 170, 124, 155, 199, 78, 213, 185, 109, 227, 200, 63, 228, 242, 140, 214, 171, 186, 156, 229, 243, 125, 94, 201, 244, 215, 216, 230, 141, 187, 202, 79, 172, 110, 157, 245, 217, 231, 95, 246, 232, 126, 203, 247, 233, 173, 218, 142, 111, 158, 188, 248, 127, 234, 219, 249, 189, 204, 143, 174, 159, 250, 235, 205, 220, 175, 190, 251, 221, 191, 206, 236, 207, 237, 252, 222, 253, 223, 238, 239, 254, 255, }; private static final int[] default_scan_32x32 = { 0, 32, 1, 64, 33, 2, 96, 65, 34, 128, 3, 97, 66, 160, 129, 35, 98, 4, 67, 130, 161, 192, 36, 99, 224, 5, 162, 193, 68, 131, 37, 100, 225, 194, 256, 163, 69, 132, 6, 226, 257, 288, 195, 101, 164, 38, 258, 7, 227, 289, 133, 320, 70, 196, 165, 290, 259, 228, 39, 321, 102, 352, 8, 197, 71, 134, 322, 291, 260, 353, 384, 229, 166, 103, 40, 354, 323, 292, 135, 385, 198, 261, 72, 9, 416, 167, 386, 355, 230, 324, 104, 293, 41, 417, 199, 136, 262, 387, 448, 325, 356, 10, 73, 418, 231, 168, 449, 294, 388, 105, 419, 263, 42, 200, 357, 450, 137, 480, 74, 326, 232, 11, 389, 169, 295, 420, 106, 451, 481, 358, 264, 327, 201, 43, 138, 512, 482, 390, 296, 233, 170, 421, 75, 452, 359, 12, 513, 265, 483, 328, 107, 202, 514, 544, 422, 391, 453, 139, 44, 234, 484, 297, 360, 171, 76, 515, 545, 266, 329, 454, 13, 423, 203, 108, 546, 485, 576, 298, 235, 140, 361, 330, 172, 547, 45, 455, 267, 577, 486, 77, 204, 362, 608, 14, 299, 578, 109, 236, 487, 609, 331, 141, 579, 46, 15, 173, 610, 363, 78, 205, 16, 110, 237, 611, 142, 47, 174, 79, 206, 17, 111, 238, 48, 143, 80, 175, 112, 207, 49, 18, 239, 81, 113, 19, 50, 82, 114, 51, 83, 115, 640, 516, 392, 268, 144, 20, 672, 641, 548, 517, 424, 393, 300, 269, 176, 145, 52, 21, 704, 673, 642, 580, 549, 518, 456, 425, 394, 332, 301, 270, 208, 177, 146, 84, 53, 22, 736, 705, 674, 643, 612, 581, 550, 519, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178, 147, 116, 85, 54, 23, 737, 706, 675, 613, 582, 551, 489, 458, 427, 365, 334, 303, 241, 210, 179, 117, 86, 55, 738, 707, 614, 583, 490, 459, 366, 335, 242, 211, 118, 87, 739, 615, 491, 367, 243, 119, 768, 644, 520, 396, 272, 148, 24, 800, 769, 676, 645, 552, 521, 428, 397, 304, 273, 180, 149, 56, 25, 832, 801, 770, 708, 677, 646, 584, 553, 522, 460, 429, 398, 336, 305, 274, 212, 181, 150, 88, 57, 26, 864, 833, 802, 771, 740, 709, 678, 647, 616, 585, 554, 523, 492, 461, 430, 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 865, 834, 803, 741, 710, 679, 617, 586, 555, 493, 462, 431, 369, 338, 307, 245, 214, 183, 121, 90, 59, 866, 835, 742, 711, 618, 587, 494, 463, 370, 339, 246, 215, 122, 91, 867, 743, 619, 495, 371, 247, 123, 896, 772, 648, 524, 400, 276, 152, 28, 928, 897, 804, 773, 680, 649, 556, 525, 432, 401, 308, 277, 184, 153, 60, 29, 960, 929, 898, 836, 805, 774, 712, 681, 650, 588, 557, 526, 464, 433, 402, 340, 309, 278, 216, 185, 154, 92, 61, 30, 992, 961, 930, 899, 868, 837, 806, 775, 744, 713, 682, 651, 620, 589, 558, 527, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 993, 962, 931, 869, 838, 807, 745, 714, 683, 621, 590, 559, 497, 466, 435, 373, 342, 311, 249, 218, 187, 125, 94, 63, 994, 963, 870, 839, 746, 715, 622, 591, 498, 467, 374, 343, 250, 219, 126, 95, 995, 871, 747, 623, 499, 375, 251, 127, 900, 776, 652, 528, 404, 280, 156, 932, 901, 808, 777, 684, 653, 560, 529, 436, 405, 312, 281, 188, 157, 964, 933, 902, 840, 809, 778, 716, 685, 654, 592, 561, 530, 468, 437, 406, 344, 313, 282, 220, 189, 158, 996, 965, 934, 903, 872, 841, 810, 779, 748, 717, 686, 655, 624, 593, 562, 531, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 997, 966, 935, 873, 842, 811, 749, 718, 687, 625, 594, 563, 501, 470, 439, 377, 346, 315, 253, 222, 191, 998, 967, 874, 843, 750, 719, 626, 595, 502, 471, 378, 347, 254, 223, 999, 875, 751, 627, 503, 379, 255, 904, 780, 656, 532, 408, 284, 936, 905, 812, 781, 688, 657, 564, 533, 440, 409, 316, 285, 968, 937, 906, 844, 813, 782, 720, 689, 658, 596, 565, 534, 472, 441, 410, 348, 317, 286, 1000, 969, 938, 907, 876, 845, 814, 783, 752, 721, 690, 659, 628, 597, 566, 535, 504, 473, 442, 411, 380, 349, 318, 287, 1001, 970, 939, 877, 846, 815, 753, 722, 691, 629, 598, 567, 505, 474, 443, 381, 350, 319, 1002, 971, 878, 847, 754, 723, 630, 599, 506, 475, 382, 351, 1003, 879, 755, 631, 507, 383, 908, 784, 660, 536, 412, 940, 909, 816, 785, 692, 661, 568, 537, 444, 413, 972, 941, 910, 848, 817, 786, 724, 693, 662, 600, 569, 538, 476, 445, 414, 1004, 973, 942, 911, 880, 849, 818, 787, 756, 725, 694, 663, 632, 601, 570, 539, 508, 477, 446, 415, 1005, 974, 943, 881, 850, 819, 757, 726, 695, 633, 602, 571, 509, 478, 447, 1006, 975, 882, 851, 758, 727, 634, 603, 510, 479, 1007, 883, 759, 635, 511, 912, 788, 664, 540, 944, 913, 820, 789, 696, 665, 572, 541, 976, 945, 914, 852, 821, 790, 728, 697, 666, 604, 573, 542, 1008, 977, 946, 915, 884, 853, 822, 791, 760, 729, 698, 667, 636, 605, 574, 543, 1009, 978, 947, 885, 854, 823, 761, 730, 699, 637, 606, 575, 1010, 979, 886, 855, 762, 731, 638, 607, 1011, 887, 763, 639, 916, 792, 668, 948, 917, 824, 793, 700, 669, 980, 949, 918, 856, 825, 794, 732, 701, 670, 1012, 981, 950, 919, 888, 857, 826, 795, 764, 733, 702, 671, 1013, 982, 951, 889, 858, 827, 765, 734, 703, 1014, 983, 890, 859, 766, 735, 1015, 891, 767, 920, 796, 952, 921, 828, 797, 984, 953, 922, 860, 829, 798, 1016, 985, 954, 923, 892, 861, 830, 799, 1017, 986, 955, 893, 862, 831, 1018, 987, 894, 863, 1019, 895, 924, 956, 925, 988, 957, 926, 1020, 989, 958, 927, 1021, 990, 959, 1022, 991, 1023, }; // Neighborhood 2-tuples for various scans and blocksizes, // in {top, left} order for each position in corresponding scan order. private static final int[] default_scan_4x4_neighbors = { 0, 0, 0, 0, 0, 0, 1, 4, 4, 4, 1, 1, 8, 8, 5, 8, 2, 2, 2, 5, 9, 12, 6, 9, 3, 6, 10, 13, 7, 10, 11, 14, 0, 0, }; private static final int[] col_scan_4x4_neighbors = { 0, 0, 0, 0, 4, 4, 0, 0, 8, 8, 1, 1, 5, 5, 1, 1, 9, 9, 2, 2, 6, 6, 2, 2, 3, 3, 10, 10, 7, 7, 11, 11, 0, 0, }; private static final int[] row_scan_4x4_neighbors = { 0, 0, 0, 0, 0, 0, 1, 1, 4, 4, 2, 2, 5, 5, 4, 4, 8, 8, 6, 6, 8, 8, 9, 9, 12, 12, 10, 10, 13, 13, 14, 14, 0, 0, }; private static final int[] col_scan_8x8_neighbors = { 0, 0, 0, 0, 8, 8, 0, 0, 16, 16, 1, 1, 24, 24, 9, 9, 1, 1, 32, 32, 17, 17, 2, 2, 25, 25, 10, 10, 40, 40, 2, 2, 18, 18, 33, 33, 3, 3, 48, 48, 11, 11, 26, 26, 3, 3, 41, 41, 19, 19, 34, 34, 4, 4, 27, 27, 12, 12, 49, 49, 42, 42, 20, 20, 4, 4, 35, 35, 5, 5, 28, 28, 50, 50, 43, 43, 13, 13, 36, 36, 5, 5, 21, 21, 51, 51, 29, 29, 6, 6, 44, 44, 14, 14, 6, 6, 37, 37, 52, 52, 22, 22, 7, 7, 30, 30, 45, 45, 15, 15, 38, 38, 23, 23, 53, 53, 31, 31, 46, 46, 39, 39, 54, 54, 47, 47, 55, 55, 0, 0, }; private static final int[] row_scan_8x8_neighbors = { 0, 0, 0, 0, 1, 1, 0, 0, 8, 8, 2, 2, 8, 8, 9, 9, 3, 3, 16, 16, 10, 10, 16, 16, 4, 4, 17, 17, 24, 24, 11, 11, 18, 18, 25, 25, 24, 24, 5, 5, 12, 12, 19, 19, 32, 32, 26, 26, 6, 6, 33, 33, 32, 32, 20, 20, 27, 27, 40, 40, 13, 13, 34, 34, 40, 40, 41, 41, 28, 28, 35, 35, 48, 48, 21, 21, 42, 42, 14, 14, 48, 48, 36, 36, 49, 49, 43, 43, 29, 29, 56, 56, 22, 22, 50, 50, 57, 57, 44, 44, 37, 37, 51, 51, 30, 30, 58, 58, 52, 52, 45, 45, 59, 59, 38, 38, 60, 60, 46, 46, 53, 53, 54, 54, 61, 61, 62, 62, 0, 0, }; private static final int[] default_scan_8x8_neighbors = { 0, 0, 0, 0, 0, 0, 8, 8, 1, 8, 1, 1, 9, 16, 16, 16, 2, 9, 2, 2, 10, 17, 17, 24, 24, 24, 3, 10, 3, 3, 18, 25, 25, 32, 11, 18, 32, 32, 4, 11, 26, 33, 19, 26, 4, 4, 33, 40, 12, 19, 40, 40, 5, 12, 27, 34, 34, 41, 20, 27, 13, 20, 5, 5, 41, 48, 48, 48, 28, 35, 35, 42, 21, 28, 6, 6, 6, 13, 42, 49, 49, 56, 36, 43, 14, 21, 29, 36, 7, 14, 43, 50, 50, 57, 22, 29, 37, 44, 15, 22, 44, 51, 51, 58, 30, 37, 23, 30, 52, 59, 45, 52, 38, 45, 31, 38, 53, 60, 46, 53, 39, 46, 54, 61, 47, 54, 55, 62, 0, 0, }; private static final int[] col_scan_16x16_neighbors = { 0, 0, 0, 0, 16, 16, 32, 32, 0, 0, 48, 48, 1, 1, 64, 64, 17, 17, 80, 80, 33, 33, 1, 1, 49, 49, 96, 96, 2, 2, 65, 65, 18, 18, 112, 112, 34, 34, 81, 81, 2, 2, 50, 50, 128, 128, 3, 3, 97, 97, 19, 19, 66, 66, 144, 144, 82, 82, 35, 35, 113, 113, 3, 3, 51, 51, 160, 160, 4, 4, 98, 98, 129, 129, 67, 67, 20, 20, 83, 83, 114, 114, 36, 36, 176, 176, 4, 4, 145, 145, 52, 52, 99, 99, 5, 5, 130, 130, 68, 68, 192, 192, 161, 161, 21, 21, 115, 115, 84, 84, 37, 37, 146, 146, 208, 208, 53, 53, 5, 5, 100, 100, 177, 177, 131, 131, 69, 69, 6, 6, 224, 224, 116, 116, 22, 22, 162, 162, 85, 85, 147, 147, 38, 38, 193, 193, 101, 101, 54, 54, 6, 6, 132, 132, 178, 178, 70, 70, 163, 163, 209, 209, 7, 7, 117, 117, 23, 23, 148, 148, 7, 7, 86, 86, 194, 194, 225, 225, 39, 39, 179, 179, 102, 102, 133, 133, 55, 55, 164, 164, 8, 8, 71, 71, 210, 210, 118, 118, 149, 149, 195, 195, 24, 24, 87, 87, 40, 40, 56, 56, 134, 134, 180, 180, 226, 226, 103, 103, 8, 8, 165, 165, 211, 211, 72, 72, 150, 150, 9, 9, 119, 119, 25, 25, 88, 88, 196, 196, 41, 41, 135, 135, 181, 181, 104, 104, 57, 57, 227, 227, 166, 166, 120, 120, 151, 151, 197, 197, 73, 73, 9, 9, 212, 212, 89, 89, 136, 136, 182, 182, 10, 10, 26, 26, 105, 105, 167, 167, 228, 228, 152, 152, 42, 42, 121, 121, 213, 213, 58, 58, 198, 198, 74, 74, 137, 137, 183, 183, 168, 168, 10, 10, 90, 90, 229, 229, 11, 11, 106, 106, 214, 214, 153, 153, 27, 27, 199, 199, 43, 43, 184, 184, 122, 122, 169, 169, 230, 230, 59, 59, 11, 11, 75, 75, 138, 138, 200, 200, 215, 215, 91, 91, 12, 12, 28, 28, 185, 185, 107, 107, 154, 154, 44, 44, 231, 231, 216, 216, 60, 60, 123, 123, 12, 12, 76, 76, 201, 201, 170, 170, 232, 232, 139, 139, 92, 92, 13, 13, 108, 108, 29, 29, 186, 186, 217, 217, 155, 155, 45, 45, 13, 13, 61, 61, 124, 124, 14, 14, 233, 233, 77, 77, 14, 14, 171, 171, 140, 140, 202, 202, 30, 30, 93, 93, 109, 109, 46, 46, 156, 156, 62, 62, 187, 187, 15, 15, 125, 125, 218, 218, 78, 78, 31, 31, 172, 172, 47, 47, 141, 141, 94, 94, 234, 234, 203, 203, 63, 63, 110, 110, 188, 188, 157, 157, 126, 126, 79, 79, 173, 173, 95, 95, 219, 219, 142, 142, 204, 204, 235, 235, 111, 111, 158, 158, 127, 127, 189, 189, 220, 220, 143, 143, 174, 174, 205, 205, 236, 236, 159, 159, 190, 190, 221, 221, 175, 175, 237, 237, 206, 206, 222, 222, 191, 191, 238, 238, 207, 207, 223, 223, 239, 239, 0, 0, }; private static final int[] row_scan_16x16_neighbors = { 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 16, 16, 3, 3, 17, 17, 16, 16, 4, 4, 32, 32, 18, 18, 5, 5, 33, 33, 32, 32, 19, 19, 48, 48, 6, 6, 34, 34, 20, 20, 49, 49, 48, 48, 7, 7, 35, 35, 64, 64, 21, 21, 50, 50, 36, 36, 64, 64, 8, 8, 65, 65, 51, 51, 22, 22, 37, 37, 80, 80, 66, 66, 9, 9, 52, 52, 23, 23, 81, 81, 67, 67, 80, 80, 38, 38, 10, 10, 53, 53, 82, 82, 96, 96, 68, 68, 24, 24, 97, 97, 83, 83, 39, 39, 96, 96, 54, 54, 11, 11, 69, 69, 98, 98, 112, 112, 84, 84, 25, 25, 40, 40, 55, 55, 113, 113, 99, 99, 12, 12, 70, 70, 112, 112, 85, 85, 26, 26, 114, 114, 100, 100, 128, 128, 41, 41, 56, 56, 71, 71, 115, 115, 13, 13, 86, 86, 129, 129, 101, 101, 128, 128, 72, 72, 130, 130, 116, 116, 27, 27, 57, 57, 14, 14, 87, 87, 42, 42, 144, 144, 102, 102, 131, 131, 145, 145, 117, 117, 73, 73, 144, 144, 88, 88, 132, 132, 103, 103, 28, 28, 58, 58, 146, 146, 118, 118, 43, 43, 160, 160, 147, 147, 89, 89, 104, 104, 133, 133, 161, 161, 119, 119, 160, 160, 74, 74, 134, 134, 148, 148, 29, 29, 59, 59, 162, 162, 176, 176, 44, 44, 120, 120, 90, 90, 105, 105, 163, 163, 177, 177, 149, 149, 176, 176, 135, 135, 164, 164, 178, 178, 30, 30, 150, 150, 192, 192, 75, 75, 121, 121, 60, 60, 136, 136, 193, 193, 106, 106, 151, 151, 179, 179, 192, 192, 45, 45, 165, 165, 166, 166, 194, 194, 91, 91, 180, 180, 137, 137, 208, 208, 122, 122, 152, 152, 208, 208, 195, 195, 76, 76, 167, 167, 209, 209, 181, 181, 224, 224, 107, 107, 196, 196, 61, 61, 153, 153, 224, 224, 182, 182, 168, 168, 210, 210, 46, 46, 138, 138, 92, 92, 183, 183, 225, 225, 211, 211, 240, 240, 197, 197, 169, 169, 123, 123, 154, 154, 198, 198, 77, 77, 212, 212, 184, 184, 108, 108, 226, 226, 199, 199, 62, 62, 227, 227, 241, 241, 139, 139, 213, 213, 170, 170, 185, 185, 155, 155, 228, 228, 242, 242, 124, 124, 93, 93, 200, 200, 243, 243, 214, 214, 215, 215, 229, 229, 140, 140, 186, 186, 201, 201, 78, 78, 171, 171, 109, 109, 156, 156, 244, 244, 216, 216, 230, 230, 94, 94, 245, 245, 231, 231, 125, 125, 202, 202, 246, 246, 232, 232, 172, 172, 217, 217, 141, 141, 110, 110, 157, 157, 187, 187, 247, 247, 126, 126, 233, 233, 218, 218, 248, 248, 188, 188, 203, 203, 142, 142, 173, 173, 158, 158, 249, 249, 234, 234, 204, 204, 219, 219, 174, 174, 189, 189, 250, 250, 220, 220, 190, 190, 205, 205, 235, 235, 206, 206, 236, 236, 251, 251, 221, 221, 252, 252, 222, 222, 237, 237, 238, 238, 253, 253, 254, 254, 0, 0, }; private static final int[] default_scan_16x16_neighbors = { 0, 0, 0, 0, 0, 0, 16, 16, 1, 16, 1, 1, 32, 32, 17, 32, 2, 17, 2, 2, 48, 48, 18, 33, 33, 48, 3, 18, 49, 64, 64, 64, 34, 49, 3, 3, 19, 34, 50, 65, 4, 19, 65, 80, 80, 80, 35, 50, 4, 4, 20, 35, 66, 81, 81, 96, 51, 66, 96, 96, 5, 20, 36, 51, 82, 97, 21, 36, 67, 82, 97, 112, 5, 5, 52, 67, 112, 112, 37, 52, 6, 21, 83, 98, 98, 113, 68, 83, 6, 6, 113, 128, 22, 37, 53, 68, 84, 99, 99, 114, 128, 128, 114, 129, 69, 84, 38, 53, 7, 22, 7, 7, 129, 144, 23, 38, 54, 69, 100, 115, 85, 100, 115, 130, 144, 144, 130, 145, 39, 54, 70, 85, 8, 23, 55, 70, 116, 131, 101, 116, 145, 160, 24, 39, 8, 8, 86, 101, 131, 146, 160, 160, 146, 161, 71, 86, 40, 55, 9, 24, 117, 132, 102, 117, 161, 176, 132, 147, 56, 71, 87, 102, 25, 40, 147, 162, 9, 9, 176, 176, 162, 177, 72, 87, 41, 56, 118, 133, 133, 148, 103, 118, 10, 25, 148, 163, 57, 72, 88, 103, 177, 192, 26, 41, 163, 178, 192, 192, 10, 10, 119, 134, 73, 88, 149, 164, 104, 119, 134, 149, 42, 57, 178, 193, 164, 179, 11, 26, 58, 73, 193, 208, 89, 104, 135, 150, 120, 135, 27, 42, 74, 89, 208, 208, 150, 165, 179, 194, 165, 180, 105, 120, 194, 209, 43, 58, 11, 11, 136, 151, 90, 105, 151, 166, 180, 195, 59, 74, 121, 136, 209, 224, 195, 210, 224, 224, 166, 181, 106, 121, 75, 90, 12, 27, 181, 196, 12, 12, 210, 225, 152, 167, 167, 182, 137, 152, 28, 43, 196, 211, 122, 137, 91, 106, 225, 240, 44, 59, 13, 28, 107, 122, 182, 197, 168, 183, 211, 226, 153, 168, 226, 241, 60, 75, 197, 212, 138, 153, 29, 44, 76, 91, 13, 13, 183, 198, 123, 138, 45, 60, 212, 227, 198, 213, 154, 169, 169, 184, 227, 242, 92, 107, 61, 76, 139, 154, 14, 29, 14, 14, 184, 199, 213, 228, 108, 123, 199, 214, 228, 243, 77, 92, 30, 45, 170, 185, 155, 170, 185, 200, 93, 108, 124, 139, 214, 229, 46, 61, 200, 215, 229, 244, 15, 30, 109, 124, 62, 77, 140, 155, 215, 230, 31, 46, 171, 186, 186, 201, 201, 216, 78, 93, 230, 245, 125, 140, 47, 62, 216, 231, 156, 171, 94, 109, 231, 246, 141, 156, 63, 78, 202, 217, 187, 202, 110, 125, 217, 232, 172, 187, 232, 247, 79, 94, 157, 172, 126, 141, 203, 218, 95, 110, 233, 248, 218, 233, 142, 157, 111, 126, 173, 188, 188, 203, 234, 249, 219, 234, 127, 142, 158, 173, 204, 219, 189, 204, 143, 158, 235, 250, 174, 189, 205, 220, 159, 174, 220, 235, 221, 236, 175, 190, 190, 205, 236, 251, 206, 221, 237, 252, 191, 206, 222, 237, 207, 222, 238, 253, 223, 238, 239, 254, 0, 0, }; private static final int[] default_scan_32x32_neighbors = { 0, 0, 0, 0, 0, 0, 32, 32, 1, 32, 1, 1, 64, 64, 33, 64, 2, 33, 96, 96, 2, 2, 65, 96, 34, 65, 128, 128, 97, 128, 3, 34, 66, 97, 3, 3, 35, 66, 98, 129, 129, 160, 160, 160, 4, 35, 67, 98, 192, 192, 4, 4, 130, 161, 161, 192, 36, 67, 99, 130, 5, 36, 68, 99, 193, 224, 162, 193, 224, 224, 131, 162, 37, 68, 100, 131, 5, 5, 194, 225, 225, 256, 256, 256, 163, 194, 69, 100, 132, 163, 6, 37, 226, 257, 6, 6, 195, 226, 257, 288, 101, 132, 288, 288, 38, 69, 164, 195, 133, 164, 258, 289, 227, 258, 196, 227, 7, 38, 289, 320, 70, 101, 320, 320, 7, 7, 165, 196, 39, 70, 102, 133, 290, 321, 259, 290, 228, 259, 321, 352, 352, 352, 197, 228, 134, 165, 71, 102, 8, 39, 322, 353, 291, 322, 260, 291, 103, 134, 353, 384, 166, 197, 229, 260, 40, 71, 8, 8, 384, 384, 135, 166, 354, 385, 323, 354, 198, 229, 292, 323, 72, 103, 261, 292, 9, 40, 385, 416, 167, 198, 104, 135, 230, 261, 355, 386, 416, 416, 293, 324, 324, 355, 9, 9, 41, 72, 386, 417, 199, 230, 136, 167, 417, 448, 262, 293, 356, 387, 73, 104, 387, 418, 231, 262, 10, 41, 168, 199, 325, 356, 418, 449, 105, 136, 448, 448, 42, 73, 294, 325, 200, 231, 10, 10, 357, 388, 137, 168, 263, 294, 388, 419, 74, 105, 419, 450, 449, 480, 326, 357, 232, 263, 295, 326, 169, 200, 11, 42, 106, 137, 480, 480, 450, 481, 358, 389, 264, 295, 201, 232, 138, 169, 389, 420, 43, 74, 420, 451, 327, 358, 11, 11, 481, 512, 233, 264, 451, 482, 296, 327, 75, 106, 170, 201, 482, 513, 512, 512, 390, 421, 359, 390, 421, 452, 107, 138, 12, 43, 202, 233, 452, 483, 265, 296, 328, 359, 139, 170, 44, 75, 483, 514, 513, 544, 234, 265, 297, 328, 422, 453, 12, 12, 391, 422, 171, 202, 76, 107, 514, 545, 453, 484, 544, 544, 266, 297, 203, 234, 108, 139, 329, 360, 298, 329, 140, 171, 515, 546, 13, 44, 423, 454, 235, 266, 545, 576, 454, 485, 45, 76, 172, 203, 330, 361, 576, 576, 13, 13, 267, 298, 546, 577, 77, 108, 204, 235, 455, 486, 577, 608, 299, 330, 109, 140, 547, 578, 14, 45, 14, 14, 141, 172, 578, 609, 331, 362, 46, 77, 173, 204, 15, 15, 78, 109, 205, 236, 579, 610, 110, 141, 15, 46, 142, 173, 47, 78, 174, 205, 16, 16, 79, 110, 206, 237, 16, 47, 111, 142, 48, 79, 143, 174, 80, 111, 175, 206, 17, 48, 17, 17, 207, 238, 49, 80, 81, 112, 18, 18, 18, 49, 50, 81, 82, 113, 19, 50, 51, 82, 83, 114, 608, 608, 484, 515, 360, 391, 236, 267, 112, 143, 19, 19, 640, 640, 609, 640, 516, 547, 485, 516, 392, 423, 361, 392, 268, 299, 237, 268, 144, 175, 113, 144, 20, 51, 20, 20, 672, 672, 641, 672, 610, 641, 548, 579, 517, 548, 486, 517, 424, 455, 393, 424, 362, 393, 300, 331, 269, 300, 238, 269, 176, 207, 145, 176, 114, 145, 52, 83, 21, 52, 21, 21, 704, 704, 673, 704, 642, 673, 611, 642, 580, 611, 549, 580, 518, 549, 487, 518, 456, 487, 425, 456, 394, 425, 363, 394, 332, 363, 301, 332, 270, 301, 239, 270, 208, 239, 177, 208, 146, 177, 115, 146, 84, 115, 53, 84, 22, 53, 22, 22, 705, 736, 674, 705, 643, 674, 581, 612, 550, 581, 519, 550, 457, 488, 426, 457, 395, 426, 333, 364, 302, 333, 271, 302, 209, 240, 178, 209, 147, 178, 85, 116, 54, 85, 23, 54, 706, 737, 675, 706, 582, 613, 551, 582, 458, 489, 427, 458, 334, 365, 303, 334, 210, 241, 179, 210, 86, 117, 55, 86, 707, 738, 583, 614, 459, 490, 335, 366, 211, 242, 87, 118, 736, 736, 612, 643, 488, 519, 364, 395, 240, 271, 116, 147, 23, 23, 768, 768, 737, 768, 644, 675, 613, 644, 520, 551, 489, 520, 396, 427, 365, 396, 272, 303, 241, 272, 148, 179, 117, 148, 24, 55, 24, 24, 800, 800, 769, 800, 738, 769, 676, 707, 645, 676, 614, 645, 552, 583, 521, 552, 490, 521, 428, 459, 397, 428, 366, 397, 304, 335, 273, 304, 242, 273, 180, 211, 149, 180, 118, 149, 56, 87, 25, 56, 25, 25, 832, 832, 801, 832, 770, 801, 739, 770, 708, 739, 677, 708, 646, 677, 615, 646, 584, 615, 553, 584, 522, 553, 491, 522, 460, 491, 429, 460, 398, 429, 367, 398, 336, 367, 305, 336, 274, 305, 243, 274, 212, 243, 181, 212, 150, 181, 119, 150, 88, 119, 57, 88, 26, 57, 26, 26, 833, 864, 802, 833, 771, 802, 709, 740, 678, 709, 647, 678, 585, 616, 554, 585, 523, 554, 461, 492, 430, 461, 399, 430, 337, 368, 306, 337, 275, 306, 213, 244, 182, 213, 151, 182, 89, 120, 58, 89, 27, 58, 834, 865, 803, 834, 710, 741, 679, 710, 586, 617, 555, 586, 462, 493, 431, 462, 338, 369, 307, 338, 214, 245, 183, 214, 90, 121, 59, 90, 835, 866, 711, 742, 587, 618, 463, 494, 339, 370, 215, 246, 91, 122, 864, 864, 740, 771, 616, 647, 492, 523, 368, 399, 244, 275, 120, 151, 27, 27, 896, 896, 865, 896, 772, 803, 741, 772, 648, 679, 617, 648, 524, 555, 493, 524, 400, 431, 369, 400, 276, 307, 245, 276, 152, 183, 121, 152, 28, 59, 28, 28, 928, 928, 897, 928, 866, 897, 804, 835, 773, 804, 742, 773, 680, 711, 649, 680, 618, 649, 556, 587, 525, 556, 494, 525, 432, 463, 401, 432, 370, 401, 308, 339, 277, 308, 246, 277, 184, 215, 153, 184, 122, 153, 60, 91, 29, 60, 29, 29, 960, 960, 929, 960, 898, 929, 867, 898, 836, 867, 805, 836, 774, 805, 743, 774, 712, 743, 681, 712, 650, 681, 619, 650, 588, 619, 557, 588, 526, 557, 495, 526, 464, 495, 433, 464, 402, 433, 371, 402, 340, 371, 309, 340, 278, 309, 247, 278, 216, 247, 185, 216, 154, 185, 123, 154, 92, 123, 61, 92, 30, 61, 30, 30, 961, 992, 930, 961, 899, 930, 837, 868, 806, 837, 775, 806, 713, 744, 682, 713, 651, 682, 589, 620, 558, 589, 527, 558, 465, 496, 434, 465, 403, 434, 341, 372, 310, 341, 279, 310, 217, 248, 186, 217, 155, 186, 93, 124, 62, 93, 31, 62, 962, 993, 931, 962, 838, 869, 807, 838, 714, 745, 683, 714, 590, 621, 559, 590, 466, 497, 435, 466, 342, 373, 311, 342, 218, 249, 187, 218, 94, 125, 63, 94, 963, 994, 839, 870, 715, 746, 591, 622, 467, 498, 343, 374, 219, 250, 95, 126, 868, 899, 744, 775, 620, 651, 496, 527, 372, 403, 248, 279, 124, 155, 900, 931, 869, 900, 776, 807, 745, 776, 652, 683, 621, 652, 528, 559, 497, 528, 404, 435, 373, 404, 280, 311, 249, 280, 156, 187, 125, 156, 932, 963, 901, 932, 870, 901, 808, 839, 777, 808, 746, 777, 684, 715, 653, 684, 622, 653, 560, 591, 529, 560, 498, 529, 436, 467, 405, 436, 374, 405, 312, 343, 281, 312, 250, 281, 188, 219, 157, 188, 126, 157, 964, 995, 933, 964, 902, 933, 871, 902, 840, 871, 809, 840, 778, 809, 747, 778, 716, 747, 685, 716, 654, 685, 623, 654, 592, 623, 561, 592, 530, 561, 499, 530, 468, 499, 437, 468, 406, 437, 375, 406, 344, 375, 313, 344, 282, 313, 251, 282, 220, 251, 189, 220, 158, 189, 127, 158, 965, 996, 934, 965, 903, 934, 841, 872, 810, 841, 779, 810, 717, 748, 686, 717, 655, 686, 593, 624, 562, 593, 531, 562, 469, 500, 438, 469, 407, 438, 345, 376, 314, 345, 283, 314, 221, 252, 190, 221, 159, 190, 966, 997, 935, 966, 842, 873, 811, 842, 718, 749, 687, 718, 594, 625, 563, 594, 470, 501, 439, 470, 346, 377, 315, 346, 222, 253, 191, 222, 967, 998, 843, 874, 719, 750, 595, 626, 471, 502, 347, 378, 223, 254, 872, 903, 748, 779, 624, 655, 500, 531, 376, 407, 252, 283, 904, 935, 873, 904, 780, 811, 749, 780, 656, 687, 625, 656, 532, 563, 501, 532, 408, 439, 377, 408, 284, 315, 253, 284, 936, 967, 905, 936, 874, 905, 812, 843, 781, 812, 750, 781, 688, 719, 657, 688, 626, 657, 564, 595, 533, 564, 502, 533, 440, 471, 409, 440, 378, 409, 316, 347, 285, 316, 254, 285, 968, 999, 937, 968, 906, 937, 875, 906, 844, 875, 813, 844, 782, 813, 751, 782, 720, 751, 689, 720, 658, 689, 627, 658, 596, 627, 565, 596, 534, 565, 503, 534, 472, 503, 441, 472, 410, 441, 379, 410, 348, 379, 317, 348, 286, 317, 255, 286, 969, 1000, 938, 969, 907, 938, 845, 876, 814, 845, 783, 814, 721, 752, 690, 721, 659, 690, 597, 628, 566, 597, 535, 566, 473, 504, 442, 473, 411, 442, 349, 380, 318, 349, 287, 318, 970, 1001, 939, 970, 846, 877, 815, 846, 722, 753, 691, 722, 598, 629, 567, 598, 474, 505, 443, 474, 350, 381, 319, 350, 971, 1002, 847, 878, 723, 754, 599, 630, 475, 506, 351, 382, 876, 907, 752, 783, 628, 659, 504, 535, 380, 411, 908, 939, 877, 908, 784, 815, 753, 784, 660, 691, 629, 660, 536, 567, 505, 536, 412, 443, 381, 412, 940, 971, 909, 940, 878, 909, 816, 847, 785, 816, 754, 785, 692, 723, 661, 692, 630, 661, 568, 599, 537, 568, 506, 537, 444, 475, 413, 444, 382, 413, 972, 1003, 941, 972, 910, 941, 879, 910, 848, 879, 817, 848, 786, 817, 755, 786, 724, 755, 693, 724, 662, 693, 631, 662, 600, 631, 569, 600, 538, 569, 507, 538, 476, 507, 445, 476, 414, 445, 383, 414, 973, 1004, 942, 973, 911, 942, 849, 880, 818, 849, 787, 818, 725, 756, 694, 725, 663, 694, 601, 632, 570, 601, 539, 570, 477, 508, 446, 477, 415, 446, 974, 1005, 943, 974, 850, 881, 819, 850, 726, 757, 695, 726, 602, 633, 571, 602, 478, 509, 447, 478, 975, 1006, 851, 882, 727, 758, 603, 634, 479, 510, 880, 911, 756, 787, 632, 663, 508, 539, 912, 943, 881, 912, 788, 819, 757, 788, 664, 695, 633, 664, 540, 571, 509, 540, 944, 975, 913, 944, 882, 913, 820, 851, 789, 820, 758, 789, 696, 727, 665, 696, 634, 665, 572, 603, 541, 572, 510, 541, 976, 1007, 945, 976, 914, 945, 883, 914, 852, 883, 821, 852, 790, 821, 759, 790, 728, 759, 697, 728, 666, 697, 635, 666, 604, 635, 573, 604, 542, 573, 511, 542, 977, 1008, 946, 977, 915, 946, 853, 884, 822, 853, 791, 822, 729, 760, 698, 729, 667, 698, 605, 636, 574, 605, 543, 574, 978, 1009, 947, 978, 854, 885, 823, 854, 730, 761, 699, 730, 606, 637, 575, 606, 979, 1010, 855, 886, 731, 762, 607, 638, 884, 915, 760, 791, 636, 667, 916, 947, 885, 916, 792, 823, 761, 792, 668, 699, 637, 668, 948, 979, 917, 948, 886, 917, 824, 855, 793, 824, 762, 793, 700, 731, 669, 700, 638, 669, 980, 1011, 949, 980, 918, 949, 887, 918, 856, 887, 825, 856, 794, 825, 763, 794, 732, 763, 701, 732, 670, 701, 639, 670, 981, 1012, 950, 981, 919, 950, 857, 888, 826, 857, 795, 826, 733, 764, 702, 733, 671, 702, 982, 1013, 951, 982, 858, 889, 827, 858, 734, 765, 703, 734, 983, 1014, 859, 890, 735, 766, 888, 919, 764, 795, 920, 951, 889, 920, 796, 827, 765, 796, 952, 983, 921, 952, 890, 921, 828, 859, 797, 828, 766, 797, 984, 1015, 953, 984, 922, 953, 891, 922, 860, 891, 829, 860, 798, 829, 767, 798, 985, 1016, 954, 985, 923, 954, 861, 892, 830, 861, 799, 830, 986, 1017, 955, 986, 862, 893, 831, 862, 987, 1018, 863, 894, 892, 923, 924, 955, 893, 924, 956, 987, 925, 956, 894, 925, 988, 1019, 957, 988, 926, 957, 895, 926, 989, 1020, 958, 989, 927, 958, 990, 1021, 959, 990, 991, 1022, 0, 0, }; private static final int[] vp9_default_iscan_4x4 = { 0, 2, 5, 8, 1, 3, 9, 12, 4, 7, 11, 14, 6, 10, 13, 15, }; private static final int[] vp9_col_iscan_4x4 = { 0, 3, 7, 11, 1, 5, 9, 12, 2, 6, 10, 14, 4, 8, 13, 15, }; private static final int[] vp9_row_iscan_4x4 = { 0, 1, 3, 5, 2, 4, 6, 9, 7, 8, 11, 13, 10, 12, 14, 15, }; private static final int[] vp9_col_iscan_8x8 = { 0, 3, 8, 15, 22, 32, 40, 47, 1, 5, 11, 18, 26, 34, 44, 51, 2, 7, 13, 20, 28, 38, 46, 54, 4, 10, 16, 24, 31, 41, 50, 56, 6, 12, 21, 27, 35, 43, 52, 58, 9, 17, 25, 33, 39, 48, 55, 60, 14, 23, 30, 37, 45, 53, 59, 62, 19, 29, 36, 42, 49, 57, 61, 63, }; private static final int[] vp9_row_iscan_8x8 = { 0, 1, 2, 5, 8, 12, 19, 24, 3, 4, 7, 10, 15, 20, 30, 39, 6, 9, 13, 16, 21, 27, 37, 46, 11, 14, 17, 23, 28, 34, 44, 52, 18, 22, 25, 31, 35, 41, 50, 57, 26, 29, 33, 38, 43, 49, 55, 59, 32, 36, 42, 47, 51, 54, 60, 61, 40, 45, 48, 53, 56, 58, 62, 63, }; private static final int[] vp9_default_iscan_8x8 = { 0, 2, 5, 9, 14, 22, 31, 37, 1, 4, 8, 13, 19, 26, 38, 44, 3, 6, 10, 17, 24, 30, 42, 49, 7, 11, 15, 21, 29, 36, 47, 53, 12, 16, 20, 27, 34, 43, 52, 57, 18, 23, 28, 35, 41, 48, 56, 60, 25, 32, 39, 45, 50, 55, 59, 62, 33, 40, 46, 51, 54, 58, 61, 63, }; private static final int[] vp9_col_iscan_16x16 = { 0, 4, 11, 20, 31, 43, 59, 75, 85, 109, 130, 150, 165, 181, 195, 198, 1, 6, 14, 23, 34, 47, 64, 81, 95, 114, 135, 153, 171, 188, 201, 212, 2, 8, 16, 25, 38, 52, 67, 83, 101, 116, 136, 157, 172, 190, 205, 216, 3, 10, 18, 29, 41, 55, 71, 89, 103, 119, 141, 159, 176, 194, 208, 218, 5, 12, 21, 32, 45, 58, 74, 93, 104, 123, 144, 164, 179, 196, 210, 223, 7, 15, 26, 37, 49, 63, 78, 96, 112, 129, 146, 166, 182, 200, 215, 228, 9, 19, 28, 39, 54, 69, 86, 102, 117, 132, 151, 170, 187, 206, 220, 230, 13, 24, 35, 46, 60, 73, 91, 108, 122, 137, 154, 174, 189, 207, 224, 235, 17, 30, 40, 53, 66, 82, 98, 115, 126, 142, 161, 180, 197, 213, 227, 237, 22, 36, 48, 62, 76, 92, 105, 120, 133, 147, 167, 186, 203, 219, 232, 240, 27, 44, 56, 70, 84, 99, 113, 127, 140, 156, 175, 193, 209, 226, 236, 244, 33, 51, 68, 79, 94, 110, 125, 138, 149, 162, 184, 202, 217, 229, 241, 247, 42, 61, 77, 90, 106, 121, 134, 148, 160, 173, 191, 211, 225, 238, 245, 251, 50, 72, 87, 100, 118, 128, 145, 158, 168, 183, 204, 222, 233, 242, 249, 253, 57, 80, 97, 111, 131, 143, 155, 169, 178, 192, 214, 231, 239, 246, 250, 254, 65, 88, 107, 124, 139, 152, 163, 177, 185, 199, 221, 234, 243, 248, 252, 255, }; private static final int[] vp9_row_iscan_16x16 = { 0, 1, 2, 4, 6, 9, 12, 17, 22, 29, 36, 43, 54, 64, 76, 86, 3, 5, 7, 11, 15, 19, 25, 32, 38, 48, 59, 68, 84, 99, 115, 130, 8, 10, 13, 18, 23, 27, 33, 42, 51, 60, 72, 88, 103, 119, 142, 167, 14, 16, 20, 26, 31, 37, 44, 53, 61, 73, 85, 100, 116, 135, 161, 185, 21, 24, 30, 35, 40, 47, 55, 65, 74, 81, 94, 112, 133, 154, 179, 205, 28, 34, 39, 45, 50, 58, 67, 77, 87, 96, 106, 121, 146, 169, 196, 212, 41, 46, 49, 56, 63, 70, 79, 90, 98, 107, 122, 138, 159, 182, 207, 222, 52, 57, 62, 69, 75, 83, 93, 102, 110, 120, 134, 150, 176, 195, 215, 226, 66, 71, 78, 82, 91, 97, 108, 113, 127, 136, 148, 168, 188, 202, 221, 232, 80, 89, 92, 101, 105, 114, 125, 131, 139, 151, 162, 177, 192, 208, 223, 234, 95, 104, 109, 117, 123, 128, 143, 144, 155, 165, 175, 190, 206, 219, 233, 239, 111, 118, 124, 129, 140, 147, 157, 164, 170, 181, 191, 203, 224, 230, 240, 243, 126, 132, 137, 145, 153, 160, 174, 178, 184, 197, 204, 216, 231, 237, 244, 246, 141, 149, 156, 166, 172, 180, 189, 199, 200, 210, 220, 228, 238, 242, 249, 251, 152, 163, 171, 183, 186, 193, 201, 211, 214, 218, 227, 236, 245, 247, 252, 253, 158, 173, 187, 194, 198, 209, 213, 217, 225, 229, 235, 241, 248, 250, 254, 255, }; private static final int[] vp9_default_iscan_16x16 = { 0, 2, 5, 9, 17, 24, 36, 44, 55, 72, 88, 104, 128, 143, 166, 179, 1, 4, 8, 13, 20, 30, 40, 54, 66, 79, 96, 113, 141, 154, 178, 196, 3, 7, 11, 18, 25, 33, 46, 57, 71, 86, 101, 119, 148, 164, 186, 201, 6, 12, 16, 23, 31, 39, 53, 64, 78, 92, 110, 127, 153, 169, 193, 208, 10, 14, 19, 28, 37, 47, 58, 67, 84, 98, 114, 133, 161, 176, 198, 214, 15, 21, 26, 34, 43, 52, 65, 77, 91, 106, 120, 140, 165, 185, 205, 221, 22, 27, 32, 41, 48, 60, 73, 85, 99, 116, 130, 151, 175, 190, 211, 225, 29, 35, 42, 49, 59, 69, 81, 95, 108, 125, 139, 155, 182, 197, 217, 229, 38, 45, 51, 61, 68, 80, 93, 105, 118, 134, 150, 168, 191, 207, 223, 234, 50, 56, 63, 74, 83, 94, 109, 117, 129, 147, 163, 177, 199, 213, 228, 238, 62, 70, 76, 87, 97, 107, 122, 131, 145, 159, 172, 188, 210, 222, 235, 242, 75, 82, 90, 102, 112, 124, 138, 146, 157, 173, 187, 202, 219, 230, 240, 245, 89, 100, 111, 123, 132, 142, 156, 167, 180, 189, 203, 216, 231, 237, 246, 250, 103, 115, 126, 136, 149, 162, 171, 183, 194, 204, 215, 224, 236, 241, 248, 252, 121, 135, 144, 158, 170, 181, 192, 200, 209, 218, 227, 233, 243, 244, 251, 254, 137, 152, 160, 174, 184, 195, 206, 212, 220, 226, 232, 239, 247, 249, 253, 255, }; private static final int[] vp9_default_iscan_32x32 = { 0, 2, 5, 10, 17, 25, 38, 47, 62, 83, 101, 121, 145, 170, 193, 204, 210, 219, 229, 233, 245, 257, 275, 299, 342, 356, 377, 405, 455, 471, 495, 527, 1, 4, 8, 15, 22, 30, 45, 58, 74, 92, 112, 133, 158, 184, 203, 215, 222, 228, 234, 237, 256, 274, 298, 317, 355, 376, 404, 426, 470, 494, 526, 551, 3, 7, 12, 18, 28, 36, 52, 64, 82, 102, 118, 142, 164, 189, 208, 217, 224, 231, 235, 238, 273, 297, 316, 329, 375, 403, 425, 440, 493, 525, 550, 567, 6, 11, 16, 23, 31, 43, 60, 73, 90, 109, 126, 150, 173, 196, 211, 220, 226, 232, 236, 239, 296, 315, 328, 335, 402, 424, 439, 447, 524, 549, 566, 575, 9, 14, 19, 29, 37, 50, 65, 78, 95, 116, 134, 157, 179, 201, 214, 223, 244, 255, 272, 295, 341, 354, 374, 401, 454, 469, 492, 523, 582, 596, 617, 645, 13, 20, 26, 35, 44, 54, 72, 85, 105, 123, 140, 163, 182, 205, 216, 225, 254, 271, 294, 314, 353, 373, 400, 423, 468, 491, 522, 548, 595, 616, 644, 666, 21, 27, 33, 42, 53, 63, 80, 94, 113, 132, 151, 172, 190, 209, 218, 227, 270, 293, 313, 327, 372, 399, 422, 438, 490, 521, 547, 565, 615, 643, 665, 680, 24, 32, 39, 48, 57, 71, 88, 104, 120, 139, 159, 178, 197, 212, 221, 230, 292, 312, 326, 334, 398, 421, 437, 446, 520, 546, 564, 574, 642, 664, 679, 687, 34, 40, 46, 56, 68, 81, 96, 111, 130, 147, 167, 186, 243, 253, 269, 291, 340, 352, 371, 397, 453, 467, 489, 519, 581, 594, 614, 641, 693, 705, 723, 747, 41, 49, 55, 67, 77, 91, 107, 124, 138, 161, 177, 194, 252, 268, 290, 311, 351, 370, 396, 420, 466, 488, 518, 545, 593, 613, 640, 663, 704, 722, 746, 765, 51, 59, 66, 76, 89, 99, 119, 131, 149, 168, 181, 200, 267, 289, 310, 325, 369, 395, 419, 436, 487, 517, 544, 563, 612, 639, 662, 678, 721, 745, 764, 777, 61, 69, 75, 87, 100, 114, 129, 144, 162, 180, 191, 207, 288, 309, 324, 333, 394, 418, 435, 445, 516, 543, 562, 573, 638, 661, 677, 686, 744, 763, 776, 783, 70, 79, 86, 97, 108, 122, 137, 155, 242, 251, 266, 287, 339, 350, 368, 393, 452, 465, 486, 515, 580, 592, 611, 637, 692, 703, 720, 743, 788, 798, 813, 833, 84, 93, 103, 110, 125, 141, 154, 171, 250, 265, 286, 308, 349, 367, 392, 417, 464, 485, 514, 542, 591, 610, 636, 660, 702, 719, 742, 762, 797, 812, 832, 848, 98, 106, 115, 127, 143, 156, 169, 185, 264, 285, 307, 323, 366, 391, 416, 434, 484, 513, 541, 561, 609, 635, 659, 676, 718, 741, 761, 775, 811, 831, 847, 858, 117, 128, 136, 148, 160, 175, 188, 198, 284, 306, 322, 332, 390, 415, 433, 444, 512, 540, 560, 572, 634, 658, 675, 685, 740, 760, 774, 782, 830, 846, 857, 863, 135, 146, 152, 165, 241, 249, 263, 283, 338, 348, 365, 389, 451, 463, 483, 511, 579, 590, 608, 633, 691, 701, 717, 739, 787, 796, 810, 829, 867, 875, 887, 903, 153, 166, 174, 183, 248, 262, 282, 305, 347, 364, 388, 414, 462, 482, 510, 539, 589, 607, 632, 657, 700, 716, 738, 759, 795, 809, 828, 845, 874, 886, 902, 915, 176, 187, 195, 202, 261, 281, 304, 321, 363, 387, 413, 432, 481, 509, 538, 559, 606, 631, 656, 674, 715, 737, 758, 773, 808, 827, 844, 856, 885, 901, 914, 923, 192, 199, 206, 213, 280, 303, 320, 331, 386, 412, 431, 443, 508, 537, 558, 571, 630, 655, 673, 684, 736, 757, 772, 781, 826, 843, 855, 862, 900, 913, 922, 927, 240, 247, 260, 279, 337, 346, 362, 385, 450, 461, 480, 507, 578, 588, 605, 629, 690, 699, 714, 735, 786, 794, 807, 825, 866, 873, 884, 899, 930, 936, 945, 957, 246, 259, 278, 302, 345, 361, 384, 411, 460, 479, 506, 536, 587, 604, 628, 654, 698, 713, 734, 756, 793, 806, 824, 842, 872, 883, 898, 912, 935, 944, 956, 966, 258, 277, 301, 319, 360, 383, 410, 430, 478, 505, 535, 557, 603, 627, 653, 672, 712, 733, 755, 771, 805, 823, 841, 854, 882, 897, 911, 921, 943, 955, 965, 972, 276, 300, 318, 330, 382, 409, 429, 442, 504, 534, 556, 570, 626, 652, 671, 683, 732, 754, 770, 780, 822, 840, 853, 861, 896, 910, 920, 926, 954, 964, 971, 975, 336, 344, 359, 381, 449, 459, 477, 503, 577, 586, 602, 625, 689, 697, 711, 731, 785, 792, 804, 821, 865, 871, 881, 895, 929, 934, 942, 953, 977, 981, 987, 995, 343, 358, 380, 408, 458, 476, 502, 533, 585, 601, 624, 651, 696, 710, 730, 753, 791, 803, 820, 839, 870, 880, 894, 909, 933, 941, 952, 963, 980, 986, 994, 1001, 357, 379, 407, 428, 475, 501, 532, 555, 600, 623, 650, 670, 709, 729, 752, 769, 802, 819, 838, 852, 879, 893, 908, 919, 940, 951, 962, 970, 985, 993, 1000, 1005, 378, 406, 427, 441, 500, 531, 554, 569, 622, 649, 669, 682, 728, 751, 768, 779, 818, 837, 851, 860, 892, 907, 918, 925, 950, 961, 969, 974, 992, 999, 1004, 1007, 448, 457, 474, 499, 576, 584, 599, 621, 688, 695, 708, 727, 784, 790, 801, 817, 864, 869, 878, 891, 928, 932, 939, 949, 976, 979, 984, 991, 1008, 1010, 1013, 1017, 456, 473, 498, 530, 583, 598, 620, 648, 694, 707, 726, 750, 789, 800, 816, 836, 868, 877, 890, 906, 931, 938, 948, 960, 978, 983, 990, 998, 1009, 1012, 1016, 1020, 472, 497, 529, 553, 597, 619, 647, 668, 706, 725, 749, 767, 799, 815, 835, 850, 876, 889, 905, 917, 937, 947, 959, 968, 982, 989, 997, 1003, 1011, 1015, 1019, 1022, 496, 528, 552, 568, 618, 646, 667, 681, 724, 748, 766, 778, 814, 834, 849, 859, 888, 904, 916, 924, 946, 958, 967, 973, 988, 996, 1002, 1006, 1014, 1018, 1021, 1023, }; public static final int[][][] vp9_default_scan_orders = { { default_scan_4x4, vp9_default_iscan_4x4, default_scan_4x4_neighbors }, { default_scan_8x8, vp9_default_iscan_8x8, default_scan_8x8_neighbors }, { default_scan_16x16, vp9_default_iscan_16x16, default_scan_16x16_neighbors }, { default_scan_32x32, vp9_default_iscan_32x32, default_scan_32x32_neighbors }, }; public static final int[][][][] vp9_scan_orders = { { // TX_4X4 { default_scan_4x4, vp9_default_iscan_4x4, default_scan_4x4_neighbors }, { row_scan_4x4, vp9_row_iscan_4x4, row_scan_4x4_neighbors }, { col_scan_4x4, vp9_col_iscan_4x4, col_scan_4x4_neighbors }, { default_scan_4x4, vp9_default_iscan_4x4, default_scan_4x4_neighbors } }, { // TX_8X8 { default_scan_8x8, vp9_default_iscan_8x8, default_scan_8x8_neighbors }, { row_scan_8x8, vp9_row_iscan_8x8, row_scan_8x8_neighbors }, { col_scan_8x8, vp9_col_iscan_8x8, col_scan_8x8_neighbors }, { default_scan_8x8, vp9_default_iscan_8x8, default_scan_8x8_neighbors } }, { // TX_16X16 { default_scan_16x16, vp9_default_iscan_16x16, default_scan_16x16_neighbors }, { row_scan_16x16, vp9_row_iscan_16x16, row_scan_16x16_neighbors }, { col_scan_16x16, vp9_col_iscan_16x16, col_scan_16x16_neighbors }, { default_scan_16x16, vp9_default_iscan_16x16, default_scan_16x16_neighbors } }, { // TX_32X32 { default_scan_32x32, vp9_default_iscan_32x32, default_scan_32x32_neighbors }, { default_scan_32x32, vp9_default_iscan_32x32, default_scan_32x32_neighbors }, { default_scan_32x32, vp9_default_iscan_32x32, default_scan_32x32_neighbors }, { default_scan_32x32, vp9_default_iscan_32x32, default_scan_32x32_neighbors } } }; }
28,239
8,805
<reponame>rudylee/expo /*============================================================================= Copyright (c) 2001-2011 <NAME> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_SPIRIT_INFO_NOVEMBER_22_2008_1132AM) #define BOOST_SPIRIT_INFO_NOVEMBER_22_2008_1132AM #if defined(_MSC_VER) #pragma once #endif #include <boost/variant/variant.hpp> #include <boost/variant/recursive_variant.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/foreach.hpp> #include <boost/spirit/home/support/utf8.hpp> #include <list> #include <iterator> #include <utility> namespace boost { namespace spirit { // info provides information about a component. Each component // has a what member function that returns an info object. // strings in the info object are assumed to be encoded as UTF8 // for uniformity. struct info { struct nil_ {}; typedef boost::variant< nil_ , utf8_string , recursive_wrapper<info> , recursive_wrapper<std::pair<info, info> > , recursive_wrapper<std::list<info> > > value_type; explicit info(utf8_string const& tag_) : tag(tag_), value(nil_()) {} template <typename T> info(utf8_string const& tag_, T const& value_) : tag(tag_), value(value_) {} info(utf8_string const& tag_, char value_) : tag(tag_), value(utf8_string(1, value_)) {} info(utf8_string const& tag_, wchar_t value_) : tag(tag_), value(to_utf8(value_)) {} info(utf8_string const& tag_, ucs4_char value_) : tag(tag_), value(to_utf8(value_)) {} template <typename Char> info(utf8_string const& tag_, Char const* str) : tag(tag_), value(to_utf8(str)) {} template <typename Char, typename Traits, typename Allocator> info(utf8_string const& tag_ , std::basic_string<Char, Traits, Allocator> const& str) : tag(tag_), value(to_utf8(str)) {} utf8_string tag; value_type value; }; template <typename Callback> struct basic_info_walker { typedef void result_type; typedef basic_info_walker<Callback> this_type; basic_info_walker(Callback& callback_, utf8_string const& tag_, int depth_) : callback(callback_), tag(tag_), depth(depth_) {} void operator()(info::nil_) const { callback.element(tag, "", depth); } void operator()(utf8_string const& str) const { callback.element(tag, str, depth); } void operator()(info const& what) const { boost::apply_visitor( this_type(callback, what.tag, depth+1), what.value); } void operator()(std::pair<info, info> const& pair) const { callback.element(tag, "", depth); boost::apply_visitor( this_type(callback, pair.first.tag, depth+1), pair.first.value); boost::apply_visitor( this_type(callback, pair.second.tag, depth+1), pair.second.value); } void operator()(std::list<info> const& l) const { callback.element(tag, "", depth); BOOST_FOREACH(info const& what, l) { boost::apply_visitor( this_type(callback, what.tag, depth+1), what.value); } } Callback& callback; utf8_string const& tag; int depth; private: // silence MSVC warning C4512: assignment operator could not be generated basic_info_walker& operator= (basic_info_walker const&); }; // bare-bones print support template <typename Out> struct simple_printer { typedef utf8_string string; simple_printer(Out& out_) : out(out_) {} void element(string const& tag, string const& value, int /*depth*/) const { if (value == "") out << '<' << tag << '>'; else out << '"' << value << '"'; } Out& out; private: // silence MSVC warning C4512: assignment operator could not be generated simple_printer& operator= (simple_printer const&); }; template <typename Out> Out& operator<<(Out& out, info const& what) { simple_printer<Out> pr(out); basic_info_walker<simple_printer<Out> > walker(pr, what.tag, 0); boost::apply_visitor(walker, what.value); return out; } }} #endif
2,369
369
// Copyright (c) 2017-2021, Mudita <NAME>.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "chip.hpp" #include <log/log.hpp> #include <map> #include <string> namespace { const std::map<std::uint32_t, std::string> bootReasonDef = { {SRC_SRSR_IPP_RESET_B_SHIFT, "ipp_reset_b pin (Power-up sequence)"}, {SRC_SRSR_LOCKUP_SYSRESETREQ_SHIFT, "CPU lockup or software setting of SYSRESETREQ"}, {SRC_SRSR_CSU_RESET_B_SHIFT, "csu_reset_b input"}, {SRC_SRSR_IPP_USER_RESET_B_SHIFT, "ipp_user_reset_b qualified reset"}, {SRC_SRSR_WDOG_RST_B_SHIFT, "IC Watchdog Time-out reset"}, {SRC_SRSR_JTAG_RST_B_SHIFT, "HIGH - Z JTAG reset"}, {SRC_SRSR_JTAG_SW_RST_SHIFT, "JTAG software reset"}, {SRC_SRSR_WDOG3_RST_B_SHIFT, "IC Watchdog3 Time-out reset"}, {SRC_SRSR_TEMPSENSE_RST_B_SHIFT, "Tamper Sensor software reset"}}; } // namespace void clearAndPrintBootReason() { // get boot reason std::uint32_t SRSR_val = SRC_GetResetStatusFlags(SRC); LOG_INFO("Boot reason: %" PRIu32, SRSR_val); if (SRSR_val & (1UL << SRC_SRSR_IPP_RESET_B_SHIFT)) LOG_INFO("\t*%s", bootReasonDef.at(SRC_SRSR_IPP_RESET_B_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_LOCKUP_SYSRESETREQ_SHIFT)) { LOG_WARN("\t*%s", bootReasonDef.at(SRC_SRSR_LOCKUP_SYSRESETREQ_SHIFT).c_str()); LOG_INFO("\tGPR_5 %" PRIu32, SRC_GetGeneralPurposeRegister(SRC, 5)); } if (SRSR_val & (1UL << SRC_SRSR_CSU_RESET_B_SHIFT)) LOG_INFO("\t*%s", bootReasonDef.at(SRC_SRSR_CSU_RESET_B_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_IPP_USER_RESET_B_SHIFT)) LOG_INFO("\t*%s", bootReasonDef.at(SRC_SRSR_IPP_USER_RESET_B_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_WDOG_RST_B_SHIFT)) LOG_WARN("\t*%s", bootReasonDef.at(SRC_SRSR_WDOG_RST_B_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_JTAG_RST_B_SHIFT)) LOG_INFO("\t*%s", bootReasonDef.at(SRC_SRSR_JTAG_RST_B_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_JTAG_SW_RST_SHIFT)) LOG_INFO("\t*%s", bootReasonDef.at(SRC_SRSR_JTAG_SW_RST_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_WDOG3_RST_B_SHIFT)) LOG_INFO("\t*%s", bootReasonDef.at(SRC_SRSR_WDOG3_RST_B_SHIFT).c_str()); if (SRSR_val & (1UL << SRC_SRSR_TEMPSENSE_RST_B_SHIFT)) LOG_WARN("\t*%s", bootReasonDef.at(SRC_SRSR_TEMPSENSE_RST_B_SHIFT).c_str()); // clear all set bits SRC_ClearResetStatusFlags(SRC, SRSR_val); }
1,338
4,538
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file pin.h * @brief header File for pin definition * @version V1.0 * @date 02. June 2018 ******************************************************************************/ #ifndef _PIN_H_ #define _PIN_H_ #include <stdint.h> #include "pin_name.h" #include "pinmux.h" #ifdef __cplusplus extern "C" { #endif #define CLOCK_GETTIME_USE_TIMER_ID 0 #define UART_TXD0 1 #define UART_RXD0 2 #define CONSOLE_TXD PAD_UART0_SIN #define CONSOLE_RXD PAD_UART0_SOUT #define CONSOLE_IDX 0 /* example pin manager */ #define EXAMPLE_USART_IDX 0 #define EXAMPLE_PIN_USART_TX PAD_UART0_SIN #define EXAMPLE_PIN_USART_RX PAD_UART0_SOUT #define EXAMPLE_PIN_USART_TX_FUNC 0 #define EXAMPLE_PIN_USART_RX_FUNC 0 #define EXAMPLE_GPIO_PIN PA1 #define EXAMPLE_BOARD_GPIO_PIN_NAME "A1" #define EXAMPLE_GPIO_PIN_FUNC 0 /* tests pin manager */ #define TEST_USART_IDX 0 #define TEST_PIN_USART_TX PAD_UART0_SIN #define TEST_PIN_USART_RX PAD_UART0_SOUT #define TEST_PIN_USART_TX_FUNC 0 #define TEST_PIN_USART_RX_FUNC 0 #define TEST_GPIO_PIN PA0 #define TEST_BOARD_GPIO_PIN_NAME "A0" #define TEST_GPIO_PIN_FUNC 0 #define UART_TXD2 3 #define UART_RXD2 4 #define UART_TXD3 5 #define UART_RXD3 6 #define UART_PINs { {PA0, PA1},\ {PA10, PA11},\ {PA23, PA22},\ {PA26, PA27} } #define GPIO_EXAMPLE_PORT PORTB #define GPIO_EXAMPLE_PIN PA1 #define CTS_GPIO_TEST_PORT PORTA #define CTS_GPIO_TEST_PIN PA0 #define EXAMPLE_BOARD_GPIO_PIN_NAME "A1" #define CTS_BOARD_GPIO_PIN_NAME "A0" #define SENSOR_UART_DIR PA3 #ifdef __cplusplus } #endif #endif /* _PIN_H_ */
868
5,169
{ "name": "HFBouncingButton", "version": "0.1.1", "summary": "HFBouncingButton is simple helper to make bouncing button.", "description": "HFBouncingButton is simple helper to make bouncing button.\n\n* The view can be customized\n* Bouncing direction can be vertical / horizontal\n* Use block for easy tap action", "homepage": "https://github.com/thidayatullah/HFBouncingButton", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/thidayatullah/HFBouncingButton.git", "tag": "0.1.1" }, "platforms": { "ios": "8.0" }, "source_files": "HFBouncingButton/Classes/**/*" }
258
438
{ "DESCRIPTION": "Charge une liste de lecture", "USAGE": "p-load <nom_de_la_playlist>", "QUEUE": "En file d'attente **{{NUM}} titres** depuis **{{TITLE}}**.", "NO_PLAYLIST": "Liste de lecture non trouvée." }
88
2,529
/** * 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. */ #include "mod_lua.h" #include "lua_dbd.h" APLOG_USE_MODULE(lua); static APR_OPTIONAL_FN_TYPE(ap_dbd_close) *lua_ap_dbd_close = NULL; static APR_OPTIONAL_FN_TYPE(ap_dbd_open) *lua_ap_dbd_open = NULL; static request_rec *ap_lua_check_request_rec(lua_State *L, int index) { request_rec *r; luaL_checkudata(L, index, "Apache2.Request"); r = lua_unboxpointer(L, index); return r; } static lua_db_handle *lua_get_db_handle(lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_rawgeti(L, 1, 0); luaL_checktype(L, -1, LUA_TUSERDATA); return (lua_db_handle *) lua_topointer(L, -1); } static lua_db_result_set *lua_get_result_set(lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_rawgeti(L, 1, 0); luaL_checktype(L, -1, LUA_TUSERDATA); return (lua_db_result_set *) lua_topointer(L, -1); } /* ============================================================================= db:close(): Closes an open database connection. ============================================================================= */ int lua_db_close(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db; apr_status_t rc = 0; /*~~~~~~~~~~~~~~~~~~~~*/ db = lua_get_db_handle(L); if (db && db->alive) { if (db->type == LUA_DBTYPE_APR_DBD) { rc = apr_dbd_close(db->driver, db->handle); if (db->pool) apr_pool_destroy(db->pool); } else { lua_ap_dbd_close = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_close); if (lua_ap_dbd_close != NULL) if (db->dbdhandle) lua_ap_dbd_close(db->server, db->dbdhandle); } db->driver = NULL; db->handle = NULL; db->alive = 0; db->pool = NULL; } lua_settop(L, 0); lua_pushnumber(L, rc); return 1; } /* ============================================================================= db:__gc(): Garbage collecting function. ============================================================================= */ int lua_db_gc(lua_State *L) { /*~~~~~~~~~~~~~~~~*/ lua_db_handle *db; /*~~~~~~~~~~~~~~~~~~~~*/ db = lua_touserdata(L, 1); if (db && db->alive) { if (db->type == LUA_DBTYPE_APR_DBD) { apr_dbd_close(db->driver, db->handle); if (db->pool) apr_pool_destroy(db->pool); } else { lua_ap_dbd_close = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_close); if (lua_ap_dbd_close != NULL) if (db->dbdhandle) lua_ap_dbd_close(db->server, db->dbdhandle); } db->driver = NULL; db->handle = NULL; db->alive = 0; db->pool = NULL; } lua_settop(L, 0); return 0; } /* ============================================================================= db:active(): Returns true if the connection to the db is still active. ============================================================================= */ int lua_db_active(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db = 0; apr_status_t rc = 0; /*~~~~~~~~~~~~~~~~~~~~*/ db = lua_get_db_handle(L); if (db && db->alive) { rc = apr_dbd_check_conn(db->driver, db->pool, db->handle); if (rc == APR_SUCCESS) { lua_pushboolean(L, 1); return 1; } } lua_pushboolean(L, 0); return 1; } /* ============================================================================= db:query(statement): Executes the given database query and returns the number of rows affected. If an error is encountered, returns nil as the first parameter and the error message as the second. ============================================================================= */ int lua_db_query(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db = 0; apr_status_t rc = 0; int x = 0; const char *statement; /*~~~~~~~~~~~~~~~~~~~~~~~*/ luaL_checktype(L, 3, LUA_TSTRING); statement = lua_tostring(L, 3); db = lua_get_db_handle(L); if (db && db->alive) rc = apr_dbd_query(db->driver, db->handle, &x, statement); else { rc = 0; x = -1; } if (rc == APR_SUCCESS) lua_pushnumber(L, x); else { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const char *err = apr_dbd_error(db->driver, db->handle, rc); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_pushnil(L); if (err) { lua_pushstring(L, err); return 2; } } return 1; } /* ============================================================================= db:escape(string): Escapes a string for safe use in the given database type. ============================================================================= */ int lua_db_escape(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db = 0; const char *statement; const char *escaped = 0; request_rec *r; /*~~~~~~~~~~~~~~~~~~~~~*/ r = ap_lua_check_request_rec(L, 2); if (r) { luaL_checktype(L, 3, LUA_TSTRING); statement = lua_tostring(L, 3); db = lua_get_db_handle(L); if (db && db->alive) { apr_dbd_init(r->pool); escaped = apr_dbd_escape(db->driver, r->pool, statement, db->handle); if (escaped) { lua_pushstring(L, escaped); return 1; } } else { lua_pushnil(L); } return (1); } return 0; } /* ============================================================================= resultset(N): Fetches one or more rows from a result set. ============================================================================= */ int lua_db_get_row(lua_State *L) { int row_no,x,alpha = 0; const char *entry, *rowname; apr_dbd_row_t *row = 0; lua_db_result_set *res = lua_get_result_set(L); row_no = luaL_optinteger(L, 2, 0); if (lua_isboolean(L, 3)) { alpha = lua_toboolean(L, 3); } lua_settop(L,0); /* Fetch all rows at once? */ if (row_no == 0) { row_no = 1; lua_newtable(L); while (apr_dbd_get_row(res->driver, res->pool, res->results, &row, -1) != -1) { lua_pushinteger(L, row_no); lua_newtable(L); for (x = 0; x < res->cols; x++) { entry = apr_dbd_get_entry(res->driver, row, x); if (entry) { if (alpha == 1) { rowname = apr_dbd_get_name(res->driver, res->results, x); lua_pushstring(L, rowname ? rowname : "(oob)"); } else { lua_pushinteger(L, x + 1); } lua_pushstring(L, entry); lua_rawset(L, -3); } } lua_rawset(L, -3); row_no++; } return 1; } /* Just fetch a single row */ if (apr_dbd_get_row(res->driver, res->pool, res->results, &row, row_no) != -1) { lua_newtable(L); for (x = 0; x < res->cols; x++) { entry = apr_dbd_get_entry(res->driver, row, x); if (entry) { if (alpha == 1) { rowname = apr_dbd_get_name(res->driver, res->results, x); lua_pushstring(L, rowname ? rowname : "(oob)"); } else { lua_pushinteger(L, x + 1); } lua_pushstring(L, entry); lua_rawset(L, -3); } } return 1; } return 0; } /* ============================================================================= db:select(statement): Queries the database for the given statement and returns the rows/columns found as a table. If an error is encountered, returns nil as the first parameter and the error message as the second. ============================================================================= */ int lua_db_select(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db = 0; apr_status_t rc = 0; const char *statement; request_rec *r; /*~~~~~~~~~~~~~~~~~~~~~~~*/ r = ap_lua_check_request_rec(L, 2); if (r) { luaL_checktype(L, 3, LUA_TSTRING); statement = lua_tostring(L, 3); db = lua_get_db_handle(L); if (db && db->alive) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ int cols; apr_dbd_results_t *results = 0; lua_db_result_set* resultset = NULL; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ rc = apr_dbd_select(db->driver, db->pool, db->handle, &results, statement, 0); if (rc == APR_SUCCESS) { cols = apr_dbd_num_cols(db->driver, results); if (cols > 0) { lua_newtable(L); resultset = lua_newuserdata(L, sizeof(lua_db_result_set)); resultset->cols = cols; resultset->driver = db->driver; resultset->pool = db->pool; resultset->rows = apr_dbd_num_tuples(db->driver, results); resultset->results = results; luaL_newmetatable(L, "lua_apr.dbselect"); lua_pushliteral(L, "__call"); lua_pushcfunction(L, lua_db_get_row); lua_rawset(L, -3); lua_setmetatable(L, -3); lua_rawseti(L, -2, 0); return 1; } return 0; } else { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const char *err = apr_dbd_error(db->driver, db->handle, rc); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_pushnil(L); if (err) { lua_pushstring(L, err); return 2; } } } lua_pushboolean(L, 0); return 1; } return 0; } /* ============================================================================= statement:select(var1, var2, var3...): Injects variables into a prepared statement and returns the number of rows matching the query. ============================================================================= */ int lua_db_prepared_select(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_db_prepared_statement *st = 0; apr_status_t rc = 0; const char **vars; int x, have; /*~~~~~~~~~~~~~~~~~~~~~~~*/ /* Fetch the prepared statement and the vars passed */ luaL_checktype(L, 1, LUA_TTABLE); lua_rawgeti(L, 1, 0); luaL_checktype(L, -1, LUA_TUSERDATA); st = (lua_db_prepared_statement*) lua_topointer(L, -1); /* Check if we got enough variables passed on to us. * This, of course, only works for prepared statements made through lua. */ have = lua_gettop(L) - 2; if (st->variables != -1 && have < st->variables ) { lua_pushboolean(L, 0); lua_pushfstring(L, "Error in executing prepared statement: Expected %d arguments, got %d.", st->variables, have); return 2; } vars = apr_pcalloc(st->db->pool, have*sizeof(char *)); for (x = 0; x < have; x++) { vars[x] = lua_tostring(L, x + 2); } /* Fire off the query */ if (st->db && st->db->alive) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ int cols; apr_dbd_results_t *results = 0; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ rc = apr_dbd_pselect(st->db->driver, st->db->pool, st->db->handle, &results, st->statement, 0, have, vars); if (rc == APR_SUCCESS) { /*~~~~~~~~~~~~~~~~~~~~~*/ lua_db_result_set *resultset; /*~~~~~~~~~~~~~~~~~~~~~*/ cols = apr_dbd_num_cols(st->db->driver, results); lua_newtable(L); resultset = lua_newuserdata(L, sizeof(lua_db_result_set)); resultset->cols = cols; resultset->driver = st->db->driver; resultset->pool = st->db->pool; resultset->rows = apr_dbd_num_tuples(st->db->driver, results); resultset->results = results; luaL_newmetatable(L, "lua_apr.dbselect"); lua_pushliteral(L, "__call"); lua_pushcfunction(L, lua_db_get_row); lua_rawset(L, -3); lua_setmetatable(L, -3); lua_rawseti(L, -2, 0); return 1; } else { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const char *err = apr_dbd_error(st->db->driver, st->db->handle, rc); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_pushnil(L); if (err) { lua_pushstring(L, err); return 2; } return 1; } } lua_pushboolean(L, 0); lua_pushliteral(L, "Database connection seems to be closed, please reacquire it."); return (2); } /* ============================================================================= statement:query(var1, var2, var3...): Injects variables into a prepared statement and returns the number of rows affected. ============================================================================= */ int lua_db_prepared_query(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_db_prepared_statement *st = 0; apr_status_t rc = 0; const char **vars; int x, have; /*~~~~~~~~~~~~~~~~~~~~~~~*/ /* Fetch the prepared statement and the vars passed */ luaL_checktype(L, 1, LUA_TTABLE); lua_rawgeti(L, 1, 0); luaL_checktype(L, -1, LUA_TUSERDATA); st = (lua_db_prepared_statement*) lua_topointer(L, -1); /* Check if we got enough variables passed on to us. * This, of course, only works for prepared statements made through lua. */ have = lua_gettop(L) - 2; if (st->variables != -1 && have < st->variables ) { lua_pushboolean(L, 0); lua_pushfstring(L, "Error in executing prepared statement: Expected %d arguments, got %d.", st->variables, have); return 2; } vars = apr_pcalloc(st->db->pool, have*sizeof(char *)); for (x = 0; x < have; x++) { vars[x] = lua_tostring(L, x + 2); } /* Fire off the query */ if (st->db && st->db->alive) { /*~~~~~~~~~~~~~~*/ int affected = 0; /*~~~~~~~~~~~~~~*/ rc = apr_dbd_pquery(st->db->driver, st->db->pool, st->db->handle, &affected, st->statement, have, vars); if (rc == APR_SUCCESS) { lua_pushinteger(L, affected); return 1; } else { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const char *err = apr_dbd_error(st->db->driver, st->db->handle, rc); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_pushnil(L); if (err) { lua_pushstring(L, err); return 2; } return 1; } } lua_pushboolean(L, 0); lua_pushliteral(L, "Database connection seems to be closed, please reacquire it."); return (2); } /* ============================================================================= db:prepare(statement): Prepares a statement for later query/select. Returns a table with a :query and :select function, same as the db funcs. ============================================================================= */ int lua_db_prepare(lua_State* L) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db = 0; apr_status_t rc = 0; const char *statement, *at; request_rec *r; lua_db_prepared_statement* st; int need = 0; /*~~~~~~~~~~~~~~~~~~~~~~~~~~*/ r = ap_lua_check_request_rec(L, 2); if (r) { apr_dbd_prepared_t *pstatement = NULL; luaL_checktype(L, 3, LUA_TSTRING); statement = lua_tostring(L, 3); /* Count number of variables in statement */ at = ap_strchr_c(statement,'%'); while (at != NULL) { if (at[1] == '%') { at++; } else { need++; } at = ap_strchr_c(at+1,'%'); } db = lua_get_db_handle(L); rc = apr_dbd_prepare(db->driver, r->pool, db->handle, statement, NULL, &pstatement); if (rc != APR_SUCCESS) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const char *err = apr_dbd_error(db->driver, db->handle, rc); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_pushnil(L); if (err) { lua_pushstring(L, err); return 2; } return 1; } /* Push the prepared statement table */ lua_newtable(L); st = lua_newuserdata(L, sizeof(lua_db_prepared_statement)); st->statement = pstatement; st->variables = need; st->db = db; lua_pushliteral(L, "select"); lua_pushcfunction(L, lua_db_prepared_select); lua_rawset(L, -4); lua_pushliteral(L, "query"); lua_pushcfunction(L, lua_db_prepared_query); lua_rawset(L, -4); lua_rawseti(L, -2, 0); return 1; } return 0; } /* ============================================================================= db:prepared(statement): Fetches a prepared statement made through DBDPrepareSQL. ============================================================================= */ int lua_db_prepared(lua_State* L) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~*/ lua_db_handle *db = 0; const char *tag; request_rec *r; lua_db_prepared_statement* st; /*~~~~~~~~~~~~~~~~~~~~~~~~~~*/ r = ap_lua_check_request_rec(L, 2); if (r) { apr_dbd_prepared_t *pstatement = NULL; db = lua_get_db_handle(L); luaL_checktype(L, 3, LUA_TSTRING); tag = lua_tostring(L, 3); /* Look for the statement */ pstatement = apr_hash_get(db->dbdhandle->prepared, tag, APR_HASH_KEY_STRING); if (pstatement == NULL) { lua_pushnil(L); lua_pushfstring(L, "Could not find any prepared statement called %s!", tag); return 2; } /* Push the prepared statement table */ lua_newtable(L); st = lua_newuserdata(L, sizeof(lua_db_prepared_statement)); st->statement = pstatement; st->variables = -1; /* we don't know :( */ st->db = db; lua_pushliteral(L, "select"); lua_pushcfunction(L, lua_db_prepared_select); lua_rawset(L, -4); lua_pushliteral(L, "query"); lua_pushcfunction(L, lua_db_prepared_query); lua_rawset(L, -4); lua_rawseti(L, -2, 0); return 1; } return 0; } /* lua_push_db_handle: Creates a database table object with database functions and a userdata at index 0, which will call lua_dbgc when garbage collected. */ static lua_db_handle* lua_push_db_handle(lua_State *L, request_rec* r, int type, apr_pool_t* pool) { lua_db_handle* db; lua_newtable(L); db = lua_newuserdata(L, sizeof(lua_db_handle)); db->alive = 1; db->pool = pool; db->type = type; db->dbdhandle = 0; db->server = r->server; luaL_newmetatable(L, "lua_apr.dbacquire"); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, lua_db_gc); lua_rawset(L, -3); lua_setmetatable(L, -2); lua_rawseti(L, -2, 0); lua_pushliteral(L, "escape"); lua_pushcfunction(L, lua_db_escape); lua_rawset(L, -3); lua_pushliteral(L, "close"); lua_pushcfunction(L, lua_db_close); lua_rawset(L, -3); lua_pushliteral(L, "select"); lua_pushcfunction(L, lua_db_select); lua_rawset(L, -3); lua_pushliteral(L, "query"); lua_pushcfunction(L, lua_db_query); lua_rawset(L, -3); lua_pushliteral(L, "active"); lua_pushcfunction(L, lua_db_active); lua_rawset(L, -3); lua_pushliteral(L, "prepare"); lua_pushcfunction(L, lua_db_prepare); lua_rawset(L, -3); lua_pushliteral(L, "prepared"); lua_pushcfunction(L, lua_db_prepared); lua_rawset(L, -3); return db; } /* ============================================================================= dbacquire(dbType, dbString): Opens a new connection to a database of type _dbType_ and with the connection parameters _dbString_. If successful, returns a table with functions for using the database handle. If an error occurs, returns nil as the first parameter and the error message as the second. See the APR_DBD for a list of database types and connection strings supported. ============================================================================= */ int lua_db_acquire(lua_State *L) { /*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const char *type; const char *arguments; const char *error = 0; request_rec *r; lua_db_handle *db = 0; apr_status_t rc = 0; ap_dbd_t *dbdhandle = NULL; apr_pool_t *pool = NULL; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ r = ap_lua_check_request_rec(L, 1); if (r) { type = luaL_optstring(L, 2, "mod_dbd"); /* Defaults to mod_dbd */ if (!strcmp(type, "mod_dbd")) { lua_settop(L, 0); lua_ap_dbd_open = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_open); if (lua_ap_dbd_open) dbdhandle = (ap_dbd_t *) lua_ap_dbd_open( r->server->process->pool, r->server); if (dbdhandle) { db = lua_push_db_handle(L, r, LUA_DBTYPE_MOD_DBD, dbdhandle->pool); db->driver = dbdhandle->driver; db->handle = dbdhandle->handle; db->dbdhandle = dbdhandle; return 1; } else { lua_pushnil(L); if ( lua_ap_dbd_open == NULL ) lua_pushliteral(L, "mod_dbd doesn't seem to have been loaded."); else lua_pushliteral( L, "Could not acquire connection from mod_dbd. If your database is running, this may indicate a permission problem."); return 2; } } else { rc = apr_pool_create(&pool, NULL); if (rc != APR_SUCCESS) { lua_pushnil(L); lua_pushliteral(L, "Could not allocate memory for database!"); return 2; } apr_pool_tag(pool, "lua_dbd_pool"); apr_dbd_init(pool); dbdhandle = apr_pcalloc(pool, sizeof(ap_dbd_t)); rc = apr_dbd_get_driver(pool, type, &dbdhandle->driver); if (rc == APR_SUCCESS) { luaL_checktype(L, 3, LUA_TSTRING); arguments = lua_tostring(L, 3); lua_settop(L, 0); if (*arguments) { rc = apr_dbd_open_ex(dbdhandle->driver, pool, arguments, &dbdhandle->handle, &error); if (rc == APR_SUCCESS) { db = lua_push_db_handle(L, r, LUA_DBTYPE_APR_DBD, pool); db->driver = dbdhandle->driver; db->handle = dbdhandle->handle; db->dbdhandle = dbdhandle; return 1; } else { lua_pushnil(L); if (error) { lua_pushstring(L, error); return 2; } return 1; } } lua_pushnil(L); lua_pushliteral(L, "No database connection string was specified."); apr_pool_destroy(pool); return (2); } else { lua_pushnil(L); if (APR_STATUS_IS_ENOTIMPL(rc)) { lua_pushfstring(L, "driver for %s not available", type); } else if (APR_STATUS_IS_EDSOOPEN(rc)) { lua_pushfstring(L, "can't find driver for %s", type); } else if (APR_STATUS_IS_ESYMNOTFOUND(rc)) { lua_pushfstring(L, "driver for %s is invalid or corrupted", type); } else { lua_pushliteral(L, "mod_lua not compatible with APR in get_driver"); } lua_pushinteger(L, rc); apr_pool_destroy(pool); return 3; } } lua_pushnil(L); return 1; } return 0; }
13,452
3,673
#include <os> void Service::start(const std::string&) { INFO("service", "Testing GRUB. And you've obviously booted OK"); INFO("service", "SUCCESS"); }
54
348
{"nom":"Villers-Patras","circ":"4ème circonscription","dpt":"Côte-d'Or","inscrits":81,"abs":34,"votants":47,"blancs":3,"nuls":1,"exp":43,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":26},{"nuance":"REM","nom":"Mme <NAME>","voix":17}]}
99
2,757
/** @file FMP Authentication RSA2048SHA256 handler. Provide generic FMP authentication functions for DXE/PEI post memory phase. Caution: This module requires additional review when modified. This module will have external input - capsule image. This external input must be validated carefully to avoid security issue like buffer overflow, integer overflow. FmpAuthenticatedHandlerRsa2048Sha256(), AuthenticateFmpImage() will receive untrusted input and do basic validation. Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include <Uefi.h> #include <Guid/SystemResourceTable.h> #include <Guid/FirmwareContentsSigned.h> #include <Guid/WinCertificate.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/BaseCryptLib.h> #include <Library/FmpAuthenticationLib.h> #include <Library/PcdLib.h> #include <Protocol/FirmwareManagement.h> #include <Guid/SystemResourceTable.h> /// /// Public Exponent of RSA Key. /// STATIC CONST UINT8 mRsaE[] = { 0x01, 0x00, 0x01 }; /** The handler is used to do the authentication for FMP capsule based upon EFI_FIRMWARE_IMAGE_AUTHENTICATION. Caution: This function may receive untrusted input. This function assumes the caller AuthenticateFmpImage() already did basic validation for EFI_FIRMWARE_IMAGE_AUTHENTICATION. @param[in] Image Points to an FMP authentication image, started from EFI_FIRMWARE_IMAGE_AUTHENTICATION. @param[in] ImageSize Size of the authentication image in bytes. @param[in] PublicKeyData The public key data used to validate the signature. @param[in] PublicKeyDataLength The length of the public key data. @retval RETURN_SUCCESS Authentication pass. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_SUCCESS. @retval RETURN_SECURITY_VIOLATION Authentication fail. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_AUTH_ERROR. @retval RETURN_INVALID_PARAMETER The image is in an invalid format. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT. @retval RETURN_OUT_OF_RESOURCES No Authentication handler associated with CertType. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_INSUFFICIENT_RESOURCES. **/ RETURN_STATUS FmpAuthenticatedHandlerRsa2048Sha256 ( IN EFI_FIRMWARE_IMAGE_AUTHENTICATION *Image, IN UINTN ImageSize, IN CONST UINT8 *PublicKeyData, IN UINTN PublicKeyDataLength ) { RETURN_STATUS Status; EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlockRsa2048Sha256; BOOLEAN CryptoStatus; UINT8 Digest[SHA256_DIGEST_SIZE]; UINT8 *PublicKey; UINTN PublicKeyBufferSize; VOID *HashContext; VOID *Rsa; DEBUG ((DEBUG_INFO, "FmpAuthenticatedHandlerRsa2048Sha256 - Image: 0x%08x - 0x%08x\n", (UINTN)Image, (UINTN)ImageSize)); if (Image->AuthInfo.Hdr.dwLength != OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData) + sizeof(EFI_CERT_BLOCK_RSA_2048_SHA256)) { DEBUG((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256 - dwLength: 0x%04x, dwLength - 0x%04x\n", (UINTN)Image->AuthInfo.Hdr.dwLength, (UINTN)OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData) + sizeof(EFI_CERT_BLOCK_RSA_2048_SHA256))); return RETURN_INVALID_PARAMETER; } CertBlockRsa2048Sha256 = (EFI_CERT_BLOCK_RSA_2048_SHA256 *)Image->AuthInfo.CertData; if (!CompareGuid(&CertBlockRsa2048Sha256->HashType, &gEfiHashAlgorithmSha256Guid)) { DEBUG((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256 - HashType: %g, expect - %g\n", &CertBlockRsa2048Sha256->HashType, &gEfiHashAlgorithmSha256Guid)); return RETURN_INVALID_PARAMETER; } HashContext = NULL; Rsa = NULL; // // Allocate hash context buffer required for SHA 256 // HashContext = AllocatePool (Sha256GetContextSize ()); if (HashContext == NULL) { CryptoStatus = FALSE; DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Can not allocate hash context\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } // // Hash public key from data payload with SHA256. // ZeroMem (Digest, SHA256_DIGEST_SIZE); CryptoStatus = Sha256Init (HashContext); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Init() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } CryptoStatus = Sha256Update (HashContext, &CertBlockRsa2048Sha256->PublicKey, sizeof(CertBlockRsa2048Sha256->PublicKey)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Update() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } CryptoStatus = Sha256Final (HashContext, Digest); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Final() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } // // Fail if the PublicKey is not one of the public keys in the input PublicKeyData. // PublicKey = (VOID *)PublicKeyData; PublicKeyBufferSize = PublicKeyDataLength; CryptoStatus = FALSE; while (PublicKeyBufferSize != 0) { if (CompareMem (Digest, PublicKey, SHA256_DIGEST_SIZE) == 0) { CryptoStatus = TRUE; break; } PublicKey = PublicKey + SHA256_DIGEST_SIZE; PublicKeyBufferSize = PublicKeyBufferSize - SHA256_DIGEST_SIZE; } if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Public key in section is not supported\n")); Status = RETURN_SECURITY_VIOLATION; goto Done; } // // Generate & Initialize RSA Context. // Rsa = RsaNew (); if (Rsa == NULL) { CryptoStatus = FALSE; DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: RsaNew() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } // // Set RSA Key Components. // NOTE: Only N and E are needed to be set as RSA public key for signature verification. // CryptoStatus = RsaSetKey (Rsa, RsaKeyN, CertBlockRsa2048Sha256->PublicKey, sizeof(CertBlockRsa2048Sha256->PublicKey)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: RsaSetKey(RsaKeyN) failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } CryptoStatus = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: RsaSetKey(RsaKeyE) failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } // // Hash data payload with SHA256. // ZeroMem (Digest, SHA256_DIGEST_SIZE); CryptoStatus = Sha256Init (HashContext); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Init() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } // It is a signature across the variable data and the Monotonic Count value. CryptoStatus = Sha256Update ( HashContext, (UINT8 *)Image + sizeof(Image->MonotonicCount) + Image->AuthInfo.Hdr.dwLength, ImageSize - sizeof(Image->MonotonicCount) - Image->AuthInfo.Hdr.dwLength ); if (!CryptoStatus) { DEBUG((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Update() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } CryptoStatus = Sha256Update ( HashContext, (UINT8 *)&Image->MonotonicCount, sizeof(Image->MonotonicCount) ); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Update() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } CryptoStatus = Sha256Final (HashContext, Digest); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: Sha256Final() failed\n")); Status = RETURN_OUT_OF_RESOURCES; goto Done; } // // Verify the RSA 2048 SHA 256 signature. // CryptoStatus = RsaPkcs1Verify ( Rsa, Digest, SHA256_DIGEST_SIZE, CertBlockRsa2048Sha256->Signature, sizeof (CertBlockRsa2048Sha256->Signature) ); if (!CryptoStatus) { // // If RSA 2048 SHA 256 signature verification fails, AUTH tested failed bit is set. // DEBUG ((DEBUG_ERROR, "FmpAuthenticatedHandlerRsa2048Sha256: RsaPkcs1Verify() failed\n")); Status = RETURN_SECURITY_VIOLATION; goto Done; } DEBUG ((DEBUG_INFO, "FmpAuthenticatedHandlerRsa2048Sha256: PASS verification\n")); Status = RETURN_SUCCESS; Done: // // Free allocated resources used to perform RSA 2048 SHA 256 signature verification // if (Rsa != NULL) { RsaFree (Rsa); } if (HashContext != NULL) { FreePool (HashContext); } return Status; } /** The function is used to do the authentication for FMP capsule based upon EFI_FIRMWARE_IMAGE_AUTHENTICATION. The FMP capsule image should start with EFI_FIRMWARE_IMAGE_AUTHENTICATION, followed by the payload. If the return status is RETURN_SUCCESS, the caller may continue the rest FMP update process. If the return status is NOT RETURN_SUCCESS, the caller should stop the FMP update process and convert the return status to LastAttemptStatus to indicate that FMP update fails. The LastAttemptStatus can be got from ESRT table or via EFI_FIRMWARE_MANAGEMENT_PROTOCOL.GetImageInfo(). Caution: This function may receive untrusted input. @param[in] Image Points to an FMP authentication image, started from EFI_FIRMWARE_IMAGE_AUTHENTICATION. @param[in] ImageSize Size of the authentication image in bytes. @param[in] PublicKeyData The public key data used to validate the signature. @param[in] PublicKeyDataLength The length of the public key data. @retval RETURN_SUCCESS Authentication pass. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_SUCCESS. @retval RETURN_SECURITY_VIOLATION Authentication fail. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_AUTH_ERROR. @retval RETURN_INVALID_PARAMETER The image is in an invalid format. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT. @retval RETURN_UNSUPPORTED No Authentication handler associated with CertType. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT. @retval RETURN_UNSUPPORTED Image or ImageSize is invalid. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_INVALID_FORMAT. @retval RETURN_OUT_OF_RESOURCES No Authentication handler associated with CertType. The LastAttemptStatus should be LAST_ATTEMPT_STATUS_ERROR_INSUFFICIENT_RESOURCES. **/ RETURN_STATUS EFIAPI AuthenticateFmpImage ( IN EFI_FIRMWARE_IMAGE_AUTHENTICATION *Image, IN UINTN ImageSize, IN CONST UINT8 *PublicKeyData, IN UINTN PublicKeyDataLength ) { GUID *CertType; EFI_STATUS Status; if ((Image == NULL) || (ImageSize == 0)) { return RETURN_UNSUPPORTED; } if ((PublicKeyDataLength % SHA256_DIGEST_SIZE) != 0) { DEBUG ((DEBUG_ERROR, "PublicKeyDataLength is not multiple SHA256 size\n")); return RETURN_UNSUPPORTED; } if (ImageSize < sizeof(EFI_FIRMWARE_IMAGE_AUTHENTICATION)) { DEBUG((DEBUG_ERROR, "AuthenticateFmpImage - ImageSize too small\n")); return RETURN_INVALID_PARAMETER; } if (Image->AuthInfo.Hdr.dwLength <= OFFSET_OF(WIN_CERTIFICATE_UEFI_GUID, CertData)) { DEBUG((DEBUG_ERROR, "AuthenticateFmpImage - dwLength too small\n")); return RETURN_INVALID_PARAMETER; } if ((UINTN) Image->AuthInfo.Hdr.dwLength > MAX_UINTN - sizeof(UINT64)) { DEBUG((DEBUG_ERROR, "AuthenticateFmpImage - dwLength too big\n")); return RETURN_INVALID_PARAMETER; } if (ImageSize <= sizeof(Image->MonotonicCount) + Image->AuthInfo.Hdr.dwLength) { DEBUG((DEBUG_ERROR, "AuthenticateFmpImage - ImageSize too small\n")); return RETURN_INVALID_PARAMETER; } if (Image->AuthInfo.Hdr.wRevision != 0x0200) { DEBUG((DEBUG_ERROR, "AuthenticateFmpImage - wRevision: 0x%02x, expect - 0x%02x\n", (UINTN)Image->AuthInfo.Hdr.wRevision, (UINTN)0x0200)); return RETURN_INVALID_PARAMETER; } if (Image->AuthInfo.Hdr.wCertificateType != WIN_CERT_TYPE_EFI_GUID) { DEBUG((DEBUG_ERROR, "AuthenticateFmpImage - wCertificateType: 0x%02x, expect - 0x%02x\n", (UINTN)Image->AuthInfo.Hdr.wCertificateType, (UINTN)WIN_CERT_TYPE_EFI_GUID)); return RETURN_INVALID_PARAMETER; } CertType = &Image->AuthInfo.CertType; DEBUG((DEBUG_INFO, "AuthenticateFmpImage - CertType: %g\n", CertType)); if (CompareGuid (&gEfiCertTypeRsa2048Sha256Guid, CertType)) { // // Call the match handler to extract raw data for the input section data. // Status = FmpAuthenticatedHandlerRsa2048Sha256 ( Image, ImageSize, PublicKeyData, PublicKeyDataLength ); return Status; } // // Not found, the input guided section is not supported. // return RETURN_UNSUPPORTED; }
6,361
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/YouTube.framework/YouTube */ #import <YouTube/YouTube-Structs.h> #import <YouTube/XXUnknownSuperclass.h> @class NSURL, NSArray, UIMoviePlayerController, UIImageView, YTSearchRequest, UILabel, YTVideo; @interface YTMovieView : XXUnknownSuperclass { id _delegate; // 48 = 0x30 YTVideo *_video; // 52 = 0x34 NSArray *_videoList; // 56 = 0x38 NSURL *_youTubeURL; // 60 = 0x3c YTSearchRequest *_videoInfoRequest; // 64 = 0x40 UIMoviePlayerController *_moviePlayer; // 68 = 0x44 UIImageView *_bugView; // 72 = 0x48 UIImageView *_gradientView; // 76 = 0x4c BOOL _canAutoPlay; // 80 = 0x50 BOOL _shownFromExternalURL; // 81 = 0x51 BOOL _switchingVideos; // 82 = 0x52 BOOL _controlsShown; // 83 = 0x53 BOOL _useSmallLogo; // 84 = 0x54 BOOL _showControlsAfterFullscreenExit; // 85 = 0x55 BOOL _isShown; // 86 = 0x56 double _seekTime; // 88 = 0x58 UILabel *_logLabel; // 96 = 0x60 } @property(readonly, retain) YTVideo *video; // G=0x5361; converted property @property(readonly, retain) UIMoviePlayerController *moviePlayer; // G=0x5341; converted property - (id)initWithFrame:(CGRect)frame; // 0x7721 - (void)dealloc; // 0x761d - (void)setDelegate:(id)delegate; // 0x530d - (void)setFrame:(CGRect)frame; // 0x754d - (void)setSeekTime:(double)time; // 0x531d - (void)_destroyMoviePlayer; // 0x53f5 - (BOOL)_canShare; // 0x54e9 - (BOOL)_canBookmark; // 0x553d - (void)_updateCaptionsForMovie; // 0x5591 - (void)_setupBackground; // 0x6e2d - (BOOL)_loggingEnabled; // 0x7511 - (void)_switchToVideo:(id)video; // 0x55f1 - (void)_loadVideoFromURL:(BOOL)url; // 0x7281 - (void)_loadVideoInfoWithID:(id)anId; // 0x5b09 - (void)_cancelVideoInfoRequest; // 0x5b79 - (void)willShowForVideo:(id)video inList:(id)list orVideoID:(id)anId; // 0x5bd9 - (void)didShow; // 0x5dad - (void)willHide; // 0x5dfd - (void)didHide; // 0x5f2d - (void)play; // 0x5f91 - (void)pause; // 0x5fb1 - (BOOL)isPlaying; // 0x5fd1 - (BOOL)canContinuePlayingWhenLocked; // 0x6001 - (int)orientation; // 0x6025 - (void)setCanAutoPlay:(BOOL)play; // 0x6051 - (void)willShowAlert; // 0x6095 - (void)setFullscreen:(BOOL)fullscreen; // 0x60c5 - (id)fullscreenView; // 0x60e9 // converted property getter: - (id)moviePlayer; // 0x5341 - (void)useSmallLogo:(BOOL)logo; // 0x5351 // converted property getter: - (id)video; // 0x5361 - (BOOL)moviePlayerExitRequest:(id)request exitReason:(int)reason; // 0x6109 - (void)_hideOverlay; // 0x6141 - (void)_hideBug; // 0x61a1 - (void)moviePlayerPlaybackStateDidChange:(id)moviePlayerPlaybackState fromPlaybackState:(unsigned)playbackState; // 0x61f5 - (void)moviePlayerBufferingStateDidChange:(id)moviePlayerBufferingState; // 0x6279 - (BOOL)moviePlayerAddBookmarkButtonPressed:(id)pressed; // 0x62d1 - (BOOL)moviePlayerEmailButtonPressed:(id)pressed; // 0x630d - (void)shareSheetWillShow; // 0x6355 - (void)shareSheetDidHide; // 0x63b1 - (BOOL)moviePlayerForwardButtonPressed:(id)pressed; // 0x640d - (BOOL)moviePlayerBackwardButtonPressed:(id)pressed; // 0x65c1 - (BOOL)moviePlayerHeadsetNextTrackPressed:(id)pressed; // 0x67ad - (BOOL)moviePlayerHeadsetPreviousTrackPressed:(id)pressed; // 0x67c5 - (BOOL)moviePlayer:(id)player validateAction:(SEL)action; // 0x67dd - (void)moviePlayerWillEnterFullscreen:(id)moviePlayer; // 0x6851 - (void)moviePlayerWillExitFullscreen:(id)moviePlayer; // 0x68a5 - (void)moviePlayerDidExitFullscreen:(id)moviePlayer; // 0x68f9 - (void)moviePlayerWillShowOverlay:(id)moviePlayer; // 0x6985 - (void)moviePlayerDidShowOverlay:(id)moviePlayer; // 0x69d9 - (void)moviePlayerWillHideOverlay:(id)moviePlayer; // 0x6a2d - (void)moviePlayerDidHideOverlay:(id)moviePlayer; // 0x6a81 - (CGRect)moviePlayerFrameAfterFullscreenExit:(id)exit; // 0x6ad5 - (void)moviePlayerPlaybackDidEnd:(id)moviePlayerPlayback; // 0x6b49 - (void)_presentAlertForError:(id)error reasonCode:(id)code; // 0x6be9 - (void)searchRequest:(id)request receivedVideos:(id)videos startIndex:(unsigned)index videosRemaining:(unsigned)remaining; // 0x6c49 - (void)searchRequest:(id)request didFailWithError:(id)error; // 0x6db5 - (void)forceControlsVisible:(BOOL)visible; // 0x6df9 @end
1,710
593
package org.ananas.cli; import org.ananas.cli.commands.MainCommand; import org.ananas.runner.kernel.ExtensionRegistry; import picocli.CommandLine; public class Main { public static void main(String[] args) { ExtensionRegistry.init(); int exitCode = new CommandLine(new MainCommand()).execute(args); if (exitCode >= 0) { // when runnng start server sub command, return -1 to avoid exit immediately System.exit(exitCode); } } }
159
9,959
<filename>test/transform/resource/before/ConflictingStaticConstructorNames.java @lombok.Data(staticConstructor="of") @lombok.NoArgsConstructor class ConflictingStaticConstructorNames { }
56
28,056
<gh_stars>1000+ package com.alibaba.json.bvt; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.fastjson.util.IOUtils; public class CharTypesTest extends TestCase { static byte[] specicalFlags_singleQuotes = IOUtils.specicalFlags_singleQuotes; static byte[] specicalFlags_doubleQuotes = IOUtils.specicalFlags_doubleQuotes; public void test_0() throws Exception { Assert.assertTrue(isSpecial_doubleQuotes('\n')); Assert.assertTrue(isSpecial_doubleQuotes('\r')); Assert.assertTrue(isSpecial_doubleQuotes('\b')); Assert.assertTrue(isSpecial_doubleQuotes('\f')); Assert.assertTrue(isSpecial_doubleQuotes('\"')); Assert.assertFalse(isSpecial_doubleQuotes('0')); Assert.assertTrue(isSpecial_doubleQuotes('\0')); Assert.assertFalse(isSpecial_doubleQuotes('中')); Assert.assertFalse(isSpecial_doubleQuotes('中')); } public static boolean isSpecial_doubleQuotes(char ch) { return ch < specicalFlags_doubleQuotes.length && specicalFlags_doubleQuotes[ch] != 0; } }
444
307
// The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.common.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> * */ public class CollectionUtils { public static <K, V> Map<K, V> toMap(K k1, V v1) { return toMap(new HashMap<K, V>(), k1, v1); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3, k4, v4); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8); } public static <K, V> Map<K, V> toMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { return toMap(new HashMap<K, V>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3, k4, v4))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8))); } public static <K, V> Map<K, V> unmodifiableMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9))); } public static <K, V> Map<K, V> unmodifiableMap(Object... entries) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(new HashMap<>(), entries))); } public static <K, V> Map<K, V> unmodifiableMap(Map<K, V> m, Object... entries) { return ObjectUtils.cast(Collections.unmodifiableMap(toMap(m, entries))); } public static <K, V> Map<K, V> toMap(Object... entries) { return toMap(new HashMap<K, V>(), entries); } public static <K, V> Map<K, V> toMap(Map<K, V> m, Object... keyValues) { AssertUtils.assertTrue(keyValues.length % 2 == 0, "keyValues is invalid."); for (int i = 0; i < keyValues.length; i += 2) { K k = ObjectUtils.cast(keyValues[i]); V v = ObjectUtils.cast(keyValues[i + 1]); m.put(k, v); } return m; } @SafeVarargs public static <V> Set<V> unmodifiableSet(V... elements) { return Collections.unmodifiableSet(toSet(new HashSet<V>(), elements)); } @SafeVarargs public static <V> Set<V> unmodifiableSet(Set<V> s, V... elements) { return Collections.unmodifiableSet(toSet(s, elements)); } @SafeVarargs public static <V> Set<V> toSet(V... elements) { return toSet(new HashSet<V>(), elements); } @SafeVarargs public static <V> Set<V> toSet(Set<V> s, V... elements) { Arrays.stream(elements).forEach(e -> s.add(e)); return s; } @SafeVarargs public static <V> List<V> unmodifiableList(V... elements) { return Collections.unmodifiableList(toList(new ArrayList<V>(), elements)); } @SafeVarargs public static <V> List<V> unmodifiableList(List<V> l, V... elements) { return Collections.unmodifiableList(toList(l, elements)); } @SafeVarargs public static <V> List<V> toList(V... elements) { return toList(new ArrayList<V>(), elements); } @SafeVarargs public static <V> List<V> toList(List<V> l, V... elements) { Arrays.stream(elements).forEach(e -> l.add(e)); return l; } public static <V> List<V> unmodifiable(List<V> list) { return ((list != null) && !list.isEmpty()) ? Collections.unmodifiableList(list) : Collections.<V>emptyList(); } public static <K, V> Map<K, V> unmodifiable(Map<K, V> map) { return ((map != null) && !map.isEmpty()) ? Collections.unmodifiableMap(map) : Collections.<K, V>emptyMap(); } public static <V> Set<V> unmodifiable(Set<V> set) { return ((set != null) && !set.isEmpty()) ? Collections.unmodifiableSet(set) : Collections.<V>emptySet(); } public static <V> List<V> unmodifiableOrNull(List<V> list) { return ((list != null) && !list.isEmpty()) ? Collections.unmodifiableList(list) : null; } public static <K, V> Map<K, V> unmodifiableOrNull(Map<K, V> map) { return ((map != null) && !map.isEmpty()) ? Collections.unmodifiableMap(map) : null; } public static <V> Set<V> unmodifiableOrNull(Set<V> set) { return ((set != null) && !set.isEmpty()) ? Collections.unmodifiableSet(set) : null; } public static <K, V> Map<V, K> inverse(Map<K, V> m, Map<V, K> newMap) { for (Entry<K, V> entry : m.entrySet()) { newMap.put(entry.getValue(), entry.getKey()); } return newMap; } public static <T> boolean hasElements(Collection<T> c) { return (c != null) && (c.size() > 0); } }
3,717
1,652
<filename>redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/migration/status/PublishState.java package com.ctrip.xpipe.redis.console.migration.status; /** * @author wenchao.meng * <p> * Jun 27, 2017 */ public interface PublishState extends MigrationState{ void forceEnd(); }
124
918
/* * 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.gobblin.runtime.embedded; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.avro.Schema; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.HiveMetaStoreClient; import org.apache.hadoop.hive.metastore.IMetaStoreClient; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.session.SessionState; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.api.client.util.Charsets; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.typesafe.config.Config; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.converter.GobblinMetricsPinotFlattenerConverter; import org.apache.gobblin.data.management.copy.CopyConfiguration; import org.apache.gobblin.data.management.copy.CopySource; import org.apache.gobblin.data.management.copy.SchemaCheckedCopySource; import org.apache.gobblin.runtime.api.JobExecutionResult; import org.apache.gobblin.util.HiveJdbcConnector; import org.apache.gobblin.util.PathUtils; import org.apache.gobblin.util.filesystem.DataFileVersionStrategy; public class EmbeddedGobblinDistcpTest { private HiveJdbcConnector jdbcConnector; private IMetaStoreClient metaStoreClient; private static final String TEST_DB = "testdb"; private static final String TEST_TABLE = "test_table"; private static final String TARGET_PATH = "/tmp/target"; private static final String TARGET_DB = "target"; @BeforeClass public void setup() throws Exception { try { HiveConf hiveConf = new HiveConf(); // Start a Hive session in this thread and register the UDF SessionState.start(hiveConf); SessionState.get().initTxnMgr(hiveConf); metaStoreClient = new HiveMetaStoreClient(new HiveConf()); jdbcConnector = HiveJdbcConnector.newEmbeddedConnector(2); } catch (HiveException he) { throw new RuntimeException("Failed to start Hive session.", he); } catch (SQLException se) { throw new RuntimeException("Cannot initialize the jdbc-connector due to: ", se); } } @Test public void test() throws Exception { String fileName = "file"; File tmpSource = Files.createTempDir(); tmpSource.deleteOnExit(); File tmpTarget = Files.createTempDir(); tmpTarget.deleteOnExit(); File tmpFile = new File(tmpSource, fileName); tmpFile.createNewFile(); FileOutputStream os = new FileOutputStream(tmpFile); for (int i = 0; i < 100; i++) { os.write("myString".getBytes(Charsets.UTF_8)); } os.close(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertFalse(new File(tmpTarget, fileName).exists()); EmbeddedGobblinDistcp embedded = new EmbeddedGobblinDistcp(new Path(tmpSource.getAbsolutePath()), new Path(tmpTarget.getAbsolutePath())); embedded.setLaunchTimeout(30, TimeUnit.SECONDS); embedded.run(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertTrue(new File(tmpTarget, fileName).exists()); } @Test public void hiveTest() throws Exception { Statement statement = jdbcConnector.getConnection().createStatement(); // Start from a fresh Hive backup: No DB, no table. // Create a DB. statement.execute("CREATE database if not exists " + TEST_DB); // Create a table. String tableCreationSQL = "CREATE TABLE IF NOT EXISTS $testdb.$test_table (id int, name String)\n" + "ROW FORMAT DELIMITED\n" + "FIELDS TERMINATED BY '\\t'\n" + "LINES TERMINATED BY '\\n'\n" + "STORED AS TEXTFILE"; statement.execute(tableCreationSQL.replace("$testdb",TEST_DB).replace("$test_table", TEST_TABLE)); // Insert data String dataInsertionSQL = "INSERT INTO TABLE $testdb.$test_table VALUES (1, 'one'), (2, 'two'), (3, 'three')"; statement.execute(dataInsertionSQL.replace("$testdb",TEST_DB).replace("$test_table", TEST_TABLE)); String templateLoc = "templates/hiveDistcp.template"; // Either of the "from" or "to" will be used here since it is a Hive Distcp. EmbeddedGobblinDistcp embeddedHiveDistcp = new EmbeddedGobblinDistcp(templateLoc, new Path("a"), new Path("b")); embeddedHiveDistcp.setConfiguration("hive.dataset.copy.target.database", TARGET_DB); embeddedHiveDistcp.setConfiguration("hive.dataset.copy.target.table.prefixReplacement", TARGET_PATH); String dbPathTemplate = "/$testdb.db/$test_table"; String rootPathOfSourceDate = metaStoreClient.getConfigValue("hive.metastore.warehouse.dir", "") .concat(dbPathTemplate.replace("$testdb", TEST_DB).replace("$test_table",TEST_TABLE) ); embeddedHiveDistcp.setConfiguration("hive.dataset.copy.target.table.prefixToBeReplaced", rootPathOfSourceDate); embeddedHiveDistcp.run(); // Verify the table is existed in the target and file exists in the target location. metaStoreClient.tableExists(TARGET_DB, TEST_TABLE); FileSystem fs = FileSystem.getLocal(new Configuration()); fs.exists(new Path(TARGET_PATH)); } // Tearing down the Hive components from derby driver if there's anything generated through the test. @AfterClass public void hiveTearDown() throws Exception { FileSystem fs = FileSystem.getLocal(new Configuration()); Path targetPath = new Path(TARGET_PATH); if (fs.exists(targetPath)) { fs.delete(targetPath, true); } if (metaStoreClient != null) { // Clean out all tables in case there are any, to avoid db-drop failure. for (String tblName : metaStoreClient.getAllTables(TEST_DB)) { metaStoreClient.dropTable(TEST_DB, tblName); } if (metaStoreClient.getAllDatabases().contains(TEST_DB)) { metaStoreClient.dropDatabase(TEST_DB); } // Clean the target table and DB if (metaStoreClient.tableExists("target", TEST_TABLE)) { metaStoreClient.dropTable("target", TEST_TABLE, true, true); } if (metaStoreClient.getAllDatabases().contains(TARGET_DB)) { metaStoreClient.dropDatabase(TARGET_DB); } metaStoreClient.close(); } jdbcConnector.close(); } @Test public void testCheckSchema() throws Exception { Schema schema = null; try (InputStream is = GobblinMetricsPinotFlattenerConverter.class.getClassLoader().getResourceAsStream("avroSchemaManagerTest/expectedSchema.avsc")) { schema = new Schema.Parser().parse(is); } catch (IOException e) { e.printStackTrace(); } String fileName = "file.avro"; File tmpSource = Files.createTempDir(); tmpSource.deleteOnExit(); File tmpTarget = Files.createTempDir(); tmpTarget.deleteOnExit(); File tmpFile = new File(tmpSource, fileName); tmpFile.createNewFile(); GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(schema, tmpFile); for(int i = 0; i < 100; i++) { GenericRecord record = new GenericData.Record(schema); record.put("foo", i); dataFileWriter.append(record); } Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertFalse(new File(tmpTarget, fileName).exists()); EmbeddedGobblinDistcp embedded = new EmbeddedGobblinDistcp(new Path(tmpSource.getAbsolutePath()), new Path(tmpTarget.getAbsolutePath())); embedded.setConfiguration(CopySource.SCHEMA_CHECK_ENABLED, "true"); embedded.setLaunchTimeout(30, TimeUnit.SECONDS); embedded.setConfiguration(ConfigurationKeys.SOURCE_CLASS_KEY, SchemaCheckedCopySource.class.getName()); embedded.setConfiguration(ConfigurationKeys.AVRO_SCHEMA_CHECK_STRATEGY, "org.apache.gobblin.util.schema_check.AvroSchemaCheckDefaultStrategy"); //test when schema is not the expected one, the job will be aborted. embedded.setConfiguration(ConfigurationKeys.COPY_EXPECTED_SCHEMA, "{\"type\":\"record\",\"name\":\"baseRecord\",\"fields\":[{\"name\":\"foo1\",\"type\":[\"null\",\"int\"],\"doc\":\"this is for test\",\"default\":null}]}"); JobExecutionResult result = embedded.run(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertFalse(result.isSuccessful()); Assert.assertFalse(new File(tmpTarget, fileName).exists()); embedded.setConfiguration(ConfigurationKeys.COPY_EXPECTED_SCHEMA, "{\"type\":\"record\",\"name\":\"baseRecord\",\"fields\":[{\"name\":\"foo\",\"type\":[\"string\",\"int\"],\"doc\":\"this is for test\",\"default\":null}]}"); result = embedded.run(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertFalse(result.isSuccessful()); Assert.assertFalse(new File(tmpTarget, fileName).exists()); //test when schema is the expected one, the job will succeed. embedded.setConfiguration(ConfigurationKeys.COPY_EXPECTED_SCHEMA, "{\"type\":\"record\",\"name\":\"baseRecord\",\"fields\":[{\"name\":\"foo\",\"type\":[\"null\",\"int\"],\"doc\":\"this is for test\",\"default\":null}]}"); result = embedded.run(); Assert.assertTrue(result.isSuccessful()); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertTrue(new File(tmpTarget, fileName).exists()); } @Test public void testWithVersionPreserve() throws Exception { String fileName = "file"; File tmpSource = Files.createTempDir(); tmpSource.deleteOnExit(); File tmpTarget = Files.createTempDir(); tmpTarget.deleteOnExit(); File tmpFile = new File(tmpSource, fileName); tmpFile.createNewFile(); FileOutputStream os = new FileOutputStream(tmpFile); for (int i = 0; i < 100; i++) { os.write("myString".getBytes(Charsets.UTF_8)); } os.close(); MyDataFileVersion versionStrategy = new MyDataFileVersion(); versionStrategy.setVersion(new Path(tmpFile.getAbsolutePath()), 123L); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertFalse(new File(tmpTarget, fileName).exists()); EmbeddedGobblinDistcp embedded = new EmbeddedGobblinDistcp(new Path(tmpSource.getAbsolutePath()), new Path(tmpTarget.getAbsolutePath())); embedded.setLaunchTimeout(30, TimeUnit.SECONDS); embedded.setConfiguration(DataFileVersionStrategy.DATA_FILE_VERSION_STRATEGY_KEY, MyDataFileVersion.class.getName()); embedded.setConfiguration(CopyConfiguration.PRESERVE_ATTRIBUTES_KEY, "v"); embedded.run(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertTrue(new File(tmpTarget, fileName).exists()); Assert.assertEquals((long) versionStrategy.getVersion(new Path(tmpTarget.getAbsolutePath(), fileName)), 123l); } @Test public void testWithModTimePreserve() throws Exception { FileSystem fs = FileSystem.getLocal(new Configuration()); String fileName = "file"; File tmpSource = Files.createTempDir(); tmpSource.deleteOnExit(); File tmpTarget = Files.createTempDir(); tmpTarget.deleteOnExit(); File tmpFile = new File(tmpSource, fileName); Assert.assertTrue(tmpFile.createNewFile()); FileOutputStream os = new FileOutputStream(tmpFile); for (int i = 0; i < 100; i++) { os.write("myString".getBytes(Charsets.UTF_8)); } os.close(); long originalModTime = fs.getFileStatus(new Path(tmpFile.getPath())).getModificationTime(); Assert.assertNotNull(originalModTime); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertFalse(new File(tmpTarget, fileName).exists()); EmbeddedGobblinDistcp embedded = new EmbeddedGobblinDistcp(new Path(tmpSource.getAbsolutePath()), new Path(tmpTarget.getAbsolutePath())); embedded.setLaunchTimeout(30, TimeUnit.SECONDS); embedded.setConfiguration(CopyConfiguration.PRESERVE_ATTRIBUTES_KEY, "t"); embedded.run(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertTrue(new File(tmpTarget, fileName).exists()); Assert.assertEquals(fs.getFileStatus(new Path(new File(tmpTarget, fileName).getAbsolutePath())).getModificationTime() , originalModTime); } @Test public void testWithModTimePreserveNegative() throws Exception { FileSystem fs = FileSystem.getLocal(new Configuration()); String fileName = "file_oh"; File tmpSource = Files.createTempDir(); tmpSource.deleteOnExit(); File tmpTarget = Files.createTempDir(); tmpTarget.deleteOnExit(); File tmpFile = new File(tmpSource, fileName); Assert.assertTrue(tmpFile.createNewFile()); FileOutputStream os = new FileOutputStream(tmpFile); for (int i = 0; i < 100; i++) { os.write("myString".getBytes(Charsets.UTF_8)); } os.close(); long originalModTime = fs.getFileStatus(new Path(tmpFile.getPath())).getModificationTime(); Assert.assertFalse(new File(tmpTarget, fileName).exists()); // Give a minimal gap between file creation and copy Thread.sleep(1000); // Negative case, not preserving the timestamp. tmpTarget.deleteOnExit(); EmbeddedGobblinDistcp embedded = new EmbeddedGobblinDistcp(new Path(tmpSource.getAbsolutePath()), new Path(tmpTarget.getAbsolutePath())); embedded.setLaunchTimeout(30, TimeUnit.SECONDS); embedded.run(); Assert.assertTrue(new File(tmpSource, fileName).exists()); Assert.assertTrue(new File(tmpTarget, fileName).exists()); long newModTime = fs.getFileStatus(new Path(new File(tmpTarget, fileName).getAbsolutePath())).getModificationTime(); Assert.assertTrue(newModTime != originalModTime); } public static class MyDataFileVersion implements DataFileVersionStrategy<Long>, DataFileVersionStrategy.DataFileVersionFactory<Long> { private static final Map<Path, Long> versions = new HashMap<>(); @Override public DataFileVersionStrategy<Long> createDataFileVersionStrategy(FileSystem fs, Config config) { return this; } @Override public Long getVersion(Path path) throws IOException { return versions.get(PathUtils.getPathWithoutSchemeAndAuthority(path)); } @Override public boolean setVersion(Path path, Long version) throws IOException { versions.put(PathUtils.getPathWithoutSchemeAndAuthority(path), version); return true; } @Override public boolean setDefaultVersion(Path path) throws IOException { return false; } @Override public Set<Characteristic> applicableCharacteristics() { return Sets.newHashSet(Characteristic.SETTABLE); } } }
5,456
489
package server.handler; import org.eclipse.jetty.server.Request; import skinny.http.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class PostBodyMethodHandler extends MethodHandler { @Override public Method getMethod() { return Method.POST(); } @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { try { if (request.getMethod().equals(getMethod().toString())) { InputStream is = request.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = r.readLine()) != null) { sb.append(line); } //System.out.println("POST:" + sb.toString()); response.setStatus(HttpServletResponse.SC_OK); response.setCharacterEncoding("UTF-8"); response.getWriter().print(sb.toString()); baseRequest.setHandled(true); } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } } catch (Exception e) { throw new RuntimeException(e); } } }
642
375
/* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.project; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.util.Optional; import org.eclipse.core.resources.IProject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.rf.ide.core.SystemVariableAccessor; import org.rf.ide.core.environment.EnvironmentSearchPaths; import org.rf.ide.core.project.RobotProjectConfig; import org.rf.ide.core.project.RobotProjectConfig.LibraryType; import org.rf.ide.core.project.RobotProjectConfig.ReferencedLibrary; import org.rf.ide.core.project.RobotProjectConfig.RelativeTo; import org.rf.ide.core.project.RobotProjectConfig.RelativityPoint; import org.rf.ide.core.project.RobotProjectConfig.SearchPath; import org.robotframework.red.junit.jupiter.Project; import org.robotframework.red.junit.jupiter.ProjectExtension; @ExtendWith(ProjectExtension.class) public class RedEclipseProjectConfigTest { @Project(files = { "resource.txt" }) static IProject project; @Test public void absolutePathIsResolved() throws Exception { final RobotProjectConfig projectConfig = new RobotProjectConfig(); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig); assertThat(redConfig.resolveToAbsolutePath(SearchPath.create(project.getName() + "/file.txt"))) .isEqualTo(project.getLocation().append("file.txt")); } @Test public void workspaceRelativePathIsResolved_forExistingResource() throws Exception { final RobotProjectConfig projectConfig = new RobotProjectConfig(); projectConfig.setRelativityPoint(RelativityPoint.create(RelativeTo.WORKSPACE)); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig); assertThat(redConfig.resolveToAbsolutePath(SearchPath.create("resource.txt"))) .isEqualTo(project.getWorkspace().getRoot().getLocation().append("resource.txt")); } @Test public void projectRelativePathIsResolved_forExistingResource() throws Exception { final RobotProjectConfig projectConfig = new RobotProjectConfig(); projectConfig.setRelativityPoint(RelativityPoint.create(RelativeTo.PROJECT)); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig); assertThat(redConfig.resolveToAbsolutePath(SearchPath.create("resource.txt"))) .isEqualTo(project.getLocation().append("resource.txt")); } @Test public void workspaceRelativePathIsResolved_forNonExistingResource() throws Exception { final RobotProjectConfig projectConfig = new RobotProjectConfig(); projectConfig.setRelativityPoint(RelativityPoint.create(RelativeTo.WORKSPACE)); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig); assertThat(redConfig.resolveToAbsolutePath(SearchPath.create("file.txt"))) .isEqualTo(project.getWorkspace().getRoot().getLocation().append("file.txt")); } @Test public void projectRelativePathIsResolved_forNonExistingResource() throws Exception { final RobotProjectConfig projectConfig = new RobotProjectConfig(); projectConfig.setRelativityPoint(RelativityPoint.create(RelativeTo.PROJECT)); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig); assertThat(redConfig.resolveToAbsolutePath(SearchPath.create("file.txt"))) .isEqualTo(project.getLocation().append("file.txt")); } @Test public void additionalEnvironmentSearchPathsContainOnlyUniqueCorrectPathsWithResolvedEnvironmentVariables() throws Exception { final SystemVariableAccessor variableAccessor = mock(SystemVariableAccessor.class); when(variableAccessor.getValue("KNOWN_1")).thenReturn(Optional.of("java")); when(variableAccessor.getValue("KNOWN_2")).thenReturn(Optional.of("python")); when(variableAccessor.getValue("JAR")).thenReturn(Optional.of("lib.jar")); when(variableAccessor.getValue("FOLDER")).thenReturn(Optional.of("folder")); when(variableAccessor.getPaths("CLASSPATH")) .thenReturn(newArrayList("FirstClassPath.jar", "SecondClassPath.jar")); final RobotProjectConfig projectConfig = new RobotProjectConfig(); projectConfig.setRelativityPoint(RelativityPoint.create(RelativeTo.PROJECT)); projectConfig.addClassPath(SearchPath.create("%{KNOWN_1}/lib.jar")); projectConfig.addClassPath(SearchPath.create("%{UNKNOWN_1}/unknown.jar")); projectConfig.addClassPath(SearchPath.create("${INCORRECT_1}/incorrect.jar")); projectConfig.addClassPath(SearchPath.create("%{KNOWN_1}/%{JAR}")); projectConfig.addPythonPath(SearchPath.create("%{KNOWN_2}/folder")); projectConfig.addPythonPath(SearchPath.create("%{UNKNOWN_2}/unknown")); projectConfig.addPythonPath(SearchPath.create("${INCORRECT_2}/incorrect")); projectConfig.addPythonPath(SearchPath.create("%{KNOWN_2}/%{FOLDER}")); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig, variableAccessor); assertThat(redConfig.createAdditionalEnvironmentSearchPaths()).isEqualTo(new EnvironmentSearchPaths( newArrayList(absolutePath("java", "lib.jar")), newArrayList(absolutePath("python", "folder")))); } @Test public void executionEnvironmentSearchPathsContainOnlyUniqueCorrectPathsWithResolvedEnvironmentVariables() throws Exception { final SystemVariableAccessor variableAccessor = mock(SystemVariableAccessor.class); when(variableAccessor.getValue("KNOWN_1")).thenReturn(Optional.of("java")); when(variableAccessor.getValue("KNOWN_2")).thenReturn(Optional.of("python")); when(variableAccessor.getValue("JAR")).thenReturn(Optional.of("lib.jar")); when(variableAccessor.getValue("FOLDER")).thenReturn(Optional.of("folder")); when(variableAccessor.getPaths("CLASSPATH")) .thenReturn(newArrayList("FirstClassPath.jar", "SecondClassPath.jar")); final RobotProjectConfig projectConfig = new RobotProjectConfig(); projectConfig.setRelativityPoint(RelativityPoint.create(RelativeTo.PROJECT)); projectConfig.addClassPath(SearchPath.create("%{KNOWN_1}/lib.jar")); projectConfig.addClassPath(SearchPath.create("%{UNKNOWN_1}/unknown.jar")); projectConfig.addClassPath(SearchPath.create("${INCORRECT_1}/incorrect.jar")); projectConfig.addClassPath(SearchPath.create("%{KNOWN_1}/%{JAR}")); projectConfig.addClassPath(SearchPath.create("lib1.jar")); projectConfig.addPythonPath(SearchPath.create("%{KNOWN_2}/folder")); projectConfig.addPythonPath(SearchPath.create("%{UNKNOWN_2}/unknown")); projectConfig.addPythonPath(SearchPath.create("${INCORRECT_2}/incorrect")); projectConfig.addPythonPath(SearchPath.create("%{KNOWN_2}/%{FOLDER}")); projectConfig.addPythonPath(SearchPath.create("folder1")); projectConfig.addReferencedLibrary( ReferencedLibrary.create(LibraryType.JAVA, "JavaLib1", project.getName() + "/lib1.jar")); projectConfig.addReferencedLibrary( ReferencedLibrary.create(LibraryType.JAVA, "JavaLib2", project.getName() + "/lib2.jar")); projectConfig.addReferencedLibrary( ReferencedLibrary.create(LibraryType.PYTHON, "PyLib1", project.getName() + "/folder1/PyLib1.py")); projectConfig.addReferencedLibrary( ReferencedLibrary.create(LibraryType.PYTHON, "PyLib2", project.getName() + "/folder2/PyLib2/__init__.py")); final RedEclipseProjectConfig redConfig = new RedEclipseProjectConfig(project, projectConfig, variableAccessor); assertThat(redConfig.createExecutionEnvironmentSearchPaths()).isEqualTo(new EnvironmentSearchPaths( newArrayList(".", absolutePath("lib1.jar"), absolutePath("lib2.jar"), absolutePath("java", "lib.jar"), "FirstClassPath.jar", "SecondClassPath.jar"), newArrayList(absolutePath("folder1"), absolutePath("folder2"), absolutePath("python", "folder")))); } private static String absolutePath(final String... projectRelativeParts) { final String projectAbsPath = project.getLocation().toOSString(); return projectAbsPath + File.separator + String.join(File.separator, projectRelativeParts); } }
3,182
1,647
<reponame>davidbrochart/pythran def omp_get_wtick(): import omp tick = omp.get_wtick() return tick > 0.0 and tick < 0.01
61
17,703
<filename>test/common/config/opaque_resource_decoder_impl_test.cc #include "envoy/config/endpoint/v3/endpoint.pb.h" #include "envoy/config/endpoint/v3/endpoint.pb.validate.h" #include "source/common/config/opaque_resource_decoder_impl.h" #include "source/common/protobuf/message_validator_impl.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" namespace Envoy { namespace Config { namespace { class OpaqueResourceDecoderImplTest : public testing::Test { public: std::pair<ProtobufTypes::MessagePtr, std::string> decodeTypedResource(const envoy::config::endpoint::v3::ClusterLoadAssignment& typed_resource) { ProtobufWkt::Any opaque_resource; opaque_resource.PackFrom(typed_resource); auto decoded_resource = resource_decoder_.decodeResource(opaque_resource); const std::string name = resource_decoder_.resourceName(*decoded_resource); return {std::move(decoded_resource), name}; } ProtobufMessage::StrictValidationVisitorImpl validation_visitor_; OpaqueResourceDecoderImpl<envoy::config::endpoint::v3::ClusterLoadAssignment> resource_decoder_{ validation_visitor_, "cluster_name"}; }; // Negative test for bad type URL in Any. TEST_F(OpaqueResourceDecoderImplTest, WrongType) { ProtobufWkt::Any opaque_resource; opaque_resource.set_type_url("huh"); EXPECT_THROW_WITH_REGEX(resource_decoder_.decodeResource(opaque_resource), EnvoyException, "Unable to unpack"); } // If the Any is empty (no type set), the default instance of the opaque resource decoder type is // created. TEST_F(OpaqueResourceDecoderImplTest, Empty) { ProtobufWkt::Any opaque_resource; const auto decoded_resource = resource_decoder_.decodeResource(opaque_resource); EXPECT_THAT(*decoded_resource, ProtoEq(envoy::config::endpoint::v3::ClusterLoadAssignment())); EXPECT_EQ("", resource_decoder_.resourceName(*decoded_resource)); } // Negative test for protoc-gen-validate constraints. TEST_F(OpaqueResourceDecoderImplTest, ValidateFail) { envoy::config::endpoint::v3::ClusterLoadAssignment invalid_resource; EXPECT_THROW(decodeTypedResource(invalid_resource), ProtoValidationException); } // When validation is skipped, verify that we can ignore unknown fields. TEST_F(OpaqueResourceDecoderImplTest, ValidateIgnored) { ProtobufMessage::NullValidationVisitorImpl validation_visitor; OpaqueResourceDecoderImpl<envoy::config::endpoint::v3::ClusterLoadAssignment> resource_decoder{ validation_visitor, "cluster_name"}; envoy::config::endpoint::v3::ClusterLoadAssignment strange_resource; strange_resource.set_cluster_name("fare"); auto* unknown = strange_resource.GetReflection()->MutableUnknownFields(&strange_resource); // add a field that doesn't exist in the proto definition: unknown->AddFixed32(1000, 1); ProtobufWkt::Any opaque_resource; opaque_resource.PackFrom(strange_resource); const auto decoded_resource = resource_decoder.decodeResource(opaque_resource); EXPECT_THAT(*decoded_resource, ProtoEq(strange_resource)); EXPECT_EQ("fare", resource_decoder_.resourceName(*decoded_resource)); } // Happy path. TEST_F(OpaqueResourceDecoderImplTest, Success) { envoy::config::endpoint::v3::ClusterLoadAssignment cluster_resource; cluster_resource.set_cluster_name("foo"); const auto result = decodeTypedResource(cluster_resource); EXPECT_THAT(*result.first, ProtoEq(cluster_resource)); EXPECT_EQ("foo", result.second); } } // namespace } // namespace Config } // namespace Envoy
1,165
1,863
import java.awt.*; class BorderPanel extends Panel { int border = 5; // size of border Color col1 = Util.light_edge; Color col2 = Util.dark_edge; Color body; BorderPanel() { } BorderPanel(int w) { border = w; } BorderPanel(int w, Color cb) { border = w; body = cb; } BorderPanel(int w, Color c1, Color c2) { border = w; col1 = c1; col2 = c2; } BorderPanel(int w, Color c1, Color c2, Color cb) { border = w; col1 = c1; col2 = c2; body = cb; } BorderPanel(Color c1, Color c2) { col1 = c1; col2 = c2; } public Insets insets() { return new Insets(border+2, border+2, border+2, border+2); } public void paint(Graphics g) { if (body != null) { g.setColor(body); g.fillRect(0, 0, size().width, size().height); } super.paint(g); int w = size().width-1, h = size().height-1; g.setColor(col1); for(int i=0; i<border; i++) { g.drawLine(i,i,w-i,i); g.drawLine(i,i,i,h-i); } g.setColor(col2); for(int i=0; i<border; i++) { g.drawLine(w-i,h-i, w-i,i); g.drawLine(w-i,h-i, i,h-i); } } }
514
14,570
/** * Swagger Petstore * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ /* * SWGCurrency.h * * some description */ #ifndef SWGCurrency_H_ #define SWGCurrency_H_ #include <QJsonObject> #include "SWGObject.h" namespace Swagger { class SWGCurrency: public SWGObject { public: SWGCurrency(); SWGCurrency(QString json); ~SWGCurrency(); void init(); void cleanup(); QString asJson () override; QJsonObject asJsonObject() override; void fromJsonObject(QJsonObject json) override; SWGCurrency* fromJson(QString jsonString) override; virtual bool isSet() override; private: }; } #endif /* SWGCurrency_H_ */
387
984
<filename>generation/WinSDK/Partitions/SideShow/main.cpp #include "intrinfix.h" #include "windows.fixed.h" #include <windowssideshowapi.h> #include <windowssideshow.h> #include <windowssideshowdriverevents.h>
76
1,159
#include "colorpalette.h" #include "base/text/smartstring.h" using namespace Gfx; ColorPalette::ColorPalette(std::initializer_list<Gfx::Color> colors) : colors(colors) {} ColorPalette::ColorPalette(const std::string &string) { auto colorList = Text::SmartString::split(string, ' ', true); colors.reserve(colorList.size()); for (const auto &color: colorList) { colors.emplace_back(color); } } ColorPalette::operator std::string() const { std::string res; for (const auto &color: colors) { res += (!res.empty() ? " " : ""); res += (std::string)color; } return res; } Gfx::Color ColorPalette::operator[](unsigned index) const { return colors.empty() ? Gfx::Color() : colors[index % colors.size()]; } Gfx::Color &ColorPalette::operator[](unsigned index) { if (index >= colors.size()) colors.resize(index + 1); return colors[index]; } ColorPalette::Citerator ColorPalette::begin() const { return colors.begin(); } ColorPalette::Citerator ColorPalette::end() const { return colors.end(); } size_t ColorPalette::size() const { return colors.size(); }
398
831
<filename>android/src/com/android/tools/idea/navigator/nodes/ndk/includes/model/PackageType.java /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.navigator.nodes.ndk.includes.model; import org.jetbrains.annotations.NotNull; /** Describes the classifications of some known packages. <pre> Terminology used: - Package: A standalone native component like SDL and OpenSSL. These exist within a pre-existing PackageType. For example, Third Party Packages <- Package type SDL <- Package SDL.h <- Header file - Module: A piece of a larger framework where the pieces are all logical peers (like cocos UI and cocos Network). - Component: A piece of a larger framework where the pieces operate at different logical levels (like NDK STL and NDK native app glue). - Folders: A simple include where it isn't known that the folder is a package, module, or component </pre> */ public enum PackageType { // Holds packages defined in CDep package manager (http://github.com/google/cdep). For example, // CDep Packages // SDL // OpenSSL CDepPackage("CDep Packages"), // These are support files for Cocos editor (see https://github.com/cocos2d/cocos2d-x) CocosEditorSupportModule("Cocos Editor Support Modules"), // These are third party packages that ship as part of Cocos. For example // Cocos Third Party Packages // SDL // OpenSSL CocosThirdPartyPackage("Cocos Third Party Packages"), // These are modules that are part of Cocos framework. For example, // Cocos Modules // 2d // audio CocosFrameworkModule("Cocos Modules"), // These are components that are part of the NDK. For example, // NDK Components // Android Platform // CPU Features NdkComponent("NDK Components", false), // These are components that are part of a side-by-side NDK. For example, // NDK r19.1 // LLVM NdkSxsComponent("NDK", false), // These are traditional include folders that don't match any other pattern. IncludeFolder("Include Folders"), // These are include folders that look like they match the traditional pattern of third_party/libname. For example, // Third Party // SDL // OpenSSL ThirdParty("Third Party Packages"), // These are include folders that look like they match the traditional pattern of externals/libname. For example, // Externals // curl Externals("Externals"); @NotNull public final String myDescription; // When true (the default) instances of this family with only one child can be collapsed by removing // the intervening package family node. For some nodes, notable NDK, it's better to not collapse these // since they are well-known and expected. public final boolean myIsCollapsibleFamily; PackageType(@NotNull String description) { this(description, true); } PackageType(@NotNull String description, boolean isCollapsibleFamily) { myDescription = description; myIsCollapsibleFamily = isCollapsibleFamily; } }
1,083
1,007
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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.appium.java_client.android.options.app; import io.appium.java_client.remote.options.BaseMapOptionData; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; public class IntentOptions extends BaseMapOptionData<IntentOptions> { public IntentOptions() { super(); } public IntentOptions(Map<String, Object> options) { super(options); } /** * An intent action name. Application-specific actions should be prefixed with * the vendor's package name. * * @param action E.g. ACTION_MAIN. * @return self instance for chaining. */ public IntentOptions withAction(String action) { return assignOptionValue("action", action); } /** * Get the action name. * * @return Action name. */ public Optional<String> getAction() { return getOptionValue("action"); } /** * Set an intent data URI. * * @param data E.g. content://contacts/people/1. * @return self instance for chaining. */ public IntentOptions withData(String data) { return assignOptionValue("data", data); } /** * Get intent data URI. * * @return Intent data URI. */ public Optional<String> getData() { return getOptionValue("data"); } /** * Intent MIME type. * * @param type E.g. image/png. * @return self instance for chaining. */ public IntentOptions withType(String type) { return assignOptionValue("type", type); } /** * Get an intent type. * * @return Intent type. */ public Optional<String> getType() { return getOptionValue("type"); } /** * Set intent categories. * * @param categories One or more comma-separated Intent categories. * @return self instance for chaining. */ public IntentOptions withCategories(String categories) { return assignOptionValue("categories", categories); } /** * Get intent categories. * * @return Intent categories. */ public Optional<String> getCategories() { return getOptionValue("categories"); } /** * Set intent component name with package name prefix * to create an explicit intent. * * @param component E.g. com.example.app/.ExampleActivity. * @return self instance for chaining. */ public IntentOptions withComponent(String component) { return assignOptionValue("component", component); } /** * Get intent component name. * * @return Intent component name. */ public Optional<String> getComponent() { return getOptionValue("component"); } /** * Single-string value, which represents intent flags set encoded into * an integer. Could also be provided in hexadecimal format. Check * https://developer.android.com/reference/android/content/Intent.html#setFlags(int) * for more details. * * @param intFlags E.g. 0x0F. * @return self instance for chaining. */ public IntentOptions withIntFlags(String intFlags) { return assignOptionValue("intFlags", intFlags); } /** * Get intent flags. * * @return Intent flags encoded into a hexadecimal value. */ public Optional<String> getIntFlags() { return getOptionValue("intFlags"); } /** * Comma-separated string of intent flag names. * * @param flags E.g. 'ACTIVITY_CLEAR_TASK' (the 'FLAG_' prefix is optional). * @return self instance for chaining. */ public IntentOptions withFlags(String flags) { return assignOptionValue("flags", flags); } /** * Get intent flag names. * * @return Comma-separated string of intent flag names. */ public Optional<String> getFlags() { return getOptionValue("flags"); } /** * The name of a class inside of the application package that * will be used as the component for this Intent. * * @param className E.g. com.example.app.MainActivity. * @return self instance for chaining. */ public IntentOptions withClassName(String className) { return assignOptionValue("className", className); } /** * Get class name. * * @return Class name. */ public Optional<String> getClassName() { return getOptionValue("className"); } /** * Intent string parameters. * * @param es Map, where the key is arg parameter name and value is its string value. * @return self instance for chaining. */ public IntentOptions withEs(Map<String, String> es) { return assignOptionValue("es", es); } /** * Get intent string parameters. * * @return Intent string parameters mapping. */ public Optional<Map<String, String>> getEs() { return getOptionValue("es"); } /** * Intent null parameters. * * @param esn List, where keys are parameter names. * @return self instance for chaining. */ public IntentOptions withEsn(List<String> esn) { return assignOptionValue("esn", esn); } /** * Get intent null parameters. * * @return Intent null parameters. */ public Optional<List<String>> getEsn() { return getOptionValue("esn"); } /** * Intent boolean parameters. * * @param ez Map, where keys are parameter names and values are booleans. * @return self instance for chaining. */ public IntentOptions withEz(Map<String, Boolean> ez) { return assignOptionValue("ez", ez); } /** * Get intent boolean parameters. * * @return Intent boolean parameters. */ public Optional<Map<String, Boolean>> getEz() { return getOptionValue("ez"); } /** * Intent integer parameters. * * @param ei Map, where keys are parameter names and values are integers. * @return self instance for chaining. */ public IntentOptions withEi(Map<String, Integer> ei) { return assignOptionValue("ei", ei); } private <T> Map<String, T> convertMapValues(Map<String, Object> map, Function<String, T> converter) { return map.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, (entry) -> converter.apply(String.valueOf(entry.getValue()))) ); } /** * Get intent integer parameters. * * @return Intent integer parameters. */ public Optional<Map<String, Integer>> getEi() { Optional<Map<String, Object>> value = getOptionValue("ei"); return value.map((v) -> convertMapValues(v, Integer::parseInt)); } /** * Intent long parameters. * * @param el Map, where keys are parameter names and values are long numbers. * @return self instance for chaining. */ public IntentOptions withEl(Map<String, Long> el) { return assignOptionValue("el", el); } /** * Get intent long parameters. * * @return Intent long parameters. */ public Optional<Map<String, Long>> getEl() { Optional<Map<String, Object>> value = getOptionValue("el"); return value.map((v) -> convertMapValues(v, Long::parseLong)); } /** * Intent float parameters. * * @param ef Map, where keys are parameter names and values are float numbers. * @return self instance for chaining. */ public IntentOptions withEf(Map<String, Float> ef) { return assignOptionValue("ef", ef); } /** * Get intent float parameters. * * @return Intent float parameters. */ public Optional<Map<String, Float>> getEf() { Optional<Map<String, Object>> value = getOptionValue("ef"); return value.map((v) -> convertMapValues(v, Float::parseFloat)); } /** * Intent URI-data parameters. * * @param eu Map, where keys are parameter names and values are valid URIs. * @return self instance for chaining. */ public IntentOptions withEu(Map<String, String> eu) { return assignOptionValue("eu", eu); } /** * Get intent URI parameters. * * @return Intent URI parameters. */ public Optional<Map<String, String>> getEu() { return getOptionValue("eu"); } /** * Intent component name parameters. * * @param ecn Map, where keys are parameter names and values are valid component names. * @return self instance for chaining. */ public IntentOptions withEcn(Map<String, String> ecn) { return assignOptionValue("ecn", ecn); } /** * Get intent component name parameters. * * @return Intent component name parameters. */ public Optional<Map<String, String>> getEcn() { return getOptionValue("ecn"); } private static Map<String, String> mergeValues(Map<String, ?> map) { return map.entrySet().stream() .collect( Collectors.toMap(Map.Entry::getKey, (entry) -> ((List<?>) entry.getValue()).stream() .map(String::valueOf) .collect(Collectors.joining(","))) ); } /** * Intent integer array parameters. * * @param eia Map, where keys are parameter names and values are lists of integers. * @return self instance for chaining. */ public IntentOptions withEia(Map<String, List<Integer>> eia) { return assignOptionValue("eia", mergeValues(eia)); } /** * Get intent integer array parameters. * * @return Intent integer array parameters. */ public Optional<Map<String, String>> getEia() { return getOptionValue("eia"); } /** * Intent long array parameters. * * @param ela Map, where keys are parameter names and values are lists of long numbers. * @return self instance for chaining. */ public IntentOptions withEla(Map<String, List<Long>> ela) { return assignOptionValue("ela", mergeValues(ela)); } /** * Get intent long array parameters. * * @return Intent long array parameters. */ public Optional<Map<String, String>> getEla() { return getOptionValue("ela"); } /** * Intent float array parameters. * * @param efa Map, where keys are parameter names and values are lists of float numbers. * @return self instance for chaining. */ public IntentOptions withEfa(Map<String, List<Float>> efa) { return assignOptionValue("efa", mergeValues(efa)); } /** * Get intent float array parameters. * * @return Intent float array parameters. */ public Optional<Map<String, String>> getEfa() { return getOptionValue("efa"); } }
4,410
1,511
<filename>etc/scripts/licenses/buildlictests.py # -*- coding: utf-8 -*- # # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more information about nexB OSS projects. # import io from os import path import sys import click from itertools import chain import scancode_config # hack to be able to load testxx utilities. The test code is not in the path otherwise licensedcode_test_dir = path.join(scancode_config.scancode_root_dir, 'tests', 'licensedcode') sys.path.append(licensedcode_test_dir) import licensedcode_test_utils # NOQA from licensedcode_test_utils import LicenseTest # NOQA test_data_dir = path.join(licensedcode_test_dir, 'data') test_gen_data_dir = path.join(test_data_dir, 'generated') TRACE = True def load_data(location='00-new-license-tests.txt'): with io.open(location, encoding='utf-8') as o: data = [l.strip() for l in o.read().splitlines(False)] lines = [] for line in data: if not line: if lines: yield '\n'.join(lines) lines = [] else: lines.append(line) if lines: yield '\n'.join(lines) def find_test_file_loc(test_gen_data_dir=test_gen_data_dir): """ Return a new, unique and non-existing base name location suitable to create a new license test. """ template = 'license_{}.txt' idx = 1 while True: test_file_loc = path.join(test_gen_data_dir, template.format(idx)) if not path.exists(test_file_loc): return test_file_loc idx += 1 def get_all_tests(): load_from = licensedcode_test_utils.LicenseTest.load_from return chain( load_from(test_gen_data_dir), load_from(path.join(test_data_dir, 'licenses')), load_from(path.join(test_data_dir, 'retro_licenses/OS-Licenses-master')), load_from(path.join(test_data_dir, 'spdx/licenses')), load_from(path.join(test_data_dir, 'license_tools')), load_from(path.join(test_data_dir, 'slic-tests/identification')), load_from(path.join(test_data_dir, 'more_licenses/licenses')), load_from(path.join(test_data_dir, 'more_licenses/tests')), load_from(path.join(test_data_dir, 'debian/licensecheck')), ) def build_dupe_index(): """ Return a set of existing license tests texts (to avoid duplication) """ existing = set() for test in get_all_tests(): existing.add(test.get_content()) return existing def build_test(text): """ Build and return a LicenseTest object given a test text. """ from licensedcode import cache test_file = find_test_file_loc() with io.open(test_file, 'w', encoding='utf-8') as tf: tf.write(text) idx = cache.get_index() matches = idx.match(query_string=text) or [] detected_expressions = [match.rule.license_expression for match in matches] notes = '' if not detected_expressions: notes = 'No license should be detected' lt = LicenseTest( test_file=test_file, license_expressions=detected_expressions, notes=notes ) lt.data_file = test_file + '.yml' return lt @click.command() @click.argument('licenses_file', type=click.Path(), metavar='FILE',) @click.help_option('-h', '--help') def cli(licenses_file): """ Create license tests from a text file that tests separated by one empty line. The expected license is computed from license detection. """ from licensedcode_test_utils import LicenseTest # NOQA existing = build_dupe_index() print() for text in load_data(licenses_file): slim = text.encode('utf-8') if slim in existing: print('--> License Test skipped, existing:', text[:80], '...') print() continue else: existing.add(slim) lt = build_test(text) lt.dump() existing.add(text) print('--> License Test added:', text[:80], '...') print() if __name__ == '__main__': cli()
1,744
1,014
[ "Airports & Air Services", "Banks - Regional", "Diversified Machinery", "Farm Products", "Grocery Stores", "Information Technology Services", "Insurance - Diversified", "Marine Shipping", "Medical Devices", "Packaged Foods", "REIT - Diversified", "Real Estate Services", "Residential Construction", "Specialty Industrial Machinery", "Specialty Retail", "Telecom Services", "Textile Manufacturing" ]
186
879
package org.zstack.header.core.progress; import java.util.ArrayList; import java.util.List; /** * Created by MaJin on 2019/7/3. */ public class ChainInfo { private List<RunningTaskInfo> runningTask = new ArrayList<>(); private List<PendingTaskInfo> pendingTask = new ArrayList<>(); public void setPendingTask(List<PendingTaskInfo> pendingTask) { this.pendingTask = pendingTask; } public void setRunningTask(List<RunningTaskInfo> runningTask) { this.runningTask = runningTask; } public List<RunningTaskInfo> getRunningTask() { return runningTask; } public List<PendingTaskInfo> getPendingTask() { return pendingTask; } public void addRunningTask(RunningTaskInfo task) { this.runningTask.add(task); } public void addPendingTask(PendingTaskInfo pendingTask) { this.pendingTask.add(pendingTask); } }
334
470
import xml.etree.ElementTree as ET from ..datetime_helpers import parse_datetime class DQWItem(object): class WarningType: WARNING = "WARNING" DEPRECATED = "DEPRECATED" STALE = "STALE" SENSITIVE_DATA = "SENSITIVE_DATA" MAINTENANCE = "MAINTENANCE" def __init__(self, warning_type="WARNING", message=None, active=True, severe=False): self._id = None # content related self._content_id = None self._content_type = None # DQW related self.warning_type = warning_type self.message = message self.active = active self.severe = severe self._created_at = None self._updated_at = None # owner self._owner_display_name = None self._owner_id = None @property def id(self): return self._id @property def content_id(self): return self._content_id @property def content_type(self): return self._content_type @property def owner_display_name(self): return self._owner_display_name @property def owner_id(self): return self._owner_id @property def warning_type(self): return self._warning_type @warning_type.setter def warning_type(self, value): self._warning_type = value @property def message(self): return self._message @message.setter def message(self, value): self._message = value @property def active(self): return self._active @active.setter def active(self, value): self._active = value @property def severe(self): return self._severe @severe.setter def severe(self, value): self._severe = value @property def active(self): return self._active @active.setter def active(self, value): self._active = value @property def created_at(self): return self._created_at @created_at.setter def created_at(self, value): self._created_at = value @property def updated_at(self): return self._updated_at @updated_at.setter def updated_at(self, value): self._updated_at = value @classmethod def from_response(cls, resp, ns): return cls.from_xml_element(ET.fromstring(resp), ns) @classmethod def from_xml_element(cls, parsed_response, ns): all_dqws = [] dqw_elem_list = parsed_response.findall(".//t:dataQualityWarning", namespaces=ns) for dqw_elem in dqw_elem_list: dqw = DQWItem() dqw._id = dqw_elem.get("id", None) dqw._owner_display_name = dqw_elem.get("userDisplayName", None) dqw._content_id = dqw_elem.get("contentId", None) dqw._content_type = dqw_elem.get("contentType", None) dqw.message = dqw_elem.get("message", None) dqw.warning_type = dqw_elem.get("type", None) is_active = dqw_elem.get("isActive", None) if is_active is not None: dqw._active = string_to_bool(is_active) is_severe = dqw_elem.get("isSevere", None) if is_severe is not None: dqw._severe = string_to_bool(is_severe) dqw._created_at = parse_datetime(dqw_elem.get("createdAt", None)) dqw._updated_at = parse_datetime(dqw_elem.get("updatedAt", None)) owner_id = None owner_tag = dqw_elem.find(".//t:owner", namespaces=ns) if owner_tag is not None: owner_id = owner_tag.get("id", None) dqw._owner_id = owner_id all_dqws.append(dqw) return all_dqws # Used to convert string represented boolean to a boolean type def string_to_bool(s): return s.lower() == "true"
1,771