text
stringlengths
2
99.9k
meta
dict
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <QuartzCore/CALayer.h> @interface CALayer (CALayer_Extensions) - (id)superlayerNamed:(id)arg1; - (id)sublayerNamed:(id)arg1; - (id)sublayersNearPoint:(struct CGPoint)arg1 threshold:(float)arg2; - (id)sublayersUnderRect:(struct CGRect)arg1; - (id)sublayersUnderPoint:(struct CGPoint)arg1; - (id)sublayerUnderPoint:(struct CGPoint)arg1; - (id)layersNotAtCorrectScaleInLayer:(id)arg1; - (id)layersNotAtCorrectScaleInView:(id)arg1; - (id)layerHierarchy; - (id)_stringForSublayersWithLevel:(unsigned long long)arg1; @end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- generated on 11/14/16 16:02:13 by SUMO Version dev-SVN-r21978 This data file and the accompanying materials are made available under the terms of the Eclipse Public License v2.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v20.html SPDX-License-Identifier: EPL-2.0 <configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/sumoConfiguration.xsd"> <input> <net-file value="net.net.xml"/> <route-files value="input_routes.rou.xml"/> <additional-files value="input_additional.add.xml"/> </input> <time> <begin value="100"/> <end value="200"/> </time> <report> <xml-validation value="never"/> <duration-log.disable value="true"/> <no-step-log value="true"/> </report> </configuration> --> <tlsStates xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/tlsstates_file.xsd"> <tlsState time="100.00" id="0" programID="2" phase="0" state="GGggrrrrGGggrrrr"/> <tlsState time="113.00" id="0" programID="2" phase="1" state="yyggrrrryyggrrrr"/> <tlsState time="117.00" id="0" programID="2" phase="2" state="rrGGrrrrrrGGrrrr"/> <tlsState time="120.00" id="0" programID="2" phase="3" state="rryyrrrrrryyrrrr"/> <tlsState time="124.00" id="0" programID="2" phase="4" state="rrrrGGggrrrrGGgg"/> <tlsState time="144.00" id="0" programID="2" phase="5" state="rrrryyggrrrryygg"/> <tlsState time="148.00" id="0" programID="2" phase="6" state="rrrrrrGGrrrrrrGG"/> <tlsState time="151.00" id="0" programID="2" phase="7" state="rrrrrryyrrrrrryy"/> <tlsState time="155.00" id="0" programID="2" phase="0" state="GGggrrrrGGggrrrr"/> <tlsState time="175.00" id="0" programID="2" phase="1" state="yyggrrrryyggrrrr"/> <tlsState time="179.00" id="0" programID="2" phase="2" state="rrGGrrrrrrGGrrrr"/> <tlsState time="182.00" id="0" programID="2" phase="3" state="rryyrrrrrryyrrrr"/> <tlsState time="186.00" id="0" programID="2" phase="4" state="rrrrGGggrrrrGGgg"/> </tlsStates>
{ "pile_set_name": "Github" }
/* * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * 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. */ #include "krb5_locl.h" /** * Allocate and initialize an autentication context. * * @param context A kerberos context. * @param auth_context The authentication context to be initialized. * * Use krb5_auth_con_free() to release the memory when done using the context. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_init(krb5_context context, krb5_auth_context *auth_context) { krb5_auth_context p; ALLOC(p, 1); if (!p) return krb5_enomem(context); memset(p, 0, sizeof(*p)); ALLOC(p->authenticator, 1); if (!p->authenticator) { free(p); return krb5_enomem(context); } memset (p->authenticator, 0, sizeof(*p->authenticator)); p->flags = KRB5_AUTH_CONTEXT_DO_TIME; p->local_address = NULL; p->remote_address = NULL; p->local_port = 0; p->remote_port = 0; p->keytype = KRB5_ENCTYPE_NULL; p->cksumtype = CKSUMTYPE_NONE; p->auth_data = NULL; *auth_context = p; return 0; } /** * Deallocate an authentication context previously initialized with * krb5_auth_con_init(). * * @param context A kerberos context. * @param auth_context The authentication context to be deallocated. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_free(krb5_context context, krb5_auth_context auth_context) { if (auth_context != NULL) { if (auth_context->authenticator) krb5_free_authenticator(context, &auth_context->authenticator); if(auth_context->local_address){ free_HostAddress(auth_context->local_address); free(auth_context->local_address); } if(auth_context->remote_address){ free_HostAddress(auth_context->remote_address); free(auth_context->remote_address); } krb5_free_keyblock(context, auth_context->keyblock); krb5_free_keyblock(context, auth_context->remote_subkey); krb5_free_keyblock(context, auth_context->local_subkey); if (auth_context->auth_data) { free_AuthorizationData(auth_context->auth_data); free(auth_context->auth_data); } free (auth_context); } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setflags(krb5_context context, krb5_auth_context auth_context, int32_t flags) { auth_context->flags = flags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getflags(krb5_context context, krb5_auth_context auth_context, int32_t *flags) { *flags = auth_context->flags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_addflags(krb5_context context, krb5_auth_context auth_context, int32_t addflags, int32_t *flags) { if (flags) *flags = auth_context->flags; auth_context->flags |= addflags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_removeflags(krb5_context context, krb5_auth_context auth_context, int32_t removeflags, int32_t *flags) { if (flags) *flags = auth_context->flags; auth_context->flags &= ~removeflags; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setaddrs(krb5_context context, krb5_auth_context auth_context, krb5_address *local_addr, krb5_address *remote_addr) { if (local_addr) { if (auth_context->local_address) krb5_free_address (context, auth_context->local_address); else if ((auth_context->local_address = malloc(sizeof(krb5_address))) == NULL) return krb5_enomem(context); krb5_copy_address(context, local_addr, auth_context->local_address); } if (remote_addr) { if (auth_context->remote_address) krb5_free_address (context, auth_context->remote_address); else if ((auth_context->remote_address = malloc(sizeof(krb5_address))) == NULL) return krb5_enomem(context); krb5_copy_address(context, remote_addr, auth_context->remote_address); } return 0; } /** * Update the authentication context \a auth_context with the local * and remote addresses from socket \a fd, according to \a flags. * * @return An krb5 error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_genaddrs(krb5_context context, krb5_auth_context auth_context, krb5_socket_t fd, int flags) { krb5_error_code ret; krb5_address local_k_address, remote_k_address; krb5_address *lptr = NULL, *rptr = NULL; struct sockaddr_storage ss_local, ss_remote; struct sockaddr *local = (struct sockaddr *)&ss_local; struct sockaddr *remote = (struct sockaddr *)&ss_remote; socklen_t len; if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR) { if (auth_context->local_address == NULL) { len = sizeof(ss_local); if(rk_IS_SOCKET_ERROR(getsockname(fd, local, &len))) { char buf[128]; ret = rk_SOCK_ERRNO; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "getsockname: %s", buf); goto out; } ret = krb5_sockaddr2address (context, local, &local_k_address); if(ret) goto out; if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR) { krb5_sockaddr2port (context, local, &auth_context->local_port); } else auth_context->local_port = 0; lptr = &local_k_address; } } if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR) { len = sizeof(ss_remote); if(rk_IS_SOCKET_ERROR(getpeername(fd, remote, &len))) { char buf[128]; ret = rk_SOCK_ERRNO; rk_strerror_r(ret, buf, sizeof(buf)); krb5_set_error_message(context, ret, "getpeername: %s", buf); goto out; } ret = krb5_sockaddr2address (context, remote, &remote_k_address); if(ret) goto out; if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR) { krb5_sockaddr2port (context, remote, &auth_context->remote_port); } else auth_context->remote_port = 0; rptr = &remote_k_address; } ret = krb5_auth_con_setaddrs (context, auth_context, lptr, rptr); out: if (lptr) krb5_free_address (context, lptr); if (rptr) krb5_free_address (context, rptr); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setaddrs_from_fd (krb5_context context, krb5_auth_context auth_context, void *p_fd) { krb5_socket_t fd = *(krb5_socket_t *)p_fd; int flags = 0; if(auth_context->local_address == NULL) flags |= KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR; if(auth_context->remote_address == NULL) flags |= KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR; return krb5_auth_con_genaddrs(context, auth_context, fd, flags); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getaddrs(krb5_context context, krb5_auth_context auth_context, krb5_address **local_addr, krb5_address **remote_addr) { if(*local_addr) krb5_free_address (context, *local_addr); *local_addr = malloc (sizeof(**local_addr)); if (*local_addr == NULL) return krb5_enomem(context); krb5_copy_address(context, auth_context->local_address, *local_addr); if(*remote_addr) krb5_free_address (context, *remote_addr); *remote_addr = malloc (sizeof(**remote_addr)); if (*remote_addr == NULL) { krb5_free_address (context, *local_addr); *local_addr = NULL; return krb5_enomem(context); } krb5_copy_address(context, auth_context->remote_address, *remote_addr); return 0; } /* coverity[+alloc : arg-*2] */ static krb5_error_code copy_key(krb5_context context, krb5_keyblock *in, krb5_keyblock **out) { *out = NULL; if (in) return krb5_copy_keyblock(context, in, out); return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return copy_key(context, auth_context->keyblock, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getlocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return copy_key(context, auth_context->local_subkey, keyblock); } /* coverity[+alloc : arg-*2] */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getremotesubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock) { return copy_key(context, auth_context->remote_subkey, keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->keyblock) krb5_free_keyblock(context, auth_context->keyblock); return copy_key(context, keyblock, &auth_context->keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setlocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->local_subkey) krb5_free_keyblock(context, auth_context->local_subkey); return copy_key(context, keyblock, &auth_context->local_subkey); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_generatelocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *key) { krb5_error_code ret; krb5_keyblock *subkey; ret = krb5_generate_subkey_extended (context, key, auth_context->keytype, &subkey); if(ret) return ret; if(auth_context->local_subkey) krb5_free_keyblock(context, auth_context->local_subkey); auth_context->local_subkey = subkey; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setremotesubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->remote_subkey) krb5_free_keyblock(context, auth_context->remote_subkey); return copy_key(context, keyblock, &auth_context->remote_subkey); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setcksumtype(krb5_context context, krb5_auth_context auth_context, krb5_cksumtype cksumtype) { auth_context->cksumtype = cksumtype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getcksumtype(krb5_context context, krb5_auth_context auth_context, krb5_cksumtype *cksumtype) { *cksumtype = auth_context->cksumtype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setkeytype (krb5_context context, krb5_auth_context auth_context, krb5_keytype keytype) { auth_context->keytype = keytype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getkeytype (krb5_context context, krb5_auth_context auth_context, krb5_keytype *keytype) { *keytype = auth_context->keytype; return 0; } krb5_error_code _krb5_add_1auth_data(krb5_context context, krb5int32 ad_type, krb5_data *ad_data, int critical, krb5_authdata **dst) { AuthorizationDataElement e; e.ad_type = ad_type; e.ad_data = *ad_data; if (!critical) { AuthorizationData ad; krb5_error_code ret; krb5_data ir; size_t len; /* Build an AD-IF-RELEVANT with the new element inside it */ ad.len = 0; ad.val = NULL; ret = add_AuthorizationData(&ad, &e); /* Encode the AD-IF-RELEVANT */ if (ret == 0) ASN1_MALLOC_ENCODE(AuthorizationData, ir.data, ir.length, &ad, &len, ret); if (ret == 0 && ir.length != len) krb5_abortx(context, "internal error in ASN.1 encoder"); /* Re-enter to add the encoded AD-IF-RELEVANT */ ret = _krb5_add_1auth_data(context, KRB5_AUTHDATA_IF_RELEVANT, &ir, 1, dst); free_AuthorizationData(&ad); krb5_data_free(&ir); return ret; } if (*dst == NULL) { ALLOC(*dst, 1); if (*dst == NULL) return krb5_enomem(context); } return add_AuthorizationData(*dst, &e); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_add_AuthorizationData(krb5_context context, krb5_auth_context auth_context, int type, krb5_data *data) { if (auth_context->auth_data == NULL) { auth_context->auth_data = calloc(1, sizeof(*auth_context->auth_data)); if (auth_context->auth_data == NULL) return krb5_enomem(context); } return _krb5_add_1auth_data(context, type, data, 1, &auth_context->auth_data); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_add_AuthorizationDataIfRelevant(krb5_context context, krb5_auth_context auth_context, krb5int32 type, krb5_data *data) { if (auth_context->auth_data == NULL) { auth_context->auth_data = calloc(1, sizeof(*auth_context->auth_data)); if (auth_context->auth_data == NULL) return krb5_enomem(context); } return _krb5_add_1auth_data(context, type, data, 0, &auth_context->auth_data); } #if 0 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setenctype(krb5_context context, krb5_auth_context auth_context, krb5_enctype etype) { if(auth_context->keyblock) krb5_free_keyblock(context, auth_context->keyblock); ALLOC(auth_context->keyblock, 1); if(auth_context->keyblock == NULL) return krb5_enomem(context); auth_context->keyblock->keytype = etype; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getenctype(krb5_context context, krb5_auth_context auth_context, krb5_enctype *etype) { krb5_abortx(context, "unimplemented krb5_auth_getenctype called"); } #endif KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getlocalseqnumber(krb5_context context, krb5_auth_context auth_context, int32_t *seqnumber) { *seqnumber = auth_context->local_seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setlocalseqnumber (krb5_context context, krb5_auth_context auth_context, int32_t seqnumber) { auth_context->local_seqnumber = seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getremoteseqnumber(krb5_context context, krb5_auth_context auth_context, int32_t *seqnumber) { *seqnumber = auth_context->remote_seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setremoteseqnumber (krb5_context context, krb5_auth_context auth_context, int32_t seqnumber) { auth_context->remote_seqnumber = seqnumber; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getauthenticator(krb5_context context, krb5_auth_context auth_context, krb5_authenticator *authenticator) { *authenticator = malloc(sizeof(**authenticator)); if (*authenticator == NULL) return krb5_enomem(context); copy_Authenticator(auth_context->authenticator, *authenticator); return 0; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_free_authenticator(krb5_context context, krb5_authenticator *authenticator) { free_Authenticator (*authenticator); free (*authenticator); *authenticator = NULL; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setuserkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock) { if(auth_context->keyblock) krb5_free_keyblock(context, auth_context->keyblock); return krb5_copy_keyblock(context, keyblock, &auth_context->keyblock); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_getrcache(krb5_context context, krb5_auth_context auth_context, krb5_rcache *rcache) { *rcache = auth_context->rcache; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setrcache(krb5_context context, krb5_auth_context auth_context, krb5_rcache rcache) { auth_context->rcache = rcache; return 0; } #if 0 /* not implemented */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_initivector(krb5_context context, krb5_auth_context auth_context) { krb5_abortx(context, "unimplemented krb5_auth_con_initivector called"); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_auth_con_setivector(krb5_context context, krb5_auth_context auth_context, krb5_pointer ivector) { krb5_abortx(context, "unimplemented krb5_auth_con_setivector called"); } #endif /* not implemented */
{ "pile_set_name": "Github" }
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build aix // +build ppc package unix //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = getrlimit64 //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) = setrlimit64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = lseek64 //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) func setTimespec(sec, nsec int64) Timespec { return Timespec{Sec: int32(sec), Nsec: int32(nsec)} } func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: int32(sec), Usec: int32(usec)} } func (iov *Iovec) SetLen(length int) { iov.Len = uint32(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint32(length) } func (msghdr *Msghdr) SetIovlen(length int) { msghdr.Iovlen = int32(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } func Fstat(fd int, stat *Stat_t) error { return fstat(fd, stat) } func Fstatat(dirfd int, path string, stat *Stat_t, flags int) error { return fstatat(dirfd, path, stat, flags) } func Lstat(path string, stat *Stat_t) error { return lstat(path, stat) } func Stat(path string, statptr *Stat_t) error { return stat(path, statptr) }
{ "pile_set_name": "Github" }
NoMainWindowAvaialble=Näppäimistöoikoteitä ei voitu muokata PleaseOpenOneMainWindow=Vähintään yhden BlueGriffon-pääikkunan täytyy olla auki, jotta näppäinoikoteiden muokkaaminen olisi mahdollista.
{ "pile_set_name": "Github" }
/*- * * Copyright 2016 Skymind, Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. */ package org.datavec.api.transform.condition; import java.util.Set; /** * Created by Alex on 24/03/2016. */ public enum ConditionOp { LessThan, LessOrEqual, GreaterThan, GreaterOrEqual, Equal, NotEqual, InSet, NotInSet; public boolean apply(double x, double value, Set<Double> set) { switch (this) { case LessThan: return x < value; case LessOrEqual: return x <= value; case GreaterThan: return x > value; case GreaterOrEqual: return x >= value; case Equal: return x == value; case NotEqual: return x != value; case InSet: return set.contains(x); case NotInSet: return !set.contains(x); default: throw new RuntimeException("Unknown or not implemented op: " + this); } } public boolean apply(float x, float value, Set<Float> set) { switch (this) { case LessThan: return x < value; case LessOrEqual: return x <= value; case GreaterThan: return x > value; case GreaterOrEqual: return x >= value; case Equal: return x == value; case NotEqual: return x != value; case InSet: return set.contains(x); case NotInSet: return !set.contains(x); default: throw new RuntimeException("Unknown or not implemented op: " + this); } } public boolean apply(int x, int value, Set<Integer> set) { switch (this) { case LessThan: return x < value; case LessOrEqual: return x <= value; case GreaterThan: return x > value; case GreaterOrEqual: return x >= value; case Equal: return x == value; case NotEqual: return x != value; case InSet: return set.contains(x); case NotInSet: return !set.contains(x); default: throw new RuntimeException("Unknown or not implemented op: " + this); } } public boolean apply(long x, long value, Set<Long> set) { switch (this) { case LessThan: return x < value; case LessOrEqual: return x <= value; case GreaterThan: return x > value; case GreaterOrEqual: return x >= value; case Equal: return x == value; case NotEqual: return x != value; case InSet: return set.contains(x); case NotInSet: return !set.contains(x); default: throw new RuntimeException("Unknown or not implemented op: " + this); } } public boolean apply(String x, String value, Set<String> set) { switch (this) { case Equal: return value.equals(x); case NotEqual: return !value.equals(x); case InSet: return set.contains(x); case NotInSet: return !set.contains(x); case LessThan: case LessOrEqual: case GreaterThan: case GreaterOrEqual: throw new UnsupportedOperationException("Cannot use ConditionOp \"" + this + "\" on Strings"); default: throw new RuntimeException("Unknown or not implemented op: " + this); } } }
{ "pile_set_name": "Github" }
# v0.9.0 ## Additions * Windows: Typos and incorrect defaults (#683). * validation: Add apparmor profile test(#684). * generate: add oci-version option (#681). * validation: Add SELinux Check (#682). * generate: add process-cap-add and process-cap-drop option (#675). * generate: Add generate option (#672). * Initialize Config Windows Network for Windows Namespace (#666). ## Minor fixes and documentation * validation-tests: fix several tests (#687). * adding security and CoC links (#686). * Simplified code (#685). * Godeps: update hashicorp/go-multierror (#678). * fix up vm parameters (#676). * generate: fix capabilities add/drop option (#674). * update to golang 1.11 (#670). # v0.8.0 ## Additions * generate: Add generate.New support for Windows (#667). * validation: add resource validation after delete (#654). * mountinfo: parse empty strings in source (#652). ## Minor fixes and documentation * readme: fix wrong filepath (#665). * Makefile: add generate to gotest (#656). * MAINTAINERS: remove philips (#659). * Vendor in windows runtime-spec changes (#663). * /proc should be mounted with nosuid, noexec, nodev to match the host (#664). * validation: mounts: fix condition of source & type check (#660). * Fix TAP output with multiple RuntimeInsideValidate (#658). * fix some misspells (#649). # v0.7.0 ## Additions * validation: use t.Fail when checking for main test errors (#645). * travis: add go 1.10 (#647). * validation: add more test cases for read-only paths tests (#644). * validation: add more test cases for masked paths tests (#643). * validation: test cgroups with different input values (#637). * validation: add more test cases for private & slave propagations (#650). * runtimetest: correctly check for a readable directory (#625). * validation: add minor checks for ptmx and kill signal (#642). * validation: add a new test for NSPathMatchTypeError (#636). * validation: add test for NSProcInPath (#628). * validation: test validation test with an empty hostname (#640). * validation: add cgroup devices validation (#633). * check the status of the state passed to hooks over stdin (#608). * validation: fix nil deferences in cpu & blkio cgroups tests (#638). ## Minor fixes and documentation * validation: fix nil dereference when handling multierror in hooks_stdin (#641). * fix generate test in calling generate.New (#648). * README: fix broken links to documentation (#646). * validation/kill_no_effect: fix bug(#635). # v0.6.0 ## Additions * add test case for KillNonCreateRunHaveNoEffect (#607). * Add cgroupsPath validation (#631). * validation: create: don't skip errors on state (#626). * validation: add tests for NSNewNSWithoutPath & NSInheritWithoutType (#620). * specerror: Add NewRFCError and NewRFCErrorOrPanic (#627). * implement specerror (#604, #602, #591, #587, #580, #583, #584, #586). * generate: Move Generator.spec to Generator.Config (#266). * Respect the host platform (#194). * runtimetest: Make TAP output more granular (#308). * generate: add process-username option and fix it's validation (#614). * validation: add process_user validation (#611). * add hooks stdin test (#589). * runtimetest: count correctly TAP tests (#594). * contrib/rootfs-builder: Support timestamps and xz compression (#598). * Add system validation (#592). * validation: run CLI with correct argument order (#600). * validation: Add system validation (#590). * validate: CheckLinux is platform dependent (#560). * validation: Add error judgment to SetConfig (#585). * validate: allow non-linux compatibility (#588). ## Minor fixes and documentation * cgroups_v1: Correction parameters (#629). * travis: fix fetch issue of golint (#630). * validation: add more values for rlimits test (#623). * doc: add developer guidelines (#621). * bash: add os (#622). * docs/command-line-interface: Require complete runtime coverage (#615). * validation/test-yaml: Drop this local experiment (#616). * validation: LinuxUIDMapping: fix tests (#597). * Fix error messages in validation cgroup tests (#605). * contrib/rootfs-builder: Use $(cat rootfs-files) (#606). * validate: mv deviceValid to validate_linux (#603). * Validate_linux: Modify the returned error (#601). * runtimetest: fix root readonly check (#599). * runtimetest: fix uid_map parsing (#596). * Fix condition in BlockIO test (#595). * generate/seccomp: platform independent values (#561). # v0.5.0 ## Additions * validation: add tests when prestart/poststart/poststop hooks fail (#569). * validate_test: add TestCheckMandatoryFields (#554). * validation: add lifecycle validation (#558). * validation: add 'state' test; using WaitingForStatus in insideValidation (#562). * Relax LGTM requirement (#559, #566). * validation: Fixes #556 (#557). ## Minor fixes and documentation * validate_test: Complement test (#568). * man: Modify the legal value of the rootfs-propagation (#548). * generate: don't overwrite hook which has a same path (#571). * validation: nil config support in lifecycle validate (#567). * runtimetest: cmd/runtimetest/main: Run validateDefaultDevices even with process unset (#553). * validation: Remove runc 'create' exit timing crutches (#563). * validation/util/container: Use ExitError for stderr (#564). # v0.4.0 ## Additions * specerror: Redefine error code as int64 (#501). * validate: Improve the test of the configuration file (#504, #534, #537, #541). * runtimetest: Add rootfs propagation test (#511). * runtimetest: Add posixValidations (#510). * runtimetest: Add host platform validation (#507). * Makefile: Add version file (#417). * validation: Complete Container Inside Test (#521). * generate: Support json value for hooks (#525). * generate: Support adding additional mounts for container (#279). * generate: Support blkio related options (#235). * cmd/runtimetest/main: Use TAP diagnostics for errors (#439). * generate: Add linux-intelRdt-l3CacheSchema option (#529). * filepath/clean: Add Windows support (#539). * validate: Add validation when host-specific is set (#495). * runtimetest: Add validation of cgroups (#93). * generate: Generator solaris application container configuration (#532). * generate: Add interface to remove mounts. (#544). * validation/linux_cgroups_*: Generate TAP output (and outside-validation cleanup) (#542). * generate: Windows-specific container configuration generate (#528). * runtimetest: Add validateSeccomp (#514). * validation: Add mount validation (#547). * ...: Transition from tap Diagnostic(...) to YAML(...) (#533). ## Minor fixes and documentation * runtimetest: Fix error return (#505). * runtimetest: Move validateRlimits to defaultValidations (#506). * runtimetest: Make validateRlimits silent on Windows (#509). * runtimetest: Raise ConfigInRootBundleDir for missing config.json (#508). * generate: Change process-tty to process-terminal (#517). * generate: Fixed seccompSet (#513). * runtimetest: Remove debug info (#518). * generate: Fix error return (#520). * validate: Fix nil deference (#522). * generate: Fix DropProcessCapability... (#519). * runtimetest: Fix nil dereference (#523). * man: Small fixs (#526). * validation: Fix idmappings test (#530). * generate: Solve conflicting options problem (#441). * generate: Use non-null validation instead of initialization (#540). * validate: Modify the non-conforming validation (#538). * validate: Fix id mappings (#531). * validate: Remove duplicate verification (#535). * generate: AddMounts should be AddMount you are only adding a single Mount (#545). * generate: Recursive propagation flags should be legal to use (#543). * generate: Modify the function return value (#546). * generate: Hooks should be passed in as rspec.Hook, not as a string. (#549). # v0.3.0 ## Additions * cmd/runtimetest: Adopt `DevicesAvailable` RFC code (#502). * cmd/runtimetest: Adopt `DefaultRuntimeLinuxSymlinks`, `DefaultDevices`, `LinuxProcOomScoreAdjSet`, `MountsInOrder`, `SpecVersionInSemVer`, `PosixHooksPathAbs`, `ProcCwdAbs`, `ProcArgsOneEntryRequired`, `PosixProcRlimitsErrorOnDup`, `MountsDestAbs`, `MountsDestOnWindowsNotNested`, `PlatformSpecConfOnWindowsSet`, `MaskedPathsAbs`, `ReadonlyPathsAbs` RFC codes (#500). * specerror: Turn all the RFC 2119 key words described in runtime-spec to RFC codes (#498, #497, #481, #458). * specerror: Add SplitLevel helper, Implement `--compliance-level` (#492). * generate: generate smoke test (#491). * travis: Add go 1.9 version (#487). * rootfs-{arch}.tar.gz: Add per-arch tarballs (#479). * generate: Add `--linux-device-cgroup-add` and `--linux-device-cgroup-remove` (#446). * filepath: Add a stand-alone package for explicit-OS path logic (#445). ## Minor fixes and documentation * cmd/runtimetest: Fix nil reference (#494). * man: Fix typo (#493). * generate: Correct rootfs default, allow unset "type" fields in resource devices whitelist (#491). * validate: Fix compile issue (#490). * bash: Fix command (#489). * validate: Fix cap valiadtion (#488). * generate: Fix rootfs-propagation (#484). # v0.2.0 ## Additions * cmd/oci-runtime-tool/generate: Add specific cap-add and -drop commands (#358). * validate: Ensure `root.path` is a GUID on non-Hyper-V Windows (#472). * validate: Check `process.rlimits[].type` on Solaris (#461, #480). * validate: Check configuration against JSON Schema (#197, #473, #474, #475, #476). ## Minor fixes and documentation * validate: Avoid "0 errors occurred" failure (#462). * validate: Remove empty string from valid seccomp actions (#468). * validate: Require 0 or unset `major`/`minor` when `linux.devices[].type` is `p` (#460). * generate: Fix cap add/drop and initialize in privileged mode (#464). * generate: Do not validate caps when being dropped (#466, #469, #472). * completions/bash/oci-runtime-tool: Fix broken cap completion (#467). * rootfs.tar.gz: Bump to BusyBox 1.25.1 (#478)
{ "pile_set_name": "Github" }
package runtime import ( "fmt" "io" "net/http" "net/textproto" "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime/internal" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/grpclog" ) // ForwardResponseStream forwards the stream from gRPC server to REST client. func ForwardResponseStream(ctx context.Context, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { f, ok := w.(http.Flusher) if !ok { grpclog.Printf("Flush not supported in %T", w) http.Error(w, "unexpected type of web server", http.StatusInternalServerError) return } md, ok := ServerMetadataFromContext(ctx) if !ok { grpclog.Printf("Failed to extract ServerMetadata from context") http.Error(w, "unexpected error", http.StatusInternalServerError) return } handleForwardResponseServerMetadata(w, md) w.Header().Set("Transfer-Encoding", "chunked") w.Header().Set("Content-Type", marshaler.ContentType()) if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) f.Flush() for { resp, err := recv() if err == io.EOF { return } if err != nil { handleForwardResponseStreamError(marshaler, w, err) return } if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { handleForwardResponseStreamError(marshaler, w, err) return } buf, err := marshaler.Marshal(streamChunk(resp, nil)) if err != nil { grpclog.Printf("Failed to marshal response chunk: %v", err) return } if _, err = fmt.Fprintf(w, "%s\n", buf); err != nil { grpclog.Printf("Failed to send response chunk: %v", err) return } f.Flush() } } func handleForwardResponseServerMetadata(w http.ResponseWriter, md ServerMetadata) { for k, vs := range md.HeaderMD { hKey := fmt.Sprintf("%s%s", metadataHeaderPrefix, k) for i := range vs { w.Header().Add(hKey, vs[i]) } } } func handleForwardResponseTrailerHeader(w http.ResponseWriter, md ServerMetadata) { for k := range md.TrailerMD { tKey := textproto.CanonicalMIMEHeaderKey(fmt.Sprintf("%s%s", metadataTrailerPrefix, k)) w.Header().Add("Trailer", tKey) } } func handleForwardResponseTrailer(w http.ResponseWriter, md ServerMetadata) { for k, vs := range md.TrailerMD { tKey := fmt.Sprintf("%s%s", metadataTrailerPrefix, k) for i := range vs { w.Header().Add(tKey, vs[i]) } } } // ForwardResponseMessage forwards the message "resp" from gRPC server to REST client. func ForwardResponseMessage(ctx context.Context, marshaler Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { md, ok := ServerMetadataFromContext(ctx) if !ok { grpclog.Printf("Failed to extract ServerMetadata from context") } handleForwardResponseServerMetadata(w, md) handleForwardResponseTrailerHeader(w, md) w.Header().Set("Content-Type", marshaler.ContentType()) if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { HTTPError(ctx, marshaler, w, req, err) return } buf, err := marshaler.Marshal(resp) if err != nil { grpclog.Printf("Marshal error: %v", err) HTTPError(ctx, marshaler, w, req, err) return } if _, err = w.Write(buf); err != nil { grpclog.Printf("Failed to write response: %v", err) } handleForwardResponseTrailer(w, md) } func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, resp proto.Message, opts []func(context.Context, http.ResponseWriter, proto.Message) error) error { if len(opts) == 0 { return nil } for _, opt := range opts { if err := opt(ctx, w, resp); err != nil { grpclog.Printf("Error handling ForwardResponseOptions: %v", err) return err } } return nil } func handleForwardResponseStreamError(marshaler Marshaler, w http.ResponseWriter, err error) { buf, merr := marshaler.Marshal(streamChunk(nil, err)) if merr != nil { grpclog.Printf("Failed to marshal an error: %v", merr) return } if _, werr := fmt.Fprintf(w, "%s\n", buf); werr != nil { grpclog.Printf("Failed to notify error to client: %v", werr) return } } func streamChunk(result proto.Message, err error) map[string]proto.Message { if err != nil { grpcCode := grpc.Code(err) httpCode := HTTPStatusFromCode(grpcCode) return map[string]proto.Message{ "error": &internal.StreamError{ GrpcCode: int32(grpcCode), HttpCode: int32(httpCode), Message: err.Error(), HttpStatus: http.StatusText(httpCode), }, } } if result == nil { return streamChunk(nil, fmt.Errorf("empty response")) } return map[string]proto.Message{"result": result} }
{ "pile_set_name": "Github" }
// (C) Copyright John Maddock 2007. // 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) // // This file is machine generated, do not edit by hand // Polynomial evaluation using second order Horners rule #ifndef BOOST_MATH_TOOLS_RAT_EVAL_20_HPP #define BOOST_MATH_TOOLS_RAT_EVAL_20_HPP namespace boost{ namespace math{ namespace tools{ namespace detail{ template <class T, class U, class V> inline V evaluate_rational_c_imp(const T*, const U*, const V&, const mpl::int_<0>*) { return static_cast<V>(0); } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const mpl::int_<1>*) { return static_cast<V>(a[0]) / static_cast<V>(b[0]); } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<2>*) { return static_cast<V>((a[1] * x + a[0]) / (b[1] * x + b[0])); } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<3>*) { return static_cast<V>(((a[2] * x + a[1]) * x + a[0]) / ((b[2] * x + b[1]) * x + b[0])); } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<4>*) { return static_cast<V>((((a[3] * x + a[2]) * x + a[1]) * x + a[0]) / (((b[3] * x + b[2]) * x + b[1]) * x + b[0])); } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<5>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[4] * x2 + a[2]; t[1] = a[3] * x2 + a[1]; t[2] = b[4] * x2 + b[2]; t[3] = b[3] * x2 + b[1]; t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[4]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<6>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[5] * x2 + a[3]; t[1] = a[4] * x2 + a[2]; t[2] = b[5] * x2 + b[3]; t[3] = b[4] * x2 + b[2]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<7>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[6] * x2 + a[4]; t[1] = a[5] * x2 + a[3]; t[2] = b[6] * x2 + b[4]; t[3] = b[5] * x2 + b[3]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[6]); t[2] += static_cast<V>(b[6]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<8>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[7] * x2 + a[5]; t[1] = a[6] * x2 + a[4]; t[2] = b[7] * x2 + b[5]; t[3] = b[6] * x2 + b[4]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<9>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[8] * x2 + a[6]; t[1] = a[7] * x2 + a[5]; t[2] = b[8] * x2 + b[6]; t[3] = b[7] * x2 + b[5]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[3]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[8]); t[2] += static_cast<V>(b[8]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<10>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[9] * x2 + a[7]; t[1] = a[8] * x2 + a[6]; t[2] = b[9] * x2 + b[7]; t[3] = b[8] * x2 + b[6]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[5]); t[3] += static_cast<V>(b[4]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<11>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[10] * x2 + a[8]; t[1] = a[9] * x2 + a[7]; t[2] = b[10] * x2 + b[8]; t[3] = b[9] * x2 + b[7]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[5]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[3]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[10]); t[2] += static_cast<V>(b[10]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<12>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[11] * x2 + a[9]; t[1] = a[10] * x2 + a[8]; t[2] = b[11] * x2 + b[9]; t[3] = b[10] * x2 + b[8]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[7]); t[1] += static_cast<V>(a[6]); t[2] += static_cast<V>(b[7]); t[3] += static_cast<V>(b[6]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[5]); t[3] += static_cast<V>(b[4]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<13>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[12] * x2 + a[10]; t[1] = a[11] * x2 + a[9]; t[2] = b[12] * x2 + b[10]; t[3] = b[11] * x2 + b[9]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[7]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[5]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[3]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[12]); t[2] += static_cast<V>(b[12]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<14>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[13] * x2 + a[11]; t[1] = a[12] * x2 + a[10]; t[2] = b[13] * x2 + b[11]; t[3] = b[12] * x2 + b[10]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[9]); t[1] += static_cast<V>(a[8]); t[2] += static_cast<V>(b[9]); t[3] += static_cast<V>(b[8]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[7]); t[1] += static_cast<V>(a[6]); t[2] += static_cast<V>(b[7]); t[3] += static_cast<V>(b[6]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[5]); t[3] += static_cast<V>(b[4]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<15>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[14] * x2 + a[12]; t[1] = a[13] * x2 + a[11]; t[2] = b[14] * x2 + b[12]; t[3] = b[13] * x2 + b[11]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[9]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[7]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[5]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[3]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[14]); t[2] += static_cast<V>(b[14]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<16>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[15] * x2 + a[13]; t[1] = a[14] * x2 + a[12]; t[2] = b[15] * x2 + b[13]; t[3] = b[14] * x2 + b[12]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[11]); t[1] += static_cast<V>(a[10]); t[2] += static_cast<V>(b[11]); t[3] += static_cast<V>(b[10]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[9]); t[1] += static_cast<V>(a[8]); t[2] += static_cast<V>(b[9]); t[3] += static_cast<V>(b[8]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[7]); t[1] += static_cast<V>(a[6]); t[2] += static_cast<V>(b[7]); t[3] += static_cast<V>(b[6]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[5]); t[3] += static_cast<V>(b[4]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[14]); t[1] += static_cast<V>(a[15]); t[2] += static_cast<V>(b[14]); t[3] += static_cast<V>(b[15]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<17>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[16] * x2 + a[14]; t[1] = a[15] * x2 + a[13]; t[2] = b[16] * x2 + b[14]; t[3] = b[15] * x2 + b[13]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[11]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[9]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[7]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[5]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[3]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[14]); t[1] += static_cast<V>(a[15]); t[2] += static_cast<V>(b[14]); t[3] += static_cast<V>(b[15]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[16]); t[2] += static_cast<V>(b[16]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<18>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[17] * x2 + a[15]; t[1] = a[16] * x2 + a[14]; t[2] = b[17] * x2 + b[15]; t[3] = b[16] * x2 + b[14]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[13]); t[1] += static_cast<V>(a[12]); t[2] += static_cast<V>(b[13]); t[3] += static_cast<V>(b[12]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[11]); t[1] += static_cast<V>(a[10]); t[2] += static_cast<V>(b[11]); t[3] += static_cast<V>(b[10]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[9]); t[1] += static_cast<V>(a[8]); t[2] += static_cast<V>(b[9]); t[3] += static_cast<V>(b[8]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[7]); t[1] += static_cast<V>(a[6]); t[2] += static_cast<V>(b[7]); t[3] += static_cast<V>(b[6]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[5]); t[3] += static_cast<V>(b[4]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[14]); t[1] += static_cast<V>(a[15]); t[2] += static_cast<V>(b[14]); t[3] += static_cast<V>(b[15]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[16]); t[1] += static_cast<V>(a[17]); t[2] += static_cast<V>(b[16]); t[3] += static_cast<V>(b[17]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<19>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[18] * x2 + a[16]; t[1] = a[17] * x2 + a[15]; t[2] = b[18] * x2 + b[16]; t[3] = b[17] * x2 + b[15]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[14]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[14]); t[3] += static_cast<V>(b[13]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[11]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[9]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[7]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[5]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[3]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[3]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[2]); t[1] += static_cast<V>(a[1]); t[2] += static_cast<V>(b[2]); t[3] += static_cast<V>(b[1]); t[0] *= x2; t[2] *= x2; t[0] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[0]); t[1] *= x; t[3] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[14]); t[1] += static_cast<V>(a[15]); t[2] += static_cast<V>(b[14]); t[3] += static_cast<V>(b[15]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[16]); t[1] += static_cast<V>(a[17]); t[2] += static_cast<V>(b[16]); t[3] += static_cast<V>(b[17]); t[0] *= z2; t[2] *= z2; t[0] += static_cast<V>(a[18]); t[2] += static_cast<V>(b[18]); t[1] *= z; t[3] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } template <class T, class U, class V> inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<20>*) { if(x <= 1) { V x2 = x * x; V t[4]; t[0] = a[19] * x2 + a[17]; t[1] = a[18] * x2 + a[16]; t[2] = b[19] * x2 + b[17]; t[3] = b[18] * x2 + b[16]; t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[15]); t[1] += static_cast<V>(a[14]); t[2] += static_cast<V>(b[15]); t[3] += static_cast<V>(b[14]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[13]); t[1] += static_cast<V>(a[12]); t[2] += static_cast<V>(b[13]); t[3] += static_cast<V>(b[12]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[11]); t[1] += static_cast<V>(a[10]); t[2] += static_cast<V>(b[11]); t[3] += static_cast<V>(b[10]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[9]); t[1] += static_cast<V>(a[8]); t[2] += static_cast<V>(b[9]); t[3] += static_cast<V>(b[8]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[7]); t[1] += static_cast<V>(a[6]); t[2] += static_cast<V>(b[7]); t[3] += static_cast<V>(b[6]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[5]); t[1] += static_cast<V>(a[4]); t[2] += static_cast<V>(b[5]); t[3] += static_cast<V>(b[4]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[3]); t[1] += static_cast<V>(a[2]); t[2] += static_cast<V>(b[3]); t[3] += static_cast<V>(b[2]); t[0] *= x2; t[1] *= x2; t[2] *= x2; t[3] *= x2; t[0] += static_cast<V>(a[1]); t[1] += static_cast<V>(a[0]); t[2] += static_cast<V>(b[1]); t[3] += static_cast<V>(b[0]); t[0] *= x; t[2] *= x; return (t[0] + t[1]) / (t[2] + t[3]); } else { V z = 1 / x; V z2 = 1 / (x * x); V t[4]; t[0] = a[0] * z2 + a[2]; t[1] = a[1] * z2 + a[3]; t[2] = b[0] * z2 + b[2]; t[3] = b[1] * z2 + b[3]; t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[4]); t[1] += static_cast<V>(a[5]); t[2] += static_cast<V>(b[4]); t[3] += static_cast<V>(b[5]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[6]); t[1] += static_cast<V>(a[7]); t[2] += static_cast<V>(b[6]); t[3] += static_cast<V>(b[7]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[8]); t[1] += static_cast<V>(a[9]); t[2] += static_cast<V>(b[8]); t[3] += static_cast<V>(b[9]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[10]); t[1] += static_cast<V>(a[11]); t[2] += static_cast<V>(b[10]); t[3] += static_cast<V>(b[11]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[12]); t[1] += static_cast<V>(a[13]); t[2] += static_cast<V>(b[12]); t[3] += static_cast<V>(b[13]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[14]); t[1] += static_cast<V>(a[15]); t[2] += static_cast<V>(b[14]); t[3] += static_cast<V>(b[15]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[16]); t[1] += static_cast<V>(a[17]); t[2] += static_cast<V>(b[16]); t[3] += static_cast<V>(b[17]); t[0] *= z2; t[1] *= z2; t[2] *= z2; t[3] *= z2; t[0] += static_cast<V>(a[18]); t[1] += static_cast<V>(a[19]); t[2] += static_cast<V>(b[18]); t[3] += static_cast<V>(b[19]); t[0] *= z; t[2] *= z; return (t[0] + t[1]) / (t[2] + t[3]); } } }}}} // namespaces #endif // include guard
{ "pile_set_name": "Github" }
// Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './src/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.e2e.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } };
{ "pile_set_name": "Github" }
------------------------------------------------------------------------ -- class.decTest -- Class operations -- -- Copyright (c) IBM Corporation, 1981, 2008. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- -- these testcases. -- -- -- -- These testcases are experimental ('beta' versions), and they -- -- may contain errors. They are offered on an as-is basis. In -- -- particular, achieving the same results as the tests here is not -- -- a guarantee that an implementation complies with any Standard -- -- or specification. The tests are not exhaustive. -- -- -- -- Please send comments, suggestions, and corrections to the author: -- -- Mike Cowlishaw, IBM Fellow -- -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- [email protected] -- ------------------------------------------------------------------------ version: 2.59 -- [New 2006.11.27] precision: 9 maxExponent: 999 minExponent: -999 extended: 1 clamp: 1 rounding: half_even clasx001 class 0 -> +Zero clasx002 class 0.00 -> +Zero clasx003 class 0E+5 -> +Zero clasx004 class 1E-1007 -> +Subnormal clasx005 class 0.1E-999 -> +Subnormal clasx006 class 0.99999999E-999 -> +Subnormal clasx007 class 1.00000000E-999 -> +Normal clasx008 class 1E-999 -> +Normal clasx009 class 1E-100 -> +Normal clasx010 class 1E-10 -> +Normal clasx012 class 1E-1 -> +Normal clasx013 class 1 -> +Normal clasx014 class 2.50 -> +Normal clasx015 class 100.100 -> +Normal clasx016 class 1E+30 -> +Normal clasx017 class 1E+999 -> +Normal clasx018 class 9.99999999E+999 -> +Normal clasx019 class Inf -> +Infinity clasx021 class -0 -> -Zero clasx022 class -0.00 -> -Zero clasx023 class -0E+5 -> -Zero clasx024 class -1E-1007 -> -Subnormal clasx025 class -0.1E-999 -> -Subnormal clasx026 class -0.99999999E-999 -> -Subnormal clasx027 class -1.00000000E-999 -> -Normal clasx028 class -1E-999 -> -Normal clasx029 class -1E-100 -> -Normal clasx030 class -1E-10 -> -Normal clasx032 class -1E-1 -> -Normal clasx033 class -1 -> -Normal clasx034 class -2.50 -> -Normal clasx035 class -100.100 -> -Normal clasx036 class -1E+30 -> -Normal clasx037 class -1E+999 -> -Normal clasx038 class -9.99999999E+999 -> -Normal clasx039 class -Inf -> -Infinity clasx041 class NaN -> NaN clasx042 class -NaN -> NaN clasx043 class +NaN12345 -> NaN clasx044 class sNaN -> sNaN clasx045 class -sNaN -> sNaN clasx046 class +sNaN12345 -> sNaN -- decimal64 bounds precision: 16 maxExponent: 384 minExponent: -383 clamp: 1 rounding: half_even clasx201 class 0 -> +Zero clasx202 class 0.00 -> +Zero clasx203 class 0E+5 -> +Zero clasx204 class 1E-396 -> +Subnormal clasx205 class 0.1E-383 -> +Subnormal clasx206 class 0.999999999999999E-383 -> +Subnormal clasx207 class 1.000000000000000E-383 -> +Normal clasx208 class 1E-383 -> +Normal clasx209 class 1E-100 -> +Normal clasx210 class 1E-10 -> +Normal clasx212 class 1E-1 -> +Normal clasx213 class 1 -> +Normal clasx214 class 2.50 -> +Normal clasx215 class 100.100 -> +Normal clasx216 class 1E+30 -> +Normal clasx217 class 1E+384 -> +Normal clasx218 class 9.999999999999999E+384 -> +Normal clasx219 class Inf -> +Infinity clasx221 class -0 -> -Zero clasx222 class -0.00 -> -Zero clasx223 class -0E+5 -> -Zero clasx224 class -1E-396 -> -Subnormal clasx225 class -0.1E-383 -> -Subnormal clasx226 class -0.999999999999999E-383 -> -Subnormal clasx227 class -1.000000000000000E-383 -> -Normal clasx228 class -1E-383 -> -Normal clasx229 class -1E-100 -> -Normal clasx230 class -1E-10 -> -Normal clasx232 class -1E-1 -> -Normal clasx233 class -1 -> -Normal clasx234 class -2.50 -> -Normal clasx235 class -100.100 -> -Normal clasx236 class -1E+30 -> -Normal clasx237 class -1E+384 -> -Normal clasx238 class -9.999999999999999E+384 -> -Normal clasx239 class -Inf -> -Infinity clasx241 class NaN -> NaN clasx242 class -NaN -> NaN clasx243 class +NaN12345 -> NaN clasx244 class sNaN -> sNaN clasx245 class -sNaN -> sNaN clasx246 class +sNaN12345 -> sNaN
{ "pile_set_name": "Github" }
import msgpack from zlib import crc32 from struct import pack from six import iteritems class Indexer(object): def __init__(self): idx = {} for name in dir(self): # discover subclass indexing methods if not name.startswith('idx_'): continue method = getattr(self, name) if callable(method): name = name[4:] idx[name] = method self._idx = idx self._index = {} def index(self, obj): keys = set() if obj is not None: for name, method in iteritems(self._idx): for value in method(obj): try: key = self.key(name, value) except TypeError: # fixme? silently ignore non-deterministic things continue keys.add(key) return keys def key(self, name, value, smash=True): hash(value) return str(name), pack('=i',crc32(msgpack.packb(value))) def prequery(self, index, value): key = self.key(index, value) method = self._idx[key[0]] def check(obj): return value in method(obj) return tuple(key) + (check,)
{ "pile_set_name": "Github" }
package cn.iocoder.mall.product.biz.bo.attr; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.util.List; @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) public class ProductAttrSimpleWithValueBO extends ProductAttrSimpleBO { /** * 规格值数组 */ private List<ProductAttrValueSimpleBO> values; }
{ "pile_set_name": "Github" }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Form\Annotation; /** * InputFilter annotation * * Use this annotation to specify a specific input filter class to use with the * form. The value should be a string indicating the fully qualified class name * of the input filter to use. * * @Annotation */ class InputFilter extends AbstractStringAnnotation { /** * Retrieve the input filter class * * @return null|string */ public function getInputFilter() { return $this->value; } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>Api Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap.min.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/prettify.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/> <link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/application.css'/> <!-- IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div id='container'> <ul class='breadcrumb'> <li> <a href='../../../apidoc/v2.ko.html'>Foreman v2</a> <span class='divider'>/</span> </li> <li> <a href='../../../apidoc/v2/realms.ko.html'> Realms </a> <span class='divider'>/</span> </li> <li class='active'>create</li> <li class='pull-right'> &nbsp;[ <a href="../../../apidoc/v2/realms/create.pt_BR.html">pt_BR</a> | <a href="../../../apidoc/v2/realms/create.de.html">de</a> | <a href="../../../apidoc/v2/realms/create.it.html">it</a> | <a href="../../../apidoc/v2/realms/create.sv_SE.html">sv_SE</a> | <a href="../../../apidoc/v2/realms/create.zh_CN.html">zh_CN</a> | <a href="../../../apidoc/v2/realms/create.en_GB.html">en_GB</a> | <a href="../../../apidoc/v2/realms/create.cs_CZ.html">cs_CZ</a> | <a href="../../../apidoc/v2/realms/create.fr.html">fr</a> | <a href="../../../apidoc/v2/realms/create.ru.html">ru</a> | <a href="../../../apidoc/v2/realms/create.ja.html">ja</a> | <a href="../../../apidoc/v2/realms/create.es.html">es</a> | <b><a href="../../../apidoc/v2/realms/create.ko.html">ko</a></b> | <a href="../../../apidoc/v2/realms/create.ca.html">ca</a> | <a href="../../../apidoc/v2/realms/create.gl.html">gl</a> | <a href="../../../apidoc/v2/realms/create.en.html">en</a> | <a href="../../../apidoc/v2/realms/create.zh_TW.html">zh_TW</a> | <a href="../../../apidoc/v2/realms/create.nl_NL.html">nl_NL</a> | <a href="../../../apidoc/v2/realms/create.pl.html">pl</a> ] </li> </ul> <div class='page-header'> <h1> POST /api/realms <br> <small>영역 생성 </small> </h1> </div> <div> <p>The <b>name</b> field is used for the name of the realm.</p> <h2><span class="translation_missing" title="translation missing: ko.apipie.examples">Examples</span></h2> <pre class="prettyprint">POST /api/realms { &quot;realm&quot;: { &quot;name&quot;: &quot;realm.net&quot;, &quot;realm_proxy_id&quot;: 0, &quot;realm_type&quot;: &quot;FreeIPA&quot; } } 422 { &quot;error&quot;: { &quot;id&quot;: null, &quot;errors&quot;: { &quot;realm_proxy_id&quot;: [ &quot;was not found&quot; ] }, &quot;full_messages&quot;: [ &quot;Realm proxy was not found&quot; ] } }</pre> <h2><span class="translation_missing" title="translation missing: ko.apipie.params">Params</span></h2> <table class='table'> <thead> <tr> <th><span class="translation_missing" title="translation missing: ko.apipie.param_name">Param Name</span></th> <th><span class="translation_missing" title="translation missing: ko.apipie.description">Description</span></th> </tr> </thead> <tbody> <tr style='background-color:rgb(255,255,255);'> <td> <strong>location_id </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.optional">Optional</span> </small> </td> <td> <p>위치 별 범위</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Integer</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>organization_id </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.optional">Optional</span> </small> </td> <td> <p>조직 별 범위</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Integer</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(255,255,255);'> <td> <strong>realm </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.required">Required</span> </small> </td> <td> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a Hash</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>realm[name] </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.required">Required</span> </small> </td> <td> <p>영역 이름 예: EXAMPLE.COM</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a String</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>realm[realm_proxy_id] </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.required">Required</span> , &lt;span class=&quot;translation_missing&quot; title=&quot;translation missing: ko.apipie.nil_allowed&quot;&gt;Nil Allowed&lt;/span&gt; </small> </td> <td> <p>Proxy ID to use within this realm</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a number.</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>realm[realm_type] </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.required">Required</span> </small> </td> <td> <p>영역 유형. 예: FreeIPA 또는 활성 디렉토리</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be a String</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>realm[location_ids] </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.optional">Optional</span> , &lt;span class=&quot;translation_missing&quot; title=&quot;translation missing: ko.apipie.nil_allowed&quot;&gt;Nil Allowed&lt;/span&gt; </small> </td> <td> <p>지정된 ID로 위치를 변경합니다</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be an array of any type</p> </li> </ul> </td> </tr> <tr style='background-color:rgb(250,250,250);'> <td> <strong>realm[organization_ids] </strong><br> <small> <span class="translation_missing" title="translation missing: ko.apipie.optional">Optional</span> , &lt;span class=&quot;translation_missing&quot; title=&quot;translation missing: ko.apipie.nil_allowed&quot;&gt;Nil Allowed&lt;/span&gt; </small> </td> <td> <p>지정된 ID로 조직을 변경합니다</p> <p><strong>Validations:</strong></p> <ul> <li> <p>Must be an array of any type</p> </li> </ul> </td> </tr> </tbody> </table> </div> </div> </div> <hr> <footer></footer> </div> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/jquery.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/bundled/prettify.js'></script> <script type='text/javascript' src='../../../apidoc/javascripts/apipie.js'></script> </body> </html>
{ "pile_set_name": "Github" }
/* Function cos vectorized with AVX2, wrapper version. Copyright (C) 2014-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <sysdep.h> #include "svml_d_wrapper_impl.h" .text ENTRY (_ZGVdN4v_cos) WRAPPER_IMPL_AVX _ZGVbN2v_cos END (_ZGVdN4v_cos) #ifndef USE_MULTIARCH libmvec_hidden_def (_ZGVdN4v_cos) #endif
{ "pile_set_name": "Github" }
<?php namespace Frozennode\Administrator\DataTable; use Frozennode\Administrator\Config\ConfigInterface; use Frozennode\Administrator\DataTable\Columns\Factory as ColumnFactory; use Frozennode\Administrator\Fields\Factory as FieldFactory; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\DatabaseManager as DB; class DataTable { /** * The config instance. * * @var \Frozennode\Administrator\Config\ConfigInterface */ protected $config; /** * The validator instance. * * @var \Frozennode\Administrator\DataTable\Columns\Factory */ protected $columnFactory; /** * The validator instance. * * @var \Frozennode\Administrator\Fields\Factory */ protected $fieldFactory; /** * The column objects. * * @var array */ protected $columns; /** * The sort options. * * @var array */ protected $sort; /** * The number of rows per page for this data table. * * @var int */ protected $rowsPerPage = 20; /** * Create a new action DataTable instance. * * @param \Frozennode\Administrator\Config\ConfigInterface $config * @param \Frozennode\Administrator\DataTable\Columns\Factory $columnFactory * @param \Frozennode\Administrator\Fields\Factory $fieldFactory */ public function __construct(ConfigInterface $config, ColumnFactory $columnFactory, FieldFactory $fieldFactory) { //set the config, and then validate it $this->config = $config; $this->columnFactory = $columnFactory; $this->fieldFactory = $fieldFactory; } /** * Builds a results array (with results and pagination info). * * @param \Illuminate\Database\DatabaseManager $db * @param array $filters * @param int $page * @param array $sort (with 'field' and 'direction' keys) * * @return array */ public function getRows(DB $db, $filters = null, $page = 1, $sort = null) { //prepare the query extract($this->prepareQuery($db, $page, $sort, $filters)); //run the count query $output = $this->performCountQuery($countQuery, $querySql, $queryBindings, $page); //now we need to limit and offset the rows in remembrance of our dear lost friend paginate() $query->take($this->rowsPerPage); $query->skip($this->rowsPerPage * ($output['page'] === 0 ? $output['page'] : $output['page'] - 1)); //parse the results $output['results'] = $this->parseResults($query->get()); return $output; } /** * Builds a results array (with results and pagination info). * * @param \Illuminate\Database\DatabaseManager $db * @param int $page * @param array $sort (with 'field' and 'direction' keys) * @param array $filters * * @return array */ public function prepareQuery(DB $db, $page = 1, $sort = null, $filters = null) { //grab the model instance $model = $this->config->getDataModel(); //update the sort options $this->setSort($sort); $sort = $this->getSort(); //get things going by grouping the set $table = $model->getTable(); $keyName = $model->getKeyName(); $query = $model->groupBy($table.'.'.$keyName); //get the Illuminate\Database\Query\Builder instance and set up the count query $dbQuery = $query->getQuery(); $countQuery = $dbQuery->getConnection()->table($table)->groupBy($table.'.'.$keyName); //run the supplied query filter for both queries if it was provided $this->config->runQueryFilter($dbQuery); $this->config->runQueryFilter($countQuery); //set up initial array states for the selects $selects = array($table.'.*'); //set the filters $this->setFilters($filters, $dbQuery, $countQuery, $selects); //set the selects $dbQuery->select($selects); //determines if the sort should have the table prefixed to it $sortOnTable = true; //get the columns $columns = $this->columnFactory->getColumns(); //iterate over the columns to check if we need to join any values or add any extra columns foreach ($columns as $column) { //if this is a related column, we'll need to add some selects $column->filterQuery($selects); //if this is a related field or if (($column->getOption('is_related') || $column->getOption('select')) && $column->getOption('column_name') === $sort['field']) { $sortOnTable = false; } } //if the sort is on the model's table, prefix the table name to it if ($sortOnTable) { $sort['field'] = $table.'.'.$sort['field']; } //grab the query sql for later $querySql = $query->toSql(); //order the set by the model table's id $query->orderBy($sort['field'], $sort['direction']); //then retrieve the rows $query->getQuery()->select($selects); //only select distinct rows $query->distinct(); //load the query bindings $queryBindings = $query->getBindings(); return compact('query', 'querySql', 'queryBindings', 'countQuery', 'sort', 'selects'); } /** * Performs the count query and returns info about the pages. * * @param \Illuminate\Database\Query\Builder $countQuery * @param string $querySql * @param array $queryBindings * @param int $page * * @return array */ public function performCountQuery(QueryBuilder $countQuery, $querySql, $queryBindings, $page) { //grab the model instance $model = $this->config->getDataModel(); //then wrap the inner table and perform the count $sql = "SELECT COUNT({$model->getKeyName()}) AS aggregate FROM ({$querySql}) AS agg"; //then perform the count query $results = $countQuery->getConnection()->select($sql, $queryBindings); $numRows = is_array($results[0]) ? $results[0]['aggregate'] : $results[0]->aggregate; $page = (int) $page; $last = (int) ceil($numRows / $this->rowsPerPage); return array( //if the current page is greater than the last page, set the current page to the last page 'page' => $page > $last ? $last : $page, 'last' => $last, 'total' => $numRows, ); } /** * Sets the query filters when getting the rows. * * @param mixed $filters * @param \Illuminate\Database\Query\Builder $query * @param \Illuminate\Database\Query\Builder $countQuery * @param array $selects */ public function setFilters($filters, QueryBuilder &$query, QueryBuilder &$countQuery, &$selects) { //then we set the filters if ($filters && is_array($filters)) { foreach ($filters as $filter) { //get the field object $fieldObject = $this->fieldFactory->findFilter($filter['field_name']); //set the filter on the object $fieldObject->setFilter($filter); //filter the query objects, only pass in the selects the first time so they aren't added twice $fieldObject->filterQuery($query, $selects); $fieldObject->filterQuery($countQuery); } } } /** * Parses the results of a getRows query and converts it into a manageable array with the proper rendering. * * @param Collection $rows * * @return array */ public function parseResults($rows) { $results = array(); //convert the resulting set into arrays foreach ($rows as $item) { //iterate over the included and related columns $arr = array(); $this->parseOnTableColumns($item, $arr); //then grab the computed, unsortable columns $this->parseComputedColumns($item, $arr); $results[] = $arr; } return $results; } /** * Goes through all related columns and sets the proper values for this row. * * @param \Illuminate\Database\Eloquent\Model $item * @param array $outputRow */ public function parseOnTableColumns($item, array &$outputRow) { if (method_exists($item, 'presenter')) { $item = $item->presenter(); } $columns = $this->columnFactory->getColumns(); $includedColumns = $this->columnFactory->getIncludedColumns($this->fieldFactory->getEditFields()); $relatedColumns = $this->columnFactory->getRelatedColumns(); //loop over both the included and related columns foreach (array_merge($includedColumns, $relatedColumns) as $field => $col) { // $attributeValue = $item->getAttribute($field); $attributeValue = $item->$field; //if this column is in our objects array, render the output with the given value if (isset($columns[$field])) { $outputRow[$field] = array( 'raw' => $attributeValue, 'rendered' => $columns[$field]->renderOutput($attributeValue, $item), ); } //otherwise it's likely the primary key column which wasn't included (though it's needed for identification purposes) else { $outputRow[$field] = array( 'raw' => $attributeValue, 'rendered' => $attributeValue, ); } } } /** * Goes through all computed columns and sets the proper values for this row. * * @param \Illuminate\Database\Eloquent\Model $item * @param array $outputRow */ public function parseComputedColumns($item, array &$outputRow) { $columns = $this->columnFactory->getColumns(); $computedColumns = $this->columnFactory->getComputedColumns(); //loop over the computed columns foreach ($computedColumns as $name => $column) { $outputRow[$name] = array( 'raw' => $item->{$name}, 'rendered' => $columns[$name]->renderOutput($item->{$name}, $item), ); } } /** * Sets up the sort options. * * @param array $sort */ public function setSort($sort = null) { $sort = $sort && is_array($sort) ? $sort : $this->config->getOption('sort'); //set the sort values $this->sort = array( 'field' => isset($sort['field']) ? $sort['field'] : $this->config->getDataModel()->getKeyName(), 'direction' => isset($sort['direction']) ? $sort['direction'] : 'desc', ); //if the sort direction isn't valid, set it to 'desc' if (!in_array($this->sort['direction'], array('asc', 'desc'))) { $this->sort['direction'] = 'desc'; } } /** * Gets the sort options. * * @return array */ public function getSort() { return $this->sort; } /** * Set the number of rows per page for this data table. * * @param \Illuminate\Session\Store $session * @param int $globalPerPage * @param int $override //if provided, this will set the session's rows per page value */ public function setRowsPerPage(\Illuminate\Session\Store $session, $globalPerPage, $override = null) { if ($override) { $perPage = (int) $override; $session->put('administrator_'.$this->config->getOption('name').'_rows_per_page', $perPage); } $perPage = $session->get('administrator_'.$this->config->getOption('name').'_rows_per_page'); if (!$perPage) { $perPage = (int) $globalPerPage; } $this->rowsPerPage = $perPage; } /** * Gets the rows per page. * * @return int */ public function getRowsPerPage() { return $this->rowsPerPage; } }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOverseasTaxOrderPayModel(object): def __init__(self): self._available_day = None self._biz_mode = None self._company_name = None self._confirm_date = None self._country_code = None self._departure_point = None self._doc_expire_date = None self._doc_id = None self._extend_param = None self._identify_account_no = None self._identify_account_type = None self._nationality = None self._out_order_no = None self._passport_name = None self._passport_no = None self._sales_amount = None self._sales_currency = None self._sales_date = None self._tax_refund_amount = None self._tax_refund_currency = None self._tax_refund_print_date = None self._tax_refund_scene_type = None self._user_received_amount = None self._user_received_currency = None @property def available_day(self): return self._available_day @available_day.setter def available_day(self, value): self._available_day = value @property def biz_mode(self): return self._biz_mode @biz_mode.setter def biz_mode(self, value): self._biz_mode = value @property def company_name(self): return self._company_name @company_name.setter def company_name(self, value): self._company_name = value @property def confirm_date(self): return self._confirm_date @confirm_date.setter def confirm_date(self, value): self._confirm_date = value @property def country_code(self): return self._country_code @country_code.setter def country_code(self, value): self._country_code = value @property def departure_point(self): return self._departure_point @departure_point.setter def departure_point(self, value): self._departure_point = value @property def doc_expire_date(self): return self._doc_expire_date @doc_expire_date.setter def doc_expire_date(self, value): self._doc_expire_date = value @property def doc_id(self): return self._doc_id @doc_id.setter def doc_id(self, value): self._doc_id = value @property def extend_param(self): return self._extend_param @extend_param.setter def extend_param(self, value): self._extend_param = value @property def identify_account_no(self): return self._identify_account_no @identify_account_no.setter def identify_account_no(self, value): self._identify_account_no = value @property def identify_account_type(self): return self._identify_account_type @identify_account_type.setter def identify_account_type(self, value): self._identify_account_type = value @property def nationality(self): return self._nationality @nationality.setter def nationality(self, value): self._nationality = value @property def out_order_no(self): return self._out_order_no @out_order_no.setter def out_order_no(self, value): self._out_order_no = value @property def passport_name(self): return self._passport_name @passport_name.setter def passport_name(self, value): self._passport_name = value @property def passport_no(self): return self._passport_no @passport_no.setter def passport_no(self, value): self._passport_no = value @property def sales_amount(self): return self._sales_amount @sales_amount.setter def sales_amount(self, value): self._sales_amount = value @property def sales_currency(self): return self._sales_currency @sales_currency.setter def sales_currency(self, value): self._sales_currency = value @property def sales_date(self): return self._sales_date @sales_date.setter def sales_date(self, value): self._sales_date = value @property def tax_refund_amount(self): return self._tax_refund_amount @tax_refund_amount.setter def tax_refund_amount(self, value): self._tax_refund_amount = value @property def tax_refund_currency(self): return self._tax_refund_currency @tax_refund_currency.setter def tax_refund_currency(self, value): self._tax_refund_currency = value @property def tax_refund_print_date(self): return self._tax_refund_print_date @tax_refund_print_date.setter def tax_refund_print_date(self, value): self._tax_refund_print_date = value @property def tax_refund_scene_type(self): return self._tax_refund_scene_type @tax_refund_scene_type.setter def tax_refund_scene_type(self, value): self._tax_refund_scene_type = value @property def user_received_amount(self): return self._user_received_amount @user_received_amount.setter def user_received_amount(self, value): self._user_received_amount = value @property def user_received_currency(self): return self._user_received_currency @user_received_currency.setter def user_received_currency(self, value): self._user_received_currency = value def to_alipay_dict(self): params = dict() if self.available_day: if hasattr(self.available_day, 'to_alipay_dict'): params['available_day'] = self.available_day.to_alipay_dict() else: params['available_day'] = self.available_day if self.biz_mode: if hasattr(self.biz_mode, 'to_alipay_dict'): params['biz_mode'] = self.biz_mode.to_alipay_dict() else: params['biz_mode'] = self.biz_mode if self.company_name: if hasattr(self.company_name, 'to_alipay_dict'): params['company_name'] = self.company_name.to_alipay_dict() else: params['company_name'] = self.company_name if self.confirm_date: if hasattr(self.confirm_date, 'to_alipay_dict'): params['confirm_date'] = self.confirm_date.to_alipay_dict() else: params['confirm_date'] = self.confirm_date if self.country_code: if hasattr(self.country_code, 'to_alipay_dict'): params['country_code'] = self.country_code.to_alipay_dict() else: params['country_code'] = self.country_code if self.departure_point: if hasattr(self.departure_point, 'to_alipay_dict'): params['departure_point'] = self.departure_point.to_alipay_dict() else: params['departure_point'] = self.departure_point if self.doc_expire_date: if hasattr(self.doc_expire_date, 'to_alipay_dict'): params['doc_expire_date'] = self.doc_expire_date.to_alipay_dict() else: params['doc_expire_date'] = self.doc_expire_date if self.doc_id: if hasattr(self.doc_id, 'to_alipay_dict'): params['doc_id'] = self.doc_id.to_alipay_dict() else: params['doc_id'] = self.doc_id if self.extend_param: if hasattr(self.extend_param, 'to_alipay_dict'): params['extend_param'] = self.extend_param.to_alipay_dict() else: params['extend_param'] = self.extend_param if self.identify_account_no: if hasattr(self.identify_account_no, 'to_alipay_dict'): params['identify_account_no'] = self.identify_account_no.to_alipay_dict() else: params['identify_account_no'] = self.identify_account_no if self.identify_account_type: if hasattr(self.identify_account_type, 'to_alipay_dict'): params['identify_account_type'] = self.identify_account_type.to_alipay_dict() else: params['identify_account_type'] = self.identify_account_type if self.nationality: if hasattr(self.nationality, 'to_alipay_dict'): params['nationality'] = self.nationality.to_alipay_dict() else: params['nationality'] = self.nationality if self.out_order_no: if hasattr(self.out_order_no, 'to_alipay_dict'): params['out_order_no'] = self.out_order_no.to_alipay_dict() else: params['out_order_no'] = self.out_order_no if self.passport_name: if hasattr(self.passport_name, 'to_alipay_dict'): params['passport_name'] = self.passport_name.to_alipay_dict() else: params['passport_name'] = self.passport_name if self.passport_no: if hasattr(self.passport_no, 'to_alipay_dict'): params['passport_no'] = self.passport_no.to_alipay_dict() else: params['passport_no'] = self.passport_no if self.sales_amount: if hasattr(self.sales_amount, 'to_alipay_dict'): params['sales_amount'] = self.sales_amount.to_alipay_dict() else: params['sales_amount'] = self.sales_amount if self.sales_currency: if hasattr(self.sales_currency, 'to_alipay_dict'): params['sales_currency'] = self.sales_currency.to_alipay_dict() else: params['sales_currency'] = self.sales_currency if self.sales_date: if hasattr(self.sales_date, 'to_alipay_dict'): params['sales_date'] = self.sales_date.to_alipay_dict() else: params['sales_date'] = self.sales_date if self.tax_refund_amount: if hasattr(self.tax_refund_amount, 'to_alipay_dict'): params['tax_refund_amount'] = self.tax_refund_amount.to_alipay_dict() else: params['tax_refund_amount'] = self.tax_refund_amount if self.tax_refund_currency: if hasattr(self.tax_refund_currency, 'to_alipay_dict'): params['tax_refund_currency'] = self.tax_refund_currency.to_alipay_dict() else: params['tax_refund_currency'] = self.tax_refund_currency if self.tax_refund_print_date: if hasattr(self.tax_refund_print_date, 'to_alipay_dict'): params['tax_refund_print_date'] = self.tax_refund_print_date.to_alipay_dict() else: params['tax_refund_print_date'] = self.tax_refund_print_date if self.tax_refund_scene_type: if hasattr(self.tax_refund_scene_type, 'to_alipay_dict'): params['tax_refund_scene_type'] = self.tax_refund_scene_type.to_alipay_dict() else: params['tax_refund_scene_type'] = self.tax_refund_scene_type if self.user_received_amount: if hasattr(self.user_received_amount, 'to_alipay_dict'): params['user_received_amount'] = self.user_received_amount.to_alipay_dict() else: params['user_received_amount'] = self.user_received_amount if self.user_received_currency: if hasattr(self.user_received_currency, 'to_alipay_dict'): params['user_received_currency'] = self.user_received_currency.to_alipay_dict() else: params['user_received_currency'] = self.user_received_currency return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayOverseasTaxOrderPayModel() if 'available_day' in d: o.available_day = d['available_day'] if 'biz_mode' in d: o.biz_mode = d['biz_mode'] if 'company_name' in d: o.company_name = d['company_name'] if 'confirm_date' in d: o.confirm_date = d['confirm_date'] if 'country_code' in d: o.country_code = d['country_code'] if 'departure_point' in d: o.departure_point = d['departure_point'] if 'doc_expire_date' in d: o.doc_expire_date = d['doc_expire_date'] if 'doc_id' in d: o.doc_id = d['doc_id'] if 'extend_param' in d: o.extend_param = d['extend_param'] if 'identify_account_no' in d: o.identify_account_no = d['identify_account_no'] if 'identify_account_type' in d: o.identify_account_type = d['identify_account_type'] if 'nationality' in d: o.nationality = d['nationality'] if 'out_order_no' in d: o.out_order_no = d['out_order_no'] if 'passport_name' in d: o.passport_name = d['passport_name'] if 'passport_no' in d: o.passport_no = d['passport_no'] if 'sales_amount' in d: o.sales_amount = d['sales_amount'] if 'sales_currency' in d: o.sales_currency = d['sales_currency'] if 'sales_date' in d: o.sales_date = d['sales_date'] if 'tax_refund_amount' in d: o.tax_refund_amount = d['tax_refund_amount'] if 'tax_refund_currency' in d: o.tax_refund_currency = d['tax_refund_currency'] if 'tax_refund_print_date' in d: o.tax_refund_print_date = d['tax_refund_print_date'] if 'tax_refund_scene_type' in d: o.tax_refund_scene_type = d['tax_refund_scene_type'] if 'user_received_amount' in d: o.user_received_amount = d['user_received_amount'] if 'user_received_currency' in d: o.user_received_currency = d['user_received_currency'] return o
{ "pile_set_name": "Github" }
goal:bool = false addr 0x0 @asm "add %eax,%ebx" label pc_0x0 t:u32 = R_EBX:u32 R_EBX:u32 = R_EBX:u32 + R_EAX:u32 R_CF:bool = R_EBX:u32 < t:u32 R_AF:bool = 0x10:u32 == (0x10:u32 & (R_EBX:u32 ^ t:u32 ^ R_EAX:u32)) R_OF:bool = high:bool((t:u32 ^ ~R_EAX:u32) & (t:u32 ^ R_EBX:u32)) R_PF:bool = ~low:bool(R_EBX:u32 >> 7:u32 ^ R_EBX:u32 >> 6:u32 ^ R_EBX:u32 >> 5:u32 ^ R_EBX:u32 >> 4:u32 ^ R_EBX:u32 >> 3:u32 ^ R_EBX:u32 >> 2:u32 ^ R_EBX:u32 >> 1:u32 ^ R_EBX:u32) R_SF:bool = high:bool(R_EBX:u32) R_ZF:bool = 0:u32 == R_EBX:u32 addr 0x2 @asm "shl %cl,%ebx" label pc_0x2 tmpDEST:u32 = R_EBX:u32 t1:u32 = R_EBX:u32 >> 0x20:u32 - (R_ECX:u32 & 0x1f:u32) R_CF:bool = if (R_ECX:u32 & 0x1f:u32) == 0:u32 then R_CF:bool else low:bool(t1:u32) R_EBX:u32 = R_EBX:u32 << (R_ECX:u32 & 0x1f:u32) R_OF:bool = if (R_ECX:u32 & 0x1f:u32) == 0:u32 then R_OF:bool else if (R_ECX:u32 & 0x1f:u32) == 1:u32 then high:bool(R_EBX:u32) ^ R_CF:bool else unknown "OF <- undefined":bool R_SF:bool = if (R_ECX:u32 & 0x1f:u32) == 0:u32 then R_SF:bool else high:bool(R_EBX:u32) R_ZF:bool = if (R_ECX:u32 & 0x1f:u32) == 0:u32 then R_ZF:bool else 0:u32 == R_EBX:u32 R_PF:bool = if (R_ECX:u32 & 0x1f:u32) == 0:u32 then R_PF:bool else ~low:bool(R_EBX:u32 >> 7:u32 ^ R_EBX:u32 >> 6:u32 ^ R_EBX:u32 >> 5:u32 ^ R_EBX:u32 >> 4:u32 ^ R_EBX:u32 >> 3:u32 ^ R_EBX:u32 >> 2:u32 ^ R_EBX:u32 >> 1:u32 ^ R_EBX:u32) R_AF:bool = if (R_ECX:u32 & 0x1f:u32) == 0:u32 then R_AF:bool else unknown "AF undefined after shift":bool addr 0x4 @asm "jb 0x0000000000000008" label pc_0x4 cjmp R_CF:bool, 8:u32, "nocjmp0" label nocjmp0 addr 0x6 @asm "jmp 0x0000000000000009" label pc_0x6 jmp 9:u32 addr 0x8 @asm "nop" label pc_0x8 goal:bool = true addr 0x9 @asm "nop" label pc_0x9
{ "pile_set_name": "Github" }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {getOutgoingHook, updateOutgoingHook} from 'mattermost-redux/actions/integrations'; import {getConfig} from 'mattermost-redux/selectors/entities/general'; import EditOutgoingWebhook from './edit_outgoing_webhook.jsx'; function mapStateToProps(state, ownProps) { const config = getConfig(state); const hookId = (new URLSearchParams(ownProps.location.search)).get('id'); const enableOutgoingWebhooks = config.EnableOutgoingWebhooks === 'true'; const enablePostUsernameOverride = config.EnablePostUsernameOverride === 'true'; const enablePostIconOverride = config.EnablePostIconOverride === 'true'; return { hookId, hook: state.entities.integrations.outgoingHooks[hookId], enableOutgoingWebhooks, enablePostUsernameOverride, enablePostIconOverride, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ updateOutgoingHook, getOutgoingHook, }, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(EditOutgoingWebhook);
{ "pile_set_name": "Github" }
package io.quarkus.it.amazon.lambda; import javax.inject.Inject; import javax.inject.Named; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; @Named("test") public class TestLambda implements RequestHandler<InputObject, OutputObject> { @Inject ProcessingService service; @Override public OutputObject handleRequest(InputObject input, Context context) { return service.proces(input).setRequestId(context.getAwsRequestId()); } }
{ "pile_set_name": "Github" }
// NOTE: This file was originally generated via JetBrains ReSharper // and is part of the JetBrains.Annoations for ReSharper. // It has since been modified for use in the re-motion framework development. // // Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // // Orignal license header by JetBrains: // // Copyright 2007-2012 JetBrains s.r.o. // // 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. // using System; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming // ReSharper disable once CheckNamespace namespace JetBrains.Annotations { [AttributeUsage (AttributeTargets.Parameter)] sealed partial class PathReferenceAttribute : Attribute { public PathReferenceAttribute () { } public PathReferenceAttribute ([PathReference] string basePath) { BasePath = basePath; } public string BasePath { get; private set; } } }
{ "pile_set_name": "Github" }
/// Source : https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/ /// Author : liuyubobobo /// Time : 2018-06-03 #include <iostream> #include <vector> #include <cassert> using namespace std; /// Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /// Recursive /// Time Complexity: O(n*h) where n is the num of node in th tree /// and h is the height of the tree /// Space Complexity: O(h) class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTree(inorder, 0, inorder.size(), postorder, 0, postorder.size()); } private: TreeNode* buildTree(vector<int>& inorder, int inorderL, int inorderR, vector<int>& postorder, int postorderL, int postorderR){ if(inorderL >= inorderR){ assert(postorderL >= postorderR); return NULL; } if(inorderL + 1 == inorderR){ assert(postorderL + 1 == postorderR); return new TreeNode(inorder[inorderL]); } TreeNode* root = new TreeNode(postorder[postorderR - 1]); int rootPos = find(inorder.begin() + inorderL, inorder.begin() + inorderR, root->val) - inorder.begin(); assert(inorderL <= rootPos && rootPos < inorderR); int lsize = rootPos - inorderL; int rsize = inorderR - (rootPos + 1); root->left = buildTree(inorder, inorderL, inorderL + lsize, postorder, postorderL, postorderL + lsize); root->right = buildTree(inorder, rootPos + 1, inorderR, postorder, postorderL + lsize, postorderR - 1); return root; } }; int main() { vector<int> inorder = {9,3,15,20,7}; vector<int> postorder = {9,15,7,20,3}; TreeNode* root = Solution().buildTree(inorder, postorder); return 0; }
{ "pile_set_name": "Github" }
["line break"]
{ "pile_set_name": "Github" }
<?php /************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2020 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: https://www.espocrm.com * * EspoCRM 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 3 of the License, or * (at your option) any later version. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ namespace Espo\Modules\Crm\SelectManagers; class Contact extends \Espo\Core\Select\SelectManager { protected function filterPortalUsers(&$result) { $this->addJoin([ 'portalUser', 'portalUserFilter', ], $result); } protected function filterNotPortalUsers(&$result) { $this->addLeftJoin([ 'portalUser', 'portalUserFilter', ], $result); $this->addAndWhere(array( 'portalUserFilter.id' => null ), $result); } protected function accessPortalOnlyContact(&$result) { $d = []; $contactId = $this->getUser()->get('contactId'); if ($contactId) { $result['whereClause'][] = array( 'id' => $contactId ); } else { $result['whereClause'][] = array( 'id' => null ); } } protected function filterAccountActive(&$result) { if (!array_key_exists('additionalColumnsConditions', $result)) { $result['additionalColumnsConditions'] = array(); } $result['additionalColumnsConditions']['isInactive'] = false; } }
{ "pile_set_name": "Github" }
2,1
{ "pile_set_name": "Github" }
/* Copyright (c) 2015 Cromulence LLC Authors: Cromulence <[email protected]> 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. */ #ifndef __MATH_H__ #define __MATH_H__ double round( double val ); double floor( double val ); #define isnan( val ) __builtin_isnan( val ) #define isinf( val ) __builtin_isinf( val ) #define M_PI 3.14159265358979323846 #endif // __MATH_H__
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <com.google.android.material.tabs.TabLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:tabIndicatorColor="@android:color/white" app:tabGravity="fill" app:tabMode="fixed" />
{ "pile_set_name": "Github" }
/* * Copyright 2015 original 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.grails.cli.profile.commands import jline.console.completer.Completer import org.grails.cli.profile.Command /** * A completer for commands * * @author Graeme Rocher * @since 3.1 */ class CommandCompleter implements Completer { Collection<Command> commands CommandCompleter(Collection<Command> commands) { this.commands = commands } @Override int complete(String buffer, int cursor, List<CharSequence> candidates) { def cmd = commands.find() { def trimmed = buffer.trim() if(trimmed.split(/\s/).size() > 1) { return trimmed.startsWith( it.name ) } else { return trimmed == it.name } } if(cmd instanceof Completer) { return ((Completer)cmd).complete(buffer, cursor, candidates) } return cursor } }
{ "pile_set_name": "Github" }
package io.vertx.example.util; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.ext.dropwizard.DropwizardMetricsOptions; import java.io.File; import java.io.IOException; import java.util.function.Consumer; /* * @author <a href="http://tfox.org">Tim Fox</a> */ public class Runner { public static final VertxOptions DROPWIZARD_OPTIONS = new VertxOptions(). setMetricsOptions(new DropwizardMetricsOptions().setEnabled(true)); private static final String METRICS_EXAMPLES_DIR = "metrics-examples"; private static final String METRICS_EXAMPLES_JAVA_DIR = METRICS_EXAMPLES_DIR + "/src/main/java/"; private static final String METRICS_EXAMPLES_JS_DIR = METRICS_EXAMPLES_DIR + "/src/main/js/"; private static final String METRICS_EXAMPLES_GROOVY_DIR = METRICS_EXAMPLES_DIR + "/src/main/groovy/"; private static final String METRICS_EXAMPLES_RUBY_DIR = METRICS_EXAMPLES_DIR + "/src/main/ruby/"; public static void runClusteredExample(Class clazz) { runExample(METRICS_EXAMPLES_JAVA_DIR, clazz, new VertxOptions(DROPWIZARD_OPTIONS).setClustered(true), null); } public static void runExample(Class clazz) { runExample(METRICS_EXAMPLES_JAVA_DIR, clazz, new VertxOptions(DROPWIZARD_OPTIONS).setClustered(false), null); } // JavaScript examples public static void runJSExample(String scriptName) { runScriptExample(METRICS_EXAMPLES_JS_DIR, scriptName, DROPWIZARD_OPTIONS); } static class JSMetricsDashboardRunner { public static void main(String[] args) { runJSExample("io/vertx/example/metrics/dashboard/dashboard.js"); } } // Groovy examples public static void runGroovyExample(String scriptName) { runScriptExample(METRICS_EXAMPLES_GROOVY_DIR, scriptName, DROPWIZARD_OPTIONS); } static class GroovyMetricsDashboardRunner { public static void main(String[] args) { runGroovyExample("io/vertx/example/metrics/dashboard/dashboard.groovy"); } } // Ruby examples public static void runRubyExample(String scriptName) { runScriptExample(METRICS_EXAMPLES_RUBY_DIR, scriptName, DROPWIZARD_OPTIONS); } static class RubyMetricsDashboardRunner { public static void main(String[] args) { runRubyExample("io/vertx/example/metrics/dashboard/dashboard.rb"); } } public static void runExample(String exampleDir, Class clazz, VertxOptions options, DeploymentOptions deploymentOptions) { runExample(exampleDir + clazz.getPackage().getName().replace(".", "/"), clazz.getName(), options, deploymentOptions); } public static void runScriptExample(String prefix, String scriptName, VertxOptions options) { File file = new File(scriptName); String dirPart = file.getParent(); String scriptDir = prefix + dirPart; runExample(scriptDir, scriptDir + "/" + file.getName(), options, null); } public static void runExample(String exampleDir, String verticleID, VertxOptions options, DeploymentOptions deploymentOptions) { if (options == null) { // Default parameter options = new VertxOptions(); } // Smart cwd detection // Based on the current directory (.) and the desired directory (exampleDir), we try to compute the vertx.cwd // directory: try { // We need to use the canonical file. Without the file name is . File current = new File(".").getCanonicalFile(); if (exampleDir.startsWith(current.getName()) && !exampleDir.equals(current.getName())) { exampleDir = exampleDir.substring(current.getName().length() + 1); } } catch (IOException e) { // Ignore it. } System.setProperty("vertx.cwd", exampleDir); Consumer<Vertx> runner = vertx -> { try { if (deploymentOptions != null) { vertx.deployVerticle(verticleID, deploymentOptions); } else { vertx.deployVerticle(verticleID); } } catch (Throwable t) { t.printStackTrace(); } }; if (options.isClustered()) { Vertx.clusteredVertx(options, res -> { if (res.succeeded()) { Vertx vertx = res.result(); runner.accept(vertx); } else { res.cause().printStackTrace(); } }); } else { Vertx vertx = Vertx.vertx(options); runner.accept(vertx); } } }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 最大子数组只有可能有三个地方出现: 1,左半部分内。 2,右半部分内。 3,跨越了左右半部分。这个时候只要从中点开始分别在左右找最大子数组就可以了。 边界条件是:列表中的元素只有一个的时候 """ """ 复杂度,使用递归树来分析: 因为二分法,树的高度是lgN。 每一层树的复杂度是N,因为find_max_in_middle中需要把所有节点都遍历一遍 所以整体复杂度是O(NlgN) """ def find_max_sublist(li): li_len = len(li) if li_len < 2: return 0, 0, sum(li) middle = li_len / 2 m_x, m_y, m_sum = find_max_in_middle(li, middle) l_x, l_y, l_sum = find_max_sublist(li[:middle]) r_x, r_y, r_sum = find_max_sublist(li[middle + 1:]) if m_sum >= l_sum and m_sum >= r_sum: return m_x, m_y, m_sum elif l_sum >= m_sum and l_sum >= r_sum: return l_x, l_y, l_sum else: return r_x, r_y, r_sum """ 思想:如果以中点开始,分别计算左右两边的最大子数列,那么他们的合并 也是最大的(除去某些边结果为负数的情况) 优化: 和插入排序类似的思想就是从从中点开始分别向左向右累计求和 这样的好处是:在累计求和的过程中就可以寻找最大值。 而不是先累计求和再求最大值,这样需要额外的循环 """ def find_max_in_middle(li, middle): li_len = len(li) left_max_index, right_max_index = 0, middle # 这里有一个bug,如果列表里面所有的数据都是负的,那么就找不到最小值了 left_max_sum, cur_sum, right_max_sum = li[middle - 1], 0, li[middle] for x in reversed(xrange(0, middle)): cur_sum += li[x] if cur_sum > left_max_sum: left_max_sum = cur_sum left_max_index = x cur_sum = 0 for x in xrange(middle, li_len): cur_sum += li[x] if cur_sum > right_max_sum: right_max_sum = cur_sum right_max_index = x # 这里并没有判断一端结果为负的情况,因为这个时候可以在其中一端的列表中得到最大子数列 return left_max_index, right_max_index, right_max_sum + left_max_sum def main(): print find_max_sublist([1, -2, 3, 10, -4, 7, 2, -5]) if __name__ == '__main__': main()
{ "pile_set_name": "Github" }
import React from 'react'; import { shallow } from 'enzyme'; import paginationTotalAdapter from '../src/pagination-total-adapter'; const MockComponent = () => null; const PaginationTotalAdapter = paginationTotalAdapter(MockComponent); describe('paginationTotalAdapter', () => { let wrapper; const props = { dataSize: 20, currPage: 1, currSizePerPage: 10, paginationTotalRenderer: jest.fn() }; describe('render', () => { beforeEach(() => { wrapper = shallow(<PaginationTotalAdapter { ...props } />); }); it('should render successfully', () => { const mockComponent = wrapper.find(MockComponent); expect(mockComponent).toHaveLength(1); expect(mockComponent.props().from).toBeDefined(); expect(mockComponent.props().to).toBeDefined(); expect(mockComponent.props().dataSize).toEqual(props.dataSize); expect(mockComponent.props().paginationTotalRenderer).toEqual(props.paginationTotalRenderer); }); }); });
{ "pile_set_name": "Github" }
[android-components](../../index.md) / [mozilla.components.feature.session](../index.md) / [SessionFeature](index.md) / [start](./start.md) # start `fun start(): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html) [(source)](https://github.com/mozilla-mobile/android-components/blob/master/components/feature/session/src/main/java/mozilla/components/feature/session/SessionFeature.kt#L28) Overrides [LifecycleAwareFeature.start](../../mozilla.components.support.base.feature/-lifecycle-aware-feature/start.md) Start feature: App is in the foreground.
{ "pile_set_name": "Github" }
LIBNAME=ffmpeg BASE_URL=https://github.com/mrmc/FFmpeg/archive/release/ VERSION=3.3-kodi ARCHIVE=$(LIBNAME)-$(VERSION).tar.gz
{ "pile_set_name": "Github" }
@import url(forms.css); @import url(l10n.css); html, body { height: 100%; margin: 0; padding: 0; } body { background: #f1f1f1; min-width: 0; color: #444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; font-size: 13px; line-height: 1.4em; } a { color: #0073aa; transition-property: border, background, color; transition-duration: .05s; transition-timing-function: ease-in-out; } a { outline: 0; } a:hover, a:active { color: #00a0d2; } a:focus { color: #124964; box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); } .ie8 a:focus { outline: #5b9dd9 solid 1px; } p { line-height: 1.5; } .login .message, .login .success, .login #login_error { border-left: 4px solid #00a0d2; padding: 12px; margin-left: 0; margin-bottom: 20px; background-color: #fff; box-shadow: 0 1px 1px 0 rgba(0,0,0,0.1); } .login .success { border-left-color: #46b450; } .login #login_error { border-left-color: #dc3232; } #loginform p.submit, .login-action-lostpassword p.submit { border: none; margin: -10px 0 20px; /* May want to revisit this */ } .login * { margin: 0; padding: 0; } .login .password-input-wrapper { display: table; } .login .input.password-input { display: table-cell; margin: 0; } .login .pw-weak { margin-bottom: 15px; } .login .button.button-secondary { display: table-cell; border-radius: 0; vertical-align: middle; } .login form { margin-top: 20px; margin-left: 0; padding: 26px 24px 46px; font-weight: 400; overflow: hidden; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.13); } .login form .forgetmenot { font-weight: 400; float: left; margin-bottom: 0; } .login .button-primary { float: right; } #login form p { margin-bottom: 0; } #login form p.submit { margin: 0; padding: 0; } .login label { color: #72777c; font-size: 14px; } .login form .forgetmenot label { font-size: 12px; line-height: 19px; } .login h1 { text-align: center; } .login h1 a { background-image: url(../images/w-logo-blue.png?ver=20131202); background-image: none, url(../images/wordpress-logo.svg?ver=20131107); background-size: 84px; background-position: center top; background-repeat: no-repeat; color: #444; height: 84px; font-size: 20px; font-weight: 400; line-height: 1.3em; margin: 0 auto 25px; padding: 0; text-decoration: none; width: 84px; text-indent: -9999px; outline: none; overflow: hidden; display: block; } #login { width: 320px; padding: 8% 0 0; margin: auto; } .login #nav, .login #backtoblog { font-size: 13px; padding: 0 24px 0; } .login #nav { margin: 24px 0 0 0; } #backtoblog { margin: 16px 0; } .login #nav a, .login #backtoblog a { text-decoration: none; color: #555d66; } .login #nav a:hover, .login #backtoblog a:hover, .login h1 a:hover { color: #00a0d2; } .login #nav a:focus, .login #backtoblog a:focus, .login h1 a:focus { color: #124964; } .login .privacy-policy-page-link { text-align: center; width: 100%; margin: 5em 0 2em; } .login form .input, .login input[type="text"] { font-size: 24px; width: 100%; padding: 3px; margin: 2px 6px 16px 0; } .login form .input, .login input[type="text"], .login form input[type="checkbox"] { background: #fbfbfb; } .ie7 .login form .input, .ie8 .login form .input { font-family: sans-serif; } .login-action-rp input[type="text"] { box-shadow: none; margin: 0; } .login #pass-strength-result { font-weight: 600; margin: -1px 5px 16px 0; padding: 6px 5px; text-align: center; width: 100%; } body.interim-login { height: auto; } .interim-login #login { padding: 0; margin: 5px auto 20px; } .interim-login.login h1 a { width: auto; } .interim-login #login_error, .interim-login.login .message { margin: 0 0 16px; } .interim-login.login form { margin: 0; } @-ms-viewport { width: device-width; } @media screen and (max-height: 550px) { #login { padding: 20px 0; } } @media screen and (max-width: 782px) { .interim-login input[type=checkbox] { height: 16px; width: 16px; } .interim-login input[type=checkbox]:checked:before { width: 16px; font: normal 21px/1 dashicons; margin: -3px 0 0 -4px; } }
{ "pile_set_name": "Github" }
package utils import "net" // Get all network card IP func GetIPs() (ips []string) { cards, err := net.Interfaces() if err != nil { } for _, card := range cards { if (card.Flags & net.FlagUp) != 0 { addrs, err := card.Addrs() if err != nil { } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && ipnet.IP.IsGlobalUnicast() { if ipnet.IP.To4() != nil { ips = append(ips, ipnet.IP.String()) } } } } } return ips }
{ "pile_set_name": "Github" }
import React from "react"; import _ from "underscore"; import classnames from "classnames"; import EditorIcon from "visual/component/EditorIcon"; class TextareaOptionType extends React.Component { static defaultProps = { className: "", label: "", placeholder: "", helper: false, helperContent: "", attr: {}, value: "", onChange: _.noop }; onChangeDebounced = _.debounce(value => { this.props.onChange(value); }, 1000); handleChance = e => { this.onChangeDebounced(e.target.value); }; handleFocus = () => { this.textarea.focus(); }; renderLabel = () => { const { label, helper: _helper, helperContent } = this.props; const helper = _helper ? ( <div className="brz-ed-option__helper"> <EditorIcon icon="nc-alert-circle-que" /> <div className="brz-ed-option__helper__content" dangerouslySetInnerHTML={{ __html: helperContent }} /> </div> ) : null; return ( <div className="brz-ed-option__label brz-ed-option__textarea__label"> {label} {helper} </div> ); }; render() { const { label, className: _className, helper, placeholder, attr: _attr, value } = this.props; const className = classnames( "brz-ed-option__textarea", "brz-ed-option__inline", _className, _attr.className ); const attr = _.omit(_attr, "className"); return ( <div className={className} {...attr}> {label || helper ? this.renderLabel() : null} <textarea ref={el => { this.textarea = el; }} type="text" className="brz-textarea brz-ed-control__textarea" placeholder={placeholder} defaultValue={value} onClick={this.handleFocus} onChange={this.handleChance} /> </div> ); } } export default TextareaOptionType;
{ "pile_set_name": "Github" }
GL_EXT_debug_marker http://www.khronos.org/registry/gles/extensions/EXT/EXT_debug_marker.txt GL_EXT_debug_marker void glInsertEventMarkerEXT (GLsizei length, const GLchar* marker) void glPushGroupMarkerEXT (GLsizei length, const GLchar* marker) void glPopGroupMarkerEXT (void)
{ "pile_set_name": "Github" }
虽然尾递归优化很好, 但python 不支持尾递归,递归深度超过1000时会报错 RuntimeError: maximum recursion depth exceeded
{ "pile_set_name": "Github" }
#pragma once #include <Core/Block.h> #include <Processors/Formats/IOutputFormat.h> #include <Formats/FormatSettings.h> namespace DB { class WriteBuffer; class Context; /** Prints the result in the form of beautiful tables. */ class PrettyBlockOutputFormat : public IOutputFormat { public: /// no_escapes - do not use ANSI escape sequences - to display in the browser, not in the console. PrettyBlockOutputFormat(WriteBuffer & out_, const Block & header_, const FormatSettings & format_settings_); String getName() const override { return "PrettyBlockOutputFormat"; } void consume(Chunk) override; void consumeTotals(Chunk) override; void consumeExtremes(Chunk) override; void finalize() override; protected: size_t total_rows = 0; size_t terminal_width = 0; bool suffix_written = false; const FormatSettings format_settings; using Widths = PODArray<size_t>; using WidthsPerColumn = std::vector<Widths>; virtual void write(const Chunk & chunk, PortKind port_kind); virtual void writeSuffix(); virtual void writeSuffixIfNot() { if (!suffix_written) writeSuffix(); suffix_written = true; } void calculateWidths( const Block & header, const Chunk & chunk, WidthsPerColumn & widths, Widths & max_padded_widths, Widths & name_widths); void writeValueWithPadding( const IColumn & column, const IDataType & type, size_t row_num, size_t value_width, size_t pad_to_width); }; }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import os import json import time from dateutil import parser as du_parser from datetime import datetime import StringIO import logging import requests from requests.auth import HTTPBasicAuth import html5lib from html5lib import treebuilders logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN') last_id = None one_minute = 60 one_hour = one_minute * 60 min_remaining_tostop = 30 reqs = 0 # reqs_limit = None # reqs_remaining = None headers = {} TOKEN_AUTH = HTTPBasicAuth(GITHUB_TOKEN, "x-oauth-basic") def check_limits(headers): reqs_limit = int(headers.get('X-RateLimit-Limit', 0)) reqs_remaining = int(headers.get('X-RateLimit-Remaining', 0)) if reqs_remaining <= min_remaining_tostop: logger.info("Reached %d requests over %d. Pausing one hour." % (reqs_limit - reqs_remaining, reqs_limit)) pause(one_hour) def pause(duration): ''' basic sleep with periodic logging (to show progess) ''' interval = 10 tick = duration / interval for i in xrange(interval): logger.info(u"Pause (%dmn) Elapsed: %dmn" % (duration / one_minute, tick * i / one_minute)) time.sleep(tick) existing_users = json.load(open('step2.json')) try: all_users = json.load(open('step3.json')) except: all_users = [] def getElementsByClassName(root, tag, className): return [e for e in root.getElementsByTagName(tag) if className in e.getAttribute('class')] def extend_user(user): print(user.get('username')) def get_activity_from_html(username): r = requests.get('https://github.com/%s' % username, headers=headers, auth=TOKEN_AUTH) if r.status_code == 404: return None parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom")) dom = parser.parse(StringIO.StringIO(r.content)) divs = dom.getElementsByTagName('div') contrib_columns = [d for d in divs if 'contrib-column' in d.getAttribute('class')] if not len(contrib_columns): return {'contrib_total_num': 0, 'contrib_total_start': None, 'contrib_total_end': None, 'contrib_long_num': 0, 'contrib_long_start': None, 'contrib_long_end': None} total_str = getElementsByClassName( contrib_columns[0], "span", "contrib-number")[0].firstChild.nodeValue # logger.debug("total_str: {}".format(total_str)) total_dates_dom = getElementsByClassName( contrib_columns[0], "span", "text-muted")[1] total_dates = "".join([n.nodeValue for n in total_dates_dom.childNodes]) # logger.debug("total_dates: {}".format(total_dates)) total_start = du_parser.parse(total_dates.split(u'–')[0]) total_end = du_parser.parse(total_dates.split(u'–')[1]) # logger.debug("total_start: {}".format(total_start)) # logger.debug("total_end: {}".format(total_end)) long_str = getElementsByClassName( contrib_columns[1], "span", "contrib-number")[0].firstChild.nodeValue # logger.debug("long_str: {}".format(long_str)) long_dates_dom = getElementsByClassName( contrib_columns[1], "span", "text-muted")[1] long_dates = "".join([n.nodeValue for n in long_dates_dom.childNodes]) # logger.debug("total_dates: {}".format(total_dates)) # logger.debug("long_dates: {}".format(long_dates)) if long_dates == "No recent contributions": long_start = None long_end = None else: long_start = du_parser.parse(long_dates.split(u'–')[0].strip()) if long_start.year > total_end.year: long_start = datetime(long_start.year - 1, long_start.month, long_start.year.day) long_end = du_parser.parse(long_dates.split(u'–')[1].strip()) if long_end.year > total_end.year: long_end = datetime(long_end.year - 1, long_end.month, long_end.year.day) return { 'contrib_total_num': int(total_str.split()[0].replace(',', '')), 'contrib_total_start': total_start.isoformat(), 'contrib_total_end': total_end.isoformat(), 'contrib_long_num': int(long_str.split()[0].replace(',', '')), 'contrib_long_start': long_start.isoformat() if long_start is not None else None, 'contrib_long_end': long_end.isoformat() if long_end is not None else None} def get_profile(user): r = requests.get( 'https://api.github.com/users/%s' % user.get('username'), headers=headers, auth=TOKEN_AUTH) check_limits(r.headers) nd = {} data = json.loads(r.content) for col in data.keys(): if 'url' in col and not col == 'avatar_url': continue if col in user.keys(): continue nd.update({col: data[col]}) return nd def get_orgs(username): orgs = {} r = requests.get('https://api.github.com/users/%s/orgs' % username, headers=headers, auth=TOKEN_AUTH) check_limits(r.headers) data = json.loads(r.content) orgs.update({'orgs_num': len(data)}) for i, org in enumerate(data): org_name = org.get('login') prefix = 'org%d_' % i rorg = requests.get('https://api.github.com/orgs/%s' % org_name, headers=headers, auth=TOKEN_AUTH) check_limits(rorg.headers) data_org = json.loads(rorg.content) nd = {} for col in data_org.keys(): if 'url' in col and not col == 'avatar_url': continue nd.update({prefix + col: data_org[col]}) orgs.update(nd) return orgs try: acitiviy = get_activity_from_html(user.get('username')) except Exception as e: logger.exception(e) raise acitiviy = {} from pprint import pprint as pp ; pp(acitiviy) if acitiviy is None: return None profile = get_profile(user) orgs = get_orgs(user.get('username')) user.update(acitiviy) user.update(profile) user.update(orgs) return user # extend_user({'username': 'tensystems'}) # raise all_usernames = [u['username'] for u in all_users] for user in existing_users: if user['username'] in all_usernames: continue user_update = extend_user(user) if user_update is None: continue all_users.append(user_update) json.dump(all_users, open('step3.json', 'w'), indent=4) json.dump(all_users, open('step3.json', 'w'), indent=4)
{ "pile_set_name": "Github" }
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
{ "pile_set_name": "Github" }
24 11 11 24x24/bd_double_arrow.png 32 14 14 32x32/bd_double_arrow.png 48 21 21 48x48/bd_double_arrow.png 64 28 28 64x64/bd_double_arrow.png 96 42 41 96x96/bd_double_arrow.png
{ "pile_set_name": "Github" }
name: UnicodeMisc_Assigned_6_3 description: Tests character class syntax of the Unicode 6.3 'Assigned' property. jflex: -q input-file-encoding: UTF-8 common-input-file: ../../resources/All.Unicode.characters.input
{ "pile_set_name": "Github" }
/* 8390.c: A general NS8390 ethernet driver core for linux. */ /* Written 1992-94 by Donald Becker. Copyright 1993 United States Government as represented by the Director, National Security Agency. This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. The author may be reached as [email protected], or C/O Scyld Computing Corporation 410 Severn Ave., Suite 210 Annapolis MD 21403 This is the chip-specific code for many 8390-based ethernet adaptors. This is not a complete driver, it must be combined with board-specific code such as ne.c, wd.c, 3c503.c, etc. Seeing how at least eight drivers use this code, (not counting the PCMCIA ones either) it is easy to break some card by what seems like a simple innocent change. Please contact me or Donald if you think you have found something that needs changing. -- PG Changelog: Paul Gortmaker : remove set_bit lock, other cleanups. Paul Gortmaker : add ei_get_8390_hdr() so we can pass skb's to ei_block_input() for eth_io_copy_and_sum(). Paul Gortmaker : exchange static int ei_pingpong for a #define, also add better Tx error handling. Paul Gortmaker : rewrite Rx overrun handling as per NS specs. Alexey Kuznetsov : use the 8390's six bit hash multicast filter. Paul Gortmaker : tweak ANK's above multicast changes a bit. Paul Gortmaker : update packet statistics for v2.1.x Alan Cox : support arbitrary stupid port mappings on the 68K Macintosh. Support >16bit I/O spaces Paul Gortmaker : add kmod support for auto-loading of the 8390 module by all drivers that require it. Alan Cox : Spinlocking work, added 'BUG_83C690' Paul Gortmaker : Separate out Tx timeout code from Tx path. Paul Gortmaker : Remove old unused single Tx buffer code. Hayato Fujiwara : Add m32r support. Paul Gortmaker : use skb_padto() instead of stack scratch area Sources: The National Semiconductor LAN Databook, and the 3Com 3c503 databook. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/jiffies.h> #include <linux/fs.h> #include <linux/types.h> #include <linux/string.h> #include <linux/bitops.h> #include <linux/uaccess.h> #include <linux/io.h> #include <asm/irq.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/fcntl.h> #include <linux/in.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/crc32.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #define NS8390_CORE #include "8390.h" #define BUG_83C690 /* These are the operational function interfaces to board-specific routines. void reset_8390(struct net_device *dev) Resets the board associated with DEV, including a hardware reset of the 8390. This is only called when there is a transmit timeout, and it is always followed by 8390_init(). void block_output(struct net_device *dev, int count, const unsigned char *buf, int start_page) Write the COUNT bytes of BUF to the packet buffer at START_PAGE. The "page" value uses the 8390's 256-byte pages. void get_8390_hdr(struct net_device *dev, struct e8390_hdr *hdr, int ring_page) Read the 4 byte, page aligned 8390 header. *If* there is a subsequent read, it will be of the rest of the packet. void block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset) Read COUNT bytes from the packet buffer into the skb data area. Start reading from RING_OFFSET, the address as the 8390 sees it. This will always follow the read of the 8390 header. */ #define ei_reset_8390 (ei_local->reset_8390) #define ei_block_output (ei_local->block_output) #define ei_block_input (ei_local->block_input) #define ei_get_8390_hdr (ei_local->get_8390_hdr) /* Index to functions. */ static void ei_tx_intr(struct net_device *dev); static void ei_tx_err(struct net_device *dev); static void ei_receive(struct net_device *dev); static void ei_rx_overrun(struct net_device *dev); /* Routines generic to NS8390-based boards. */ static void NS8390_trigger_send(struct net_device *dev, unsigned int length, int start_page); static void do_set_multicast_list(struct net_device *dev); static void __NS8390_init(struct net_device *dev, int startp); static unsigned version_printed; static u32 msg_enable; module_param(msg_enable, uint, (S_IRUSR|S_IRGRP|S_IROTH)); MODULE_PARM_DESC(msg_enable, "Debug message level (see linux/netdevice.h for bitmap)"); /* * SMP and the 8390 setup. * * The 8390 isn't exactly designed to be multithreaded on RX/TX. There is * a page register that controls bank and packet buffer access. We guard * this with ei_local->page_lock. Nobody should assume or set the page other * than zero when the lock is not held. Lock holders must restore page 0 * before unlocking. Even pure readers must take the lock to protect in * page 0. * * To make life difficult the chip can also be very slow. We therefore can't * just use spinlocks. For the longer lockups we disable the irq the device * sits on and hold the lock. We must hold the lock because there is a dual * processor case other than interrupts (get stats/set multicast list in * parallel with each other and transmit). * * Note: in theory we can just disable the irq on the card _but_ there is * a latency on SMP irq delivery. So we can easily go "disable irq" "sync irqs" * enter lock, take the queued irq. So we waddle instead of flying. * * Finally by special arrangement for the purpose of being generally * annoying the transmit function is called bh atomic. That places * restrictions on the user context callers as disable_irq won't save * them. * * Additional explanation of problems with locking by Alan Cox: * * "The author (me) didn't use spin_lock_irqsave because the slowness of the * card means that approach caused horrible problems like losing serial data * at 38400 baud on some chips. Remember many 8390 nics on PCI were ISA * chips with FPGA front ends. * * Ok the logic behind the 8390 is very simple: * * Things to know * - IRQ delivery is asynchronous to the PCI bus * - Blocking the local CPU IRQ via spin locks was too slow * - The chip has register windows needing locking work * * So the path was once (I say once as people appear to have changed it * in the mean time and it now looks rather bogus if the changes to use * disable_irq_nosync_irqsave are disabling the local IRQ) * * * Take the page lock * Mask the IRQ on chip * Disable the IRQ (but not mask locally- someone seems to have * broken this with the lock validator stuff) * [This must be _nosync as the page lock may otherwise * deadlock us] * Drop the page lock and turn IRQs back on * * At this point an existing IRQ may still be running but we can't * get a new one * * Take the lock (so we know the IRQ has terminated) but don't mask * the IRQs on the processor * Set irqlock [for debug] * * Transmit (slow as ****) * * re-enable the IRQ * * * We have to use disable_irq because otherwise you will get delayed * interrupts on the APIC bus deadlocking the transmit path. * * Quite hairy but the chip simply wasn't designed for SMP and you can't * even ACK an interrupt without risking corrupting other parallel * activities on the chip." [lkml, 25 Jul 2007] */ /** * ei_open - Open/initialize the board. * @dev: network device to initialize * * This routine goes all-out, setting everything * up anew at each open, even though many of these registers should only * need to be set once at boot. */ static int __ei_open(struct net_device *dev) { unsigned long flags; struct ei_device *ei_local = netdev_priv(dev); if (dev->watchdog_timeo <= 0) dev->watchdog_timeo = TX_TIMEOUT; /* * Grab the page lock so we own the register set, then call * the init function. */ spin_lock_irqsave(&ei_local->page_lock, flags); __NS8390_init(dev, 1); /* Set the flag before we drop the lock, That way the IRQ arrives after its set and we get no silly warnings */ netif_start_queue(dev); spin_unlock_irqrestore(&ei_local->page_lock, flags); ei_local->irqlock = 0; return 0; } /** * ei_close - shut down network device * @dev: network device to close * * Opposite of ei_open(). Only used when "ifconfig <devname> down" is done. */ static int __ei_close(struct net_device *dev) { struct ei_device *ei_local = netdev_priv(dev); unsigned long flags; /* * Hold the page lock during close */ spin_lock_irqsave(&ei_local->page_lock, flags); __NS8390_init(dev, 0); spin_unlock_irqrestore(&ei_local->page_lock, flags); netif_stop_queue(dev); return 0; } /** * ei_tx_timeout - handle transmit time out condition * @dev: network device which has apparently fallen asleep * * Called by kernel when device never acknowledges a transmit has * completed (or failed) - i.e. never posted a Tx related interrupt. */ static void __ei_tx_timeout(struct net_device *dev) { unsigned long e8390_base = dev->base_addr; struct ei_device *ei_local = netdev_priv(dev); int txsr, isr, tickssofar = jiffies - dev_trans_start(dev); unsigned long flags; dev->stats.tx_errors++; spin_lock_irqsave(&ei_local->page_lock, flags); txsr = ei_inb(e8390_base+EN0_TSR); isr = ei_inb(e8390_base+EN0_ISR); spin_unlock_irqrestore(&ei_local->page_lock, flags); netdev_dbg(dev, "Tx timed out, %s TSR=%#2x, ISR=%#2x, t=%d\n", (txsr & ENTSR_ABT) ? "excess collisions." : (isr) ? "lost interrupt?" : "cable problem?", txsr, isr, tickssofar); if (!isr && !dev->stats.tx_packets) { /* The 8390 probably hasn't gotten on the cable yet. */ ei_local->interface_num ^= 1; /* Try a different xcvr. */ } /* Ugly but a reset can be slow, yet must be protected */ disable_irq_nosync_lockdep(dev->irq); spin_lock(&ei_local->page_lock); /* Try to restart the card. Perhaps the user has fixed something. */ ei_reset_8390(dev); __NS8390_init(dev, 1); spin_unlock(&ei_local->page_lock); enable_irq_lockdep(dev->irq); netif_wake_queue(dev); } /** * ei_start_xmit - begin packet transmission * @skb: packet to be sent * @dev: network device to which packet is sent * * Sends a packet to an 8390 network device. */ static netdev_tx_t __ei_start_xmit(struct sk_buff *skb, struct net_device *dev) { unsigned long e8390_base = dev->base_addr; struct ei_device *ei_local = netdev_priv(dev); int send_length = skb->len, output_page; unsigned long flags; char buf[ETH_ZLEN]; char *data = skb->data; if (skb->len < ETH_ZLEN) { memset(buf, 0, ETH_ZLEN); /* more efficient than doing just the needed bits */ memcpy(buf, data, skb->len); send_length = ETH_ZLEN; data = buf; } /* Mask interrupts from the ethercard. SMP: We have to grab the lock here otherwise the IRQ handler on another CPU can flip window and race the IRQ mask set. We end up trashing the mcast filter not disabling irqs if we don't lock */ spin_lock_irqsave(&ei_local->page_lock, flags); ei_outb_p(0x00, e8390_base + EN0_IMR); spin_unlock_irqrestore(&ei_local->page_lock, flags); /* * Slow phase with lock held. */ disable_irq_nosync_lockdep_irqsave(dev->irq, &flags); spin_lock(&ei_local->page_lock); ei_local->irqlock = 1; /* * We have two Tx slots available for use. Find the first free * slot, and then perform some sanity checks. With two Tx bufs, * you get very close to transmitting back-to-back packets. With * only one Tx buf, the transmitter sits idle while you reload the * card, leaving a substantial gap between each transmitted packet. */ if (ei_local->tx1 == 0) { output_page = ei_local->tx_start_page; ei_local->tx1 = send_length; if ((netif_msg_tx_queued(ei_local)) && ei_local->tx2 > 0) netdev_dbg(dev, "idle transmitter tx2=%d, lasttx=%d, txing=%d\n", ei_local->tx2, ei_local->lasttx, ei_local->txing); } else if (ei_local->tx2 == 0) { output_page = ei_local->tx_start_page + TX_PAGES/2; ei_local->tx2 = send_length; if ((netif_msg_tx_queued(ei_local)) && ei_local->tx1 > 0) netdev_dbg(dev, "idle transmitter, tx1=%d, lasttx=%d, txing=%d\n", ei_local->tx1, ei_local->lasttx, ei_local->txing); } else { /* We should never get here. */ netif_dbg(ei_local, tx_err, dev, "No Tx buffers free! tx1=%d tx2=%d last=%d\n", ei_local->tx1, ei_local->tx2, ei_local->lasttx); ei_local->irqlock = 0; netif_stop_queue(dev); ei_outb_p(ENISR_ALL, e8390_base + EN0_IMR); spin_unlock(&ei_local->page_lock); enable_irq_lockdep_irqrestore(dev->irq, &flags); dev->stats.tx_errors++; return NETDEV_TX_BUSY; } /* * Okay, now upload the packet and trigger a send if the transmitter * isn't already sending. If it is busy, the interrupt handler will * trigger the send later, upon receiving a Tx done interrupt. */ ei_block_output(dev, send_length, data, output_page); if (!ei_local->txing) { ei_local->txing = 1; NS8390_trigger_send(dev, send_length, output_page); if (output_page == ei_local->tx_start_page) { ei_local->tx1 = -1; ei_local->lasttx = -1; } else { ei_local->tx2 = -1; ei_local->lasttx = -2; } } else ei_local->txqueue++; if (ei_local->tx1 && ei_local->tx2) netif_stop_queue(dev); else netif_start_queue(dev); /* Turn 8390 interrupts back on. */ ei_local->irqlock = 0; ei_outb_p(ENISR_ALL, e8390_base + EN0_IMR); spin_unlock(&ei_local->page_lock); enable_irq_lockdep_irqrestore(dev->irq, &flags); skb_tx_timestamp(skb); dev_consume_skb_any(skb); dev->stats.tx_bytes += send_length; return NETDEV_TX_OK; } /** * ei_interrupt - handle the interrupts from an 8390 * @irq: interrupt number * @dev_id: a pointer to the net_device * * Handle the ether interface interrupts. We pull packets from * the 8390 via the card specific functions and fire them at the networking * stack. We also handle transmit completions and wake the transmit path if * necessary. We also update the counters and do other housekeeping as * needed. */ static irqreturn_t __ei_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; unsigned long e8390_base = dev->base_addr; int interrupts, nr_serviced = 0; struct ei_device *ei_local = netdev_priv(dev); /* * Protect the irq test too. */ spin_lock(&ei_local->page_lock); if (ei_local->irqlock) { /* * This might just be an interrupt for a PCI device sharing * this line */ netdev_err(dev, "Interrupted while interrupts are masked! isr=%#2x imr=%#2x\n", ei_inb_p(e8390_base + EN0_ISR), ei_inb_p(e8390_base + EN0_IMR)); spin_unlock(&ei_local->page_lock); return IRQ_NONE; } /* Change to page 0 and read the intr status reg. */ ei_outb_p(E8390_NODMA+E8390_PAGE0, e8390_base + E8390_CMD); netif_dbg(ei_local, intr, dev, "interrupt(isr=%#2.2x)\n", ei_inb_p(e8390_base + EN0_ISR)); /* !!Assumption!! -- we stay in page 0. Don't break this. */ while ((interrupts = ei_inb_p(e8390_base + EN0_ISR)) != 0 && ++nr_serviced < MAX_SERVICE) { if (!netif_running(dev)) { netdev_warn(dev, "interrupt from stopped card\n"); /* rmk - acknowledge the interrupts */ ei_outb_p(interrupts, e8390_base + EN0_ISR); interrupts = 0; break; } if (interrupts & ENISR_OVER) ei_rx_overrun(dev); else if (interrupts & (ENISR_RX+ENISR_RX_ERR)) { /* Got a good (?) packet. */ ei_receive(dev); } /* Push the next to-transmit packet through. */ if (interrupts & ENISR_TX) ei_tx_intr(dev); else if (interrupts & ENISR_TX_ERR) ei_tx_err(dev); if (interrupts & ENISR_COUNTERS) { dev->stats.rx_frame_errors += ei_inb_p(e8390_base + EN0_COUNTER0); dev->stats.rx_crc_errors += ei_inb_p(e8390_base + EN0_COUNTER1); dev->stats.rx_missed_errors += ei_inb_p(e8390_base + EN0_COUNTER2); ei_outb_p(ENISR_COUNTERS, e8390_base + EN0_ISR); /* Ack intr. */ } /* Ignore any RDC interrupts that make it back to here. */ if (interrupts & ENISR_RDC) ei_outb_p(ENISR_RDC, e8390_base + EN0_ISR); ei_outb_p(E8390_NODMA+E8390_PAGE0+E8390_START, e8390_base + E8390_CMD); } if (interrupts && (netif_msg_intr(ei_local))) { ei_outb_p(E8390_NODMA+E8390_PAGE0+E8390_START, e8390_base + E8390_CMD); if (nr_serviced >= MAX_SERVICE) { /* 0xFF is valid for a card removal */ if (interrupts != 0xFF) netdev_warn(dev, "Too much work at interrupt, status %#2.2x\n", interrupts); ei_outb_p(ENISR_ALL, e8390_base + EN0_ISR); /* Ack. most intrs. */ } else { netdev_warn(dev, "unknown interrupt %#2x\n", interrupts); ei_outb_p(0xff, e8390_base + EN0_ISR); /* Ack. all intrs. */ } } spin_unlock(&ei_local->page_lock); return IRQ_RETVAL(nr_serviced > 0); } #ifdef CONFIG_NET_POLL_CONTROLLER static void __ei_poll(struct net_device *dev) { disable_irq(dev->irq); __ei_interrupt(dev->irq, dev); enable_irq(dev->irq); } #endif /** * ei_tx_err - handle transmitter error * @dev: network device which threw the exception * * A transmitter error has happened. Most likely excess collisions (which * is a fairly normal condition). If the error is one where the Tx will * have been aborted, we try and send another one right away, instead of * letting the failed packet sit and collect dust in the Tx buffer. This * is a much better solution as it avoids kernel based Tx timeouts, and * an unnecessary card reset. * * Called with lock held. */ static void ei_tx_err(struct net_device *dev) { unsigned long e8390_base = dev->base_addr; /* ei_local is used on some platforms via the EI_SHIFT macro */ struct ei_device *ei_local __maybe_unused = netdev_priv(dev); unsigned char txsr = ei_inb_p(e8390_base+EN0_TSR); unsigned char tx_was_aborted = txsr & (ENTSR_ABT+ENTSR_FU); #ifdef VERBOSE_ERROR_DUMP netdev_dbg(dev, "transmitter error (%#2x):", txsr); if (txsr & ENTSR_ABT) pr_cont(" excess-collisions "); if (txsr & ENTSR_ND) pr_cont(" non-deferral "); if (txsr & ENTSR_CRS) pr_cont(" lost-carrier "); if (txsr & ENTSR_FU) pr_cont(" FIFO-underrun "); if (txsr & ENTSR_CDH) pr_cont(" lost-heartbeat "); pr_cont("\n"); #endif ei_outb_p(ENISR_TX_ERR, e8390_base + EN0_ISR); /* Ack intr. */ if (tx_was_aborted) ei_tx_intr(dev); else { dev->stats.tx_errors++; if (txsr & ENTSR_CRS) dev->stats.tx_carrier_errors++; if (txsr & ENTSR_CDH) dev->stats.tx_heartbeat_errors++; if (txsr & ENTSR_OWC) dev->stats.tx_window_errors++; } } /** * ei_tx_intr - transmit interrupt handler * @dev: network device for which tx intr is handled * * We have finished a transmit: check for errors and then trigger the next * packet to be sent. Called with lock held. */ static void ei_tx_intr(struct net_device *dev) { unsigned long e8390_base = dev->base_addr; struct ei_device *ei_local = netdev_priv(dev); int status = ei_inb(e8390_base + EN0_TSR); ei_outb_p(ENISR_TX, e8390_base + EN0_ISR); /* Ack intr. */ /* * There are two Tx buffers, see which one finished, and trigger * the send of another one if it exists. */ ei_local->txqueue--; if (ei_local->tx1 < 0) { if (ei_local->lasttx != 1 && ei_local->lasttx != -1) pr_err("%s: bogus last_tx_buffer %d, tx1=%d\n", ei_local->name, ei_local->lasttx, ei_local->tx1); ei_local->tx1 = 0; if (ei_local->tx2 > 0) { ei_local->txing = 1; NS8390_trigger_send(dev, ei_local->tx2, ei_local->tx_start_page + 6); dev->trans_start = jiffies; ei_local->tx2 = -1, ei_local->lasttx = 2; } else ei_local->lasttx = 20, ei_local->txing = 0; } else if (ei_local->tx2 < 0) { if (ei_local->lasttx != 2 && ei_local->lasttx != -2) pr_err("%s: bogus last_tx_buffer %d, tx2=%d\n", ei_local->name, ei_local->lasttx, ei_local->tx2); ei_local->tx2 = 0; if (ei_local->tx1 > 0) { ei_local->txing = 1; NS8390_trigger_send(dev, ei_local->tx1, ei_local->tx_start_page); dev->trans_start = jiffies; ei_local->tx1 = -1; ei_local->lasttx = 1; } else ei_local->lasttx = 10, ei_local->txing = 0; } /* else netdev_warn(dev, "unexpected TX-done interrupt, lasttx=%d\n", ei_local->lasttx); */ /* Minimize Tx latency: update the statistics after we restart TXing. */ if (status & ENTSR_COL) dev->stats.collisions++; if (status & ENTSR_PTX) dev->stats.tx_packets++; else { dev->stats.tx_errors++; if (status & ENTSR_ABT) { dev->stats.tx_aborted_errors++; dev->stats.collisions += 16; } if (status & ENTSR_CRS) dev->stats.tx_carrier_errors++; if (status & ENTSR_FU) dev->stats.tx_fifo_errors++; if (status & ENTSR_CDH) dev->stats.tx_heartbeat_errors++; if (status & ENTSR_OWC) dev->stats.tx_window_errors++; } netif_wake_queue(dev); } /** * ei_receive - receive some packets * @dev: network device with which receive will be run * * We have a good packet(s), get it/them out of the buffers. * Called with lock held. */ static void ei_receive(struct net_device *dev) { unsigned long e8390_base = dev->base_addr; struct ei_device *ei_local = netdev_priv(dev); unsigned char rxing_page, this_frame, next_frame; unsigned short current_offset; int rx_pkt_count = 0; struct e8390_pkt_hdr rx_frame; int num_rx_pages = ei_local->stop_page-ei_local->rx_start_page; while (++rx_pkt_count < 10) { int pkt_len, pkt_stat; /* Get the rx page (incoming packet pointer). */ ei_outb_p(E8390_NODMA+E8390_PAGE1, e8390_base + E8390_CMD); rxing_page = ei_inb_p(e8390_base + EN1_CURPAG); ei_outb_p(E8390_NODMA+E8390_PAGE0, e8390_base + E8390_CMD); /* Remove one frame from the ring. Boundary is always a page behind. */ this_frame = ei_inb_p(e8390_base + EN0_BOUNDARY) + 1; if (this_frame >= ei_local->stop_page) this_frame = ei_local->rx_start_page; /* Someday we'll omit the previous, iff we never get this message. (There is at least one clone claimed to have a problem.) Keep quiet if it looks like a card removal. One problem here is that some clones crash in roughly the same way. */ if ((netif_msg_rx_status(ei_local)) && this_frame != ei_local->current_page && (this_frame != 0x0 || rxing_page != 0xFF)) netdev_err(dev, "mismatched read page pointers %2x vs %2x\n", this_frame, ei_local->current_page); if (this_frame == rxing_page) /* Read all the frames? */ break; /* Done for now */ current_offset = this_frame << 8; ei_get_8390_hdr(dev, &rx_frame, this_frame); pkt_len = rx_frame.count - sizeof(struct e8390_pkt_hdr); pkt_stat = rx_frame.status; next_frame = this_frame + 1 + ((pkt_len+4)>>8); /* Check for bogosity warned by 3c503 book: the status byte is never written. This happened a lot during testing! This code should be cleaned up someday. */ if (rx_frame.next != next_frame && rx_frame.next != next_frame + 1 && rx_frame.next != next_frame - num_rx_pages && rx_frame.next != next_frame + 1 - num_rx_pages) { ei_local->current_page = rxing_page; ei_outb(ei_local->current_page-1, e8390_base+EN0_BOUNDARY); dev->stats.rx_errors++; continue; } if (pkt_len < 60 || pkt_len > 1518) { netif_dbg(ei_local, rx_status, dev, "bogus packet size: %d, status=%#2x nxpg=%#2x\n", rx_frame.count, rx_frame.status, rx_frame.next); dev->stats.rx_errors++; dev->stats.rx_length_errors++; } else if ((pkt_stat & 0x0F) == ENRSR_RXOK) { struct sk_buff *skb; skb = netdev_alloc_skb(dev, pkt_len + 2); if (skb == NULL) { netif_err(ei_local, rx_err, dev, "Couldn't allocate a sk_buff of size %d\n", pkt_len); dev->stats.rx_dropped++; break; } else { skb_reserve(skb, 2); /* IP headers on 16 byte boundaries */ skb_put(skb, pkt_len); /* Make room */ ei_block_input(dev, pkt_len, skb, current_offset + sizeof(rx_frame)); skb->protocol = eth_type_trans(skb, dev); if (!skb_defer_rx_timestamp(skb)) netif_rx(skb); dev->stats.rx_packets++; dev->stats.rx_bytes += pkt_len; if (pkt_stat & ENRSR_PHY) dev->stats.multicast++; } } else { netif_err(ei_local, rx_err, dev, "bogus packet: status=%#2x nxpg=%#2x size=%d\n", rx_frame.status, rx_frame.next, rx_frame.count); dev->stats.rx_errors++; /* NB: The NIC counts CRC, frame and missed errors. */ if (pkt_stat & ENRSR_FO) dev->stats.rx_fifo_errors++; } next_frame = rx_frame.next; /* This _should_ never happen: it's here for avoiding bad clones. */ if (next_frame >= ei_local->stop_page) { netdev_notice(dev, "next frame inconsistency, %#2x\n", next_frame); next_frame = ei_local->rx_start_page; } ei_local->current_page = next_frame; ei_outb_p(next_frame-1, e8390_base+EN0_BOUNDARY); } /* We used to also ack ENISR_OVER here, but that would sometimes mask a real overrun, leaving the 8390 in a stopped state with rec'vr off. */ ei_outb_p(ENISR_RX+ENISR_RX_ERR, e8390_base+EN0_ISR); } /** * ei_rx_overrun - handle receiver overrun * @dev: network device which threw exception * * We have a receiver overrun: we have to kick the 8390 to get it started * again. Problem is that you have to kick it exactly as NS prescribes in * the updated datasheets, or "the NIC may act in an unpredictable manner." * This includes causing "the NIC to defer indefinitely when it is stopped * on a busy network." Ugh. * Called with lock held. Don't call this with the interrupts off or your * computer will hate you - it takes 10ms or so. */ static void ei_rx_overrun(struct net_device *dev) { unsigned long e8390_base = dev->base_addr; unsigned char was_txing, must_resend = 0; /* ei_local is used on some platforms via the EI_SHIFT macro */ struct ei_device *ei_local __maybe_unused = netdev_priv(dev); /* * Record whether a Tx was in progress and then issue the * stop command. */ was_txing = ei_inb_p(e8390_base+E8390_CMD) & E8390_TRANS; ei_outb_p(E8390_NODMA+E8390_PAGE0+E8390_STOP, e8390_base+E8390_CMD); netif_dbg(ei_local, rx_err, dev, "Receiver overrun\n"); dev->stats.rx_over_errors++; /* * Wait a full Tx time (1.2ms) + some guard time, NS says 1.6ms total. * Early datasheets said to poll the reset bit, but now they say that * it "is not a reliable indicator and subsequently should be ignored." * We wait at least 10ms. */ mdelay(10); /* * Reset RBCR[01] back to zero as per magic incantation. */ ei_outb_p(0x00, e8390_base+EN0_RCNTLO); ei_outb_p(0x00, e8390_base+EN0_RCNTHI); /* * See if any Tx was interrupted or not. According to NS, this * step is vital, and skipping it will cause no end of havoc. */ if (was_txing) { unsigned char tx_completed = ei_inb_p(e8390_base+EN0_ISR) & (ENISR_TX+ENISR_TX_ERR); if (!tx_completed) must_resend = 1; } /* * Have to enter loopback mode and then restart the NIC before * you are allowed to slurp packets up off the ring. */ ei_outb_p(E8390_TXOFF, e8390_base + EN0_TXCR); ei_outb_p(E8390_NODMA + E8390_PAGE0 + E8390_START, e8390_base + E8390_CMD); /* * Clear the Rx ring of all the debris, and ack the interrupt. */ ei_receive(dev); ei_outb_p(ENISR_OVER, e8390_base+EN0_ISR); /* * Leave loopback mode, and resend any packet that got stopped. */ ei_outb_p(E8390_TXCONFIG, e8390_base + EN0_TXCR); if (must_resend) ei_outb_p(E8390_NODMA + E8390_PAGE0 + E8390_START + E8390_TRANS, e8390_base + E8390_CMD); } /* * Collect the stats. This is called unlocked and from several contexts. */ static struct net_device_stats *__ei_get_stats(struct net_device *dev) { unsigned long ioaddr = dev->base_addr; struct ei_device *ei_local = netdev_priv(dev); unsigned long flags; /* If the card is stopped, just return the present stats. */ if (!netif_running(dev)) return &dev->stats; spin_lock_irqsave(&ei_local->page_lock, flags); /* Read the counter registers, assuming we are in page 0. */ dev->stats.rx_frame_errors += ei_inb_p(ioaddr + EN0_COUNTER0); dev->stats.rx_crc_errors += ei_inb_p(ioaddr + EN0_COUNTER1); dev->stats.rx_missed_errors += ei_inb_p(ioaddr + EN0_COUNTER2); spin_unlock_irqrestore(&ei_local->page_lock, flags); return &dev->stats; } /* * Form the 64 bit 8390 multicast table from the linked list of addresses * associated with this dev structure. */ static inline void make_mc_bits(u8 *bits, struct net_device *dev) { struct netdev_hw_addr *ha; netdev_for_each_mc_addr(ha, dev) { u32 crc = ether_crc(ETH_ALEN, ha->addr); /* * The 8390 uses the 6 most significant bits of the * CRC to index the multicast table. */ bits[crc>>29] |= (1<<((crc>>26)&7)); } } /** * do_set_multicast_list - set/clear multicast filter * @dev: net device for which multicast filter is adjusted * * Set or clear the multicast filter for this adaptor. May be called * from a BH in 2.1.x. Must be called with lock held. */ static void do_set_multicast_list(struct net_device *dev) { unsigned long e8390_base = dev->base_addr; int i; struct ei_device *ei_local = netdev_priv(dev); if (!(dev->flags&(IFF_PROMISC|IFF_ALLMULTI))) { memset(ei_local->mcfilter, 0, 8); if (!netdev_mc_empty(dev)) make_mc_bits(ei_local->mcfilter, dev); } else memset(ei_local->mcfilter, 0xFF, 8); /* mcast set to accept-all */ /* * DP8390 manuals don't specify any magic sequence for altering * the multicast regs on an already running card. To be safe, we * ensure multicast mode is off prior to loading up the new hash * table. If this proves to be not enough, we can always resort * to stopping the NIC, loading the table and then restarting. * * Bug Alert! The MC regs on the SMC 83C690 (SMC Elite and SMC * Elite16) appear to be write-only. The NS 8390 data sheet lists * them as r/w so this is a bug. The SMC 83C790 (SMC Ultra and * Ultra32 EISA) appears to have this bug fixed. */ if (netif_running(dev)) ei_outb_p(E8390_RXCONFIG, e8390_base + EN0_RXCR); ei_outb_p(E8390_NODMA + E8390_PAGE1, e8390_base + E8390_CMD); for (i = 0; i < 8; i++) { ei_outb_p(ei_local->mcfilter[i], e8390_base + EN1_MULT_SHIFT(i)); #ifndef BUG_83C690 if (ei_inb_p(e8390_base + EN1_MULT_SHIFT(i)) != ei_local->mcfilter[i]) netdev_err(dev, "Multicast filter read/write mismap %d\n", i); #endif } ei_outb_p(E8390_NODMA + E8390_PAGE0, e8390_base + E8390_CMD); if (dev->flags&IFF_PROMISC) ei_outb_p(E8390_RXCONFIG | 0x18, e8390_base + EN0_RXCR); else if (dev->flags & IFF_ALLMULTI || !netdev_mc_empty(dev)) ei_outb_p(E8390_RXCONFIG | 0x08, e8390_base + EN0_RXCR); else ei_outb_p(E8390_RXCONFIG, e8390_base + EN0_RXCR); } /* * Called without lock held. This is invoked from user context and may * be parallel to just about everything else. Its also fairly quick and * not called too often. Must protect against both bh and irq users */ static void __ei_set_multicast_list(struct net_device *dev) { unsigned long flags; struct ei_device *ei_local = netdev_priv(dev); spin_lock_irqsave(&ei_local->page_lock, flags); do_set_multicast_list(dev); spin_unlock_irqrestore(&ei_local->page_lock, flags); } /** * ethdev_setup - init rest of 8390 device struct * @dev: network device structure to init * * Initialize the rest of the 8390 device structure. Do NOT __init * this, as it is used by 8390 based modular drivers too. */ static void ethdev_setup(struct net_device *dev) { struct ei_device *ei_local = netdev_priv(dev); if ((msg_enable & NETIF_MSG_DRV) && (version_printed++ == 0)) pr_info("%s", version); ether_setup(dev); spin_lock_init(&ei_local->page_lock); } /** * alloc_ei_netdev - alloc_etherdev counterpart for 8390 * @size: extra bytes to allocate * * Allocate 8390-specific net_device. */ static struct net_device *____alloc_ei_netdev(int size) { return alloc_netdev(sizeof(struct ei_device) + size, "eth%d", NET_NAME_UNKNOWN, ethdev_setup); } /* This page of functions should be 8390 generic */ /* Follow National Semi's recommendations for initializing the "NIC". */ /** * NS8390_init - initialize 8390 hardware * @dev: network device to initialize * @startp: boolean. non-zero value to initiate chip processing * * Must be called with lock held. */ static void __NS8390_init(struct net_device *dev, int startp) { unsigned long e8390_base = dev->base_addr; struct ei_device *ei_local = netdev_priv(dev); int i; int endcfg = ei_local->word16 ? (0x48 | ENDCFG_WTS | (ei_local->bigendian ? ENDCFG_BOS : 0)) : 0x48; if (sizeof(struct e8390_pkt_hdr) != 4) panic("8390.c: header struct mispacked\n"); /* Follow National Semi's recommendations for initing the DP83902. */ ei_outb_p(E8390_NODMA+E8390_PAGE0+E8390_STOP, e8390_base+E8390_CMD); /* 0x21 */ ei_outb_p(endcfg, e8390_base + EN0_DCFG); /* 0x48 or 0x49 */ /* Clear the remote byte count registers. */ ei_outb_p(0x00, e8390_base + EN0_RCNTLO); ei_outb_p(0x00, e8390_base + EN0_RCNTHI); /* Set to monitor and loopback mode -- this is vital!. */ ei_outb_p(E8390_RXOFF, e8390_base + EN0_RXCR); /* 0x20 */ ei_outb_p(E8390_TXOFF, e8390_base + EN0_TXCR); /* 0x02 */ /* Set the transmit page and receive ring. */ ei_outb_p(ei_local->tx_start_page, e8390_base + EN0_TPSR); ei_local->tx1 = ei_local->tx2 = 0; ei_outb_p(ei_local->rx_start_page, e8390_base + EN0_STARTPG); ei_outb_p(ei_local->stop_page-1, e8390_base + EN0_BOUNDARY); /* 3c503 says 0x3f,NS0x26*/ ei_local->current_page = ei_local->rx_start_page; /* assert boundary+1 */ ei_outb_p(ei_local->stop_page, e8390_base + EN0_STOPPG); /* Clear the pending interrupts and mask. */ ei_outb_p(0xFF, e8390_base + EN0_ISR); ei_outb_p(0x00, e8390_base + EN0_IMR); /* Copy the station address into the DS8390 registers. */ ei_outb_p(E8390_NODMA + E8390_PAGE1 + E8390_STOP, e8390_base+E8390_CMD); /* 0x61 */ for (i = 0; i < 6; i++) { ei_outb_p(dev->dev_addr[i], e8390_base + EN1_PHYS_SHIFT(i)); if ((netif_msg_probe(ei_local)) && ei_inb_p(e8390_base + EN1_PHYS_SHIFT(i)) != dev->dev_addr[i]) netdev_err(dev, "Hw. address read/write mismap %d\n", i); } ei_outb_p(ei_local->rx_start_page, e8390_base + EN1_CURPAG); ei_outb_p(E8390_NODMA+E8390_PAGE0+E8390_STOP, e8390_base+E8390_CMD); ei_local->tx1 = ei_local->tx2 = 0; ei_local->txing = 0; if (startp) { ei_outb_p(0xff, e8390_base + EN0_ISR); ei_outb_p(ENISR_ALL, e8390_base + EN0_IMR); ei_outb_p(E8390_NODMA+E8390_PAGE0+E8390_START, e8390_base+E8390_CMD); ei_outb_p(E8390_TXCONFIG, e8390_base + EN0_TXCR); /* xmit on. */ /* 3c503 TechMan says rxconfig only after the NIC is started. */ ei_outb_p(E8390_RXCONFIG, e8390_base + EN0_RXCR); /* rx on, */ do_set_multicast_list(dev); /* (re)load the mcast table */ } } /* Trigger a transmit start, assuming the length is valid. Always called with the page lock held */ static void NS8390_trigger_send(struct net_device *dev, unsigned int length, int start_page) { unsigned long e8390_base = dev->base_addr; struct ei_device *ei_local __attribute((unused)) = netdev_priv(dev); ei_outb_p(E8390_NODMA+E8390_PAGE0, e8390_base+E8390_CMD); if (ei_inb_p(e8390_base + E8390_CMD) & E8390_TRANS) { netdev_warn(dev, "trigger_send() called with the transmitter busy\n"); return; } ei_outb_p(length & 0xff, e8390_base + EN0_TCNTLO); ei_outb_p(length >> 8, e8390_base + EN0_TCNTHI); ei_outb_p(start_page, e8390_base + EN0_TPSR); ei_outb_p(E8390_NODMA+E8390_TRANS+E8390_START, e8390_base+E8390_CMD); }
{ "pile_set_name": "Github" }
StartChar: uni0314.grk Encoding: 1114990 -1 2710 Width: 0 VWidth: 0 Flags: HMW AnchorPoint: "grk_hstack" 130 640 basemark 0 AnchorPoint: "grk_top" 130 550 mark 0 AnchorPoint: "grk_uc_top_left" 202 630 mark 0 LayerCount: 3 Back SplineSet 90 590 m 0 70 589 53 568 53 544 c 0 53 513 73 488 102 478 c 0 111 475 116 470 116 466 c 0 116 461 110 456 98 456 c 0 59 456 0 497 0 561 c 0 0 617 31 656 79 656 c 0 108 656 126 640 126 624 c 0 126 602 109 591 90 590 c 0 EndSplineSet Fore SplineSet 78 578 m 0 62 575 52 562 52 546 c 0 52 517 72 499 99 486 c 0 107 482 116 479 116 472 c 0 116 467 109 462 96 462 c 0 43 462 0 506 0 559 c 0 0 606 26 656 73 656 c 0 97 656 120 641 120 618 c 0 120 595 101 582 78 578 c 0 EndSplineSet Validated: 1 Substitution2: "Smallcaps1 subtable" uni0314.grksc EndChar
{ "pile_set_name": "Github" }
errors = Module.constants.grep(/error|exception/i) RSpec.describe 'list_of_errors_and_exceptions' do %w( Lowercaseerror Lowercaseexception Errorerr Exceptionatstart ExceptionAtStart ExcEPtion Abcexceptiondef ).each do |error_to_find| # changed between 1.8 and 1.9 if Module.constants.first.kind_of? Symbol error_to_find = error_to_find.to_sym end Object.const_set error_to_find, Class.new(StandardError) example "finds the added #{error_to_find}" do expect(list_of_errors_and_exceptions).to include error_to_find end end end
{ "pile_set_name": "Github" }
// // $Id: KTextInputSlider.tjs,v 1.6 2007/09/17 12:09:52 m2 Exp $ // /**---------------------------------------------------------------------- * テキストインプットスライダー ----------------------------------------------------------------------*/ class KTextInputSlider extends KGridLayout { var _value; var textInput; var slider; // 辞書 var dict; /*------------------------------ * テキストインプットとスライダーを合成したウィジェットです。 * * @param win ウィンドウ * @param w 幅 * @param h 高さ * @param minValue 値の最小値 * @param maxValue 値の最大値 * @param name 名前 * @param step 刻み幅 ------------------------------*/ function KTextInputSlider(win, w, h, leftValue, rightValue, step = 1, name = "") { super.KGridLayout(win, name); add(0, 0, (textInput = new KTextInput(win, h * 2, h, step == int(step) ? TEXT_DIGIT : TEXT_REAL, "textInput"))); add(1, 0, (slider = new KSlider(win, w == 0 ? 0 : w, h, leftValue, rightValue, step, "slider"))); _value = leftValue; slider.value = leftValue; slider.focusable = false; textInput.value = string(leftValue); } /*------------------------------ * ファイナライザ ------------------------------*/ function finalize { if (dict) { dict.set(name, value); } super.finalize(...); } /*------------------------------ * 永続化辞書を値にバインドする ------------------------------*/ function bindPersistentDictionary(dict) { if (name !== void) { this.dict = dict; value = dict.init(name, value); } } /**------------------------------ * イベントを発生させ強制的に現在の値を通知する。 * * 現在の値で onValueModifiedを呼びます。 ------------------------------*/ function invalidateValue { if (nodeEnabled) onValueModified(value); } /**------------------------------ * 値を設定する * * @param v 値 * @return 値 ------------------------------*/ property value { getter { return _value; } setter(v) { v = Math.min(maxValue, Math.max(v, minValue)); if (step == int(step)) v = int(v); if (_value == v) return; _value = v; slider.value = v; textInput.value = string(v); } } /*------------------------------ * 子孫ウィジェットから特定の名前を持った子ウィジェットを捜す * * 子の「名前」を拾わないようにトラップ。 ------------------------------*/ function find(name) { if (this.name === name) return this; else return void; } function onChildValueModified(child, newValue) { var oldValue = _value; value = newValue; if (oldValue != value) onValueModified(value, oldValue); } /**------------------------------ * 値の変化量を設定する * * @param v 値 * @return 値 ------------------------------*/ property step { getter { return slider.step; } setter(v) { if(step != v) { var l = leftValue, r = rightValue; slider.step = v; leftValue = l; // step の変化に伴う、再設定 rightValue = r; invalidateSliderRange(); textInput.type = v == int(v) ? TEXT_DIGIT : TEXT_REAL; value = value; // 値の再設定 } } } /**------------------------------ * スライダーの最少最大範囲を再計算 ------------------------------*/ function invalidateSliderRange() { slider.minValue = int(Math.min(slider.leftValue, slider.rightValue)); slider.maxValue = int(Math.max(slider.leftValue, slider.rightValue)); } /**------------------------------ * 左値を設定する * * @param v 値 * @return 値 ------------------------------*/ property leftValue { getter { return slider.leftValue * step; } setter(v) { slider.leftValue = int(v / step); invalidateSliderRange(); value = value; // 値の再設定 } } /**------------------------------ * 右値を設定する * * @param v 値 * @return 値 ------------------------------*/ property rightValue { getter { return slider.rightValue * step; } setter(v) { slider.rightValue = int(v / step); invalidateSliderRange(); value = value; // 値の再設定 } } /**------------------------------ * 最小値を設定する * * @param v 値 * @return 値 ------------------------------*/ property minValue { getter { return slider.minValue * step; } setter(v) { if (slider.sign > 0) slider.leftValue = int(v / step); else slider.rightValue = int(v / step); invalidateSliderRange(); value = value; // 値の再設定 } } /**------------------------------ * 最大値を設定する * * @param v 値 * @return 値 ------------------------------*/ property maxValue { getter { return slider.maxValue * step; } setter(v) { if (slider.sign > 0) slider.rightValue = int(v / step); else slider.leftValue = int(v / step); invalidateSliderRange(); value = value; // 値の再設定 } } };
{ "pile_set_name": "Github" }
{ "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "+=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "-=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "*=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "/=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "%=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "<<=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": ">>=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": ">>>=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "&=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "^=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] } { "type": "Program", "body": [ { "type": "ExpressionStatement", "expression": { "type": "AssignmentExpression", "operator": "|=", "left": { "type": "Identifier", "name": "xyz" }, "right": { "type": "Literal", "value": 314 } } } ] }
{ "pile_set_name": "Github" }
use actix_web::{get, web, HttpRequest}; #[cfg(unix)] use actix_web::{middleware, App, Error, HttpResponse, HttpServer}; #[get("/resource1/{name}/index.html")] async fn index(req: HttpRequest, name: web::Path<String>) -> String { println!("REQ: {:?}", req); format!("Hello: {}!\r\n", name) } #[cfg(unix)] async fn index_async(req: HttpRequest) -> Result<&'static str, Error> { println!("REQ: {:?}", req); Ok("Hello world!\r\n") } #[get("/")] async fn no_params() -> &'static str { "Hello world!\r\n" } #[cfg(unix)] #[actix_web::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info"); env_logger::init(); HttpServer::new(|| { App::new() .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2")) .wrap(middleware::Compress::default()) .wrap(middleware::Logger::default()) .service(index) .service(no_params) .service( web::resource("/resource2/index.html") .wrap( middleware::DefaultHeaders::new().header("X-Version-R2", "0.3"), ) .default_service( web::route().to(|| HttpResponse::MethodNotAllowed()), ) .route(web::get().to(index_async)), ) .service(web::resource("/test1.html").to(|| async { "Test\r\n" })) }) .bind_uds("/Users/fafhrd91/uds-test")? .workers(1) .run() .await } #[cfg(not(unix))] fn main() {}
{ "pile_set_name": "Github" }
/* * Copyright (c) 1998, 2017, 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. */ package java.security.cert; /** * This class is an abstraction of certificate revocation lists (CRLs) that * have different formats but important common uses. For example, all CRLs * share the functionality of listing revoked certificates, and can be queried * on whether or not they list a given certificate. * <p> * Specialized CRL types can be defined by subclassing off of this abstract * class. * * @author Hemma Prafullchandra * * * @see X509CRL * @see CertificateFactory * * @since 1.2 */ public abstract class CRL { // the CRL type private String type; /** * Creates a CRL of the specified type. * * @param type the standard name of the CRL type. * See the <a href= * "{@docRoot}/../specs/security/standard-names.html"> * Java Security Standard Algorithm Names</a> document * for information about standard CRL types. */ protected CRL(String type) { this.type = type; } /** * Returns the type of this CRL. * * @return the type of this CRL. */ public final String getType() { return this.type; } /** * Returns a string representation of this CRL. * * @return a string representation of this CRL. */ public abstract String toString(); /** * Checks whether the given certificate is on this CRL. * * @param cert the certificate to check for. * @return true if the given certificate is on this CRL, * false otherwise. */ public abstract boolean isRevoked(Certificate cert); }
{ "pile_set_name": "Github" }
<?php /** * THttpRequest, THttpCookie, THttpCookieCollection, TUri class file * * @author Qiang Xue <[email protected]> * @link https://github.com/pradosoft/prado * @license https://github.com/pradosoft/prado/blob/master/LICENSE * @package Prado\Web */ namespace Prado\Web; use Prado\Exceptions\TInvalidDataTypeException; /** * THttpCookieCollection class. * * THttpCookieCollection implements a collection class to store cookies. * Besides using all functionalities from {@link TList}, you can also * retrieve a cookie by its name using either {@link findCookieByName} or * simply: * <code> * $cookie=$collection[$cookieName]; * </code> * * @author Qiang Xue <[email protected]> * @package Prado\Web * @since 3.0 */ class THttpCookieCollection extends \Prado\Collections\TList { /** * @var mixed owner of this collection */ private $_o; /** * Constructor. * @param mixed $owner owner of this collection. */ public function __construct($owner = null) { $this->_o = $owner; } /** * Inserts an item at the specified position. * This overrides the parent implementation by performing additional * operations for each newly added THttpCookie object. * @param int $index the specified position. * @param mixed $item new item * @throws TInvalidDataTypeException if the item to be inserted is not a THttpCookie object. */ public function insertAt($index, $item) { if ($item instanceof THttpCookie) { parent::insertAt($index, $item); if ($this->_o instanceof THttpResponse) { $this->_o->addCookie($item); } } else { throw new TInvalidDataTypeException('httpcookiecollection_httpcookie_required'); } } /** * Removes an item at the specified position. * This overrides the parent implementation by performing additional * cleanup work when removing a TCookie object. * @param int $index the index of the item to be removed. * @return mixed the removed item. */ public function removeAt($index) { $item = parent::removeAt($index); if ($this->_o instanceof THttpResponse) { $this->_o->removeCookie($item); } return $item; } /** * @param int|string $index index of the cookie in the collection or the cookie's name * @return THttpCookie the cookie found */ public function itemAt($index) { if (is_int($index)) { return parent::itemAt($index); } else { return $this->findCookieByName($index); } } /** * Finds the cookie with the specified name. * @param string $name the name of the cookie to be looked for * @return THttpCookie the cookie, null if not found */ public function findCookieByName($name) { foreach ($this as $cookie) { if ($cookie->getName() === $name) { return $cookie; } } return null; } }
{ "pile_set_name": "Github" }
Additional IP Rights Grant (Patents) "This implementation" means the copyrightable works distributed by Google as part of the Go project. Google hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer and otherwise run, modify and propagate the contents of this implementation of Go, where such license applies only to those patent claims, both currently owned or controlled by Google and acquired in the future, licensable by Google that are necessarily infringed by this implementation of Go. This grant does not include claims that would be infringed only as a consequence of further modification of this implementation. If you or your agent or exclusive licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that this implementation of Go or any code incorporated within this implementation of Go constitutes direct or contributory patent infringement, or inducement of patent infringement, then any patent rights granted to you under this License for this implementation of Go shall terminate as of the date such litigation is filed.
{ "pile_set_name": "Github" }
package com.googlecode.objectify.test.entity; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** */ @Data @NoArgsConstructor public class Name implements Serializable { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
{ "pile_set_name": "Github" }
import * as React from 'react'; import { CallState } from '../redux/callState'; const defaultCallState: CallState = { currentIssueId: '', contactIndexes: {}, completedIssueIds: [] }; export const callStateContext = React.createContext<CallState>( defaultCallState );
{ "pile_set_name": "Github" }
<?php /** * Trellis Desk * * @copyright Copyright (C) 2009-2012 ACCORD5. All rights reserved. * @license GNU General Public License version 3 or later; see LICENSE.txt */ class td_ad_maint { #======================================= # @ Auto Run # Function that is run automatically # when the file is required. #======================================= function auto_run() { if ( ! $this->trellis->user['acp']['tools_maint'] ) { $this->trellis->skin->error('no_perm'); } $this->trellis->skin->set_section( 'Tools &amp; Maintenance' ); $this->trellis->skin->set_description( 'Run reports &amp; statistics, maintenance utilities, recount functions, cleaning utilities, and backup functions.' ); switch( $this->trellis->input['code'] ) { case 'recount': $this->show_recount(); break; case 'rebuild': $this->show_rebuild(); break; case 'clean': $this->show_clean(); break; case 'syscheck': $this->syscheck(); break; case 'dorecount': $this->do_recount(); break; case 'doclean': $this->do_clean(); break; default: $this->show_recount(); break; } } #======================================= # @ Show Recount # Show the recount page. #======================================= function show_recount($alert='') { #============================= # Security Checks #============================= if ( ! $this->trellis->user['acp']['tools_maint_recount'] ) { $this->trellis->skin->error('no_perm'); } #============================= # Do Output #============================= if ( $alert ) { $alert = "<div class='alert'>{$alert}</div>"; } $this->output = "{$alert} <div class='groupbox'>Recount Functions</div> <div class='subbox'>Please select a task below.</div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rticket'>Ticket Statistics</a> <span class='desc'>-- Rebuild ticket statistics such as total tickets, etc.</span></div> <div class='option2'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rkb'>Knowledge Base Statistics</a> <span class='desc'>-- Rebuild knowledge base statistics such as article count, etc.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=ruser'>User Statistics</a> <span class='desc'>-- Rebuild user statistics such as total user count, etc.</span></div> <div class='option2'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rreplies'>Replies Per Ticket</a> <span class='desc'>-- The number of replies for each ticket.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rmemtick'>Tickets Per User</a> <span class='desc'>-- The number of tickets for each user.</span></div> <div class='option2'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rdeptick'>Tickets Per Department</a> <span class='desc'>-- The number of tickets for each department.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rtassign'>Assigned Tickets</a> <span class='desc'>-- The number of open tickets assigned to each staff user.</span></div> <div class='option2'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=racomments'>Article Comments</a> <span class='desc'>-- The number of comments for each article.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rncomments'>News Comments</a> <span class='desc'>-- The number of comments for each announcement.</span></div> <div class='option2'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rusers'>Users</a> <span class='desc'>-- The number of users for each group, etc.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rartrate'>Article Ratings</a> <span class='desc'>-- The rating value for each article.</span></div> <div class='option2'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=rsettings'>Settings</a> <span class='desc'>-- The number of settings per settings group.</span></div>"; $this->trellis->skin->add_output( $this->output ); $this->nav = array( "<a href='<! TD_URL !>/admin.php?section=tools'>Tools</a>", "<a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint'>Maintenance</a>", "Recount Functions", ); $this->trellis->skin->do_output( array( 'nav' => $this->nav, 'title' => 'Maintenance' ) ); } #======================================= # @ Show Rebuild # Show the rebuild page. #======================================= function show_rebuild($alert='') { #============================= # Security Checks #============================= if ( ! $this->trellis->user['acp']['tools_maint_recount'] ) { $this->trellis->skin->error('no_perm'); } #============================= # Do Output #============================= if ( $alert ) { $alert = "<div class='alert'>{$alert}</div>"; } $this->output = "{$alert} <div class='groupbox'>Rebuild Functions</div> <div class='subbox'>Please select a function below to rebuild.</div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cannounce'>Announcement Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=ccanned'>Canned Replies Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=ckbcat'>Category Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=ccdfields'>Custom Department Fields Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=ccpfields'>Custom Profile Fields Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cdepart'>Department Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cgroup'>Group Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=clang'>Language Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cconfig'>Settings Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cskin'>Skin Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cstaff'>Staff Cache</a></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cchmod'>CHMOD Cache Files</a> <span class='desc'>-- CHMOD all cache files to 0777.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=cloginkeys'>Login Keys</a> <span class='desc'>-- Regenerate login keys for all users.</span></div> <div class='option1'><a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint&amp;code=dorecount&amp;type=crsskeys'>RSS Keys</a> <span class='desc'>-- Regenerate RSS keys for all users.</span></div>"; $this->trellis->skin->add_output( $this->output ); $this->nav = array( "<a href='<! TD_URL !>/admin.php?section=tools'>Tools</a>", "<a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint'>Maintenance</a>", "Rebuild Functions", ); $this->trellis->skin->do_output( array( 'nav' => $this->nav, 'title' => 'Maintenance' ) ); } #======================================= # @ Show Clean # Show the Spring cleaning page. :D #======================================= function show_clean($alert='') { #============================= # Security Checks #============================= if ( ! $this->trellis->user['acp']['tools_maint_clean'] ) { $this->trellis->skin->error('no_perm'); } #============================= # Do Output #============================= if ( $alert ) { $alert = "<div class='alert'>{$alert}</div>"; } $this->output = "{$alert} <div class='groupbox'>Spring Cleaning</div> <div class='subbox'>Please select the checkbox next to each action you wish to perform. Then click Start Cleaning.</div> <form action='<! TD_URL !>/admin.php?section=tools&amp;act=clean&amp;code=doclean' method='post' onsubmit='return validate_form(this)'> <table width='100%' cellpadding='0' cellspacing='0'> <tr> <td class='option1' width='5%' align='center'><input type='checkbox' name='del_old_tickets' value='1' class='ckbox' /></td> <td class='option1' width='95%'>Delete all tickets older than <input type='text' name='dot_days' id='dot_days' value='{$this->trellis->input['dot_days']}' size='3' /> days.</td> </tr> <tr> <td class='option2' align='center'><input type='checkbox' name='del_old_comments' value='1' class='ckbox' /></td> <td class='option2' width='95%'>Delete all comments older than <input type='text' name='doc_days' id='doc_days' value='{$this->trellis->input['doc_days']}' size='3' /> days.</td> </tr> <tr> <td class='option1' align='center'><input type='checkbox' name='del_unapproved_mem' value='1' class='ckbox' /></td> <td class='option1'>Delete all validating users who have been registered for more than <input type='text' name='dum_days' id='dum_days' value='{$this->trellis->input['dum_days']}' size='3' /> days.</td> </tr> <tr> <td class='option2' align='center'><input type='checkbox' name='del_inactive_mem' value='1' class='ckbox' /></td> <td class='option2'>Delete all users who have been inactive for <input type='text' name='dim_days' id='dim_days' value='{$this->trellis->input['dim_days']}' size='3' /> days.</td> </tr> <tr> <td class='option1' align='center'><input type='checkbox' name='delete_core_logs' value='1' class='ckbox' /></td> <td class='option1'>Delete all A5 Core logs.</td> </tr> <tr> <td class='option2' align='center'><input type='checkbox' name='delete_tmp_files' value='1' class='ckbox' /></td> <td class='option2'>Delete all A5 Core temporary files.</td> </tr> <tr> <td class='option1' align='center'><input type='checkbox' name='del_logs_admin' value='1' class='ckbox' /></td> <td class='option1'>Delete admin logs older than <input type='text' name='dla_days' id='dla_days' value='{$this->trellis->input['dla_days']}' size='3' /> days.</td> </tr> <tr> <td class='option2' align='center'><input type='checkbox' name='del_logs_mem' value='1' class='ckbox' /></td> <td class='option2'>Delete user logs older than <input type='text' name='dlm_days' id='dlm_days' value='{$this->trellis->input['dlm_days']}' size='3' /> days.</td> </tr> <tr> <td class='option1' align='center'><input type='checkbox' name='del_logs_error' value='1' class='ckbox' /></td> <td class='option1'>Delete error logs older than <input type='text' name='dle_days' id='dle_days' value='{$this->trellis->input['dle_days']}' size='3' /> days.</td> </tr> <tr> <td class='option2' align='center'><input type='checkbox' name='del_logs_sec' value='1' class='ckbox' /></td> <td class='option2'>Delete security logs older than <input type='text' name='dls_days' id='dls_days' value='{$this->trellis->input['dls_days']}' size='3' /> days.</td> </tr> <tr> <td class='option1' align='center'><input type='checkbox' name='del_logs_tick' value='1' class='ckbox' /></td> <td class='option1'>Delete ticket logs older than <input type='text' name='dlt_days' id='dlt_days' value='{$this->trellis->input['dlt_days']}' size='3' /> days.</td> </tr> <tr> <td class='option2' align='center'><input type='checkbox' name='kill_asessions' value='1' class='ckbox' /></td> <td class='option2'>Kill all administrative sessions (you will be logged out).</td> </tr> <tr> <td class='option1' align='center'><input type='checkbox' name='kill_sessions' value='1' class='ckbox' /></td> <td class='option1'>Kill all user sessions.</td> </tr> </table> <div class='formtail'><input type='submit' name='submit' id='clean' value='Start Cleaning' class='button' /></div> </form>"; $this->trellis->skin->add_output( $this->output ); $this->nav = array( "<a href='<! TD_URL !>/admin.php?section=tools'>Tools</a>", "<a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint'>Maintenance</a>", "Spring Cleaning", ); $this->trellis->skin->do_output( array( 'nav' => $this->nav, 'title' => 'Maintenance' ) ); } #======================================= # @ Do Recount # Perform the appropriate task to # recount or rebuild. #======================================= function do_recount() { #============================= # Security Checks #============================= if ( ! $this->trellis->user['acp']['tools_maint_recount'] ) { $this->trellis->skin->error('no_perm'); } #============================= # Perform Our Action #============================= if ( substr( $this->trellis->input['type'], 0, 1 ) == 'c' ) { if ( $this->trellis->input['type'] == 'cannounce' ) { $this->trellis->rebuild_announce_cache(); $this->trellis->log( 'other', "Announcement Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'ccanned' ) { $this->trellis->rebuild_canned_cache(); $this->trellis->log( 'other', "Canned Replies Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'ckbcat' ) { $this->trellis->rebuild_cat_cache(); $this->trellis->log( 'other', "Category Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'cdepart' ) { $this->trellis->rebuild_dprt_cache(); $this->trellis->log( 'other', "Department Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'cgroup' ) { $this->trellis->rebuild_groups_cache(); $this->trellis->log( 'other', "Group Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'clang' ) { $this->trellis->rebuild_lang_cache(); $this->trellis->log( 'other', "Language Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'cskin' ) { $this->trellis->rebuild_skin_cache(); $this->trellis->log( 'other', "Skin Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'cstaff' ) { $this->trellis->rebuild_staff_cache(); $this->trellis->log( 'other', "Staff Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'cconfig' ) { $this->trellis->rebuild_set_cache(); $this->trellis->log( 'other', "Settings Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'ccdfields' ) { $this->trellis->rebuild_dfields_cache(); $this->trellis->log( 'other', "Custom Department Fields Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'ccpfields' ) { $this->trellis->rebuild_pfields_cache(); $this->trellis->log( 'other', "Custom Profile Fields Cache Rebuilt" ); } elseif ( $this->trellis->input['type'] == 'cchmod' ) { $this->trellis->core->chmod(); $this->trellis->log( 'other', "Cache Files CHMOD to 0777" ); } elseif ( $this->trellis->input['type'] == 'crsskeys' ) { $this->r_rss_keys(); } elseif ( $this->trellis->input['type'] == 'cloginkeys' ) { $this->r_login_keys(); } #$this->trellis->skin->redirect( '?section=tools&act=maint&code=rebuild', 'cache_rebuilt' ); $this->show_rebuild( 'The rebuild function has been successfully run.' ); } elseif ( substr( $this->trellis->input['type'], 0, 1 ) == 'r' ) { if ( $this->trellis->input['type'] == 'rticket' ) { $this->trellis->r_ticket_stats(); $this->trellis->log( 'other', "Rebuilt Ticket Statistics" ); } elseif ( $this->trellis->input['type'] == 'rkb' ) { $this->trellis->r_kb_stats(); $this->trellis->log( 'other', "Rebuilt KB Statistics" ); } elseif ( $this->trellis->input['type'] == 'ruser' ) { $this->trellis->r_user_stats(); $this->trellis->log( 'other', "Rebuilt User Statistics" ); } elseif ( $this->trellis->input['type'] == 'rreplies' ) { $this->r_replies_per_ticket(); } elseif ( $this->trellis->input['type'] == 'rreplies' ) { $this->r_replies_per_ticket(); } elseif ( $this->trellis->input['type'] == 'rmemtick' ) { $this->trellis->r_tickets_per_user(); } elseif ( $this->trellis->input['type'] == 'rdeptick' ) { $this->trellis->r_tickets_per_dept(); } elseif ( $this->trellis->input['type'] == 'racomments' ) { $this->r_acomments(); } elseif ( $this->trellis->input['type'] == 'rncomments' ) { $this->r_ncomments(); } elseif ( $this->trellis->input['type'] == 'rusers' ) { $this->r_users(); } elseif ( $this->trellis->input['type'] == 'rartrate' ) { $this->r_article_ratings(); } elseif ( $this->trellis->input['type'] == 'rsettings' ) { $this->r_settings(); } elseif ( $this->trellis->input['type'] == 'rtassign' ) { $this->r_tassigned(); } #$this->trellis->skin->redirect( '?section=tools&act=maint&code=recount', 'maint_recount' ); $this->show_rebuild( 'The recount function has been successfully run.' ); } } #======================================= # @ Recount: Replies Per Ticket # Recounts the number of replies per # ticket. #======================================= function r_replies_per_ticket() { #============================= # Grab Replies #============================= $this->trellis->db->construct( array( 'select' => array( 'id', 'tid' ), 'from' => 'replies', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $r = $this->trellis->db->fetch_row() ) { $replies[ $r['tid'] ] ++; } } #============================= # Grab Tickets #============================= $this->trellis->db->construct( array( 'select' => array( 'id' ), 'from' => 'tickets', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $t = $this->trellis->db->fetch_row() ) { $tickets[ $t['id'] ] = 1; } #============================= # Update Tickets #============================= while ( list( $tid, ) = each( $tickets ) ) { $this->trellis->db->construct( array( 'update' => 'tickets', 'set' => array( 'replies' => $replies[ $tid ] ), 'where' => array( 'id', '=', $tid ), ) ); $this->trellis->db->execute(); } } $this->trellis->log( 'other', "Recounted Replies Per Ticket" ); } #======================================= # @ Recount: Article Comments # Recounts the number of comments per # article. #======================================= function r_acomments() { #============================= # Grab Comments #============================= $this->trellis->db->construct( array( 'select' => array( 'id', 'aid' ), 'from' => 'comments', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $c = $this->trellis->db->fetch_row() ) { $comments[ $c['aid'] ] ++; } } #============================= # Grab Articles #============================= $this->trellis->db->construct( array( 'select' => array( 'id' ), 'from' => 'articles', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $a = $this->trellis->db->fetch_row() ) { $articles[ $a['id'] ] = 1; } #============================= # Update Articles #============================= while ( list( $aid, ) = each( $articles ) ) { $this->trellis->db->construct( array( 'update' => 'articles', 'set' => array( 'comments' => $comments[ $aid ] ), 'where' => array( 'id', '=', $aid ), ) ); $this->trellis->db->execute(); } } $this->trellis->log( 'other', "Recounted Article Comments" ); } #======================================= # @ Recount: News Comments # Recounts the number of comments per # announcement. #======================================= function r_ncomments() { #============================= # Grab Comments #============================= $this->trellis->db->construct( array( 'select' => array( 'id', 'nid' ), 'from' => 'news_comments', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $c = $this->trellis->db->fetch_row() ) { $comments[ $c['nid'] ] ++; } } #============================= # Grab Announcements #============================= $this->trellis->db->construct( array( 'select' => array( 'id' ), 'from' => 'announcements', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $a = $this->trellis->db->fetch_row() ) { $news[ $a['id'] ] = 1; } #============================= # Update Announcements #============================= while ( list( $nid, ) = each( $news ) ) { $this->trellis->db->construct( array( 'update' => 'announcements', 'set' => array( 'comments' => $comments[ $nid ] ), 'where' => array( 'id', '=', $nid ), ) ); $this->trellis->db->execute(); } } $this->trellis->log( 'other', "Recounted News Comments" ); } #======================================= # @ Recount: Users # Recounts the number of users per # group. #======================================= function r_users() { #============================= # Grab Users #============================= $this->trellis->db->construct( array( 'select' => array( 'id', 'ugroup' ), 'from' => 'users', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $m = $this->trellis->db->fetch_row() ) { $users[ $m['ugroup'] ] ++; } } #============================= # Grab Groups #============================= $this->trellis->db->construct( array( 'select' => array( 'g_id' ), 'from' => 'groups', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $g = $this->trellis->db->fetch_row() ) { $groups[ $g['g_id'] ] = 1; } } #============================= # Update Groups #============================= while ( list( $gid, ) = each( $groups ) ) { $this->trellis->db->construct( array( 'update' => 'groups', 'set' => array( 'g_users' => $users[ $gid ] ), 'where' => array( 'g_id', '=', $gid ), ) ); $this->trellis->db->execute(); } $this->trellis->log( 'other', "Recounted Users" ); } #======================================= # @ Recount: Settings # Recounts the number of settings per # settings group. #======================================= function r_settings() { #============================= # Grab Settings #============================= $this->trellis->db->construct( array( 'select' => array( 'cf_id', 'cf_group' ), 'from' => 'settings', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $s = $this->trellis->db->fetch_row() ) { $settings[ $s['cf_group'] ] ++; } } #============================= # Grab Settings Groups #============================= $this->trellis->db->construct( array( 'select' => array( 'cg_id' ), 'from' => 'settings_groups', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $g = $this->trellis->db->fetch_row() ) { $groups[ $g['cg_id'] ] = 1; } } #============================= # Update Settings Groups #============================= while ( list( $gid, ) = each( $groups ) ) { $this->trellis->db->construct( array( 'update' => 'settings_groups', 'set' => array( 'cg_set_count' => $settings[ $gid ] ), 'where' => array( 'cg_id', '=', $gid ), ) ); $this->trellis->db->execute(); } $this->trellis->log( 'other', "Recounted Settings" ); } #======================================= # @ Recount: Article Ratings # Recounts the article rating for each # article. #======================================= function r_article_ratings() { #============================= # Grab Ratings #============================= $this->trellis->db->construct( array( 'select' => array( 'id', 'aid', 'rating' ), 'from' => 'article_rate', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $r = $this->trellis->db->fetch_row() ) { $rates[ $r['aid'] ] += $r['rating']; $rate_count[ $r['aid'] ] ++; } #============================= # Calculate Ratings #============================= while ( list( $a_id, $t_rate ) = each( $rates ) ) { $ratings[ $a_id ] = round( ( $t_rate / $rate_count[ $a_id ] ), 2 ); } #============================= # Grab Articles #============================= $this->trellis->db->construct( array( 'select' => array( 'id' ), 'from' => 'articles', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $a = $this->trellis->db->fetch_row() ) { $articles[ $a['id'] ] = 1; } } #============================= # Update Articles #============================= while ( list( $aid, ) = each( $articles ) ) { $this->trellis->db->construct( array( 'update' => 'articles', 'set' => array( 'votes' => $rate_count[ $aid ], 'rating' => $ratings[ $aid ] ), 'where' => array( 'id', '=', $aid ), ) ); $this->trellis->db->execute(); } } $this->trellis->log( 'other', "Recounted Article Ratings" ); } #======================================= # @ Recount: RSS Keys # Regenerates new RSS keys for users. #======================================= function r_rss_keys() { #============================= # Grab Users #============================= $this->trellis->db->construct( array( 'select' => array( 'id' ), 'from' => 'users', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $m = $this->trellis->db->fetch_row() ) { $users[ $m['id'] ] = 1; } } #============================= # Generate Keys and Update #============================= while ( list( $uid, ) = each( $users ) ) { $rss_key = md5( 'rk' . uniqid( rand(), true ) . $uid ); $this->trellis->db->construct( array( 'update' => 'users', 'set' => array( 'rss_key' => $rss_key ), 'where' => array( 'id', '=', $uid ), ) ); $this->trellis->db->execute(); } $this->trellis->log( 'other', "RSS Keys Regenerated" ); } #======================================= # @ Rebuild: Login Keys # Regenerates new login keys for users. #======================================= function r_login_keys() { #============================= # Grab Users #============================= $this->trellis->db->construct( array( 'select' => array( 'id' ), 'from' => 'users', ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $m = $this->trellis->db->fetch_row() ) { $users[ $m['id'] ] = 1; } } #============================= # Generate Keys and Update #============================= while ( list( $uid, ) = each( $users ) ) { $login_key = str_replace( "=", "", base64_encode( strrev( crypt( md5( 'lk'. uniqid( rand(), true ) . $uid ) ) ) ) ); $this->trellis->db->construct( array( 'update' => 'users', 'set' => array( 'login_key' => $login_key ), 'where' => array( 'id', '=', $uid ), ) ); $this->trellis->db->execute(); } $this->trellis->log( 'other', "Login Keys Regenerated" ); } #======================================= # @ Recount: Assigned Tickets # Recounts the number of assigned # tickets per staff user. #======================================= function r_tassigned() { #============================= # Grab Tickets #============================= $this->trellis->db->construct( array( 'select' => array( 'id', 'auid' ), 'from' => 'tickets', 'where' => array( array( 'auid', '!=', 0 ), array( 'status', '!=', 6, 'and' ) ) ) ); $this->trellis->db->execute(); if ( $this->trellis->db->get_num_rows() ) { while( $t = $this->trellis->db->fetch_row() ) { $staff[ $t['auid'] ] ++; } } #============================= # Update Staff #============================= while ( list( $suid, ) = each( $staff ) ) { if ( $this->trellis->cache->data['staff'][ $suid ] ) { $this->trellis->db->construct( array( 'update' => 'users', 'set' => array( 'assigned' => $staff[ $suid ] ), 'where' => array( 'id', '=', $suid ), ) ); $this->trellis->db->execute(); } } $this->trellis->log( 'other', "Recounted Assigned Tickets" ); $this->trellis->rebuild_staff_cache(); } #======================================= # @ System Check # Perform a self system check. #======================================= function syscheck() { #============================= # Security Checks #============================= if ( ! $this->trellis->user['acp']['tools_maint_syscheck'] ) { $this->trellis->skin->error('no_perm'); } $this->output = "<div class='groupbox'>System Check</div> <table width='100%' cellpadding='0' cellspacing='0'> <tr> <th width='50%' align='left'>Table</th> <th width='12%'>Found</th> <th width='38%'>Rows</th> </tr>"; #============================= # Check Database #============================= $datab_c = array( 'announcements', 'articles', 'article_rate', 'asessions', 'attachments', 'canned', 'categories', 'comments', 'departments', 'depart_fields', 'groups', 'languages', 'logs', 'users', 'news_comments', 'pages', 'profile_fields', 'replies', 'reply_rate', 'sessions', 'settings', 'settings_groups', 'skins', 'tickets', 'tokens', 'upg_history', 'validation', ); $sql = $this->trellis->db->get_tables(); $num_rows = $this->trellis->db->get_num_rows( $sql ); $row_count = 0; // Initialize for Security for ( $i = 0; $i < $num_rows; $i++ ) { $tables[] = mysql_tablename( $sql, $i ); } while ( list( , $ck_table ) = each( $datab_c ) ) { $row_count ++; ( $row_count & 1 ) ? $row_class = 'option1-med' : $row_class = 'option2-med'; if ( ! in_array( $this->trellis->db->db_prefix . $ck_table, $tables ) ) { $this->output .= "<tr> <td class='{$row_class}'><font color='#FF0000'>". $ck_table ."</font></td> <td class='{$row_class}' align='center'><font color='#FF0000'>Not Found</font></td> <td class='{$row_class}' align='center'><font color='#FF0000'>X</font></td> </tr>"; } else { $this->trellis->db->construct( array( 'select' => 'all', 'from' => $ck_table, ) ); $this->trellis->db->execute(); $temp_rows = $this->trellis->db->get_num_rows(); $this->output .= "<tr> <td class='{$row_class}'><font color='#007900'>". $ck_table ."</font></td> <td class='{$row_class}' align='center'><font color='#007900'>Found</font></td> <td class='{$row_class}' align='center'><font color='#007900'>". $temp_rows ."</font></td> </tr>"; } } $this->output .= "</table>"; $this->trellis->skin->add_output( $this->output ); $this->nav = array( "<a href='<! TD_URL !>/admin.php?section=tools'>Tools</a>", "<a href='<! TD_URL !>/admin.php?section=tools&amp;act=maint'>Maintenance</a>", "System Check", ); $this->trellis->skin->do_output( array( 'nav' => $this->nav, 'title' => 'Maintenance' ) ); } #======================================= # @ Do Clean # Perform a Spring cleaning. #======================================= function do_clean() { #============================= # Security Checks #============================= if ( ! $this->trellis->user['acp']['tools_maint_clean'] ) { $this->trellis->skin->error('no_perm'); } #============================= # Do Some Cleanin' #============================= if ( $this->trellis->input['del_old_tickets'] && $this->trellis->input['dot_days'] ) { $this->trellis->db->construct( array( 'delete' => 'tickets', 'where' => array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dot_days'] ) ) ), ) ); $this->trellis->db->execute(); $rticket = 1; $rmemtick = 1; $rdeptick = 1; } if ( $this->trellis->input['del_old_comments'] && $this->trellis->input['doc_days'] ) { $this->trellis->db->construct( array( 'delete' => 'comments', 'where' => array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['doc_days'] ) ) ), ) ); $this->trellis->db->execute(); $rcomments = 1; } if ( $this->trellis->input['del_unapproved_mem'] && $this->trellis->input['dum_days'] ) { $this->trellis->db->construct( array( 'delete' => 'users', 'where' => array( array( 'ugroup', '=', 3, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dum_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); $ruser = 1; $rusers = 1; } if ( $this->trellis->input['del_inactive_mem'] && $this->trellis->input['dim_days'] ) { $this->trellis->db->construct( array( 'delete' => 'users', 'where' => array( array( 'ugroup', '!=', 4, ), array( 'last_activity', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dim_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); $ruser = 1; $rusers = 1; } if ( $this->trellis->input['delete_core_logs'] ) { if ( $handle = opendir( TD_PATH .'core/logs' ) ) { while ( ( $file = readdir($handle) ) !== false ) { if ( $file != "." && $file != ".." && $file != "index.html" ) { if ( ! is_dir( TD_PATH .'core/logs/' . $file ) ) { @unlink( TD_PATH .'core/logs/' . $file ); } } } closedir($handle); } } if ( $this->trellis->input['delete_tmp_files'] ) { if ( $handle = opendir( TD_PATH .'core/tmp' ) ) { while ( ( $file = readdir($handle) ) !== false ) { if ( $file != "." && $file != ".." && $file != "index.html" ) { if ( ! is_dir( TD_PATH .'core/tmp/' . $file ) ) { @unlink( TD_PATH .'core/tmp/' . $file ); } } } closedir($handle); } } if ( $this->trellis->input['del_logs_admin'] && $this->trellis->input['dla_days'] ) { $this->trellis->db->construct( array( 'delete' => 'logs', 'where' => array( array( 'type', '=', 2, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dla_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } if ( $this->trellis->input['del_logs_mem'] && $this->trellis->input['dlm_days'] ) { $this->trellis->db->construct( array( 'delete' => 'logs', 'where' => array( array( 'type', '=', 6, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dlm_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } if ( $this->trellis->input['del_logs_error'] && $this->trellis->input['dle_days'] ) { $this->trellis->db->construct( array( 'delete' => 'logs', 'where' => array( array( 'type', '=', 3, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dle_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } if ( $this->trellis->input['del_logs_sec'] && $this->trellis->input['dls_days'] ) { $this->trellis->db->construct( array( 'delete' => 'logs', 'where' => array( array( 'type', '=', 4, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dls_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } if ( $this->trellis->input['del_logs_tick'] && $this->trellis->input['dlt_days'] ) { $this->trellis->db->construct( array( 'delete' => 'logs', 'where' => array( array( 'type', '=', 7, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dlt_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } if ( $this->trellis->input['kill_asessions'] ) { $this->trellis->db->construct( array( 'delete' => 'asessions', #'where' => array( array( 'type', '=', 2, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dla_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } if ( $this->trellis->input['kill_sessions'] ) { $this->trellis->db->construct( array( 'delete' => 'sessions', #'where' => array( array( 'type', '=', 2, ), array( 'date', '<', ( time() - ( 60 * 60 * 24 * $this->trellis->input['dla_days'] ) ), 'and' ) ), ) ); $this->trellis->db->execute(); } #============================= # Do We Need To Rebuild? #============================= if ( $rticket ) { $this->trellis->r_ticket_stats(); } if ( $rmemtick ) { $this->r_tickets_per_user(); } if ( $rdeptick ) { $this->r_tickets_per_dept(); } if ( $rcomments ) { $this->r_comments(); } if ( $ruser ) { $this->trellis->r_user_stats(); } if ( $rusers ) { $this->r_users(); } #============================= # Redirect #============================= $this->trellis->log( 'other', "Spring Cleaning Ran", 2 ); #$this->trellis->skin->redirect( '?section=tools&act=maint&code=clean', 'spring_clean_success' ); $this->show_rebuild( 'Spring cleaning has been successfully run.' ); } } ?>
{ "pile_set_name": "Github" }
# Copyright (c) 2017, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # # All rights reserved. # # The Astrobee platform is licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # This message allows the MOBILITY::MAPPER zones to be retrieved --- time timestamp # When these zones were updated ff_msgs/Zone[] zones # A vector of zones
{ "pile_set_name": "Github" }
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600); @import url(http://fonts.googleapis.com/css?family=Source+Code+Pro:500,700); /* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */ article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; } audio, canvas, video { display: inline-block; } audio:not([controls]) { display: none; height: 0; } [hidden], template { display: none; } script { display: none !important; } html { background: #fff; color: #000; font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } body { margin: 0; } a { background: transparent; } a:focus { outline: thin dotted; } a:active, a:hover { outline: 0; } h1 { font-size: 2em; margin: 0.67em 0; } abbr[title] { border-bottom: 1px dotted; } b, strong { font-weight: bold; } dfn { font-style: italic; } hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0; } mark { background: #ff0; color: #000; } code, kbd, pre, samp { font-family: 'Source Code Pro', monospace, serif; font-size: 1em; } pre { white-space: pre-wrap; } q { quotes: "\201C" "\201D" "\2018" "\2019"; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } img { border: 0; } svg:not(:root) { overflow: hidden; } figure { margin: 0; } fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } legend { border: 0; padding: 0; } button, input, select, textarea { font-family: inherit; font-size: 100%; margin: 0; } button, input { line-height: normal; } button, select { text-transform: none; } button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button[disabled], html input[disabled] { cursor: default; } input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; } input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; } input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } textarea { overflow: auto; vertical-align: top; } table { border-collapse: collapse; border-spacing: 0; } *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } html, body { font-size: 100%; } body { background: white; color: #222222; padding: 0; margin: 0; font-family: "Noto Serif", "DejaVu Serif", "Serif", serif; font-weight: normal; font-style: normal; line-height: 1; position: relative; cursor: auto; } a:hover { cursor: pointer; } a:focus { outline: none; } img, object, embed { max-width: 100%; height: auto; } object, embed { height: 100%; } img { -ms-interpolation-mode: bicubic; } #map_canvas img, #map_canvas embed, #map_canvas object, .map_canvas img, .map_canvas embed, .map_canvas object { max-width: none !important; } .left { float: left !important; } .right { float: right !important; } .text-left { text-align: left !important; } .text-right { text-align: right !important; } .text-center { text-align: center !important; } .text-justify { text-align: justify !important; } .hide { display: none; } .antialiased, body { -webkit-font-smoothing: antialiased; } img { display: inline-block; vertical-align: middle; } textarea { height: auto; min-height: 50px; } select { width: 100%; } p.lead, .paragraph.lead > p, #preamble > .sectionbody > .paragraph:first-of-type p { font-size: 1.21875em; line-height: 1.6; } .subheader, #content #toctitle, .admonitionblock td.content > .title, .exampleblock > .title, .imageblock > .title, .listingblock > .title, .literalblock > .title, .mathblock > .title, .openblock > .title, .paragraph > .title, .quoteblock > .title, .tableblock > .title, .verseblock > .title, .videoblock > .title, .dlist > .title, .olist > .title, .ulist > .title, .qlist > .title, .hdlist > .title, .tableblock > caption { line-height: 1.4; color: #7a2518; font-weight: 300; margin-top: 0.2em; margin-bottom: 0.5em; } div, dl, dt, dd, ul, ol, li, h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6, pre, form, p, blockquote, th, td { margin: 0; padding: 0; direction: ltr; } a { color: #005498; text-decoration: underline; line-height: inherit; } a:hover, a:focus { color: #00467f; } a img { border: none; } p { font-family: inherit; font-weight: normal; font-size: 1em; line-height: 1.6; margin-bottom: 1.25em; text-rendering: optimizeLegibility; } p aside { font-size: 0.875em; line-height: 1.35; font-style: italic; } h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6 { font-family: "Open Sans", "DejaVu Sans", "Sans", sans-serif; font-weight: 300; font-style: normal; color: #222; text-rendering: optimizeLegibility; margin-top: 1em; margin-bottom: 0.5em; line-height: 1.2125em; } h1 small, h2 small, h3 small, #toctitle small, .sidebarblock > .content > .title small, h4 small, h5 small, h6 small { font-size: 60%; color: #e99b8f; line-height: 0; } h1 { font-size: 2.125em; font-weight: bold; } h2 { font-size: 1.6875em; font-weight: bold; } h3, #toctitle, .sidebarblock > .content > .title { font-size: 1.375em; font-weight: bold; } h4 { font-size: 1.125em; font-weight: bold; } h5 { font-size: 1.125em; font-weight: bold; } h6 { font-size: 1em; } hr { border: solid #d8d8d8; border-width: 1px 0 0; clear: both; margin: 1.25em 0 1.1875em; height: 0; } em, i { font-style: italic; line-height: inherit; } strong, b { font-weight: bold; line-height: inherit; } small { font-size: 60%; line-height: inherit; } code { font-family: "Source Code Pro", "Droid Sans Mono", "DejaVu Sans Mono", "Monospace", monospace; font-weight: normal; color: #6d180b; font-size: 85%; } ul, ol, dl { font-size: 1em; line-height: 1.6; margin-bottom: 1.25em; list-style-position: outside; font-family: inherit; } ul, ol { margin-left: 1.5em; } ul.no-bullet, ol.no-bullet { margin-left: 1.5em; } ul li ul, ul li ol { margin-left: 1.25em; margin-bottom: 0; font-size: 1em; } ul.square li ul, ul.circle li ul, ul.disc li ul { list-style: inherit; } ul.square { list-style-type: square; } ul.circle { list-style-type: circle; } ul.disc { list-style-type: disc; } ul.no-bullet { list-style: none; } ol li ul, ol li ol { margin-left: 1.25em; margin-bottom: 0; } dl dt { margin-bottom: 0.3125em; font-weight: bold; } dl dd { margin-bottom: 1.25em; } abbr, acronym { text-transform: uppercase; font-size: 90%; color: #333333; border-bottom: 1px dotted #dddddd; cursor: help; } abbr { text-transform: none; } blockquote { margin: 0 0 1.25em; padding: 0.5625em 1.25em 0 1.1875em; border-left: 3px solid #487c58; } blockquote cite { display: block; font-size: inherit; color: #454545; } blockquote cite:before { content: "\2014 \0020"; } blockquote cite a, blockquote cite a:visited { color: #454545; } blockquote, blockquote p { line-height: 1.6; color: #6e6e6e; } @media only screen and (min-width: 768px) { h1, h2, h3, #toctitle, .sidebarblock > .content > .title, h4, h5, h6 { line-height: 1.4; } h1 { font-size: 2.75em; font-weight: bold; } h2 { font-size: 2.3125em; font-weight: bold; } h3, #toctitle, .sidebarblock > .content > .title { font-size: 1.6875em; font-weight: bold; } h4 { font-size: 1.4375em; font-weight: bold; } h5 { font-size: 1.3em; font-weight: bold; } } .print-only { display: none !important; } @media print { * { background: transparent !important; color: #000 !important; box-shadow: none !important; text-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 0.5cm; } p, h2, h3, #toctitle, .sidebarblock > .content > .title { orphans: 3; widows: 3; } h2, h3, #toctitle, .sidebarblock > .content > .title { page-break-after: avoid; } .hide-on-print { display: none !important; } .print-only { display: block !important; } .hide-for-print { display: none !important; } .show-for-print { display: inherit !important; } } table { background: white; margin-bottom: 1.25em; border: solid 1px #dddddd; } table thead, table tfoot { background: whitesmoke; font-weight: bold; } table thead tr th, table thead tr td, table tfoot tr th, table tfoot tr td { padding: 0.5em 0.625em 0.625em; font-size: inherit; color: #333333; text-align: left; } table tr th, table tr td { padding: 0.5625em 0.625em; font-size: inherit; color: #333333; } table tr.even, table tr.alt, table tr:nth-of-type(even) { background: #f9f9f9; } table thead tr th, table tfoot tr th, table tbody tr td, table tr td, table tfoot tr td { display: table-cell; line-height: 1.6; } .clearfix:before, .clearfix:after, .float-group:before, .float-group:after { content: " "; display: table; } .clearfix:after, .float-group:after { clear: both; } *:not(pre) > code { font-size: inherit; padding: 0; white-space: nowrap; background-color: inherit; border: 0 solid #dddddd; -webkit-border-radius: 4px; border-radius: 4px; text-shadow: none; line-height: 1; } pre, pre > code { line-height: 1.4; color: #191919; font-family: "Source Code Pro", "Droid Sans Mono", "DejaVu Sans Mono", "Monospace", monospace; font-weight: normal; } .keyseq { color: #666666; } kbd:not(.keyseq) { display: inline-block; color: #333333; font-size: 0.75em; line-height: 1.4; background-color: #f7f7f7; border: 1px solid #ccc; -webkit-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 0 2px white inset; box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 0 2px white inset; margin: -0.15em 0.15em 0 0.15em; padding: 0.2em 0.6em 0.2em 0.5em; vertical-align: middle; white-space: nowrap; } .keyseq kbd:first-child { margin-left: 0; } .keyseq kbd:last-child { margin-right: 0; } .menuseq, .menu { color: #1a1a1a; } b.button:before, b.button:after { position: relative; top: -1px; font-weight: normal; } b.button:before { content: "["; padding: 0 3px 0 2px; } b.button:after { content: "]"; padding: 0 2px 0 3px; } p a > code:hover { color: #561309; } #header, #content, #footnotes, #footer { width: 100%; margin-left: auto; margin-right: auto; margin-top: 0; margin-bottom: 0; max-width: 62.5em; *zoom: 1; position: relative; padding-left: 0.9375em; padding-right: 0.9375em; } #header:before, #header:after, #content:before, #content:after, #footnotes:before, #footnotes:after, #footer:before, #footer:after { content: " "; display: table; } #header:after, #content:after, #footnotes:after, #footer:after { clear: both; } #header { margin-bottom: 2.5em; } #header > h1 { color: black; font-weight: 300; border-bottom: 1px solid #d8d8d8; margin-bottom: -28px; padding-bottom: 32px; } #header span { color: #6e6e6e; } #header #revnumber { text-transform: capitalize; } #header br { display: none; } #header br + span { padding-left: 3px; } #header br + span:before { content: "\2013 \0020"; } #header br + span.author { padding-left: 0; } #header br + span.author:before { content: ", "; } #toc { border-bottom: 3px double #e5e5e5; padding-bottom: 1.25em; } #toc > ul { margin-left: 0.25em; } #toc ul.sectlevel0 > li > a { font-style: italic; } #toc ul.sectlevel0 ul.sectlevel1 { margin-left: 0; margin-top: 0.5em; margin-bottom: 0.5em; } #toc ul { font-family: "Open Sans", "DejaVu Sans", "Sans", sans-serif; list-style-type: none; } #toc a { text-decoration: none; } #toc a:active { text-decoration: underline; } #toctitle { color: #7a2518; } @media only screen and (min-width: 768px) { body.toc2 { padding-left: 15em; padding-right: 0; } #toc.toc2 { position: fixed; width: 15em; left: 0; top: 0; border-right: 1px solid #e5e5e5; border-bottom: 0; z-index: 1000; padding: 1.25em 1em; height: 100%; overflow: auto; } #toc.toc2 #toctitle { margin-top: 0; font-size: 1.2em; } #toc.toc2 > ul { font-size: .90em; margin-bottom: 0; } #toc.toc2 ul ul { margin-left: 0; padding-left: 1em; } #toc.toc2 ul.sectlevel0 ul.sectlevel1 { padding-left: 0; margin-top: 0.5em; margin-bottom: 0.5em; } body.toc2.toc-right { padding-left: 0; padding-right: 15em; } body.toc2.toc-right #toc.toc2 { border-right: 0; border-left: 1px solid #e5e5e5; left: auto; right: 0; } } @media only screen and (min-width: 1280px) { body.toc2 { padding-left: 20em; padding-right: 0; } #toc.toc2 { width: 20em; } #toc.toc2 #toctitle { font-size: 1.375em; } #toc.toc2 > ul { font-size: 0.95em; } #toc.toc2 ul ul { padding-left: 1.25em; } body.toc2.toc-right { padding-left: 0; padding-right: 20em; } } #toc.toc2 { background-color: #fafaf9; } #content #toc { border-style: solid; border-width: 1px; border-color: #e3e3dd; margin-bottom: 1.25em; padding: 1.25em; background: #fafaf9; border-width: 0; -webkit-border-radius: 4px; border-radius: 4px; } #content #toc > :first-child { margin-top: 0; } #content #toc > :last-child { margin-bottom: 0; } #content #toc a { text-decoration: none; } #content #toctitle { font-weight: bold; font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif; font-size: 1.375em; padding-left: 0.125em; } #footer { max-width: 100%; background-color: #333333; padding: 1.25em; } #footer-text { color: #cccccc; line-height: 1.44; } .sect1 { padding-bottom: 1.25em; } .sect1 + .sect1 { border-top: 3px double #e5e5e5; } #content h1 > a.anchor, h2 > a.anchor, h3 > a.anchor, #toctitle > a.anchor, .sidebarblock > .content > .title > a.anchor, h4 > a.anchor, h5 > a.anchor, h6 > a.anchor { position: absolute; width: 1em; margin-left: -1em; display: block; text-decoration: none; visibility: hidden; text-align: center; font-weight: normal; } #content h1 > a.anchor:before, h2 > a.anchor:before, h3 > a.anchor:before, #toctitle > a.anchor:before, .sidebarblock > .content > .title > a.anchor:before, h4 > a.anchor:before, h5 > a.anchor:before, h6 > a.anchor:before { content: '\00A7'; font-size: .85em; vertical-align: text-top; display: block; margin-top: 0.05em; } #content h1:hover > a.anchor, #content h1 > a.anchor:hover, h2:hover > a.anchor, h2 > a.anchor:hover, h3:hover > a.anchor, #toctitle:hover > a.anchor, .sidebarblock > .content > .title:hover > a.anchor, h3 > a.anchor:hover, #toctitle > a.anchor:hover, .sidebarblock > .content > .title > a.anchor:hover, h4:hover > a.anchor, h4 > a.anchor:hover, h5:hover > a.anchor, h5 > a.anchor:hover, h6:hover > a.anchor, h6 > a.anchor:hover { visibility: visible; } #content h1 > a.link, h2 > a.link, h3 > a.link, #toctitle > a.link, .sidebarblock > .content > .title > a.link, h4 > a.link, h5 > a.link, h6 > a.link { color: #ba3925; text-decoration: none; } #content h1 > a.link:hover, h2 > a.link:hover, h3 > a.link:hover, #toctitle > a.link:hover, .sidebarblock > .content > .title > a.link:hover, h4 > a.link:hover, h5 > a.link:hover, h6 > a.link:hover { color: #a53221; } .imageblock, .literalblock, .listingblock, .mathblock, .verseblock, .videoblock { margin-bottom: 1.25em; } .admonitionblock td.content > .title, .exampleblock > .title, .imageblock > .title, .listingblock > .title, .literalblock > .title, .mathblock > .title, .openblock > .title, .paragraph > .title, .quoteblock > .title, .tableblock > .title, .verseblock > .title, .videoblock > .title, .dlist > .title, .olist > .title, .ulist > .title, .qlist > .title, .hdlist > .title { text-align: left; font-family: "Noto Serif", "DejaVu Serif", "Serif", serif; font-weight: normal; font-style: italic; } .tableblock > caption { text-align: left; font-family: "Noto Serif", "DejaVu Serif", "Serif", serif; font-weight: normal; font-style: italic; white-space: nowrap; overflow: visible; max-width: 0; } table.tableblock #preamble > .sectionbody > .paragraph:first-of-type p { font-size: inherit; } .admonitionblock > table { border: 0; background: none; width: 100%; } .admonitionblock > table td.icon { text-align: center; width: 80px; } .admonitionblock > table td.icon img { max-width: none; } .admonitionblock > table td.icon .title { font-weight: 300; text-transform: uppercase; } .admonitionblock > table td.content { padding-left: 1.125em; padding-right: 1.25em; border-left: 1px solid #d8d8d8; color: #6e6e6e; } .admonitionblock > table td.content > :last-child > :last-child { margin-bottom: 0; } .exampleblock > .content { border-style: solid; border-width: 1px; border-color: #e6e6e6; margin-bottom: 1.25em; padding: 1.25em; background: white; -webkit-border-radius: 4px; border-radius: 4px; } .exampleblock > .content > :first-child { margin-top: 0; } .exampleblock > .content > :last-child { margin-bottom: 0; } .exampleblock > .content h1, .exampleblock > .content h2, .exampleblock > .content h3, .exampleblock > .content #toctitle, .sidebarblock.exampleblock > .content > .title, .exampleblock > .content h4, .exampleblock > .content h5, .exampleblock > .content h6, .exampleblock > .content p { color: #333333; } .exampleblock > .content h1, .exampleblock > .content h2, .exampleblock > .content h3, .exampleblock > .content #toctitle, .sidebarblock.exampleblock > .content > .title, .exampleblock > .content h4, .exampleblock > .content h5, .exampleblock > .content h6 { line-height: 1; margin-bottom: 0.625em; } .exampleblock > .content h1.subheader, .exampleblock > .content h2.subheader, .exampleblock > .content h3.subheader, .exampleblock > .content .subheader#toctitle, .sidebarblock.exampleblock > .content > .subheader.title, .exampleblock > .content h4.subheader, .exampleblock > .content h5.subheader, .exampleblock > .content h6.subheader { line-height: 1.4; } .exampleblock.result > .content { -webkit-box-shadow: 0 1px 8px #e3e3dd; box-shadow: 0 1px 8px #e3e3dd; } .sidebarblock { border-style: solid; border-width: 1px; border-color: #e3e3dd; margin-bottom: 1.25em; padding: 1.25em; background: #fafaf9; -webkit-border-radius: 4px; border-radius: 4px; } .sidebarblock > :first-child { margin-top: 0; } .sidebarblock > :last-child { margin-bottom: 0; } .sidebarblock h1, .sidebarblock h2, .sidebarblock h3, .sidebarblock #toctitle, .sidebarblock > .content > .title, .sidebarblock h4, .sidebarblock h5, .sidebarblock h6, .sidebarblock p { color: #333333; } .sidebarblock h1, .sidebarblock h2, .sidebarblock h3, .sidebarblock #toctitle, .sidebarblock > .content > .title, .sidebarblock h4, .sidebarblock h5, .sidebarblock h6 { line-height: 1; margin-bottom: 0.625em; } .sidebarblock h1.subheader, .sidebarblock h2.subheader, .sidebarblock h3.subheader, .sidebarblock .subheader#toctitle, .sidebarblock > .content > .subheader.title, .sidebarblock h4.subheader, .sidebarblock h5.subheader, .sidebarblock h6.subheader { line-height: 1.4; } .sidebarblock > .content > .title { color: #7a2518; margin-top: 0; line-height: 1.6; } .exampleblock > .content > :last-child > :last-child, .exampleblock > .content .olist > ol > li:last-child > :last-child, .exampleblock > .content .ulist > ul > li:last-child > :last-child, .exampleblock > .content .qlist > ol > li:last-child > :last-child, .sidebarblock > .content > :last-child > :last-child, .sidebarblock > .content .olist > ol > li:last-child > :last-child, .sidebarblock > .content .ulist > ul > li:last-child > :last-child, .sidebarblock > .content .qlist > ol > li:last-child > :last-child { margin-bottom: 0; } .literalblock pre:not([class]), .listingblock pre:not([class]) { background: none; } .literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { border-width: 1px 0; border-style: dotted; border-color: #bfbfbf; -webkit-border-radius: 4px; border-radius: 4px; padding: 0.75em 0.5em; word-wrap: break-word; } .literalblock pre.nowrap, .literalblock pre[class].nowrap, .listingblock pre.nowrap, .listingblock pre[class].nowrap { overflow-x: auto; white-space: pre; word-wrap: normal; } .literalblock pre > code, .literalblock pre[class] > code, .listingblock pre > code, .listingblock pre[class] > code { display: block; } @media only screen { .literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { font-size: 0.8em; } } @media only screen and (min-width: 768px) { .literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { font-size: 0.9em; } } @media only screen and (min-width: 1280px) { .literalblock pre, .literalblock pre[class], .listingblock pre, .listingblock pre[class] { font-size: 1em; } } .listingblock pre.highlight { padding: 0; } .listingblock pre.highlight > code { padding: 0.75em 0.5em; } .listingblock > .content { position: relative; } .listingblock:hover code[class*=" language-"]:before { text-transform: uppercase; font-size: 0.9em; color: #999; position: absolute; top: 0.375em; right: 0.375em; } .listingblock:hover code.asciidoc:before { content: "asciidoc"; } .listingblock:hover code.clojure:before { content: "clojure"; } .listingblock:hover code.css:before { content: "css"; } .listingblock:hover code.go:before { content: "go"; } .listingblock:hover code.groovy:before { content: "groovy"; } .listingblock:hover code.html:before { content: "html"; } .listingblock:hover code.java:before { content: "java"; } .listingblock:hover code.javascript:before { content: "javascript"; } .listingblock:hover code.python:before { content: "python"; } .listingblock:hover code.ruby:before { content: "ruby"; } .listingblock:hover code.sass:before { content: "sass"; } .listingblock:hover code.scss:before { content: "scss"; } .listingblock:hover code.xml:before { content: "xml"; } .listingblock:hover code.yaml:before { content: "yaml"; } .listingblock.terminal pre .command:before { content: attr(data-prompt); padding-right: 0.5em; color: #999; } .listingblock.terminal pre .command:not([data-prompt]):before { content: '$'; } table.pyhltable { border: 0; margin-bottom: 0; } table.pyhltable td { vertical-align: top; padding-top: 0; padding-bottom: 0; } table.pyhltable td.code { padding-left: .75em; padding-right: 0; } .highlight.pygments .lineno, table.pyhltable td:not(.code) { color: #999; padding-left: 0; padding-right: .5em; border-right: 1px solid #d8d8d8; } .highlight.pygments .lineno { display: inline-block; margin-right: .25em; } table.pyhltable .linenodiv { background-color: transparent !important; padding-right: 0 !important; } .quoteblock { margin: 0 0 1.25em 0; padding: 0.5625em 1.25em 0 1.1875em; border-left: 3px solid #487c58; } .quoteblock blockquote { margin: 0 0 1.25em 0; padding: 0 0 0.625em 0; border: 0; } .quoteblock blockquote > .paragraph:last-child p { margin-bottom: 0; } .quoteblock .attribution { margin-top: -0.625em; padding-bottom: 0.625em; font-size: inherit; color: #454545; line-height: 1.6; } .quoteblock .attribution br { display: none; } .quoteblock .attribution cite { display: block; margin-bottom: 0.625em; } table thead th, table tfoot th { font-weight: bold; } table.tableblock.grid-all { border-collapse: separate; border-spacing: 1px; -webkit-border-radius: 4px; border-radius: 4px; border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; } table.tableblock.frame-topbot, table.tableblock.frame-none { border-left: 0; border-right: 0; } table.tableblock.frame-sides, table.tableblock.frame-none { border-top: 0; border-bottom: 0; } table.tableblock td .paragraph:last-child p > p:last-child, table.tableblock th > p:last-child, table.tableblock td > p:last-child { margin-bottom: 0; } th.tableblock.halign-left, td.tableblock.halign-left { text-align: left; } th.tableblock.halign-right, td.tableblock.halign-right { text-align: right; } th.tableblock.halign-center, td.tableblock.halign-center { text-align: center; } th.tableblock.valign-top, td.tableblock.valign-top { vertical-align: top; } th.tableblock.valign-bottom, td.tableblock.valign-bottom { vertical-align: bottom; } th.tableblock.valign-middle, td.tableblock.valign-middle { vertical-align: middle; } tbody tr th { display: table-cell; line-height: 1.6; background: whitesmoke; } tbody tr th, tbody tr th p, tfoot tr th, tfoot tr th p { color: #333333; font-weight: bold; } td > div.verse { white-space: pre; } ol { margin-left: 1.75em; } ul li ol { margin-left: 1.5em; } dl dd { margin-left: 1.125em; } dl dd:last-child, dl dd:last-child > :last-child { margin-bottom: 0; } ol > li p, ul > li p, ul dd, ol dd, .olist .olist, .ulist .ulist, .ulist .olist, .olist .ulist { margin-bottom: 0.625em; } ul.unstyled, ol.unnumbered, ul.checklist, ul.none { list-style-type: none; } ul.unstyled, ol.unnumbered, ul.checklist { margin-left: 0.625em; } ul.checklist li > p:first-child > .fa-check-square-o:first-child, ul.checklist li > p:first-child > input[type="checkbox"]:first-child { margin-right: 0.25em; } ul.checklist li > p:first-child > input[type="checkbox"]:first-child { position: relative; top: 1px; } ul.inline { margin: 0 auto 0.625em auto; margin-left: -1.375em; margin-right: 0; padding: 0; list-style: none; overflow: hidden; } ul.inline > li { list-style: none; float: left; margin-left: 1.375em; display: block; } ul.inline > li > * { display: block; } .unstyled dl dt { font-weight: normal; font-style: normal; } ol.arabic { list-style-type: decimal; } ol.decimal { list-style-type: decimal-leading-zero; } ol.loweralpha { list-style-type: lower-alpha; } ol.upperalpha { list-style-type: upper-alpha; } ol.lowerroman { list-style-type: lower-roman; } ol.upperroman { list-style-type: upper-roman; } ol.lowergreek { list-style-type: lower-greek; } .hdlist > table, .colist > table { border: 0; background: none; } .hdlist > table > tbody > tr, .colist > table > tbody > tr { background: none; } td.hdlist1 { padding-right: .75em; font-weight: bold; } td.hdlist1, td.hdlist2 { vertical-align: top; } .literalblock + .colist, .listingblock + .colist { margin-top: -0.5em; } .colist > table tr > td:first-of-type { padding: 0 .75em; line-height: 1; } .colist > table tr > td:last-of-type { padding: 0.25em 0; } .qanda > ol > li > p > em:only-child { color: #1d4b8f; } .thumb, .th { line-height: 0; display: inline-block; border: solid 4px white; -webkit-box-shadow: 0 0 0 1px #dddddd; box-shadow: 0 0 0 1px #dddddd; } .imageblock.left, .imageblock[style*="float: left"] { margin: 0.25em 0.625em 1.25em 0; } .imageblock.right, .imageblock[style*="float: right"] { margin: 0.25em 0 1.25em 0.625em; } .imageblock > .title { margin-bottom: 0; } .imageblock.thumb, .imageblock.th { border-width: 6px; } .imageblock.thumb > .title, .imageblock.th > .title { padding: 0 0.125em; } .image.left, .image.right { margin-top: 0.25em; margin-bottom: 0.25em; display: inline-block; line-height: 0; } .image.left { margin-right: 0.625em; } .image.right { margin-left: 0.625em; } a.image { text-decoration: none; } span.footnote, span.footnoteref { vertical-align: super; font-size: 0.875em; } span.footnote a, span.footnoteref a { text-decoration: none; } span.footnote a:active, span.footnoteref a:active { text-decoration: underline; } #footnotes { padding-top: 0.75em; padding-bottom: 0.75em; margin-bottom: 0.625em; } #footnotes hr { width: 20%; min-width: 6.25em; margin: -.25em 0 .75em 0; border-width: 1px 0 0 0; } #footnotes .footnote { padding: 0 0.375em; line-height: 1.3; font-size: 0.875em; margin-left: 1.2em; text-indent: -1.2em; margin-bottom: .2em; } #footnotes .footnote a:first-of-type { font-weight: bold; text-decoration: none; } #footnotes .footnote:last-of-type { margin-bottom: 0; } #content #footnotes { margin-top: -0.625em; margin-bottom: 0; padding: 0.75em 0; } .gist .file-data > table { border: none; background: #fff; width: 100%; margin-bottom: 0; } .gist .file-data > table td.line-data { width: 99%; } div.unbreakable { page-break-inside: avoid; } .big { font-size: larger; } .small { font-size: smaller; } .underline { text-decoration: underline; } .overline { text-decoration: overline; } .line-through { text-decoration: line-through; } .aqua { color: #00bfbf; } .aqua-background { background-color: #00fafa; } .black { color: black; } .black-background { background-color: black; } .blue { color: #0000bf; } .blue-background { background-color: #0000fa; } .fuchsia { color: #bf00bf; } .fuchsia-background { background-color: #fa00fa; } .gray { color: #606060; } .gray-background { background-color: #7d7d7d; } .green { color: #006000; } .green-background { background-color: #007d00; } .lime { color: #00bf00; } .lime-background { background-color: #00fa00; } .maroon { color: #600000; } .maroon-background { background-color: #7d0000; } .navy { color: #000060; } .navy-background { background-color: #00007d; } .olive { color: #606000; } .olive-background { background-color: #7d7d00; } .purple { color: #600060; } .purple-background { background-color: #7d007d; } .red { color: #bf0000; } .red-background { background-color: #fa0000; } .silver { color: #909090; } .silver-background { background-color: #bcbcbc; } .teal { color: #006060; } .teal-background { background-color: #007d7d; } .white { color: #bfbfbf; } .white-background { background-color: #fafafa; } .yellow { color: #bfbf00; } .yellow-background { background-color: #fafa00; } span.icon > .fa { cursor: default; } .admonitionblock td.icon [class^="fa icon-"] { font-size: 2.5em; text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); cursor: default; } .admonitionblock td.icon .icon-note:before { content: "\f05a"; color: #4298b8; } .admonitionblock td.icon .icon-tip:before { content: "\f0eb"; text-shadow: 1px 1px 2px rgba(155, 155, 0, 0.8); color: #ffe400; } .admonitionblock td.icon .icon-warning:before { content: "\f071"; color: #ff8c00; } .admonitionblock td.icon .icon-caution:before { content: "\f06d"; color: #db4800; } .admonitionblock td.icon .icon-important:before { content: "\f06a"; color: #db4800; } /* .conum[data-value] { display: inline-block; color: white !important; background-color: #333333; -webkit-border-radius: 100px; border-radius: 100px; text-align: center; width: 20px; height: 20px; font-size: 12px; line-height: 20px; font-family: "Open Sans", "Sans", sans-serif; font-style: normal; font-weight: bold; text-indent: -1px; } .conum[data-value] * { color: white !important; } .conum[data-value] + b { display: none; } .conum[data-value]:after { content: attr(data-value); } pre .conum[data-value] { position: relative; top: -2px; } b.conum * { color: inherit !important; } .conum:not([data-value]):empty { display: none; } */ .conum { display: inline-block; color: white !important; background-color: #222222; -webkit-border-radius: 100px; border-radius: 100px; text-align: center; width: 20px; height: 20px; font-size: 12px; font-weight: bold; line-height: 20px; font-family: "Open Sans", "Sans", sans-serif; font-style: normal; font-weight: bold; position: relative; top: -2px; letter-spacing: -1px; } .conum * { color: white !important; } .conum + b { display: none; } .conum:after { content: attr(data-value); } .conum:not([data-value]):empty { display: none; } #toc.toc2 { background: #ededed; } .literalblock > .content > pre, .listingblock > .content > pre { -webkit-border-radius: 0; border-radius: 0; }
{ "pile_set_name": "Github" }
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/datastructures/image/layerutil.h> namespace inviwo {} // namespace inviwo
{ "pile_set_name": "Github" }
""" Array methods which are called by both the C-code for the method and the Python code for the NumPy-namespace function """ from __future__ import division, absolute_import, print_function import warnings from numpy.core import multiarray as mu from numpy.core import umath as um from numpy.core.numeric import asanyarray from numpy.core import numerictypes as nt # save those O(100) nanoseconds! umr_maximum = um.maximum.reduce umr_minimum = um.minimum.reduce umr_sum = um.add.reduce umr_prod = um.multiply.reduce umr_any = um.logical_or.reduce umr_all = um.logical_and.reduce # avoid keyword arguments to speed up parsing, saves about 15%-20% for very # small reductions def _amax(a, axis=None, out=None, keepdims=False): return umr_maximum(a, axis, None, out, keepdims) def _amin(a, axis=None, out=None, keepdims=False): return umr_minimum(a, axis, None, out, keepdims) def _sum(a, axis=None, dtype=None, out=None, keepdims=False): return umr_sum(a, axis, dtype, out, keepdims) def _prod(a, axis=None, dtype=None, out=None, keepdims=False): return umr_prod(a, axis, dtype, out, keepdims) def _any(a, axis=None, dtype=None, out=None, keepdims=False): return umr_any(a, axis, dtype, out, keepdims) def _all(a, axis=None, dtype=None, out=None, keepdims=False): return umr_all(a, axis, dtype, out, keepdims) def _count_reduce_items(arr, axis): if axis is None: axis = tuple(range(arr.ndim)) if not isinstance(axis, tuple): axis = (axis,) items = 1 for ax in axis: items *= arr.shape[ax] return items def _mean(a, axis=None, dtype=None, out=None, keepdims=False): arr = asanyarray(a) is_float16_result = False rcount = _count_reduce_items(arr, axis) # Make this warning show up first if rcount == 0: warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2) # Cast bool, unsigned int, and int to float64 by default if dtype is None: if issubclass(arr.dtype.type, (nt.integer, nt.bool_)): dtype = mu.dtype('f8') elif issubclass(arr.dtype.type, nt.float16): dtype = mu.dtype('f4') is_float16_result = True ret = umr_sum(arr, axis, dtype, out, keepdims) if isinstance(ret, mu.ndarray): ret = um.true_divide( ret, rcount, out=ret, casting='unsafe', subok=False) if is_float16_result and out is None: ret = arr.dtype.type(ret) elif hasattr(ret, 'dtype'): if is_float16_result: ret = arr.dtype.type(ret / rcount) else: ret = ret.dtype.type(ret / rcount) else: ret = ret / rcount return ret def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): arr = asanyarray(a) rcount = _count_reduce_items(arr, axis) # Make this warning show up on top. if ddof >= rcount: warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2) # Cast bool, unsigned int, and int to float64 by default if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)): dtype = mu.dtype('f8') # Compute the mean. # Note that if dtype is not of inexact type then arraymean will # not be either. arrmean = umr_sum(arr, axis, dtype, keepdims=True) if isinstance(arrmean, mu.ndarray): arrmean = um.true_divide( arrmean, rcount, out=arrmean, casting='unsafe', subok=False) else: arrmean = arrmean.dtype.type(arrmean / rcount) # Compute sum of squared deviations from mean # Note that x may not be inexact and that we need it to be an array, # not a scalar. x = asanyarray(arr - arrmean) if issubclass(arr.dtype.type, nt.complexfloating): x = um.multiply(x, um.conjugate(x), out=x).real else: x = um.multiply(x, x, out=x) ret = umr_sum(x, axis, dtype, out, keepdims) # Compute degrees of freedom and make sure it is not negative. rcount = max([rcount - ddof, 0]) # divide by degrees of freedom if isinstance(ret, mu.ndarray): ret = um.true_divide( ret, rcount, out=ret, casting='unsafe', subok=False) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(ret / rcount) else: ret = ret / rcount return ret def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret
{ "pile_set_name": "Github" }
# # EDAC Kconfig # Copyright (c) 2008 Doug Thompson www.softwarebitmaker.com # Licensed and distributed under the GPL # menuconfig EDAC bool "EDAC (Error Detection And Correction) reporting" depends on HAS_IOMEM depends on X86 || PPC || TILE help EDAC is designed to report errors in the core system. These are low-level errors that are reported in the CPU or supporting chipset or other subsystems: memory errors, cache errors, PCI errors, thermal throttling, etc.. If unsure, select 'Y'. If this code is reporting problems on your system, please see the EDAC project web pages for more information at: <http://bluesmoke.sourceforge.net/> and: <http://buttersideup.com/edacwiki> There is also a mailing list for the EDAC project, which can be found via the sourceforge page. if EDAC comment "Reporting subsystems" config EDAC_DEBUG bool "Debugging" help This turns on debugging information for the entire EDAC sub-system. You can insert module with "debug_level=x", current there're four debug levels (x=0,1,2,3 from low to high). Usually you should select 'N'. config EDAC_DECODE_MCE tristate "Decode MCEs in human-readable form (only on AMD for now)" depends on CPU_SUP_AMD && X86_MCE default y ---help--- Enable this option if you want to decode Machine Check Exceptions occurring on your machine in human-readable form. You should definitely say Y here in case you want to decode MCEs which occur really early upon boot, before the module infrastructure has been initialized. config EDAC_MCE_INJ tristate "Simple MCE injection interface over /sysfs" depends on EDAC_DECODE_MCE default n help This is a simple interface to inject MCEs over /sysfs and test the MCE decoding code in EDAC. This is currently AMD-only. config EDAC_MM_EDAC tristate "Main Memory EDAC (Error Detection And Correction) reporting" help Some systems are able to detect and correct errors in main memory. EDAC can report statistics on memory error detection and correction (EDAC - or commonly referred to ECC errors). EDAC will also try to decode where these errors occurred so that a particular failing memory module can be replaced. If unsure, select 'Y'. config EDAC_MCE bool config EDAC_AMD64 tristate "AMD64 (Opteron, Athlon64) K8, F10h" depends on EDAC_MM_EDAC && AMD_NB && X86_64 && EDAC_DECODE_MCE help Support for error detection and correction of DRAM ECC errors on the AMD64 families of memory controllers (K8 and F10h) config EDAC_AMD64_ERROR_INJECTION bool "Sysfs HW Error injection facilities" depends on EDAC_AMD64 help Recent Opterons (Family 10h and later) provide for Memory Error Injection into the ECC detection circuits. The amd64_edac module allows the operator/user to inject Uncorrectable and Correctable errors into DRAM. When enabled, in each of the respective memory controller directories (/sys/devices/system/edac/mc/mcX), there are 3 input files: - inject_section (0..3, 16-byte section of 64-byte cacheline), - inject_word (0..8, 16-bit word of 16-byte section), - inject_ecc_vector (hex ecc vector: select bits of inject word) In addition, there are two control files, inject_read and inject_write, which trigger the DRAM ECC Read and Write respectively. config EDAC_AMD76X tristate "AMD 76x (760, 762, 768)" depends on EDAC_MM_EDAC && PCI && X86_32 help Support for error detection and correction on the AMD 76x series of chipsets used with the Athlon processor. config EDAC_E7XXX tristate "Intel e7xxx (e7205, e7500, e7501, e7505)" depends on EDAC_MM_EDAC && PCI && X86_32 help Support for error detection and correction on the Intel E7205, E7500, E7501 and E7505 server chipsets. config EDAC_E752X tristate "Intel e752x (e7520, e7525, e7320) and 3100" depends on EDAC_MM_EDAC && PCI && X86 && HOTPLUG help Support for error detection and correction on the Intel E7520, E7525, E7320 server chipsets. config EDAC_I82443BXGX tristate "Intel 82443BX/GX (440BX/GX)" depends on EDAC_MM_EDAC && PCI && X86_32 depends on BROKEN help Support for error detection and correction on the Intel 82443BX/GX memory controllers (440BX/GX chipsets). config EDAC_I82875P tristate "Intel 82875p (D82875P, E7210)" depends on EDAC_MM_EDAC && PCI && X86_32 help Support for error detection and correction on the Intel DP82785P and E7210 server chipsets. config EDAC_I82975X tristate "Intel 82975x (D82975x)" depends on EDAC_MM_EDAC && PCI && X86 help Support for error detection and correction on the Intel DP82975x server chipsets. config EDAC_I3000 tristate "Intel 3000/3010" depends on EDAC_MM_EDAC && PCI && X86 help Support for error detection and correction on the Intel 3000 and 3010 server chipsets. config EDAC_I3200 tristate "Intel 3200" depends on EDAC_MM_EDAC && PCI && X86 && EXPERIMENTAL help Support for error detection and correction on the Intel 3200 and 3210 server chipsets. config EDAC_X38 tristate "Intel X38" depends on EDAC_MM_EDAC && PCI && X86 help Support for error detection and correction on the Intel X38 server chipsets. config EDAC_I5400 tristate "Intel 5400 (Seaburg) chipsets" depends on EDAC_MM_EDAC && PCI && X86 help Support for error detection and correction the Intel i5400 MCH chipset (Seaburg). config EDAC_I7CORE tristate "Intel i7 Core (Nehalem) processors" depends on EDAC_MM_EDAC && PCI && X86 select EDAC_MCE help Support for error detection and correction the Intel i7 Core (Nehalem) Integrated Memory Controller that exists on newer processors like i7 Core, i7 Core Extreme, Xeon 35xx and Xeon 55xx processors. config EDAC_I82860 tristate "Intel 82860" depends on EDAC_MM_EDAC && PCI && X86_32 help Support for error detection and correction on the Intel 82860 chipset. config EDAC_R82600 tristate "Radisys 82600 embedded chipset" depends on EDAC_MM_EDAC && PCI && X86_32 help Support for error detection and correction on the Radisys 82600 embedded chipset. config EDAC_I5000 tristate "Intel Greencreek/Blackford chipset" depends on EDAC_MM_EDAC && X86 && PCI help Support for error detection and correction the Intel Greekcreek/Blackford chipsets. config EDAC_I5100 tristate "Intel San Clemente MCH" depends on EDAC_MM_EDAC && X86 && PCI help Support for error detection and correction the Intel San Clemente MCH. config EDAC_I7300 tristate "Intel Clarksboro MCH" depends on EDAC_MM_EDAC && X86 && PCI help Support for error detection and correction the Intel Clarksboro MCH (Intel 7300 chipset). config EDAC_MPC85XX tristate "Freescale MPC83xx / MPC85xx" depends on EDAC_MM_EDAC && FSL_SOC && (PPC_83xx || PPC_85xx) help Support for error detection and correction on the Freescale MPC8349, MPC8560, MPC8540, MPC8548 config EDAC_MV64X60 tristate "Marvell MV64x60" depends on EDAC_MM_EDAC && MV64X60 help Support for error detection and correction on the Marvell MV64360 and MV64460 chipsets. config EDAC_PASEMI tristate "PA Semi PWRficient" depends on EDAC_MM_EDAC && PCI depends on PPC_PASEMI help Support for error detection and correction on PA Semi PWRficient. config EDAC_CELL tristate "Cell Broadband Engine memory controller" depends on EDAC_MM_EDAC && PPC_CELL_COMMON help Support for error detection and correction on the Cell Broadband Engine internal memory controller on platform without a hypervisor config EDAC_PPC4XX tristate "PPC4xx IBM DDR2 Memory Controller" depends on EDAC_MM_EDAC && 4xx help This enables support for EDAC on the ECC memory used with the IBM DDR2 memory controller found in various PowerPC 4xx embedded processors such as the 405EX[r], 440SP, 440SPe, 460EX, 460GT and 460SX. config EDAC_AMD8131 tristate "AMD8131 HyperTransport PCI-X Tunnel" depends on EDAC_MM_EDAC && PCI && PPC_MAPLE help Support for error detection and correction on the AMD8131 HyperTransport PCI-X Tunnel chip. Note, add more Kconfig dependency if it's adopted on some machine other than Maple. config EDAC_AMD8111 tristate "AMD8111 HyperTransport I/O Hub" depends on EDAC_MM_EDAC && PCI && PPC_MAPLE help Support for error detection and correction on the AMD8111 HyperTransport I/O Hub chip. Note, add more Kconfig dependency if it's adopted on some machine other than Maple. config EDAC_CPC925 tristate "IBM CPC925 Memory Controller (PPC970FX)" depends on EDAC_MM_EDAC && PPC64 help Support for error detection and correction on the IBM CPC925 Bridge and Memory Controller, which is a companion chip to the PowerPC 970 family of processors. config EDAC_TILE tristate "Tilera Memory Controller" depends on EDAC_MM_EDAC && TILE default y help Support for error detection and correction on the Tilera memory controller. endif # EDAC
{ "pile_set_name": "Github" }
#include "region.h" inline static int sgn(int const val) { return (0 < val) - (val < 0); } GstImxRegionContains gst_imx_region_contains(GstImxRegion const *first_region, GstImxRegion const *second_region) { g_assert(first_region != NULL); g_assert(second_region != NULL); /* The -1 subtraction is necessary since the (x2,y2) * coordinates are right outside of the region */ int sx1 = first_region->x1; int sx2 = first_region->x2 - 1; int sy1 = first_region->y1; int sy2 = first_region->y2 - 1; int dx1 = second_region->x1; int dx2 = second_region->x2 - 1; int dy1 = second_region->y1; int dy2 = second_region->y2 - 1; int xt1 = sgn(dx2 - sx1); int xt2 = sgn(dx1 - sx2); int yt1 = sgn(dy2 - sy1); int yt2 = sgn(dy1 - sy2); if ((xt1 != xt2) && (yt1 != yt2)) { /* In case there is an overlap, check if second_region (dx/dy) * contains first_region (sx/sy) partially or fully */ return ((sx1 >= dx1) && (sy1 >= dy1) && (sx2 <= dx2) && (sy2 <= dy2)) ? GST_IMX_REGION_CONTAINS_FULL : GST_IMX_REGION_CONTAINS_PARTIAL; } else return GST_IMX_REGION_CONTAINS_NONE; } gboolean gst_imx_region_equal(GstImxRegion const *first_region, GstImxRegion const *second_region) { g_assert(first_region != NULL); g_assert(second_region != NULL); return (first_region->x1 == second_region->x1) && (first_region->y1 == second_region->y1) && (first_region->x2 == second_region->x2) && (first_region->y2 == second_region->y2); } void gst_imx_region_intersect(GstImxRegion *intersection, GstImxRegion const *first_region, GstImxRegion const *second_region) { g_assert(intersection != NULL); g_assert(first_region != NULL); g_assert(second_region != NULL); intersection->x1 = MAX(first_region->x1, second_region->x1); intersection->y1 = MAX(first_region->y1, second_region->y1); intersection->x2 = MIN(first_region->x2, second_region->x2); intersection->y2 = MIN(first_region->y2, second_region->y2); } void gst_imx_region_merge(GstImxRegion *merged_region, GstImxRegion const *first_region, GstImxRegion const *second_region) { g_assert(merged_region != NULL); g_assert(first_region != NULL); g_assert(second_region != NULL); merged_region->x1 = MIN(first_region->x1, second_region->x1); merged_region->y1 = MIN(first_region->y1, second_region->y1); merged_region->x2 = MAX(first_region->x2, second_region->x2); merged_region->y2 = MAX(first_region->y2, second_region->y2); } void gst_imx_region_calculate_inner_region(GstImxRegion *inner_region, GstImxRegion const *outer_region, GstVideoInfo const *info, gboolean transposed, gboolean keep_aspect_ratio) { guint display_ratio_n, display_ratio_d; guint video_width, video_height; g_assert(inner_region != NULL); g_assert(outer_region != NULL); g_assert(info != NULL); /* Calculate aspect ratio factors if required */ if (keep_aspect_ratio) { guint video_par_n, video_par_d, window_par_n, window_par_d; video_width = GST_VIDEO_INFO_WIDTH(info); video_height = GST_VIDEO_INFO_HEIGHT(info); video_par_n = GST_VIDEO_INFO_PAR_N(info); video_par_d = GST_VIDEO_INFO_PAR_D(info); window_par_n = 1; window_par_d = 1; if ((video_width == 0) || (video_height == 0)) { /* Turn off aspect ratio calculation if either width * or height is 0 */ keep_aspect_ratio = FALSE; } else { if (!gst_video_calculate_display_ratio( &display_ratio_n, &display_ratio_d, video_width, video_height, video_par_n, video_par_d, window_par_n, window_par_d )) { keep_aspect_ratio = FALSE; } else if (transposed) { guint d = display_ratio_d; display_ratio_d = display_ratio_n; display_ratio_n = d; } } } /* Calculate the inner region, either with or without * aspect ratio correction (in the latter case, the inner * and outer regions are identical) */ if (keep_aspect_ratio) { guint ratio_factor; guint outw, outh, innerw, innerh; /* Fit the inner region in the outer one, keeping display ratio * This means that either its width or its height will be set to the * outer region's width/height, and the other length will be shorter, * scaled accordingly to retain the display ratio * * Setting dn = display_ratio_n , dd = display_ratio_d , * outw = outer_region_width , outh = outer_region_height , * we can identify cases: * * (1) Inner region fits in outer one with its width maximized * In this case, this holds: outw/outh < dn/dd * (1) Inner region fits in outer one with its height maximized * In this case, this holds: outw/outh > dn/dd * * To simplify comparison, the inequality outw/outh > dn/dd is * transformed to: outw*dd/outh > dn * outw*dd/outh is the ratio_factor */ outw = outer_region->x2 - outer_region->x1; outh = outer_region->y2 - outer_region->y1; ratio_factor = (guint)gst_util_uint64_scale_int(outw, display_ratio_d, outh); if (ratio_factor >= display_ratio_n) { innerw = (guint)gst_util_uint64_scale_int(outh, display_ratio_n, display_ratio_d); innerh = outh; } else { innerw = outw; innerh = (guint)gst_util_uint64_scale_int(outw, display_ratio_d, display_ratio_n); } /* Safeguard to ensure width/height aren't out of bounds * (should not happen, but better safe than sorry) */ innerw = MIN(innerw, outw); innerh = MIN(innerh, outh); inner_region->x1 = outer_region->x1 + (outw - innerw) / 2; inner_region->y1 = outer_region->y1 + (outh - innerh) / 2; inner_region->x2 = inner_region->x1 + innerw; inner_region->y2 = inner_region->y1 + innerh; } else { *inner_region = *outer_region; } }
{ "pile_set_name": "Github" }
#region Copyright (C) 2005-2011 Team MediaPortal // Copyright (C) 2005-2011 Team MediaPortal // http://www.team-mediaportal.com // // MediaPortal 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. // // MediaPortal 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 MediaPortal. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Generic; using System.IO; using System.Management; using System.Security.Cryptography; using System.Text; using System.Threading; using DirectShowLib; using DirectShowLib.BDA; using Microsoft.Win32; using TvDatabase; using TvLibrary.Implementations.Analog; using TvLibrary.Implementations.Dri; using TvLibrary.Implementations.DVB; using TvLibrary.Implementations.Pbda; using TvLibrary.Implementations.RadioWebStream; using TvLibrary.Interfaces; using TvLibrary.Interfaces.Analyzer; using UPnP.Infrastructure; using UPnP.Infrastructure.CP; using UPnP.Infrastructure.CP.Description; using UPnP.Infrastructure.CP.DeviceTree; using UPnP.Infrastructure.CP.SSDP; namespace TvLibrary.Implementations { /// <summary> /// This class continually monitors device events. /// </summary> public class DeviceDetector : IDisposable { // Used for detecting and communicating with UPnP devices. private CPData _upnpControlPointData = null; private UPnPNetworkTracker _upnpAgent = null; private UPnPControlPoint _upnpControlPoint = null; private HashSet<string> _knownUpnpDevices = new HashSet<string>(); // Used for detecting and communicating with devices that are directly // connected to the system. private ManagementEventWatcher _systemDeviceChangeEventWatcher = null; private DateTime _previousSystemDeviceChange = DateTime.MinValue; private object _lockObject = new object(); private HashSet<string> _knownBdaWdmDevices = new HashSet<string>(); private RadioWebStreamCard _rwsTuner = new RadioWebStreamCard(); // Always one RWS "tuner". // The listener that we notify when device events occur. private IDeviceEventListener _deviceEventListener = null; // network providers private IBaseFilter _atscNp = null; private IBaseFilter _dvbcNp = null; private IBaseFilter _dvbsNp = null; private IBaseFilter _dvbtNp = null; private IBaseFilter _mpNp = null; private IFilterGraph2 _graphBuilder = null; private DsROTEntry _rotEntry = null; /// <summary> /// Constructor. /// </summary> /// <param name="listener">A listener that wishes to be notified about device events.</param> public DeviceDetector(IDeviceEventListener listener) { _deviceEventListener = listener; // Setup UPnP device detection. UPnPConfiguration.LOGGER = new Tve3Logger(); _upnpControlPointData = new CPData(); _upnpAgent = new UPnPNetworkTracker(_upnpControlPointData); _upnpAgent.RootDeviceAdded += OnUpnpRootDeviceAdded; _upnpAgent.RootDeviceRemoved += OnUpnpRootDeviceRemoved; _upnpControlPoint = new UPnPControlPoint(_upnpAgent); // Setup other (BDA, PBDA, WDM) device detection. try { InitBdaDetectionGraph(); } catch (Exception ex) { Log.Log.Error("Failed to initialise the BDA device detection graph!\r\n{0}", ex); throw; } _systemDeviceChangeEventWatcher = new ManagementEventWatcher(); // EventType 2 and 3 are device arrival and removal. See: // http://msdn.microsoft.com/en-us/library/windows/desktop/aa394124%28v=vs.85%29.aspx _systemDeviceChangeEventWatcher.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 OR EventType = 3"); _systemDeviceChangeEventWatcher.EventArrived += OnSystemDeviceConnectedOrDisconnected; } public void Start() { Log.Log.Info("Starting async device detection..."); // Start detecting BDA and WDM devices. _deviceEventListener.OnDeviceAdded(_rwsTuner); DetectBdaWdmDevices(); _systemDeviceChangeEventWatcher.Start(); // Start detecting UPnP devices. // IMPORTANT: this parameter must be set to allow devices with many sub-devices // and/or services to be detected. The timer interval specifies how long the // SSDP controller has from first detection of the root device SSDP packet // until descriptions for all devices and services have been requested, received // and processed. DRI tuners normally take about 5 seconds. SSDPClientController.EXPIRATION_TIMER_INTERVAL = 60000; // IMPORTANT: you should start the control point before the network tracker. _upnpControlPoint.Start(); _upnpAgent.Start(); _upnpAgent.SharedControlPointData.SSDPController.SearchDeviceByDeviceTypeVersion("schemas-opencable-com:service:Tuner", "1", null); } public void Reset() { Stop(); _knownUpnpDevices.Clear(); _knownBdaWdmDevices.Clear(); Start(); } public void Stop() { Log.Log.Info("Stopping async device detection..."); _upnpAgent.Close(); _upnpControlPoint.Close(); _systemDeviceChangeEventWatcher.Stop(); } #region IDisposable member /// <summary> /// Clean up, dispose, release. /// </summary> public void Dispose() { Stop(); if (_rwsTuner != null) { _rwsTuner.Dispose(); _rwsTuner = null; } if (_rotEntry != null) { _rotEntry.Dispose(); } if (_graphBuilder != null) { FilterGraphTools.RemoveAllFilters(_graphBuilder); Release.ComObject("device detection graph builder", _graphBuilder); } Release.ComObject("device detection ATSC network provider", _atscNp); Release.ComObject("device detection DVB-C network provider", _dvbcNp); Release.ComObject("device detection DVB-S network provider", _dvbsNp); Release.ComObject("device detection DVB-T network provider", _dvbtNp); Release.ComObject("device detection MediaPortal network provider", _mpNp); } #endregion #region BDA/WDM device detection private static bool ConnectFilter(IFilterGraph2 graphBuilder, IBaseFilter networkFilter, IBaseFilter tunerFilter) { IPin pinOut = DsFindPin.ByDirection(networkFilter, PinDirection.Output, 0); IPin pinIn = DsFindPin.ByDirection(tunerFilter, PinDirection.Input, 0); int hr = graphBuilder.Connect(pinOut, pinIn); Release.ComObject(pinOut); Release.ComObject(pinIn); return (hr == 0); } private void OnSystemDeviceConnectedOrDisconnected(object sender, EventArrivedEventArgs e) { // Often several events will be triggered within a very short period of // time when a device is added/removed. We only want to check for new // devices once. Also, the first event may occur before the device is // ready, so we apply the device detection delay here. if ((DateTime.Now - _previousSystemDeviceChange).TotalMilliseconds < 10000) { return; } _previousSystemDeviceChange = DateTime.Now; TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("delayCardDetect", "0"); int delayDetect = Convert.ToInt32(setting.Value); if (delayDetect >= 1) { Thread.Sleep(delayDetect * 1000); } DetectBdaWdmDevices(); } private void DetectBdaWdmDevices() { lock (_lockObject) { Log.Log.Debug("Detecting BDA/WDM devices..."); HashSet<string> previouslyKnownDevices = _knownBdaWdmDevices; _knownBdaWdmDevices = new HashSet<string>(); _knownBdaWdmDevices.Add(_rwsTuner.DevicePath); // Detect TechniSat SkyStar/AirStar/CableStar 2 & IP streaming devices. DetectSupportedLegacyAmFilterDevices(ref previouslyKnownDevices, ref _knownBdaWdmDevices); // Detect capture devices. Currently only the Hauppauge HD PVR & Colossus. DetectSupportedAmKsCrossbarDevices(ref previouslyKnownDevices, ref _knownBdaWdmDevices); // Detect analog tuners. DetectSupportedAmKsTvTunerDevices(ref previouslyKnownDevices, ref _knownBdaWdmDevices); // Detect digital BDA tuners. DetectSupportedBdaSourceDevices(ref previouslyKnownDevices, ref _knownBdaWdmDevices); // Remove the devices that are no longer connected. foreach (string previouslyKnownDevice in previouslyKnownDevices) { if (!_knownBdaWdmDevices.Contains(previouslyKnownDevice)) { Log.Log.Info("BDA/WDM device {0} removed", previouslyKnownDevice); _deviceEventListener.OnDeviceRemoved(previouslyKnownDevice); } } } } private void InitBdaDetectionGraph() { Log.Log.Debug("Initialise BDA device detection graph"); _graphBuilder = (IFilterGraph2)new FilterGraph(); _rotEntry = new DsROTEntry(_graphBuilder); Guid mpNetworkProviderClsId = new Guid("{D7D42E5C-EB36-4aad-933B-B4C419429C98}"); if (FilterGraphTools.IsThisComObjectInstalled(mpNetworkProviderClsId)) { _mpNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, mpNetworkProviderClsId, "MediaPortal Network Provider"); return; } ITuningSpace tuningSpace = null; ILocator locator = null; // ATSC _atscNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, typeof(ATSCNetworkProvider).GUID, "ATSC Network Provider"); tuningSpace = (ITuningSpace)new ATSCTuningSpace(); tuningSpace.put_UniqueName("ATSC TuningSpace"); tuningSpace.put_FriendlyName("ATSC TuningSpace"); ((IATSCTuningSpace)tuningSpace).put_MaxChannel(10000); ((IATSCTuningSpace)tuningSpace).put_MaxMinorChannel(10000); ((IATSCTuningSpace)tuningSpace).put_MinChannel(0); ((IATSCTuningSpace)tuningSpace).put_MinMinorChannel(0); ((IATSCTuningSpace)tuningSpace).put_MinPhysicalChannel(0); ((IATSCTuningSpace)tuningSpace).put_InputType(TunerInputType.Antenna); locator = (IATSCLocator)new ATSCLocator(); locator.put_CarrierFrequency(-1); locator.put_InnerFEC(FECMethod.MethodNotSet); locator.put_InnerFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_Modulation(ModulationType.ModNotSet); locator.put_OuterFEC(FECMethod.MethodNotSet); locator.put_OuterFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_SymbolRate(-1); locator.put_CarrierFrequency(-1); ((IATSCLocator)locator).put_PhysicalChannel(-1); ((IATSCLocator)locator).put_TSID(-1); tuningSpace.put_DefaultLocator(locator); ((ITuner)_atscNp).put_TuningSpace(tuningSpace); // DVB-C _dvbcNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, typeof(DVBCNetworkProvider).GUID, "DVB-C Network Provider"); tuningSpace = (ITuningSpace)new DVBTuningSpace(); tuningSpace.put_UniqueName("DVB-C TuningSpace"); tuningSpace.put_FriendlyName("DVB-C TuningSpace"); tuningSpace.put__NetworkType(typeof(DVBCNetworkProvider).GUID); ((IDVBTuningSpace)tuningSpace).put_SystemType(DVBSystemType.Cable); locator = (ILocator)new DVBCLocator(); locator.put_CarrierFrequency(-1); locator.put_InnerFEC(FECMethod.MethodNotSet); locator.put_InnerFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_Modulation(ModulationType.ModNotSet); locator.put_OuterFEC(FECMethod.MethodNotSet); locator.put_OuterFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_SymbolRate(-1); tuningSpace.put_DefaultLocator(locator); ((ITuner)_dvbcNp).put_TuningSpace(tuningSpace); // DVB-S _dvbsNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, typeof(DVBSNetworkProvider).GUID, "DVB-S Network Provider"); tuningSpace = (ITuningSpace)new DVBSTuningSpace(); tuningSpace.put_UniqueName("DVB-S TuningSpace"); tuningSpace.put_FriendlyName("DVB-S TuningSpace"); tuningSpace.put__NetworkType(typeof(DVBSNetworkProvider).GUID); ((IDVBSTuningSpace)tuningSpace).put_SystemType(DVBSystemType.Satellite); locator = (ILocator)new DVBTLocator(); locator.put_CarrierFrequency(-1); locator.put_InnerFEC(FECMethod.MethodNotSet); locator.put_InnerFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_Modulation(ModulationType.ModNotSet); locator.put_OuterFEC(FECMethod.MethodNotSet); locator.put_OuterFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_SymbolRate(-1); tuningSpace.put_DefaultLocator(locator); ((ITuner)_dvbsNp).put_TuningSpace(tuningSpace); // DVB-T _dvbtNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, typeof(DVBTNetworkProvider).GUID, "DVB-T Network Provider"); tuningSpace = (ITuningSpace)new DVBTuningSpace(); tuningSpace.put_UniqueName("DVB-T TuningSpace"); tuningSpace.put_FriendlyName("DVB-T TuningSpace"); tuningSpace.put__NetworkType(typeof(DVBTNetworkProvider).GUID); ((IDVBTuningSpace)tuningSpace).put_SystemType(DVBSystemType.Terrestrial); locator = (ILocator)new DVBTLocator(); locator.put_CarrierFrequency(-1); locator.put_InnerFEC(FECMethod.MethodNotSet); locator.put_InnerFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_Modulation(ModulationType.ModNotSet); locator.put_OuterFEC(FECMethod.MethodNotSet); locator.put_OuterFECRate(BinaryConvolutionCodeRate.RateNotSet); locator.put_SymbolRate(-1); tuningSpace.put_DefaultLocator(locator); ((ITuner)_dvbtNp).put_TuningSpace(tuningSpace); } private void DetectSupportedLegacyAmFilterDevices(ref HashSet<string> previouslyKnownDevices, ref HashSet<string> knownDevices) { Log.Log.Debug("Detect legacy AM filter devices"); TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = layer.GetSetting("iptvCardCount", "1"); int iptvTunerCount = Convert.ToInt32(setting.Value); DsDevice[] connectedDevices = DsDevice.GetDevicesOfCat(FilterCategory.LegacyAmFilterCategory); foreach (DsDevice connectedDevice in connectedDevices) { string name = connectedDevice.Name; string devicePath = connectedDevice.DevicePath; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(devicePath)) { continue; } if (name.Equals("B2C2 MPEG-2 Source")) { knownDevices.Add(devicePath); if (!previouslyKnownDevices.Contains(devicePath)) { Log.Log.Info("Detected new TechniSat *Star 2 tuner root device"); TvCardDvbSS2 tuner = new TvCardDvbSS2(connectedDevice); _deviceEventListener.OnDeviceAdded(tuner); } } else if (name.Equals("Elecard NWSource-Plus")) { for (int i = 0; i < iptvTunerCount; i++) { TvCardDVBIP iptvTuner = new TvCardDVBIPElecard(connectedDevice, i); knownDevices.Add(iptvTuner.DevicePath); if (!previouslyKnownDevices.Contains(iptvTuner.DevicePath)) { Log.Log.Info("Detected new Elecard IPTV tuner {0} {1}", iptvTuner.Name, iptvTuner.DevicePath); _deviceEventListener.OnDeviceAdded(iptvTuner); } else { iptvTuner.Dispose(); } } } else if (name.Equals("MediaPortal IPTV Source Filter")) { for (int i = 0; i < iptvTunerCount; i++) { TvCardDVBIP iptvTuner = new TvCardDVBIPBuiltIn(connectedDevice, i); knownDevices.Add(iptvTuner.DevicePath); if (!previouslyKnownDevices.Contains(iptvTuner.DevicePath)) { Log.Log.Info("Detected new MediaPortal IPTV tuner {0} {1}", iptvTuner.Name, iptvTuner.DevicePath); _deviceEventListener.OnDeviceAdded(iptvTuner); } else { iptvTuner.Dispose(); } } } } } private void DetectSupportedAmKsCrossbarDevices(ref HashSet<string> previouslyKnownDevices, ref HashSet<string> knownDevices) { Log.Log.Debug("Detect AM KS crossbar devices"); DsDevice[] connectedDevices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCrossbar); foreach (DsDevice connectedDevice in connectedDevices) { string name = connectedDevice.Name; string devicePath = connectedDevice.DevicePath; if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(devicePath) && ( name.Equals(TvCardHDPVR.CROSSBAR_NAME_HDPVR) || name.Contains(TvCardHDPVR.CROSSBAR_NAME_COLOSSUS) || name.Equals(TvCardHDPVR.CROSSBAR_NAME_HDPVR2_COLOSSUS2) || name.Equals(TvCardHDPVR.CROSSBAR_NAME_HDPVR60) ) ) { knownDevices.Add(devicePath); if (!previouslyKnownDevices.Contains(devicePath)) { Log.Log.Info("Detected new Hauppauge capture device {0} {1)", name, devicePath); TvCardHDPVR captureDevice = new TvCardHDPVR(connectedDevice); _deviceEventListener.OnDeviceAdded(captureDevice); } } } } private void DetectSupportedAmKsTvTunerDevices(ref HashSet<string> previouslyKnownDevices, ref HashSet<string> knownDevices) { Log.Log.Debug("Detect AM KS TV tuner devices"); DsDevice[] connectedDevices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSTVTuner); foreach (DsDevice connectedDevice in connectedDevices) { string name = connectedDevice.Name; string devicePath = connectedDevice.DevicePath; if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(devicePath)) { knownDevices.Add(devicePath); if (!previouslyKnownDevices.Contains(devicePath)) { Log.Log.Info("Detected new analog tuner device {0} {1}", name, devicePath); TvCardAnalog analogTuner = new TvCardAnalog(connectedDevice); _deviceEventListener.OnDeviceAdded(analogTuner); } } } } private void DetectSupportedBdaSourceDevices(ref HashSet<string> previouslyKnownDevices, ref HashSet<string> knownDevices) { Log.Log.Debug("Detect BDA source devices"); // MS generic, MCE 2005 roll-up 2 or better bool isMsGenericNpAvailable = FilterGraphTools.IsThisComObjectInstalled(typeof(NetworkProvider).GUID); DsDevice[] connectedDevices = DsDevice.GetDevicesOfCat(FilterCategory.BDASourceFiltersCategory); foreach (DsDevice connectedDevice in connectedDevices) { string name = connectedDevice.Name; string devicePath = connectedDevice.DevicePath; if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(devicePath)) { continue; } if (previouslyKnownDevices.Contains(devicePath)) { knownDevices.Add(devicePath); continue; } // North American CableCARD tuners [PBDA]. if (name.StartsWith("HDHomeRun Prime") || name.StartsWith("Ceton InfiniTV")) { Log.Log.Info("Detected new PBDA CableCARD tuner device {0} {1}", name, devicePath); TunerPbdaCableCard cableCardTuner = new TunerPbdaCableCard(connectedDevice); knownDevices.Add(devicePath); _deviceEventListener.OnDeviceAdded(cableCardTuner); continue; } IBaseFilter tmpDeviceFilter; try { _graphBuilder.AddSourceFilterForMoniker(connectedDevice.Mon, null, name, out tmpDeviceFilter); } catch (Exception ex) { Log.Log.Error("Failed to add filter to detect device type for {0}!\r\n{1}", name, ex); continue; } try { // Silicondust regular (non-CableCARD) HDHomeRun. Workaround for tuner type // detection issue. The MS generic provider would always detect DVB-T. bool isCablePreferred = false; if (name.StartsWith("Silicondust HDHomeRun Tuner")) { isCablePreferred = GetHdHomeRunSourceType(name).Equals("Digital Cable"); } Log.Log.Info("Detected new digital BDA tuner device {0} {1}", name, devicePath); // Try the MediaPortal network provider first. ITVCard deviceToAdd = null; if (_mpNp != null) { Log.Log.Debug(" check type with MP NP"); IDvbNetworkProvider interfaceNetworkProvider = (IDvbNetworkProvider)_mpNp; string hash = GetHash(devicePath); interfaceNetworkProvider.ConfigureLogging(GetFileName(devicePath), hash, LogLevelOption.Debug); if (ConnectFilter(_graphBuilder, _mpNp, tmpDeviceFilter)) { TuningType tuningTypes; interfaceNetworkProvider.GetAvailableTuningTypes(out tuningTypes); Log.Log.Debug(" tuning types = {0}, hash = {1}", tuningTypes, hash); if ((tuningTypes & TuningType.DvbT) != 0 && !isCablePreferred) { deviceToAdd = new TvCardDVBT(connectedDevice); } else if ((tuningTypes & TuningType.DvbS) != 0 && !isCablePreferred) { deviceToAdd = new TvCardDVBS(connectedDevice); } else if ((tuningTypes & TuningType.DvbC) != 0) { deviceToAdd = new TvCardDVBC(connectedDevice); } else if ((tuningTypes & TuningType.Atsc) != 0) { deviceToAdd = new TvCardATSC(connectedDevice); } else { Log.Log.Debug(" connected to MP NP but type not recognised"); } } else { Log.Log.Debug(" failed to connect to MP NP"); } } // Try the Microsoft network provider next if the MP NP // failed and the MS generic NP is available. if (deviceToAdd == null && isMsGenericNpAvailable) { // Note: the MS NP must be added/removed to/from the graph for each // device that is checked. If you don't do this, the networkTypes // list gets longer and longer and longer. Log.Log.Debug(" check type with MS NP"); IBaseFilter genericNp = null; try { genericNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, typeof(NetworkProvider).GUID, "Microsoft Network Provider"); } catch { genericNp = null; } if (genericNp == null) { Log.Log.Error(" failed to add MS NP to graph"); } else { if (ConnectFilter(_graphBuilder, genericNp, tmpDeviceFilter)) { int networkTypesMax = 5; int networkTypeCount; Guid[] networkTypes = new Guid[networkTypesMax]; int hr = (genericNp as ITunerCap).get_SupportedNetworkTypes(networkTypesMax, out networkTypeCount, networkTypes); Log.Log.Debug(" network type count = {0}", networkTypeCount); for (int n = 0; n < networkTypeCount; n++) { Log.Log.Debug(" network type {0} = {1}", n, networkTypes[n]); } for (int n = 0; n < networkTypeCount; n++) { if (networkTypes[n] == typeof(DVBTNetworkProvider).GUID && !isCablePreferred) { deviceToAdd = new TvCardDVBT(connectedDevice); } else if (networkTypes[n] == typeof(DVBSNetworkProvider).GUID && !isCablePreferred) { deviceToAdd = new TvCardDVBS(connectedDevice); } else if (networkTypes[n] == typeof(DVBCNetworkProvider).GUID) { deviceToAdd = new TvCardDVBC(connectedDevice); } else if (networkTypes[n] == typeof(ATSCNetworkProvider).GUID) { deviceToAdd = new TvCardATSC(connectedDevice); } if (deviceToAdd != null) { break; } else if (n == (networkTypeCount - 1)) { Log.Log.Debug(" connected to MS NP but type not recognised"); } } } else { Log.Log.Debug(" failed to connect to MS NP"); } _graphBuilder.RemoveFilter(genericNp); Release.ComObject("device detection generic network provider", genericNp); genericNp = null; } } // Last shot is the old style Microsoft network providers. if (deviceToAdd == null) { Log.Log.Debug(" check type with specific NPs"); if (ConnectFilter(_graphBuilder, _dvbtNp, tmpDeviceFilter)) { deviceToAdd = new TvCardDVBT(connectedDevice); } else if (ConnectFilter(_graphBuilder, _dvbcNp, tmpDeviceFilter)) { deviceToAdd = new TvCardDVBC(connectedDevice); } else if (ConnectFilter(_graphBuilder, _dvbsNp, tmpDeviceFilter)) { deviceToAdd = new TvCardDVBS(connectedDevice); } else if (ConnectFilter(_graphBuilder, _atscNp, tmpDeviceFilter)) { deviceToAdd = new TvCardATSC(connectedDevice); } else { Log.Log.Debug(" failed to connect to specific NP"); } } if (deviceToAdd != null) { Log.Log.Info(" tuner type = {0}", deviceToAdd.CardType); knownDevices.Add(devicePath); _deviceEventListener.OnDeviceAdded(deviceToAdd); } } finally { _graphBuilder.RemoveFilter(tmpDeviceFilter); Release.ComObject("device detection device filter", tmpDeviceFilter); } } } #endregion #region MP network provider only (contact MisterD) /// <summary> /// Generates the file and pathname of the log file /// </summary> /// <param name="devicePath">Device Path of the card</param> /// <returns>Complete filename of the configuration file</returns> public static string GetFileName(string devicePath) { string hash = GetHash(devicePath); string pathName = PathManager.GetDataPath; string fileName = string.Format(@"{0}\Log\NetworkProvider-{1}.log", pathName, hash); Log.Log.Debug("NetworkProvider logfilename: " + fileName); Directory.CreateDirectory(Path.GetDirectoryName(fileName)); return fileName; } public static string GetHash(string value) { byte[] data = Encoding.ASCII.GetBytes(value); byte[] hashData = new SHA1Managed().ComputeHash(data); string hash = string.Empty; foreach (byte b in hashData) { hash += b.ToString("X2"); } return hash; } #endregion #region UPnP device detection private void OnUpnpRootDeviceAdded(RootDescriptor rootDescriptor) { if (rootDescriptor == null || rootDescriptor.State != RootDescriptorState.Ready || _knownUpnpDevices.Contains(rootDescriptor.SSDPRootEntry.RootDeviceUUID)) { return; } _knownUpnpDevices.Add(rootDescriptor.SSDPRootEntry.RootDeviceUUID); DeviceDescriptor deviceDescriptor = DeviceDescriptor.CreateRootDeviceDescriptor(rootDescriptor); IEnumerator<DeviceEntry> childDeviceEn = rootDescriptor.SSDPRootEntry.Devices.Values.GetEnumerator(); bool isFirst = true; while (childDeviceEn.MoveNext()) { foreach (string serviceUrn in childDeviceEn.Current.Services) { // Supported device? if (serviceUrn.Equals("urn:schemas-opencable-com:service:Tuner:1")) { if (isFirst) { isFirst = false; Log.Log.Info("Detected new OCUR/DRI device {0}", deviceDescriptor.FriendlyName); } // Find the corresponding DeviceDescriptor. IEnumerator<DeviceDescriptor> childDeviceDescriptorEn = deviceDescriptor.ChildDevices.GetEnumerator(); while (childDeviceDescriptorEn.MoveNext()) { if (childDeviceDescriptorEn.Current.DeviceUUID == childDeviceEn.Current.UUID) { break; } } Log.Log.Info(" add {0} {1}", childDeviceDescriptorEn.Current.FriendlyName, childDeviceDescriptorEn.Current.DeviceUDN); _deviceEventListener.OnDeviceAdded(new TunerDri(childDeviceDescriptorEn.Current, _upnpControlPoint)); break; } } } } private void OnUpnpRootDeviceRemoved(RootDescriptor rootDescriptor) { if (rootDescriptor == null) { return; } _knownUpnpDevices.Remove(rootDescriptor.SSDPRootEntry.RootDeviceUUID); DeviceDescriptor deviceDescriptor = DeviceDescriptor.CreateRootDeviceDescriptor(rootDescriptor); IEnumerator<DeviceEntry> childDeviceEn = rootDescriptor.SSDPRootEntry.Devices.Values.GetEnumerator(); bool isFirst = true; while (childDeviceEn.MoveNext()) { foreach (string serviceUrn in childDeviceEn.Current.Services) { if (serviceUrn.Equals("urn:schemas-opencable-com:service:Tuner:1")) { if (isFirst) { isFirst = false; Log.Log.Info("UPnP device {0} removed", deviceDescriptor.FriendlyName); } IEnumerator<DeviceDescriptor> childDeviceDescriptorEn = deviceDescriptor.ChildDevices.GetEnumerator(); while (childDeviceDescriptorEn.MoveNext()) { if (childDeviceDescriptorEn.Current.DeviceUUID == childDeviceEn.Current.UUID) { break; } } Log.Log.Info(" remove {0} {1}", childDeviceDescriptorEn.Current.FriendlyName, childDeviceDescriptorEn.Current.DeviceUDN); _deviceEventListener.OnDeviceRemoved(childDeviceDescriptorEn.Current.DeviceUDN); break; } } } } #endregion #region hardware specific functions private string GetHdHomeRunSourceType(string tunerName) { try { // The tuner settings (configured by "HDHomeRun Setup" - part of the // Silicondust HDHomeRun driver and software package) are stored in the // registry. Example: // tuner device name = "Silicondust HDHomeRun Tuner 1210551E-0" // registry key = "HKEY_LOCAL_MACHINE\SOFTWARE\Silicondust\HDHomeRun\Tuners\1210551E-0" // possible source type values = // "Digital Cable" [DVB-C, clear QAM] // "Digital Antenna" [DVB-T, ATSC] // "CableCARD" [North American encrypted cable television] string serialNumber = tunerName.Replace("Silicondust HDHomeRun Tuner ", ""); using ( RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(string.Format(@"SOFTWARE\Silicondust\HDHomeRun\Tuners\{0}", serialNumber))) { if (registryKey != null) { return registryKey.GetValue("Source").ToString(); } } } catch (Exception ex) { Log.Log.Error("Failed to check HDHomeRun preferred mode.\r\n{0}", ex); } return "Digital Antenna"; } #endregion } }
{ "pile_set_name": "Github" }
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * sysfile.c * * Initialize, read, write, etc. system files. * * Copyright (C) 2002, 2004 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/fs.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/highmem.h> #define MLOG_MASK_PREFIX ML_INODE #include <cluster/masklog.h> #include "ocfs2.h" #include "alloc.h" #include "dir.h" #include "inode.h" #include "journal.h" #include "sysfile.h" #include "buffer_head_io.h" static struct inode * _ocfs2_get_system_file_inode(struct ocfs2_super *osb, int type, u32 slot); static inline int is_global_system_inode(int type); static inline int is_in_system_inode_array(struct ocfs2_super *osb, int type, u32 slot); #ifdef CONFIG_DEBUG_LOCK_ALLOC static struct lock_class_key ocfs2_sysfile_cluster_lock_key[NUM_SYSTEM_INODES]; #endif static inline int is_global_system_inode(int type) { return type >= OCFS2_FIRST_ONLINE_SYSTEM_INODE && type <= OCFS2_LAST_GLOBAL_SYSTEM_INODE; } static inline int is_in_system_inode_array(struct ocfs2_super *osb, int type, u32 slot) { return slot == osb->slot_num || is_global_system_inode(type); } struct inode *ocfs2_get_system_file_inode(struct ocfs2_super *osb, int type, u32 slot) { struct inode *inode = NULL; struct inode **arr = NULL; /* avoid the lookup if cached in local system file array */ if (is_in_system_inode_array(osb, type, slot)) arr = &(osb->system_inodes[type]); if (arr && ((inode = *arr) != NULL)) { /* get a ref in addition to the array ref */ inode = igrab(inode); BUG_ON(!inode); return inode; } /* this gets one ref thru iget */ inode = _ocfs2_get_system_file_inode(osb, type, slot); /* add one more if putting into array for first time */ if (arr && inode) { *arr = igrab(inode); BUG_ON(!*arr); } return inode; } static struct inode * _ocfs2_get_system_file_inode(struct ocfs2_super *osb, int type, u32 slot) { char namebuf[40]; struct inode *inode = NULL; u64 blkno; int status = 0; ocfs2_sprintf_system_inode_name(namebuf, sizeof(namebuf), type, slot); status = ocfs2_lookup_ino_from_name(osb->sys_root_inode, namebuf, strlen(namebuf), &blkno); if (status < 0) { goto bail; } inode = ocfs2_iget(osb, blkno, OCFS2_FI_FLAG_SYSFILE, type); if (IS_ERR(inode)) { mlog_errno(PTR_ERR(inode)); inode = NULL; goto bail; } #ifdef CONFIG_DEBUG_LOCK_ALLOC if (type == LOCAL_USER_QUOTA_SYSTEM_INODE || type == LOCAL_GROUP_QUOTA_SYSTEM_INODE || type == JOURNAL_SYSTEM_INODE) { /* Ignore inode lock on these inodes as the lock does not * really belong to any process and lockdep cannot handle * that */ OCFS2_I(inode)->ip_inode_lockres.l_lockdep_map.key = NULL; } else { lockdep_init_map(&OCFS2_I(inode)->ip_inode_lockres. l_lockdep_map, ocfs2_system_inodes[type].si_name, &ocfs2_sysfile_cluster_lock_key[type], 0); } #endif bail: return inode; }
{ "pile_set_name": "Github" }
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.study.xuan.gifshow" > <application android:allowBackup="true" android:label="@string/app_name" android:supportsRtl="true" > </application> </manifest>
{ "pile_set_name": "Github" }
import { Component, OnInit } from '@angular/core'; import { SocialAuthService } from 'lib'; import { SocialUser } from 'lib'; import { GoogleLoginProvider, FacebookLoginProvider, AmazonLoginProvider, } from 'lib'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) export class DemoComponent implements OnInit { user: SocialUser; constructor(private authService: SocialAuthService) { } ngOnInit() { this.authService.authState.subscribe(user => { this.user = user; }); } signInWithGoogle(): void { this.authService.signIn(GoogleLoginProvider.PROVIDER_ID); } signInWithFB(): void { this.authService.signIn(FacebookLoginProvider.PROVIDER_ID); } signInWithAmazon(): void { this.authService.signIn(AmazonLoginProvider.PROVIDER_ID); } signOut(): void { this.authService.signOut(); } }
{ "pile_set_name": "Github" }
--- title: "synchronizationQuarantine resource type" description: "Provides information about the quarantine state of a synchronizationJob." localization_priority: Normal doc_type: resourcePageType author: "ArvindHarinder1" ms.prod: "microsoft-identity-platform" --- # synchronizationQuarantine resource type Namespace: microsoft.graph [!INCLUDE [beta-disclaimer](../../includes/beta-disclaimer.md)] Provides information about the quarantine state of a [synchronizationJob](synchronization-synchronizationjob.md). ## Properties | Property | Type |Description| |:---------------|:--------|:----------| |currentBegan|DateTimeOffset|Date and time when the quarantine was last evaluated and imposed. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: `'2014-01-01T00:00:00Z'`.| |nextAttempt|DateTimeOffset|Date and time when the next attempt to re-evaluate the quarantine will be made. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: `'2014-01-01T00:00:00Z'`.| |reason|String|A code that signifies why the quarantine was imposed. Possible values are: `EncounteredBaseEscrowThreshold`, `EncounteredTotalEscrowThreshold`, `EncounteredEscrowProportionThreshold`, `EncounteredQuarantineException`, `QuarantinedOnDemand`, `TooManyDeletes`, `Unknown`.| |seriesBegan|DateTimeOffset|Date and time when the quarantine was first imposed in this series (a series starts when a quarantine is first imposed, and is reset as soon as the quarantine is lifted). The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: `'2014-01-01T00:00:00Z'`.| |seriesCount|Int64|Number of times in this series the quarantine was re-evaluated and left in effect (a series starts when quarantine is first imposed, and is reset as soon as quarantine is lifted).| |error|[synchronizationError](synchronization-synchronizationerror.md)|Describes the error(s) that occurred when putting the synchronization job into quarantine.| ## JSON representation The following is a JSON representation of the resource. <!-- { "blockType": "resource", "optionalProperties": [ ], "@odata.type": "microsoft.graph.synchronizationQuarantine" }--> ```json { "error": {"@odata.type": "microsoft.graph.synchronizationError"}, "currentBegan": "String (timestamp)", "nextAttempt": "String (timestamp)", "reason": "String", "seriesBegan": "String (timestamp)", "seriesCount": 1024 } ``` <!-- uuid: 8fcb5dbc-d5aa-4681-8e31-b001d5168d79 2015-10-25 14:57:30 UTC --> <!-- { "type": "#page.annotation", "description": "synchronizationQuarantine resource", "keywords": "", "section": "documentation", "tocPath": "", "suppressions": [] } -->
{ "pile_set_name": "Github" }
// 非递归版 function merge(left, right) { const result = []; while (left.length && right.length) { if (left[0] < right[0]) result.push(left.shift()); else result.push(right.shift()); } return result.concat(left, right); } function mergeSort(a) { if (a.length === 1) return a; const work = [], len = a.length; for (let i = 0; i < len; i++) work.push([a[i]]); work.push([]); // 如果数组长度为奇数 let last = 0; for (let lim = len; lim > 1; lim = lim + 1 >> 1) { for (let j = 0, k = 0; k < lim; j++, k += 2) { work[j] = merge(work[k], work[k + 1]); last = j; } work[last + 1] = []; // 如果数组长度为奇数 } return work[0]; } console.log(mergeSort([1, 2, 3, 4, 5, 6, 5, 4, 3, 1]));
{ "pile_set_name": "Github" }
#include "Parameters.h" #include "Util.h" #include "DBReader.h" #include "CommandCaller.h" #include "Debug.h" #include "FileUtil.h" #include "createindex.sh.h" #include <string> #include <cassert> #include <climits> int createindex(Parameters &par, std::string indexerModule, std::string flag) { bool sensitivity = false; // only set kmerScore to INT_MAX if -s was used for (size_t i = 0; i < par.createindex.size(); i++) { if (par.createindex[i]->uniqid == par.PARAM_S.uniqid && par.createindex[i]->wasSet) { par.kmerScore = INT_MAX; sensitivity=true; break; } } int dbType = FileUtil::parseDbType(par.db1.c_str()); if (Parameters::isEqualDbtype(dbType, Parameters::DBTYPE_HMM_PROFILE) && sensitivity == false) { Debug(Debug::ERROR) << "Please adjust the sensitivity of your target profile index with -s.\n" "Be aware that this searches can take huge amount of memory. \n"; return EXIT_FAILURE; } std::string tmpDir = par.db2; std::string hash = SSTR(par.hashParameter(par.filenames, par.createindex)); if (par.reuseLatest) { hash = FileUtil::getHashFromSymLink(tmpDir + "/latest"); } tmpDir = FileUtil::createTemporaryDirectory(tmpDir, hash); par.filenames.pop_back(); par.filenames.push_back(tmpDir); CommandCaller cmd; cmd.addVariable("INDEXER", indexerModule.c_str()); cmd.addVariable("REMOVE_TMP", par.removeTmpFiles ? "TRUE" : NULL); par.translate = 1; cmd.addVariable("ORF_PAR", par.createParameterString(par.extractorfs).c_str()); cmd.addVariable("EXTRACT_FRAMES_PAR", par.createParameterString(par.extractframes).c_str()); cmd.addVariable("SPLIT_SEQ_PAR", par.createParameterString(par.splitsequence).c_str()); if(indexerModule == "kmerindexdb"){ cmd.addVariable("INDEX_PAR", par.createParameterString(par.kmerindexdb).c_str()); }else{ cmd.addVariable("INDEX_PAR", par.createParameterString(par.indexdb).c_str()); } if(flag.size() > 0){ cmd.addVariable(flag.c_str(), "1"); } std::string program(tmpDir + "/createindex.sh"); FileUtil::writeFile(program, createindex_sh, createindex_sh_len); cmd.execProgram(program.c_str(), par.filenames); return 0; } int createlinindex(int argc, const char **argv, const Command& command) { Parameters& par = Parameters::getInstance(); par.orfStartMode = 1; par.orfMinLength = 30; par.orfMaxLength = 32734; par.kmerScore = 0; // extract all k-mers par.maskMode = 0; par.spacedKmer = false; // VTML has a slightly lower sensitivity in the regression test par.seedScoringMatrixFile = MultiParam<char*>("blosum62.out", "nucleotide.out"); par.PARAM_COV_MODE.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_C.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_MIN_SEQ_ID.addCategory(MMseqsParameter::COMMAND_EXPERT); for (size_t i = 0; i < par.extractorfs.size(); i++) { par.extractorfs[i]->addCategory(MMseqsParameter::COMMAND_EXPERT); } for (size_t i = 0; i < par.translatenucs.size(); i++) { par.translatenucs[i]->addCategory(MMseqsParameter::COMMAND_EXPERT); } par.PARAM_COMPRESSED.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_THREADS.removeCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_V.removeCategory(MMseqsParameter::COMMAND_EXPERT); par.parseParameters(argc, argv, command, true, 0, 0); int dbType = FileUtil::parseDbType(par.db1.c_str()); bool isNucl = Parameters::isEqualDbtype(dbType, Parameters::DBTYPE_NUCLEOTIDES); if(isNucl && par.searchType == Parameters::SEARCH_TYPE_NUCLEOTIDES && par.PARAM_MAX_SEQ_LEN.wasSet == false){ if(par.PARAM_MAX_SEQ_LEN.wasSet == false){ par.maxSeqLen = 10000; } } par.printParameters(command.cmd, argc, argv, *command.params); if(isNucl && par.searchType == Parameters::SEARCH_TYPE_AUTO){ Debug(Debug::WARNING) << "Database " << par.db1 << " is a nucleotide database. \n" << "Please provide the parameter --search-type 2 (translated) or 3 (nucleotide)\n"; return EXIT_FAILURE; } return createindex(par, "kmerindexdb", (isNucl == false) ? "" : (par.searchType == Parameters::SEARCH_TYPE_TRANSLATED|| par.searchType == Parameters::SEARCH_TYPE_TRANS_NUCL_ALN) ? "TRANSLATED" : "LIN_NUCL"); } int createindex(int argc, const char **argv, const Command& command) { Parameters& par = Parameters::getInstance(); par.orfStartMode = 1; par.orfMinLength = 30; par.orfMaxLength = 32734; par.kmerScore = 0; // extract all k-mers par.sensitivity = 7.5; par.maskMode = 1; par.PARAM_COV_MODE.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_C.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_MIN_SEQ_ID.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_MAX_SEQS.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_SPLIT.removeCategory(MMseqsParameter::COMMAND_EXPERT); for (size_t i = 0; i < par.splitsequence.size(); i++) { par.splitsequence[i]->addCategory(MMseqsParameter::COMMAND_EXPERT); } for (size_t i = 0; i < par.extractorfs.size(); i++) { par.extractorfs[i]->addCategory(MMseqsParameter::COMMAND_EXPERT); } for (size_t i = 0; i < par.translatenucs.size(); i++) { par.translatenucs[i]->addCategory(MMseqsParameter::COMMAND_EXPERT); } par.PARAM_COMPRESSED.addCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_THREADS.removeCategory(MMseqsParameter::COMMAND_EXPERT); par.PARAM_V.removeCategory(MMseqsParameter::COMMAND_EXPERT); par.parseParameters(argc, argv, command, true, 0, 0); int dbType = FileUtil::parseDbType(par.db1.c_str()); bool isNucl = Parameters::isEqualDbtype(dbType, Parameters::DBTYPE_NUCLEOTIDES); if (par.PARAM_STRAND.wasSet == false) { par.strand = 1; } if(isNucl && par.searchType == Parameters::SEARCH_TYPE_NUCLEOTIDES ){ if ( par.PARAM_K.wasSet == false) { par.kmerSize = 15; } if ( par.PARAM_MAX_SEQ_LEN.wasSet == false) { par.maxSeqLen = 10000; } // 0: reverse, 1: forward, 2: both switch (par.strand){ case 0: par.forwardFrames= ""; par.reverseFrames= "1"; break; case 1: par.forwardFrames= "1"; par.reverseFrames= ""; break; case 2: par.forwardFrames= "1"; par.reverseFrames= "1"; break; } } par.printParameters(command.cmd, argc, argv, *command.params); if(isNucl && par.searchType == Parameters::SEARCH_TYPE_AUTO){ Debug(Debug::WARNING) << "Database " << par.db1 << " is a nucleotide database. \n" << "Please provide the parameter --search-type 2 (translated) or 3 (nucleotide)\n"; return EXIT_FAILURE; } return createindex(par, "indexdb", (isNucl == false) ? "" : (par.searchType == Parameters::SEARCH_TYPE_TRANSLATED|| par.searchType == Parameters::SEARCH_TYPE_TRANS_NUCL_ALN) ? "TRANSLATED" : "NUCL"); }
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef DRBD_STATE_CHANGE_H #define DRBD_STATE_CHANGE_H struct drbd_resource_state_change { struct drbd_resource *resource; enum drbd_role role[2]; bool susp[2]; bool susp_nod[2]; bool susp_fen[2]; }; struct drbd_device_state_change { struct drbd_device *device; enum drbd_disk_state disk_state[2]; }; struct drbd_connection_state_change { struct drbd_connection *connection; enum drbd_conns cstate[2]; /* drbd9: enum drbd_conn_state */ enum drbd_role peer_role[2]; }; struct drbd_peer_device_state_change { struct drbd_peer_device *peer_device; enum drbd_disk_state disk_state[2]; enum drbd_conns repl_state[2]; /* drbd9: enum drbd_repl_state */ bool resync_susp_user[2]; bool resync_susp_peer[2]; bool resync_susp_dependency[2]; }; struct drbd_state_change { struct list_head list; unsigned int n_devices; unsigned int n_connections; struct drbd_resource_state_change resource[1]; struct drbd_device_state_change *devices; struct drbd_connection_state_change *connections; struct drbd_peer_device_state_change *peer_devices; }; extern struct drbd_state_change *remember_old_state(struct drbd_resource *, gfp_t); extern void copy_old_to_new_state_change(struct drbd_state_change *); extern void forget_state_change(struct drbd_state_change *); extern void notify_resource_state_change(struct sk_buff *, unsigned int, struct drbd_resource_state_change *, enum drbd_notification_type type); extern void notify_connection_state_change(struct sk_buff *, unsigned int, struct drbd_connection_state_change *, enum drbd_notification_type type); extern void notify_device_state_change(struct sk_buff *, unsigned int, struct drbd_device_state_change *, enum drbd_notification_type type); extern void notify_peer_device_state_change(struct sk_buff *, unsigned int, struct drbd_peer_device_state_change *, enum drbd_notification_type type); #endif /* DRBD_STATE_CHANGE_H */
{ "pile_set_name": "Github" }
package Plagger::Plugin::Widget::Simple; use strict; use base qw( Plagger::Plugin ); use Encode; use HTML::Entities; use URI; sub register { my($self, $context) = @_; $context->register_hook( $self, 'publish.entry.fixup' => \&add, 'plugin.init' => \&initialize, ); } sub initialize { my($self, $context, $args) = @_; if (my $name = $self->conf->{widget}) { my $found; $self->load_assets( "$name.yaml", sub { my $data = YAML::LoadFile(shift); $self->{conf} = { %{$self->{conf}}, %$data }; $found++; }, ); unless ($found) { $context->log(error => "Can't find widget for $name"); } } } sub add { my($self, $context, $args) = @_; my $widget = Plagger::Plugin::Widget::Simple::Widget->new; $widget->{feed} = $args->{entry}->source || $args->{feed}; $widget->{plugin} = $self; $args->{entry}->add_widget($widget); } package Plagger::Plugin::Widget::Simple::Widget; sub new { bless {}, shift } sub feed { shift->{feed} } sub plugin { shift->{plugin} } sub value { my($self, $string, $args) = @_; if ($string =~ /\$/) { # DWIM $string = eval $string; Plagger->context->log(error => $@) if $@; $string = "$string"; # stringify ::Content utf8::encode($string) if utf8::is_utf8($string); } $string; } sub html { my($self, $entry) = @_; my $uri = URI->new($self->plugin->conf->{link}); my $args = { entry => $entry, feed => $self->{feed} }; if (my $append = $self->plugin->conf->{append}) { $uri->path( $uri->path . $self->value($append, $args) ); } if (my $query = $self->plugin->conf->{query}) { if (ref $query) { my @query = map { ($_ => $self->value($query->{$_}, $args)); } sort keys %$query; $uri->query_form(@query); } else { $query = $self->value($query, $args); $uri->query($query); } } my $url = HTML::Entities::encode($uri->as_string); my $content; if (my $template = $self->plugin->conf->{content_dynamic}) { $content = $self->plugin->templatize(\$template, $args); } else { $content = $self->plugin->conf->{content}; } return qq(<a href="$url">$content</a>); } 1; __END__ =head1 NAME Plagger::Plugin::Widget::Simple - Simple widget creation using config =head1 SYNOPSIS - module: Widget::Simple config: link: http://www.example.com/ content_dynamic: "Entry from [% entry.author %]" =head1 DESCRIPTION Widget::Simple is a plugin that allows you to write your own widget using a simple configuration file. =head1 CONFIG =over 4 =item link link: http://example.com/add URL that the widget links to. Required. =item query query: version: 4 url: $args->{entry}->url Query parameter to append to the URL. If the value contains C<$>, it'll be automatically eval()ed. Optional. =item content content: <img src="http://example.com/img.gif" alt="foo" /> Content to display in a widget. HTML tags will be displayed as is and thus any HTML meta characters have to be escaped. Required, if you don't use I<content_dynamic>. =item content_dynamic content_dynamic: "Entry from [% entry.author | html %]" If you want to dynamically generate the content of widget, use I<content_dynamic> instead. Value of the content_dynamic is compiled and rendered using Template-Toolkit. Required, if you don't use I<content>. =back =head1 AUTHOR Tatsuhiko Miyagawa =head1 SEE ALSO L<Plagger> =cut
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -E -verify %s #define DO_PRAGMA _Pragma #define STR "GCC dependency \"parse.y\"") // expected-error@+1 {{'parse.y' file not found}} DO_PRAGMA (STR
{ "pile_set_name": "Github" }
// Copyright 2014 The Go 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 ipv4 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/socket" ) var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_TTL, 1, marshalTTL, parseTTL}, ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, } sockOpts = map[int]*sockOpt{ ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_PKTINFO, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolReserved, Name: sysICMP_FILTER, Len: sizeofICMPFilter}}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoAttachFilter: {Option: socket.Option{Level: sysSOL_SOCKET, Name: sysSO_ATTACH_FILTER, Len: sizeofSockFprog}}, } ) func (pi *inetPktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } func (gr *groupReq) setGroup(grp net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(&gr.Group)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sockaddrInet)(unsafe.Pointer(&gsr.Group)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sockaddrInet)(unsafe.Pointer(&gsr.Source)) sa.Family = syscall.AF_INET copy(sa.Addr[:], src) }
{ "pile_set_name": "Github" }
/* * amdtp-ff.c - a part of driver for RME Fireface series * * Copyright (c) 2015-2017 Takashi Sakamoto * * Licensed under the terms of the GNU General Public License, version 2. */ #include <sound/pcm.h> #include "ff.h" struct amdtp_ff { unsigned int pcm_channels; }; int amdtp_ff_set_parameters(struct amdtp_stream *s, unsigned int rate, unsigned int pcm_channels) { struct amdtp_ff *p = s->protocol; unsigned int data_channels; if (amdtp_stream_running(s)) return -EBUSY; p->pcm_channels = pcm_channels; data_channels = pcm_channels; return amdtp_stream_set_parameters(s, rate, data_channels); } static void write_pcm_s32(struct amdtp_stream *s, struct snd_pcm_substream *pcm, __le32 *buffer, unsigned int frames) { struct amdtp_ff *p = s->protocol; struct snd_pcm_runtime *runtime = pcm->runtime; unsigned int channels, remaining_frames, i, c; const u32 *src; channels = p->pcm_channels; src = (void *)runtime->dma_area + frames_to_bytes(runtime, s->pcm_buffer_pointer); remaining_frames = runtime->buffer_size - s->pcm_buffer_pointer; for (i = 0; i < frames; ++i) { for (c = 0; c < channels; ++c) { buffer[c] = cpu_to_le32(*src); src++; } buffer += s->data_block_quadlets; if (--remaining_frames == 0) src = (void *)runtime->dma_area; } } static void read_pcm_s32(struct amdtp_stream *s, struct snd_pcm_substream *pcm, __le32 *buffer, unsigned int frames) { struct amdtp_ff *p = s->protocol; struct snd_pcm_runtime *runtime = pcm->runtime; unsigned int channels, remaining_frames, i, c; u32 *dst; channels = p->pcm_channels; dst = (void *)runtime->dma_area + frames_to_bytes(runtime, s->pcm_buffer_pointer); remaining_frames = runtime->buffer_size - s->pcm_buffer_pointer; for (i = 0; i < frames; ++i) { for (c = 0; c < channels; ++c) { *dst = le32_to_cpu(buffer[c]) & 0xffffff00; dst++; } buffer += s->data_block_quadlets; if (--remaining_frames == 0) dst = (void *)runtime->dma_area; } } static void write_pcm_silence(struct amdtp_stream *s, __le32 *buffer, unsigned int frames) { struct amdtp_ff *p = s->protocol; unsigned int i, c, channels = p->pcm_channels; for (i = 0; i < frames; ++i) { for (c = 0; c < channels; ++c) buffer[c] = cpu_to_le32(0x00000000); buffer += s->data_block_quadlets; } } int amdtp_ff_add_pcm_hw_constraints(struct amdtp_stream *s, struct snd_pcm_runtime *runtime) { int err; err = snd_pcm_hw_constraint_msbits(runtime, 0, 32, 24); if (err < 0) return err; return amdtp_stream_add_pcm_hw_constraints(s, runtime); } static unsigned int process_rx_data_blocks(struct amdtp_stream *s, __be32 *buffer, unsigned int data_blocks, unsigned int *syt) { struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm); unsigned int pcm_frames; if (pcm) { write_pcm_s32(s, pcm, (__le32 *)buffer, data_blocks); pcm_frames = data_blocks; } else { write_pcm_silence(s, (__le32 *)buffer, data_blocks); pcm_frames = 0; } return pcm_frames; } static unsigned int process_tx_data_blocks(struct amdtp_stream *s, __be32 *buffer, unsigned int data_blocks, unsigned int *syt) { struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm); unsigned int pcm_frames; if (pcm) { read_pcm_s32(s, pcm, (__le32 *)buffer, data_blocks); pcm_frames = data_blocks; } else { pcm_frames = 0; } return pcm_frames; } int amdtp_ff_init(struct amdtp_stream *s, struct fw_unit *unit, enum amdtp_stream_direction dir) { amdtp_stream_process_data_blocks_t process_data_blocks; if (dir == AMDTP_IN_STREAM) process_data_blocks = process_tx_data_blocks; else process_data_blocks = process_rx_data_blocks; return amdtp_stream_init(s, unit, dir, CIP_NO_HEADER, 0, process_data_blocks, sizeof(struct amdtp_ff)); }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2005-2016 Broadcom. * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. The full GNU General * Public License is included in this distribution in the file called COPYING. * * Contact Information: * [email protected] * * Emulex * 3333 Susan Street * Costa Mesa, CA 92626 */ /********* Mailbox door bell *************/ /* Used for driver communication with the FW. * The software must write this register twice to post any command. First, * it writes the register with hi=1 and the upper bits of the physical address * for the MAILBOX structure. Software must poll the ready bit until this * is acknowledged. Then, sotware writes the register with hi=0 with the lower * bits in the address. It must poll the ready bit until the command is * complete. Upon completion, the MAILBOX will contain a valid completion * queue entry. */ #define MPU_MAILBOX_DB_OFFSET 0x160 #define MPU_MAILBOX_DB_RDY_MASK 0x1 /* bit 0 */ #define MPU_MAILBOX_DB_HI_MASK 0x2 /* bit 1 */ #define MPU_EP_CONTROL 0 /********** MPU semphore: used for SH & BE *************/ #define SLIPORT_SOFTRESET_OFFSET 0x5c /* CSR BAR offset */ #define SLIPORT_SEMAPHORE_OFFSET_BEx 0xac /* CSR BAR offset */ #define SLIPORT_SEMAPHORE_OFFSET_SH 0x94 /* PCI-CFG offset */ #define POST_STAGE_MASK 0x0000FFFF #define POST_ERR_MASK 0x1 #define POST_ERR_SHIFT 31 #define POST_ERR_RECOVERY_CODE_MASK 0xFFF /* Soft Reset register masks */ #define SLIPORT_SOFTRESET_SR_MASK 0x00000080 /* SR bit */ /* MPU semphore POST stage values */ #define POST_STAGE_AWAITING_HOST_RDY 0x1 /* FW awaiting goahead from host */ #define POST_STAGE_HOST_RDY 0x2 /* Host has given go-ahed to FW */ #define POST_STAGE_BE_RESET 0x3 /* Host wants to reset chip */ #define POST_STAGE_ARMFW_RDY 0xc000 /* FW is done with POST */ #define POST_STAGE_RECOVERABLE_ERR 0xE000 /* Recoverable err detected */ /* Lancer SLIPORT registers */ #define SLIPORT_STATUS_OFFSET 0x404 #define SLIPORT_CONTROL_OFFSET 0x408 #define SLIPORT_ERROR1_OFFSET 0x40C #define SLIPORT_ERROR2_OFFSET 0x410 #define PHYSDEV_CONTROL_OFFSET 0x414 #define SLIPORT_STATUS_ERR_MASK 0x80000000 #define SLIPORT_STATUS_DIP_MASK 0x02000000 #define SLIPORT_STATUS_RN_MASK 0x01000000 #define SLIPORT_STATUS_RDY_MASK 0x00800000 #define SLI_PORT_CONTROL_IP_MASK 0x08000000 #define PHYSDEV_CONTROL_FW_RESET_MASK 0x00000002 #define PHYSDEV_CONTROL_DD_MASK 0x00000004 #define PHYSDEV_CONTROL_INP_MASK 0x40000000 #define SLIPORT_ERROR_NO_RESOURCE1 0x2 #define SLIPORT_ERROR_NO_RESOURCE2 0x9 #define SLIPORT_ERROR_FW_RESET1 0x2 #define SLIPORT_ERROR_FW_RESET2 0x0 /********* Memory BAR register ************/ #define PCICFG_MEMBAR_CTRL_INT_CTRL_OFFSET 0xfc /* Host Interrupt Enable, if set interrupts are enabled although "PCI Interrupt * Disable" may still globally block interrupts in addition to individual * interrupt masks; a mechanism for the device driver to block all interrupts * atomically without having to arbitrate for the PCI Interrupt Disable bit * with the OS. */ #define MEMBAR_CTRL_INT_CTRL_HOSTINTR_MASK BIT(29) /* bit 29 */ /********* PCI Function Capability *********/ #define BE_FUNCTION_CAPS_RSS 0x2 #define BE_FUNCTION_CAPS_SUPER_NIC 0x40 /********* Power management (WOL) **********/ #define PCICFG_PM_CONTROL_OFFSET 0x44 #define PCICFG_PM_CONTROL_MASK 0x108 /* bits 3 & 8 */ /********* Online Control Registers *******/ #define PCICFG_ONLINE0 0xB0 #define PCICFG_ONLINE1 0xB4 /********* UE Status and Mask Registers ***/ #define PCICFG_UE_STATUS_LOW 0xA0 #define PCICFG_UE_STATUS_HIGH 0xA4 #define PCICFG_UE_STATUS_LOW_MASK 0xA8 #define PCICFG_UE_STATUS_HI_MASK 0xAC /******** SLI_INTF ***********************/ #define SLI_INTF_REG_OFFSET 0x58 #define SLI_INTF_VALID_MASK 0xE0000000 #define SLI_INTF_VALID 0xC0000000 #define SLI_INTF_HINT2_MASK 0x1F000000 #define SLI_INTF_HINT2_SHIFT 24 #define SLI_INTF_HINT1_MASK 0x00FF0000 #define SLI_INTF_HINT1_SHIFT 16 #define SLI_INTF_FAMILY_MASK 0x00000F00 #define SLI_INTF_FAMILY_SHIFT 8 #define SLI_INTF_IF_TYPE_MASK 0x0000F000 #define SLI_INTF_IF_TYPE_SHIFT 12 #define SLI_INTF_REV_MASK 0x000000F0 #define SLI_INTF_REV_SHIFT 4 #define SLI_INTF_FT_MASK 0x00000001 #define SLI_INTF_TYPE_2 2 #define SLI_INTF_TYPE_3 3 /********* ISR0 Register offset **********/ #define CEV_ISR0_OFFSET 0xC18 #define CEV_ISR_SIZE 4 /********* Event Q door bell *************/ #define DB_EQ_OFFSET DB_CQ_OFFSET #define DB_EQ_RING_ID_MASK 0x1FF /* bits 0 - 8 */ #define DB_EQ_RING_ID_EXT_MASK 0x3e00 /* bits 9-13 */ #define DB_EQ_RING_ID_EXT_MASK_SHIFT (2) /* qid bits 9-13 placing at 11-15 */ /* Clear the interrupt for this eq */ #define DB_EQ_CLR_SHIFT (9) /* bit 9 */ /* Must be 1 */ #define DB_EQ_EVNT_SHIFT (10) /* bit 10 */ /* Number of event entries processed */ #define DB_EQ_NUM_POPPED_SHIFT (16) /* bits 16 - 28 */ /* Rearm bit */ #define DB_EQ_REARM_SHIFT (29) /* bit 29 */ /* Rearm to interrupt delay encoding */ #define DB_EQ_R2I_DLY_SHIFT (30) /* bits 30 - 31 */ /* Rearm to interrupt (R2I) delay multiplier encoding represents 3 different * values configured in CEV_REARM2IRPT_DLY_MULT_CSR register. This value is * programmed by host driver while ringing an EQ doorbell(EQ_DB) if a delay * between rearming the EQ and next interrupt on this EQ is desired. */ #define R2I_DLY_ENC_0 0 /* No delay */ #define R2I_DLY_ENC_1 1 /* maps to 160us EQ delay */ #define R2I_DLY_ENC_2 2 /* maps to 96us EQ delay */ #define R2I_DLY_ENC_3 3 /* maps to 48us EQ delay */ /********* Compl Q door bell *************/ #define DB_CQ_OFFSET 0x120 #define DB_CQ_RING_ID_MASK 0x3FF /* bits 0 - 9 */ #define DB_CQ_RING_ID_EXT_MASK 0x7C00 /* bits 10-14 */ #define DB_CQ_RING_ID_EXT_MASK_SHIFT (1) /* qid bits 10-14 placing at 11-15 */ /* Number of event entries processed */ #define DB_CQ_NUM_POPPED_SHIFT (16) /* bits 16 - 28 */ /* Rearm bit */ #define DB_CQ_REARM_SHIFT (29) /* bit 29 */ /********** TX ULP door bell *************/ #define DB_TXULP1_OFFSET 0x60 #define DB_TXULP_RING_ID_MASK 0x7FF /* bits 0 - 10 */ /* Number of tx entries posted */ #define DB_TXULP_NUM_POSTED_SHIFT (16) /* bits 16 - 29 */ #define DB_TXULP_NUM_POSTED_MASK 0x3FFF /* bits 16 - 29 */ /********** RQ(erx) door bell ************/ #define DB_RQ_OFFSET 0x100 #define DB_RQ_RING_ID_MASK 0x3FF /* bits 0 - 9 */ /* Number of rx frags posted */ #define DB_RQ_NUM_POSTED_SHIFT (24) /* bits 24 - 31 */ /********** MCC door bell ************/ #define DB_MCCQ_OFFSET 0x140 #define DB_MCCQ_RING_ID_MASK 0x7FF /* bits 0 - 10 */ /* Number of entries posted */ #define DB_MCCQ_NUM_POSTED_SHIFT (16) /* bits 16 - 29 */ /********** SRIOV VF PCICFG OFFSET ********/ #define SRIOV_VF_PCICFG_OFFSET (4096) /********** FAT TABLE ********/ #define RETRIEVE_FAT 0 #define QUERY_FAT 1 /************* Rx Packet Type Encoding **************/ #define BE_UNICAST_PACKET 0 #define BE_MULTICAST_PACKET 1 #define BE_BROADCAST_PACKET 2 #define BE_RSVD_PACKET 3 /* * BE descriptors: host memory data structures whose formats * are hardwired in BE silicon. */ /* Event Queue Descriptor */ #define EQ_ENTRY_VALID_MASK 0x1 /* bit 0 */ #define EQ_ENTRY_RES_ID_MASK 0xFFFF /* bits 16 - 31 */ #define EQ_ENTRY_RES_ID_SHIFT 16 struct be_eq_entry { u32 evt; }; /* TX Queue Descriptor */ #define ETH_WRB_FRAG_LEN_MASK 0xFFFF struct be_eth_wrb { __le32 frag_pa_hi; /* dword 0 */ __le32 frag_pa_lo; /* dword 1 */ u32 rsvd0; /* dword 2 */ __le32 frag_len; /* dword 3: bits 0 - 15 */ } __packed; /* Pseudo amap definition for eth_hdr_wrb in which each bit of the * actual structure is defined as a byte : used to calculate * offset/shift/mask of each field */ struct amap_eth_hdr_wrb { u8 rsvd0[32]; /* dword 0 */ u8 rsvd1[32]; /* dword 1 */ u8 complete; /* dword 2 */ u8 event; u8 crc; u8 forward; u8 lso6; u8 mgmt; u8 ipcs; u8 udpcs; u8 tcpcs; u8 lso; u8 vlan; u8 gso[2]; u8 num_wrb[5]; u8 lso_mss[14]; u8 len[16]; /* dword 3 */ u8 vlan_tag[16]; } __packed; #define TX_HDR_WRB_COMPL 1 /* word 2 */ #define TX_HDR_WRB_EVT BIT(1) /* word 2 */ #define TX_HDR_WRB_NUM_SHIFT 13 /* word 2: bits 13:17 */ #define TX_HDR_WRB_NUM_MASK 0x1F /* word 2: bits 13:17 */ struct be_eth_hdr_wrb { __le32 dw[4]; }; /********* Tx Compl Status Encoding *********/ #define BE_TX_COMP_HDR_PARSE_ERR 0x2 #define BE_TX_COMP_NDMA_ERR 0x3 #define BE_TX_COMP_ACL_ERR 0x5 #define LANCER_TX_COMP_LSO_ERR 0x1 #define LANCER_TX_COMP_HSW_DROP_MAC_ERR 0x3 #define LANCER_TX_COMP_HSW_DROP_VLAN_ERR 0x5 #define LANCER_TX_COMP_QINQ_ERR 0x7 #define LANCER_TX_COMP_PARITY_ERR 0xb #define LANCER_TX_COMP_DMA_ERR 0xd /* TX Compl Queue Descriptor */ /* Pseudo amap definition for eth_tx_compl in which each bit of the * actual structure is defined as a byte: used to calculate * offset/shift/mask of each field */ struct amap_eth_tx_compl { u8 wrb_index[16]; /* dword 0 */ u8 ct[2]; /* dword 0 */ u8 port[2]; /* dword 0 */ u8 rsvd0[8]; /* dword 0 */ u8 status[4]; /* dword 0 */ u8 user_bytes[16]; /* dword 1 */ u8 nwh_bytes[8]; /* dword 1 */ u8 lso; /* dword 1 */ u8 cast_enc[2]; /* dword 1 */ u8 rsvd1[5]; /* dword 1 */ u8 rsvd2[32]; /* dword 2 */ u8 pkts[16]; /* dword 3 */ u8 ringid[11]; /* dword 3 */ u8 hash_val[4]; /* dword 3 */ u8 valid; /* dword 3 */ } __packed; struct be_eth_tx_compl { u32 dw[4]; }; /* RX Queue Descriptor */ struct be_eth_rx_d { u32 fragpa_hi; u32 fragpa_lo; }; /* RX Compl Queue Descriptor */ /* Pseudo amap definition for BE2 and BE3 legacy mode eth_rx_compl in which * each bit of the actual structure is defined as a byte: used to calculate * offset/shift/mask of each field */ struct amap_eth_rx_compl_v0 { u8 vlan_tag[16]; /* dword 0 */ u8 pktsize[14]; /* dword 0 */ u8 port; /* dword 0 */ u8 ip_opt; /* dword 0 */ u8 err; /* dword 1 */ u8 rsshp; /* dword 1 */ u8 ipf; /* dword 1 */ u8 tcpf; /* dword 1 */ u8 udpf; /* dword 1 */ u8 ipcksm; /* dword 1 */ u8 l4_cksm; /* dword 1 */ u8 ip_version; /* dword 1 */ u8 macdst[6]; /* dword 1 */ u8 vtp; /* dword 1 */ u8 ip_frag; /* dword 1 */ u8 fragndx[10]; /* dword 1 */ u8 ct[2]; /* dword 1 */ u8 sw; /* dword 1 */ u8 numfrags[3]; /* dword 1 */ u8 rss_flush; /* dword 2 */ u8 cast_enc[2]; /* dword 2 */ u8 qnq; /* dword 2 */ u8 rss_bank; /* dword 2 */ u8 rsvd1[23]; /* dword 2 */ u8 lro_pkt; /* dword 2 */ u8 rsvd2[2]; /* dword 2 */ u8 valid; /* dword 2 */ u8 rsshash[32]; /* dword 3 */ } __packed; /* Pseudo amap definition for BE3 native mode eth_rx_compl in which * each bit of the actual structure is defined as a byte: used to calculate * offset/shift/mask of each field */ struct amap_eth_rx_compl_v1 { u8 vlan_tag[16]; /* dword 0 */ u8 pktsize[14]; /* dword 0 */ u8 vtp; /* dword 0 */ u8 ip_opt; /* dword 0 */ u8 err; /* dword 1 */ u8 rsshp; /* dword 1 */ u8 ipf; /* dword 1 */ u8 tcpf; /* dword 1 */ u8 udpf; /* dword 1 */ u8 ipcksm; /* dword 1 */ u8 l4_cksm; /* dword 1 */ u8 ip_version; /* dword 1 */ u8 macdst[7]; /* dword 1 */ u8 rsvd0; /* dword 1 */ u8 fragndx[10]; /* dword 1 */ u8 ct[2]; /* dword 1 */ u8 sw; /* dword 1 */ u8 numfrags[3]; /* dword 1 */ u8 rss_flush; /* dword 2 */ u8 cast_enc[2]; /* dword 2 */ u8 qnq; /* dword 2 */ u8 rss_bank; /* dword 2 */ u8 port[2]; /* dword 2 */ u8 vntagp; /* dword 2 */ u8 header_len[8]; /* dword 2 */ u8 header_split[2]; /* dword 2 */ u8 rsvd1[12]; /* dword 2 */ u8 tunneled; u8 valid; /* dword 2 */ u8 rsshash[32]; /* dword 3 */ } __packed; struct be_eth_rx_compl { u32 dw[4]; };
{ "pile_set_name": "Github" }
<template name="reactiveTableFilter"> <div id="{{id}}" class="{{class}}"> <span class="input-group-addon"> {{#if useFontAwesome}} <i class="fa fa-filter"></i> {{else}} {{#if label}} <span>{{label}}</span> {{else}} {{i18n 'reactiveTable.filter'}} {{/if}} {{/if}} </span> {{#if useFontAwesome}} {{#if label}} <input class="reactive-table-input form-control" type="text" value="{{filter}}" placeholder="{{label}}"> {{else}} <input class="reactive-table-input form-control" type="text" value="{{filter}}" placeholder="{{i18n 'reactiveTable.filter'}}"> {{/if}} {{else}} <input class="reactive-table-input form-control" type="text" value="{{filter}}"> {{/if}} </div> </template>
{ "pile_set_name": "Github" }
function! neoterm#term#vim#() abort return s:vim endfunction let s:vim = {} function! s:vim.new(opts) abort let l:opts = { \ 'curwin': 1, \ 'term_finish': 'close', \ 'term_name': a:opts.name, \ 'out_cb': a:opts.on_stdout, \ 'err_cb': a:opts.on_stderr, \ 'close_cb': a:opts.on_exit, \ 'exit_cb': a:opts.on_exit \ } return term_start(a:opts.shell, l:opts) endfunction function! s:vim.termsend(termid, command) abort let l:command = type(a:command) ==# type('') ? a:command : join(a:command, "\<CR>") return term_sendkeys(a:termid, l:command) endfunction function! s:vim.get_current_termid() abort return bufnr('') endfunction
{ "pile_set_name": "Github" }
/* * Copyright (C) 2017 Rob Clark <[email protected]> * * 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 (including the next * paragraph) 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. * * Authors: * Rob Clark <[email protected]> */ #include "util/u_blitter.h" #include "freedreno_blitter.h" #include "freedreno_context.h" /* generic blit using u_blitter.. slightly modified version of util_blitter_blit * which also handles PIPE_BUFFER: */ static void default_dst_texture(struct pipe_surface *dst_templ, struct pipe_resource *dst, unsigned dstlevel, unsigned dstz) { memset(dst_templ, 0, sizeof(*dst_templ)); if (dst->target == PIPE_BUFFER) dst_templ->format = PIPE_FORMAT_R8_UINT; else dst_templ->format = util_format_linear(dst->format); dst_templ->u.tex.level = dstlevel; dst_templ->u.tex.first_layer = dstz; dst_templ->u.tex.last_layer = dstz; } static void default_src_texture(struct pipe_sampler_view *src_templ, struct pipe_resource *src, unsigned srclevel) { bool cube_as_2darray = src->screen->get_param(src->screen, PIPE_CAP_SAMPLER_VIEW_TARGET); memset(src_templ, 0, sizeof(*src_templ)); if (cube_as_2darray && (src->target == PIPE_TEXTURE_CUBE || src->target == PIPE_TEXTURE_CUBE_ARRAY)) src_templ->target = PIPE_TEXTURE_2D_ARRAY; else src_templ->target = src->target; if (src->target == PIPE_BUFFER) { src_templ->target = PIPE_TEXTURE_1D; src_templ->format = PIPE_FORMAT_R8_UINT; } else { src_templ->format = util_format_linear(src->format); } src_templ->u.tex.first_level = srclevel; src_templ->u.tex.last_level = srclevel; src_templ->u.tex.first_layer = 0; src_templ->u.tex.last_layer = src->target == PIPE_TEXTURE_3D ? u_minify(src->depth0, srclevel) - 1 : (unsigned)(src->array_size - 1); src_templ->swizzle_r = PIPE_SWIZZLE_X; src_templ->swizzle_g = PIPE_SWIZZLE_Y; src_templ->swizzle_b = PIPE_SWIZZLE_Z; src_templ->swizzle_a = PIPE_SWIZZLE_W; } void fd_blitter_blit(struct fd_context *ctx, const struct pipe_blit_info *info) { struct pipe_resource *dst = info->dst.resource; struct pipe_resource *src = info->src.resource; struct pipe_context *pipe = &ctx->base; struct pipe_surface *dst_view, dst_templ; struct pipe_sampler_view src_templ, *src_view; /* Initialize the surface. */ default_dst_texture(&dst_templ, dst, info->dst.level, info->dst.box.z); dst_templ.format = info->dst.format; dst_view = pipe->create_surface(pipe, dst, &dst_templ); /* Initialize the sampler view. */ default_src_texture(&src_templ, src, info->src.level); src_templ.format = info->src.format; src_view = pipe->create_sampler_view(pipe, src, &src_templ); /* Copy. */ util_blitter_blit_generic(ctx->blitter, dst_view, &info->dst.box, src_view, &info->src.box, src->width0, src->height0, info->mask, info->filter, info->scissor_enable ? &info->scissor : NULL, info->alpha_blend); pipe_surface_reference(&dst_view, NULL); pipe_sampler_view_reference(&src_view, NULL); }
{ "pile_set_name": "Github" }
#include <string> #include <vector> #include "boost/algorithm/string.hpp" #include "google/protobuf/text_format.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/db.hpp" #include "caffe/util/format.hpp" #include "caffe/util/io.hpp" using caffe::Blob; using caffe::Caffe; using caffe::Datum; using caffe::Net; using std::string; namespace db = caffe::db; template<typename Dtype> int feature_extraction_pipeline(int argc, char** argv); int main(int argc, char** argv) { return feature_extraction_pipeline<float>(argc, argv); // return feature_extraction_pipeline<double>(argc, argv); } template<typename Dtype> int feature_extraction_pipeline(int argc, char** argv) { ::google::InitGoogleLogging(argv[0]); const int num_required_args = 7; if (argc < num_required_args) { LOG(ERROR)<< "This program takes in a trained network and an input data layer, and then" " extract features of the input data produced by the net.\n" "Usage: extract_features pretrained_net_param" " feature_extraction_proto_file extract_feature_blob_name1[,name2,...]" " save_feature_dataset_name1[,name2,...] num_mini_batches db_type" " [CPU/GPU] [DEVICE_ID=0]\n" "Note: you can extract multiple features in one pass by specifying" " multiple feature blob names and dataset names separated by ','." " The names cannot contain white space characters and the number of blobs" " and datasets must be equal."; return 1; } int arg_pos = num_required_args; arg_pos = num_required_args; if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) { LOG(ERROR)<< "Using GPU"; int device_id = 0; if (argc > arg_pos + 1) { device_id = atoi(argv[arg_pos + 1]); CHECK_GE(device_id, 0); } LOG(ERROR) << "Using Device_id=" << device_id; Caffe::SetDevice(device_id); Caffe::set_mode(Caffe::GPU); } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } arg_pos = 0; // the name of the executable std::string pretrained_binary_proto(argv[++arg_pos]); // Expected prototxt contains at least one data layer such as // the layer data_layer_name and one feature blob such as the // fc7 top blob to extract features. /* layers { name: "data_layer_name" type: DATA data_param { source: "/path/to/your/images/to/extract/feature/images_leveldb" mean_file: "/path/to/your/image_mean.binaryproto" batch_size: 128 crop_size: 227 mirror: false } top: "data_blob_name" top: "label_blob_name" } layers { name: "drop7" type: DROPOUT dropout_param { dropout_ratio: 0.5 } bottom: "fc7" top: "fc7" } */ std::string feature_extraction_proto(argv[++arg_pos]); boost::shared_ptr<Net<Dtype> > feature_extraction_net( new Net<Dtype>(feature_extraction_proto, caffe::TEST)); feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto); std::string extract_feature_blob_names(argv[++arg_pos]); std::vector<std::string> blob_names; boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(",")); std::string save_feature_dataset_names(argv[++arg_pos]); std::vector<std::string> dataset_names; boost::split(dataset_names, save_feature_dataset_names, boost::is_any_of(",")); CHECK_EQ(blob_names.size(), dataset_names.size()) << " the number of blob names and dataset names must be equal"; size_t num_features = blob_names.size(); for (size_t i = 0; i < num_features; i++) { CHECK(feature_extraction_net->has_blob(blob_names[i])) << "Unknown feature blob name " << blob_names[i] << " in the network " << feature_extraction_proto; } int num_mini_batches = atoi(argv[++arg_pos]); std::vector<boost::shared_ptr<db::DB> > feature_dbs; std::vector<boost::shared_ptr<db::Transaction> > txns; const char* db_type = argv[++arg_pos]; for (size_t i = 0; i < num_features; ++i) { LOG(INFO)<< "Opening dataset " << dataset_names[i]; boost::shared_ptr<db::DB> db(db::GetDB(db_type)); db->Open(dataset_names.at(i), db::NEW); feature_dbs.push_back(db); boost::shared_ptr<db::Transaction> txn(db->NewTransaction()); txns.push_back(txn); } LOG(ERROR)<< "Extracting Features"; Datum datum; std::vector<int> image_indices(num_features, 0); for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) { feature_extraction_net->Forward(); for (int i = 0; i < num_features; ++i) { const boost::shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net->blob_by_name(blob_names[i]); int batch_size = feature_blob->num(); int dim_features = feature_blob->count() / batch_size; const Dtype* feature_blob_data; for (int n = 0; n < batch_size; ++n) { datum.set_height(feature_blob->height()); datum.set_width(feature_blob->width()); datum.set_channels(feature_blob->channels()); datum.clear_data(); datum.clear_float_data(); feature_blob_data = feature_blob->cpu_data() + feature_blob->offset(n); for (int d = 0; d < dim_features; ++d) { datum.add_float_data(feature_blob_data[d]); } string key_str = caffe::format_int(image_indices[i], 10); string out; CHECK(datum.SerializeToString(&out)); txns.at(i)->Put(key_str, out); ++image_indices[i]; if (image_indices[i] % 1000 == 0) { txns.at(i)->Commit(); txns.at(i).reset(feature_dbs.at(i)->NewTransaction()); LOG(ERROR)<< "Extracted features of " << image_indices[i] << " query images for feature blob " << blob_names[i]; } } // for (int n = 0; n < batch_size; ++n) } // for (int i = 0; i < num_features; ++i) } // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) // write the last batch for (int i = 0; i < num_features; ++i) { if (image_indices[i] % 1000 != 0) { txns.at(i)->Commit(); } LOG(ERROR)<< "Extracted features of " << image_indices[i] << " query images for feature blob " << blob_names[i]; feature_dbs.at(i)->Close(); } LOG(ERROR)<< "Successfully extracted the features!"; return 0; }
{ "pile_set_name": "Github" }
<html lang="en"> <head> <title>Output Section Type - Untitled</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Untitled"> <meta name="generator" content="makeinfo 4.7"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Output-Section-Attributes.html#Output-Section-Attributes" title="Output Section Attributes"> <link rel="next" href="Output-Section-LMA.html#Output-Section-LMA" title="Output Section LMA"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU linker LD (GNU Binutils) version 2.19. Copyright (C) 1991, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family: serif; font-weight: normal; } --></style> </head> <body> <div class="node"> <p> <a name="Output-Section-Type"></a>Next:&nbsp;<a rel="next" accesskey="n" href="Output-Section-LMA.html#Output-Section-LMA">Output Section LMA</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Output-Section-Attributes.html#Output-Section-Attributes">Output Section Attributes</a> <hr><br> </div> <h5 class="subsubsection">3.6.8.1 Output Section Type</h5> <p>Each output section may have a type. The type is a keyword in parentheses. The following types are defined: <dl> <dt><code>NOLOAD</code><dd>The section should be marked as not loadable, so that it will not be loaded into memory when the program is run. <br><dt><code>DSECT</code><dt><code>COPY</code><dt><code>INFO</code><dt><code>OVERLAY</code><dd>These type names are supported for backward compatibility, and are rarely used. They all have the same effect: the section should be marked as not allocatable, so that no memory is allocated for the section when the program is run. </dl> <p><a name="index-NOLOAD-405"></a><a name="index-prevent-unnecessary-loading-406"></a><a name="index-loading_002c-preventing-407"></a>The linker normally sets the attributes of an output section based on the input sections which map into it. You can override this by using the section type. For example, in the script sample below, the <span class="samp">ROM</span> section is addressed at memory location <span class="samp">0</span> and does not need to be loaded when the program is run. The contents of the <span class="samp">ROM</span> section will appear in the linker output file as usual. <pre class="smallexample"> SECTIONS { ROM 0 (NOLOAD) : { ... } ... } </pre> </body></html>
{ "pile_set_name": "Github" }
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Event Types. */ goog.provide('goog.events.EventType'); goog.provide('goog.events.MouseAsMouseEventType'); goog.provide('goog.events.MouseEvents'); goog.provide('goog.events.PointerAsMouseEventType'); goog.provide('goog.events.PointerAsTouchEventType'); goog.provide('goog.events.PointerFallbackEventType'); goog.provide('goog.events.PointerTouchFallbackEventType'); goog.require('goog.events.BrowserFeature'); goog.require('goog.userAgent'); /** * Returns a prefixed event name for the current browser. * @param {string} eventName The name of the event. * @return {string} The prefixed event name. * @private */ goog.events.getVendorPrefixedName_ = function(eventName) { 'use strict'; return goog.userAgent.WEBKIT ? 'webkit' + eventName : (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() : eventName.toLowerCase()); }; /** * Constants for event names. * @enum {string} */ goog.events.EventType = { // Mouse events CLICK: 'click', RIGHTCLICK: 'rightclick', DBLCLICK: 'dblclick', AUXCLICK: 'auxclick', MOUSEDOWN: 'mousedown', MOUSEUP: 'mouseup', MOUSEOVER: 'mouseover', MOUSEOUT: 'mouseout', MOUSEMOVE: 'mousemove', MOUSEENTER: 'mouseenter', MOUSELEAVE: 'mouseleave', // Non-existent event; will never fire. This exists as a mouse counterpart to // POINTERCANCEL. MOUSECANCEL: 'mousecancel', // Selection events. // https://www.w3.org/TR/selection-api/ SELECTIONCHANGE: 'selectionchange', SELECTSTART: 'selectstart', // IE, Safari, Chrome // Wheel events // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents WHEEL: 'wheel', // Key events KEYPRESS: 'keypress', KEYDOWN: 'keydown', KEYUP: 'keyup', // Focus BLUR: 'blur', FOCUS: 'focus', DEACTIVATE: 'deactivate', // IE only FOCUSIN: 'focusin', FOCUSOUT: 'focusout', // Forms CHANGE: 'change', RESET: 'reset', SELECT: 'select', SUBMIT: 'submit', INPUT: 'input', PROPERTYCHANGE: 'propertychange', // IE only // Drag and drop DRAGSTART: 'dragstart', DRAG: 'drag', DRAGENTER: 'dragenter', DRAGOVER: 'dragover', DRAGLEAVE: 'dragleave', DROP: 'drop', DRAGEND: 'dragend', // Touch events // Note that other touch events exist, but we should follow the W3C list here. // http://www.w3.org/TR/touch-events/#list-of-touchevent-types TOUCHSTART: 'touchstart', TOUCHMOVE: 'touchmove', TOUCHEND: 'touchend', TOUCHCANCEL: 'touchcancel', // Misc BEFOREUNLOAD: 'beforeunload', CONSOLEMESSAGE: 'consolemessage', CONTEXTMENU: 'contextmenu', DEVICECHANGE: 'devicechange', DEVICEMOTION: 'devicemotion', DEVICEORIENTATION: 'deviceorientation', DOMCONTENTLOADED: 'DOMContentLoaded', ERROR: 'error', HELP: 'help', LOAD: 'load', LOSECAPTURE: 'losecapture', ORIENTATIONCHANGE: 'orientationchange', READYSTATECHANGE: 'readystatechange', RESIZE: 'resize', SCROLL: 'scroll', UNLOAD: 'unload', // Media events CANPLAY: 'canplay', CANPLAYTHROUGH: 'canplaythrough', DURATIONCHANGE: 'durationchange', EMPTIED: 'emptied', ENDED: 'ended', LOADEDDATA: 'loadeddata', LOADEDMETADATA: 'loadedmetadata', PAUSE: 'pause', PLAY: 'play', PLAYING: 'playing', PROGRESS: 'progress', RATECHANGE: 'ratechange', SEEKED: 'seeked', SEEKING: 'seeking', STALLED: 'stalled', SUSPEND: 'suspend', TIMEUPDATE: 'timeupdate', VOLUMECHANGE: 'volumechange', WAITING: 'waiting', // Media Source Extensions events // https://www.w3.org/TR/media-source/#mediasource-events SOURCEOPEN: 'sourceopen', SOURCEENDED: 'sourceended', SOURCECLOSED: 'sourceclosed', // https://www.w3.org/TR/media-source/#sourcebuffer-events ABORT: 'abort', UPDATE: 'update', UPDATESTART: 'updatestart', UPDATEEND: 'updateend', // HTML 5 History events // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0 HASHCHANGE: 'hashchange', PAGEHIDE: 'pagehide', PAGESHOW: 'pageshow', POPSTATE: 'popstate', // Copy and Paste // Support is limited. Make sure it works on your favorite browser // before using. // http://www.quirksmode.org/dom/events/cutcopypaste.html COPY: 'copy', PASTE: 'paste', CUT: 'cut', BEFORECOPY: 'beforecopy', BEFORECUT: 'beforecut', BEFOREPASTE: 'beforepaste', // HTML5 online/offline events. // http://www.w3.org/TR/offline-webapps/#related ONLINE: 'online', OFFLINE: 'offline', // HTML 5 worker events MESSAGE: 'message', CONNECT: 'connect', // Service Worker Events - ServiceWorkerGlobalScope context // See https://w3c.github.io/ServiceWorker/#execution-context-events // Note: message event defined in worker events section INSTALL: 'install', ACTIVATE: 'activate', FETCH: 'fetch', FOREIGNFETCH: 'foreignfetch', MESSAGEERROR: 'messageerror', // Service Worker Events - Document context // See https://w3c.github.io/ServiceWorker/#document-context-events STATECHANGE: 'statechange', UPDATEFOUND: 'updatefound', CONTROLLERCHANGE: 'controllerchange', // CSS animation events. ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'), ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'), ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'), // CSS transition events. Based on the browser support described at: // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'), // W3C Pointer Events // http://www.w3.org/TR/pointerevents/ POINTERDOWN: 'pointerdown', POINTERUP: 'pointerup', POINTERCANCEL: 'pointercancel', POINTERMOVE: 'pointermove', POINTEROVER: 'pointerover', POINTEROUT: 'pointerout', POINTERENTER: 'pointerenter', POINTERLEAVE: 'pointerleave', GOTPOINTERCAPTURE: 'gotpointercapture', LOSTPOINTERCAPTURE: 'lostpointercapture', // IE specific events. // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx // Note: these events will be supplanted in IE11. MSGESTURECHANGE: 'MSGestureChange', MSGESTUREEND: 'MSGestureEnd', MSGESTUREHOLD: 'MSGestureHold', MSGESTURESTART: 'MSGestureStart', MSGESTURETAP: 'MSGestureTap', MSGOTPOINTERCAPTURE: 'MSGotPointerCapture', MSINERTIASTART: 'MSInertiaStart', MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture', MSPOINTERCANCEL: 'MSPointerCancel', MSPOINTERDOWN: 'MSPointerDown', MSPOINTERENTER: 'MSPointerEnter', MSPOINTERHOVER: 'MSPointerHover', MSPOINTERLEAVE: 'MSPointerLeave', MSPOINTERMOVE: 'MSPointerMove', MSPOINTEROUT: 'MSPointerOut', MSPOINTEROVER: 'MSPointerOver', MSPOINTERUP: 'MSPointerUp', // Native IMEs/input tools events. TEXT: 'text', // The textInput event is supported in IE9+, but only in lower case. All other // browsers use the camel-case event name. TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput', COMPOSITIONSTART: 'compositionstart', COMPOSITIONUPDATE: 'compositionupdate', COMPOSITIONEND: 'compositionend', // The beforeinput event is initially only supported in Safari. See // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome // implementation tracking. BEFOREINPUT: 'beforeinput', // Webview tag events // See https://developer.chrome.com/apps/tags/webview EXIT: 'exit', LOADABORT: 'loadabort', LOADCOMMIT: 'loadcommit', LOADREDIRECT: 'loadredirect', LOADSTART: 'loadstart', LOADSTOP: 'loadstop', RESPONSIVE: 'responsive', SIZECHANGED: 'sizechanged', UNRESPONSIVE: 'unresponsive', // HTML5 Page Visibility API. See details at // `goog.labs.dom.PageVisibilityMonitor`. VISIBILITYCHANGE: 'visibilitychange', // LocalStorage event. STORAGE: 'storage', // DOM Level 2 mutation events (deprecated). DOMSUBTREEMODIFIED: 'DOMSubtreeModified', DOMNODEINSERTED: 'DOMNodeInserted', DOMNODEREMOVED: 'DOMNodeRemoved', DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument', DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument', DOMATTRMODIFIED: 'DOMAttrModified', DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified', // Print events. BEFOREPRINT: 'beforeprint', AFTERPRINT: 'afterprint', // Web app manifest events. BEFOREINSTALLPROMPT: 'beforeinstallprompt', APPINSTALLED: 'appinstalled' }; /** * Returns one of the given pointer fallback event names in order of preference: * 1. pointerEventName * 2. msPointerEventName * 3. fallbackEventName * @param {string} pointerEventName * @param {string} msPointerEventName * @param {string} fallbackEventName * @return {string} The supported pointer or fallback (mouse or touch) event * name. * @private */ goog.events.getPointerFallbackEventName_ = function( pointerEventName, msPointerEventName, fallbackEventName) { 'use strict'; if (goog.events.BrowserFeature.POINTER_EVENTS) { return pointerEventName; } if (goog.events.BrowserFeature.MSPOINTER_EVENTS) { return msPointerEventName; } return fallbackEventName; }; /** * Constants for pointer event names that fall back to corresponding mouse event * names on unsupported platforms. These are intended to be drop-in replacements * for corresponding values in `goog.events.EventType`. * @enum {string} */ goog.events.PointerFallbackEventType = { POINTERDOWN: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN, goog.events.EventType.MOUSEDOWN), POINTERUP: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP, goog.events.EventType.MOUSEUP), POINTERCANCEL: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERCANCEL, goog.events.EventType.MSPOINTERCANCEL, // When falling back to mouse events, there is no MOUSECANCEL equivalent // of POINTERCANCEL. In this case POINTERUP already falls back to MOUSEUP // which represents both UP and CANCEL. POINTERCANCEL does not fall back // to MOUSEUP to prevent listening twice on the same event. goog.events.EventType.MOUSECANCEL), POINTERMOVE: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE, goog.events.EventType.MOUSEMOVE), POINTEROVER: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTEROVER, goog.events.EventType.MSPOINTEROVER, goog.events.EventType.MOUSEOVER), POINTEROUT: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTEROUT, goog.events.EventType.MSPOINTEROUT, goog.events.EventType.MOUSEOUT), POINTERENTER: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERENTER, goog.events.EventType.MSPOINTERENTER, goog.events.EventType.MOUSEENTER), POINTERLEAVE: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERLEAVE, goog.events.EventType.MSPOINTERLEAVE, goog.events.EventType.MOUSELEAVE) }; /** * Constants for pointer event names that fall back to corresponding touch event * names on unsupported platforms. These are intended to be drop-in replacements * for corresponding values in `goog.events.EventType`. * @enum {string} */ goog.events.PointerTouchFallbackEventType = { POINTERDOWN: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN, goog.events.EventType.TOUCHSTART), POINTERUP: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP, goog.events.EventType.TOUCHEND), POINTERCANCEL: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERCANCEL, goog.events.EventType.MSPOINTERCANCEL, goog.events.EventType.TOUCHCANCEL), POINTERMOVE: goog.events.getPointerFallbackEventName_( goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE, goog.events.EventType.TOUCHMOVE) }; /** * Mapping of mouse event names to underlying browser event names. * @typedef {{ * MOUSEDOWN: string, * MOUSEUP: string, * MOUSECANCEL:string, * MOUSEMOVE:string, * MOUSEOVER:string, * MOUSEOUT:string, * MOUSEENTER:string, * MOUSELEAVE: string, * }} */ goog.events.MouseEvents; /** * An alias for `goog.events.EventType.MOUSE*` event types that is overridden by * corresponding `POINTER*` event types. * @const {!goog.events.MouseEvents} */ goog.events.PointerAsMouseEventType = { MOUSEDOWN: goog.events.PointerFallbackEventType.POINTERDOWN, MOUSEUP: goog.events.PointerFallbackEventType.POINTERUP, MOUSECANCEL: goog.events.PointerFallbackEventType.POINTERCANCEL, MOUSEMOVE: goog.events.PointerFallbackEventType.POINTERMOVE, MOUSEOVER: goog.events.PointerFallbackEventType.POINTEROVER, MOUSEOUT: goog.events.PointerFallbackEventType.POINTEROUT, MOUSEENTER: goog.events.PointerFallbackEventType.POINTERENTER, MOUSELEAVE: goog.events.PointerFallbackEventType.POINTERLEAVE }; /** * An alias for `goog.events.EventType.MOUSE*` event types that continue to use * mouse events. * @const {!goog.events.MouseEvents} */ goog.events.MouseAsMouseEventType = { MOUSEDOWN: goog.events.EventType.MOUSEDOWN, MOUSEUP: goog.events.EventType.MOUSEUP, MOUSECANCEL: goog.events.EventType.MOUSECANCEL, MOUSEMOVE: goog.events.EventType.MOUSEMOVE, MOUSEOVER: goog.events.EventType.MOUSEOVER, MOUSEOUT: goog.events.EventType.MOUSEOUT, MOUSEENTER: goog.events.EventType.MOUSEENTER, MOUSELEAVE: goog.events.EventType.MOUSELEAVE }; /** * An alias for `goog.events.EventType.TOUCH*` event types that is overridden by * corresponding `POINTER*` event types. * @enum {string} */ goog.events.PointerAsTouchEventType = { TOUCHCANCEL: goog.events.PointerTouchFallbackEventType.POINTERCANCEL, TOUCHEND: goog.events.PointerTouchFallbackEventType.POINTERUP, TOUCHMOVE: goog.events.PointerTouchFallbackEventType.POINTERMOVE, TOUCHSTART: goog.events.PointerTouchFallbackEventType.POINTERDOWN };
{ "pile_set_name": "Github" }
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package herddb.cli; import java.util.ArrayList; import java.util.List; /** * Rewrites MySQL dump INSERT statements in order to leverage PreparedStatement feature, and so "cache" the execution * plan * * @author enrico.olivelli */ public class MySqlDumpInsertStatementRewriter { static final int STATE_START_RECORD = 0; static final int STATE_IN_VALUE = 1; static final int STATE_IN_STRING_VALUE = 2; static final int STATE_IN_NUMERIC_VALUE = 3; static final int STATE_IN_NULL_VALUE = 4; static final int STATE_IN_NULL_VALUE_1 = 40; static final int STATE_IN_NULL_VALUE_2 = 41; static final int STATE_IN_NULL_VALUE_3 = 42; static final int STATE_END_VALUE = 5; public static QueryWithParameters rewriteSimpleInsertStatement(String query) { if (!query.startsWith("INSERT INTO ")) { return null; } int startValues = query.indexOf("VALUES "); if (startValues <= 0) { return null; } String tableName = query.substring(12, startValues).trim(); List<Object> jdbcParameters = new ArrayList<>(); int pos = startValues + "VALUES ".length(); StringBuilder rewritten = new StringBuilder(query.substring(0, pos)); StringBuilder currentValue = new StringBuilder(); int end = query.length(); int state = STATE_START_RECORD; while (pos < end) { char c = query.charAt(pos++); switch (state) { case STATE_START_RECORD: { if (c == '(') { rewritten.append(c); state = STATE_IN_VALUE; } else if (c == ',') { rewritten.append(c); state = STATE_START_RECORD; } else { return null; } break; } case STATE_IN_VALUE: { if (c == '\'') { state = STATE_IN_STRING_VALUE; currentValue.setLength(0); } else if (Character.isDigit(c)) { state = STATE_IN_NUMERIC_VALUE; currentValue.setLength(0); currentValue.append(c); } else if (c == 'N' || c == 'n') { state = STATE_IN_NULL_VALUE; currentValue.setLength(0); } else { return null; } break; } case STATE_IN_NULL_VALUE: { if (c == 'U' || c == 'u') { state = STATE_IN_NULL_VALUE_1; } else { return null; } break; } case STATE_IN_NULL_VALUE_1: { if (c == 'L' || c == 'l') { state = STATE_IN_NULL_VALUE_2; } else { return null; } break; } case STATE_IN_NULL_VALUE_2: { if (c == 'L' || c == 'l') { state = STATE_IN_NULL_VALUE_3; } else { return null; } break; } case STATE_IN_NULL_VALUE_3: { if (c == ',') { jdbcParameters.add(null); rewritten.append("?,"); currentValue.setLength(0); state = STATE_IN_VALUE; break; } else if (c == ')') { jdbcParameters.add(null); rewritten.append("?)"); currentValue.setLength(0); state = STATE_START_RECORD; break; } else { currentValue.append(c); } break; } case STATE_IN_STRING_VALUE: { if (c == '\'') { if (query.charAt(pos) == '\'') { // sql escape of '' syntax currentValue.append('\''); pos++; } else { jdbcParameters.add(currentValue.toString()); rewritten.append('?'); currentValue.setLength(0); state = STATE_END_VALUE; } break; } else { currentValue.append(c); } break; } case STATE_IN_NUMERIC_VALUE: { if (c == ',') { Number value; try { value = Long.parseLong(currentValue.toString()); } catch (NumberFormatException bigNumber) { try { value = Double.parseDouble(currentValue.toString()); } catch (NumberFormatException noAgain) { return null; } } jdbcParameters.add(value); rewritten.append("?,"); currentValue.setLength(0); state = STATE_IN_VALUE; break; } else if (c == ')') { Number value; try { value = Long.parseLong(currentValue.toString()); } catch (NumberFormatException bigNumber) { try { value = Double.parseDouble(currentValue.toString()); } catch (NumberFormatException noAgain) { return null; } } jdbcParameters.add(value); rewritten.append("?)"); currentValue.setLength(0); state = STATE_START_RECORD; break; } else { currentValue.append(c); } break; } case STATE_END_VALUE: if (c == ',') { rewritten.append(','); state = STATE_IN_VALUE; } else if (c == ')') { rewritten.append(')'); state = STATE_START_RECORD; } else { return null; } break; default: throw new IllegalStateException(state + " at pos:" + pos); } } if (state != STATE_START_RECORD) { return null; } return new QueryWithParameters(rewritten.toString(), tableName, jdbcParameters, null); } }
{ "pile_set_name": "Github" }
/* Fontname: -Misc-Fixed-Medium-R-Normal--8-80-75-75-C-50-ISO10646-1 Copyright: Public domain font. Share and enjoy. Glyphs: 95/1426 BBX Build Mode: 3 */ const uint8_t u8x8_font_5x8_r[764] U8X8_FONT_SECTION("u8x8_font_5x8_r") = " ~\1\1\0\0\0\0\0\0\0\0\0\0^\0\0\0\0\0\0\16\0\16\0\0\0\0\24\177\24\177" "\24\0\0\0\4*\177*\20\0\0\0\0\26\10\64\0\0\0\0\66I\66@\0\0\0\0\0\0\16\0" "\0\0\0\0\0<B\0\0\0\0\0\0B<\0\0\0\0\0T\70\70T\0\0\0\0\20\20|\20" "\20\0\0\0\0\200` \0\0\0\0\20\20\20\20\0\0\0\0\0@\340@\0\0\0\0`\20\10\6" "\0\0\0\0\0<B<\0\0\0\0\0D~@\0\0\0\0dRRL\0\0\0\0\42JN\62" "\0\0\0\0\30\24~\20\0\0\0\0.JJ\62\0\0\0\0<JJ\60\0\0\0\0\2b\32\6" "\0\0\0\0\64JJ\64\0\0\0\0\14RR<\0\0\0\0\0ll\0\0\0\0\0\0\200l," "\0\0\0\0\0\30$B\0\0\0\0((((\0\0\0\0\0B$\30\0\0\0\0\0\4R\14" "\0\0\0\0<B\231\245\36\0\0\0|\22\22|\0\0\0\0~JJ\64\0\0\0\0<BB$" "\0\0\0\0~BB<\0\0\0\0~JJB\0\0\0\0~\12\12\2\0\0\0\0<BR\64" "\0\0\0\0~\10\10~\0\0\0\0\0B~B\0\0\0\0 B>\2\0\0\0\0~\10\64B" "\0\0\0\0~@@@\0\0\0\0~\14\14~\0\0\0\0~\14\70~\0\0\0\0<BB<" "\0\0\0\0~\22\22\14\0\0\0\0<Rb\274\0\0\0\0~\22\22l\0\0\0\0$JR$" "\0\0\0\0\0\2~\2\0\0\0\0>@@>\0\0\0\0\36``\36\0\0\0\0~\60\60~" "\0\0\0\0f\30\30f\0\0\0\0\6\10p\10\6\0\0\0bRJF\0\0\0\0\0~BB" "\0\0\0\0\6\10\20`\0\0\0\0\0BB~\0\0\0\0\0\4\2\4\0\0\0\0\200\200\200\200" "\0\0\0\0\0\2\4\0\0\0\0\0\60HHx\0\0\0\0~HH\60\0\0\0\0\0\60HH" "\0\0\0\0\60HH~\0\0\0\0\60hX\20\0\0\0\0\20|\22\4\0\0\0\0\20\250\250p" "\0\0\0\0~\10\10p\0\0\0\0\0Hz@\0\0\0\0\0@\200z\0\0\0\0~\20\20h" "\0\0\0\0\0B~@\0\0\0\0x\10p\10p\0\0\0x\10\10p\0\0\0\0\60HH\60" "\0\0\0\0\370((\20\0\0\0\0\20((\370\0\0\0\0x\20\10\20\0\0\0\0\0PX(" "\0\0\0\0\10>H \0\0\0\0\70@@x\0\0\0\0\0\70@\70\0\0\0\0\70@\60@" "\70\0\0\0H\60\60H\0\0\0\0X\240\240x\0\0\0\0HhXH\0\0\0\0\10*UA" "\0\0\0\0\0\0~\0\0\0\0\0AU*\10\0\0\0\0\4\2\4\2\0\0\0";
{ "pile_set_name": "Github" }
<?php /** * Smarty Internal Undefined * * Class to handle undefined method calls or calls to obsolete runtime extensions * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Undefined { /** * Name of undefined extension class * * @var string|null */ public $class = null; /** * Smarty_Internal_Undefined constructor. * * @param null|string $class name of undefined extension class */ public function __construct($class = null) { $this->class = $class; } /** * Wrapper for obsolete class Smarty_Internal_Runtime_ValidateCompiled * * @param \Smarty_Internal_Template $tpl * @param array $properties special template properties * @param bool $cache flag if called from cache file * * @return bool false */ public function decodeProperties(Smarty_Internal_Template $tpl, $properties, $cache = false) { if ($cache) { $tpl->cached->valid = false; } else { $tpl->mustCompile = true; } return false; } /** * Call error handler for undefined method * * @param string $name unknown method-name * @param array $args argument array * * @return mixed * @throws SmartyException */ public function __call($name, $args) { if (isset($this->class)) { throw new SmartyException("undefined extension class '{$this->class}'"); } else { throw new SmartyException(get_class($args[ 0 ]) . "->{$name}() undefined method"); } } }
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Green.Model.V20170823 { public class DescribeBizTypeSettingResponse : AcsResponse { private string requestId; private DescribeBizTypeSetting_Terrorism terrorism; private DescribeBizTypeSetting_Porn porn; private DescribeBizTypeSetting_Antispam antispam; private DescribeBizTypeSetting_Ad ad; public string RequestId { get { return requestId; } set { requestId = value; } } public DescribeBizTypeSetting_Terrorism Terrorism { get { return terrorism; } set { terrorism = value; } } public DescribeBizTypeSetting_Porn Porn { get { return porn; } set { porn = value; } } public DescribeBizTypeSetting_Antispam Antispam { get { return antispam; } set { antispam = value; } } public DescribeBizTypeSetting_Ad Ad { get { return ad; } set { ad = value; } } public class DescribeBizTypeSetting_Terrorism { private List<string> categories; public List<string> Categories { get { return categories; } set { categories = value; } } } public class DescribeBizTypeSetting_Porn { private List<string> categories1; public List<string> Categories1 { get { return categories1; } set { categories1 = value; } } } public class DescribeBizTypeSetting_Antispam { private List<string> categories2; public List<string> Categories2 { get { return categories2; } set { categories2 = value; } } } public class DescribeBizTypeSetting_Ad { private List<string> categories3; public List<string> Categories3 { get { return categories3; } set { categories3 = value; } } } } }
{ "pile_set_name": "Github" }
use std::{fmt, result::Result}; use crate::parser::{Lexer, LexerError, Spanning, Token}; /// Error while parsing a GraphQL query #[derive(Debug, PartialEq)] pub enum ParseError<'a> { /// An unexpected token occurred in the source UnexpectedToken(Token<'a>), /// The input source abruptly ended UnexpectedEndOfFile, /// An error during tokenization occurred LexerError(LexerError), /// A scalar of unexpected type occurred in the source ExpectedScalarError(&'static str), } #[doc(hidden)] pub type ParseResult<'a, T> = Result<Spanning<T>, Spanning<ParseError<'a>>>; #[doc(hidden)] pub type UnlocatedParseResult<'a, T> = Result<T, Spanning<ParseError<'a>>>; #[doc(hidden)] pub type OptionParseResult<'a, T> = Result<Option<Spanning<T>>, Spanning<ParseError<'a>>>; #[doc(hidden)] #[derive(Debug)] pub struct Parser<'a> { tokens: Vec<Spanning<Token<'a>>>, } impl<'a> Parser<'a> { #[doc(hidden)] pub fn new(lexer: &mut Lexer<'a>) -> Result<Parser<'a>, Spanning<LexerError>> { let mut tokens = Vec::new(); for res in lexer { match res { Ok(s) => tokens.push(s), Err(e) => return Err(e), } } Ok(Parser { tokens }) } #[doc(hidden)] pub fn peek(&self) -> &Spanning<Token<'a>> { &self.tokens[0] } #[doc(hidden)] pub fn next_token(&mut self) -> ParseResult<'a, Token<'a>> { if self.tokens.len() == 1 { Err(Spanning::start_end( &self.peek().start, &self.peek().end, ParseError::UnexpectedEndOfFile, )) } else { Ok(self.tokens.remove(0)) } } #[doc(hidden)] pub fn expect(&mut self, expected: &Token) -> ParseResult<'a, Token<'a>> { if &self.peek().item != expected { Err(self.next_token()?.map(ParseError::UnexpectedToken)) } else { self.next_token() } } #[doc(hidden)] pub fn skip( &mut self, expected: &Token, ) -> Result<Option<Spanning<Token<'a>>>, Spanning<ParseError<'a>>> { if &self.peek().item == expected { Ok(Some(self.next_token()?)) } else if self.peek().item == Token::EndOfFile { Err(Spanning::zero_width( &self.peek().start, ParseError::UnexpectedEndOfFile, )) } else { Ok(None) } } #[doc(hidden)] pub fn delimited_list<T, F>( &mut self, opening: &Token, parser: F, closing: &Token, ) -> ParseResult<'a, Vec<Spanning<T>>> where T: fmt::Debug, F: Fn(&mut Parser<'a>) -> ParseResult<'a, T>, { let Spanning { start: start_pos, .. } = self.expect(opening)?; let mut items = Vec::new(); loop { if let Some(Spanning { end: end_pos, .. }) = self.skip(closing)? { return Ok(Spanning::start_end(&start_pos, &end_pos, items)); } items.push(parser(self)?); } } #[doc(hidden)] pub fn delimited_nonempty_list<T, F>( &mut self, opening: &Token, parser: F, closing: &Token, ) -> ParseResult<'a, Vec<Spanning<T>>> where T: fmt::Debug, F: Fn(&mut Parser<'a>) -> ParseResult<'a, T>, { let Spanning { start: start_pos, .. } = self.expect(opening)?; let mut items = Vec::new(); loop { items.push(parser(self)?); if let Some(Spanning { end: end_pos, .. }) = self.skip(closing)? { return Ok(Spanning::start_end(&start_pos, &end_pos, items)); } } } #[doc(hidden)] pub fn unlocated_delimited_nonempty_list<T, F>( &mut self, opening: &Token, parser: F, closing: &Token, ) -> ParseResult<'a, Vec<T>> where T: fmt::Debug, F: Fn(&mut Parser<'a>) -> UnlocatedParseResult<'a, T>, { let Spanning { start: start_pos, .. } = self.expect(opening)?; let mut items = Vec::new(); loop { items.push(parser(self)?); if let Some(Spanning { end: end_pos, .. }) = self.skip(closing)? { return Ok(Spanning::start_end(&start_pos, &end_pos, items)); } } } #[doc(hidden)] pub fn expect_name(&mut self) -> ParseResult<'a, &'a str> { match *self.peek() { Spanning { item: Token::Name(_), .. } => Ok(self.next_token()?.map(|token| { if let Token::Name(name) = token { name } else { panic!("Internal parse error in `expect_name`"); } })), Spanning { item: Token::EndOfFile, .. } => Err(Spanning::start_end( &self.peek().start, &self.peek().end, ParseError::UnexpectedEndOfFile, )), _ => Err(self.next_token()?.map(ParseError::UnexpectedToken)), } } } impl<'a> fmt::Display for ParseError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ParseError::UnexpectedToken(ref token) => write!(f, "Unexpected \"{}\"", token), ParseError::UnexpectedEndOfFile => write!(f, "Unexpected end of input"), ParseError::LexerError(ref err) => err.fmt(f), ParseError::ExpectedScalarError(err) => err.fmt(f), } } } impl<'a> std::error::Error for ParseError<'a> {}
{ "pile_set_name": "Github" }
{ "type": "minecraft:crafting_shaped", "pattern": [ "#W#", "#W#" ], "key": { "#": { "tag": "forge:ingots/nether_brick" }, "W": { "item": "minecraft:nether_bricks" } }, "result": { "item": "quark:nether_brick_fence_gate" }, "conditions": [ { "type": "quark:flag", "flag": "nether_brick_fence_gate" } ] }
{ "pile_set_name": "Github" }
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) include $(LOCAL_PATH)/Config.mk LOCAL_MODULE:= clapack LOCAL_CFLAGS:= -O3 -fPIC LOCAL_SRC_FILES:= $(ALLOBJ) include $(BUILD_STATIC_LIBRARY)
{ "pile_set_name": "Github" }
{# Copyright 2019 Author: Vivek Kumar<[email protected]> Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. #} {% for result in details %} <div class="detailsClass" id="detailsModal{{ loop.index0 }}" style="display:none"> <table id="detailsTable" class="simpleTable detailsTable left-align-cells"> <tbody> <tr class="detailsRow detailsId{{ loop.index0 }}"> <th> Declared </th> <td> <span>{{ result.declaredLicense|e }}</span> </td> </tr> <tr class="detailsRow detailsId{{ loop.index0 }}"> <th> Source </th> <td> <span> <a href="{{ result.url }}" target="_blank" rel="noopener noreferrer">{{ result.url }}</a> </span> </td> </tr> <tr class="detailsRow detailsId{{ loop.index0 }}"> <th> Release </th> <td> <span>{{ result.release|e }}</span> </td> </tr> <tr class="detailsRow detailsId{{ loop.index0 }}"> <th> Files </th> <td> <span>{{ result.files }}</span> </td> </tr> <tr class="detailsRow detailsId{{ loop.index0 }}"> <th> Attributions </th> <td> <span>{{ result.attribution|e }}{% if result.attribution is not empty %}...{% endif %}</span> </td> </tr> <tr class="detailsRow detailsId{{ loop.index0 }}"> <th> Discovered </th> <td> <span>{{ result.discoveredLicenses|e }}{% if result.discoveredLicenses is not empty %}...{% endif %}</span> </td> </tr> </tbody> </table> {% endfor %} <input id="selectedDetailKey" type="hidden" name="selectedDetailKey" value="" />
{ "pile_set_name": "Github" }
int somedllfunc(void) { return 42; }
{ "pile_set_name": "Github" }
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ 'use strict'; var replace = String.prototype.replace; var percentTwenties = /%20/g; module.exports = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; },{}],2:[function(require,module,exports){ 'use strict'; var stringify = require('./stringify'); var parse = require('./parse'); var formats = require('./formats'); module.exports = { formats: formats, parse: parse, stringify: stringify }; },{"./formats":1,"./parse":3,"./stringify":4}],3:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; // This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the ✓ character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset); val = options.decoder(part.slice(pos + 1), defaults.decoder, charset); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (val && options.comma && val.indexOf(',') > -1) { val = val.split(','); } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; },{"./utils":5}],4:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, formatter: formats.formatters[formats['default']], // deprecated indices: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = obj.join(','); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (isArray(obj)) { pushToArray(values, stringify( obj[key], typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset )); } else { pushToArray(values, stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset )); } } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.formatter, options.encodeValuesOnly, options.charset )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('✓') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; },{"./formats":1,"./utils":5}],5:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, merge: merge }; },{}]},{},[2])(2) });
{ "pile_set_name": "Github" }
66.000000 0.000000
{ "pile_set_name": "Github" }
TITLE ../openssl/crypto/bn/asm/x86-gf2m.asm IF @Version LT 800 ECHO MASM version 8.00 or later is strongly recommended. ENDIF .686 .XMM IF @Version LT 800 XMMWORD STRUCT 16 DQ 2 dup (?) XMMWORD ENDS ENDIF .MODEL FLAT OPTION DOTNAME IF @Version LT 800 .text$ SEGMENT PAGE 'CODE' ELSE .text$ SEGMENT ALIGN(64) 'CODE' ENDIF ;EXTERN _OPENSSL_ia32cap_P:NEAR ALIGN 16 __mul_1x1_mmx PROC PRIVATE sub esp,36 mov ecx,eax lea edx,DWORD PTR [eax*1+eax] and ecx,1073741823 lea ebp,DWORD PTR [edx*1+edx] mov DWORD PTR [esp],0 and edx,2147483647 movd mm2,eax movd mm3,ebx mov DWORD PTR 4[esp],ecx xor ecx,edx pxor mm5,mm5 pxor mm4,mm4 mov DWORD PTR 8[esp],edx xor edx,ebp mov DWORD PTR 12[esp],ecx pcmpgtd mm5,mm2 paddd mm2,mm2 xor ecx,edx mov DWORD PTR 16[esp],ebp xor ebp,edx pand mm5,mm3 pcmpgtd mm4,mm2 mov DWORD PTR 20[esp],ecx xor ebp,ecx psllq mm5,31 pand mm4,mm3 mov DWORD PTR 24[esp],edx mov esi,7 mov DWORD PTR 28[esp],ebp mov ebp,esi and esi,ebx shr ebx,3 mov edi,ebp psllq mm4,30 and edi,ebx shr ebx,3 movd mm0,DWORD PTR [esi*4+esp] mov esi,ebp and esi,ebx shr ebx,3 movd mm2,DWORD PTR [edi*4+esp] mov edi,ebp psllq mm2,3 and edi,ebx shr ebx,3 pxor mm0,mm2 movd mm1,DWORD PTR [esi*4+esp] mov esi,ebp psllq mm1,6 and esi,ebx shr ebx,3 pxor mm0,mm1 movd mm2,DWORD PTR [edi*4+esp] mov edi,ebp psllq mm2,9 and edi,ebx shr ebx,3 pxor mm0,mm2 movd mm1,DWORD PTR [esi*4+esp] mov esi,ebp psllq mm1,12 and esi,ebx shr ebx,3 pxor mm0,mm1 movd mm2,DWORD PTR [edi*4+esp] mov edi,ebp psllq mm2,15 and edi,ebx shr ebx,3 pxor mm0,mm2 movd mm1,DWORD PTR [esi*4+esp] mov esi,ebp psllq mm1,18 and esi,ebx shr ebx,3 pxor mm0,mm1 movd mm2,DWORD PTR [edi*4+esp] mov edi,ebp psllq mm2,21 and edi,ebx shr ebx,3 pxor mm0,mm2 movd mm1,DWORD PTR [esi*4+esp] mov esi,ebp psllq mm1,24 and esi,ebx shr ebx,3 pxor mm0,mm1 movd mm2,DWORD PTR [edi*4+esp] pxor mm0,mm4 psllq mm2,27 pxor mm0,mm2 movd mm1,DWORD PTR [esi*4+esp] pxor mm0,mm5 psllq mm1,30 add esp,36 pxor mm0,mm1 ret __mul_1x1_mmx ENDP ALIGN 16 __mul_1x1_ialu PROC PRIVATE sub esp,36 mov ecx,eax lea edx,DWORD PTR [eax*1+eax] lea ebp,DWORD PTR [eax*4] and ecx,1073741823 lea edi,DWORD PTR [eax*1+eax] sar eax,31 mov DWORD PTR [esp],0 and edx,2147483647 mov DWORD PTR 4[esp],ecx xor ecx,edx mov DWORD PTR 8[esp],edx xor edx,ebp mov DWORD PTR 12[esp],ecx xor ecx,edx mov DWORD PTR 16[esp],ebp xor ebp,edx mov DWORD PTR 20[esp],ecx xor ebp,ecx sar edi,31 and eax,ebx mov DWORD PTR 24[esp],edx and edi,ebx mov DWORD PTR 28[esp],ebp mov edx,eax shl eax,31 mov ecx,edi shr edx,1 mov esi,7 shl edi,30 and esi,ebx shr ecx,2 xor eax,edi shr ebx,3 mov edi,7 and edi,ebx shr ebx,3 xor edx,ecx xor eax,DWORD PTR [esi*4+esp] mov esi,7 and esi,ebx shr ebx,3 mov ebp,DWORD PTR [edi*4+esp] mov edi,7 mov ecx,ebp shl ebp,3 and edi,ebx shr ecx,29 xor eax,ebp shr ebx,3 xor edx,ecx mov ecx,DWORD PTR [esi*4+esp] mov esi,7 mov ebp,ecx shl ecx,6 and esi,ebx shr ebp,26 xor eax,ecx shr ebx,3 xor edx,ebp mov ebp,DWORD PTR [edi*4+esp] mov edi,7 mov ecx,ebp shl ebp,9 and edi,ebx shr ecx,23 xor eax,ebp shr ebx,3 xor edx,ecx mov ecx,DWORD PTR [esi*4+esp] mov esi,7 mov ebp,ecx shl ecx,12 and esi,ebx shr ebp,20 xor eax,ecx shr ebx,3 xor edx,ebp mov ebp,DWORD PTR [edi*4+esp] mov edi,7 mov ecx,ebp shl ebp,15 and edi,ebx shr ecx,17 xor eax,ebp shr ebx,3 xor edx,ecx mov ecx,DWORD PTR [esi*4+esp] mov esi,7 mov ebp,ecx shl ecx,18 and esi,ebx shr ebp,14 xor eax,ecx shr ebx,3 xor edx,ebp mov ebp,DWORD PTR [edi*4+esp] mov edi,7 mov ecx,ebp shl ebp,21 and edi,ebx shr ecx,11 xor eax,ebp shr ebx,3 xor edx,ecx mov ecx,DWORD PTR [esi*4+esp] mov esi,7 mov ebp,ecx shl ecx,24 and esi,ebx shr ebp,8 xor eax,ecx shr ebx,3 xor edx,ebp mov ebp,DWORD PTR [edi*4+esp] mov ecx,ebp shl ebp,27 mov edi,DWORD PTR [esi*4+esp] shr ecx,5 mov esi,edi xor eax,ebp shl edi,30 xor edx,ecx shr esi,2 xor eax,edi xor edx,esi add esp,36 ret __mul_1x1_ialu ENDP ALIGN 16 _bn_GF2m_mul_2x2 PROC PUBLIC $L_bn_GF2m_mul_2x2_begin:: lea edx,DWORD PTR _OPENSSL_ia32cap_P mov eax,DWORD PTR [edx] mov edx,DWORD PTR 4[edx] test eax,8388608 jz $L000ialu test eax,16777216 jz $L001mmx test edx,2 jz $L001mmx movups xmm0,XMMWORD PTR 8[esp] shufps xmm0,xmm0,177 DB 102,15,58,68,192,1 mov eax,DWORD PTR 4[esp] movups XMMWORD PTR [eax],xmm0 ret ALIGN 16 $L001mmx: push ebp push ebx push esi push edi mov eax,DWORD PTR 24[esp] mov ebx,DWORD PTR 32[esp] call __mul_1x1_mmx movq mm7,mm0 mov eax,DWORD PTR 28[esp] mov ebx,DWORD PTR 36[esp] call __mul_1x1_mmx movq mm6,mm0 mov eax,DWORD PTR 24[esp] mov ebx,DWORD PTR 32[esp] xor eax,DWORD PTR 28[esp] xor ebx,DWORD PTR 36[esp] call __mul_1x1_mmx pxor mm0,mm7 mov eax,DWORD PTR 20[esp] pxor mm0,mm6 movq mm2,mm0 psllq mm0,32 pop edi psrlq mm2,32 pop esi pxor mm0,mm6 pop ebx pxor mm2,mm7 movq QWORD PTR [eax],mm0 pop ebp movq QWORD PTR 8[eax],mm2 emms ret ALIGN 16 $L000ialu: push ebp push ebx push esi push edi sub esp,20 mov eax,DWORD PTR 44[esp] mov ebx,DWORD PTR 52[esp] call __mul_1x1_ialu mov DWORD PTR 8[esp],eax mov DWORD PTR 12[esp],edx mov eax,DWORD PTR 48[esp] mov ebx,DWORD PTR 56[esp] call __mul_1x1_ialu mov DWORD PTR [esp],eax mov DWORD PTR 4[esp],edx mov eax,DWORD PTR 44[esp] mov ebx,DWORD PTR 52[esp] xor eax,DWORD PTR 48[esp] xor ebx,DWORD PTR 56[esp] call __mul_1x1_ialu mov ebp,DWORD PTR 40[esp] mov ebx,DWORD PTR [esp] mov ecx,DWORD PTR 4[esp] mov edi,DWORD PTR 8[esp] mov esi,DWORD PTR 12[esp] xor eax,edx xor edx,ecx xor eax,ebx mov DWORD PTR [ebp],ebx xor edx,edi mov DWORD PTR 12[ebp],esi xor eax,esi add esp,20 xor edx,esi pop edi xor eax,edx pop esi mov DWORD PTR 8[ebp],edx pop ebx mov DWORD PTR 4[ebp],eax pop ebp ret _bn_GF2m_mul_2x2 ENDP DB 71,70,40,50,94,109,41,32,77,117,108,116,105,112,108,105 DB 99,97,116,105,111,110,32,102,111,114,32,120,56,54,44,32 DB 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97 DB 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103 DB 62,0 .text$ ENDS .bss SEGMENT 'BSS' COMM _OPENSSL_ia32cap_P:DWORD:4 .bss ENDS END
{ "pile_set_name": "Github" }
c --------------------------------------------------------------------------- c CFL3D is a structured-grid, cell-centered, upwind-biased, Reynolds-averaged c Navier-Stokes (RANS) code. It can be run in parallel on multiple grid zones c with point-matched, patched, overset, or embedded connectivities. Both c multigrid and mesh sequencing are available in time-accurate or c steady-state modes. c c Copyright 2001 United States Government as represented by the Administrator c of the National Aeronautics and Space Administration. All Rights Reserved. c c The CFL3D platform is licensed under the Apache License, Version 2.0 c (the "License"); you may not use this file except in compliance with the c License. You may obtain a copy of the License at c http://www.apache.org/licenses/LICENSE-2.0. c c Unless required by applicable law or agreed to in writing, software c distributed under the License is distributed on an "AS IS" BASIS, WITHOUT c WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the c License for the specific language governing permissions and limitations c under the License. c --------------------------------------------------------------------------- c subroutine spltsg(iseg,ix1,ix2,indx,is,it,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) c c $Id$ c dimension nsubbl(mbloc),idobl(mbloc),nseg(mbloc),idno(mbloc), . ijk(6,mbloc),idseg(mbloc),idnext(mbloc) dimension imap(msegt,mtot),idbloc(mtot), . ivisb(msegt,mbloc),itrb(7,mbloc), . val(mtot),xdum(msegt,mtot), . iold(4,mtot),nxtseg(mtot),intrfc(mtot), . ipatch(mtot) c common /segment/ nsgtop c call mkseg(iseg,it,ns,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) c imap(ix2,iseg) = indx imap(ix1,ns) = indx if (imap(13,iseg).ne.0) then if (imap(ix1+11,iseg).ge.indx) then imap(13,iseg) = 0 else if (imap(ix2+11,iseg).gt.indx) then imap(ix2+11,iseg) = indx endif if (imap(ix2+11,ns).le.indx) then imap(13,ns) = 0 else if (imap(ix1+11,ns).lt.indx) then imap(ix1+11,ns) = indx endif endif iold(ix2-2,iseg) = iold(ix1-2,iseg) + (indx-imap(ix1,iseg)) iold(ix1-2,ns) = iold(ix2-2,iseg) jseg = intrfc(iseg) if (jseg.gt.0) then if (imap(8,iseg).gt.0) then jx1 = ix1 jx2 = ix2 is1 = ix1 + 6 is2 = ix2 + 6 else if (ix1.eq.3) then jx1 = 5 jx2 = 6 is1 = 11 is2 = 12 else jx1 = 3 jx2 = 4 is1 = 9 is2 = 10 endif ia = (imap(is2,iseg)-imap(is1,iseg)) / . (imap(ix2,ns)-imap(ix1,iseg)) ib = imap(is1,iseg) - ia*imap(ix1,iseg) jndx = ia*indx + ib if (iseg.eq.jseg) then if (jndx.gt.imap(is1,iseg)) then imap(is2,iseg) = jndx imap(is1,ns) = jndx intrfc(ns) = ns else if (jndx.eq.indx) then imap(is2,iseg) = jndx imap(is1,ns) = jndx intrfc(ns) = iseg intrfc(iseg) = ns else if (jndx.gt.indx) then call splt2(ns,ix1,ix2,jndx,it,it,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) imap(ix1,ns) = 1 imap(ix2,ns) = jndx - indx + 1 imap(is1,ns) = imap(ix2,ns) imap(is2,ns) = imap(ix1,ns) intrfc(ns) = ns imap(7,ns) = it imap(8,ns) = imap(2,ns) ns = nsgtop intrfc(ns) = iseg intrfc(iseg) = ns else if (jndx.lt.indx) then call splt2(iseg,ix1,ix2,jndx,is,is,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) nsold = ns ns = nsgtop imap(ix1,ns) = jndx imap(ix2,ns) = indx imap(is1,ns) = imap(ix2,ns) imap(is2,ns) = imap(ix1,ns) intrfc(ns) = ns imap(7,ns) = is imap(8,ns) = imap(2,ns) ns = nsold intrfc(ns) = iseg intrfc(iseg) = ns endif call renmbr(iseg,ix1,ix2,1,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) else imap(is2,iseg) = jndx imap(is1,ns) = jndx ibl = idbloc(jseg) call splt2(jseg,jx1,jx2,jndx,ibl,ibl,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) if (jndx.gt.imap(is1,iseg)) then intrfc(ns) = idseg(ibl) intrfc(idseg(ibl)) = ns intrfc(jseg) = iseg else intrfc(ns) = jseg intrfc(idseg(ibl)) = iseg intrfc(jseg) = ns intrfc(iseg) = idseg(ibl) endif call renmbr(iseg,ix1,ix2,1,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) endif endif call renmbr(ns,ix1,ix2,indx,mbloc,msegt,mtot, . imap,idbloc,ivisb,itrb,val,xdum,iold, . nxtseg,intrfc,ipatch,nsubbl,idobl, . nseg,idno,ijk,idseg,idnext) c return end
{ "pile_set_name": "Github" }
# PicoJSON - a C++ JSON parser / serializer Copyright &copy; 2009-2010 Cybozu Labs, Inc. Copyright &copy; 2011 Kazuho Oku ## Introduction PicoJSON is a tiny JSON parser / serializer for C++ with following properties: - header-file only - no external dependencies (only uses standard C++ libraries) - STL-frendly (arrays are represented by using std::vector, objects are std::map) - provides both pull interface and streaming (event-based) interface - licensed under the new BSD License ## Reading JSON using the pull interface There are two ways to use the pull (DOM-like) interface of picojson. One is to use operator&lt;&lt;, and the other is by specifying a set of iterators specifying the range from where the JSON stream should be read. <pre> picojson::value v; std::cin &gt;&gt; v; std::string err = picojson::get_last_error(); if (! err.empty()) { std::cerr &lt;&lt; err &lt;&lt; std::endl; } </pre> <pre> std::istream_iterator input(cin); picojson::value v; std::string err; input = picojson::parse(v, input, std::istream_iterator(), &err); if (! err.empty()) { std::cerr &lt;&lt; err &lt;&lt; std::endl; } </pre> <pre> const char* json = "{\"a\":1}"; picojson::value v; std::string err; picojson::parse(v, json, json + strlen(json), &err); if (! err.empty()) { std::cerr &lt;&lt; err &lt;&lt; std::endl; } </pre> ## Accessing the values Values of a JSON object is represented as instances of picojson::value class. <pre> namespace picojson { class value { ... public: typedef std::vector&lt;value&gt; array; typedef std::map&lt;std::string, value&gt; object; value(); // create a null object explicit value(bool b); // create a boolean object explicit value(double n); // create a number object explicit value(const std::string& s); // create a string object explicit value(const array& a); // create an array object explicit value(const object& o); // create an "object" bool is&lt;picojson::null&gt;() const; // check if the object is "null" bool is&lt;bool&gt;() const; // check if the object is a boolean const bool& get&lt;bool&gt;() const; // const accessor (usable only if the object is a boolean) bool& get&lt;bool&gt;(); // non-const accessor (usable only if the object is a boolean) bool is&lt;double&gt;() const; // check if the object is a number const double& get&lt;double&gt;() const; // const accessor (usable only if the object is a number) double& get&lt;double&gt;(); // non-const accessor (usable only if the object is a number) bool is&lt;std::string&gt;() const; // check if the object is a string const std::string& get&lt;std::string&gt;() const; // const accessor (usable only if the object is a string) std::string& get&lt;std::string&gt;(); // non-const accessor (usable only if the object is a string) bool is&lt;array&gt;() const; // check if the object is an array const array& get&lt;array&gt;() const; // const accessor (usable only if the object is an array) array& get&lt;array&gt;(); // non-const accessor (usable only if the object is an array) bool is&lt;object&gt;() const; // check if the object is an "object" const object& get&lt;object&gt;() const; // const accessor (usable only if the object is an object) object& get&lt;object&gt;(); // non-const accessor (usable only if the object is an array) bool evaluate_as_boolean() const; // evaluates the object as a boolean std::string serialize() const; // returns the object in JSON representation template<typename Iter> void serialize(Iter os) const; // serializes the object in JSON representation through an output iterator std::string to_str() const; // returns the object in string (for casual use) }; } </pre> The code below parses a JSON string and prints the contents of the object. <pre> picojson::value v; // parse the input std::cin &gt;&gt; v; std::string err = picojson::get_last_error(); if (! err.empty()) { std::cerr &lt;&lt; err &lt;&lt; std::endl; exit(1); } // check if the type of the value is "object" if (! v.is&lt;picojson::object&gt;()) { std::cerr &lt;&lt; "JSON is not an object" &lt;&lt; std::endl; exit(2); } // obtain a const reference to the map, and print the contents const picojson::value::object& obj = v.get&lt;picojson::object&gt;(); for (picojson::value::object::const_iterator i = obj.begin(); i != obj.end(); ++i) { std::cout &lt;&lt; i-&gt;first &lt;&lt; ': ' &lt;&lt; i-&gt;second.to_str() &lt;&lt; std::endl; } </pre> Please note that the type check is mandatory; do not forget to check the type of the object by calling is&lt;type&gt;() before accessing the value by calling get&lt;type&gt;(). ## Reading JSON using the streaming (event-driven) interface Please refer to the implementation of picojson::default_parse_context and picojson::null_parse_context. There is also an example (examples/streaming.cc) . ## Serializing to JSON Instances of the picojson::value class can be serialized in three ways, to ostream, to std::string, or to an output iterator. <pre> picojson::value v; ... std::cout &lt;&lt; v; </pre> <pre> picojson::value v; ... std::string json = v.serialize(); </pre> <pre> picojson::value v; ... v.serialize(std::ostream_iterator(std::cout)); </pre> ## Further reading Examples can be found in the <i>examples</i> directory.
{ "pile_set_name": "Github" }
#ifndef __PERF_CPUMAP_H #define __PERF_CPUMAP_H struct cpu_map { int nr; int map[]; }; struct cpu_map *cpu_map__new(const char *cpu_list); struct cpu_map *cpu_map__dummy_new(void); void cpu_map__delete(struct cpu_map *map); #endif /* __PERF_CPUMAP_H */
{ "pile_set_name": "Github" }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/prob.max_acc.R \name{prob.max_acc} \alias{prob.max_acc} \title{Probability binary accuracy} \usage{ prob.max_acc(preds, labels, thresh = 0.5) } \arguments{ \item{preds}{Type: numeric. The predictions.} \item{labels}{Type: numeric. The labels (0, 1).} \item{thresh}{Type: numeric. The cutoff (threshold) probability which is deemed positive when higher or equal, or negative when lower. Defaults to \code{0.5} (anything higher or equal to 0.5 is positive, anything lower is negative).} } \value{ The accuracy at the provided threshold. } \description{ This function allows to use a custom thresholding method to compute the binary accuracy. }
{ "pile_set_name": "Github" }
// Copyright 2018 The Go 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 xerrors // A Formatter formats error messages. type Formatter interface { error // FormatError prints the receiver's first error and returns the next error in // the error chain, if any. FormatError(p Printer) (next error) } // A Printer formats error messages. // // The most common implementation of Printer is the one provided by package fmt // during Printf (as of Go 1.13). Localization packages such as golang.org/x/text/message // typically provide their own implementations. type Printer interface { // Print appends args to the message output. Print(args ...interface{}) // Printf writes a formatted string. Printf(format string, args ...interface{}) // Detail reports whether error detail is requested. // After the first call to Detail, all text written to the Printer // is formatted as additional detail, or ignored when // detail has not been requested. // If Detail returns false, the caller can avoid printing the detail at all. Detail() bool }
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # # File : __init__.py # Author : Hang Gao # Email : [email protected] # Date : 12/26/2019 # # Distributed under terms of the MIT license. from .cond_conv import CondConv2d from .deform_conv import DeformConv2d from .deform_kernel import ( GlobalDeformKernel2d, LocalDeformKernel2d, DeformKernel2d, DeformKernelConv2d, ) __all__ = [ 'CondConv2d', 'DeformConv2d', 'GlobalDeformKernel2d', 'LocalDeformKernel2d', 'DeformKernel2d', 'DeformKernelConv2d', ]
{ "pile_set_name": "Github" }
/** * Copyright © MyCollab * * 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 com.mycollab.module.project.ui.format import com.hp.gagawa.java.elements.A import com.hp.gagawa.java.elements.Img import com.mycollab.core.utils.StringUtils import com.mycollab.html.DivLessFormatter import com.mycollab.module.file.service.AbstractStorageService import com.mycollab.module.user.domain.SimpleUser import com.mycollab.module.user.service.UserService import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.TooltipHelper import com.mycollab.vaadin.TooltipHelper.TOOLTIP_ID import com.mycollab.vaadin.UserUIContext import com.mycollab.vaadin.ui.formatter.HistoryFieldFormat import com.mycollab.vaadin.web.ui.WebThemes import org.slf4j.LoggerFactory /** * @author MyCollab Ltd. * @since 4.0 */ class ProjectMemberHistoryFieldFormat : HistoryFieldFormat { override fun toString(value: String): String = toString(UserUIContext.getUser(), value, true, "") override fun toString(currentViewUser:SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String { if (StringUtils.isBlank(value)) { return msgIfBlank } try { val userService = AppContextUtil.getSpringBean(UserService::class.java) val user = userService.findUserByUserNameInAccount(value, AppUI.accountId) if (user != null) { return if (displayAsHtml) { val userAvatar = Img("", AppContextUtil.getSpringBean(AbstractStorageService::class.java) .getAvatarPath(user.avatarid, 16)).setCSSClass(WebThemes.CIRCLE_BOX) val link = A().setId("tag" + TOOLTIP_ID).appendText(StringUtils.trim(user.displayName, 30, true)) link.setAttribute("onmouseover", TooltipHelper.userHoverJsFunction(user.username)) link.setAttribute("onmouseleave", TooltipHelper.itemMouseLeaveJsFunction()) DivLessFormatter().appendChild(userAvatar, DivLessFormatter.EMPTY_SPACE, link).write() } else user.displayName!! } } catch (e: Exception) { LOG.error("Error", e) } return value } companion object { private val LOG = LoggerFactory.getLogger(ProjectMemberHistoryFieldFormat::class.java) } }
{ "pile_set_name": "Github" }