max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
478
/* Q Light Controller alsamidiutil.cpp Copyright (c) <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <alsa/asoundlib.h> #include <QDebug> #include "alsamidiutil.h" QVariant AlsaMidiUtil::addressToVariant(const snd_seq_addr_t* addr) { Q_ASSERT(addr != NULL); uint value = addr->client << 8; value = value | addr->port; return QVariant(value); } bool AlsaMidiUtil::variantToAddress(const QVariant& var, snd_seq_addr_t* addr) { Q_ASSERT(addr != NULL); if (var.isValid() == false) return false; uint value = var.toUInt(); addr->client = (value >> 8); addr->port = (value & 0xFF); return true; } QString AlsaMidiUtil::extractName(snd_seq_t* alsa, const snd_seq_addr_t* address) { //qDebug() << Q_FUNC_INFO; Q_ASSERT(alsa != NULL); Q_ASSERT(address != NULL); snd_seq_port_info_t* portInfo = NULL; snd_seq_port_info_alloca(&portInfo); int r = snd_seq_get_any_port_info(alsa, address->client, address->port, portInfo); if (r == 0) { qDebug() << "ALSA Port name: " << QString(snd_seq_port_info_get_name(portInfo)); return QString(snd_seq_port_info_get_name(portInfo)); } else return QString(); }
660
348
<filename>docs/data/leg-t2/079/07902009.json {"nom":"Amuré","circ":"2ème circonscription","dpt":"Deux-Sèvres","inscrits":324,"abs":167,"votants":157,"blancs":6,"nuls":4,"exp":147,"res":[{"nuance":"SOC","nom":"<NAME>","voix":76},{"nuance":"REM","nom":"Mme <NAME>","voix":71}]}
117
190,993
<filename>tensorflow/compiler/xla/client/xla_computation.cc<gh_stars>1000+ /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/client/xla_computation.h" #include <utility> #include "absl/memory/memory.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/util.h" namespace xla { StatusOr<ProgramShape> XlaComputation::GetProgramShape() const { TF_RET_CHECK(proto_.has_host_program_shape()); return ProgramShape(proto_.host_program_shape()); } StatusOr<std::unique_ptr<HloSnapshot>> XlaComputation::Snapshot() const { if (IsNull()) { return InvalidArgument("Computation is invalid."); } auto session = absl::make_unique<HloSnapshot>(); *session->mutable_hlo()->mutable_hlo_module() = proto_; return std::move(session); } } // namespace xla
448
61,676
<gh_stars>1000+ from django.template.defaultfilters import divisibleby from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_true(self): self.assertIs(divisibleby(4, 2), True) def test_false(self): self.assertIs(divisibleby(4, 3), False)
111
308
from rest_framework import status from rest_framework.response import Response from rest_framework.views import exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) # We overwrite the response status code to 500 if response is not None: return Response({"detail": str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response
120
373
<filename>uniauth-server/src/main/java/com/dianrong/common/uniauth/server/support/apicontrl/pejudger/AbstractHttpRequestPermissionJudger.java package com.dianrong.common.uniauth.server.support.apicontrl.pejudger; import com.dianrong.common.uniauth.common.apicontrol.server.CallerCredential; import com.dianrong.common.uniauth.common.apicontrol.server.PermissionJudger; import com.dianrong.common.uniauth.common.bean.dto.ApiPermissionDto.UriMethod; import com.dianrong.common.uniauth.common.util.Assert; import com.dianrong.common.uniauth.common.util.HttpRequestUtil; import com.dianrong.common.uniauth.server.support.apicontrl.ApiCtlPermission; import com.dianrong.common.uniauth.server.support.apicontrl.ApiCtlPermissionItem; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.servlet.http.HttpServletRequest; public abstract class AbstractHttpRequestPermissionJudger implements PermissionJudger<ApiCtlPermission, HttpServletRequest> { @Override public boolean judge(CallerCredential<ApiCtlPermission> credential, HttpServletRequest request) { Assert.notNull(credential); Assert.notNull(credential.getPermissionInfo()); Assert.notNull(request); String requestUrl = HttpRequestUtil.extractRequestUrl(request, false); String requestMethod = request.getMethod(); ApiCtlPermission permissionInfo = getPermissionInfo(credential); for (ApiCtlPermissionItem item : permissionInfo.getPermissions()) { if (checkPermission(requestUrl, requestMethod, item)) { return true; } } return false; } // check permission private boolean checkPermission(String requestUrl, String requestMethod, ApiCtlPermissionItem item) { // check method // METHOD ALL, ignore if (!item.getMethod().equals(UriMethod.ALL)) { if (!item.getMethod().toString().equalsIgnoreCase(requestMethod)) { return false; } } // check request url Pattern pattern = getPattern(item.getUri()); if (!pattern.matcher(requestUrl).matches()) { return false; } return true; } /** * Get pattern. * * @param patternStr patternStr * @return pattern * @throws PatternSyntaxException - If the expression's syntax is invalid */ protected Pattern getPattern(String patternStr) { Assert.notNull(patternStr); Assert.notNull(patternStr); return Pattern.compile(patternStr); } protected abstract ApiCtlPermission getPermissionInfo( CallerCredential<ApiCtlPermission> credential); }
896
580
/** * Copyright 2011, Big Switch Networks, Inc. * Originally created by <NAME>, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.core.internal; import org.projectfloodlight.openflow.protocol.OFMessage; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; /** * Encode an iterable of openflow messages for output into a ByteBuf, for use in a * netty pipeline * * @author <NAME> <<EMAIL>> */ public class OFMessageEncoder extends MessageToByteEncoder<Iterable<OFMessage>> { @Override protected void encode(ChannelHandlerContext ctx, Iterable<OFMessage> msgList, ByteBuf out) throws Exception { for (OFMessage ofm : msgList) { ofm.writeTo(out); } } }
439
325
{ "data":[ { "author": "<NAME>", "quote": "Life isn't about finding yourself. Life is about creating yourself." }, { "author": "<NAME>", "quote": "The most important thing is to enjoy your life - to be happy - it's all that matters." }, { "author": "<NAME>", "quote": "I have found that if you love life, life will love you back." }, { "author": "Confucius", "quote": "Life is really simple, but we insist on making it complicated. " }, { "author": "<NAME>", "quote": "We all have two lives. The second one starts when we realize we only have one." }, { "author": "<NAME>", "quote": "To live is the rarest thing in the world. Most people exist, that is all." }, { "author": "<NAME>", "quote": "Life is a progress, and not a station." }, { "author": "<NAME>", "quote": "To live is so startling it leaves little time for anything else." }, { "author": "<NAME>", "quote": "It is not the length of life, but depth of life. " }, { "author": "<NAME>", "quote": "Vision without execution is just hallucination." }, { "author": "<NAME>", "quote": "Life is about making an impact, not making an income." }, { "author": "Socrates", "quote": "An unexamined life is not worth living." }, { "author": "<NAME>", "quote": "The two most important days in your life are the day you are born and the day you find out why." }, { "author": "<NAME>", "quote": "I think being in love with life is a key to eternal youth." }, { "author": "<NAME>", "quote": "If life were predictable it would cease to be life, and be without flavor." }, { "author": "<NAME>", "quote": "Find ecstasy in life; the mere sense of living is joy enough." }, { "author": "<NAME>", "quote": "I enjoy life , I don’t care if it’s good things or bad things. That means you’re alive." }, { "author": "<NAME>", "quote": "Life is short, and it is up to you to make it sweet." }, { "author": "<NAME>.", "quote": "Life doesn’t require that we be the best, only that we try our best." }, { "author": "<NAME>", "quote": "There isn't a way things should be. There's just what happens, and what we do." } ] }
868
777
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_ #define IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_ #include "base/macros.h" class PrefService; namespace net { class HttpServerPropertiesManager; } namespace user_prefs { class PrefRegistrySyncable; } // Class for registration and creation of HttpServerPropertiesManager class HttpServerPropertiesManagerFactory { public: // Create an instance of HttpServerPropertiesManager. static net::HttpServerPropertiesManager* CreateManager( PrefService* pref_service); // Register prefs for properties managed by HttpServerPropertiesManager. static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); private: DISALLOW_COPY_AND_ASSIGN(HttpServerPropertiesManagerFactory); }; #endif // IOS_CHROME_BROWSER_NET_HTTP_SERVER_PROPERTIES_MANAGER_FACTORY_H_
341
14,668
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include "testing/libfuzzer/fuzzers/skia_path_common.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/core/SkSurface.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { uint8_t w, h, anti_alias; if (!read<uint8_t>(&data, &size, &w)) return 0; if (!read<uint8_t>(&data, &size, &h)) return 0; if (!read<uint8_t>(&data, &size, &anti_alias)) return 0; SkScalar a, b, c, d; if (!read<SkScalar>(&data, &size, &a)) return 0; if (!read<SkScalar>(&data, &size, &b)) return 0; if (!read<SkScalar>(&data, &size, &c)) return 0; if (!read<SkScalar>(&data, &size, &d)) return 0; // In this case, we specifically don't want to include kDone_Verb. SkPath path; BuildPath(&data, &size, &path, SkPath::Verb::kClose_Verb); // Try a few potentially interesting things with our path. path.contains(a, b); path.conservativelyContainsRect(SkRect::MakeLTRB(a, b, c, d)); SkPaint paint_fill; paint_fill.setStyle(SkPaint::Style::kFill_Style); paint_fill.setAntiAlias(anti_alias & 1); SkPaint paint_stroke; paint_stroke.setStyle(SkPaint::Style::kStroke_Style); paint_stroke.setStrokeWidth(1); paint_stroke.setAntiAlias(anti_alias & 1); SkPath dst_path; paint_stroke.getFillPath(path, &dst_path, nullptr); // Width and height should never be 0. auto surface(SkSurface::MakeRasterN32Premul(w ? w : 1, h ? h : 1)); surface->getCanvas()->drawPath(path, paint_fill); surface->getCanvas()->drawPath(path, paint_stroke); return 0; }
738
1,444
package mage.cards.b; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.DestroyAllEffect; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.keyword.OverloadAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.ManaType; import mage.constants.Zone; import mage.filter.FilterPermanent; import mage.filter.common.FilterLandPermanent; import mage.filter.predicate.Predicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.target.TargetPermanent; import java.util.UUID; /** * @author TheElk801 */ public final class BreakTheIce extends CardImpl { private static final FilterPermanent filter = new FilterLandPermanent("land that is snow or could produce {C}"); static { filter.add(BreakTheIcePredicate.instance); } public BreakTheIce(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{B}{B}"); // Destroy target land that is snow or could produce {C}. this.getSpellAbility().addEffect(new DestroyTargetEffect()); this.getSpellAbility().addTarget(new TargetPermanent(filter)); // Overload {4}{B}{B} this.addAbility(new OverloadAbility(this, new DestroyAllEffect(filter), new ManaCostsImpl<>("{4}{B}{B}"))); } private BreakTheIce(final BreakTheIce card) { super(card); } @Override public BreakTheIce copy() { return new BreakTheIce(this); } } enum BreakTheIcePredicate implements Predicate<Permanent> { instance; @Override public boolean apply(Permanent input, Game game) { return input.isSnow() || input .getAbilities() .getActivatedManaAbilities(Zone.BATTLEFIELD) .stream() .anyMatch(ability -> ability.getProducableManaTypes(game).contains(ManaType.COLORLESS)); } }
749
5,252
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "./Primitive.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" namespace oatpp { namespace data { namespace mapping { namespace type { String::String(const std::shared_ptr<oatpp::base::StrBuffer>& ptr, const type::Type* const valueType) : oatpp::data::mapping::type::ObjectWrapper<oatpp::base::StrBuffer, __class::String>(ptr) { if(type::__class::String::getType() != valueType) { throw std::runtime_error("Value type does not match"); } } String operator + (const char* a, const String& b) { return oatpp::base::StrBuffer::createSharedConcatenated(a, (v_int32) std::strlen(a), b->getData(), b->getSize()); } String operator + (const String& b, const char* a) { return oatpp::base::StrBuffer::createSharedConcatenated(b->getData(), b->getSize(), a, (v_int32) std::strlen(a)); } String operator + (const String& a, const String& b) { return oatpp::base::StrBuffer::createSharedConcatenated(a->getData(), a->getSize(), b->getData(), b->getSize()); } namespace __class { const ClassId String::CLASS_ID("String"); const ClassId Int8::CLASS_ID("Int8"); const ClassId UInt8::CLASS_ID("UInt8"); const ClassId Int16::CLASS_ID("Int16"); const ClassId UInt16::CLASS_ID("UInt16"); const ClassId Int32::CLASS_ID("Int32"); const ClassId UInt32::CLASS_ID("UInt32"); const ClassId Int64::CLASS_ID("Int64"); const ClassId UInt64::CLASS_ID("UInt64"); const ClassId Float32::CLASS_ID("Float32"); const ClassId Float64::CLASS_ID("Float64"); const ClassId Boolean::CLASS_ID("Boolean"); } }}}}
873
1,131
<reponame>ycyun/ablestack-cloud // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.affinity; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; import org.apache.cloudstack.api.response.ControlledViewEntityResponse; import com.cloud.serializer.Param; @SuppressWarnings("unused") @EntityReference(value = AffinityGroup.class) public class AffinityGroupResponse extends BaseResponse implements ControlledViewEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "the ID of the affinity group") private String id; @SerializedName(ApiConstants.NAME) @Param(description = "the name of the affinity group") private String name; @SerializedName(ApiConstants.DESCRIPTION) @Param(description = "the description of the affinity group") private String description; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account owning the affinity group") private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the affinity group") private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain name of the affinity group") private String domainName; @SerializedName(ApiConstants.PROJECT_ID) @Param(description = "the project ID of the affinity group") private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description = "the project name of the affinity group") private String projectName; @SerializedName(ApiConstants.TYPE) @Param(description = "the type of the affinity group") private String type; @SerializedName("virtualmachineIds") @Param(description = "virtual machine IDs associated with this affinity group") private List<String> vmIdList; public AffinityGroupResponse() { } @Override public String getObjectId() { return this.getId(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } @Override public void setAccountName(String accountName) { this.accountName = accountName; } public void setType(String type) { this.type = type; } @Override public void setDomainId(String domainId) { this.domainId = domainId; } @Override public void setDomainName(String domainName) { this.domainName = domainName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AffinityGroupResponse other = (AffinityGroupResponse)obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public void setProjectId(String projectId) { this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } public void setVMIdList(List<String> vmIdList) { this.vmIdList = vmIdList; } public void addVMId(String vmId) { if (this.vmIdList == null) { this.vmIdList = new ArrayList<String>(); } this.vmIdList.add(vmId); } }
1,683
14,668
<reponame>chromium/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/service/performance_hint/utils.h" #include "base/containers/contains.h" #include "build/build_config.h" #if defined(OS_ANDROID) #include "base/linux_util.h" #endif namespace viz { bool CheckThreadIdsDoNotBelongToProcessIds( const std::vector<base::ProcessId>& privileged_process_ids, const base::flat_set<base::PlatformThreadId>& thread_ids_from_sandboxed_process) { #if defined(OS_ANDROID) // This is inherently racy as threads or processes can die and the IDs can be // reused at any time. But this is the best we can do. for (auto& process_id : privileged_process_ids) { std::vector<pid_t> privileged_thread_ids; if (!base::GetThreadsForProcess(process_id, &privileged_thread_ids)) { return false; } for (auto& tid : thread_ids_from_sandboxed_process) { if (base::Contains(privileged_thread_ids, tid)) { return false; } } } return true; #else return false; #endif } } // namespace viz
430
545
{ "AuthBase.accessAsGuest": "Raarugo bannda sigorɗum", "AuthBase.oidcGenericExplanation": "Kolibri ɗum laawol janngugo nder kompiita. Bee sigorɗum Kolibri maaɗa a waaway nastugo app-ji goɗɗi feere.", "AuthBase.oidcSpecificExplanation": "A yerɓoyaama daga app bi'eteeɗum '{app_name}'.Kolibri ɗum laawol janngugo nder kompiita. Bee sigorɗum Kolibri maaɗa a waaway nastugo app bi'eteeɗum '{app_name}'.", "AuthBase.photoCreditLabel": "Koosuɗo foto ɗu'um: {photoCredit}", "AuthBase.poweredBy": "Kolibri {version}", "AuthBase.poweredByKolibri": "Semmbiɗinaama bee Kolibri", "AuthBase.restrictedAccess": "Kolibri haɗii kompiitaaji diga yaasi nastugo", "AuthBase.restrictedAccessDescription": "Laawol wo''ingoɗum: Sey dawroowo mawɗo hokka junngo nden hesɗitina settings nastugo moɓgal kompiitaaji", "AuthBase.whatsThis": "Ɗum ɗume?", "AuthSelect.newUserPrompt": "A kuutiniroowo keso na?", "ChangeUserPasswordModal.passwordChangeFormHeader": "Sannju paltirgel", "ChangeUserPasswordModal.passwordChangedNotification": "Paltirgel maaɗa sannjaama", "CommonUserPageStrings.createAccountAction": "Waɗu sigorɗum", "CommonUserPageStrings.goBackToHomeAction": "Yahugo e ɗerewol artungol", "CommonUserPageStrings.signInPrompt": "Taa mari sigorɗum, hokku junngo", "CommonUserPageStrings.signInToFacilityLabel": "Nastugo '{facility}'", "CommonUserPageStrings.signingInAsUserLabel": "'{user}'e hokka junngo", "CommonUserPageStrings.signingInToFacilityAsUserLabel": "{user} e hokka junngo nastugo {facility}", "FacilitySelect.askAdminForAccountLabel": "Ƴamu dawroowo waɗanma sigorɗum gure bote ɗe'e:", "FacilitySelect.canSignUpForFacilityLabel": "Suɓtu wuro bote ngo ngiɗɗa hawtanngo sigorɗum maaɗa kesum:", "FacilitySelect.selectFacilityLabel": "Suɓtu wuro bote marngo sigorɗum maaɗa", "NewPasswordPage.needToMakeNewPasswordLabel": "Sannu, {user}. Waɗan sigorɗum maaɗa paltirgel kesel.", "ProfileEditPage.editProfileHeader": "Wo''in tinndinoore dow kuutiniroowo", "ProfilePage.changePasswordPrompt": "<PASSWORD>", "ProfilePage.detailsHeader": "Tiimugo", "ProfilePage.documentTitle": "Tinndinoore dow kuutiniroowo", "ProfilePage.editAction": "Wo''ingo", "ProfilePage.isSuperuser": "Yerduye diga dawroojum mawɗum ", "ProfilePage.limitedPermissions": "Hetaneego yerduye", "ProfilePage.manageContent": "Hakkilango gure janngugo bee jannginillum", "ProfilePage.manageDevicePermissions": "Hakkilango yerduye kompiita", "ProfilePage.points": "Keɓal", "ProfilePage.youCan": "A waaway:", "SignInPage.changeFacility": "Sannju wuro bote", "SignInPage.changeUser": "S<NAME>utiniroowo", "SignInPage.documentTitle": "Hokkugo junngo", "SignInPage.incorrectPasswordError": "<PASSWORD>", "SignInPage.incorrectUsernameError": "Innde kuutiniroowo wooɗa", "SignInPage.nextLabel": "Jokkotoongol", "SignInPage.requiredForCoachesAdmins": "Jannginooɓe e dawrooɓe sey nasta paltirgel", "SignUpPage.createAccount": "Waɗugo sigorɗum", "SignUpPage.demographicInfoExplanation": "Dawrooɓe mbaaway yi'ugoɗum. Ɗum wallay ɓeydugo e wo''ingo software koo logiciel bee jannginillum ngam ko janngooɓe feere-feere ngiɗi.", "SignUpPage.demographicInfoOptional": "Naa' ɗum doole hokkugo anndinoore ƴamaande ɗo'o.", "SignUpPage.documentTitle": "Waɗugo sigorɗum", "SignUpPage.privacyLinkText": "Ɓeydu janngugo dow kuutiniral bee haala sirrugo", "UserIndex.signUpStep1Title": "Falannde 1 nder 2", "UserIndex.signUpStep2Title": "Falannde 2 nder 2", "UserIndex.userProfileTitle": "Tinndinoore dow kuutiniroowo", "UserPageSnackbars.dismiss": "Maɓɓugo", "UserPageSnackbars.signedOut": "A wayrii huwugo, sey ngokka junngo fahin" }
1,535
660
<filename>media_driver/agnostic/common/codec/shared/codec_def_vp9_probs.h /* * Copyright (c) 2017, Intel Corporation * * 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. */ //! //! \file codec_def_vp9_probs.h //! \brief Defines the probs for VP9. //! \details Defines all probs required by CodecHal for VP9 decoding/encoding. //! /* * This file declares some vp9 definitions/probs * that are ported from libvpx (https://github.com/webmproject/libvpx/). * The original copyright and licence statement as below. */ /* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the media_libvpx.LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file media_libvpx.PATENTS. All contributing project authors may * be found in the media_libvpx.AUTHORS file in the root of the source tree. */ #ifndef __CODEC_DEF_VP9_PROBS_H__ #define __CODEC_DEF_VP9_PROBS_H__ #include "stdint.h" #define CODEC_VP9_PROB_MAX_NUM_ELEM 2048 #define CODEC_VP9_SEG_PROB_OFFSET 2010 #define CODEC_VP9_INTER_PROB_OFFSET 1667 #define CODECHAL_VP9_INTER_PROB_SIZE (CODEC_VP9_SEG_PROB_OFFSET - CODEC_VP9_INTER_PROB_OFFSET) #define CODEC_VP9_MAX_PROB 255 #define CODEC_VP9_TX_SIZE_CONTEXTS 2 //default probs copied from libvpx //! //! \struct CODEC_VP9_TX_PROBS //! \brief Codec VP9 tx probs //! struct CODEC_VP9_TX_PROBS { uint8_t p32x32[2][3]; uint8_t p16x16[2][2]; uint8_t p8x8[2][1]; }; typedef struct { uint8_t sign; uint8_t classes[10]; uint8_t class0[1]; uint8_t bits[10]; uint8_t class0_fp[2][3]; uint8_t fp[3]; uint8_t class0_hp; uint8_t hp; } CODEC_VP9_NMV_COMPONENT; typedef struct { uint8_t joints[3]; CODEC_VP9_NMV_COMPONENT comps[2]; } CODEC_VP9_NMV_CONTEXT; typedef uint8_t CODEC_VP9_COEFF_PROBS_MODEL[2][6][6][3]; const struct CODEC_VP9_TX_PROBS DefaultTxProbs = { { { 3, 136, 37 }, { 5, 52, 13 } }, { { 20, 152 }, { 15, 101 } }, { { 100 }, { 66 } } }; const uint8_t DefaultMbskipProbs[3] = { 192, 128, 64 }; const uint8_t DefaultInterModeProbs[7][3] = { { 2, 173, 34 }, // 0 = both zero mv { 7, 145, 85 }, // 1 = one zero mv + one a predicted mv { 7, 166, 63 }, // 2 = two predicted mvs { 7, 94, 66 }, // 3 = one predicted/zero and one new mv { 8, 64, 46 }, // 4 = two new mvs { 17, 81, 31 }, // 5 = one intra neighbour + x { 25, 29, 30 }, // 6 = two intra neighbours }; const uint8_t DefaultIntraInterProb[4] = { 9, 102, 187, 225 }; const uint8_t DefaultCompInterProb[5] = { 239, 183, 119, 96, 41 }; const uint8_t DefaultSingleRefProb[5][2] = { { 33, 16 }, { 77, 74 }, { 142, 142 }, { 172, 170 }, { 238, 247 } }; const uint8_t DefaultCompRefProb[5] = { 50, 126, 123, 221, 226 }; const uint8_t DefaultKFUVModeProb[10][9] = { { 144, 11, 54, 157, 195, 130, 46, 58, 108 }, // y = dc { 118, 15, 123, 148, 131, 101, 44, 93, 131 }, // y = v { 113, 12, 23, 188, 226, 142, 26, 32, 125 }, // y = h { 120, 11, 50, 123, 163, 135, 64, 77, 103 }, // y = d45 { 113, 9, 36, 155, 111, 157, 32, 44, 161 }, // y = d135 { 116, 9, 55, 176, 76, 96, 37, 61, 149 }, // y = d117 { 115, 9, 28, 141, 161, 167, 21, 25, 193 }, // y = d153 { 120, 12, 32, 145, 195, 142, 32, 38, 86 }, // y = d207 { 116, 12, 64, 120, 140, 125, 49, 115, 121 }, // y = d63 { 102, 19, 66, 162, 182, 122, 35, 59, 128 } // y = tm }; const uint8_t DefaultIFYProb[4][9] = { { 65, 32, 18, 144, 162, 194, 41, 51, 98 }, // block_size < 8x8 { 132, 68, 18, 165, 217, 196, 45, 40, 78 }, // block_size < 16x16 { 173, 80, 19, 176, 240, 193, 64, 35, 46 }, // block_size < 32x32 { 221, 135, 38, 194, 248, 121, 96, 85, 29 } // block_size >= 32x32 }; const uint8_t DefaultIFUVProbs[10][9] = { { 120, 7, 76, 176, 208, 126, 28, 54, 103 }, // y = dc { 48, 12, 154, 155, 139, 90, 34, 117, 119 }, // y = v { 67, 6, 25, 204, 243, 158, 13, 21, 96 }, // y = h { 97, 5, 44, 131, 176, 139, 48, 68, 97 }, // y = d45 { 83, 5, 42, 156, 111, 152, 26, 49, 152 }, // y = d135 { 80, 5, 58, 178, 74, 83, 33, 62, 145 }, // y = d117 { 86, 5, 32, 154, 192, 168, 14, 22, 163 }, // y = d153 { 85, 5, 32, 156, 216, 148, 19, 29, 73 }, // y = d207 { 77, 7, 64, 116, 132, 122, 37, 126, 120 }, // y = d63 { 101, 21, 107, 181, 192, 103, 19, 67, 125 } // y = tm }; const CODEC_VP9_COEFF_PROBS_MODEL DefaultCoefProbs4x4[2] = { { // Y plane { // Intra { // Band 0 { 195, 29, 183 },{ 84, 49, 136 },{ 8, 42, 71 } }, { // Band 1 { 31, 107, 169 },{ 35, 99, 159 },{ 17, 82, 140 }, { 8, 66, 114 },{ 2, 44, 76 },{ 1, 19, 32 } }, { // Band 2 { 40, 132, 201 },{ 29, 114, 187 },{ 13, 91, 157 }, { 7, 75, 127 },{ 3, 58, 95 },{ 1, 28, 47 } }, { // Band 3 { 69, 142, 221 },{ 42, 122, 201 },{ 15, 91, 159 }, { 6, 67, 121 },{ 1, 42, 77 },{ 1, 17, 31 } }, { // Band 4 { 102, 148, 228 },{ 67, 117, 204 },{ 17, 82, 154 }, { 6, 59, 114 },{ 2, 39, 75 },{ 1, 15, 29 } }, { // Band 5 { 156, 57, 233 },{ 119, 57, 212 },{ 58, 48, 163 }, { 29, 40, 124 },{ 12, 30, 81 },{ 3, 12, 31 } } }, { // Inter { // Band 0 { 191, 107, 226 },{ 124, 117, 204 },{ 25, 99, 155 } },{ // Band 1 { 29, 148, 210 },{ 37, 126, 194 },{ 8, 93, 157 }, { 2, 68, 118 },{ 1, 39, 69 },{ 1, 17, 33 } },{ // Band 2 { 41, 151, 213 },{ 27, 123, 193 },{ 3, 82, 144 }, { 1, 58, 105 },{ 1, 32, 60 },{ 1, 13, 26 } },{ // Band 3 { 59, 159, 220 },{ 23, 126, 198 },{ 4, 88, 151 }, { 1, 66, 114 },{ 1, 38, 71 },{ 1, 18, 34 } },{ // Band 4 { 114, 136, 232 },{ 51, 114, 207 },{ 11, 83, 155 }, { 3, 56, 105 },{ 1, 33, 65 },{ 1, 17, 34 } },{ // Band 5 { 149, 65, 234 },{ 121, 57, 215 },{ 61, 49, 166 }, { 28, 36, 114 },{ 12, 25, 76 },{ 3, 16, 42 } } } }, { // UV plane { // Intra { // Band 0 { 214, 49, 220 },{ 132, 63, 188 },{ 42, 65, 137 } }, { // Band 1 { 85, 137, 221 },{ 104, 131, 216 },{ 49, 111, 192 }, { 21, 87, 155 },{ 2, 49, 87 },{ 1, 16, 28 } }, { // Band 2 { 89, 163, 230 },{ 90, 137, 220 },{ 29, 100, 183 }, { 10, 70, 135 },{ 2, 42, 81 },{ 1, 17, 33 } }, { // Band 3 { 108, 167, 237 },{ 55, 133, 222 },{ 15, 97, 179 }, { 4, 72, 135 },{ 1, 45, 85 },{ 1, 19, 38 } }, { // Band 4 { 124, 146, 240 },{ 66, 124, 224 },{ 17, 88, 175 }, { 4, 58, 122 },{ 1, 36, 75 },{ 1, 18, 37 } }, { // Band 5 { 141, 79, 241 },{ 126, 70, 227 },{ 66, 58, 182 }, { 30, 44, 136 },{ 12, 34, 96 },{ 2, 20, 47 } } }, { // Inter { // Band 0 { 229, 99, 249 },{ 143, 111, 235 },{ 46, 109, 192 } }, { // Band 1 { 82, 158, 236 },{ 94, 146, 224 },{ 25, 117, 191 }, { 9, 87, 149 },{ 3, 56, 99 },{ 1, 33, 57 } }, { // Band 2 { 83, 167, 237 },{ 68, 145, 222 },{ 10, 103, 177 }, { 2, 72, 131 },{ 1, 41, 79 },{ 1, 20, 39 } }, { // Band 3 { 99, 167, 239 },{ 47, 141, 224 },{ 10, 104, 178 }, { 2, 73, 133 },{ 1, 44, 85 },{ 1, 22, 47 } }, { // Band 4 { 127, 145, 243 },{ 71, 129, 228 },{ 17, 93, 177 }, { 3, 61, 124 },{ 1, 41, 84 },{ 1, 21, 52 } }, { // Band 5 { 157, 78, 244 },{ 140, 72, 231 },{ 69, 58, 184 }, { 31, 44, 137 },{ 14, 38, 105 },{ 8, 23, 61 } } } } }; const CODEC_VP9_COEFF_PROBS_MODEL DefaultCoefPprobs8x8[2] = { { // Y plane { // Intra { // Band 0 { 125, 34, 187 },{ 52, 41, 133 },{ 6, 31, 56 } }, { // Band 1 { 37, 109, 153 },{ 51, 102, 147 },{ 23, 87, 128 }, { 8, 67, 101 },{ 1, 41, 63 },{ 1, 19, 29 } }, { // Band 2 { 31, 154, 185 },{ 17, 127, 175 },{ 6, 96, 145 }, { 2, 73, 114 },{ 1, 51, 82 },{ 1, 28, 45 } }, { // Band 3 { 23, 163, 200 },{ 10, 131, 185 },{ 2, 93, 148 }, { 1, 67, 111 },{ 1, 41, 69 },{ 1, 14, 24 } }, { // Band 4 { 29, 176, 217 },{ 12, 145, 201 },{ 3, 101, 156 }, { 1, 69, 111 },{ 1, 39, 63 },{ 1, 14, 23 } }, { // Band 5 { 57, 192, 233 },{ 25, 154, 215 },{ 6, 109, 167 }, { 3, 78, 118 },{ 1, 48, 69 },{ 1, 21, 29 } } }, { // Inter { // Band 0 { 202, 105, 245 },{ 108, 106, 216 },{ 18, 90, 144 } }, { // Band 1 { 33, 172, 219 },{ 64, 149, 206 },{ 14, 117, 177 }, { 5, 90, 141 },{ 2, 61, 95 },{ 1, 37, 57 } }, { // Band 2 { 33, 179, 220 },{ 11, 140, 198 },{ 1, 89, 148 }, { 1, 60, 104 },{ 1, 33, 57 },{ 1, 12, 21 } }, { // Band 3 { 30, 181, 221 },{ 8, 141, 198 },{ 1, 87, 145 }, { 1, 58, 100 },{ 1, 31, 55 },{ 1, 12, 20 } }, { // Band 4 { 32, 186, 224 },{ 7, 142, 198 },{ 1, 86, 143 }, { 1, 58, 100 },{ 1, 31, 55 },{ 1, 12, 22 } }, { // Band 5 { 57, 192, 227 },{ 20, 143, 204 },{ 3, 96, 154 }, { 1, 68, 112 },{ 1, 42, 69 },{ 1, 19, 32 } } } }, { // UV plane { // Intra { // Band 0 { 212, 35, 215 },{ 113, 47, 169 },{ 29, 48, 105 } }, { // Band 1 { 74, 129, 203 },{ 106, 120, 203 },{ 49, 107, 178 }, { 19, 84, 144 },{ 4, 50, 84 },{ 1, 15, 25 } }, { // Band 2 { 71, 172, 217 },{ 44, 141, 209 },{ 15, 102, 173 }, { 6, 76, 133 },{ 2, 51, 89 },{ 1, 24, 42 } }, { // Band 3 { 64, 185, 231 },{ 31, 148, 216 },{ 8, 103, 175 }, { 3, 74, 131 },{ 1, 46, 81 },{ 1, 18, 30 } }, { // Band 4 { 65, 196, 235 },{ 25, 157, 221 },{ 5, 105, 174 }, { 1, 67, 120 },{ 1, 38, 69 },{ 1, 15, 30 } }, { // Band 5 { 65, 204, 238 },{ 30, 156, 224 },{ 7, 107, 177 }, { 2, 70, 124 },{ 1, 42, 73 },{ 1, 18, 34 } } }, { // Inter { // Band 0 { 225, 86, 251 },{ 144, 104, 235 },{ 42, 99, 181 } }, { // Band 1 { 85, 175, 239 },{ 112, 165, 229 },{ 29, 136, 200 }, { 12, 103, 162 },{ 6, 77, 123 },{ 2, 53, 84 } }, { // Band 2 { 75, 183, 239 },{ 30, 155, 221 },{ 3, 106, 171 }, { 1, 74, 128 },{ 1, 44, 76 },{ 1, 17, 28 } }, { // Band 3 { 73, 185, 240 },{ 27, 159, 222 },{ 2, 107, 172 }, { 1, 75, 127 },{ 1, 42, 73 },{ 1, 17, 29 } }, { // Band 4 { 62, 190, 238 },{ 21, 159, 222 },{ 2, 107, 172 }, { 1, 72, 122 },{ 1, 40, 71 },{ 1, 18, 32 } }, { // Band 5 { 61, 199, 240 },{ 27, 161, 226 },{ 4, 113, 180 }, { 1, 76, 129 },{ 1, 46, 80 },{ 1, 23, 41 } } } } }; const CODEC_VP9_COEFF_PROBS_MODEL DefaultCoefProbs16x16[2] = { { // Y plane { // Intra { // Band 0 { 7, 27, 153 },{ 5, 30, 95 },{ 1, 16, 30 } }, { // Band 1 { 50, 75, 127 },{ 57, 75, 124 },{ 27, 67, 108 }, { 10, 54, 86 },{ 1, 33, 52 },{ 1, 12, 18 } }, { // Band 2 { 43, 125, 151 },{ 26, 108, 148 },{ 7, 83, 122 }, { 2, 59, 89 },{ 1, 38, 60 },{ 1, 17, 27 } }, { // Band 3 { 23, 144, 163 },{ 13, 112, 154 },{ 2, 75, 117 }, { 1, 50, 81 },{ 1, 31, 51 },{ 1, 14, 23 } }, { // Band 4 { 18, 162, 185 },{ 6, 123, 171 },{ 1, 78, 125 }, { 1, 51, 86 },{ 1, 31, 54 },{ 1, 14, 23 } }, { // Band 5 { 15, 199, 227 },{ 3, 150, 204 },{ 1, 91, 146 }, { 1, 55, 95 },{ 1, 30, 53 },{ 1, 11, 20 } } }, { // Inter { // Band 0 { 19, 55, 240 },{ 19, 59, 196 },{ 3, 52, 105 } }, { // Band 1 { 41, 166, 207 },{ 104, 153, 199 },{ 31, 123, 181 }, { 14, 101, 152 },{ 5, 72, 106 },{ 1, 36, 52 } }, { // Band 2 { 35, 176, 211 },{ 12, 131, 190 },{ 2, 88, 144 }, { 1, 60, 101 },{ 1, 36, 60 },{ 1, 16, 28 } }, { // Band 3 { 28, 183, 213 },{ 8, 134, 191 },{ 1, 86, 142 }, { 1, 56, 96 },{ 1, 30, 53 },{ 1, 12, 20 } }, { // Band 4 { 20, 190, 215 },{ 4, 135, 192 },{ 1, 84, 139 }, { 1, 53, 91 },{ 1, 28, 49 },{ 1, 11, 20 } }, { // Band 5 { 13, 196, 216 },{ 2, 137, 192 },{ 1, 86, 143 }, { 1, 57, 99 },{ 1, 32, 56 },{ 1, 13, 24 } } } }, { // UV plane { // Intra { // Band 0 { 211, 29, 217 },{ 96, 47, 156 },{ 22, 43, 87 } }, { // Band 1 { 78, 120, 193 },{ 111, 116, 186 },{ 46, 102, 164 }, { 15, 80, 128 },{ 2, 49, 76 },{ 1, 18, 28 } }, { // Band 2 { 71, 161, 203 },{ 42, 132, 192 },{ 10, 98, 150 }, { 3, 69, 109 },{ 1, 44, 70 },{ 1, 18, 29 } }, { // Band 3 { 57, 186, 211 },{ 30, 140, 196 },{ 4, 93, 146 }, { 1, 62, 102 },{ 1, 38, 65 },{ 1, 16, 27 } }, { // Band 4 { 47, 199, 217 },{ 14, 145, 196 },{ 1, 88, 142 }, { 1, 57, 98 },{ 1, 36, 62 },{ 1, 15, 26 } }, { // Band 5 { 26, 219, 229 },{ 5, 155, 207 },{ 1, 94, 151 }, { 1, 60, 104 },{ 1, 36, 62 },{ 1, 16, 28 } } }, { // Inter { // Band 0 { 233, 29, 248 },{ 146, 47, 220 },{ 43, 52, 140 } }, { // Band 1 { 100, 163, 232 },{ 179, 161, 222 },{ 63, 142, 204 }, { 37, 113, 174 },{ 26, 89, 137 },{ 18, 68, 97 } }, { // Band 2 { 85, 181, 230 },{ 32, 146, 209 },{ 7, 100, 164 }, { 3, 71, 121 },{ 1, 45, 77 },{ 1, 18, 30 } }, { // Band 3 { 65, 187, 230 },{ 20, 148, 207 },{ 2, 97, 159 }, { 1, 68, 116 },{ 1, 40, 70 },{ 1, 14, 29 } }, { // Band 4 { 40, 194, 227 },{ 8, 147, 204 },{ 1, 94, 155 }, { 1, 65, 112 },{ 1, 39, 66 },{ 1, 14, 26 } }, { // Band 5 { 16, 208, 228 },{ 3, 151, 207 },{ 1, 98, 160 }, { 1, 67, 117 },{ 1, 41, 74 },{ 1, 17, 31 } } } } }; const CODEC_VP9_COEFF_PROBS_MODEL DefaultCoefProbs32x32[2] = { { // Y plane { // Intra { // Band 0 { 17, 38, 140 },{ 7, 34, 80 },{ 1, 17, 29 } }, { // Band 1 { 37, 75, 128 },{ 41, 76, 128 },{ 26, 66, 116 }, { 12, 52, 94 },{ 2, 32, 55 },{ 1, 10, 16 } }, { // Band 2 { 50, 127, 154 },{ 37, 109, 152 },{ 16, 82, 121 }, { 5, 59, 85 },{ 1, 35, 54 },{ 1, 13, 20 } }, { // Band 3 { 40, 142, 167 },{ 17, 110, 157 },{ 2, 71, 112 }, { 1, 44, 72 },{ 1, 27, 45 },{ 1, 11, 17 } }, { // Band 4 { 30, 175, 188 },{ 9, 124, 169 },{ 1, 74, 116 }, { 1, 48, 78 },{ 1, 30, 49 },{ 1, 11, 18 } }, { // Band 5 { 10, 222, 223 },{ 2, 150, 194 },{ 1, 83, 128 }, { 1, 48, 79 },{ 1, 27, 45 },{ 1, 11, 17 } } }, { // Inter { // Band 0 { 36, 41, 235 },{ 29, 36, 193 },{ 10, 27, 111 } }, { // Band 1 { 85, 165, 222 },{ 177, 162, 215 },{ 110, 135, 195 }, { 57, 113, 168 },{ 23, 83, 120 },{ 10, 49, 61 } }, { // Band 2 { 85, 190, 223 },{ 36, 139, 200 },{ 5, 90, 146 }, { 1, 60, 103 },{ 1, 38, 65 },{ 1, 18, 30 } }, { // Band 3 { 72, 202, 223 },{ 23, 141, 199 },{ 2, 86, 140 }, { 1, 56, 97 },{ 1, 36, 61 },{ 1, 16, 27 } }, { // Band 4 { 55, 218, 225 },{ 13, 145, 200 },{ 1, 86, 141 }, { 1, 57, 99 },{ 1, 35, 61 },{ 1, 13, 22 } }, { // Band 5 { 15, 235, 212 },{ 1, 132, 184 },{ 1, 84, 139 }, { 1, 57, 97 },{ 1, 34, 56 },{ 1, 14, 23 } } } }, { // UV plane { // Intra { // Band 0 { 181, 21, 201 },{ 61, 37, 123 },{ 10, 38, 71 } }, { // Band 1 { 47, 106, 172 },{ 95, 104, 173 },{ 42, 93, 159 }, { 18, 77, 131 },{ 4, 50, 81 },{ 1, 17, 23 } }, { // Band 2 { 62, 147, 199 },{ 44, 130, 189 },{ 28, 102, 154 }, { 18, 75, 115 },{ 2, 44, 65 },{ 1, 12, 19 } }, { // Band 3 { 55, 153, 210 },{ 24, 130, 194 },{ 3, 93, 146 }, { 1, 61, 97 },{ 1, 31, 50 },{ 1, 10, 16 } }, { // Band 4 { 49, 186, 223 },{ 17, 148, 204 },{ 1, 96, 142 }, { 1, 53, 83 },{ 1, 26, 44 },{ 1, 11, 17 } }, { // Band 5 { 13, 217, 212 },{ 2, 136, 180 },{ 1, 78, 124 }, { 1, 50, 83 },{ 1, 29, 49 },{ 1, 14, 23 } } }, { // Inter { // Band 0 { 197, 13, 247 },{ 82, 17, 222 },{ 25, 17, 162 } }, { // Band 1 { 126, 186, 247 },{ 234, 191, 243 },{ 176, 177, 234 }, { 104, 158, 220 },{ 66, 128, 186 },{ 55, 90, 137 } }, { // Band 2 { 111, 197, 242 },{ 46, 158, 219 },{ 9, 104, 171 }, { 2, 65, 125 },{ 1, 44, 80 },{ 1, 17, 91 } }, { // Band 3 { 104, 208, 245 },{ 39, 168, 224 },{ 3, 109, 162 }, { 1, 79, 124 },{ 1, 50, 102 },{ 1, 43, 102 } }, { // Band 4 { 84, 220, 246 },{ 31, 177, 231 },{ 2, 115, 180 }, { 1, 79, 134 },{ 1, 55, 77 },{ 1, 60, 79 } }, { // Band 5 { 43, 243, 240 },{ 8, 180, 217 },{ 1, 115, 166 }, { 1, 84, 121 },{ 1, 51, 67 },{ 1, 16, 6 } } } } }; const uint8_t DefaultSwitchableInterpProb[4][2] = { { 235, 162, }, { 36, 255, }, { 34, 3, }, { 149, 144, }, }; const uint8_t DefaultKFPartitionProb[16][3] = { // 8x8 -> 4x4 { 158, 97, 94 }, // a/l both not split { 93, 24, 99 }, // a split, l not split { 85, 119, 44 }, // l split, a not split { 62, 59, 67 }, // a/l both split // 16x16 -> 8x8 { 149, 53, 53 }, // a/l both not split { 94, 20, 48 }, // a split, l not split { 83, 53, 24 }, // l split, a not split { 52, 18, 18 }, // a/l both split // 32x32 -> 16x16 { 150, 40, 39 }, // a/l both not split { 78, 12, 26 }, // a split, l not split { 67, 33, 11 }, // l split, a not split { 24, 7, 5 }, // a/l both split // 64x64 -> 32x32 { 174, 35, 49 }, // a/l both not split { 68, 11, 27 }, // a split, l not split { 57, 15, 9 }, // l split, a not split { 12, 3, 3 }, // a/l both split }; const uint8_t DefaultPartitionProb[16][3] = { // 8x8 -> 4x4 { 199, 122, 141 }, // a/l both not split { 147, 63, 159 }, // a split, l not split { 148, 133, 118 }, // l split, a not split { 121, 104, 114 }, // a/l both split // 16x16 -> 8x8 { 174, 73, 87 }, // a/l both not split { 92, 41, 83 }, // a split, l not split { 82, 99, 50 }, // l split, a not split { 53, 39, 39 }, // a/l both split // 32x32 -> 16x16 { 177, 58, 59 }, // a/l both not split { 68, 26, 63 }, // a split, l not split { 52, 79, 25 }, // l split, a not split { 17, 14, 12 }, // a/l both split // 64x64 -> 32x32 { 222, 34, 30 }, // a/l both not split { 72, 16, 44 }, // a split, l not split { 58, 32, 12 }, // l split, a not split { 10, 7, 6 }, // a/l both split }; const CODEC_VP9_NMV_CONTEXT DefaultNmvContext = { { 32, 64, 96 }, { // NOLINT { /* vert component */ // NOLINT 128, /* sign */ { 224, 144, 192, 168, 192, 176, 192, 198, 198, 245 }, /* class */ { 216 }, /* class0 */ { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240 }, /* bits */ { { 128, 128, 64 },{ 96, 112, 64 } }, /* class0_fp */ { 64, 96, 64 }, /* fp */ 160, /* class0_hp bit */ 128, /* hp */ }, { /* hor component */ // NOLINT 128, /* sign */ { 216, 128, 176, 160, 176, 176, 192, 198, 198, 208 }, /* class */ { 208 }, /* class0 */ { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240 }, /* bits */ { { 128, 128, 64 },{ 96, 112, 64 } }, /* class0_fp */ { 64, 96, 64 }, /* fp */ 160, /* class0_hp bit */ 128, /* hp */ } }, }; #endif // __CODEC_DEF_VP9_PROBS_H__
14,249
2,113
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- #include "T3D/components/camera/cameraOrbiterComponent.h" #include "core/util/safeDelete.h" #include "console/consoleTypes.h" #include "console/consoleObject.h" #include "core/stream/bitStream.h" #include "console/engineAPI.h" #include "sim/netConnection.h" #include "math/mathUtils.h" ////////////////////////////////////////////////////////////////////////// // Constructor/Destructor ////////////////////////////////////////////////////////////////////////// CameraOrbiterComponent::CameraOrbiterComponent() : Component() { mMinOrbitDist = 0.0f; mMaxOrbitDist = 0.0f; mCurOrbitDist = 8.0f; mPosition.set(0.0f, 0.0f, 0.0f); mMaxPitchAngle = 70; mMinPitchAngle = -10; mRotation.set(0, 0, 0); mCamera = NULL; } CameraOrbiterComponent::~CameraOrbiterComponent() { } IMPLEMENT_CO_NETOBJECT_V1(CameraOrbiterComponent); bool CameraOrbiterComponent::onAdd() { if (!Parent::onAdd()) return false; return true; } void CameraOrbiterComponent::onRemove() { Parent::onRemove(); } void CameraOrbiterComponent::initPersistFields() { Parent::initPersistFields(); addField("orbitDistance", TypeF32, Offset(mCurOrbitDist, CameraOrbiterComponent), "Object world orientation."); addField("Rotation", TypeRotationF, Offset(mRotation, CameraOrbiterComponent), "Object world orientation."); addField("maxPitchAngle", TypeF32, Offset(mMaxPitchAngle, CameraOrbiterComponent), "Object world orientation."); addField("minPitchAngle", TypeF32, Offset(mMinPitchAngle, CameraOrbiterComponent), "Object world orientation."); } //This is mostly a catch for situations where the behavior is re-added to the object and the like and we may need to force an update to the behavior void CameraOrbiterComponent::onComponentAdd() { Parent::onComponentAdd(); CameraComponent *cam = mOwner->getComponent<CameraComponent>(); if (cam) { mCamera = cam; } } void CameraOrbiterComponent::onComponentRemove() { Parent::onComponentRemove(); } void CameraOrbiterComponent::componentAddedToOwner(Component *comp) { if (comp->getId() == getId()) return; //test if this is a shape component! CameraComponent *camComponent = dynamic_cast<CameraComponent*>(comp); if (camComponent) { mCamera = camComponent; } } void CameraOrbiterComponent::componentRemovedFromOwner(Component *comp) { if (comp->getId() == getId()) //????????? return; //test if this is a shape component! CameraComponent *camComponent = dynamic_cast<CameraComponent*>(comp); if (camComponent) { mCamera = NULL; } } U32 CameraOrbiterComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream) { U32 retMask = Parent::packUpdate(con, mask, stream); return retMask; } void CameraOrbiterComponent::unpackUpdate(NetConnection *con, BitStream *stream) { Parent::unpackUpdate(con, stream); } void CameraOrbiterComponent::processTick() { Parent::processTick(); if (!mOwner) return; if (mCamera) { //Clamp our pitch to whatever range we allow, first. mRotation.x = mClampF(mRotation.x, mDegToRad(mMinPitchAngle), mDegToRad(mMaxPitchAngle)); MatrixF ownerTrans = mOwner->getRenderTransform(); Point3F ownerPos = ownerTrans.getPosition(); Point3F pos; pos.x = mCurOrbitDist * mSin(mRotation.x + M_HALFPI_F) * mCos(-1.0f * (mRotation.z + M_HALFPI_F)); pos.y = mCurOrbitDist * mSin(mRotation.x + M_HALFPI_F) * mSin(-1.0f * (mRotation.z + M_HALFPI_F)); pos.z = mCurOrbitDist * mSin(mRotation.x); //orient the camera towards the owner VectorF ownerVec = ownerPos - pos; ownerVec.normalize(); MatrixF xRot, zRot, cameraMatrix; xRot.set(EulerF(mRotation.x, 0.0f, 0.0f)); zRot.set(EulerF(0.0f, 0.0f, mRotation.z)); cameraMatrix.mul(zRot, xRot); cameraMatrix.getColumn(1, &ownerVec); cameraMatrix.setColumn(3, pos - ownerVec * pos); RotationF camRot = RotationF(cameraMatrix); if (camRot != mCamera->getRotOffset()) mCamera->setRotation(camRot); if (pos != mCamera->getPosOffset()) mCamera->setPosition(pos); } }
1,844
544
import json from office365.sharepoint.client_context import ClientContext from tests import test_user_credentials, test_site_url if __name__ == '__main__': """Demonstrates how to construct and submit requests without model involved""" client = ClientContext(test_site_url).with_credentials(test_user_credentials) response = client.execute_request_direct("web") response.raise_for_status() json = json.loads(response.content) web_title = json['d']['Title'] print("Web title: {0}".format(web_title))
171
1,338
/* Standard queue */ /* ** Copyright 2001, <NAME>. All rights reserved. ** Distributed under the terms of the NewOS License. */ #include <kernel.h> #include <queue.h> #include <malloc.h> #include <errno.h> typedef struct queue_element { void *next; } queue_element; typedef struct queue_typed { queue_element *head; queue_element *tail; int count; } queue_typed; int queue_init(queue *q) { q->head = q->tail = NULL; q->count = 0; return 0; } int queue_remove_item(queue *_q, void *e) { queue_typed *q = (queue_typed *)_q; queue_element *elem = (queue_element *)e; queue_element *temp, *last = NULL; temp = (queue_element *)q->head; while (temp) { if (temp == elem) { if (last) last->next = temp->next; else q->head = (queue_element*)temp->next; if (q->tail == temp) q->tail = last; q->count--; return 0; } last = temp; temp = (queue_element*)temp->next; } return -1; } int queue_enqueue(queue *_q, void *e) { queue_typed *q = (queue_typed *)_q; queue_element *elem = (queue_element *)e; if (q->tail == NULL) { q->tail = elem; q->head = elem; } else { q->tail->next = elem; q->tail = elem; } elem->next = NULL; q->count++; return 0; } void * queue_dequeue(queue *_q) { queue_typed *q = (queue_typed *)_q; queue_element *elem; elem = q->head; if (q->head != NULL) q->head = (queue_element*)q->head->next; if (q->tail == elem) q->tail = NULL; if (elem != NULL) q->count--; return elem; } void * queue_peek(queue *q) { return q->head; } // #pragma mark - /* fixed queue stuff */ int fixed_queue_init(fixed_queue *q, int size) { if (size <= 0) return EINVAL; q->table = (void**)malloc(size * sizeof(void *)); if (!q->table) return ENOMEM; q->head = 0; q->tail = 0; q->count = 0; q->size = size; return 0; } void fixed_queue_destroy(fixed_queue *q) { free(q->table); } int fixed_queue_enqueue(fixed_queue *q, void *e) { if (q->count == q->size) return ENOMEM; q->table[q->head++] = e; if (q->head >= q->size) q->head = 0; q->count++; return 0; } void * fixed_queue_dequeue(fixed_queue *q) { void *e; if (q->count <= 0) return NULL; e = q->table[q->tail++]; if (q->tail >= q->size) q->tail = 0; q->count--; return e; } void * fixed_queue_peek(fixed_queue *q) { if (q->count <= 0) return NULL; return q->table[q->tail]; }
1,067
305
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video/stream_synchronization.h" #include <algorithm> #include "system_wrappers/include/clock.h" #include "system_wrappers/include/ntp_time.h" #include "test/gtest.h" namespace webrtc { namespace { constexpr int kMaxAudioDiffMs = 80; // From stream_synchronization.cc constexpr int kDefaultAudioFrequency = 8000; constexpr int kDefaultVideoFrequency = 90000; constexpr int kSmoothingFilter = 4 * 2; } // namespace class StreamSynchronizationTest : public ::testing::Test { public: StreamSynchronizationTest() : sync_(0, 0), clock_sender_(98765000), clock_receiver_(43210000) {} protected: // Generates the necessary RTCP measurements and RTP timestamps and computes // the audio and video delays needed to get the two streams in sync. // |audio_delay_ms| and |video_delay_ms| are the number of milliseconds after // capture which the frames are rendered. // |current_audio_delay_ms| is the number of milliseconds which audio is // currently being delayed by the receiver. bool DelayedStreams(int audio_delay_ms, int video_delay_ms, int current_audio_delay_ms, int* extra_audio_delay_ms, int* total_video_delay_ms) { int audio_frequency = static_cast<int>(kDefaultAudioFrequency * audio_clock_drift_ + 0.5); int video_frequency = static_cast<int>(kDefaultVideoFrequency * video_clock_drift_ + 0.5); // Generate NTP/RTP timestamp pair for both streams corresponding to RTCP. bool new_sr; StreamSynchronization::Measurements audio; StreamSynchronization::Measurements video; NtpTime ntp_time = clock_sender_.CurrentNtpTime(); uint32_t rtp_timestamp = clock_sender_.CurrentTime().ms() * audio_frequency / 1000; EXPECT_TRUE(audio.rtp_to_ntp.UpdateMeasurements( ntp_time.seconds(), ntp_time.fractions(), rtp_timestamp, &new_sr)); clock_sender_.AdvanceTimeMilliseconds(100); clock_receiver_.AdvanceTimeMilliseconds(100); ntp_time = clock_sender_.CurrentNtpTime(); rtp_timestamp = clock_sender_.CurrentTime().ms() * video_frequency / 1000; EXPECT_TRUE(video.rtp_to_ntp.UpdateMeasurements( ntp_time.seconds(), ntp_time.fractions(), rtp_timestamp, &new_sr)); clock_sender_.AdvanceTimeMilliseconds(900); clock_receiver_.AdvanceTimeMilliseconds(900); ntp_time = clock_sender_.CurrentNtpTime(); rtp_timestamp = clock_sender_.CurrentTime().ms() * audio_frequency / 1000; EXPECT_TRUE(audio.rtp_to_ntp.UpdateMeasurements( ntp_time.seconds(), ntp_time.fractions(), rtp_timestamp, &new_sr)); clock_sender_.AdvanceTimeMilliseconds(100); clock_receiver_.AdvanceTimeMilliseconds(100); ntp_time = clock_sender_.CurrentNtpTime(); rtp_timestamp = clock_sender_.CurrentTime().ms() * video_frequency / 1000; EXPECT_TRUE(video.rtp_to_ntp.UpdateMeasurements( ntp_time.seconds(), ntp_time.fractions(), rtp_timestamp, &new_sr)); clock_sender_.AdvanceTimeMilliseconds(900); clock_receiver_.AdvanceTimeMilliseconds(900); // Capture an audio and a video frame at the same time. audio.latest_timestamp = clock_sender_.CurrentTime().ms() * audio_frequency / 1000; video.latest_timestamp = clock_sender_.CurrentTime().ms() * video_frequency / 1000; if (audio_delay_ms > video_delay_ms) { // Audio later than video. clock_receiver_.AdvanceTimeMilliseconds(video_delay_ms); video.latest_receive_time_ms = clock_receiver_.CurrentTime().ms(); clock_receiver_.AdvanceTimeMilliseconds(audio_delay_ms - video_delay_ms); audio.latest_receive_time_ms = clock_receiver_.CurrentTime().ms(); } else { // Video later than audio. clock_receiver_.AdvanceTimeMilliseconds(audio_delay_ms); audio.latest_receive_time_ms = clock_receiver_.CurrentTime().ms(); clock_receiver_.AdvanceTimeMilliseconds(video_delay_ms - audio_delay_ms); video.latest_receive_time_ms = clock_receiver_.CurrentTime().ms(); } int relative_delay_ms; StreamSynchronization::ComputeRelativeDelay(audio, video, &relative_delay_ms); EXPECT_EQ(video_delay_ms - audio_delay_ms, relative_delay_ms); return sync_.ComputeDelays(relative_delay_ms, current_audio_delay_ms, extra_audio_delay_ms, total_video_delay_ms); } // Simulate audio playback 300 ms after capture and video rendering 100 ms // after capture. Verify that the correct extra delays are calculated for // audio and video, and that they change correctly when we simulate that // NetEQ or the VCM adds more delay to the streams. // TODO(holmer): This is currently wrong! We should simply change // audio_delay_ms or video_delay_ms since those now include VCM and NetEQ // delays. void BothDelayedAudioLaterTest(int base_target_delay) { int current_audio_delay_ms = base_target_delay; int audio_delay_ms = base_target_delay + 300; int video_delay_ms = base_target_delay + 100; int extra_audio_delay_ms = 0; int total_video_delay_ms = base_target_delay; int filtered_move = (audio_delay_ms - video_delay_ms) / kSmoothingFilter; const int kNeteqDelayIncrease = 50; const int kNeteqDelayDecrease = 10; EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay + filtered_move, total_video_delay_ms); EXPECT_EQ(base_target_delay, extra_audio_delay_ms); current_audio_delay_ms = extra_audio_delay_ms; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds( 1000 - std::max(audio_delay_ms, video_delay_ms)); // Simulate base_target_delay minimum delay in the VCM. total_video_delay_ms = base_target_delay; EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay + 2 * filtered_move, total_video_delay_ms); EXPECT_EQ(base_target_delay, extra_audio_delay_ms); current_audio_delay_ms = extra_audio_delay_ms; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds( 1000 - std::max(audio_delay_ms, video_delay_ms)); // Simulate base_target_delay minimum delay in the VCM. total_video_delay_ms = base_target_delay; EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay + 3 * filtered_move, total_video_delay_ms); EXPECT_EQ(base_target_delay, extra_audio_delay_ms); // Simulate that NetEQ introduces some audio delay. current_audio_delay_ms = base_target_delay + kNeteqDelayIncrease; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds( 1000 - std::max(audio_delay_ms, video_delay_ms)); // Simulate base_target_delay minimum delay in the VCM. total_video_delay_ms = base_target_delay; EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); filtered_move = 3 * filtered_move + (kNeteqDelayIncrease + audio_delay_ms - video_delay_ms) / kSmoothingFilter; EXPECT_EQ(base_target_delay + filtered_move, total_video_delay_ms); EXPECT_EQ(base_target_delay, extra_audio_delay_ms); // Simulate that NetEQ reduces its delay. current_audio_delay_ms = base_target_delay + kNeteqDelayDecrease; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds( 1000 - std::max(audio_delay_ms, video_delay_ms)); // Simulate base_target_delay minimum delay in the VCM. total_video_delay_ms = base_target_delay; EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); filtered_move = filtered_move + (kNeteqDelayDecrease + audio_delay_ms - video_delay_ms) / kSmoothingFilter; EXPECT_EQ(base_target_delay + filtered_move, total_video_delay_ms); EXPECT_EQ(base_target_delay, extra_audio_delay_ms); } void BothDelayedVideoLaterTest(int base_target_delay) { int current_audio_delay_ms = base_target_delay; int audio_delay_ms = base_target_delay + 100; int video_delay_ms = base_target_delay + 300; int extra_audio_delay_ms = 0; int total_video_delay_ms = base_target_delay; EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay, total_video_delay_ms); // The audio delay is not allowed to change more than this in 1 second. EXPECT_GE(base_target_delay + kMaxAudioDiffMs, extra_audio_delay_ms); current_audio_delay_ms = extra_audio_delay_ms; int current_extra_delay_ms = extra_audio_delay_ms; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay, total_video_delay_ms); // The audio delay is not allowed to change more than the half of the // required change in delay. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease( current_audio_delay_ms, base_target_delay + video_delay_ms - audio_delay_ms), extra_audio_delay_ms); current_audio_delay_ms = extra_audio_delay_ms; current_extra_delay_ms = extra_audio_delay_ms; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay, total_video_delay_ms); // The audio delay is not allowed to change more than the half of the // required change in delay. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease( current_audio_delay_ms, base_target_delay + video_delay_ms - audio_delay_ms), extra_audio_delay_ms); current_extra_delay_ms = extra_audio_delay_ms; // Simulate that NetEQ for some reason reduced the delay. current_audio_delay_ms = base_target_delay + 10; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay, total_video_delay_ms); // Since we only can ask NetEQ for a certain amount of extra delay, and // we only measure the total NetEQ delay, we will ask for additional delay // here to try to stay in sync. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease( current_audio_delay_ms, base_target_delay + video_delay_ms - audio_delay_ms), extra_audio_delay_ms); current_extra_delay_ms = extra_audio_delay_ms; // Simulate that NetEQ for some reason significantly increased the delay. current_audio_delay_ms = base_target_delay + 350; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(audio_delay_ms, video_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(base_target_delay, total_video_delay_ms); // The audio delay is not allowed to change more than the half of the // required change in delay. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease( current_audio_delay_ms, base_target_delay + video_delay_ms - audio_delay_ms), extra_audio_delay_ms); } int MaxAudioDelayIncrease(int current_audio_delay_ms, int delay_ms) { return std::min((delay_ms - current_audio_delay_ms) / kSmoothingFilter, kMaxAudioDiffMs); } int MaxAudioDelayDecrease(int current_audio_delay_ms, int delay_ms) { return std::max((delay_ms - current_audio_delay_ms) / kSmoothingFilter, -kMaxAudioDiffMs); } StreamSynchronization sync_; SimulatedClock clock_sender_; SimulatedClock clock_receiver_; double audio_clock_drift_ = 1.0; double video_clock_drift_ = 1.0; }; TEST_F(StreamSynchronizationTest, NoDelay) { uint32_t current_audio_delay_ms = 0; int extra_audio_delay_ms = 0; int total_video_delay_ms = 0; EXPECT_FALSE(DelayedStreams(0, 0, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, extra_audio_delay_ms); EXPECT_EQ(0, total_video_delay_ms); } TEST_F(StreamSynchronizationTest, VideoDelay) { uint32_t current_audio_delay_ms = 0; int delay_ms = 200; int extra_audio_delay_ms = 0; int total_video_delay_ms = 0; EXPECT_TRUE(DelayedStreams(delay_ms, 0, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, extra_audio_delay_ms); // The video delay is not allowed to change more than this in 1 second. EXPECT_EQ(delay_ms / kSmoothingFilter, total_video_delay_ms); clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); // Simulate 0 minimum delay in the VCM. total_video_delay_ms = 0; EXPECT_TRUE(DelayedStreams(delay_ms, 0, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, extra_audio_delay_ms); // The video delay is not allowed to change more than this in 1 second. EXPECT_EQ(2 * delay_ms / kSmoothingFilter, total_video_delay_ms); clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); // Simulate 0 minimum delay in the VCM. total_video_delay_ms = 0; EXPECT_TRUE(DelayedStreams(delay_ms, 0, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, extra_audio_delay_ms); EXPECT_EQ(3 * delay_ms / kSmoothingFilter, total_video_delay_ms); } TEST_F(StreamSynchronizationTest, AudioDelay) { int current_audio_delay_ms = 0; int delay_ms = 200; int extra_audio_delay_ms = 0; int total_video_delay_ms = 0; EXPECT_TRUE(DelayedStreams(0, delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, total_video_delay_ms); // The audio delay is not allowed to change more than this in 1 second. EXPECT_EQ(delay_ms / kSmoothingFilter, extra_audio_delay_ms); current_audio_delay_ms = extra_audio_delay_ms; int current_extra_delay_ms = extra_audio_delay_ms; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(0, delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, total_video_delay_ms); // The audio delay is not allowed to change more than the half of the required // change in delay. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease(current_audio_delay_ms, delay_ms), extra_audio_delay_ms); current_audio_delay_ms = extra_audio_delay_ms; current_extra_delay_ms = extra_audio_delay_ms; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(0, delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, total_video_delay_ms); // The audio delay is not allowed to change more than the half of the required // change in delay. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease(current_audio_delay_ms, delay_ms), extra_audio_delay_ms); current_extra_delay_ms = extra_audio_delay_ms; // Simulate that NetEQ for some reason reduced the delay. current_audio_delay_ms = 10; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(0, delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, total_video_delay_ms); // Since we only can ask NetEQ for a certain amount of extra delay, and // we only measure the total NetEQ delay, we will ask for additional delay // here to try to EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayIncrease(current_audio_delay_ms, delay_ms), extra_audio_delay_ms); current_extra_delay_ms = extra_audio_delay_ms; // Simulate that NetEQ for some reason significantly increased the delay. current_audio_delay_ms = 350; clock_sender_.AdvanceTimeMilliseconds(1000); clock_receiver_.AdvanceTimeMilliseconds(800); EXPECT_TRUE(DelayedStreams(0, delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); EXPECT_EQ(0, total_video_delay_ms); // The audio delay is not allowed to change more than the half of the required // change in delay. EXPECT_EQ(current_extra_delay_ms + MaxAudioDelayDecrease(current_audio_delay_ms, delay_ms), extra_audio_delay_ms); } TEST_F(StreamSynchronizationTest, BothDelayedVideoLater) { BothDelayedVideoLaterTest(0); } TEST_F(StreamSynchronizationTest, BothDelayedVideoLaterAudioClockDrift) { audio_clock_drift_ = 1.05; BothDelayedVideoLaterTest(0); } TEST_F(StreamSynchronizationTest, BothDelayedVideoLaterVideoClockDrift) { video_clock_drift_ = 1.05; BothDelayedVideoLaterTest(0); } TEST_F(StreamSynchronizationTest, BothDelayedAudioLater) { BothDelayedAudioLaterTest(0); } TEST_F(StreamSynchronizationTest, BothDelayedAudioClockDrift) { audio_clock_drift_ = 1.05; BothDelayedAudioLaterTest(0); } TEST_F(StreamSynchronizationTest, BothDelayedVideoClockDrift) { video_clock_drift_ = 1.05; BothDelayedAudioLaterTest(0); } TEST_F(StreamSynchronizationTest, BaseDelay) { int base_target_delay_ms = 2000; int current_audio_delay_ms = 2000; int extra_audio_delay_ms = 0; int total_video_delay_ms = base_target_delay_ms; sync_.SetTargetBufferingDelay(base_target_delay_ms); // We are in sync don't change. EXPECT_FALSE(DelayedStreams(base_target_delay_ms, base_target_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); // Triggering another call with the same values. Delay should not be modified. base_target_delay_ms = 2000; current_audio_delay_ms = base_target_delay_ms; total_video_delay_ms = base_target_delay_ms; sync_.SetTargetBufferingDelay(base_target_delay_ms); // We are in sync don't change. EXPECT_FALSE(DelayedStreams(base_target_delay_ms, base_target_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); // Changing delay value - intended to test this module only. In practice it // would take VoE time to adapt. base_target_delay_ms = 5000; current_audio_delay_ms = base_target_delay_ms; total_video_delay_ms = base_target_delay_ms; sync_.SetTargetBufferingDelay(base_target_delay_ms); // We are in sync don't change. EXPECT_FALSE(DelayedStreams(base_target_delay_ms, base_target_delay_ms, current_audio_delay_ms, &extra_audio_delay_ms, &total_video_delay_ms)); } TEST_F(StreamSynchronizationTest, BothDelayedAudioLaterWithBaseDelay) { int base_target_delay_ms = 3000; sync_.SetTargetBufferingDelay(base_target_delay_ms); BothDelayedAudioLaterTest(base_target_delay_ms); } TEST_F(StreamSynchronizationTest, BothDelayedAudioClockDriftWithBaseDelay) { int base_target_delay_ms = 3000; sync_.SetTargetBufferingDelay(base_target_delay_ms); audio_clock_drift_ = 1.05; BothDelayedAudioLaterTest(base_target_delay_ms); } TEST_F(StreamSynchronizationTest, BothDelayedVideoClockDriftWithBaseDelay) { int base_target_delay_ms = 3000; sync_.SetTargetBufferingDelay(base_target_delay_ms); video_clock_drift_ = 1.05; BothDelayedAudioLaterTest(base_target_delay_ms); } TEST_F(StreamSynchronizationTest, BothDelayedVideoLaterWithBaseDelay) { int base_target_delay_ms = 2000; sync_.SetTargetBufferingDelay(base_target_delay_ms); BothDelayedVideoLaterTest(base_target_delay_ms); } TEST_F(StreamSynchronizationTest, BothDelayedVideoLaterAudioClockDriftWithBaseDelay) { int base_target_delay_ms = 2000; audio_clock_drift_ = 1.05; sync_.SetTargetBufferingDelay(base_target_delay_ms); BothDelayedVideoLaterTest(base_target_delay_ms); } TEST_F(StreamSynchronizationTest, BothDelayedVideoLaterVideoClockDriftWithBaseDelay) { int base_target_delay_ms = 2000; video_clock_drift_ = 1.05; sync_.SetTargetBufferingDelay(base_target_delay_ms); BothDelayedVideoLaterTest(base_target_delay_ms); } } // namespace webrtc
9,205
302
<filename>package.json { "name": "vue-google-signin-button", "version": "1.0.4", "description": "A simple plugin to include a Google sign-in button into your web app", "main": "dist/vue-google-signin-button.min.js", "scripts": { "lint": "./node_modules/.bin/eslint index.js", "build": "./node_modules/.bin/eslint index.js && BABEL_ENV=production && babel index.js -o ./dist/vue-google-signin-button.min.js" }, "eslintConfig": { "extends": "vue" }, "babel": { "presets": [ "es2015", "babili" ] }, "keywords": [ "Vue", "Google", "oAuth", "sign-in", "sign in", "log-in", "log in" ], "author": "<NAME> <<EMAIL>>", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/phanan/vue-google-signin-button/" }, "devDependencies": { "babel-cli": "^6.18.0", "babel-preset-babili": "0.0.9", "babel-preset-es2015": "^6.18.0", "eslint": "^4.18.2", "eslint-config-vue": "^2.0.1", "eslint-plugin-vue": "^1.0.0" } }
510
482
#include "test.h" #include "sidx_api_test.h" int main(int argc, char** argv) { printf("Running main() from gtest_main.cc\n"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
81
1,444
<reponame>amc8391/mage<filename>Mage.Sets/src/mage/sets/KaladeshPromos.java<gh_stars>1000+ package mage.sets; import mage.cards.ExpansionSet; import mage.constants.Rarity; import mage.constants.SetType; /** * https://scryfall.com/sets/pkld */ public class KaladeshPromos extends ExpansionSet { private static final KaladeshPromos instance = new KaladeshPromos(); public static KaladeshPromos getInstance() { return instance; } private KaladeshPromos() { super("Kaladesh Promos", "PKLD", ExpansionSet.buildDate(2016, 9, 30), SetType.PROMOTIONAL); this.hasBoosters = false; this.hasBasicLands = false; cards.add(new SetCardInfo("Aetherflux Reservoir", "192s", Rarity.RARE, mage.cards.a.AetherfluxReservoir.class)); cards.add(new SetCardInfo("Aethersquall Ancient", "39s", Rarity.RARE, mage.cards.a.AethersquallAncient.class)); cards.add(new SetCardInfo("Aetherstorm Roc", "3s", Rarity.RARE, mage.cards.a.AetherstormRoc.class)); cards.add(new SetCardInfo("Aetherworks Marvel", "193s", Rarity.MYTHIC, mage.cards.a.AetherworksMarvel.class)); cards.add(new SetCardInfo("Angel of Invention", "4s", Rarity.MYTHIC, mage.cards.a.AngelOfInvention.class)); cards.add(new SetCardInfo("Animation Module", "194s", Rarity.RARE, mage.cards.a.AnimationModule.class)); cards.add(new SetCardInfo("Architect of the Untamed", "143s", Rarity.RARE, mage.cards.a.ArchitectOfTheUntamed.class)); cards.add(new SetCardInfo("Authority of the Consuls", "5s", Rarity.RARE, mage.cards.a.AuthorityOfTheConsuls.class)); cards.add(new SetCardInfo("Blooming Marsh", "243s", Rarity.RARE, mage.cards.b.BloomingMarsh.class)); cards.add(new SetCardInfo("Bomat Courier", "199s", Rarity.RARE, mage.cards.b.BomatCourier.class)); cards.add(new SetCardInfo("Botanical Sanctum", "244s", Rarity.RARE, mage.cards.b.BotanicalSanctum.class)); cards.add(new SetCardInfo("Bristling Hydra", "147s", Rarity.RARE, mage.cards.b.BristlingHydra.class)); cards.add(new SetCardInfo("Captured by the Consulate", "8s", Rarity.RARE, mage.cards.c.CapturedByTheConsulate.class)); cards.add(new SetCardInfo("Cataclysmic Gearhulk", "9s", Rarity.MYTHIC, mage.cards.c.CataclysmicGearhulk.class)); cards.add(new SetCardInfo("Chandra, Torch of Defiance", "110s", Rarity.MYTHIC, mage.cards.c.ChandraTorchOfDefiance.class)); cards.add(new SetCardInfo("Chief of the Foundry", 200, Rarity.UNCOMMON, mage.cards.c.ChiefOfTheFoundry.class)); cards.add(new SetCardInfo("Combustible Gearhulk", "112p", Rarity.MYTHIC, mage.cards.c.CombustibleGearhulk.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Combustible Gearhulk", "112s", Rarity.MYTHIC, mage.cards.c.CombustibleGearhulk.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Concealed Courtyard", "245s", Rarity.RARE, mage.cards.c.ConcealedCourtyard.class)); cards.add(new SetCardInfo("Confiscation Coup", "41s", Rarity.RARE, mage.cards.c.ConfiscationCoup.class)); cards.add(new SetCardInfo("Cultivator of Blades", 151, Rarity.RARE, mage.cards.c.CultivatorOfBlades.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Cultivator of Blades", "151s", Rarity.RARE, mage.cards.c.CultivatorOfBlades.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Cultivator's Caravan", "203s", Rarity.RARE, mage.cards.c.CultivatorsCaravan.class)); cards.add(new SetCardInfo("Deadlock Trap", "204s", Rarity.RARE, mage.cards.d.DeadlockTrap.class)); cards.add(new SetCardInfo("Demon of Dark Schemes", "73s", Rarity.MYTHIC, mage.cards.d.DemonOfDarkSchemes.class)); cards.add(new SetCardInfo("Depala, Pilot Exemplar", "178s", Rarity.RARE, mage.cards.d.DepalaPilotExemplar.class)); cards.add(new SetCardInfo("Dovin Baan", "179s", Rarity.MYTHIC, mage.cards.d.DovinBaan.class)); cards.add(new SetCardInfo("Dubious Challenge", "152s", Rarity.RARE, mage.cards.d.DubiousChallenge.class)); cards.add(new SetCardInfo("Dynavolt Tower", "208s", Rarity.RARE, mage.cards.d.DynavoltTower.class)); cards.add(new SetCardInfo("Electrostatic Pummeler", "210s", Rarity.RARE, mage.cards.e.ElectrostaticPummeler.class)); cards.add(new SetCardInfo("Eliminate the Competition", "78s", Rarity.RARE, mage.cards.e.EliminateTheCompetition.class)); cards.add(new SetCardInfo("Essence Extraction", 80, Rarity.UNCOMMON, mage.cards.e.EssenceExtraction.class)); cards.add(new SetCardInfo("Fateful Showdown", "114s", Rarity.RARE, mage.cards.f.FatefulShowdown.class)); cards.add(new SetCardInfo("Fleetwheel Cruiser", "214s", Rarity.RARE, mage.cards.f.FleetwheelCruiser.class)); cards.add(new SetCardInfo("Fumigate", "15s", Rarity.RARE, mage.cards.f.Fumigate.class)); cards.add(new SetCardInfo("Ghirapur Orrery", "216s", Rarity.RARE, mage.cards.g.GhirapurOrrery.class)); cards.add(new SetCardInfo("Gonti, Lord of Luxury", "84s", Rarity.RARE, mage.cards.g.GontiLordOfLuxury.class)); cards.add(new SetCardInfo("Insidious Will", "52s", Rarity.RARE, mage.cards.i.InsidiousWill.class)); cards.add(new SetCardInfo("Inspiring Vantage", "246s", Rarity.RARE, mage.cards.i.InspiringVantage.class)); cards.add(new SetCardInfo("Inventors' Fair", "247s", Rarity.RARE, mage.cards.i.InventorsFair.class)); cards.add(new SetCardInfo("Kambal, Consul of Allocation", "183s", Rarity.RARE, mage.cards.k.KambalConsulOfAllocation.class)); cards.add(new SetCardInfo("Key to the City", "220s", Rarity.RARE, mage.cards.k.KeyToTheCity.class)); cards.add(new SetCardInfo("Lathnu Hellion", "121s", Rarity.RARE, mage.cards.l.LathnuHellion.class)); cards.add(new SetCardInfo("Lost Legacy", "88s", Rarity.RARE, mage.cards.l.LostLegacy.class)); cards.add(new SetCardInfo("Madcap Experiment", "122s", Rarity.RARE, mage.cards.m.MadcapExperiment.class)); cards.add(new SetCardInfo("Marionette Master", "90s", Rarity.RARE, mage.cards.m.MarionetteMaster.class)); cards.add(new SetCardInfo("Master Trinketeer", "21s", Rarity.RARE, mage.cards.m.MasterTrinketeer.class)); cards.add(new SetCardInfo("Metallurgic Summonings", "56s", Rarity.MYTHIC, mage.cards.m.MetallurgicSummonings.class)); cards.add(new SetCardInfo("Metalwork Colossus", "222s", Rarity.RARE, mage.cards.m.MetalworkColossus.class)); cards.add(new SetCardInfo("Midnight Oil", "92s", Rarity.RARE, mage.cards.m.MidnightOil.class)); cards.add(new SetCardInfo("Multiform Wonder", "223s", Rarity.RARE, mage.cards.m.MultiformWonder.class)); cards.add(new SetCardInfo("Nissa, Vital Force", "163s", Rarity.MYTHIC, mage.cards.n.NissaVitalForce.class)); cards.add(new SetCardInfo("Noxious Gearhulk", "96p", Rarity.MYTHIC, mage.cards.n.NoxiousGearhulk.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Noxious Gearhulk", "96s", Rarity.MYTHIC, mage.cards.n.NoxiousGearhulk.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Oviya Pashiri, Sage Lifecrafter", "165s", Rarity.RARE, mage.cards.o.OviyaPashiriSageLifecrafter.class)); cards.add(new SetCardInfo("Padeem, Consul of Innovation", "59s", Rarity.RARE, mage.cards.p.PadeemConsulOfInnovation.class)); cards.add(new SetCardInfo("Panharmonicon", "226s", Rarity.RARE, mage.cards.p.Panharmonicon.class)); cards.add(new SetCardInfo("Paradoxical Outcome", "60s", Rarity.RARE, mage.cards.p.ParadoxicalOutcome.class)); cards.add(new SetCardInfo("Pia Nalaar", "124s", Rarity.RARE, mage.cards.p.PiaNalaar.class)); cards.add(new SetCardInfo("Rashmi, Eternities Crafter", "184s", Rarity.MYTHIC, mage.cards.r.RashmiEternitiesCrafter.class)); cards.add(new SetCardInfo("Saheeli Rai", "186s", Rarity.MYTHIC, mage.cards.s.SaheeliRai.class)); cards.add(new SetCardInfo("Saheeli's Artistry", 62, Rarity.RARE, mage.cards.s.SaheelisArtistry.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Saheeli's Artistry", "62s", Rarity.RARE, mage.cards.s.SaheelisArtistry.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Scrapheap Scrounger", "231s", Rarity.RARE, mage.cards.s.ScrapheapScrounger.class)); cards.add(new SetCardInfo("Skyship Stalker", 130, Rarity.RARE, mage.cards.s.SkyshipStalker.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Skyship Stalker", "130s", Rarity.RARE, mage.cards.s.SkyshipStalker.class, NON_FULL_USE_VARIOUS)); cards.add(new SetCardInfo("Skysovereign, Consul Flagship", "234s", Rarity.MYTHIC, mage.cards.s.SkysovereignConsulFlagship.class)); cards.add(new SetCardInfo("Smuggler's Copter", "235s", Rarity.RARE, mage.cards.s.SmugglersCopter.class)); cards.add(new SetCardInfo("Spirebluff Canal", "249s", Rarity.RARE, mage.cards.s.SpirebluffCanal.class)); cards.add(new SetCardInfo("Syndicate Trafficker", "101s", Rarity.RARE, mage.cards.s.SyndicateTrafficker.class)); cards.add(new SetCardInfo("Territorial Gorger", "136s", Rarity.RARE, mage.cards.t.TerritorialGorger.class)); cards.add(new SetCardInfo("Toolcraft Exemplar", "32s", Rarity.RARE, mage.cards.t.ToolcraftExemplar.class)); cards.add(new SetCardInfo("Torrential Gearhulk", "67s", Rarity.MYTHIC, mage.cards.t.TorrentialGearhulk.class)); cards.add(new SetCardInfo("Verdurous Gearhulk", "172s", Rarity.MYTHIC, mage.cards.v.VerdurousGearhulk.class)); cards.add(new SetCardInfo("Wildest Dreams", "174s", Rarity.RARE, mage.cards.w.WildestDreams.class)); } }
3,864
5,169
<gh_stars>1000+ { "name": "iosVoiceBPMLib", "version": "0.0.1", "summary": "Library for Cooey voice based BPMeter", "description": "This is a library for using Cooey voice based BPMeter in any app.", "homepage": "https://cooeydevelopers.visualstudio.com/IOS/_git/iOSVoiceBPMLib", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<YOUR NAME HERE>": "<YOUR EMAIL HERE>" }, "source": { "git": "https://cooeydevelopers.visualstudio.com/IOS/_git/iOSVoiceBPMLib", "tag": "0.0.1" }, "platforms": { "ios": "9.0" }, "source_files": "Bluetooth/*", "pushed_with_swift_version": "3.0" }
276
1,130
<gh_stars>1000+ from bokeh.models import Div from panel.layout import Card from panel.models import Card as CardModel from panel.pane import HTML def test_card_model_cache_cleanup(document, comm): html = HTML() l = Card(header=html) model = l.get_root(document, comm) ref = model.ref['id'] assert ref in l._models assert l._models[ref] == (model, None) assert ref in html._models l._cleanup(model) assert l._models == {} assert html._models == {} def test_card_get_root(document, comm): div1 = Div() div2 = Div() layout = Card(div1, div2) model = layout.get_root(document, comm=comm) ref = model.ref['id'] header = layout._header_layout._models[ref][0] assert isinstance(model, CardModel) assert model.children == [header, div1, div2] assert header.children[0].text == "&amp;#8203;" def test_card_get_root_title(document, comm): div1 = Div() div2 = Div() layout = Card(div1, div2, title='Test') model = layout.get_root(document, comm=comm) ref = model.ref['id'] header = layout._header_layout._models[ref][0] assert isinstance(model, CardModel) assert model.children == [header, div1, div2] assert header.children[0].text == "Test" div3 = Div() layout.header = div3 assert header.children[0] is div3 layout.header = None assert header.children[0].text == "Test" def test_card_get_root_header(document, comm): div1 = Div() div2 = Div() div3 = Div() layout = Card(div1, div2, header=div3) model = layout.get_root(document, comm=comm) ref = model.ref['id'] header = layout._header_layout._models[ref][0] assert isinstance(model, CardModel) assert model.children == [header, div1, div2] assert header.children[0] is div3
691
555
/* Copyright 2021 Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hip/hip_runtime.h" #include"realm_defines.h" #ifdef REALM_USE_HIP #include "realm/hip/hiphijack_api.h" #endif #include "circuit.h" template<typename AT, int SEGMENTS> struct SegmentAccessors { public: __host__ __device__ inline AT& operator[](unsigned index) { return accessors[index]; } __host__ __device__ inline const AT& operator[](unsigned index) const { return accessors[index]; } public: AT accessors[SEGMENTS]; }; __device__ __forceinline__ float find_node_voltage(const AccessorROfloat &pvt, const AccessorROfloat &shr, const AccessorROfloat &ghost, Point<1> ptr, PointerLocation loc) { switch (loc) { case PRIVATE_PTR: return pvt[ptr]; case SHARED_PTR: return shr[ptr]; case GHOST_PTR: return ghost[ptr]; default: break; // assert(false); } return 0.f; } __global__ void calc_new_currents_kernel(Point<1> first, int num_wires, float dt, int steps, const AccessorROpoint fa_in_ptr, const AccessorROpoint fa_out_ptr, const AccessorROloc fa_in_loc, const AccessorROloc fa_out_loc, const AccessorROfloat fa_inductance, const AccessorROfloat fa_resistance, const AccessorROfloat fa_wire_cap, const AccessorROfloat fa_pvt_voltage, const AccessorROfloat fa_shr_voltage, const AccessorROfloat fa_ghost_voltage, const SegmentAccessors<AccessorRWfloat_nobounds,WIRE_SEGMENTS> fa_currents, const SegmentAccessors<AccessorRWfloat_nobounds,WIRE_SEGMENTS-1> fa_voltages) { const int tid = blockIdx.x * blockDim.x + threadIdx.x; // We can do this because we know we have SOA layout and wires are dense if (tid < num_wires) { const Point<1> wire_ptr = first + tid; float recip_dt = 1.f/dt; float temp_v[WIRE_SEGMENTS+1]; float temp_i[WIRE_SEGMENTS]; float old_i[WIRE_SEGMENTS]; float old_v[WIRE_SEGMENTS-1]; #pragma unroll for (int i = 0; i < WIRE_SEGMENTS; i++) { temp_i[i] = fa_currents[i][wire_ptr]; old_i[i] = temp_i[i]; } #pragma unroll for (int i = 0; i < (WIRE_SEGMENTS-1); i++) { temp_v[i+1] = fa_voltages[i][wire_ptr]; old_v[i] = temp_v[i+1]; } Point<1> in_ptr = fa_in_ptr[wire_ptr]; PointerLocation in_loc = fa_in_loc[wire_ptr]; temp_v[0] = find_node_voltage(fa_pvt_voltage, fa_shr_voltage, fa_ghost_voltage, in_ptr, in_loc); Point<1> out_ptr = fa_out_ptr[wire_ptr]; PointerLocation out_loc = fa_out_loc[wire_ptr]; temp_v[WIRE_SEGMENTS] = find_node_voltage(fa_pvt_voltage, fa_shr_voltage, fa_ghost_voltage, in_ptr, in_loc); // Solve the RLC model iteratively float inductance = fa_inductance[wire_ptr]; float recip_resistance = 1.f/fa_resistance[wire_ptr]; float recip_capacitance = 1.f/fa_wire_cap[wire_ptr]; for (int j = 0; j < steps; j++) { #pragma unroll for (int i = 0; i < WIRE_SEGMENTS; i++) { temp_i[i] = ((temp_v[i] - temp_v[i+1]) - (inductance * (temp_i[i] - old_i[i]) * recip_dt)) * recip_resistance; } #pragma unroll for (int i = 0; i < (WIRE_SEGMENTS-1); i++) { temp_v[i+1] = old_v[i] + dt * (temp_i[i] - temp_i[i+1]) * recip_capacitance; } } // Write out the result #pragma unroll for (int i = 0; i < WIRE_SEGMENTS; i++) fa_currents[i][wire_ptr] = temp_i[i]; #pragma unroll for (int i = 0; i < (WIRE_SEGMENTS-1); i++) fa_voltages[i][wire_ptr] = temp_v[i+1]; } } /*static*/ __host__ void CalcNewCurrentsTask::gpu_base_impl(const CircuitPiece &piece, const std::vector<PhysicalRegion> &regions) { #ifndef DISABLE_MATH // the segment accessors don't need to pay for bounds checks because // other wire accessors below will use the same bounds and be checked // first SegmentAccessors<AccessorRWfloat_nobounds,WIRE_SEGMENTS> fa_currents; for (int i = 0; i < WIRE_SEGMENTS; i++) fa_currents[i] = AccessorRWfloat_nobounds(regions[0], FID_CURRENT+i); SegmentAccessors<AccessorRWfloat_nobounds,WIRE_SEGMENTS-1> fa_voltages; for (int i = 0; i < (WIRE_SEGMENTS-1); i++) fa_voltages[i] = AccessorRWfloat_nobounds(regions[0], FID_WIRE_VOLTAGE+i); const AccessorROpoint fa_in_ptr(regions[1], FID_IN_PTR); const AccessorROpoint fa_out_ptr(regions[1], FID_OUT_PTR); const AccessorROloc fa_in_loc(regions[1], FID_IN_LOC); const AccessorROloc fa_out_loc(regions[1], FID_OUT_LOC); const AccessorROfloat fa_inductance(regions[1], FID_INDUCTANCE); const AccessorROfloat fa_resistance(regions[1], FID_RESISTANCE); const AccessorROfloat fa_wire_cap(regions[1], FID_WIRE_CAP); const AccessorROfloat fa_pvt_voltage(regions[2], FID_NODE_VOLTAGE); const AccessorROfloat fa_shr_voltage(regions[3], FID_NODE_VOLTAGE); const AccessorROfloat fa_ghost_voltage(regions[4], FID_NODE_VOLTAGE); const int threads_per_block = 256; const int num_blocks = (piece.num_wires + (threads_per_block-1)) / threads_per_block; hipLaunchKernelGGL(calc_new_currents_kernel, dim3(num_blocks), dim3(threads_per_block), 0, hipGetTaskStream(), piece.first_wire, piece.num_wires, piece.dt, piece.steps, fa_in_ptr, fa_out_ptr, fa_in_loc, fa_out_loc, fa_inductance, fa_resistance, fa_wire_cap, fa_pvt_voltage, fa_shr_voltage, fa_ghost_voltage, fa_currents, fa_voltages); #endif } typedef ReductionAccessor<SumReduction<float>,false/*exclusive*/,1,coord_t, Realm::AffineAccessor<float,1,coord_t> > AccessorRDfloat; __device__ __forceinline__ void reduce_local(const AccessorRWfloat &pvt, const AccessorRDfloat &shr, const AccessorRDfloat &ghost, Point<1> ptr, PointerLocation loc, float value) { switch (loc) { case PRIVATE_PTR: SumReduction<float>::apply<true/*exclusive*/>(pvt[ptr], value); break; case SHARED_PTR: shr[ptr] <<= value; break; case GHOST_PTR: ghost[ptr] <<= value; break; default: break; // assert(false); // should never make it here } } __global__ void distribute_charge_kernel(Point<1> first, const int num_wires, float dt, const AccessorROpoint fa_in_ptr, const AccessorROpoint fa_out_ptr, const AccessorROloc fa_in_loc, const AccessorROloc fa_out_loc, const AccessorROfloat fa_in_current, const AccessorROfloat fa_out_current, const AccessorRWfloat fa_pvt_charge, const AccessorRDfloat fa_shr_charge, const AccessorRDfloat fa_ghost_charge) { const int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid < num_wires) { const Point<1> wire_ptr = first + tid; float in_dq = -dt * fa_in_current[wire_ptr]; float out_dq = dt * fa_out_current[wire_ptr]; Point<1> in_ptr = fa_in_ptr[wire_ptr]; PointerLocation in_loc = fa_in_loc[wire_ptr]; reduce_local(fa_pvt_charge, fa_shr_charge, fa_ghost_charge, in_ptr, in_loc, in_dq); Point<1> out_ptr = fa_out_ptr[wire_ptr]; PointerLocation out_loc = fa_out_loc[wire_ptr]; reduce_local(fa_pvt_charge, fa_shr_charge, fa_ghost_charge, out_ptr, out_loc, out_dq); } } /*static*/ __host__ void DistributeChargeTask::gpu_base_impl(const CircuitPiece &piece, const std::vector<PhysicalRegion> &regions) { #ifndef DISABLE_MATH const AccessorROpoint fa_in_ptr(regions[0], FID_IN_PTR); const AccessorROpoint fa_out_ptr(regions[0], FID_OUT_PTR); const AccessorROloc fa_in_loc(regions[0], FID_IN_LOC); const AccessorROloc fa_out_loc(regions[0], FID_OUT_LOC); const AccessorROfloat fa_in_current(regions[0], FID_CURRENT); const AccessorROfloat fa_out_current(regions[0], FID_CURRENT+WIRE_SEGMENTS-1); const AccessorRWfloat fa_pvt_charge(regions[1], FID_CHARGE); const AccessorRDfloat fa_shr_charge(regions[2], FID_CHARGE, REDUCE_ID); const AccessorRDfloat fa_ghost_charge(regions[3], FID_CHARGE, REDUCE_ID); const int threads_per_block = 256; const int num_blocks = (piece.num_wires + (threads_per_block-1)) / threads_per_block; hipLaunchKernelGGL(distribute_charge_kernel, dim3(num_blocks), dim3(threads_per_block), 0, hipGetTaskStream(), piece.first_wire, piece.num_wires, piece.dt, fa_in_ptr, fa_out_ptr, fa_in_loc, fa_out_loc, fa_in_current, fa_out_current, fa_pvt_charge, fa_shr_charge, fa_ghost_charge); #endif } __global__ void update_voltages_kernel(Point<1> first, const int num_nodes, const AccessorRWfloat fa_pvt_voltage, const AccessorRWfloat fa_shr_voltage, const AccessorRWfloat fa_pvt_charge, const AccessorRWfloat fa_shr_charge, const AccessorROfloat fa_pvt_cap, const AccessorROfloat fa_shr_cap, const AccessorROfloat fa_pvt_leakage, const AccessorROfloat fa_shr_leakage, const AccessorROloc fa_ptr_loc) { const int tid = blockIdx.x * blockDim.x + threadIdx.x; if (tid < num_nodes) { const Point<1> node_ptr = first + tid; PointerLocation node_loc = fa_ptr_loc[node_ptr]; if (node_loc == PRIVATE_PTR) { float voltage = fa_pvt_voltage[node_ptr]; float charge = fa_pvt_charge[node_ptr]; float capacitance = fa_pvt_cap[node_ptr]; float leakage = fa_pvt_leakage[node_ptr]; voltage += (charge / capacitance); voltage *= (1.f - leakage); fa_pvt_voltage[node_ptr] = voltage; fa_pvt_charge[node_ptr] = 0.f; } else { float voltage = fa_shr_voltage[node_ptr]; float charge = fa_shr_charge[node_ptr]; float capacitance = fa_shr_cap[node_ptr]; float leakage = fa_shr_leakage[node_ptr]; voltage += (charge / capacitance); voltage *= (1.f - leakage); fa_pvt_voltage[node_ptr] = voltage; fa_pvt_charge[node_ptr] = 0.f; } } } /*static*/ __host__ void UpdateVoltagesTask::gpu_base_impl(const CircuitPiece &piece, const std::vector<PhysicalRegion> &regions) { #ifndef DISABLE_MATH const AccessorRWfloat fa_pvt_voltage(regions[0], FID_NODE_VOLTAGE); const AccessorRWfloat fa_pvt_charge(regions[0], FID_CHARGE); const AccessorRWfloat fa_shr_voltage(regions[1], FID_NODE_VOLTAGE); const AccessorRWfloat fa_shr_charge(regions[1], FID_CHARGE); const AccessorROfloat fa_pvt_cap(regions[2], FID_NODE_CAP); const AccessorROfloat fa_pvt_leakage(regions[2], FID_LEAKAGE); const AccessorROfloat fa_shr_cap(regions[3], FID_NODE_CAP); const AccessorROfloat fa_shr_leakage(regions[3], FID_LEAKAGE); const AccessorROloc fa_ptr_loc(regions[4], FID_LOCATOR); const int threads_per_block = 256; const int num_blocks = (piece.num_nodes + (threads_per_block-1)) / threads_per_block; hipLaunchKernelGGL(update_voltages_kernel, dim3(num_blocks), dim3(threads_per_block), 0, hipGetTaskStream(), piece.first_node, piece.num_nodes, fa_pvt_voltage, fa_shr_voltage, fa_pvt_charge, fa_shr_charge, fa_pvt_cap, fa_shr_cap, fa_pvt_leakage, fa_shr_leakage, fa_ptr_loc); #endif }
8,007
5,169
{ "name": "PushApps", "version": "1.0.0", "summary": "PushApps - the first Push Notification Enrichment Platform", "description": "PushApps SDK enables you to send enriched push notifications via the PushApps platform.", "homepage": "https://www.pushapps.mobi", "license": "MIT", "authors": { "PushApps": "<EMAIL>" }, "source": { "git": "https://github.com/PushAppsPlatform/pushapps-ios-sdk.git", "tag": "1.0.0" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "vendored_frameworks": "Framework/PushApps.framework" }
211
7,113
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.otter.shared.arbitrate.impl.zookeeper; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import com.alibaba.otter.shared.common.utils.thread.NamedThreadFactory; /** * 包装ZooKeeper的Watcher接口,支持Async的异步调用处理 * * <pre> * 说明: * 1. zookeeper针对watcher的调用是以单线程串行的方式进行处理,容易造成堵塞影响,monitor的数据同步及时性 * 2. AsyncWatcher为采取的一种策略为当不超过acceptCount=60的任务时,会采用异步线程的方式处理。如果超过60任务,会变为原先的单线程串行的模式 * </pre> * * @author jianghang 2011-9-21 下午01:00:39 * @version 4.0.0 */ public abstract class AsyncWatcher implements Watcher { private static final int DEFAULT_POOL_SIZE = 30; private static final int DEFAULT_ACCEPT_COUNT = 60; private static ExecutorService executor = new ThreadPoolExecutor( DEFAULT_POOL_SIZE, DEFAULT_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue( DEFAULT_ACCEPT_COUNT), new NamedThreadFactory( "Arbitrate-Async-Watcher"), new ThreadPoolExecutor.CallerRunsPolicy()); public void process(final WatchedEvent event) { executor.execute(new Runnable() {// 提交异步处理 public void run() { asyncProcess(event); } }); } public abstract void asyncProcess(WatchedEvent event); }
1,675
872
<filename>src/layer/insanity_pooling_layer-inl.hpp #ifndef INSANITY_POOLING_LAYER_INL_HPP #define INSANITY_POOLING_LAYER_INL_HPP #pragma once #include <mshadow/tensor.h> #include "./layer.h" #include "./param.h" namespace mshadow { namespace expr { template<typename Reducer, typename SrcExp, typename MaskExp, typename DType, int srcdim> struct InsanityPoolingExp : public MakeTensorExp<InsanityPoolingExp<Reducer, SrcExp, MaskExp, DType, srcdim>, SrcExp, srcdim, DType> { const SrcExp &src_; const MaskExp &mask_; index_t ksize_y_; index_t ksize_x_; index_t kstride_; index_t src_height_; index_t src_width_; DType p_keep_; InsanityPoolingExp(const SrcExp &src, const MaskExp &mask, index_t ksize_y, index_t ksize_x, index_t kstride, DType p_keep) : src_(src), mask_(mask), ksize_y_(ksize_y), ksize_x_(ksize_x), kstride_(kstride), p_keep_(p_keep) { Shape<srcdim> sshape = ShapeCheck<srcdim, SrcExp>::Check(src_); Shape<srcdim> smshape = ShapeCheck<srcdim, MaskExp>::Check(mask_); CHECK(sshape == smshape) << "Incorrect shape"; CHECK(sshape[srcdim - 1] >= ksize_x && sshape[srcdim - 2] >= ksize_y) <<"InsanityPoolingExp: kernel must be smaller than image"; this->src_height_ = sshape[srcdim - 2]; this->src_width_ = sshape[srcdim - 1]; this->shape_ = sshape; this->shape_[srcdim - 2] = std::min(src_height_ - ksize_y + kstride - 1, src_height_ - 1) / kstride + 1, this->shape_[srcdim - 1] = std::min(src_width_ - ksize_x + kstride-1, src_width_ - 1) / kstride + 1; } }; // struct InsanityPoolingExp template<typename Reducer, typename SrcExp, typename MaskExp, typename DType, int etype> inline InsanityPoolingExp<Reducer, SrcExp, MaskExp, DType, ExpInfo<SrcExp>::kDim> insanity_pool(const Exp<SrcExp, DType, etype> &src, const Exp<MaskExp, DType, etype> &mask, index_t ksize_y, index_t ksize_x, index_t kstride, DType p_keep) { TypeCheckPass<ExpInfo<SrcExp>::kDim >= 2>::Error_Expression_Does_Not_Meet_Dimension_Req(); return InsanityPoolingExp<Reducer, SrcExp, MaskExp, DType, ExpInfo<SrcExp>::kDim> (src.self(), mask.self(), ksize_y, ksize_x, kstride, p_keep); } template<typename Reducer, typename SrcExp, typename MaskExp, typename DType, int srcdim> struct Plan<InsanityPoolingExp<Reducer, SrcExp, MaskExp, DType, srcdim>, DType> { public: explicit Plan(const InsanityPoolingExp<Reducer, SrcExp, MaskExp, DType, srcdim> &e) : src_(MakePlan(e.src_)), mask_(MakePlan(e.mask_)), ksize_y_(e.ksize_y_), ksize_x_(e.ksize_x_), kstride_(e.kstride_), src_height_(e.src_height_), src_width_(e.src_width_), new_height_(e.shape_[srcdim - 2]), p_keep_(e.p_keep_), delta_((1.0f - e.p_keep_) / 4.0f) {} MSHADOW_XINLINE DType Eval(index_t i, index_t j) const { using namespace std; const index_t py = i % new_height_; const index_t y_start = py * kstride_; const index_t y_end = min(y_start + ksize_y_, src_height_); const index_t px = j; const index_t x_start = px * kstride_; const index_t x_end = min(x_start + ksize_x_, src_width_); const index_t c = i / new_height_; DType res; Reducer::SetInitValue(res); for (index_t y = y_start; y < y_end; ++y) { for (index_t x = x_start; x < x_end; ++x) { index_t loc_y = y; index_t loc_x = x; DType flag = mask_.Eval(c * src_height_ + y, x); if (flag < p_keep_) { ; } else if (flag < p_keep_ + delta_) { loc_y = loc_y > 0 ? loc_y - 1 : loc_y; } else if (flag < p_keep_ + delta_ * 2.0f) { loc_y = loc_y + 1 < src_height_ ? loc_y + 1 : src_height_ - 1; } else if (flag < p_keep_ + delta_ * 3.0f) { loc_x = loc_x > 0 ? loc_x - 1 : loc_x; } else { loc_x = loc_x + 1 < src_width_ ? loc_x + 1 : src_width_ - 1; } Reducer::Reduce(res, src_.Eval(c * src_height_ + loc_y, loc_x)); } } return res; } private: Plan<SrcExp, DType> src_; Plan<MaskExp, DType> mask_; const index_t ksize_y_, ksize_x_, kstride_; const index_t src_height_, src_width_; const index_t new_height_; const DType p_keep_; const DType delta_; }; // struct Plan } // namespace expr } // namespace mshadow namespace mshadow { namespace expr { template<typename Reducer, typename SrcExp, typename MaskExp, typename DType, int srcdim> struct InsanityUnPoolingExp: public MakeTensorExp<InsanityUnPoolingExp<Reducer, SrcExp, MaskExp, DType, srcdim>, SrcExp, srcdim, DType> { const SrcExp &data_src_; const SrcExp &data_pooled_; const SrcExp &grad_pooled_; const MaskExp &mask_; index_t pshape_y_; index_t pshape_x_; index_t ksize_y_; index_t ksize_x_; index_t kstride_; DType p_keep_; InsanityUnPoolingExp(const SrcExp &data_src, const SrcExp &data_pooled, const SrcExp &grad_pooled, const MaskExp &mask, index_t ksize_y, index_t ksize_x, index_t kstride, DType p_keep) : data_src_(data_src), data_pooled_(data_pooled), grad_pooled_(grad_pooled), mask_(mask), ksize_y_(ksize_y), ksize_x_(ksize_x), kstride_(kstride), p_keep_(p_keep) { Shape<srcdim> pshape = ShapeCheck<srcdim, SrcExp>::Check(grad_pooled); Shape<srcdim> sshape = ShapeCheck<srcdim, SrcExp>::Check(data_src); Shape<srcdim> smshape = ShapeCheck<srcdim, MaskExp>::Check(mask_); CHECK(sshape == smshape) << "Incorrect shape"; for (int k = 0; k < srcdim - 2; ++k) { CHECK(pshape[k] == sshape[k]) << "UnPoolingExp: pool and src shape mismatch"; } pshape_x_ = pshape[srcdim - 1]; pshape_y_ = pshape[srcdim - 2]; this->shape_ = sshape; } }; // struct InsanityUnPoolingExp template<typename Reducer, typename SrcExp, typename MaskExp, typename DType, int etype> inline InsanityUnPoolingExp<Reducer, SrcExp, MaskExp, DType, ExpInfo<SrcExp>::kDim> insanity_unpool(const Exp<SrcExp, DType, etype> &data_src, const Exp<SrcExp, DType, etype> &data_pooled, const Exp<SrcExp, DType, etype> &grad_pooled, const Exp<MaskExp, DType, etype> &mask, index_t ksize_y, index_t ksize_x, index_t kstride, DType p_keep) { return InsanityUnPoolingExp<Reducer, SrcExp, MaskExp, DType, ExpInfo<SrcExp>::kDim> (data_src.self(), data_pooled.self(), grad_pooled.self(), mask.self(), ksize_y, ksize_x, kstride, p_keep); } template<typename Reducer, typename SrcExp, typename MaskExp, typename DType, int srcdim> struct Plan<InsanityUnPoolingExp<Reducer, SrcExp, MaskExp, DType, srcdim>, DType> { public: explicit Plan(const InsanityUnPoolingExp<Reducer, SrcExp, MaskExp, DType, srcdim> &e) : data_src_(e.data_src_), data_pooled_(e.data_pooled_), grad_pooled_(e.grad_pooled_), mask_(e.mask_), sshape_y_(e.shape_[srcdim - 2]), sshape_x_(e.shape_[srcdim - 3]), pshape_y_(e.pshape_y_), pshape_x_(e.pshape_x_), ksize_y_(e.ksize_y_), ksize_x_(e.ksize_x_), kstride_(e.kstride_), p_keep_(e.p_keep_), delta_((1.0f - p_keep_) / 4.0f) {} MSHADOW_XINLINE DType Eval(index_t i, index_t j) const { using namespace cxxnet; using namespace std; const index_t x = j; const index_t y = i % sshape_y_; const index_t c = i / sshape_y_; const DType flag = mask_.Eval(i, j); index_t loc_x = x; index_t loc_y = y; if (flag < p_keep_) { ; } else if (flag < p_keep_ + delta_) { loc_y = loc_y > 0 ? loc_y - 1 : loc_y; } else if (flag < p_keep_ + delta_ * 2.0f) { loc_y = loc_y + 1 < sshape_y_ ? loc_y + 1 : sshape_y_ - 1; } else if (flag < p_keep_ + delta_ * 3.0f) { loc_x = loc_x > 0 ? loc_x - 1 : loc_x; } else { loc_x = loc_x + 1 < sshape_x_ ? loc_x + 1 : sshape_x_ - 1; } const DType vsrc = data_src_.Eval(c * sshape_y_ + loc_y ,loc_x); const index_t py_min = y < ksize_y_ ? 0 : (y - ksize_y_ + kstride_) / kstride_; const index_t px_min = x < ksize_x_ ? 0 : (x - ksize_x_ + kstride_) / kstride_; const index_t py_max = min((y + kstride_) / kstride_, pshape_y_); const index_t px_max = min((x + kstride_) / kstride_, pshape_x_); DType val = static_cast<DType>(0); for (index_t py = py_min; py < py_max; ++py) { for (index_t px = px_min; px < px_max; ++px) { val += Reducer::PartialGrad(vsrc, data_pooled_.Eval(c * pshape_y_ + py, px)) * grad_pooled_.Eval(c * pshape_y_ + py, px); } } return val; } private: Plan<SrcExp, DType> data_src_, data_pooled_, grad_pooled_; Plan<MaskExp, DType> mask_; const index_t sshape_y_, sshape_x_, pshape_y_, pshape_x_; const index_t ksize_y_, ksize_x_; const index_t kstride_; const DType p_keep_; const DType delta_; }; // struct Plan } // namespace expr } // namespace mshadow namespace cxxnet { namespace layer { template<typename Reducer, int mode, typename xpu> class InsanityPoolingLayer : public PoolingLayer<Reducer, mode, xpu> { private: typedef PoolingLayer<Reducer, mode, xpu> Parent; public: InsanityPoolingLayer(mshadow::Random<xpu> *p_rnd) : prnd(p_rnd) {p_keep = 1.0f;}; virtual ~InsanityPoolingLayer() {} virtual void SetParam(const char *name, const char *val) { Parent::SetParam(name, val); if (!strcmp(name, "keep")) p_keep = atof(val); } virtual void InitConnection(const std::vector<Node<xpu>*> &nodes_in, const std::vector<Node<xpu>*> &nodes_out, ConnectState<xpu> *p_cstate) { this->InitNode(nodes_in, nodes_out, p_cstate); } virtual void Forward(bool is_train, const std::vector<Node<xpu>*> &nodes_in, const std::vector<Node<xpu>*> &nodes_out, ConnectState<xpu> *p_cstate) { mshadow::TensorContainer<xpu,4> &tmp = p_cstate->states[0]; mshadow::TensorContainer<xpu,4> &mask = p_cstate->states[1]; mshadow::Shape<2> pshape = nodes_out[0]->data[0][0].shape_; using namespace mshadow::expr; if (is_train) { mask = prnd->uniform(mask.shape_); tmp = insanity_pool<Reducer>(nodes_in[0]->data, mask, Parent::param_.kernel_height, Parent::param_.kernel_width, Parent::param_.stride, p_keep); } else { tmp = pool<Reducer>(nodes_in[0]->data, pshape, Parent::param_.kernel_height, Parent::param_.kernel_width, Parent::param_.stride); } mshadow::Copy(nodes_out[0]->data, tmp, nodes_out[0]->data.stream_); } virtual void Backprop(bool prop_grad, const std::vector<Node<xpu>*> &nodes_in, const std::vector<Node<xpu>*> &nodes_out, ConnectState<xpu> *p_cstate) { mshadow::TensorContainer<xpu,4> &tmp = p_cstate->states[0]; mshadow::TensorContainer<xpu,4> &mask = p_cstate->states[1]; using namespace mshadow::expr; nodes_in[0]->data = insanity_unpool<Reducer>(nodes_in[0]->data, tmp, nodes_out[0]->data, mask, Parent::param_.kernel_height, Parent::param_.kernel_width, Parent::param_.stride, p_keep); } protected: inline void InitNode(const std::vector<Node<xpu>*> &nodes_in, const std::vector<Node<xpu>*> &nodes_out, ConnectState<xpu> *p_cstate) { Parent::InitNode(nodes_in, nodes_out, p_cstate); p_cstate->states.push_back(mshadow::TensorContainer<xpu,4>(false)); p_cstate->states[1].Resize(nodes_in[0]->data.shape_); } private: mshadow::Random<xpu> *prnd; float p_keep; }; // class InsanityPoolingLayer } // namespace layer } // namespace cxxnet #endif // INSANITY_POOLING_LAYER_INL_HPP
6,287
348
<filename>docs/data/leg-t2/003/00301090.json {"nom":"Couzon","circ":"1ère circonscription","dpt":"Allier","inscrits":232,"abs":124,"votants":108,"blancs":6,"nuls":12,"exp":90,"res":[{"nuance":"COM","nom":"<NAME>","voix":46},{"nuance":"REM","nom":"<NAME>","voix":44}]}
107
8,805
// boost/detail/lightweight_test_reporter.hpp ----------------------------------------// // Copyright <NAME> 2014 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt //--------------------------------------------------------------------------------------// // // // Configuration reporting cpp_main() // // // // Displays configuration information, then returns test_main(argc, argv), which // // must be supplied by the user. // // // // Note: cpp_main(argc, argv) is called from a try block in main(), which is // // supplied by <boost/detail/lightweight_main.hpp> as is a catch block that reports // // std::exception what(). // // // //--------------------------------------------------------------------------------------// #include <boost/config.hpp> #include <boost/version.hpp> #include <boost/detail/lightweight_test.hpp> #include <boost/detail/lightweight_main.hpp> #include <iostream> int test_main(int argc, char* argv[]); int cpp_main(int argc, char* argv[]) { std::cout << BOOST_COMPILER #ifdef __GNUC__ << ", __GXX_EXPERIMENTAL_CXX0X__ " # ifdef __GXX_EXPERIMENTAL_CXX0X__ "defined" # else "not defined" # endif #endif << "\n" << BOOST_STDLIB << "\n" << BOOST_PLATFORM << "\n" << "Boost version " << BOOST_VERSION / 100000 << '.' << BOOST_VERSION / 100 % 1000 << '.' << BOOST_VERSION % 100 << "\n"; std::cout << "Command line: "; for (int a = 0; a < argc; ++a) { std::cout << argv[a]; if (a != argc - 1) std::cout << ' '; } std::cout << std::endl; return test_main(argc, argv); }
1,230
679
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif #include <X11_transferable.hxx> #include <X11/Xatom.h> #include <com/sun/star/io/IOException.hpp> using namespace com::sun::star::datatransfer; using namespace com::sun::star::lang; using namespace com::sun::star::io; using namespace com::sun::star::uno; using namespace cppu; using namespace osl; using namespace rtl; using namespace x11; X11Transferable::X11Transferable( SelectionManager& rManager, const Reference< XInterface >& xCreator, Atom selection ) : m_rManager( rManager ), m_xCreator( xCreator ), m_aSelection( selection ) { } //================================================================================================== X11Transferable::~X11Transferable() { } //================================================================================================== Any SAL_CALL X11Transferable::getTransferData( const DataFlavor& rFlavor ) throw(UnsupportedFlavorException, IOException, RuntimeException) { Any aRet; Sequence< sal_Int8 > aData; bool bSuccess = m_rManager.getPasteData( m_aSelection ? m_aSelection : XA_PRIMARY, rFlavor.MimeType, aData ); if( ! bSuccess && m_aSelection == 0 ) bSuccess = m_rManager.getPasteData( m_rManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ), rFlavor.MimeType, aData ); if( ! bSuccess ) { throw UnsupportedFlavorException( rFlavor.MimeType, static_cast < XTransferable * > ( this ) ); } if( rFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "text/plain;charset=utf-16" ) ) ) { int nLen = aData.getLength()/2; if( ((sal_Unicode*)aData.getConstArray())[nLen-1] == 0 ) nLen--; OUString aString( (sal_Unicode*)aData.getConstArray(), nLen ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "X11Transferable::getTransferData( \"%s\" )\n -> \"%s\"\n", OUStringToOString( rFlavor.MimeType, RTL_TEXTENCODING_ISO_8859_1 ).getStr(), OUStringToOString( aString, RTL_TEXTENCODING_ISO_8859_1 ).getStr() ); #endif aRet <<= aString; } else aRet <<= aData; return aRet; } //================================================================================================== Sequence< DataFlavor > SAL_CALL X11Transferable::getTransferDataFlavors() throw(RuntimeException) { Sequence< DataFlavor > aFlavorList; bool bSuccess = m_rManager.getPasteDataTypes( m_aSelection ? m_aSelection : XA_PRIMARY, aFlavorList ); if( ! bSuccess && m_aSelection == 0 ) bSuccess = m_rManager.getPasteDataTypes( m_rManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) ), aFlavorList ); return aFlavorList; } //================================================================================================== sal_Bool SAL_CALL X11Transferable::isDataFlavorSupported( const DataFlavor& aFlavor ) throw(RuntimeException) { if( aFlavor.DataType != getCppuType( (Sequence< sal_Int8 >*)0 ) ) { if( ! aFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "text/plain;charset=utf-16" ) ) && aFlavor.DataType == getCppuType( (OUString*)0 ) ) return false; } Sequence< DataFlavor > aFlavors( getTransferDataFlavors() ); for( int i = 0; i < aFlavors.getLength(); i++ ) if( aFlavor.MimeType.equalsIgnoreAsciiCase( aFlavors.getConstArray()[i].MimeType ) && aFlavor.DataType == aFlavors.getConstArray()[i].DataType ) return sal_True; return sal_False; }
1,462
5,169
{ "name": "ExtResponderEvent", "version": "0.0.1", "summary": "Deliver event via responder chain", "homepage": "https://github.com/Pn-X/ExtResponderEvent", "license": "MIT", "authors": { "pn-x": "<EMAIL>" }, "source": { "git": "https://github.com/Pn-X/ExtResponderEvent.git", "tag": "0.0.1" }, "source_files": [ "Classes", "Classes/**/*" ], "exclude_files": "Classes/Exclude", "platforms": { "ios": "9.0" }, "swift_version": "5.0" }
222
807
<filename>djangoql/compat.py import sys PY2 = sys.version_info.major == 2 if PY2: binary_type = str text_type = unicode # noqa: F821 else: binary_type = bytes text_type = str
85
310
{ "name": "ReadyNAS Pro", "description": "A network backup/storage solution.", "url": "https://www.readynas.com/?p=1498" }
46
956
/* <NAME> Cisco Systems, Inc. */ /* Copyright (c) 2016-2016 Cisco Systems, 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. */ #include "trex_rx_tx.h" #include "trex_rx_core.h" /** * create a new queue with a capacity * * @author imarom (8/20/2017) * */ void TXQueue::create(CRxCore *rx, uint32_t capacity) { m_rx = rx; m_capacity = capacity; } /** * remove all packets from the queue */ void TXQueue::destroy() { while (!m_heap.empty()) { TXPacket *pkt = m_heap.top(); delete pkt; m_heap.pop(); } } /** * add a packet to the queue * if capacity is met - return false o.w true */ bool TXQueue::push(int port_id, const std::string &raw, double ts_sec) { /* do we have space ? */ if (is_full()) { return false; } /* add the packet to the heap */ m_heap.push(new TXPacket(port_id, raw, ts_sec)); return true; } /** * slow path tick * */ void TXQueue::_tick() { int pkts_sent = 0; /* trasnmit all packets that have their TS in the past but not more than 100 */ while (!m_heap.empty() && (pkts_sent < 100)) { TXPacket *pkt = m_heap.top(); if (pkt->get_time() <= now_sec()) { /* pop */ m_heap.pop(); /* send the packet */ m_rx->tx_pkt(pkt->get_port_id(), pkt->get_raw()); delete pkt; pkts_sent++; } else { /* next packet is in the future - exit */ break; } } }
902
680
<gh_stars>100-1000 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_TENSORFLOW_CONTRIB_LINEAR_OPTIMIZER_KERNELS_LOGISTIC_LOSS_H_ #define THIRD_PARTY_TENSORFLOW_CONTRIB_LINEAR_OPTIMIZER_KERNELS_LOGISTIC_LOSS_H_ #include <algorithm> #include <cmath> #include "tensorflow/contrib/linear_optimizer/kernels/loss.h" #include "tensorflow/core/lib/core/errors.h" namespace tensorflow { class LogisticLossUpdater : public DualLossUpdater { public: // Use an approximate step that is guaranteed to decrease the dual loss. // Derivation of this is available in Page 14 Eq 16 of // http://arxiv.org/pdf/1211.2717v1.pdf // // Adding vs. Averaging in Distributed Primal-Dual Optimization. // <NAME>, <NAME>, <NAME>, <NAME>, Peter // Richtarik, <NAME> http://arxiv.org/abs/1502.03508 // // TODO(sibyl-Aix6ihai): Add a readme.md for the derivation here. double ComputeUpdatedDual(const int num_partitions, const double label, const double example_weight, const double current_dual, const double wx, const double weighted_example_norm, const double primal_loss, const double dual_loss) const final { const double partial_derivative_loss = PartialDerivativeLogisticLoss(label, wx); // f(a) = sup (a*x - f(x)) then a = f'(x), where a is the aproximate dual. const double approximate_dual = partial_derivative_loss * label; // Dual loss is gamma-strongly convex. const double gamma = 1 / SmoothnessConstantLogisticLoss(partial_derivative_loss, label, wx); const double delta_dual = approximate_dual - current_dual; const double wx_dual = wx * current_dual * example_weight; const double delta_dual_squared = delta_dual * delta_dual; const double smooth_delta_dual_squared = delta_dual_squared * gamma * 0.5; double multiplier = (primal_loss + dual_loss + wx_dual + smooth_delta_dual_squared) / std::max(1.0, delta_dual_squared * (gamma + num_partitions * weighted_example_norm * example_weight * example_weight)); // Multiplier must be in the range [0, 1]. multiplier = std::max(std::min(1.0, multiplier), 0.0); return current_dual + delta_dual * multiplier; } // Dual of logisitic loss function. // https://en.wikipedia.org/wiki/Convex_conjugate double ComputeDualLoss(const double current_dual, const double example_label, const double example_weight) const final { // Dual of the logistic loss function is // ay * log(ay) + (1-ay) * log (1-ay), where a is the dual variable. const double ay = current_dual * example_label; const double log_ay = (ay > 0) ? log(ay) : 0; const double one_minus_ay = 1 - ay; const double log_one_minus_ay = (one_minus_ay > 0) ? log(one_minus_ay) : 0; return ((ay * log_ay) + (one_minus_ay * log_one_minus_ay)) * example_weight; } // Logistic loss for binary classification. // https://en.wikipedia.org/wiki/Loss_functions_for_classification double ComputePrimalLoss(const double wx, const double example_label, const double example_weight) const final { // Logistic loss: // log(1 + e^(-ywx)) // log(e^0 + e^(-ywx)) // a + log(e^(0-a) + e^(-ywx - a)), where a is max(0, -ywx) // https://hips.seas.harvard.edu/blog/2013/01/09/computing-log-sum-exp/ const double y_wx = example_label * wx; if (y_wx > 0) { // 0 + log(e^(0) + e^(-ywx - 0)) // log(1 + e^(-ywx)) return log(1 + exp(-y_wx)) * example_weight; } // -ywx + log(e^(ywx) + e^(-ywx + ywx)) // log(e^(ywx) + e^(0)) - ywx // log(1 + e^(ywx)) - ywx return (log(1 + exp(y_wx)) - y_wx) * example_weight; } // Converts binary example labels from 0.0 or 1.0 to -1.0 or 1.0 respectively // as expected by logistic regression. Status ConvertLabel(float* const example_label) const final { if (*example_label == 0.0) { *example_label = -1; return Status::OK(); } if (*example_label == 1.0) { return Status::OK(); } return errors::InvalidArgument( "Only labels of 0.0 or 1.0 are supported right now. " "Found example with label: ", *example_label); } private: // Partial derivative of the logistic loss w.r.t (1 + exp(-ywx)). static inline double PartialDerivativeLogisticLoss(const double wx, const double label) { // To avoid overflow, we compute partial derivative of logistic loss as // follows. const double ywx = label * wx; if (ywx > 0) { const double exp_minus_ywx = exp(-ywx); return exp_minus_ywx / (1 + exp_minus_ywx); } return 1 / (1 + exp(ywx)); } // Smoothness constant for the logistic loss. static inline double SmoothnessConstantLogisticLoss( const double partial_derivative_loss, const double wx, const double label) { // Upper bound on the smoothness constant of log loss. This is 0.25 i.e. // when log-odds is zero. return (wx == 0) ? 0.25 : (1 - 2 * partial_derivative_loss) / (2 * label * wx); } }; } // namespace tensorflow #endif // THIRD_PARTY_TENSORFLOW_CONTRIB_LINEAR_OPTIMIZER_KERNELS_LOGISTIC_LOSS_H_
2,472
5,594
<reponame>kit-lee/tale<gh_stars>1000+ package com.tale.controller.admin; import com.blade.ioc.annotation.Inject; import com.blade.kit.EncryptKit; import com.blade.kit.StringKit; import com.blade.mvc.annotation.Param; import com.blade.mvc.annotation.Path; import com.blade.mvc.annotation.PostRoute; import com.blade.mvc.ui.RestResponse; import com.tale.annotation.SysLog; import com.tale.bootstrap.TaleConst; import com.tale.controller.BaseController; import com.tale.model.entity.Users; import com.tale.service.OptionsService; import com.tale.service.SiteService; import lombok.extern.slf4j.Slf4j; /** * 后台控制器 * Created by biezhi on 2017/2/21. */ @Slf4j @Path(value = "admin", restful = true) public class SystemController extends BaseController { @Inject private OptionsService optionsService; @Inject private SiteService siteService; @SysLog("保存个人信息") @PostRoute("profile") public RestResponse saveProfile(@Param String screenName, @Param String email) { Users users = this.user(); if (StringKit.isNotBlank(screenName) && StringKit.isNotBlank(email)) { Users temp = new Users(); temp.setScreenName(screenName); temp.setEmail(email); temp.updateById(users.getUid()); } return RestResponse.ok(); } @SysLog("修改登录密码") @PostRoute("password") public RestResponse upPwd(@Param String old_password, @Param String password) { Users users = this.user(); if (StringKit.isBlank(old_password) || StringKit.isBlank(password)) { return RestResponse.fail("请确认信息输入完整"); } if (!users.getPassword().equals(EncryptKit.md5(users.getUsername() + old_password))) { return RestResponse.fail("旧密码错误"); } if (password.length() < 6 || password.length() > 14) { return RestResponse.fail("请输入6-14位密码"); } Users temp = new Users(); String pwd = EncryptKit.md5(users.getUsername() + password); temp.setPassword(<PASSWORD>); temp.updateById(users.getUid()); optionsService.deleteOption(TaleConst.OPTION_SAFE_REMEMBER_ME); return RestResponse.ok(); } }
956
335
{ "word": "Less", "definitions": [ "To a smaller extent; not so much.", "Far from; certainly not." ], "parts-of-speech": "Adverb" }
75
683
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.smoketest.matrix; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JspServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { RequestDispatcher resultView = req.getRequestDispatcher("test.jsp"); resultView.forward(req, resp); } }
223
824
import torch import typing as _typ import torch.nn as nn import torch.nn.functional as F from . import register_nas_space from .base import BaseSpace, map_nn from ...model import BaseModel from .operation import act_map from torch.nn import Parameter from torch_geometric.nn.inits import glorot, zeros from torch_geometric.utils import ( remove_self_loops, add_self_loops, add_remaining_self_loops, softmax, ) from torch_scatter import scatter_add import torch_scatter import inspect import sys special_args = [ "edge_index", "edge_index_i", "edge_index_j", "size", "size_i", "size_j", ] __size_error_msg__ = ( "All tensors which should get mapped to the same source " "or target nodes must be of same size in dimension 0." ) is_python2 = sys.version_info[0] < 3 getargspec = inspect.getargspec if is_python2 else inspect.getfullargspec def scatter_(name, src, index, dim_size=None): r"""Aggregates all values from the :attr:`src` tensor at the indices specified in the :attr:`index` tensor along the first dimension. If multiple indices reference the same location, their contributions are aggregated according to :attr:`name` (either :obj:`"add"`, :obj:`"mean"` or :obj:`"max"`). Args: name (string): The aggregation to use (:obj:`"add"`, :obj:`"mean"`, :obj:`"max"`). src (Tensor): The source tensor. index (LongTensor): The indices of elements to scatter. dim_size (int, optional): Automatically create output tensor with size :attr:`dim_size` in the first dimension. If set to :attr:`None`, a minimal sized output tensor is returned. (default: :obj:`None`) :rtype: :class:`Tensor` """ assert name in ["add", "mean", "max"] op = getattr(torch_scatter, "scatter_{}".format(name)) fill_value = -1e9 if name == "max" else 0 out = op(src, index, 0, None, dim_size) if isinstance(out, tuple): out = out[0] if name == "max": out[out == fill_value] = 0 return out class MessagePassing(torch.nn.Module): def __init__(self, aggr="add", flow="source_to_target"): super(MessagePassing, self).__init__() self.aggr = aggr assert self.aggr in ["add", "mean", "max"] self.flow = flow assert self.flow in ["source_to_target", "target_to_source"] self.__message_args__ = getargspec(self.message)[0][1:] self.__special_args__ = [ (i, arg) for i, arg in enumerate(self.__message_args__) if arg in special_args ] self.__message_args__ = [ arg for arg in self.__message_args__ if arg not in special_args ] self.__update_args__ = getargspec(self.update)[0][2:] def propagate(self, edge_index, size=None, **kwargs): r"""The initial call to start propagating messages. Args: edge_index (Tensor): The indices of a general (sparse) assignment matrix with shape :obj:`[N, M]` (can be directed or undirected). size (list or tuple, optional): The size :obj:`[N, M]` of the assignment matrix. If set to :obj:`None`, the size is tried to get automatically inferrred. (default: :obj:`None`) **kwargs: Any additional data which is needed to construct messages and to update node embeddings. """ size = [None, None] if size is None else list(size) assert len(size) == 2 i, j = (0, 1) if self.flow == "target_to_source" else (1, 0) ij = {"_i": i, "_j": j} message_args = [] for arg in self.__message_args__: if arg[-2:] in ij.keys(): tmp = kwargs.get(arg[:-2], None) if tmp is None: # pragma: no cover message_args.append(tmp) else: idx = ij[arg[-2:]] if isinstance(tmp, tuple) or isinstance(tmp, list): assert len(tmp) == 2 if tmp[1 - idx] is not None: if size[1 - idx] is None: size[1 - idx] = tmp[1 - idx].size(0) if size[1 - idx] != tmp[1 - idx].size(0): raise ValueError(__size_error_msg__) tmp = tmp[idx] if size[idx] is None: size[idx] = tmp.size(0) if size[idx] != tmp.size(0): raise ValueError(__size_error_msg__) tmp = torch.index_select(tmp, 0, edge_index[idx]) message_args.append(tmp) else: message_args.append(kwargs.get(arg, None)) size[0] = size[1] if size[0] is None else size[0] size[1] = size[0] if size[1] is None else size[1] kwargs["edge_index"] = edge_index kwargs["size"] = size for (idx, arg) in self.__special_args__: if arg[-2:] in ij.keys(): message_args.insert(idx, kwargs[arg[:-2]][ij[arg[-2:]]]) else: message_args.insert(idx, kwargs[arg]) update_args = [kwargs[arg] for arg in self.__update_args__] out = self.message(*message_args) if self.aggr in ["add", "mean", "max"]: out = scatter_(self.aggr, out, edge_index[i], dim_size=size[i]) else: pass out = self.update(out, *update_args) return out def message(self, x_j): # pragma: no cover r"""Constructs messages in analogy to :math:`\phi_{\mathbf{\Theta}}` for each edge in :math:`(i,j) \in \mathcal{E}`. Can take any argument which was initially passed to :meth:`propagate`. In addition, features can be lifted to the source node :math:`i` and target node :math:`j` by appending :obj:`_i` or :obj:`_j` to the variable name, *.e.g.* :obj:`x_i` and :obj:`x_j`.""" return x_j def update(self, aggr_out): # pragma: no cover r"""Updates node embeddings in analogy to :math:`\gamma_{\mathbf{\Theta}}` for each node :math:`i \in \mathcal{V}`. Takes in the output of aggregation as first argument and any argument which was initially passed to :meth:`propagate`.""" return aggr_out class GeoLayer(MessagePassing): def __init__( self, in_channels, out_channels, heads=1, concat=True, negative_slope=0.2, dropout=0, bias=True, att_type="gat", agg_type="sum", pool_dim=0, ): if agg_type in ["sum", "mlp"]: super(GeoLayer, self).__init__("add") elif agg_type in ["mean", "max"]: super(GeoLayer, self).__init__(agg_type) self.in_channels = in_channels self.out_channels = out_channels self.heads = heads self.concat = concat self.negative_slope = negative_slope self.dropout = dropout self.att_type = att_type self.agg_type = agg_type # GCN weight self.gcn_weight = None self.weight = Parameter(torch.Tensor(in_channels, heads * out_channels)) self.att = Parameter(torch.Tensor(1, heads, 2 * out_channels)) if bias and concat: self.bias = Parameter(torch.Tensor(heads * out_channels)) elif bias and not concat: self.bias = Parameter(torch.Tensor(out_channels)) else: self.register_parameter("bias", None) if self.att_type in ["generalized_linear"]: self.general_att_layer = torch.nn.Linear(out_channels, 1, bias=False) if self.agg_type in ["mean", "max", "mlp"]: if pool_dim <= 0: pool_dim = 128 self.pool_dim = pool_dim if pool_dim != 0: self.pool_layer = torch.nn.ModuleList() self.pool_layer.append(torch.nn.Linear(self.out_channels, self.pool_dim)) self.pool_layer.append(torch.nn.Linear(self.pool_dim, self.out_channels)) else: pass self.reset_parameters() @staticmethod def norm(edge_index, num_nodes, edge_weight, improved=False, dtype=None): if edge_weight is None: edge_weight = torch.ones( (edge_index.size(1),), dtype=dtype, device=edge_index.device ) fill_value = 1 if not improved else 2 edge_index, edge_weight = add_remaining_self_loops( edge_index, edge_weight, fill_value, num_nodes ) row, col = edge_index deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes) deg_inv_sqrt = deg.pow(-0.5) deg_inv_sqrt[deg_inv_sqrt == float("inf")] = 0 return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col] def reset_parameters(self): glorot(self.weight) glorot(self.att) zeros(self.bias) if self.att_type in ["generalized_linear"]: glorot(self.general_att_layer.weight) if self.pool_dim != 0: for layer in self.pool_layer: glorot(layer.weight) zeros(layer.bias) def forward(self, x, edge_index): """""" edge_index, _ = remove_self_loops(edge_index) edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0)) # prepare x = torch.mm(x, self.weight).view(-1, self.heads, self.out_channels) return self.propagate(edge_index, x=x, num_nodes=x.size(0)) def message(self, x_i, x_j, edge_index, num_nodes): if self.att_type == "const": if self.training and self.dropout > 0: x_j = F.dropout(x_j, p=self.dropout, training=True) neighbor = x_j elif self.att_type == "gcn": if self.gcn_weight is None or self.gcn_weight.size(0) != x_j.size( 0 ): # 对于不同的图gcn_weight需要重新计算 _, norm = self.norm(edge_index, num_nodes, None) self.gcn_weight = norm neighbor = self.gcn_weight.view(-1, 1, 1) * x_j else: # Compute attention coefficients. alpha = self.apply_attention(edge_index, num_nodes, x_i, x_j) alpha = softmax(alpha, edge_index[0], num_nodes=num_nodes) # Sample attention coefficients stochastically. if self.training and self.dropout > 0: alpha = F.dropout(alpha, p=self.dropout, training=True) neighbor = x_j * alpha.view(-1, self.heads, 1) if self.pool_dim > 0: for layer in self.pool_layer: neighbor = layer(neighbor) return neighbor def apply_attention(self, edge_index, num_nodes, x_i, x_j): if self.att_type == "gat": alpha = (torch.cat([x_i, x_j], dim=-1) * self.att).sum(dim=-1) alpha = F.leaky_relu(alpha, self.negative_slope) elif self.att_type == "gat_sym": wl = self.att[:, :, : self.out_channels] # weight left wr = self.att[:, :, self.out_channels :] # weight right alpha = (x_i * wl).sum(dim=-1) + (x_j * wr).sum(dim=-1) alpha_2 = (x_j * wl).sum(dim=-1) + (x_i * wr).sum(dim=-1) alpha = F.leaky_relu(alpha, self.negative_slope) + F.leaky_relu( alpha_2, self.negative_slope ) elif self.att_type == "linear": wl = self.att[:, :, : self.out_channels] # weight left wr = self.att[:, :, self.out_channels :] # weight right al = x_j * wl ar = x_j * wr alpha = al.sum(dim=-1) + ar.sum(dim=-1) alpha = torch.tanh(alpha) elif self.att_type == "cos": wl = self.att[:, :, : self.out_channels] # weight left wr = self.att[:, :, self.out_channels :] # weight right alpha = x_i * wl * x_j * wr alpha = alpha.sum(dim=-1) elif self.att_type == "generalized_linear": wl = self.att[:, :, : self.out_channels] # weight left wr = self.att[:, :, self.out_channels :] # weight right al = x_i * wl ar = x_j * wr alpha = al + ar alpha = torch.tanh(alpha) alpha = self.general_att_layer(alpha) else: raise Exception("Wrong attention type:", self.att_type) return alpha def update(self, aggr_out): if self.concat is True: aggr_out = aggr_out.view(-1, self.heads * self.out_channels) else: aggr_out = aggr_out.mean(dim=1) if self.bias is not None: aggr_out = aggr_out + self.bias return aggr_out def __repr__(self): return "{}({}, {}, heads={})".format( self.__class__.__name__, self.in_channels, self.out_channels, self.heads ) def get_param_dict(self): params = {} key = f"{self.att_type}_{self.agg_type}_{self.in_channels}_{self.out_channels}_{self.heads}" weight_key = key + "_weight" att_key = key + "_att" agg_key = key + "_agg" bais_key = key + "_bais" params[weight_key] = self.weight params[att_key] = self.att params[bais_key] = self.bias if hasattr(self, "pool_layer"): params[agg_key] = self.pool_layer.state_dict() return params def load_param(self, params): key = f"{self.att_type}_{self.agg_type}_{self.in_channels}_{self.out_channels}_{self.heads}" weight_key = key + "_weight" att_key = key + "_att" agg_key = key + "_agg" bais_key = key + "_bais" if weight_key in params: self.weight = params[weight_key] if att_key in params: self.att = params[att_key] if bais_key in params: self.bias = params[bais_key] if agg_key in params and hasattr(self, "pool_layer"): self.pool_layer.load_state_dict(params[agg_key]) @register_nas_space("graphnasmacro") class GraphNasMacroNodeClassificationSpace(BaseSpace): def __init__( self, hidden_dim: _typ.Optional[int] = 64, layer_number: _typ.Optional[int] = 2, dropout: _typ.Optional[float] = 0.6, input_dim: _typ.Optional[int] = None, output_dim: _typ.Optional[int] = None, ops: _typ.Tuple = None, search_act_con=False, ): super().__init__() self.layer_number = layer_number self.hidden_dim = hidden_dim self.input_dim = input_dim self.output_dim = output_dim self.ops = ops self.dropout = dropout self.search_act_con = search_act_con def instantiate( self, hidden_dim: _typ.Optional[int] = None, layer_number: _typ.Optional[int] = None, input_dim: _typ.Optional[int] = None, output_dim: _typ.Optional[int] = None, ops: _typ.Tuple = None, dropout=None, ): super().instantiate() self.hidden_dim = hidden_dim or self.hidden_dim self.layer_number = layer_number or self.layer_number self.input_dim = input_dim or self.input_dim self.output_dim = output_dim or self.output_dim self.ops = ops or self.ops self.dropout = dropout or self.dropout num_feat = self.input_dim num_label = self.output_dim layer_nums = self.layer_number state_num = 5 # build hidden layer for i in range(layer_nums): # extract layer information setattr( self, f"attention_{i}", self.setLayerChoice( i * state_num + 0, map_nn( [ "gat", "gcn", "cos", "const", "gat_sym", "linear", "generalized_linear", ] ), key=f"attention_{i}", ), ) setattr( self, f"aggregator_{i}", self.setLayerChoice( i * state_num + 1, map_nn( [ "sum", "mean", "max", "mlp", ] ), key=f"aggregator_{i}", ), ) setattr( self, f"act_{i}", self.setLayerChoice( i * state_num + 0, map_nn( [ "sigmoid", "tanh", "relu", "linear", "softplus", "leaky_relu", "relu6", "elu", ] ), key=f"act_{i}", ), ) setattr( self, f"head_{i}", self.setLayerChoice( i * state_num + 0, map_nn([1, 2, 4, 6, 8, 16]), key=f"head_{i}" ), ) if i < layer_nums - 1: setattr( self, f"out_channels_{i}", self.setLayerChoice( i * state_num + 0, map_nn([4, 8, 16, 32, 64, 128, 256]), key=f"out_channels_{i}", ), ) def parse_model(self, selection, device) -> BaseModel: sel_list = [] for i in range(self.layer_number): sel_list.append( [ "gat", "gcn", "cos", "const", "gat_sym", "linear", "generalized_linear", ][selection[f"attention_{i}"]] ) sel_list.append( [ "sum", "mean", "max", "mlp", ][selection[f"aggregator_{i}"]] ) sel_list.append( [ "sigmoid", "tanh", "relu", "linear", "softplus", "leaky_relu", "relu6", "elu", ][selection[f"act_{i}"]] ) sel_list.append([1, 2, 4, 6, 8, 16][selection[f"head_{i}"]]) if i < self.layer_number - 1: sel_list.append( [4, 8, 16, 32, 64, 128, 256][selection[f"out_channels_{i}"]] ) sel_list.append(self.output_dim) # sel_list = ['const', 'sum', 'relu6', 2, 128, 'gat', 'sum', 'linear', 2, 7] model = GraphNet( sel_list, self.input_dim, self.output_dim, self.dropout, multi_label=False, batch_normal=False, layers=self.layer_number, ).wrap(device) return model class GraphNet(BaseSpace): def __init__( self, actions, num_feat, num_label, drop_out=0.6, multi_label=False, batch_normal=True, state_num=5, residual=False, layers=2, ): self.residual = residual self.batch_normal = batch_normal self.layer_nums = layers self.multi_label = multi_label self.num_feat = num_feat self.num_label = num_label self.input_dim = num_feat self.output_dim = num_label self.dropout = drop_out super().__init__() self.build_model( actions, batch_normal, drop_out, num_feat, num_label, state_num ) def build_model( self, actions, batch_normal, drop_out, num_feat, num_label, state_num ): if self.residual: self.fcs = torch.nn.ModuleList() if self.batch_normal: self.bns = torch.nn.ModuleList() self.layers = torch.nn.ModuleList() self.acts = [] self.gates = torch.nn.ModuleList() self.build_hidden_layers( actions, batch_normal, drop_out, self.layer_nums, num_feat, num_label, state_num, ) def build_hidden_layers( self, actions, batch_normal, drop_out, layer_nums, num_feat, num_label, state_num=6, ): # build hidden layer for i in range(layer_nums): if i == 0: in_channels = num_feat else: in_channels = out_channels * head_num # extract layer information attention_type = actions[i * state_num + 0] aggregator_type = actions[i * state_num + 1] act = actions[i * state_num + 2] head_num = actions[i * state_num + 3] out_channels = actions[i * state_num + 4] concat = True if i == layer_nums - 1: concat = False if self.batch_normal: self.bns.append(torch.nn.BatchNorm1d(in_channels, momentum=0.5)) self.layers.append( GeoLayer( in_channels, out_channels, head_num, concat, dropout=self.dropout, att_type=attention_type, agg_type=aggregator_type, ) ) self.acts.append(act_map(act)) if self.residual: if concat: self.fcs.append( torch.nn.Linear(in_channels, out_channels * head_num) ) else: self.fcs.append(torch.nn.Linear(in_channels, out_channels)) def forward(self, data): output, edge_index_all = data.x, data.edge_index # x [2708,1433] ,[2, 10556] if self.residual: for i, (act, layer, fc) in enumerate(zip(self.acts, self.layers, self.fcs)): output = F.dropout(output, p=self.dropout, training=self.training) if self.batch_normal: output = self.bns[i](output) output = act(layer(output, edge_index_all) + fc(output)) else: for i, (act, layer) in enumerate(zip(self.acts, self.layers)): output = F.dropout(output, p=self.dropout, training=self.training) if self.batch_normal: output = self.bns[i](output) output = act(layer(output, edge_index_all)) if not self.multi_label: output = F.log_softmax(output, dim=1) return output def __repr__(self): result_lines = "" for each in self.layers: result_lines += str(each) return result_lines @staticmethod def merge_param(old_param, new_param, update_all): for key in new_param: if update_all or key not in old_param: old_param[key] = new_param[key] return old_param def get_param_dict(self, old_param=None, update_all=True): if old_param is None: result = {} else: result = old_param for i in range(self.layer_nums): key = "layer_%d" % i new_param = self.layers[i].get_param_dict() if key in result: new_param = self.merge_param(result[key], new_param, update_all) result[key] = new_param else: result[key] = new_param if self.residual: for i, fc in enumerate(self.fcs): key = f"layer_{i}_fc_{fc.weight.size(0)}_{fc.weight.size(1)}" result[key] = self.fcs[i] if self.batch_normal: for i, bn in enumerate(self.bns): key = f"layer_{i}_fc_{bn.weight.size(0)}" result[key] = self.bns[i] return result def load_param(self, param): if param is None: return for i in range(self.layer_nums): self.layers[i].load_param(param["layer_%d" % i]) if self.residual: for i, fc in enumerate(self.fcs): key = f"layer_{i}_fc_{fc.weight.size(0)}_{fc.weight.size(1)}" if key in param: self.fcs[i] = param[key] if self.batch_normal: for i, bn in enumerate(self.bns): key = f"layer_{i}_fc_{bn.weight.size(0)}" if key in param: self.bns[i] = param[key]
13,796
26,932
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # standard modules from metasploit import module import logging import string import random # extra modules dependency1_missing = False dependency2_missing = False try: import socket except ImportError: dependency1_missing = True try: import paramiko except ImportError: dependency2_missing = True metadata = { 'name': 'Cisco 7937G Denial-of-Service Attack', 'description': ''' This module exploits a bug in how the conference station handles incoming SSH connections that provide an incompatible key exchange. By connecting with an incompatible key exchange, the device becomes nonresponsive until it is manually power cycled. ''', 'authors': [ '<NAME>' # Author Homepage: debifrank.github.io # Organization: BlackLanternSecurity # Org. Homepage: BlackLanternSecurity.com ], 'date': '2020-06-02', 'license': 'GPL_LICENSE', 'references': [ {'type': 'url', 'ref': 'https://blacklanternsecurity.com/2020-08-07-Cisco-Unified-IP-Conference-Station-7937G/'}, {'type': 'cve', 'ref': '2020-16138'} ], 'type': 'dos', 'options': { 'rhost': {'type': 'address', 'description': 'Target address', 'required': True, 'default': 'None'}, 'timeout': {'type': 'int', 'description': 'Timeout in seconds', 'required': True, 'default': 15} } } # from modules/auxiliary/dos/http/slowloris.py def create_rand_cred(size, seq=string.ascii_uppercase + string.ascii_lowercase): return ''.join(random.choice(seq) for _ in range(size)) def run(args): module.LogHandler.setup(msg_prefix='{} - '.format(args['rhost'])) if dependency1_missing: logging.error('Python module dependency (socket) is missing, cannot continue') logging.error('Please execute pip3 install socket.') return if dependency2_missing: logging.error('Python module dependency (paramiko) is missing, cannot continue') logging.error('Please execute pip3 install paramiko.') return sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(int(args['timeout'])) try: sock.connect((args['rhost'], 22)) except OSError: logging.error("Device doesn't appear to be functioning (already DoS'd?) or SSH is not enabled.") return transport = paramiko.Transport(sock=sock, disabled_algorithms={"kex": ["diffie-hellman-group-exchange-sha1", "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1"]}) ssh_uname = create_rand_cred(random.randint(7, 10)) ssh_pass = create_rand_cred(random.randint(7, 10)) try: transport.connect(username=ssh_uname, password=<PASSWORD>) except (paramiko.ssh_exception.SSHException, OSError, paramiko.SSHException): logging.info("DoS non-reset attack completed!") logging.info("Errors are intended.") logging.info("Device must be power cycled to restore functionality.") return return if __name__ == '__main__': module.run(metadata, run)
1,318
575
<reponame>jason-fox/Fast-RTPS // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /*! * @file TypesTypeObject.h * This header file contains the declaration of the described types in the IDL file. * * This file was generated by the tool gen. */ #ifndef _TYPES_TYPE_OBJECT_H_ #define _TYPES_TYPE_OBJECT_H_ #include <fastrtps/types/TypeObject.h> #include <map> #if defined(_WIN32) #if defined(EPROSIMA_USER_DLL_EXPORT) #define eProsima_user_DllExport __declspec( dllexport ) #else #define eProsima_user_DllExport #endif #else #define eProsima_user_DllExport #endif #if defined(_WIN32) #if defined(EPROSIMA_USER_DLL_EXPORT) #if defined(Types_SOURCE) #define Types_DllAPI __declspec( dllexport ) #else #define Types_DllAPI __declspec( dllimport ) #endif // Types_SOURCE #else #define Types_DllAPI #endif #else #define Types_DllAPI #endif // _WIN32 using namespace eprosima::fastrtps::types; eProsima_user_DllExport void registerTypesTypes(); eProsima_user_DllExport const TypeIdentifier* GetMyEnumIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMyEnumObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMyEnumObject(); eProsima_user_DllExport const TypeObject* GetCompleteMyEnumObject(); eProsima_user_DllExport const TypeIdentifier* GetMyBadEnumIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMyBadEnumObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMyBadEnumObject(); eProsima_user_DllExport const TypeObject* GetCompleteMyBadEnumObject(); eProsima_user_DllExport const TypeIdentifier* GetMyEnumStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMyEnumStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMyEnumStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMyEnumStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMyBadEnumStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMyBadEnumStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMyBadEnumStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMyBadEnumStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMyAliasEnumIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMyAliasEnumObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMyAliasEnumObject(); eProsima_user_DllExport const TypeObject* GetCompleteMyAliasEnumObject(); eProsima_user_DllExport const TypeIdentifier* GetMyAliasEnumStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMyAliasEnumStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMyAliasEnumStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMyAliasEnumStructObject(); eProsima_user_DllExport const TypeIdentifier* GetBasicStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetBasicStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalBasicStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteBasicStructObject(); eProsima_user_DllExport const TypeIdentifier* GetBasicNamesStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetBasicNamesStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalBasicNamesStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteBasicNamesStructObject(); eProsima_user_DllExport const TypeIdentifier* GetBasicBadStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetBasicBadStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalBasicBadStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteBasicBadStructObject(); eProsima_user_DllExport const TypeIdentifier* GetBasicWideStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetBasicWideStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalBasicWideStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteBasicWideStructObject(); eProsima_user_DllExport const TypeIdentifier* GetBadBasicWideStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetBadBasicWideStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalBadBasicWideStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteBadBasicWideStructObject(); eProsima_user_DllExport const TypeIdentifier* GetStringStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetStringStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalStringStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteStringStructObject(); eProsima_user_DllExport const TypeIdentifier* GetLargeStringStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetLargeStringStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalLargeStringStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteLargeStringStructObject(); eProsima_user_DllExport const TypeIdentifier* GetWStringStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetWStringStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalWStringStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteWStringStructObject(); eProsima_user_DllExport const TypeIdentifier* GetLargeWStringStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetLargeWStringStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalLargeWStringStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteLargeWStringStructObject(); eProsima_user_DllExport const TypeIdentifier* GetArrayStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetArrayStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalArrayStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteArrayStructObject(); eProsima_user_DllExport const TypeIdentifier* GetArrayStructEqualIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetArrayStructEqualObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalArrayStructEqualObject(); eProsima_user_DllExport const TypeObject* GetCompleteArrayStructEqualObject(); eProsima_user_DllExport const TypeIdentifier* GetArrayBadStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetArrayBadStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalArrayBadStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteArrayBadStructObject(); eProsima_user_DllExport const TypeIdentifier* GetArrayDimensionsStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetArrayDimensionsStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalArrayDimensionsStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteArrayDimensionsStructObject(); eProsima_user_DllExport const TypeIdentifier* GetArraySizeStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetArraySizeStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalArraySizeStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteArraySizeStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSequenceStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSequenceStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSequenceStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSequenceStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSequenceStructEqualIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSequenceStructEqualObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSequenceStructEqualObject(); eProsima_user_DllExport const TypeObject* GetCompleteSequenceStructEqualObject(); eProsima_user_DllExport const TypeIdentifier* GetSequenceBadStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSequenceBadStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSequenceBadStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSequenceBadStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSequenceBoundsStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSequenceBoundsStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSequenceBoundsStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSequenceBoundsStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSequenceSequenceStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSequenceSequenceStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSequenceSequenceStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSequenceSequenceStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSequenceSequenceBoundsStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSequenceSequenceBoundsStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSequenceSequenceBoundsStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSequenceSequenceBoundsStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMapStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMapStructEqualIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapStructEqualObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapStructEqualObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapStructEqualObject(); eProsima_user_DllExport const TypeIdentifier* GetMapBadKeyStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapBadKeyStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapBadKeyStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapBadKeyStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMapBadElemStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapBadElemStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapBadElemStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapBadElemStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMapBoundsStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapBoundsStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapBoundsStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapBoundsStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMapMapStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapMapStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapMapStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapMapStructObject(); eProsima_user_DllExport const TypeIdentifier* GetMapMapBoundsStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetMapMapBoundsStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalMapMapBoundsStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteMapMapBoundsStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleUnionIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleUnionObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleUnionObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleUnionObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleUnionNamesIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleUnionNamesObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleUnionNamesObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleUnionNamesObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleTypeUnionIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleTypeUnionObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleTypeUnionObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleTypeUnionObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleBadUnionIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleBadUnionObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleBadUnionObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleBadUnionObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleBadDiscUnionIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleBadDiscUnionObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleBadDiscUnionObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleBadDiscUnionObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleUnionStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleUnionStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleUnionStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleUnionStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleUnionStructEqualIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleUnionStructEqualObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleUnionStructEqualObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleUnionStructEqualObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleUnionNamesStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleUnionNamesStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleUnionNamesStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleUnionNamesStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleTypeUnionStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleTypeUnionStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleTypeUnionStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleTypeUnionStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSimpleBadUnionStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimpleBadUnionStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimpleBadUnionStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimpleBadUnionStructObject(); eProsima_user_DllExport const TypeIdentifier* GetSimplBadDiscUnionStructIdentifier(bool complete = false); eProsima_user_DllExport const TypeObject* GetSimplBadDiscUnionStructObject(bool complete = false); eProsima_user_DllExport const TypeObject* GetMinimalSimplBadDiscUnionStructObject(); eProsima_user_DllExport const TypeObject* GetCompleteSimplBadDiscUnionStructObject(); #endif // _TYPES_TYPE_OBJECT_H_
4,884
2,338
<filename>compiler-rt/lib/gwp_asan/tests/compression.cpp<gh_stars>1000+ //===-- compression.cpp -----------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "gwp_asan/stack_trace_compressor.h" #include "gwp_asan/tests/harness.h" namespace gwp_asan { namespace compression { TEST(GwpAsanCompressionTest, SingleByteVarInt) { uint8_t Compressed[1]; uintptr_t Uncompressed = 0x00; EXPECT_EQ(1u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0x00); Uncompressed = 0x01; EXPECT_EQ(1u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0x02); // +1 => 2 in zigzag. Uncompressed = 0x3f; EXPECT_EQ(1u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0x7e); // +63 => 127 in zigzag. } TEST(GwpAsanCompressionTest, MultiByteVarInt) { uint8_t Compressed[sizeof(uintptr_t) + 1]; uintptr_t Uncompressed = 0x40; EXPECT_EQ(2u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0x80); // +64 => 128 in zigzag. EXPECT_EQ(Compressed[1], 0x01); Uncompressed = 0x41; EXPECT_EQ(2u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0x82); // +65 => 130 in zigzag EXPECT_EQ(Compressed[1], 0x01); Uncompressed = 0x1fff; EXPECT_EQ(2u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0xfe); // +8191 => 16382 in zigzag EXPECT_EQ(Compressed[1], 0x7f); Uncompressed = 0x2000; EXPECT_EQ(3u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0x80); // +8192 => 16384 in zigzag EXPECT_EQ(Compressed[1], 0x80); EXPECT_EQ(Compressed[2], 0x01); Uncompressed = 0x7f010ff0; EXPECT_EQ(5u, pack(&Uncompressed, 1u, Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[0], 0xe0); // +0x7f010ff0 => 0xFE021FE0 in zigzag EXPECT_EQ(Compressed[1], 0xbf); EXPECT_EQ(Compressed[2], 0x88); EXPECT_EQ(Compressed[3], 0xf0); EXPECT_EQ(Compressed[4], 0x0f); } TEST(GwpAsanCompressionTest, CorrectDifference) { uint8_t Compressed[10]; uintptr_t Uncompressed[2] = {0x00, 0x00}; EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[1], 0x00); // +0 difference => 0 in zigzag. Uncompressed[1] = 0x01; EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[1], 0x02); // +1 difference => 2 in zigzag. Uncompressed[1] = 0x02; EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[1], 0x04); // +2 difference => 4 in zigzag. Uncompressed[1] = 0x80; EXPECT_EQ(3u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[1], 0x80); // +128 difference => +256 in zigzag (note the EXPECT_EQ(Compressed[2], 0x02); // varint encoding here). Uncompressed[0] = 0x01; Uncompressed[1] = 0x00; EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[1], 0x01); // -1 difference => +1 in zigzag. Uncompressed[0] = 0x02; EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[1], 0x03); // -2 difference => +3 in zigzag. Uncompressed[0] = 0x80; EXPECT_EQ(4u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); EXPECT_EQ(Compressed[2], 0xff); // -128 difference => +255 in zigzag (note the EXPECT_EQ(Compressed[3], 0x01); // varint encoding here). } // Space needed to encode the biggest uintptr_t as a varint is ceil((8 / 7) * // sizeof(uintptr_t)), as each 7 bits requires 8 bits of space. constexpr size_t kBytesForLargestVarInt = (sizeof(uintptr_t) * 8) / 7 + 1; // Ensures that when the closest diff between two pointers is via. underflow, // we take the underflow option. TEST(GwpAsanCompressionTest, ClosestDiffIsUnderflow) { uint8_t Compressed[2]; uintptr_t Uncompressed[2] = {0x00, UINTPTR_MAX}; EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); // -1 difference => +1 in zigzag. EXPECT_EQ(Compressed[1], 0x01); } // Ensures that when the closest diff between two pointers is via. overflow, // that we take this option. TEST(GwpAsanCompressionTest, ClosestDiffIsOverflow) { uint8_t Compressed[2]; uintptr_t Uncompressed[2] = {UINTPTR_MAX, 0x00}; // Note here that the first element is encoded as the difference from zero. EXPECT_EQ(2u, pack(Uncompressed, sizeof(Uncompressed) / sizeof(uintptr_t), Compressed, sizeof(Compressed))); // -1 difference => +1 in zigzag (the first pointer is encoded as -1). EXPECT_EQ(Compressed[0], 0x01); // +1 difference => +2 in zigzag. EXPECT_EQ(Compressed[1], 0x02); } void runPackUnpack(uintptr_t *Test, size_t NumEntries) { // Setup the input/output buffers based on the maximum possible size. uintptr_t *Uncompressed = static_cast<uintptr_t *>(alloca(NumEntries * sizeof(uintptr_t))); size_t CompressedBufferSize = NumEntries * kBytesForLargestVarInt; uint8_t *Compressed = static_cast<uint8_t *>(alloca(CompressedBufferSize)); // Pack the provided testcase, recoding the number of bytes it took for // storage. size_t BytesUsedForPacking = pack(Test, NumEntries, Compressed, CompressedBufferSize); EXPECT_NE(BytesUsedForPacking, 0u); // Unpack the testcase and ensure that the correct number of entries was // unpacked. EXPECT_EQ(NumEntries, unpack(Compressed, BytesUsedForPacking, Uncompressed, NumEntries)); // Ensure that the unpacked trace is the same as the original testcase. for (size_t i = 0; i < NumEntries; ++i) { EXPECT_EQ(Uncompressed[i], Test[i]); } } TEST(GwpAsanCompressionTest, UncompressVarInt) { uint8_t Compressed[] = {0x00, 0xaa, 0xaf, 0xd0, 0xda, 0x04}; uintptr_t Uncompressed[2]; EXPECT_EQ(2u, unpack(Compressed, sizeof(Compressed), Uncompressed, 2u)); EXPECT_EQ(Uncompressed[0], 0x00u); EXPECT_EQ(Uncompressed[1], 0x25aa0bd5u); } TEST(GwpAsanCompressionTest, UncompressVarIntUnderflow) { uint8_t Compressed[] = {0x00, 0xab, 0xaf, 0xd0, 0xda, 0x04}; uintptr_t Uncompressed[2]; EXPECT_EQ(2u, unpack(Compressed, sizeof(Compressed), Uncompressed, 2u)); EXPECT_EQ(Uncompressed[0], 0x00u); EXPECT_EQ(Uncompressed[1], UINTPTR_MAX - 0x25aa0bd5u); } TEST(GwpAsanCompressionTest, CompressUncompressAscending) { uintptr_t Test[] = {1, 2, 3}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, CompressUncompressDescending) { uintptr_t Test[] = {3, 2, 1}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, CompressUncompressRepeated) { uintptr_t Test[] = {3, 3, 3}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, CompressUncompressZigZag) { uintptr_t Test[] = {1, 3, 2, 4, 1, 2}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, CompressUncompressVarInt) { uintptr_t Test[] = {0x1981561, 0x18560, 0x25ab9135, 0x1232562}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, CompressUncompressLargestDifference) { uintptr_t Test[] = {0x00, INTPTR_MAX, UINTPTR_MAX, INTPTR_MAX, 0x00}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, CompressUncompressBigPointers) { uintptr_t Test[] = {UINTPTR_MAX, UINTPTR_MAX - 10}; runPackUnpack(Test, sizeof(Test) / sizeof(uintptr_t)); uintptr_t Test2[] = {UINTPTR_MAX - 10, UINTPTR_MAX}; runPackUnpack(Test2, sizeof(Test2) / sizeof(uintptr_t)); } TEST(GwpAsanCompressionTest, UncompressFailsWithOutOfBoundsVarInt) { uint8_t Compressed[kBytesForLargestVarInt + 1]; for (size_t i = 0; i < kBytesForLargestVarInt; ++i) { Compressed[i] = 0x80; } Compressed[kBytesForLargestVarInt] = 0x00; uintptr_t Uncompressed; EXPECT_EQ(unpack(Compressed, kBytesForLargestVarInt + 1, &Uncompressed, 1), 0u); } TEST(GwpAsanCompressionTest, UncompressFailsWithTooSmallBuffer) { uint8_t Compressed[] = {0x80, 0x00}; uintptr_t Uncompressed; EXPECT_EQ(unpack(Compressed, 1u, &Uncompressed, 1), 0u); } TEST(GwpAsanCompressionTest, CompressPartiallySucceedsWithTooSmallBuffer) { uintptr_t Uncompressed[] = { 0x80, // Requires 2 bytes for varint. 0x100, // Requires two bytes for varint difference of 0x80. 0xff, // Requires single byte for varint difference of -0x01 }; uint8_t Compressed[3 * kBytesForLargestVarInt]; // Zero and one byte buffers shouldn't encode anything (see above for size // requirements). EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 0u), 0u); EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 1u), 0u); // Two byte buffer should hold a single varint-encoded value. EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 2u), 2u); // Three bytes isn't enough to cover the first two pointers, as both take two // bytes each to store. Expect a single value to be compressed. EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 3u), 2u); // Four bytes is enough for the first two pointers to be stored. EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 4u), 4u); // And five is enough for all three pointers to be stored. EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 5u), 5u); // And a buffer that's bigger than five bytes should still only write five // bytes. EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 6u), 5u); EXPECT_EQ(pack(Uncompressed, 3u, Compressed, 3 * kBytesForLargestVarInt), 5u); } } // namespace compression } // namespace gwp_asan
4,157
861
package cn.springcloud.gray.mock; import cn.springcloud.gray.choose.ChooseGroup; import cn.springcloud.gray.model.HandleActionDefinition; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * @author saleson * @date 2020-05-22 23:07 */ public class HandleActionDefinitionTest { @Test public void testSortList() { List<HandleActionDefinition> list = new ArrayList<>(); HandleActionDefinition definition = new HandleActionDefinition(); definition.setId("2"); definition.setOrder(2); list.add(definition); definition = new HandleActionDefinition(); definition.setId("1"); definition.setOrder(1); list.add(definition); System.out.println(list.stream().sorted().collect(Collectors.toList())); } @Test public void test() { List list = Arrays.asList("1", "2") .stream() .map(j -> null) .filter(Objects::nonNull) .collect(Collectors.toList()); System.out.println(list); } @Test public void test1() { ChooseGroup chooseGroup = ChooseGroup.ofNameDefaultAll("ALL"); System.out.println(chooseGroup); } }
544
352
<filename>src/main/java/helloworld/behavioral/strategy/HelloWorldStrategy.java<gh_stars>100-1000 package helloworld.behavioral.strategy; import helloworld.HelloWorld; /** * @author <EMAIL> */ public interface HelloWorldStrategy extends HelloWorld { }
82
3,799
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.slice; import android.content.Context; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.annotation.RestrictTo; import androidx.slice.compat.SliceProviderCompat; import java.util.List; import java.util.Set; /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) @RequiresApi(19) class SliceManagerCompat extends SliceManager { private final Context mContext; SliceManagerCompat(Context context) { mContext = context; } @Override public @NonNull Set<SliceSpec> getPinnedSpecs(@NonNull Uri uri) { return SliceProviderCompat.getPinnedSpecs(mContext, uri); } @Override public int checkSlicePermission(Uri uri, int pid, int uid) { return SliceProviderCompat.checkSlicePermission(mContext, mContext.getPackageName(), uri, pid, uid); } @Override public void grantSlicePermission(String toPackage, Uri uri) { SliceProviderCompat.grantSlicePermission(mContext, mContext.getPackageName(), toPackage, uri); } @Override public void revokeSlicePermission(String toPackage, Uri uri) { SliceProviderCompat.revokeSlicePermission(mContext, mContext.getPackageName(), toPackage, uri); } @Override public List<Uri> getPinnedSlices() { return SliceProviderCompat.getPinnedSlices(mContext); } }
713
764
{"symbol": "YUP","address": "0xD9A12Cde03a86E800496469858De8581D3A5353d","overview":{"en": ""},"email": "<EMAIL>","website": "crowdholding.com","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/crowdholding","telegram": "https://t.me/Crowdholding","github": ""}}
106
412
<gh_stars>100-1000 int main() { int x = 0; x = ++x + x; // depending on the order of evaluation, the following may fail assert(x == 2); return 0; }
59
372
/* * * (c) Copyright 1989 OPEN SOFTWARE FOUNDATION, INC. * (c) Copyright 1989 HEWLETT-PACKARD COMPANY * (c) Copyright 1989 DIGITAL EQUIPMENT CORPORATION * To anyone who acknowledges that this file is provided "AS IS" * without any express or implied warranty: * permission to use, copy, modify, and distribute this * file for any purpose is hereby granted without fee, provided that * the above copyright notices and this notice appears in all source * code copies, and that none of the names of Open Software * Foundation, Inc., Hewlett-Packard Company, or Digital Equipment * Corporation be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. Neither Open Software Foundation, Inc., Hewlett- * Packard Company, nor Digital Equipment Corporation makes any * representations about the suitability of this software for any * purpose. * */ /* */ /* ** ** NAME ** ** twr_ip.c ** ** FACILITY: ** ** Protocol Tower Services for the internet address family ** ** ABSTRACT: ** ** The protocol tower service provides routines that: ** ** o convert a socket address to the lower floors of ** a protocol tower ** ** o convert a protocol tower to a socket address ** ** */ #include <commonp.h> /* Common declarations for all RPC runtime */ #if NAF_IP #include <com.h> /* Common communications services */ #include <twrp.h> /* Private tower services */ /* * Include the Internet specific socket address */ #ifdef VMS #include <in.h> #else #include <netinet/in.h> #endif /* **++ ** ** ROUTINE NAME: twr_ip_lower_flrs_from_sa ** ** SCOPE: PUBLIC - declared in twr.idl ** ** DESCRIPTION: ** ** Creates the canonical representation of an internet protocol tower's ** lower floors from a sockadddr. The canonical form can be transmitted ** on the wire, or included in a DNS tower. ** ** INPUTS: ** ** trans_prot Integer value specifying the transport layer ** protocol for the Internet address family. ** For address family RPC_C_NAF_ID_IP specify: ** ** RPC_C_NETWORK_PROTOCOL_ID_TCP for tcp ** RPC_C_NETWORK_PROTOCOL_ID_UDP for udp ** ** sa Internet-specific socket address data ** structure. ** ** INPUTS/OUTPUTS: none ** ** OUTPUTS: ** ** lower_flrs Returns the lower tower floors in a twr_t ** structure (includes the floor count in the ** "tower_octet_string" member). ** ** status A value indicating the return status of the routine: ** twr_s_ok ** twr_s_unknown_sa ** ** IMPLICIT INPUTS: none ** ** IMPLICIT OUTPUTS: none ** ** FUNCTION VALUE: void ** ** SIDE EFFECTS: none ** **-- **/ PUBLIC void twr_ip_lower_flrs_from_sa ( unsigned32 trans_prot, sockaddr_p_t sa, twr_p_t *lower_flrs, unsigned32 *status ) { unsigned8 protocol_id[TWR_C_NUM_IP_LOWER_FLRS]; unsigned16 id_size = TWR_C_TOWER_PROT_ID_SIZE, floor_count, related_data_size[TWR_C_NUM_IP_LOWER_FLRS], twr_rep_16; unsigned32 count, twr_t_length; byte_p_t related_data_ptr[TWR_C_NUM_IP_LOWER_FLRS], tmp_tower; static unsigned8 zeroes[TWR_C_IP_ADDR_SIZE] = {0}; CODING_ERROR (status); RPC_VERIFY_INIT (); /* * all depends on the network family to which this socket belongs */ if (sa->family == RPC_C_NAF_ID_IP || sa->family == RPC_C_NAF_ID_IP6) { /* * only two network protocols are supported for internet */ if (trans_prot == RPC_C_NETWORK_PROTOCOL_ID_TCP) { protocol_id[0] = TWR_C_FLR_PROT_ID_TCP; } else { if ( trans_prot == RPC_C_NETWORK_PROTOCOL_ID_UDP ) { protocol_id[0] = TWR_C_FLR_PROT_ID_UDP; } else { *status = twr_s_unknown_sa; return; } } protocol_id[1] = TWR_C_FLR_PROT_ID_IP; } else { *status = twr_s_unknown_sa; return; } /* * Since we now know the socket address we're dealing with, * collect the sizes of each field to allocate memory, and * remember the pointers to the fields so we can copy the * data once we have allocated the tower string. */ floor_count = TWR_C_NUM_IP_LOWER_FLRS; /* * Note that the port number and address are already * stored in big endian (network order) which is what * the architecture specifies, so no endian conversion * is necessary. */ switch (sa->family) { case RPC_C_NAF_ID_IP: related_data_size[0] = TWR_C_IP_PORT_SIZE; related_data_ptr[0] = (byte_p_t) (&((struct sockaddr_in *)sa)->sin_port); related_data_size[1] = TWR_C_IP_ADDR_SIZE; related_data_ptr[1] = (byte_p_t) (&((struct sockaddr_in *)sa)->sin_addr.s_addr); break; case RPC_C_NAF_ID_IP6: related_data_size[0] = TWR_C_IP_PORT_SIZE; related_data_ptr[0] = (byte_p_t) (&((struct sockaddr_in6 *)sa)->sin6_port); // Use zeroes for address related_data_size[1] = TWR_C_IP_ADDR_SIZE; related_data_ptr[1] = (byte_p_t) zeroes; break; default: abort(); } /* * Calculate the length of the tower floors. */ twr_t_length = TWR_C_TOWER_FLR_COUNT_SIZE; /* to store floor count */ for ( count = 0; count < floor_count; count++ ) { twr_t_length += TWR_C_FLR_OVERHEAD; twr_t_length += related_data_size[count]; } /* * Next allocate space for the tower structure */ RPC_MEM_ALLOC ( *lower_flrs, twr_p_t, sizeof (twr_t) + (twr_t_length - 1), RPC_C_MEM_TOWER, RPC_C_MEM_WAITOK ); /* * Copy the length of the tower octet string into the tower structure */ (*lower_flrs)->tower_length = twr_t_length; /* * Copy the floor information into the tower octet string */ /* * Use a temporary for the octet string since we need * to increment the pointer. */ tmp_tower = (*lower_flrs)->tower_octet_string; /* * Copy the number of floors into the tower octet string */ twr_rep_16 = floor_count; RPC_RESOLVE_ENDIAN_INT16 (twr_rep_16); memcpy ((char *)tmp_tower, (char *)&twr_rep_16, TWR_C_TOWER_FLR_COUNT_SIZE); tmp_tower += TWR_C_TOWER_FLR_COUNT_SIZE; /* * Convert the protocol identifier size to its proper * representation for use in the following loop. */ RPC_RESOLVE_ENDIAN_INT16 (id_size); for ( count = 0; count < floor_count; count++ ) { /* * Copy the length of the protocol identifier field into * tower octet string. (Converted before the loop.) */ memcpy ((char *)tmp_tower, (char *)&id_size, TWR_C_TOWER_FLR_LHS_COUNT_SIZE); tmp_tower += TWR_C_TOWER_FLR_LHS_COUNT_SIZE; /* * Copy the protocol identifier into tower octet string * (1 byte so no need to convert endian representation). */ memcpy ((char *)tmp_tower, (char *)&(protocol_id[count]), TWR_C_TOWER_PROT_ID_SIZE); tmp_tower += TWR_C_TOWER_PROT_ID_SIZE; /* * Copy the length of the address data field into * tower octet string. */ twr_rep_16 = related_data_size[count]; RPC_RESOLVE_ENDIAN_INT16 (twr_rep_16); memcpy ((char *)tmp_tower, (char *)&twr_rep_16, TWR_C_TOWER_FLR_RHS_COUNT_SIZE); tmp_tower += TWR_C_TOWER_FLR_RHS_COUNT_SIZE; /* * If there is addressing data, copy the address data field into * tower octet string */ if (related_data_size[count]) { memcpy ((char *)tmp_tower, (char *)related_data_ptr[count], related_data_size[count]); /* * Set up for the next floor. */ tmp_tower += related_data_size[count]; } } *status = twr_s_ok; } /* **++ ** ** ROUTINE NAME: twr_ip_lower_flrs_to_sa ** ** SCOPE: PUBLIC - declared in twr.idl ** ** DESCRIPTION: ** ** Creates an internet sockaddr from the canonical representation of an ** internet protocol tower's lower floors. ** ** INPUTS: ** ** tower_octet_string ** The protocol tower to convert to a sockaddr. ** ** INPUTS/OUTPUTS: none ** ** OUTPUTS: ** ** sa Returns a pointer to the created sockaddr structure. ** ** sa_len Returns the length, in bytes, of the returned ** "sa" argument. ** ** status A value indicating the return status of the routine: ** twr_s_ok ** twr_s_unknown_tower ** ** IMPLICIT INPUTS: none ** ** IMPLICIT OUTPUTS: none ** ** FUNCTION VALUE: void ** ** SIDE EFFECTS: none ** **-- **/ PUBLIC void twr_ip_lower_flrs_to_sa ( byte_p_t tower_octet_string, sockaddr_p_t *sa, unsigned32 *sa_len, unsigned32 *status ) { unsigned8 id; byte_p_t tower; unsigned16 count, floor_count, id_size, addr_size; unsigned32 length; CODING_ERROR (status); RPC_VERIFY_INIT (); id_size = 0; /* * Make sure we have a pointer to some data structure. */ if ( !(tower = tower_octet_string)) { *status = twr_s_unknown_tower; return; } /* * Get the tower floor count */ memcpy ((char *)&floor_count, (char *)tower, TWR_C_TOWER_FLR_COUNT_SIZE); RPC_RESOLVE_ENDIAN_INT16 (floor_count); tower += TWR_C_TOWER_FLR_COUNT_SIZE; /* * Skip over the (application's) upper floors while we look for the * beginning of the ip-specific lower floors. */ for ( count = 0; count < floor_count; count++ ) { /* * Get the length of this floor's protocol id field (don't advance * the pointer). */ memcpy ((char *)&id_size, (char *)tower, TWR_C_TOWER_FLR_LHS_COUNT_SIZE); RPC_RESOLVE_ENDIAN_INT16 (id_size); /* * Get the protocol id (don't advance the pointer). * Expect one byte; no need to convert. */ memcpy ((char *)&id, (char *)(tower + TWR_C_TOWER_FLR_LHS_COUNT_SIZE), TWR_C_TOWER_PROT_ID_SIZE); /* * See if we support the protocol id. */ if ( (id_size == TWR_C_TOWER_PROT_ID_SIZE) && (id == TWR_C_FLR_PROT_ID_TCP || id == TWR_C_FLR_PROT_ID_UDP)) { /* * Indicate we found the beginning of the ip floors. */ *status = twr_s_ok; break; } else { /* * Skip this floor. Get the address size in order * to know how much to skip. */ memcpy ((char *)&addr_size, (char *)(tower + TWR_C_TOWER_FLR_LHS_COUNT_SIZE + id_size), TWR_C_TOWER_FLR_RHS_COUNT_SIZE); RPC_RESOLVE_ENDIAN_INT16 (addr_size); tower += TWR_C_TOWER_FLR_LHS_COUNT_SIZE + id_size + TWR_C_TOWER_FLR_RHS_COUNT_SIZE + addr_size; /* * For now, assume we don't find the floors we're looking for. */ *status = twr_s_unknown_tower; } } if (*status != twr_s_ok) { return; } /* * Skip the floor's protocol id field length and protocol id * (now move the pointer). We already know it's * TWR_C_FLR_PROT_ID_TCP or TWR_C_FLR_PROT_ID_UDP. */ tower += (TWR_C_TOWER_FLR_LHS_COUNT_SIZE + id_size); /* * Allocate space for ip sockaddr */ length = sizeof(struct sockaddr_in); RPC_MEM_ALLOC ( *sa, sockaddr_p_t, length, RPC_C_MEM_SOCKADDR, RPC_C_MEM_WAITOK ); *sa_len = length; /* * make sure unused bytes are null */ memset ((char *) *sa, 0, length); /* * define this as an internet family socket */ ((struct sockaddr_in *)(*sa))->sin_family = RPC_C_NAF_ID_IP; /* * Get the length of in_port */ memcpy ((char *)&addr_size, (char *)tower, RPC_C_TOWER_FLR_RHS_COUNT_SIZE); RPC_RESOLVE_ENDIAN_INT16 (addr_size); tower += RPC_C_TOWER_FLR_RHS_COUNT_SIZE; /* * Copy the port number to the sockaddr. */ memcpy ( &((struct sockaddr_in *)(*sa))->sin_port, tower, addr_size); tower += addr_size; /* * Get the length of host address floor protocol id */ memcpy ((char *)&id_size, (char *)tower, TWR_C_TOWER_FLR_LHS_COUNT_SIZE); RPC_RESOLVE_ENDIAN_INT16 (id_size); tower += TWR_C_TOWER_FLR_LHS_COUNT_SIZE; /* * Get the protocol id * Expect one byte; no need to convert. */ memcpy ((char *)&id, (char *)tower, TWR_C_TOWER_PROT_ID_SIZE); tower += id_size; if ( (id_size != TWR_C_TOWER_PROT_ID_SIZE) || (id != TWR_C_FLR_PROT_ID_IP) ) { *status = twr_s_unknown_tower; RPC_MEM_FREE (*sa, RPC_C_MEM_SOCKADDR); return; } /* * Get the length of in_address */ memcpy ((char *)&addr_size, (char *)tower, RPC_C_TOWER_FLR_RHS_COUNT_SIZE); RPC_RESOLVE_ENDIAN_INT16 (addr_size); tower += RPC_C_TOWER_FLR_RHS_COUNT_SIZE; /* * Copy the host address to the sockaddr */ memcpy (&((struct sockaddr_in *)(*sa))->sin_addr.s_addr, (char *)tower, addr_size); *status = twr_s_ok; } #else static int _naf_ip_dummy_ = 0 ; #endif /* NAF_IP */
7,165
5,964
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef GIN_MODULES_MODULE_REGISTRY_OBSERVER_H_ #define GIN_MODULES_MODULE_REGISTRY_OBSERVER_H_ #include <string> #include <vector> #include "gin/gin_export.h" namespace gin { // Notified of interesting events from ModuleRegistry. class GIN_EXPORT ModuleRegistryObserver { public: // Called from AddPendingModule(). |id| is the id/name of the module and // |dependencies| this list of modules |id| depends upon. virtual void OnDidAddPendingModule( const std::string& id, const std::vector<std::string>& dependencies) = 0; protected: virtual ~ModuleRegistryObserver() {} }; } // namespace gin #endif // GIN_MODULES_MODULE_REGISTRY_OBSERVER_H_
287
465
/* * Tencent is pleased to support the open source community by making wwsearch * available. * * Copyright (C) 2018-present Tencent. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/Apache-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 OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #pragma once #include "doc_iterator.h" #include "search_slice.h" #include "serialize.h" #include "storage_type.h" namespace wwsearch { // 1 byte in header // no order insert. struct DocListHeader { // version = 0 -> default,fixed size uint8_t version : 4; // flag for version used uint8_t flag : 3; uint8_t extend : 1; DocListHeader() : version(0), flag(0), extend(0) {} } __attribute__((packed)); typedef uint8_t DocumentState; enum kDocumentIDState { kDocumentStateOK = 0, kDocumentStateDelete = 1 }; class DocListWriterCodec : public SerializeAble { public: virtual ~DocListWriterCodec() {} virtual void AddDocID(const DocumentID& doc_id, DocumentState state) = 0; virtual std::string DebugString() = 0; }; class DocListReaderCodec : public DocIdSetIterator { private: size_t priority_; // used for merge. public: virtual ~DocListReaderCodec() {} virtual DocumentState& State() = 0; inline void SetPriority(size_t v) { this->priority_ = v; } inline size_t GetPriority() { return this->priority_; } private: }; typedef bool (*DocListReaderCodecGreater)(DocListReaderCodec* left, DocListReaderCodec* right); } // namespace wwsearch
608
2,699
{ "title": "Lists", "summary": "All of these list patterns require no extra classes and style the correct semantic element.", "context": { "items": [ "A standard ordered list", "Praesent commodo cursus magna, vel scelerisque nisl consectetur et.", "Pellentesque Condimentum Dapibus Cursus Sit" ] } }
122
384
<reponame>fengjixuchui/exploits-15 #include <stdio.h> #include <stdlib.h> #include <winsock.h> #define READ_PIPE_BUFFER_SIZE 32 #define READ_PIPE_LOOP_SLEEP_TIME 5 #ifdef __cplusplus #define EXTERN extern "C" #else #define EXTERN #endif #ifdef _MSC_VER #define EXPORT __declspec(dllexport) #endif enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT}; typedef struct st_udf_args { unsigned int arg_count; enum Item_result *arg_type; char **args; unsigned long *lengths; char *maybe_null; } UDF_ARGS; typedef struct st_udf_init { char maybe_null; unsigned int decimals; unsigned long max_length; char *ptr; char const_item; } UDF_INIT; typedef struct { HANDLE hPipeHandle; SOCKET sSocket; } THREAD_PARAM, *PTHREAD_PARAM; static VOID ProcessInThread(PTHREAD_PARAM ptpParam); static VOID ProcessOutThread(PTHREAD_PARAM ptpParam); void Report(LPTSTR lpErrorMessage, DWORD dwErrorCode, BOOL bTerminateProcess);
443
335
{ "word": "Cell", "definitions": [ "A small room in which a prisoner is locked up or in which a monk or nun sleeps.", "A small monastery or nunnery dependent on a larger one.", "The smallest structural and functional unit of an organism, which is typically microscopic and consists of cytoplasm and a nucleus enclosed in a membrane.", "An enclosed cavity in an organism.", "A small compartment in a larger structure such as a honeycomb.", "A small group forming a nucleus of political activity, typically a secret, subversive one.", "A device containing electrodes immersed in an electrolyte, used for generating current or for electrolysis.", "A unit in a device for converting chemical or solar energy into electricity.", "The local area covered by one of the short-range transmitters in a cellular telephone system.", "A mobile phone." ], "parts-of-speech": "Noun" }
285
388
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.stream.Stream; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTextArea log = new JTextArea(); JFileChooser chooser = new JFileChooser(); JButton button1 = new JButton("FILES_AND_DIRECTORIES"); button1.addActionListener(e -> { chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); updateFileChooser(chooser); int retValue = chooser.showOpenDialog(getRootPane()); if (retValue == JFileChooser.APPROVE_OPTION) { log.append(String.format("%s%n", chooser.getSelectedFile())); } }); JButton button2 = new JButton("DIRECTORIES_ONLY"); button2.addActionListener(e -> { chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); updateFileChooser(chooser); int retValue = chooser.showOpenDialog(getRootPane()); if (retValue == JFileChooser.APPROVE_OPTION) { log.append(String.format("%s%n", chooser.getSelectedFile())); } }); JPanel p = new JPanel(new GridLayout(0, 1, 5, 5)); p.setBorder(BorderFactory.createTitledBorder("JFileChooser#showOpenDialog(...)")); p.add(button1); p.add(button2); add(p, BorderLayout.NORTH); add(new JScrollPane(log)); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setPreferredSize(new Dimension(320, 240)); } private static void updateFileChooser(JFileChooser fileChooser) { boolean f = fileChooser.getFileSelectionMode() != JFileChooser.DIRECTORIES_ONLY; fileChooser.setAcceptAllFileFilterUsed(f); String labelText = UIManager.getString("FileChooser.filesOfTypeLabelText", fileChooser.getLocale()); SwingUtils.descendants(fileChooser) .filter(JLabel.class::isInstance).map(JLabel.class::cast) .forEach(label -> { if (labelText.equals(label.getText())) { Component c = label.getLabelFor(); label.setEnabled(f); if (c instanceof JComboBox<?>) { JComboBox<?> combo = (JComboBox<?>) c; combo.setEnabled(f); ((JComponent) combo.getRenderer()).setOpaque(f); } } }); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } final class SwingUtils { private SwingUtils() { /* Singleton */ } public static Stream<Component> descendants(Container parent) { return Stream.of(parent.getComponents()) .filter(Container.class::isInstance).map(Container.class::cast) .flatMap(c -> Stream.concat(Stream.of(c), descendants(c))); } }
1,331
1,369
<gh_stars>1000+ { "name": "DreamFactory API Management Platform", "description": "DreamFactory is a popular iPaaS solution used by thousands of companies around the globe.", "repository": "https://github.com/dreamfactorysoftware/dreamfactory", "logo": "https://github.com/dreamfactorysoftware/dreamfactory/raw/master/readme/vertical-logo-fullcolor.png", "keywords": [ "ipaas", "api", "api-gateway", "api-management", "dreamfactory" ], "addons": ["heroku-postgresql:hobby-dev"], "buildpacks": [ { "url": "https://github.com/heroku/heroku-buildpack-cli" }, { "url": "https://github.com/heroku/heroku-buildpack-php" } ], "env": { "APP_NAME": { "description": "This must exactly match the App name you specified above", "required": "true" }, "APP_ENV": "local", "DB_CONNECTION": "pgsql", "LOG_CHANNEL": "heroku", "HEROKU_API_KEY": { "description": "Please enter your Heroku API Key: https://dashboard.heroku.com/account", "required": "true" } }, "scripts": { "postdeploy": "./bin/heroku.sh" } }
469
945
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkTransformGeometryImageFilter.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkVersorRigid3DTransform.h" #include "itkImageRegionConstIterator.h" #include "itkTestingMacros.h" #include <iostream> // return true if it fails the validation inline bool Validate(double input, double desired, double tolerance) { return std::abs<double>(input - desired) > tolerance * std::abs<double>(desired); } // Returns true if images are different template <typename ImageType> bool imagesDifferent(ImageType * baselineImage, ImageType * outputImage) { double tol = 1.e-3; // tolerance typename ImageType::PointType origin = outputImage->GetOrigin(); typename ImageType::DirectionType direction = outputImage->GetDirection(); typename ImageType::SpacingType spacing = outputImage->GetSpacing(); typename ImageType::PointType origin_d = baselineImage->GetOrigin(); typename ImageType::DirectionType direction_d = baselineImage->GetDirection(); typename ImageType::SpacingType spacing_d = baselineImage->GetSpacing(); // Image info validation bool result = false; // no difference by default for (unsigned int i = 0; i < ImageType::ImageDimension; ++i) { result = (result || Validate(origin[i], origin_d[i], tol)); result = (result || Validate(spacing[i], spacing_d[i], tol)); for (unsigned int j = 0; j < ImageType::ImageDimension; ++j) { result = (result || Validate(direction(i, j), direction_d(i, j), tol)); } } // Voxel contents validation using ImageConstIterator = itk::ImageRegionConstIterator<ImageType>; ImageConstIterator it1(outputImage, outputImage->GetRequestedRegion()); ImageConstIterator it2(baselineImage, baselineImage->GetRequestedRegion()); it1.GoToBegin(); it2.GoToBegin(); while (!it1.IsAtEnd()) { result = (result || Validate(it1.Get(), it2.Get(), tol)); ++it1; ++it2; } return result; } int itkTransformGeometryImageFilterTest(int argc, char * argv[]) { if (argc < 3) { std::cerr << "Wrong arguments!" << std::endl; std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " inputImage baselineImage outputImage" << std::endl; return EXIT_FAILURE; } constexpr unsigned int Dimension = 3; using PixelType = short; using ImageType = itk::Image<PixelType, Dimension>; using ImagePointer = ImageType::Pointer; using TransformType = itk::VersorRigid3DTransform<double>; using FilterType = itk::TransformGeometryImageFilter<ImageType, ImageType>; // Read in input test image ImagePointer inputImage; ITK_TRY_EXPECT_NO_EXCEPTION(inputImage = itk::ReadImage<ImageType>(argv[1])); // Set up transforms ImageType::PointType center; center.Fill(0.0); center[0] = 2.0; // In mm along X (RL-axis) center[1] = 5.0; // In mm along Y (AP-axis) center[2] = 7.0; // In mm along Z (IS-axis) itk::Vector<double, Dimension> translation; translation.Fill(0.); translation[0] = 10.0; // In mm along X (RL-axis) translation[1] = 15.0; // In mm along Y (AP-axis) translation[2] = 20.0; // In mm along Z (IS-axis) itk::Vector<double, Dimension> rotationAxis; rotationAxis[0] = 0.1; rotationAxis[1] = 0.2; rotationAxis[2] = 0.7; double rotationAngle = .5; // Radians TransformType::Pointer transform = TransformType::New(); // Identity by default transform->SetCenter(center); transform->Translate(translation); transform->SetRotation(rotationAxis, rotationAngle); // Set up the transform filter FilterType::Pointer filter = FilterType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, TransformGeometryImageFilter, InPlaceImageFilter); // Test the exceptions ITK_TRY_EXPECT_EXCEPTION(filter->Update()); filter->SetInputImage(inputImage); ITK_TEST_SET_GET_VALUE(inputImage, filter->GetInputImage()); filter->SetTransform(transform); ITK_TEST_SET_GET_VALUE(transform, filter->GetTransform()); ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); ImagePointer outputImage = filter->GetOutput(); ITK_TRY_EXPECT_NO_EXCEPTION(itk::WriteImage(outputImage, argv[3])); // Read in baseline image ImagePointer baselineImage = nullptr; ITK_TRY_EXPECT_NO_EXCEPTION(baselineImage = itk::ReadImage<ImageType>(argv[2])); // Now do comparisons bool result = imagesDifferent<ImageType>(baselineImage, outputImage); transform->ApplyToImageMetadata(inputImage); result = (result || imagesDifferent<ImageType>(baselineImage, inputImage)); // Make sure we can invoke ApplyToImageMetadata via const/raw pointer TransformType * rawPointerTransform = transform.GetPointer(); rawPointerTransform->ApplyToImageMetadata(inputImage); rawPointerTransform->ApplyToImageMetadata(inputImage.GetPointer()); const TransformType * constRawPointerTransform = transform.GetPointer(); constRawPointerTransform->ApplyToImageMetadata(inputImage); TransformType::ConstPointer constPointerTransform = transform.GetPointer(); constPointerTransform->ApplyToImageMetadata(inputImage); constPointerTransform->ApplyToImageMetadata(inputImage.GetPointer()); return result; }
1,871
337
<reponame>KamilKurde/AmazMod package com.amazmod.service.springboard.settings; import android.graphics.drawable.Drawable; import android.widget.CompoundButton; import com.amazmod.service.springboard.SpringboardItem; /** * Created by Kieron on 12/02/2018. */ public class SpringboardSetting extends SwitchSetting { //Hold springboard item for use later private SpringboardItem springboardItem; //Constructor to be identical to the super but with an item for setting public SpringboardSetting(Drawable icon, String title, String subtitle, CompoundButton.OnCheckedChangeListener changeListener, boolean isChecked, SpringboardItem springboardItem) { super(icon, title, subtitle, changeListener, isChecked); //Set item this.springboardItem = springboardItem; } //Getter for item public SpringboardItem getSpringboardItem() { return springboardItem; } }
287
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-7ggp-fc92-x5m6", "modified": "2022-01-12T00:02:08Z", "published": "2021-12-31T00:00:22Z", "aliases": [ "CVE-2021-20171" ], "details": "Netgear RAX43 version 172.16.58.3 stores sensitive information in plaintext. All usernames and passwords for the device's associated services are stored in plaintext on the device. For example, the admin password is stored in plaintext in the primary configuration file on the device.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20171" }, { "type": "WEB", "url": "https://www.tenable.com/security/research/tra-2021-55" } ], "database_specific": { "cwe_ids": [ "CWE-312" ], "severity": "MODERATE", "github_reviewed": false } }
389
696
<reponame>hwang-pku/Strata /* * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.capfloor; import static com.opengamma.strata.basics.currency.Currency.EUR; import static com.opengamma.strata.basics.date.DayCounts.ACT_ACT_ISDA; import static com.opengamma.strata.market.curve.interpolator.CurveInterpolators.LINEAR; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import com.opengamma.strata.basics.index.IborIndex; import com.opengamma.strata.collect.array.DoubleArray; import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries; import com.opengamma.strata.market.ValueType; import com.opengamma.strata.market.curve.ConstantCurve; import com.opengamma.strata.market.curve.CurveMetadata; import com.opengamma.strata.market.curve.CurveName; import com.opengamma.strata.market.curve.Curves; import com.opengamma.strata.market.curve.DefaultCurveMetadata; import com.opengamma.strata.market.curve.InterpolatedNodalCurve; import com.opengamma.strata.market.curve.SimpleCurveParameterMetadata; import com.opengamma.strata.market.param.ParameterMetadata; import com.opengamma.strata.pricer.model.SabrParameters; import com.opengamma.strata.pricer.model.SabrVolatilityFormula; import com.opengamma.strata.pricer.rate.ImmutableRatesProvider; /** * Data sets for testing SABR model for Ibor caplet/floorlet. */ public class IborCapletFloorletSabrRateVolatilityDataSet { private static final DoubleArray EUR_DSC_TIME = DoubleArray.of(0.0, 0.5, 1.0, 2.0, 5.0, 10.0); private static final DoubleArray EUR_DSC_RATE = DoubleArray.of(0.0150, 0.0125, 0.0150, 0.0175, 0.0150, 0.0150); private static final CurveName EUR_DSC_NAME = CurveName.of("EUR-DSCON"); private static final CurveMetadata EUR_DSC_META = Curves.zeroRates(EUR_DSC_NAME, ACT_ACT_ISDA); private static final InterpolatedNodalCurve EUR_DSC_CURVE = InterpolatedNodalCurve.of(EUR_DSC_META, EUR_DSC_TIME, EUR_DSC_RATE, LINEAR); private static final DoubleArray EUR_FWD_TIME = DoubleArray.of(0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0); private static final DoubleArray EUR_FWD_RATE = DoubleArray.of(0.0150, 0.0125, 0.0150, 0.0175, 0.0175, 0.0190, 0.0200, 0.0210); private static final CurveName EUR_FWD_NAME = CurveName.of("EUR-FWD"); private static final CurveMetadata EUR_FWD_META = Curves.zeroRates(EUR_FWD_NAME, ACT_ACT_ISDA); private static final InterpolatedNodalCurve EUR_FWD_CURVE = InterpolatedNodalCurve.of(EUR_FWD_META, EUR_FWD_TIME, EUR_FWD_RATE, LINEAR); private static final DoubleArray ALPHA_TIME = DoubleArray.of(0.0, 0.5, 1.0, 2.0, 5.0, 10.0); private static final DoubleArray BETA_TIME = DoubleArray.of(0.0, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0); private static final DoubleArray RHO_TIME = DoubleArray.of(0.0, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0); private static final DoubleArray NU_TIME = DoubleArray.of(0.0, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0); static final CurveMetadata META_ALPHA = Curves.sabrParameterByExpiry( "Test-SABR-Alpha", ACT_ACT_ISDA, ValueType.SABR_ALPHA).withParameterMetadata(createParameterMetadata(ALPHA_TIME)); static final CurveMetadata META_BETA = Curves.sabrParameterByExpiry( "Test-SABR-Beta", ACT_ACT_ISDA, ValueType.SABR_BETA).withParameterMetadata(createParameterMetadata(BETA_TIME)); static final CurveMetadata META_RHO = Curves.sabrParameterByExpiry( "Test-SABR-Rho", ACT_ACT_ISDA, ValueType.SABR_RHO).withParameterMetadata(createParameterMetadata(RHO_TIME)); static final CurveMetadata META_NU = Curves.sabrParameterByExpiry( "Test-SABR-Nu", ACT_ACT_ISDA, ValueType.SABR_NU).withParameterMetadata(createParameterMetadata(NU_TIME)); private static final DoubleArray ALPHA_VALUE_FLAT = DoubleArray.of(0.05, 0.05, 0.05, 0.05, 0.05, 0.05); private static final DoubleArray BETA_VALUE_FLAT = DoubleArray.of(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5); private static final DoubleArray RHO_VALUE_FLAT = DoubleArray.of(-0.25, -0.25, -0.25, -0.25, -0.25, -0.25, -0.25); private static final DoubleArray NU_VALUE_FLAT = DoubleArray.of(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5); private static final InterpolatedNodalCurve CURVE_ALPHA_FLAT = InterpolatedNodalCurve.of( META_ALPHA, ALPHA_TIME, ALPHA_VALUE_FLAT, LINEAR); private static final InterpolatedNodalCurve CURVE_BETA_FLAT = InterpolatedNodalCurve.of( META_BETA, BETA_TIME, BETA_VALUE_FLAT, LINEAR); private static final InterpolatedNodalCurve CURVE_RHO_FLAT = InterpolatedNodalCurve.of( META_RHO, RHO_TIME, RHO_VALUE_FLAT, LINEAR); private static final InterpolatedNodalCurve CURVE_NU_FLAT = InterpolatedNodalCurve.of( META_NU, NU_TIME, NU_VALUE_FLAT, LINEAR); static final SabrParameters SABR_PARAM_FLAT = SabrParameters.of( CURVE_ALPHA_FLAT, CURVE_BETA_FLAT, CURVE_RHO_FLAT, CURVE_NU_FLAT, SabrVolatilityFormula.hagan()); private static final DoubleArray ALPHA_VALUE = DoubleArray.of(0.035, 0.057, 0.044, 0.033, 0.032, 0.022); private static final DoubleArray BETA_VALUE = DoubleArray.of(0.5, 0.6, 0.4, 0.1, 0.8, 0.2, 0.2); private static final DoubleArray RHO_VALUE = DoubleArray.of(-0.75, -0.2, 0.05, 0.25, -0.25, 0.15, 0.22); private static final DoubleArray NU_VALUE = DoubleArray.of(0.35, 0.45, 0.59, 0.52, 0.51, 0.32, 0.44); private static final InterpolatedNodalCurve CURVE_ALPHA = InterpolatedNodalCurve.of( META_ALPHA, ALPHA_TIME, ALPHA_VALUE, LINEAR); private static final InterpolatedNodalCurve CURVE_BETA = InterpolatedNodalCurve.of( META_BETA, BETA_TIME, BETA_VALUE, LINEAR); private static final InterpolatedNodalCurve CURVE_RHO = InterpolatedNodalCurve.of( META_RHO, RHO_TIME, RHO_VALUE, LINEAR); private static final InterpolatedNodalCurve CURVE_NU = InterpolatedNodalCurve.of( META_NU, NU_TIME, NU_VALUE, LINEAR); private static final DoubleArray SHIFT_TIME = DoubleArray.of(0.0, 5.0, 10.0, 100.0); private static final DoubleArray SHIFT_VALUE = DoubleArray.of(0.01, 0.02, 0.012, 0.01); static final CurveMetadata META_SHIFT = DefaultCurveMetadata.builder() .curveName(CurveName.of("Test-SABR-Shift")) .xValueType(ValueType.YEAR_FRACTION) .parameterMetadata(createParameterMetadata(SHIFT_TIME)) .build(); private static final InterpolatedNodalCurve CURVE_SHIFT = InterpolatedNodalCurve.of( META_SHIFT, SHIFT_TIME, SHIFT_VALUE, LINEAR); static final SabrParameters SABR_PARAM = SabrParameters.of( CURVE_ALPHA, CURVE_BETA, CURVE_RHO, CURVE_NU, CURVE_SHIFT, SabrVolatilityFormula.hagan()); static final double CONST_SHIFT = 0.015; private static final DefaultCurveMetadata META_CONST_SHIFT = DefaultCurveMetadata.of("Test-SABR-Shift"); static final ConstantCurve CURVE_CONST_SHIFT = ConstantCurve.of(META_CONST_SHIFT, CONST_SHIFT); static final SabrParameters SABR_PARAM_CONST_SHIFT = SabrParameters.of( CURVE_ALPHA, CURVE_BETA, CURVE_RHO, CURVE_NU, CURVE_CONST_SHIFT, SabrVolatilityFormula.hagan()); static final IborCapletFloorletVolatilitiesName NAME = IborCapletFloorletVolatilitiesName.of("Test-SABR"); // create a list of SimpleCurveParameterMetadata private static List<ParameterMetadata> createParameterMetadata(DoubleArray time) { int n = time.size(); List<ParameterMetadata> list = new ArrayList<>(); for (int i = 0; i < n; ++i) { list.add(SimpleCurveParameterMetadata.of(ValueType.YEAR_FRACTION, time.get(i))); } return list; } //------------------------------------------------------------------------- /** * Obtains {@code ImmutableRatesProvider} for specified valuation date. * * @param valuationDate the valuation date * @param index the index * @param timeSeries the time series * @return the rates provider */ public static ImmutableRatesProvider getRatesProvider(LocalDate valuationDate, IborIndex index, LocalDateDoubleTimeSeries timeSeries) { return ImmutableRatesProvider.builder(valuationDate) .discountCurve(EUR, EUR_DSC_CURVE) .iborIndexCurve(index, EUR_FWD_CURVE) .timeSeries(index, timeSeries) .build(); } /** * Obtains {@code SabrParametersIborCapletFloorletVolatilities} with constant SABR parameters for specified valuation date. * * @param valuationDate the valuation date * @param index the index * @return the volatility provider */ public static SabrParametersIborCapletFloorletVolatilities getVolatilitiesFlatParameters( LocalDate valuationDate, IborIndex index) { ZonedDateTime dateTime = valuationDate.atStartOfDay(ZoneOffset.UTC); return SabrParametersIborCapletFloorletVolatilities.of(NAME, index, dateTime, SABR_PARAM_FLAT); } /** * Obtains {@code SabrParametersIborCapletFloorletVolatilities} with constant shift for specified valuation date. * * @param dateTime the valuation date time * @param index the index * @return the volatility provider */ public static SabrParametersIborCapletFloorletVolatilities getVolatilities(ZonedDateTime dateTime, IborIndex index) { return SabrParametersIborCapletFloorletVolatilities.of(NAME, index, dateTime, SABR_PARAM_CONST_SHIFT); } }
3,611
575
<filename>third_party/blink/renderer/core/workers/worker_backing_thread.h // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_BACKING_THREAD_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_BACKING_THREAD_H_ #include <memory> #include "base/memory/ptr_util.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/thread_state.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/forward.h" #include "third_party/blink/renderer/platform/wtf/threading_primitives.h" #include "v8/include/v8.h" namespace blink { struct WorkerBackingThreadStartupData; // WorkerBackingThread represents a WebThread with Oilpan and V8. A client of // WorkerBackingThread (i.e., WorkerThread) needs to call // InitializeOnBackingThread() to use V8 and Oilpan functionalities, and call // ShutdownOnBackingThread() when it no longer needs the thread. class CORE_EXPORT WorkerBackingThread final { USING_FAST_MALLOC(WorkerBackingThread); public: explicit WorkerBackingThread(const ThreadCreationParams&); ~WorkerBackingThread(); // InitializeOnBackingThread() and ShutdownOnBackingThread() attaches and // detaches Oilpan and V8 to / from the caller worker script, respectively. // A worker script must not call any function after calling // ShutdownOnBackingThread(). They should be called from |this| thread. void InitializeOnBackingThread(const WorkerBackingThreadStartupData&); void ShutdownOnBackingThread(); blink::Thread& BackingThread() { DCHECK(backing_thread_); return *backing_thread_; } v8::Isolate* GetIsolate() { return isolate_; } static void MemoryPressureNotificationToWorkerThreadIsolates( v8::MemoryPressureLevel); private: std::unique_ptr<blink::Thread> backing_thread_; v8::Isolate* isolate_ = nullptr; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_BACKING_THREAD_H_
744
303
<gh_stars>100-1000 #pragma once #include "common/luax.h" #include "objects/random/randomgenerator.h" namespace Wrap_RandomGenerator { int GetSeed(lua_State* L); int GetState(lua_State* L); int _Random(lua_State* L); int RandomNormal(lua_State* L); int SetSeed(lua_State* L); int SetState(lua_State* L); love::RandomGenerator::Seed CheckRandomSeed(lua_State* L, int index); love::RandomGenerator* CheckRandomGenerator(lua_State* L, int index); int Register(lua_State* L); } // namespace Wrap_RandomGenerator
210
879
<reponame>LEONAD486/zstack package org.zstack.sdk; public enum MdevDeviceStatus { Active, Attached, Reserved, }
48
575
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_MODEL_OBSERVER_H_ #define COMPONENTS_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_MODEL_OBSERVER_H_ #include <string> #include <vector> namespace send_tab_to_self { class SendTabToSelfEntry; // Observer for the Send Tab To Self model. In the observer methods care should // be taken to not modify the model. class SendTabToSelfModelObserver { public: SendTabToSelfModelObserver() {} virtual ~SendTabToSelfModelObserver() {} // Invoked when the model has finished loading. Until this method is called it // is unsafe to use the model. // This call has overlaps with SendTabToSelfModel::IsReady but by having this // be a pure virtual function we can ensure that subclasses of this class will // have a way to ensure that the model is active before interacting with it. virtual void SendTabToSelfModelLoaded() = 0; // Invoked when elements of the model are added, removed, or updated. This is // the mechanism for the sync server to push changes in the state of the model // to clients. // TODO(crbug.com/945396) move EntriesAddedRemotely to use const refs to // clarify ownership. virtual void EntriesAddedRemotely( const std::vector<const SendTabToSelfEntry*>& new_entries) = 0; virtual void EntriesRemovedRemotely( const std::vector<std::string>& guids) = 0; // This observer will>>>>>>>> notify listeners of new and existing entries // that have been marked as opened. virtual void EntriesOpenedRemotely( const std::vector<const SendTabToSelfEntry*>& opened_entries) {} private: DISALLOW_COPY_AND_ASSIGN(SendTabToSelfModelObserver); }; } // namespace send_tab_to_self #endif // COMPONENTS_SEND_TAB_TO_SELF_SEND_TAB_TO_SELF_MODEL_OBSERVER_H_
612
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.datalabeling.v1beta1.model; /** * Config for video classification human labeling task. Currently two types of video classification * are supported: 1. Assign labels on the entire video. 2. Split the video into multiple video clips * based on camera shot, and assign labels on each video clip. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Data Labeling API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDatalabelingV1beta1VideoClassificationConfig extends com.google.api.client.json.GenericJson { /** * Required. The list of annotation spec set configs. Since watching a video clip takes much * longer time than an image, we support label with multiple AnnotationSpecSet at the same time. * Labels in each AnnotationSpecSet will be shown in a group to contributors. Contributors can * select one or more (depending on whether to allow multi label) from each group. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDatalabelingV1beta1AnnotationSpecSetConfig> annotationSpecSetConfigs; static { // hack to force ProGuard to consider GoogleCloudDatalabelingV1beta1AnnotationSpecSetConfig used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDatalabelingV1beta1AnnotationSpecSetConfig.class); } /** * Optional. Option to apply shot detection on the video. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean applyShotDetection; /** * Required. The list of annotation spec set configs. Since watching a video clip takes much * longer time than an image, we support label with multiple AnnotationSpecSet at the same time. * Labels in each AnnotationSpecSet will be shown in a group to contributors. Contributors can * select one or more (depending on whether to allow multi label) from each group. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDatalabelingV1beta1AnnotationSpecSetConfig> getAnnotationSpecSetConfigs() { return annotationSpecSetConfigs; } /** * Required. The list of annotation spec set configs. Since watching a video clip takes much * longer time than an image, we support label with multiple AnnotationSpecSet at the same time. * Labels in each AnnotationSpecSet will be shown in a group to contributors. Contributors can * select one or more (depending on whether to allow multi label) from each group. * @param annotationSpecSetConfigs annotationSpecSetConfigs or {@code null} for none */ public GoogleCloudDatalabelingV1beta1VideoClassificationConfig setAnnotationSpecSetConfigs(java.util.List<GoogleCloudDatalabelingV1beta1AnnotationSpecSetConfig> annotationSpecSetConfigs) { this.annotationSpecSetConfigs = annotationSpecSetConfigs; return this; } /** * Optional. Option to apply shot detection on the video. * @return value or {@code null} for none */ public java.lang.Boolean getApplyShotDetection() { return applyShotDetection; } /** * Optional. Option to apply shot detection on the video. * @param applyShotDetection applyShotDetection or {@code null} for none */ public GoogleCloudDatalabelingV1beta1VideoClassificationConfig setApplyShotDetection(java.lang.Boolean applyShotDetection) { this.applyShotDetection = applyShotDetection; return this; } @Override public GoogleCloudDatalabelingV1beta1VideoClassificationConfig set(String fieldName, Object value) { return (GoogleCloudDatalabelingV1beta1VideoClassificationConfig) super.set(fieldName, value); } @Override public GoogleCloudDatalabelingV1beta1VideoClassificationConfig clone() { return (GoogleCloudDatalabelingV1beta1VideoClassificationConfig) super.clone(); } }
1,410
5,821
<gh_stars>1000+ package io.javalin.examples; import io.javalin.Javalin; import io.javalin.plugin.graphql.GraphQLOptions; import io.javalin.plugin.graphql.GraphQLPlugin; public class HelloWorldGraphQL { public static void main(String[] args) { GraphQLOptions graphQLOptions = new GraphQLOptions("/graphql", null) .addPackage("io.javalin.examples") .register(new QueryExampleJVM()); Javalin .create(config -> config.registerPlugin(new GraphQLPlugin(graphQLOptions))) .start(7070); } }
228
911
default_app_config = 'jobs.apps.JobsAppConfig'
17
965
<filename>docs/parallel/concrt/codesnippet/CPP/walkthrough-removing-work-from-a-user-interface-thread_13.cpp void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting // If the unbounded_buffer object contains a Bitmap object, // draw the image to the client area. BitmapPtr pBitmap; if (try_receive(m_MandelbrotImages, pBitmap)) { if (pBitmap != NULL) { // Draw the bitmap to the client area. Graphics g(dc); g.DrawImage(pBitmap.get(), 0, 0); } } // Draw the image on a worker thread if the image is not available. else { RECT rc; GetClientRect(&rc); m_DrawingTasks.run([rc,this]() { DrawMandelbrot(BitmapPtr(new Bitmap(rc.right, rc.bottom))); }); } }
338
678
<gh_stars>100-1000 /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices */ #import <PhotoLibraryServices/PhotoLibraryServices-Structs.h> #import <PhotoLibraryServices/PLFilteredShuffledAlbum.h> #import <PhotoLibraryServices/PLShuffledAlbum.h> @class NSPredicate; @interface PLFilteredShuffledAlbum : PLShuffledAlbum { @private int _filter; // 12 = 0xc NSPredicate *_filterPredicate; // 16 = 0x10 } @property(readonly, assign, nonatomic) NSPredicate *filterPredicate; // G=0x6f729; @synthesize=_filterPredicate @property(readonly, assign, nonatomic) int filter; // G=0x6f719; @synthesize=_filter + (NSObject *)_shuffledAlbumWithAlbum:(NSObject *)album filter:(int)filter startingAsset:(id)asset; // 0x6f439 // declared property getter: - (id)filterPredicate; // 0x6f729 // declared property getter: - (int)filter; // 0x6f719 - (unsigned)count; // 0x6f6e1 - (void)dealloc; // 0x6f68d - (id)initWithBackingAlbum:(NSObject *)backingAlbum filter:(int)filter startingAsset:(id)asset; // 0x6f609 - (NSObject *)unshuffledAlbum; // 0x6f5b5 @end @interface PLFilteredShuffledAlbum (IndexMapping) - (void)createShuffledIndexesMaps; // 0x6f739 @end
467
892
{ "schema_version": "1.2.0", "id": "GHSA-x97c-px3m-v4g2", "modified": "2022-05-13T01:49:11Z", "published": "2022-05-13T01:49:11Z", "aliases": [ "CVE-2018-11319" ], "details": "Syntastic (aka vim-syntastic) through 3.9.0 does not properly handle searches for configuration files (it searches the current directory up to potentially the root). This improper handling might be exploited for arbitrary code execution via a malicious gcc plugin, if an attacker has write access to a directory that is a parent of the base directory of the project being checked. NOTE: exploitation is more difficult after 3.8.0 because filename prediction may be needed.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-11319" }, { "type": "WEB", "url": "https://github.com/vim-syntastic/syntastic/issues/2170" }, { "type": "WEB", "url": "https://github.com/vim-syntastic/syntastic/commit/6d7c0b394e001233dd09ec473fbea2002c72632f" }, { "type": "WEB", "url": "https://bugs.debian.org/894736" }, { "type": "WEB", "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00036.html" }, { "type": "WEB", "url": "https://www.debian.org/security/2018/dsa-4261" } ], "database_specific": { "cwe_ids": [ "CWE-22" ], "severity": "HIGH", "github_reviewed": false } }
710
1,197
<gh_stars>1000+ from setuptools import setup from setuptools.command.develop import develop as BaseDevelop from setuptools.command.sdist import sdist as BaseSDist try: from wheel.bdist_wheel import bdist_wheel as BaseBDistWheel except ImportError: BaseBDistWheel = None class CompileCatalogMixin: """Compile MO files with Babel's ``compile_catalog`` command. This happens after installing in development mode, or before building sdist and wheel. """ def __init__(self, dist, **kw): super().__init__(dist, **kw) def run(self): is_develop = isinstance(self, Develop) if not is_develop: self.run_command("compile_catalog") super().run() if is_develop and not self.uninstall: self.run_command("compile_catalog") class Develop(CompileCatalogMixin, BaseDevelop): pass class SDist(CompileCatalogMixin, BaseSDist): pass command_classes = {"develop": Develop, "sdist": SDist} if BaseBDistWheel: class BDistWheel(CompileCatalogMixin, BaseBDistWheel): pass command_classes["bdist_wheel"] = BDistWheel # Metadata goes in setup.cfg. These are here for GitHub's dependency graph. setup( name="WTForms", install_requires=["MarkupSafe"], cmdclass=command_classes, )
472
5,843
import unittest from flask import Flask, Blueprint, request try: from mock import Mock except: # python3 from unittest.mock import Mock import flask import flask_restful import flask_restful.fields #noinspection PyUnresolvedReferences from nose.tools import assert_true, assert_false # you need it for tests in form of continuations # Add a dummy Resource to verify that the app is properly set. class HelloWorld(flask_restful.Resource): def get(self): return {} class GoodbyeWorld(flask_restful.Resource): def __init__(self, err): self.err = err def get(self): flask.abort(self.err) class APIWithBlueprintTestCase(unittest.TestCase): def test_api_base(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) app = Flask(__name__) app.register_blueprint(blueprint) self.assertEqual(api.urls, {}) self.assertEqual(api.prefix, '') self.assertEqual(api.default_mediatype, 'application/json') def test_api_delayed_initialization(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api() api.init_app(blueprint) app = Flask(__name__) app.register_blueprint(blueprint) api.add_resource(HelloWorld, '/', endpoint="hello") def test_add_resource_endpoint(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) view = Mock(**{'as_view.return_value': Mock(__name__='test_view')}) api.add_resource(view, '/foo', endpoint='bar') app = Flask(__name__) app.register_blueprint(blueprint) view.as_view.assert_called_with('bar') def test_add_resource_endpoint_after_registration(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) app = Flask(__name__) app.register_blueprint(blueprint) view = Mock(**{'as_view.return_value': Mock(__name__='test_view')}) api.add_resource(view, '/foo', endpoint='bar') view.as_view.assert_called_with('bar') def test_url_with_api_prefix(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint, prefix='/api') api.add_resource(HelloWorld, '/hi', endpoint='hello') app = Flask(__name__) app.register_blueprint(blueprint) with app.test_request_context('/api/hi'): self.assertEqual(request.endpoint, 'test.hello') def test_url_with_blueprint_prefix(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint) api.add_resource(HelloWorld, '/hi', endpoint='hello') app = Flask(__name__) app.register_blueprint(blueprint) with app.test_request_context('/bp/hi'): self.assertEqual(request.endpoint, 'test.hello') def test_url_with_registration_prefix(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) api.add_resource(HelloWorld, '/hi', endpoint='hello') app = Flask(__name__) app.register_blueprint(blueprint, url_prefix='/reg') with app.test_request_context('/reg/hi'): self.assertEqual(request.endpoint, 'test.hello') def test_registration_prefix_overrides_blueprint_prefix(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint) api.add_resource(HelloWorld, '/hi', endpoint='hello') app = Flask(__name__) app.register_blueprint(blueprint, url_prefix='/reg') with app.test_request_context('/reg/hi'): self.assertEqual(request.endpoint, 'test.hello') def test_url_with_api_and_blueprint_prefix(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint, prefix='/api') api.add_resource(HelloWorld, '/hi', endpoint='hello') app = Flask(__name__) app.register_blueprint(blueprint) with app.test_request_context('/bp/api/hi'): self.assertEqual(request.endpoint, 'test.hello') def test_url_part_order_aeb(self): blueprint = Blueprint('test', __name__, url_prefix='/bp') api = flask_restful.Api(blueprint, prefix='/api', url_part_order='aeb') api.add_resource(HelloWorld, '/hi', endpoint='hello') app = Flask(__name__) app.register_blueprint(blueprint) with app.test_request_context('/api/hi/bp'): self.assertEqual(request.endpoint, 'test.hello') def test_error_routing(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) api.add_resource(HelloWorld(), '/hi', endpoint="hello") api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye") app = Flask(__name__) app.register_blueprint(blueprint) with app.test_request_context('/hi', method='POST'): assert_true(api._should_use_fr_error_handler()) assert_true(api._has_fr_route()) with app.test_request_context('/bye'): api._should_use_fr_error_handler = Mock(return_value=False) assert_true(api._has_fr_route()) def test_non_blueprint_rest_error_routing(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) api.add_resource(HelloWorld(), '/hi', endpoint="hello") api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye") app = Flask(__name__) app.register_blueprint(blueprint, url_prefix='/blueprint') api2 = flask_restful.Api(app) api2.add_resource(HelloWorld(), '/hi', endpoint="hello") api2.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye") with app.test_request_context('/hi', method='POST'): assert_false(api._should_use_fr_error_handler()) assert_true(api2._should_use_fr_error_handler()) assert_false(api._has_fr_route()) assert_true(api2._has_fr_route()) with app.test_request_context('/blueprint/hi', method='POST'): assert_true(api._should_use_fr_error_handler()) assert_false(api2._should_use_fr_error_handler()) assert_true(api._has_fr_route()) assert_false(api2._has_fr_route()) api._should_use_fr_error_handler = Mock(return_value=False) api2._should_use_fr_error_handler = Mock(return_value=False) with app.test_request_context('/bye'): assert_false(api._has_fr_route()) assert_true(api2._has_fr_route()) with app.test_request_context('/blueprint/bye'): assert_true(api._has_fr_route()) assert_false(api2._has_fr_route()) def test_non_blueprint_non_rest_error_routing(self): blueprint = Blueprint('test', __name__) api = flask_restful.Api(blueprint) api.add_resource(HelloWorld(), '/hi', endpoint="hello") api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye") app = Flask(__name__) app.register_blueprint(blueprint, url_prefix='/blueprint') @app.route('/hi') def hi(): return 'hi' @app.route('/bye') def bye(): flask.abort(404) with app.test_request_context('/hi', method='POST'): assert_false(api._should_use_fr_error_handler()) assert_false(api._has_fr_route()) with app.test_request_context('/blueprint/hi', method='POST'): assert_true(api._should_use_fr_error_handler()) assert_true(api._has_fr_route()) api._should_use_fr_error_handler = Mock(return_value=False) with app.test_request_context('/bye'): assert_false(api._has_fr_route()) with app.test_request_context('/blueprint/bye'): assert_true(api._has_fr_route()) if __name__ == '__main__': unittest.main()
3,455
344
#ifndef QPBO_LazyElim_h_ #define QPBO_LazyElim_h_ // Solves a Quadratic Pseudo Boolean Optimization problem defined over a // four-connect lattice using the LazyElimination algorithm. #include "QPBO_Generic.h" class LazyElimQPBO : public GenericQPBO { public: // See QPBO_Generic.h for details about these parameters. LazyElimQPBO( const Matrix< float >& A, const Matrix< float >& B_right, const Matrix< float >& B_down, Matrix< unsigned char >& X_star ); }; #endif // QPBO_LazyElim_h_
259
8,772
<filename>api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/mfa/gauth/DynamoDbGoogleAuthenticatorMultifactorProperties.java package org.apereo.cas.configuration.model.support.mfa.gauth; import org.apereo.cas.configuration.model.support.dynamodb.AbstractDynamoDbProperties; import org.apereo.cas.configuration.support.RequiresModule; import com.fasterxml.jackson.annotation.JsonFilter; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; /** * This is {@link DynamoDbGoogleAuthenticatorMultifactorProperties}. * * @author <NAME> * @since 6.5.0 */ @Getter @Setter @RequiresModule(name = "cas-server-support-gauth-dynamodb") @Accessors(chain = true) @JsonFilter("DynamoDbGoogleAuthenticatorMultifactorProperties") public class DynamoDbGoogleAuthenticatorMultifactorProperties extends AbstractDynamoDbProperties { private static final long serialVersionUID = -1161683393319585262L; /** * The table name used and created by CAS to hold accounts in DynamoDb. */ private String tableName = "DynamoDbGoogleAuthenticatorRepository"; /** * The table name used and created by CAS to hold tokens in DynamoDb. */ private String tokenTableName = "DynamoDbGoogleAuthenticatorTokenRepository"; }
432
1,338
<reponame>Kirishikesan/haiku // **************************************************************************** // // CEchoGalsVmixer.cpp // // CEchoGalsVmixer is used to add virtual output mixing to the base // CEchoGals class. // // Set editor tabs to 3 for your viewing pleasure. // // ---------------------------------------------------------------------------- // // This file is part of Echo Digital Audio's generic driver library. // Copyright Echo Digital Audio Corporation (c) 1998 - 2005 // All rights reserved // www.echoaudio.com // // This 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. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // **************************************************************************** #include "CEchoGalsVmixer.h" //**************************************************************************** // // Constructor and destructor // //**************************************************************************** CEchoGalsVmixer::CEchoGalsVmixer( PCOsSupport pOsSupport ) : CEchoGals( pOsSupport ) { ECHO_DEBUGPRINTF( ( "CEchoGalsVmixer::CEchoGalsVmixer() is born!\n" ) ); } // CEchoGalsVmixer::CEchoGalsVmixer() CEchoGalsVmixer::~CEchoGalsVmixer() { ECHO_DEBUGPRINTF( ( "CEchoGalsVmixer::~CEchoGalsVmixer() is toast!\n" ) ); } // CEchoGalsVmixer::~CEchoGalsVmixer() //**************************************************************************** // // Vmixer // //**************************************************************************** //=========================================================================== // // Most of the cards don't have an actual output bus gain; they only // have gain controls for output pipes; the output bus gain is implemented // as a logical control. Vmixer cards work fifferently; it does have // a physical output bus gain control, so just pass the gain down to the // DSP comm object. // //=========================================================================== ECHOSTATUS CEchoGalsVmixer::AdjustPipesOutForBusOut(WORD wBusOut,INT32 iBusOutGain) { WORD wPipe; ECHO_DEBUGPRINTF(("CEchoGalsVmixer::AdjustPipesOutForBusOut wBusOut %d iBusOutGain %ld\n", wBusOut, iBusOutGain)); wBusOut &= 0xfffe; for (wPipe = 1; wPipe < GetNumPipesOut(); wPipe++) { m_PipeOutCtrl.SetGain( wPipe, wBusOut, ECHOGAIN_UPDATE, FALSE); } m_PipeOutCtrl.SetGain( 0, wBusOut, ECHOGAIN_UPDATE, TRUE); return ECHOSTATUS_OK; } // AdjustPipesOutForBusOut //=========================================================================== // // GetBaseCapabilities is used by the CEchoGals-derived classes to // help fill out the ECHOGALS_CAPS struct. Override this here to add // the vmixer stuff. // //=========================================================================== ECHOSTATUS CEchoGalsVmixer::GetBaseCapabilities ( PECHOGALS_CAPS pCapabilities ) { DWORD i; ECHOSTATUS Status; // // Base class // Status = CEchoGals::GetBaseCapabilities(pCapabilities); // // Add meters & pans to output pipes // for (i = 0 ; i < GetNumPipesOut(); i++) { pCapabilities->dwPipeOutCaps[i] |= ECHOCAPS_PEAK_METER | ECHOCAPS_PAN; } return Status; } // GetBaseCapabilities //=========================================================================== // // Adjust all the monitor levels for a particular output bus // // For vmixer cards, need to force the "update monitors" command // for the DSP 'cos it doesn't get sent otherwise. // //=========================================================================== ECHOSTATUS CEchoGalsVmixer::AdjustMonitorsForBusOut(WORD wBusOut) { ECHOSTATUS Status; // // Call the base class // Status = CEchoGals::AdjustMonitorsForBusOut( wBusOut ); if (ECHOSTATUS_OK == Status) { GetDspCommObject()->UpdateAudioOutLineLevel(); } return Status; } // AdjustMonitorsForBusOut // *** CEchoGalsVmixer.cpp ***
1,358
1,305
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang; /** * Signals that a method has been invoked at an illegal or * inappropriate time. In other words, the Java environment or * Java application is not in an appropriate state for the requested * operation. * * @author <NAME> * @since JDK1.1 */ public class IllegalStateException extends RuntimeException { /** * Constructs an IllegalStateException with no detail message. * A detail message is a String that describes this particular exception. */ public IllegalStateException() { super(); } /** * Constructs an IllegalStateException with the specified detail * message. A detail message is a String that describes this particular * exception. * * @param s the String that contains a detailed message */ public IllegalStateException(String s) { super(s); } /** * Constructs a new exception with the specified detail message and * cause. * * <p>Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this exception's detail * message. * * @param message the detail message (which is saved for later retrieval * by the {@link Throwable#getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link Throwable#getCause()} method). (A <tt>null</tt> value * is permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.5 */ public IllegalStateException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail * message of <tt>(cause==null ? null : cause.toString())</tt> (which * typically contains the class and detail message of <tt>cause</tt>). * This constructor is useful for exceptions that are little more than * wrappers for other throwables (for example, {@link * java.security.PrivilegedActionException}). * * @param cause the cause (which is saved for later retrieval by the * {@link Throwable#getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.5 */ public IllegalStateException(Throwable cause) { super(cause); } static final long serialVersionUID = -1848914673093119416L; }
950
12,278
<gh_stars>1000+ // Copyright (C) 2016-2018 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[ tarray #include <boost/yap/algorithm.hpp> #include <boost/yap/print.hpp> #include <array> #include <iostream> template <boost::yap::expr_kind Kind, typename Tuple> struct tarray_expr; struct take_nth { boost::yap::terminal<tarray_expr, int> operator() (boost::yap::terminal<tarray_expr, std::array<int, 3>> const & expr); std::size_t n; }; // Another custom expression template. In this case, we static_assert() that // it only gets instantiated with terminals with pre-approved value types. template <boost::yap::expr_kind Kind, typename Tuple> struct tarray_expr { // Make sure that, if this expression is a terminal, its value is one we // want to support. Note that the presence of expr_kind::expr_ref makes // life slightly more difficult; we have to account for int const & and // int & as well as int. static_assert( Kind != boost::yap::expr_kind::terminal || std::is_same<Tuple, boost::hana::tuple<int const &>>{} || std::is_same<Tuple, boost::hana::tuple<int &>>{} || std::is_same<Tuple, boost::hana::tuple<int>>{} || std::is_same<Tuple, boost::hana::tuple<std::array<int, 3>>>{}, "tarray_expr instantiated with an unsupported terminal type." ); static const boost::yap::expr_kind kind = Kind; Tuple elements; int operator[] (std::size_t n) const { return boost::yap::evaluate(boost::yap::transform(*this, take_nth{n})); } }; // Define operators +, -, *, and /. BOOST_YAP_USER_BINARY_OPERATOR(plus, tarray_expr, tarray_expr) BOOST_YAP_USER_BINARY_OPERATOR(minus, tarray_expr, tarray_expr) BOOST_YAP_USER_BINARY_OPERATOR(multiplies, tarray_expr, tarray_expr) BOOST_YAP_USER_BINARY_OPERATOR(divides, tarray_expr, tarray_expr) boost::yap::terminal<tarray_expr, int> take_nth::operator() (boost::yap::terminal<tarray_expr, std::array<int, 3>> const & expr) { int x = boost::yap::value(expr)[n]; // Again, this is the move hack to get x into the resulting terminal as a // value instead of a reference. return boost::yap::make_terminal<tarray_expr>(std::move(x)); } // Stream-out operators for the two kinds of terminals we support. std::ostream & operator<< (std::ostream & os, boost::yap::terminal<tarray_expr, int> expr) { return os << '{' << boost::yap::value(expr) << '}'; } std::ostream & operator<< (std::ostream & os, boost::yap::terminal<tarray_expr, std::array<int, 3>> expr) { std::array<int, 3> const & a = boost::yap::value(expr); return os << '{' << a[0] << ", " << a[1] << ", " << a[2] << '}'; } // Stream-out operators for general expressions. Note that we have to treat // the reference case separately; this also could have been done using // constexpr if in a single function template. template <typename Tuple> std::ostream & operator<< (std::ostream & os, tarray_expr<boost::yap::expr_kind::expr_ref, Tuple> const & expr) { return os << boost::yap::deref(expr); } template <boost::yap::expr_kind Kind, typename Tuple> std::ostream & operator<< (std::ostream & os, tarray_expr<Kind, Tuple> const & expr) { if (Kind == boost::yap::expr_kind::plus || Kind == boost::yap::expr_kind::minus) os << '('; os << boost::yap::left(expr) << " " << op_string(Kind) << " " << boost::yap::right(expr); if (Kind == boost::yap::expr_kind::plus || Kind == boost::yap::expr_kind::minus) os << ')'; return os; } // Since we want different behavior on terminals than on other kinds of // expressions, we create a custom type that does so. struct tarray : tarray_expr< boost::yap::expr_kind::terminal, boost::hana::tuple<std::array<int, 3>> > { explicit tarray (int i = 0, int j = 0, int k = 0) { (*this)[0] = i; (*this)[1] = j; (*this)[2] = k; } explicit tarray (std::array<int, 3> a) { (*this)[0] = a[0]; (*this)[1] = a[1]; (*this)[2] = a[2]; } int & operator[] (std::ptrdiff_t i) { return boost::yap::value(*this)[i]; } int const & operator[] (std::ptrdiff_t i) const { return boost::yap::value(*this)[i]; } template <typename T> tarray & operator= (T const & t) { // We use as_expr() here to make sure that the value passed to // assign() is an expression. as_expr() simply forwards expressions // through, and wraps non-expressions as terminals. return assign(boost::yap::as_expr< ::tarray_expr>(t)); } template <typename Expr> tarray & printAssign (Expr const & expr) { *this = expr; std::cout << *this << " = " << expr << std::endl; return *this; } private: template <typename Expr> tarray & assign (Expr const & expr) { (*this)[0] = expr[0]; (*this)[1] = expr[1]; (*this)[2] = expr[2]; return *this; } }; int main() { tarray a(3,1,2); tarray b; std::cout << a << std::endl; std::cout << b << std::endl; b[0] = 7; b[1] = 33; b[2] = -99; tarray c(a); std::cout << c << std::endl; a = 0; std::cout << a << std::endl; std::cout << b << std::endl; std::cout << c << std::endl; a = b + c; std::cout << a << std::endl; a.printAssign(b+c*(b + 3*c)); return 0; } //]
2,246
348
{"nom":"Chézery-Forens","circ":"3ème circonscription","dpt":"Ain","inscrits":331,"abs":201,"votants":130,"blancs":15,"nuls":5,"exp":110,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":55},{"nuance":"LR","nom":"Mme <NAME>","voix":55}]}
96
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.models; import com.azure.resourcemanager.security.fluent.models.RulesResultsInner; import java.util.List; /** An immutable client-side representation of RulesResults. */ public interface RulesResults { /** * Gets the value property: List of rule results. * * @return the value value. */ List<RuleResults> value(); /** * Gets the inner com.azure.resourcemanager.security.fluent.models.RulesResultsInner object. * * @return the inner object. */ RulesResultsInner innerModel(); }
229
1,132
#include "gb-include.h" #include "Url.h" #include "Domains.h" #include "Errno.h" #include "HashTable.h" #include "Speller.h" #include "Punycode.h" #include "Unicode.h" static void print_string ( char *s , int32_t len ); void Url::reset() { m_scheme = NULL; m_host = NULL; m_path = NULL; m_filename = NULL; m_extension = NULL; m_query = NULL; m_domain = NULL; m_tld = NULL; m_anchor = NULL; //m_site = NULL; m_url[0] = '\0'; m_ulen = 0; m_dlen = 0; m_slen = 0; m_qlen = 0; m_hlen = 0; m_elen = 0; m_mdlen = 0; m_anchorLen = 0; //m_siteLen = 0; // ip related stuff m_ip = 0; // m_isWarcValid = false; // m_isArcValid = false; } // set from another Url, does a copy void Url::set ( Url *url , bool addWWW ) { if ( ! url ) { reset(); return; } set ( url->getUrl() , url->getUrlLen() , addWWW ); } void Url::set (Url *baseUrl,char *s,int32_t len,bool addWWW,bool stripSessionId, bool stripPound , bool stripCommonFile, int32_t titleRecVersion ) { reset(); // debug msg //if ( addWWW ) // log("Url::set: warning, forcing WWW\n"); if ( ! baseUrl ) { set ( s , len , addWWW ); return; } char *base = (char *) baseUrl->m_url; int32_t blen = baseUrl->m_ulen; // don't include cgi crap if ( baseUrl->m_query ) blen -= (baseUrl->m_qlen + 1); // . adjust length of the base url. // . if base url does not end in / then it must have a m_filename at // the end, therefore we should strip the m_filename if ( blen > 0 && base[blen-1] != '/' ) while (blen > 0 && base[blen-1] != '/') blen--; // . fix baseurl = "http://xyz.com/poo/all" and s = "?page=3" // . if "s" starts with ? then keep the filename in the base url if ( s[0] == '?' ) { for ( ; base[blen] && base[blen]!='?'; blen++ ); } if ( blen==0 && len==0 ) return; // skip s over spaces char *send = s + len; while ( s < send && is_wspace_a ( *s ) ) { s++; len--; } // . is s a relative url? search for ://, but break at first / // . but break at any non-alnum or non-hyphen bool isAbsolute = false; int32_t i; for ( i = 0; i < len && (is_alnum_a(s[i]) || s[i]=='-') ; i++ ); //for ( i = 0 ; s[i] && (is_alnum_a(s[i]) || s[i]=='-') ; i++ ); if ( ! isAbsolute ) isAbsolute = ( i + 2 < len && s[i+0]==':' && s[i+1]=='/' ); // some are missing both /'s! //s[i+2]=='/' ) ; if ( ! isAbsolute ) isAbsolute = ( i + 2 < len && s[i+0]==':' && s[i+1]=='\\' ); // or if s starts with // then it's also considered absolute! if ( ! isAbsolute && len > 1 && s[0]=='/' && s[1]=='/' ) isAbsolute = true; // watch out for idiots if ( ! isAbsolute && len > 1 && s[0]=='\\' && s[1]=='\\' ) isAbsolute = true; // debug msg //log("base=%s, abs=%i, slen=%i, s=%s, i=%i\n", // base,isAbsolute,len,s,i); // don't use base if s is not relative if ( blen==0 || isAbsolute ) { set(s,len,addWWW,stripSessionId,stripPound, false, // stripCommonFile? titleRecVersion); return; } // . if s starts with / then hack of base's m_path // . careful not to hack of the port, if any // . blen = baseUrl->m_slen + 3 + baseUrl->m_hlen; if ( len > 0 && s[0]=='/' ) blen = baseUrl->m_path - baseUrl->m_url ; char temp[MAX_URL_LEN*2+1]; strncpy(temp,base,blen); if (len>MAX_URL_LEN) len = MAX_URL_LEN-2; // if s does NOT start with a '/' then add one here in case baseUrl // does NOT end in one. // fix baseurl = "http://xyz.com/poo/all" and s = "?page=3" if ( len > 0 && s[0] != '/' && s[0] !='?' && temp[blen-1] != '/' ) temp[blen++] ='/'; strncpy(temp+blen,s,len); set ( temp, blen+len , addWWW , stripSessionId , stripPound , stripCommonFile , titleRecVersion ); } // . url rfc = http://www.blooberry.com/indexdot/html/topics/urlencoding.htm // . "...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," // [not including the quotes - ed], and reserved characters used for their // reserved purposes may be used unencoded within a URL." // . i know sun.com has urls like "http://sun.com/;$sessionid=123ABC$" // . url should be ENCODED PROPERLY for this to work properly void Url::set ( char *t , int32_t tlen , bool addWWW , bool stripSessionId , bool stripPound , bool stripCommonFile , int32_t titleRecVersion ) { reset(); // debug //t = "http://www.ac.uk/../../news/.asp"; //tlen = gbstrlen(t); if ( ! t || tlen == 0 ) return ; // we may add a "www." a trailing backslash and \0, ... if ( tlen > MAX_URL_LEN - 10 ) { log( LOG_LIMIT,"db: Encountered url of length %"INT32". " "Truncating to %i" , tlen , MAX_URL_LEN - 10 ); tlen = MAX_URL_LEN - 10; } // . skip over non-alnum chars (except - or /) in the beginning // . if url begins with // then it's just missing the http: (slashdot) // . watch out for hostname like: -dark-.deviantart.com(yes, it's real) // . so all protocols are hostnames MUST start with alnum OR hyphen while ( tlen > 0 && !is_alnum_a(*t) && *t!='-' && *t!='/'){t++;tlen--;} // . stop t at first space or binary char // . url should be in encoded form! int32_t i = 0; int32_t nonAsciiPos = -1; for ( i = 0 ; i < tlen ; i++ ) { if ( is_wspace_a(t[i]) ) break; // no spaces allowed if ( ! is_ascii(t[i]) ) { // Sometimes the length with the null is passed in, // so ignore nulls FIXME? if( t[i] ) nonAsciiPos = i; break; // no non-ascii chars allowed } } if(nonAsciiPos != -1) { // Try turning utf8 and latin1 encodings into punycode. // All labels(between dots) in the domain are encoded // separately. We don't support encoded tlds, but they are // not widespread yet. // If it is a non ascii domain it needs to take the form // xn--<punycoded label>.xn--<punycoded label>.../ char tmp = t[tlen]; if(t[tlen]) t[tlen] = 0; log(LOG_DEBUG, "build: attempting to decode unicode url %s pos at %"INT32, t, nonAsciiPos); if(tmp) t[tlen] = tmp; char encoded [ MAX_URL_LEN ]; size_t encodedLen = MAX_URL_LEN; char *encodedDomStart = encoded; char *p = t; char *pend = t+tlen; // Find the start of the domain if(tlen > 7 && strncmp(p, "http://", 7) == 0) p += 7; else if(tlen > 8 && strncmp(p, "https://", 8) == 0) p += 8; gbmemcpy(encodedDomStart, t, p-t); encodedDomStart += p-t; while(p < pend && *p != '/') { char *labelStart = p; uint32_t tmpBuf[MAX_URL_LEN]; int32_t tmpLen = 0; while(p < pend && *p != '.' && *p != '/') p++; int32_t labelLen = p - labelStart; bool tryLatin1 = false; // For utf8 urls p = labelStart; bool labelIsAscii = true; // Convert the domain to code points and copy it to // tmpbuf to be punycoded for(;p-labelStart<labelLen; p += utf8Size(tmpBuf[tmpLen]), tmpLen++) { labelIsAscii &= is_ascii(*p); tmpBuf[tmpLen] = utf8Decode(p); if(!tmpBuf[tmpLen]) { // invalid char? tryLatin1 = true; break; } } if(labelIsAscii) { if(labelStart[labelLen] == '.') { labelLen++; p++; } gbmemcpy(encodedDomStart, labelStart, labelLen); encodedDomStart += labelLen; continue; } if( tryLatin1 ) { // For latin1 urls tmpLen = 0; for(;tmpLen<labelLen;tmpLen++) { tmpBuf[tmpLen] = labelStart[tmpLen]; } } gbmemcpy(encodedDomStart, "xn--", 4); encodedDomStart += 4; punycode_status status ; status = punycode_encode(tmpLen, tmpBuf, NULL, &encodedLen, encodedDomStart); if ( status != 0 ) { // Give up? try again? log("build: Bad Engineer, failed to " "punycode international url %s", t); return; } // We should check if what we encoded were valid url // characters, no spaces, etc // FIXME: should we exclude just the bad chars? I've // seen plenty of urls with // a newline in the middle. Just discard the whole // chunk for now bool badUrlChars = false; for(uint32_t i=0;i<encodedLen;i++) { if(is_wspace_a(encodedDomStart[i])){ badUrlChars = true; break; } } if(encodedLen == 0 || badUrlChars) { encodedDomStart -= 4; //don't need the xn-- p++; } else { encodedDomStart += encodedLen; *encodedDomStart++ = *p++; // Copy in the . or the / } } // p now points to the end of the domain // encodedDomStart now points to the first free space in encoded string // Now copy the rest of the url in. Watch out for non-ascii chars // truncate the url, and keep it under max url length uint32_t newUrlLen = encodedDomStart - encoded; while(p < pend) { if ( ! *p ) break; // null? if(!is_ascii(*p)) { //break; // url encode utf8 characters now char cs = getUtf8CharSize(p); // bad utf8 char? if ( cs <= 1 ) break; // too long? if ( newUrlLen + 12 >= MAX_URL_LEN ) break; char stored = urlEncode ( &encoded[newUrlLen], 12 , p , cs ); p += cs; newUrlLen += stored; continue; } if(is_wspace_a(*p)) break; if(newUrlLen >= MAX_URL_LEN) break; encoded[newUrlLen++] = *p++; } //gbmemcpy(encodedDomStart, p, restOfUrlLen); encoded[newUrlLen] = '\0'; return this->set(encoded, newUrlLen, addWWW, stripSessionId, stripPound, stripCommonFile, titleRecVersion); } // truncate length to the first occurrence of an unacceptable char tlen = i; // . decode characters that should not have been encoded // . also NULL terminates //char tmp[MAX_URL_LEN]; //int32_t tmpLen; //tmpLen = safeDecode ( t , tlen , tmp ); // . jump over http:// if it starts with http://http:// // . a common mistake... while ( tlen > 14 && ! strncasecmp ( t , "http://http://" , 14 ) ) { t += 7; tlen -= 7; } //if ( tlen > 26 ) //while ( ! strncasecmp ( t , "http%3A%2F%2Fhttp%3A%2F%2F",26)){ //t += 13; tlen -= 13; } // strip the "#anchor" from http://www.xyz.com/somepage.html#anchor" int32_t anchorPos = 0; int32_t anchorLen = 0; for ( int32_t i = 0 ; i < tlen ; i++ ) { if ( t[i] != '#' ) continue; // ignore anchor if a ! follows it. 'google hash bang hack' // which breaks the web and is now deprecated, but, there it is if ( i+1<tlen && t[i+1] == '!' ) continue; anchorPos = i; anchorLen = tlen - i; if ( stripPound ) tlen = i; break; } // copy to "s" so we can NULL terminate it char s [ MAX_URL_LEN ]; int32_t len = tlen; // store filtered url into s gbmemcpy ( s , t , tlen ); s[len]='\0'; // make http:////www.xyz.com into http://www.xyz.com // if ( len > 14 && s[7]=='/' && ! strncasecmp ( s , "http:////" ,9) ){ // gbmemcpy (s+7,s+9,len-9+1); // len -= 2; // } // if ( len > 14 && s[8]=='/' && ! strncasecmp ( s ,"https:////",10)){ // gbmemcpy (s+8,s+10,len-9+1); // len -= 2; // } // . remove session ids from s // . ';' most likely preceeds a session id // . http://www.b.com/p.jhtml;jsessionid=J4QMFWBG1SPRVWCKUUXCJ0W?pp=1 // . http://www.b.com/generic.html;$sessionid$QVBMODQAAAGNA?pid=7 // . http://www.b.com/?PHPSESSID=737aec14eb7b360983d4fe39395&p=1 // . http://www.b.com/cat.cgi/process?mv_session_id=xrf2EY3q&p=1 // . http://www.b.com/default?SID=f320a739cdecb4c3edef67e&p=1 if ( stripSessionId ) { // CHECK FOR A SESSION ID USING SEMICOLONS // or don't...bad for dmoz urls and apparently has ligit use // int32_t i = 0; // while ( s[i] && s[i]!=';' ) i++; // // did we get a semi colon? // if ( s[i] == ';' ) { // // i is start of it // int32_t a = i; // // find the end of the session id // int32_t b = i + 1; // while ( s[b] && s[b] != '?' ) b++; // // remove the session id by covering it up // memmove ( &s[a] , &s[b] , len - b ); // // reduce length // len -= (b-a); // // NULL terminate // s[len] = '\0'; // } // CHECK FOR A SESSION ID USING QUERY STRINGS char *p = s; while ( *p && *p != '?' && *p != ';' ) p++; // bail if no ? if ( ! *p ) goto skip; // now search for several strings in the cgi query string char *tt = NULL; int32_t x; if ( ! tt ) { tt = gb_strcasestr ( p , "PHPSESSID=" ); x = 10;} if ( ! tt ) { tt = strstr ( p , "SID=" ); x = 4;} // . osCsid and XTCsid are new session ids // . keep this up here so "sid=" doesn't override it if ( ! tt && titleRecVersion >= 59 ) { tt = strstr ( p , "osCsid=" ); x = 7; if ( ! tt ) tt = strstr ( p , "XTCsid=" ); // a hex sequence of at least 10 digits must follow if ( tt && ! isSessionId ( tt + x, titleRecVersion ) ) tt = NULL; } if ( ! tt && titleRecVersion >= 59 ) { tt = strstr ( p , "osCsid/" ); x = 7; // a hex sequence of at least 10 digits must follow if ( tt && ! isSessionId ( tt + x, titleRecVersion ) ) tt = NULL; } // this is a new session id thing if ( ! tt && titleRecVersion >= 54 ) { tt = strstr ( p , "sid=" ); x = 4; // a hex sequence of at least 10 digits must follow if ( tt && ! isSessionId ( tt + x, titleRecVersion ) ) tt = NULL; } // osCsid and XTCsid are new session ids if ( ! tt && titleRecVersion >= 57 ) { tt = strstr ( p , "osCsid=" ); x = 7; if ( ! tt ) tt = strstr ( p , "XTCsid=" ); // a hex sequence of at least 10 digits must follow if ( tt && ! isSessionId ( tt + x, titleRecVersion ) ) tt = NULL; } // fixes for bug of matching plain &sessionid= first and // then realizing char before is an alnum... if ( ! tt && titleRecVersion >= 59 ) { tt = gb_strcasestr ( p, "jsessionid="); x = 11; } if ( ! tt && titleRecVersion >= 59 ) { tt = gb_strcasestr ( p , "vbsessid=" ); x = 9;} if ( ! tt && titleRecVersion >= 59 ) { tt = gb_strcasestr ( p, "asesessid=" ); x = 10; } if ( ! tt && titleRecVersion >= 59 ) { tt = gb_strcasestr ( p, "nlsessid=" ); x = 9; } if ( ! tt && titleRecVersion >= 59 ) { tt = gb_strcasestr ( p, "psession=" ); x = 9; } if ( ! tt ) { tt = gb_strcasestr ( p , "session_id="); x = 11;} if ( ! tt ) { tt = gb_strcasestr ( p , "sessionid=" ); x = 10;} if ( ! tt ) { tt = gb_strcasestr ( p , "sessid=" ); x = 7;} if ( ! tt ) { tt = gb_strcasestr ( p , "vbsessid=" ); x = 9;} if ( ! tt ) { tt = gb_strcasestr ( p , "session=" ); x = 8;} if ( ! tt ) { tt = gb_strcasestr ( p , "session/" ); x = 8;} if ( ! tt ) { tt = gb_strcasestr ( p , "POSTNUKESID=");x = 12;} // some new session ids as of Feb 2005 if ( ! tt ) { tt = gb_strcasestr ( p, "auth_sess=" ); x = 10; } if ( ! tt ) { tt = gb_strcasestr ( p, "mysid=" ); x = 6; } if ( ! tt ) { tt = gb_strcasestr ( p, "oscsid=" ); x = 7; } if ( ! tt ) { tt = gb_strcasestr ( p, "cg_sess=" ); x = 8; } if ( ! tt ) { tt = gb_strcasestr ( p, "galileoSession");x=14; } if ( ! tt ) { tt = gb_strcasestr ( p, "asesessid=" ); x = 10; } if ( ! tt ) { tt = gb_strcasestr ( p, "nlsessid=" ); x = 9; } if ( ! tt ) { tt = gb_strcasestr ( p, "jsessionid="); x = 11; } if ( ! tt ) { tt = gb_strcasestr ( p, "psession=" ); x = 9; } // new as of Jan 2006. is hurting news5 collection on gb6 if ( ! tt ) { tt = gb_strcasestr ( p, "sess=" ); x = 5; } // .php?s=8af9d6d0d59e8a3108f3bf3f64166f5a& // .php?s=eae5808588c0708d428784a483083734& // .php?s=6256dbb2912e517e5952caccdbc534f3& if ( ! tt && (tt = strstr ( p-4 , ".php?s=" )) ) { // point to the value of the s= char *pp = tt + 7; int32_t i = 0; // ensure we got 32 hexadecimal chars while ( pp[i] && ( is_digit(pp[i]) || ( pp[i]>='a' && pp[i]<='f' ) ) ) i++; // if not, do not consider it a session id if ( i < 32 ) tt = NULL; // point to s= for removal else { tt += 5; x = 2; } } // bail if none were found if ( ! tt ) goto skip; // . must not have an alpha char before it! // . prevent "DAVESID=" from being labeled as session id if ( is_alnum_a ( *(tt-1) ) ) goto skip; // start of the shit int32_t a = tt - s; // get the end of the shit int32_t b = a + x; // back up until we hit a ? or & or / or ; while ( a > 0 && s[a-1] != '?' && s[a-1] != '&' && s[a-1] != '/' && s[a-1] != ';' ) a--; // keep the '?' if ( s[a]=='?' ) a++; // back up over any semicolon if ( s[a-1] == ';' && titleRecVersion >= 59 ) a--; // advance b until we hit & or end or ? or a ';' while ( s[b] && s[b] != '&' && s[b] != '?' && s[b] != ';') b++; // if we don't have 5+ chars in session id itself, skip it if ( b - (a + x) < 5 ) goto skip; // go over a & or a ; if ( s[b] == '&' || s[b] == ';' ) b++; // remove the session id by covering it up memmove ( &s[a] , &s[b] , len - b ); // reduce length len -= (b-a); // if s ends in ? or & or ;, backup while ( len > 0 && (s[len-1]=='?'||s[len-1]=='&'||s[len-1]==';')) len--; // NULL terminate s[len] = '\0'; } skip: // remove common filenames like index.html if ( stripCommonFile ) { if ( len - 14 > 0 && strncasecmp(&s[len-14], "/default.xhtml", 14) == 0 ) len -= 13; else if ( len - 13 > 0 && ( strncasecmp(&s[len-13], "/default.html", 13) == 0 || strncasecmp(&s[len-13], "/default.ascx", 13) == 0 || strncasecmp(&s[len-13], "/default.ashx", 13) == 0 || strncasecmp(&s[len-13], "/default.asmx", 13) == 0 || strncasecmp(&s[len-13], "/default.xhtm", 13) == 0 || strncasecmp(&s[len-13], "/default.aspx", 13) == 0 ) ) len -= 12; else if ( len - 12 > 0 && ( strncasecmp(&s[len-12], "/default.htm", 12) == 0 || strncasecmp(&s[len-12], "/default.php", 12) == 0 || strncasecmp(&s[len-12], "/default.asp", 12) == 0 || strncasecmp(&s[len-12], "/index.xhtml", 12) == 0 ) ) len -= 11; else if ( len - 11 > 0 && ( strncasecmp(&s[len-11], "/index.html", 11) == 0 || strncasecmp(&s[len-11], "/index.aspx", 11) == 0 || strncasecmp(&s[len-11], "/index.xhtm", 11) == 0 || strncasecmp(&s[len-11], "/default.pl", 11) == 0 || strncasecmp(&s[len-11], "/default.cs", 11) == 0 ) ) len -= 10; else if ( len - 10 > 0 && ( strncasecmp(&s[len-10], "/index.htm", 10) == 0 || strncasecmp(&s[len-10], "/index.php", 10) == 0 || strncasecmp(&s[len-10], "/index.asp", 10) == 0 || strncasecmp(&s[len-10], "/main.html", 10) == 0 || strncasecmp(&s[len-10], "/main.aspx", 10) == 0 ) ) len -= 9; else if ( len - 9 > 0 && ( strncasecmp(&s[len-9], "/index.pl", 9) == 0 || strncasecmp(&s[len-9], "/main.htm", 9) == 0 || strncasecmp(&s[len-9], "/main.php", 9) == 0 ) ) len -= 8; else if ( len - 8 > 0 && ( strncasecmp(&s[len-8], "/main.pl", 8) == 0 ) ) len -= 7; s[len] = '\0'; } // replace the "\" with "/" -- a common mistake int32_t j; for ( j = 0 ; s[j] ; j++) if (s[j]=='\\') s[j]='/'; // . dig out the protocol/scheme for this s (check for ://) // . protocol may only have alnums and hyphens in it for ( i = 0 ; s[i] && (is_alnum_a(s[i]) || s[i]=='-') ; i++ ); // if we have a legal protocol, then set "m_scheme", "slen" and "sch" // and advance i to the m_host if ( i + 2 < len && s[i]==':' && s[i+1]=='/' && s[i+2]=='/') { // copy lowercase protocol to "m_url" to_lower3_a ( s , i + 3 , m_url ); m_scheme = m_url; m_slen = i; m_ulen = i + 3; i += 3; } else if (i + 2 < len && s[i]==':' && s[i+1]=='/'&& is_alnum_a(s[i+2])){ // copy lowercase protocol to "m_url" to_lower3_a ( s , i + 2 , m_url ); // add in needed / m_url[i+2]='/'; m_scheme = m_url; m_slen = i; m_ulen = i + 3; i += 2; } // callto:+441202300007 (skype links) // mailto:<EMAIL> /* else if ( i+1 < len && s[i]==':' && version >= 62 ) { // copy lowercase protocol to "m_url" to_lower3_a ( s , i + 1 , m_url ); // add in needed / m_url[i+2]='/'; m_scheme = m_url; m_slen = i; m_ulen = i + 3; i += 2; } */ // otherwise we had no syntactically correct protocol else { gbmemcpy ( m_url,"http://" , 7 ); m_scheme = m_url; m_slen = 4; m_ulen = 7; i = 0; // if s started with // then skip that (slashdot) if ( s[0]=='/' && s[1]=='/' ) i = 2; } // . now &s[i] should point to the m_host name // . chars allowed in hostname = period,alnum,hyphen,underscore // . stops at '/' or ':' or any other disallowed character j = i; while (s[j] && (is_alnum_a(s[j]) || s[j]=='.' || s[j]=='-'||s[j]=='_')) j++; // copy m_host into "s" (make it lower case, too) to_lower3_a ( s + i, j - i, m_url + m_ulen ); m_host = m_url + m_ulen; m_hlen = j - i; // common mistake: if hostname ends in a . then back up while ( m_hlen > 0 && m_host[m_hlen-1]=='.' ) m_hlen--; // NULL terminate for strchr() m_host [ m_hlen ] = '\0'; // . common mistake: if hostname has no '.' in it append a ".com" // . now that we use hosts in /etc/hosts we no longer do this //if ( m_hlen > 0 && strchr ( m_host ,'.' ) == NULL ) { // gbmemcpy ( &m_host[m_hlen] , ".com" , 4 ); // m_hlen += 4; //} // advance m_ulen to end of hostname m_ulen += m_hlen; // . set our m_ip if hostname is in a.b.c.d format // . this returns 0 if not a valid ip string m_ip = atoip ( m_host , m_hlen ); // advance i to the : for the port, if it exists i = j; // NULL terminate m_host for getTLD(), getDomain() and strchr() below m_host [ m_hlen ] = '\0'; // use ip as domain if we're just an ip address like 172.16.31.10 if ( m_ip ) { // ip address has no tld, or mid domain m_tld = NULL; m_tldLen = 0; // but it does have a domain (1.2.3) m_domain = getDomainOfIp ( m_host , m_hlen , &m_dlen ); // just use the domain as the mid domain for ip-based urls m_mdlen = m_dlen; } // . otherwise, get the tld // . uses thorough list of tlds in Domains.cpp else if ( ( m_tld = ::getTLD ( m_host, m_hlen ) ) && m_tld > m_host ) { // set m_domain if we had a tld that's not equal to our host m_tldLen = gbstrlen ( m_tld ); m_domain = ::getDomain ( m_host , m_hlen , m_tld , &m_dlen ); // set the mid domain length (-1 for the '.') m_mdlen = m_dlen - m_tldLen - 1; } // otherwise, we're no ip and we have no valid domain else { m_domain = NULL; m_dlen = 0; m_tldLen = 0; m_mdlen = 0; } // . if domain same as host then we might insert a "www." server name // . however, must have a period in domain name // . otherwise a domain name of "xxx" would become "www.xxx" and if // Url::set() is called on that it would be "www.www.xxx" (bad bad) // . let's only add "www." if there's only 1 period, ok? if ( ! m_ip && addWWW && m_host == m_domain && strchr(m_host,'.') ) { memmove ( m_host + 4 , m_host , m_hlen ); gbmemcpy ( m_host , "www." , 4 ); if ( m_domain ) m_domain += 4; if ( m_tld ) m_tld += 4; m_ulen += 4; m_hlen += 4; } // set the default port based on the protocol m_defPort = 80; if ( m_slen==5 && strncmp(m_scheme, "https",5)==0 ) m_defPort = 443; if ( m_slen==3 && strncmp(m_scheme, "ftp" ,3)==0 ) m_defPort = 21; // assume we're using the default port for this scheme/protocol m_port = m_defPort; m_portStr = NULL; // see if a port was provided in the hostname after a colon if ( s[i] == ':' ) { // remember the ptr so far int32_t savedLen = m_ulen; // add a colon to our m_url m_url [ m_ulen++ ] = ':'; // scan for a '/' j = i + 1; while ( s[j] && s[j]!='/') m_url[m_ulen++] = s[j++]; // now read our port m_portStr = s + i; // str includes ':' m_port = atol2 ( s + (i + 1) , j - (i + 1) ); // if it's the default port, then remove what we copied if ( m_port == m_defPort ) m_ulen = savedLen; // make i point to the root / in the m_path, if any i = j; } // how many chars is taken up by a specified port? m_portLen = 0; if ( m_port != m_defPort ) { m_portLen += 2; // :3 if ( m_port >= 10 ) m_portLen += 1; if ( m_port >= 100 ) m_portLen += 1; if ( m_port >= 1000 ) m_portLen += 1; if ( m_port >= 10000 ) m_portLen += 1; } //m_site = m_url; //m_siteLen = m_ulen+1; // append a '/' to m_url then bail if there is no m_path after the port if ( s[i]=='\0' || s[i] != '/') { m_path = m_url + m_ulen; m_path[0] = '/'; m_plen = 1; m_url[ ++m_ulen ]='\0'; // debug change goto done; return; } // . get the m_path and m_path length // . j,i should point to start of path slash '/' // . scan so it points to end or a ? or # j = i; // now we include # as part of the path if it is a hash bang '#!' // which was the web-breaking google hack that is now deprecated while ( s[j] && s[j]!='?' ) { if ( s[j] == '#' && s[j+1] != '!' ) break; j++; } // point the path inside m_url even though we haven't written it yet m_path = m_url + m_ulen; m_plen = m_ulen; // . deal with weird things in the path // . i points to start of path (should be /) for (; i < j ; i++ ) { // dedup double backslashes // ensure m_ulen >= m_plen so we don't hurt "http:///" ... // but people sometimes put http:// in the *path* if ( s[i] == '/' && m_url[m_ulen-1] == '/' && m_ulen-1 >= m_plen && m_ulen >= 2 && m_url[m_ulen-2] != ':' ) continue; // deal with current directories in the m_path if ( s[i] == '.' && m_url[m_ulen-1] == '/' && (i+1 == j || s[i+1]=='/')) continue; // . deal with damned ..'s in the m_path // . if next 2 chars are .'s and last char we wrote was '/' if ( s[i] == '.' && s[i+1]=='.' && m_url[m_ulen-1] == '/' ) { // dont back up over first / in path if ( m_url + m_ulen - 1 > m_path ) m_ulen--; while ( m_url[m_ulen-1] != '/' ) m_ulen--; // skip i to next / after these 2 dots while ( s[i] && s[i]!='/' ) i++; continue; } // don't allow ; before the ?...probably because of stripped // sessionId... // I was going to add other possible dup separators, but now // it seems as though it might cause problems if (titleRecVersion >= 78){ if (s[i] == ';' && s[i+1] == '?') continue; } // store char and advance to next m_url[m_ulen++] = s[i]; } // reset the path length in case we had to remove some weird stuff m_plen = m_ulen - m_plen; // . remove trailing /'s from path, but not first one! // . NO! this is WRONG! we need it so we know it's a dir name //while ( m_plen > 1 && m_path[m_plen-1]=='/' ) { m_plen--; m_ulen--; } // . get the m_query // . the query is anything after the path that starts with ? // . NOTE: we ignore strings beginning with '#' (page relative anchors) if ( i < len && s[i] != '#' ) { //gbmemcpy ( m_url + m_ulen , s + i , len - i ); //remove back to back &'s in the cgi query //http://www.nyasatimes.com/national/politics/160.html?print&&& char *kstart = s + i; char *kend = s + i + (len - i); char *dst = m_url + m_ulen; for ( char *k = kstart ; k < kend ; k++ ) { // skip & if we just did one if ( *k == '&' && k > kstart && *(k-1)=='&' ) continue; // copy over one char at a time *dst++ = *k; } // point after the '?' i guess m_query = m_url + m_ulen + 1; //m_qlen = len - i - 1; m_qlen = dst - m_query; m_ulen += m_qlen + 1; } // get the m_filename from the m_path (m_flen might be 0) m_flen = 0; while (m_path[m_plen-1-m_flen]!='/' && m_flen<m_plen) m_flen++; m_filename = m_path + m_plen - m_flen; // get the m_extension from the m_path m_elen = 0; while (is_alnum_a(m_path[m_plen-1-m_elen]) && m_elen < m_plen)m_elen++; if ( m_path[ m_plen-1-m_elen] != '.' ) m_elen = 0; // no m_extension m_extension = m_path + m_plen - m_elen; // null terminate our s m_url[ m_ulen ]='\0'; // add the anchor after m_anchor = NULL; m_anchorLen = anchorLen; if ( anchorLen > 0 && m_ulen + anchorLen + 2 < MAX_URL_LEN ) { m_anchor = &m_url[m_ulen+1]; gbmemcpy(&m_url[m_ulen+1], &t[anchorPos], anchorLen); m_url[m_ulen+1+anchorLen] = '\0'; } done: // debug msg //log("--------------%s has domain \"",s); //for (int32_t k=0;k <m_dlen; k++ ) log("%c",m_domain[k]); //log("\"\n"); // check for iterative stablization static int32_t flag = 0; if ( flag == 1 ) return; Url u2; flag = 1; // Must not use defaults! u2.set ( m_url, m_ulen , addWWW, stripSessionId , stripPound , stripCommonFile , titleRecVersion ); if ( strcmp(u2.getUrl(),m_url) != 0 ) { log(LOG_REMIND,"db: *********url %s-->%s\n",m_url,u2.getUrl()); //sleep(5000); } flag = 0; } char Url::isSessionId ( char *hh, int32_t titleRecVersion ) { int32_t count = 0; int32_t step = 0; int32_t nonNumCount = 0; // old bug didn't step through characters if (titleRecVersion >= 69) step = 1; // do not limit count to 12, the hex numbers may only be // after the 12th character! we were not identifying these // as sessionids when we shold have been because of that. for ( ; *hh ; count++, hh+=step ) { if ( *hh >= '0' && *hh <= '9' ) continue; nonNumCount++; if ( *hh >= 'a' && *hh <= 'f' ) continue; // we got an illegal session id character return false; } // if we got at least 12 of em, consider it a valid id if (titleRecVersion >= 69) // make sure it's a hexadecimal number...lots of product // ids and dates use only decimal numbers return ( nonNumCount > 0 && count >= 12); return ( count >= 12 ); } // hostname must also be www or NULL to be a root url bool Url::isRoot() { if ( m_plen != 1 ) return false; if ( !m_path || m_path[0] != '/' ) return false; if ( m_query ) return false; // for now we'll let all thos *.deviantart.com names clog us up // because i don't want to dis' stuff like espn.go.com return true; // get just the hostname w/o the domain (includes '.' following name) //int32_t nameLen = m_hlen - m_dlen ; //if ( nameLen <= 0 ) return true; //if ( nameLen != 4 ) return false; // "www." //if ( strncmp ( m_host , "www" , 3 ) != 0 ) return false; //return true; } // a super root url is a root url where the hostname is NULL or "www" bool Url::isSuperRoot () { if ( ! isRoot() ) return false; // if hostname is same as domain, it's a super root if ( m_host == m_domain && m_hlen == m_dlen ) return true; // if host is not "www." followed by domain, it's NOT a super root if ( m_hlen != m_dlen + 4 ) return false; if ( strncmp ( m_host , "www." , 4 ) == 0 ) return true; return false; } bool Url::isSimpleSubdomain ( ) { // if hostname is same as domain, it's passes if ( m_host == m_domain && m_hlen == m_dlen ) return true; // if host is not "www." followed by domain, it's NOT if ( m_hlen != m_dlen + 4 ) return false; if ( strncmp ( m_host , "www." , 4 ) == 0 ) return true; return false; } // . get length of sub-url #j // . basically like adding j /.. to the end of the url // . sub-url #0 is the full url // . includes /~ as it's own path int32_t Url::getSubUrlLen ( int32_t j ) { // assume it's the whole url int32_t len = m_ulen; // subtract the m_query (cgi) part at the end of the url if ( m_query ) len -= m_qlen + 1; //and the ? // return the full url (without m_query) if j is 0 if ( j == 0 ) return len; // . start right past the http://m_host.domain.com/ int32_t start = m_slen + 3 + m_hlen + 1 + m_portLen ; while ( len > start ) { if ( m_url [ len - 1 ] == '/' ) j--; if ( m_url [ len - 2 ] == '/' && m_url [ len - 1 ] == '~') j--; // include this backslash (or ~) in the sub-url if ( j == 0 ) return len; // shrink by one character len--; } // return 0 if jth sub-url does not exist return 0; } // . similar to getSubUrlLen() above but only works on the path // . if j is 0 that's the whole url path! int32_t Url::getSubPathLen ( int32_t j ) { int32_t subUrlLen = getSubUrlLen ( j ); if ( subUrlLen <= 0 ) return 0; // . the subPath length includes the root backslash // . portLen includes the whole :8080 thing (for non default ports) return subUrlLen - m_slen - 3 - m_hlen - m_portLen; } void Url::print() { printf("############ url ############\n"); printf("url: %s\n",m_url); printf("host: "); print_string( m_host, m_hlen ); printf("\n"); printf("scheme: "); print_string( m_scheme , m_slen ); printf("\n"); printf("path: "); print_string(m_path , m_plen ); printf("\n"); printf("query: %s\n",m_query); printf("port: %"INT32"\n", m_port ); printf("domain: "); print_string(m_domain, m_dlen ); printf("tld: "); print_string(m_tld, m_tldLen ); printf("mid domain: "); print_string(m_domain, m_mdlen ); printf("\n"); printf("is root %i\n",isRoot()); } void print_string ( char *s , int32_t len ) { int32_t i = 0; if ( ! s ) return; while ( i < len ) printf("%c",s[i++]); } bool Url::isExtensionIndexable () { // assume no extension is html if ( m_elen == 0 ) return true; if ( ! m_extension ) return true; // no matter what the extension, if it has cgi parms, let it through. if ( m_query ) return true; // now we index source code if ( m_elen == 1 ) { if ( m_extension[0] == 'c' ) return true; if ( m_extension[0] == 'h' ) return true; } else if ( m_elen == 2 ) { if ( strncasecmp ( m_extension , "ps", 2 ) == 0 ) return true; // perl is used like cgi if ( strncasecmp ( m_extension , "pl", 2 ) == 0 ) return true; return false; } else if ( m_elen == 3 ) { if ( strncasecmp ( m_extension , "htm", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "asp", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "xml", 3 ) == 0 ) return true; // rss has a Content-Type of xml usually if ( strncasecmp ( m_extension , "rss", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "cgi", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "dll", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "jsp", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "php", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "txt", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "pdf", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "doc", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "xls", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "ppt", 3 ) == 0 ) return true; // now we index source code if ( strncasecmp ( m_extension , "cpp", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "hpp", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "vbs", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "frm", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "bas", 3 ) == 0 ) return true; if ( strncasecmp ( m_extension , "jsp", 3 ) == 0 ) return true; // probably cold fusion template file. seems to be text/html if ( strncasecmp ( m_extension , "cfm", 3 ) == 0 ) return true; //http://news.bbc.co.uk/2/hi/science/nature/default.stm if ( strncasecmp ( m_extension , "stm", 3 ) == 0 ) return true; // rdf for rss feeds if ( strncasecmp ( m_extension , "rdf", 3 ) == 0 ) return true; return false; } else if ( m_elen == 4 ) { if ( strncasecmp ( m_extension , "html",4 ) == 0 ) return true; if ( strncasecmp ( m_extension , "phtm",4 ) == 0 ) return true; if ( strncasecmp ( m_extension , "shtm",4 ) == 0 ) return true; if ( strncasecmp ( m_extension , "fcgi",4 ) == 0 ) return true; if ( strncasecmp ( m_extension , "aspx",4 ) == 0 ) return true; // php3 and php4 etc. if ( strncasecmp ( m_extension , "php" ,3 ) == 0 ) return true; // now we index source code if ( strncasecmp ( m_extension , "java",4 ) == 0 ) return true; return false; } else if ( m_elen == 5 ) { if ( strncasecmp ( m_extension, "shtml", 5) == 0 ) return true; if ( strncasecmp ( m_extension, "jhtml", 5) == 0 ) return true; if ( strncasecmp ( m_extension, "phtml", 5) == 0 ) return true; if ( strncasecmp ( m_extension, "story", 5) == 0 ) return true; return false; } return false; } // . return url w/o http:// // . without trailing / if path is just "/" // . without "www." if in hostname and "rmWWW" is true // . sets *len to it's length char *Url::getShorthandUrl ( bool rmWWW , int32_t *len ) { char *u = m_url; int32_t ulen = m_ulen; if ( ulen > 7 && strncasecmp ( u , "http://" , 7 ) == 0) { u += 7 ; ulen -= 7 ; // if hostname is just "www" then skip iff rmWWW is true if ( rmWWW && m_hlen >= 4 && strncmp(m_host,"www.",4) == 0) { u += 4; ulen -= 4; } } // skip trailing / if ( m_plen == 1 && m_path[0]=='/' && m_query == NULL ) ulen--; // set the length *len = ulen; // return the url int16_thand return u; } int32_t Url::getPathDepth ( bool countFilename ) { char *s = m_path + 1; char *send = m_url + m_ulen; int32_t count = 0; while ( s < send ) if ( *s++ == '/' ) count++; // if we're counting the filename as a path component... if ( countFilename && *(send-1) != '/' ) count++; return count; } char *Url::getPathComponent ( int32_t num , int32_t *clen ) { // start countint at path char *start = m_path; char *p = m_path; char *pend = m_path + m_plen; int32_t count = 0; // loop up here for each component loop: // skip the '/' p++; start++; // advance until next / or end while ( p < pend && *p != '/' ) p++; // set length of that if ( clen ) *clen = p - start; // all done? if ( count == num ) return start; // if none, simply does not exist if ( p >= pend ) return NULL; // advance count++; // set start to p now start = p; goto loop; } //char *Url::getPathEnd ( int32_t num ) { // // get component // int32_t pclen = 0; // char *pc = getPathComponent ( num , &pclen ); // // return the end of it // return pc + pclen; //} bool Url::isHostWWW ( ) { if ( m_hlen < 4 ) return false; if ( m_host[0] != 'w' ) return false; if ( m_host[1] != 'w' ) return false; if ( m_host[2] != 'w' ) return false; if ( m_host[3] != '.' ) return false; return true; } // . is the url a porn/spam url? // . i use /usr/share/dict/words to check for legit words // . if it's int32_t and has 4+ hyphens, consider it spam // . if you add a word here, add it to PageResults.cpp:isQueryDirty() bool Url::isSpam() { // store the hostname in a buf since we strtok it char s [ MAX_URL_LEN ]; // don't store the .com or .org while searching for isSpam int32_t slen = m_hlen - m_tldLen - 1; gbmemcpy ( s , m_host , slen ); if ( ! m_domain ) return false; if ( ! m_dlen ) return false; //int32_t len = m_dlen; //gbmemcpy ( s , m_domain , len ); // if tld is gov or edu or org, not porn if ( m_tldLen >= 3 && strncmp ( m_tld , "edu" , 3 )==0 ) return false; if ( m_tldLen >= 3 && strncmp ( m_tld , "gov" , 3 )==0 ) return false; // NULL terminate for strstr s[slen]='\0'; // . if there is 4 or more hyphens, and hostLen > 30 consider it spam // . actually there seems to be a lot of legit sites with many hyphens if ( slen > 30 ) { int32_t count = 0; char *p = s; while ( *p ) if ( *p++ == '-' ) count++; if ( count >= 4 ) return true; } // // TODO: use getMatch()!!!! +pts -pts system // // check each thing separated by periods for porn char *send = s + slen; char *p = s; loop: // if done, return if ( p >= send ) return false; // find the next period or hyphen char *pend = p; while ( pend < send && *pend != '.' && *pend !='-' ) pend++; // ok NULL terminate it *pend = '\0'; // check that if ( isSpam ( p , pend - p ) ) return true; // point to next p = pend + 1; // loop back goto loop; } bool Url::isSpam ( char *s , int32_t slen ) { // no need to indent below, keep it clearer if ( ! isAdult ( s, slen ) ) return false; // check for naughty words. Split words to deep check if we're surely // adult. Required because montanalinux.org is showing up as porn // because it has 'anal' in the hostname. // send each phrase separately to be tested. // hotjobs.yahoo.com char *a = s; char *p = s; bool foundCleanSequence = false; char splitWords[1024]; char *splitp = splitWords; while ( p < s + slen ){ while ( p < s + slen && *p != '.' && *p != '-' ) p++; bool isPorn = false; // TODO: do not include "ult" in the dictionary, it is // always splitting "adult" as "ad ult". i'd say do not // allow it to split a dirty word into two words like that. if ( g_speller.canSplitWords( a, p - a, &isPorn, splitp, langEnglish, csUTF8 ) ){ if ( isPorn ){ log(LOG_DEBUG,"build: identified %s as " "porn after splitting words as " "%s", s, splitp); return true; } foundCleanSequence = true; // keep searching for some porn sequence } p++; a = p; splitp += gbstrlen(splitp); } // if we found a clean sequence, its not porn if ( foundCleanSequence ) { log(LOG_INFO,"build: did not identify url %s " "as porn after splitting words as %s", s, splitWords); return false; } // we tried to get some seq of words but failed. Still report // this as porn, since isAdult() was true logf ( LOG_DEBUG,"build: failed to find sequence of words to " "prove %s was not porn.", s ); return true; /* if ( strstr ( s , "upskirt" ) ) return true; if ( strstr ( s , "downblouse") ) return true; if ( strstr ( s , "adult" ) ) return true; if ( strstr ( s , "shemale" ) ) return true; if ( strstr ( s , "spank" ) ) return true; if ( strstr ( s , "dildo" ) ) return true; if ( strstr ( s , "shaved" ) ) return true; if ( strstr ( s , "bdsm" ) ) return true; if ( strstr ( s , "voyeur" ) ) return true; if ( strstr ( s , "shemale" ) ) return true; if ( strstr ( s , "fisting" ) ) return true; if ( strstr ( s , "escorts" ) ) return true; if ( strstr ( s , "vibrator" ) ) return true; if ( strstr ( s , "rgasm" ) ) return true; // 0rgasm if ( strstr ( s , "orgy" ) ) return true; if ( strstr ( s , "orgies" ) ) return true; if ( strstr ( s , "masturbat" ) ) return true; if ( strstr ( s , "stripper" ) ) return true; if ( strstr ( s , "lolita" ) ) return true; //if ( strstr ( s , "hardcore" ) ) return true; ps2hardcore.co.uk if ( strstr ( s , "softcore" ) ) return true; if ( strstr ( s , "whore" ) ) return true; if ( strstr ( s , "slut" ) ) return true; if ( strstr ( s , "smut" ) ) return true; if ( strstr ( s , "tits" ) ) return true; if ( strstr ( s , "lesbian" ) ) return true; if ( strstr ( s , "swinger" ) ) return true; if ( strstr ( s , "fetish" ) ) return true; if ( strstr ( s , "housewife" ) ) return true; if ( strstr ( s , "housewive" ) ) return true; if ( strstr ( s , "nude" ) ) return true; if ( strstr ( s , "bondage" ) ) return true; if ( strstr ( s , "centerfold") ) return true; if ( strstr ( s , "incest" ) ) return true; if ( strstr ( s , "pedophil" ) ) return true; if ( strstr ( s , "pedofil" ) ) return true; // hornyear.com if ( strstr ( s , "horny" ) ) return true; if ( strstr ( s , "pussy" ) ) return true; if ( strstr ( s , "pussies" ) ) return true; if ( strstr ( s , "penis" ) ) return true; if ( strstr ( s , "vagina" ) ) return true; if ( strstr ( s , "phuck" ) ) return true; if ( strstr ( s , "blowjob" ) ) return true; if ( strstr ( s , "gangbang" ) ) return true; if ( strstr ( s , "xxx" ) ) return true; if ( strstr ( s , "porn" ) ) return true; if ( strstr ( s , "felch" ) ) return true; if ( strstr ( s , "cunt" ) ) return true; if ( strstr ( s , "bestial" ) ) return true; if ( strstr ( s , "beastial" ) ) return true; //if ( strstr ( s , "oral" ) ) return true; // moral, doctorial, ... // these below may have legit meanings if ( strstr ( s , "kink" ) ) { if ( strstr ( s , "kinko" ) ) return false; // the store return true; } if ( strstr ( s , "sex" ) ) { // sexton, sextant, sextuplet, sextet if ( strstr ( s , "sext" ) ) return false; if ( strstr ( s , "middlesex" ) ) return false; if ( strstr ( s , "sussex" ) ) return false; if ( strstr ( s , "essex" ) ) return false; if ( strstr ( s , "deusex" ) ) return false; // video game if ( strstr ( s , "sexchange" ) ) return false; // businessexh if ( strstr ( s , "sexpress" ) ) return false; // *express if ( strstr ( s , "sexpert" ) ) return false; // *expert if ( strstr ( s , "sexcel" ) ) return false; // *excellence if ( strstr ( s , "sexist" ) ) return false; // existence if ( strstr ( s , "sexile" ) ) return false; // existence if ( strstr ( s , "harassm" ) ) return false; // harassment if ( strstr ( s , "sexperi" ) ) return false; // experience if ( strstr ( s , "transex" ) ) return false; // transexual if ( strstr ( s , "sexual" ) ) return false; // abuse,health if ( strstr ( s , "sexpo" ) ) return false; // expo,expose if ( strstr ( s , "exoti" ) ) return false; // exotic(que) if ( strstr ( s , "sexclu" ) ) return false; // exclusive/de return true; } // www.losAnaLos.de // sanalcafe.net if ( strstr ( s , "anal") ) { if ( strstr ( s , "analog" ) ) return false; // analogy if ( strstr ( s , "analy" ) ) return false; // analysis if ( strstr ( s , "canal" ) ) return false; if ( strstr ( s , "kanal" ) ) return false; // german if ( strstr ( s , "banal" ) ) return false; return true; } if ( strstr ( s , "cum") ) { if ( strstr ( s , "circum" ) ) return false; // circumvent if ( strstr ( s , "magn" ) ) return false; // magna cum if ( strstr ( s , "succu" ) ) return false; // succumb if ( strstr ( s , "cumber" ) ) return false; // encumber if ( strstr ( s , "docum" ) ) return false; // document if ( strstr ( s , "cumul" ) ) return false; // accumulate if ( strstr ( s , "acumen" ) ) return false; // acumen if ( strstr ( s , "cucum" ) ) return false; // cucumber if ( strstr ( s , "incum" ) ) return false; // incumbent if ( strstr ( s , "capsicum" ) ) return false; if ( strstr ( s , "modicum" ) ) return false; if ( strstr ( s , "locum" ) ) return false; // slocum if ( strstr ( s , "scum" ) ) return false; if ( strstr ( s , "accu" ) ) return false; // compounds! // arcum.de // cummingscove.com // cumchristo.org return true; } //if ( strstr ( s , "lust" ) ) { // if ( strstr ( s , "illust" ) ) return false; // illustrated // if ( strstr ( s , "clust" ) ) return false; // cluster // if ( strstr ( s , "blust" ) ) return false; // bluster // if ( strstr ( s , "lustrad" ) ) return false; // balustrade // // TODO: plusthemes.com wanderlust // return true; //} // brettwatt.com //if ( strstr ( s , "twat" ) ) { // if ( strstr ( s , "watch" ) ) return false; // wristwatch // if ( strstr ( s , "atwater" ) ) return false; // if ( strstr ( s , "water" ) ) return false; // sweetwater // return true; //} if ( strstr ( s, "clit" ) && ! strstr ( s, "heraclitus") ) return true; // fuckedcompany.com is ok if ( strstr ( s, "fuck" ) && ! strstr ( s, "fuckedcomp") ) return true; if ( strstr ( s, "boob" ) && ! strstr ( s, "booboo" ) ) return true; if ( strstr ( s, "wank" ) && ! strstr ( s, "swank" ) ) return true; // fick is german for fuck (fornication under consent of the king) if ( strstr ( s, "fick" ) && ! strstr ( s, "fickle") && ! strstr ( s , "traffick" ) ) return true; // sclerotic // buerotipp.de if ( strstr ( s, "eroti") && ! strstr ( s, "sclero" ) ) return true; // albaberlin.com // babelfish.altavista.com if ( strstr ( s, "babe" ) && ! strstr ( s, "toyland" ) && ! strstr ( s , "babel") ) return true; // what is gaya.dk? if ( strstr ( s , "gay" ) && ! strstr ( s, "gaylord" ) ) return true; // url appears to be ok return false;*/ } // . remove any session id // . i'm sick of these tihngs causing dup problems // . types: // http://www.b.com/?PHPSESSID=737aec14eb7b360983d4fe39395 // http://www.b.com/cat.cgi/process?mv_session_id=xrf2EY3q& // http://www.b.com/default?SID=f320a739cdecb4c3edef67e // http://www.b.com/generic.html;$sessionid$QVBMODQAAAGNA?pid=7 // http://www.b.com/p.jhtml;jsessionid=J4QMFWBG1SPRVWCKUUXCJ0W?stuff=1 // look for ';' // look for PHPSESSID, session_id, SID, jsessionid // followed by string of at least 4 letters/numbers //List of extensions NOT to parse static char *s_badExtensions[] = { "ai", "aif", "aifc", "aiff", "asc", "au", "avi", "bcpio", "bin", "bmp", "bz2", //"c", //"cc",// c source code, allow "ccad", "cdf", //"class",// text source code file usually, allow "cpio", "cpt", //"csh", "css", "dcr", "dir", "dms", //"doc", "drw", "dvi", "dwg", "dxf", "dxr", "eps", "etx", "exe", "ez", //"f", // ambiguous "f90", "fli", "gif", "gtar", "gz", //"h", "hdf", "hh", "hqx", //"htm", //"html", "ice", "ief", "iges", "igs", "ips", "ipx", "jpe", "jpeg", "jpg", //"js", "kar", "latex", "lha", "lsp", "lzh", //"m", // ambiguous "man", "me", "mesh", "mid", "midi", "mif", "mime", "mov", "movie", "mp2", "mp3", "mpe", "mpeg", "mpg", "mpga", "ms", "msh", "nc", "oda", "pbm", "pdb", //"pdf", "pgm", "pgn", "png", "pnm", "pot", "ppm", "pps", // "ppt", "ppz", "pre", "prt", // "ps", "qt", "ra", "ram", "ras", "rgb", "rm", "roff", "rpm", "deb", // debian/ubuntu package file "rtf", "rtx", "scm", "set", "sgm", "sgml", //"sh", // shells are text files "shar", "silo", "sit", "skd", "skm", "skp", "skt", "smi", "smil", "snd", "sol", "spl", "src", "step", "stl", "stp", "sv4cpio", "sv4crc", "swf", //"t", // ambiguous ... Mr.T. "tar", "tcl", "tex", "texi", "texinfo", "tif", "tiff", "tr", "tsi", "tsp", "tsv", //"txt", "unv", "ustar", "vcd", "vda", "viv", "vivo", "vrml", "wav", "wrl", "xbm", "xlc", "xll", "xlm", //"xls", "xlw", //"xml", "xpm", "xwd", "xyz", "zip",// };//look below, I added 3 more types for TR version 73 static HashTable s_badExtTable; static bool s_badExtInitialized; //returns True if the extension is listed as bad bool Url::isBadExtension ( int32_t version ) { // return !isExtensionIndexable(); if ( ! m_extension || m_elen == 0 ) return false; if(!s_badExtInitialized) { //if hash has not been created-create one int32_t i=0; //version 72 and before. do { int tlen = gbstrlen(s_badExtensions[i]); int64_t swh = hash64Lower_a(s_badExtensions[i],tlen); if(!s_badExtTable.addKey(swh,(int32_t)50)) return false; i++; } while(strcmp(s_badExtensions[i],"zip")!=0); //version 73 and after. if(!s_badExtTable.addKey(hash64Lower_a("wmv", 3), (int32_t)73) || !s_badExtTable.addKey(hash64Lower_a("wma", 3), (int32_t)73) || !s_badExtTable.addKey(hash64Lower_a("ogg", 3), (int32_t)73)) return false; s_badExtInitialized = true; } int myKey = hash64Lower_a(m_extension,m_elen); //zero unless we have a bad extension, otherwise //we return TR version in which it was banned int32_t badVersion = s_badExtTable.getValue(myKey); if (badVersion == 0) return false; //if(badVersion <= version) return true; if ( badVersion > version ) return false; // exceptions for .warc.gz .warc .arc .argc.gz if ( isWarc() || isArc() ) return false; return true; } bool Url::isWarc ( ) { // if ( ulen>8 && strncmp(uend-8,".warc.gz",8)==0 ) // m_isWarc = true; // if ( ulen>8 && strncmp(uend-5,".warc" ,5)==0 ) // m_isWarc = true; // if ( ulen>8 && strncmp(uend-7,".arc.gz",7)==0 ) // m_isArc = true; // if ( ulen>8 && strncmp(uend-4,".arc" ,4)==0 ) // m_isArc = true; if ( m_elen == 4 && m_extension[0] == 'w' && m_extension[1] == 'a' && m_extension[2] == 'r' && m_extension[3] == 'c' ) return true; if ( m_elen == 2 && m_extension[0] == 'g' && m_extension[1] == 'z' && m_ulen > 10 && m_extension[-1] == '.' && m_extension[-2] == 'c' && m_extension[-3] == 'r' && m_extension[-4] == 'a' && m_extension[-5] == 'w' && m_extension[-6] == '.' ) { // m_isWarc = true; // m_isWarcValid = true; return true; } return false; } bool Url::isArc ( ) { if ( m_elen == 3 && m_extension[0] == 'a' && m_extension[1] == 'r' && m_extension[2] == 'c' ) return true; // hack to allow for .gz if it is .warc.gz or .arc.gz if ( m_elen == 2 && m_extension[0] == 'g' && m_extension[1] == 'z' && m_ulen > 10 && m_extension[-1] == '.' && m_extension[-2] == 'c' && m_extension[-3] == 'r' && m_extension[-4] == 'a' && m_extension[-5] == '.' ) { // m_isArc = true; // m_isArcValid = true; return true; } return false; } // see Url.h for a description of this. bool Url::isLinkLoop ( ) { char *s = m_path ; char *send = m_url + m_ulen; int32_t count = 0; int32_t components = 0; bool prevWasDouble = false; char *last = NULL; if (!s) return false; // use this hash table to hash each path component in the url char buf [ 5000 ]; HashTable t; t.set ( 100 , buf , 5000 ); // grab each path component for ( ; s < send ; s++ ) { if ( *s != '/' ) continue; // ok, add this guy to the hash table, if we had one if ( ! last ) { last = s; continue; } // give up after 50 components if ( components++ >= 50 ) return false; // hash him uint32_t h = hash32 ( last , s - last ); // is he in there? int32_t slot = t.getSlot ( h ); // get his val (count) int32_t val = 0; if ( slot >= 0 ) val = t.getValueFromSlot ( slot ); // if not in there put him in a slot if ( slot < 0 ) { last = s; t.addKey ( h , 1 ); continue; } // increment it val++; // does it occur 3 or more times? if so, we have a link loop if ( val >= 3 ) return true; // is it 2 or more? if ( val == 2 ) count++; // if we have two such components, then we are a link loop. // BUT, we must be a pair! if ( count >= 2 && prevWasDouble ) return true; // set this so in case next guy is a double if ( val == 2 ) prevWasDouble = true; else prevWasDouble = false; // add it back after incrementing t.setValue ( slot , val ); // update "last" last = s; } return false; } // // here are some examples of link loops in urls: // //http://www.pittsburghlive.com:8000/x/tribune-review/opinion/steigerwald/letters\/send/archive/letters/send/archive/bish/archive/bish/letters/bish/archive/lette\rs/send/archive/letters/send/bish/letters/archive/bish/letters/ //http://www.pittsburghlive.com:8000/x/tribune-review/opinion/steigerwald/letters\/bish/letters/archive/bish/archive/letters/send/archive/letters/send/archive/le\tters/send/archive/letters/send/bish/ //http://www.pittsburghlive.com:8000/x/tribune-review/opinion/steigerwald/letters\/send/archive/bish/letters/send/archive/letters/send/archive/bish/archive/bish/\archive/bish/letters/send/archive/letters/archive/letters/send/archive/bish/let\ters/ //http://www.pittsburghlive.com:8000/x/tribune-review/opinion/steigerwald/letters\/send/archive/letters/send/archive/letters/archive/bish/archive/bish/archive/bi\sh/letters/send/archive/bish/archive/letters/send/bish/archive/bish/letters/sen\d/archive/ //http://www.pittsburghlive.com:8000/x/tribune-review/opinion/steigerwald/letters\/send/archive/bish/letters/send/archive/bish/letters/bish/letters/send/archive/\bish/archive/letters/bish/letters/send/archive/bish/letters/send/bish/archive/l\etters/bish/letters/archive/letters/send/ //http://www.pittsburghlive.com:8000/x/tribune-review/opinion/steigerwald/letters\/send/archive/bish/letters/send/archive/bish/letters/send/bish/archive/letters/\send/bish/archive/letters/send/archive/letters/bish/archive/bish/archive/letter\s/ bool Url::isIp() { if(!m_host) return false; if(!is_digit(*m_host)) return false; return atoip ( m_host , m_hlen ); } /* bool Url::isSiteRoot ( char *coll , TagRec *tagRec , char **retSite , int32_t *retSiteLen ) { int32_t siteLen; // use the DOMAIN as the default site char *site = getSite ( &siteLen , coll , false , tagRec ); // check end of site char *send = site + siteLen; // our end char *uend = m_url + m_ulen; // backup over an ending '/' if ( uend[-1] == '/' ) uend--; // set it if ( retSite ) *retSite = site; if ( retSiteLen ) *retSiteLen = siteLen; // if before our end, we are not a site root return (uend <= send); } // . a "site" is a set of urls controlled/regulated primarily by the same // entity. // . this returns the smallest site containing the url, m_url // . so fred.blogspot.com is considered a site regulated by "fred" // . BUT blogspot.com is a larger site regulated by blogspot // . the default site is the domain // . returns NULL and sets g_errno on error // . if "defaultToHostname" is true we default to the hostname // as opposed to the domain name. char *Url::getSite ( int32_t *siteLen , char *coll , bool defaultToHostname , TagRec *tagRec , bool *isDefault ) { // clear just in case g_errno = 0; // convenience vars char *p; int32_t len = 0; // assume we return the default if ( isDefault ) *isDefault = true; int32_t sitepathdepth = -1; // we may have a defined path depth Tag *tag = NULL; // see if we do if ( tagRec ) tag = tagRec->getTag("sitepathdepth"); // sanity check if ( tag && tag->m_dataSize != 1 ) { char *xx=NULL;*xx=0; } // if there, get the sitepathdepth value it contains if ( tag ) sitepathdepth = (int32_t)tag->m_data[0]; // . deal with site indicators // . these are applied to all domains uniformly // . if it is xyz.com/users/ use xyz.com/users/fred/ as the site p = m_path; // a lot of times these were not individual blogs, but the blog subsite // of a site... http://dccc.org/blog/P4575/ //if ( strncasecmp(p,"/blogs/" , 7) == 0 ) len = 7; //if ( strncasecmp(p,"/blog/" , 6) == 0 ) len = 6; // commented out a bunch cuz they were profiles mostly, not blogs... if ( strncasecmp(p,"/~" , 2) == 0 ) len = 2; // assume this is a username. skip the first / if ( sitepathdepth == 1 ) len = 1; //if ( strncasecmp(p,"/users/" , 7) == 0 ) len = 7; //if ( strncasecmp(p,"/user/" , 6) == 0 ) len = 6; //if ( strncasecmp(p,"/members/" , 9) == 0 ) len = 9; //if ( strncasecmp(p,"/membres/" , 9) == 0 ) len = 9; //if ( strncasecmp(p,"/member/" , 8) == 0 ) len = 8; //if ( strncasecmp(p,"/membre/" , 8) == 0 ) len = 8; //if ( strncasecmp(p,"/member.php?u=",14) == 0 ) len = 14; // point to after the /users/, /blogs/, /user/, /blog/ or /~xxx/ p += len; // assume there is NOT an alpha char after this char username = false; // . skip to next / OR ? // . stop at . or -, because we do not allow those in usernames and // they are often indicative of filenames without file extensions while ( len && *p && *p!= '/'&&*p!='?'&&*p!='.'&&*p!='-'&&*p!='_') { if ( is_alpha_a(*p) ) username = true; p++; } // if we hit this, not a username if ( *p=='.' || *p == '-' || *p == '_' ) username = false; // did we get a match? // . www.cits.ucsb.edu/users/michael-osborne // . www.cits.ucsb.edu/users/michael-osborne/ // . after /blog/ or /~ should be another / or \0, not a period, // because that indicates probably a filename, which is not right, // because we are expecting a username! if ( username ) { // include the '/' if ( *p == '/' ) p++; // get length *siteLen = p - m_host; // not the default if ( isDefault ) *isDefault = false; // return the site return m_host; } // assume none *siteLen = 0; // . the default site is the domain // . if domain is invalid, site/siteLen will be NULL/0 if ( ! getDomain() ) return NULL; // check the Site Filters table CollectionRec *cr = NULL; if ( coll ) cr = g_collectiondb.getRec(coll); // the default site is the domain char *site; if ( defaultToHostname ) { site = m_host ; *siteLen = m_hlen; } else { site = m_domain; *siteLen = m_dlen; } // g_errno should be set if ( ! cr ) return site; // initialize the hash table if it needs to be if ( cr->m_updateSiteRulesTable ) { logf ( LOG_INFO, "db: Updating Site Filters Table" ); // fill in the hash tables with domain hashes cr->m_siteRulesTable.reset(); cr->m_siteRulesTable.set(cr->m_numSiteExpressions*2); for ( int32_t i = 0; i < cr->m_numSiteExpressions ; i++ ) { Url f; char *u = cr->m_siteExpressions[i]; int32_t ulen = gbstrlen ( u ); // do not add "www." f.set(u,ulen,false); // hash the whole hostname (might be just domain) int32_t h = hash32 ( f.getHost(), f.getHostLen() ); // also hash scheme and port h = hash32 ( f.getScheme() , f.getSchemeLen() , h ); h = hash32 ( h , f.getPort() ); // add to the table cr->m_siteRulesTable.addKey(h, i+1); } // unset the update flag cr->m_updateSiteRulesTable = 0; } // . you can only have on entry per domain or subdomain in the table! // . that entry will be a domain or a subdomain // . so check for both in the hash table int32_t t = 2; loop: t--; // return the DEFAULT SITE if no matches if ( t < 0 ) return site; // check hash table for this domain or subdomain int32_t h ; if ( t == 1 ) h = hash32 ( getHost () , getHostLen () ); else h = hash32 ( getDomain() , getDomainLen() ); // also hash scheme and port h = hash32 ( getScheme(), getSchemeLen(), h); h = hash32 ( h, getPort()); // is it in the table? int32_t s = cr->m_siteRulesTable.getSlot(h); // if not found, try the domain next if ( s < 0 ) goto loop; // found, grab the index # int32_t i = cr->m_siteRulesTable.getValueFromSlot(s) - 1; // . see if the url properly matches a filter // . do NOT add "www." to the domain/subdomain of the filter url char *e = cr->m_siteExpressions[i]; Url f; f.set (e,gbstrlen(e),false); // what is the rule #? if rule is 0, that means the "hostname" rule // otherwise this specifies a path depth that defines the site... int32_t r = cr->m_siteRules[i]; // get the full hostname of it //char *h = f.getHost(); //int32_t hlen = f.getHostLen(); // get its hostname (might just be a domain name) char *sub = f.getHost(); int32_t subLen = f.getUrlLen() - f.getSchemeLen() - 3; // assume we did not match it char matched = 0; // is the filtered url "f" a "substring" of us? if ( strncmp ( getHost () , sub , subLen ) == 0 ) matched = 1; if ( strncmp ( getDomain() , sub , subLen ) == 0 ) matched = 2; // must also match scheme and port if ( getPort() != f.getPort() ) matched = false; if ( getSchemeLen() != f.getSchemeLen() ) matched = false; if ( strncmp(getScheme(), f.getScheme(),m_slen) ) matched = false; // if really not a match try again if ( ! matched ) goto loop; // . we got a match // . if r == 0 then the hostname is the site for this rule // . so return the hostname as the site if ( r == 0 ) { // not the default if ( isDefault ) *isDefault = false; *siteLen = m_hlen; return m_host; } // . otherwise, it is path depth based // . m_path starts off point to "/" p = m_path; // if empty, no good, no site. return the DEFAULT SITE if ( ! p ) return site; // do not count the first "/" p++; // how many /'s to count to? int32_t count ; // count them for ( count = r ; count > 0 ; count-- ) { // inc p while ( *p && *p !='/' ) p++; // done? if ( ! *p ) break; // skip passed the '/' p++; } // if count not accomplished, no site. return the DEFAULT SITE. if ( count > 0 ) return site; // not the default if ( isDefault ) *isDefault = false; // otherwise we got the site if ( matched == 1 ) { // use the host, since we matched that *siteLen = p - m_host; // return it return m_host; } // otherwise, use domain *siteLen = p - m_domain; return m_domain; } int32_t Url::getSiteHash32 ( char *coll ) { int32_t siteLen; // prefer domain as default, not hostname char *site = getSite ( &siteLen , coll , false ); return hash32 ( site , siteLen ); } */ int32_t Url::getHash32WithWWW ( ) { uint32_t hh = hash32n ( "www." ); int32_t conti = 4; hh = hash32_cont ( m_domain , m_dlen , hh , &conti ); return hh; } int32_t Url::getHostHash32 ( ) { return hash32 ( m_host , m_hlen ); } int64_t Url::getHostHash64 ( ) { return hash64 ( m_host , m_hlen ); } int32_t Url::getDomainHash32 ( ) { return hash32 ( m_domain , m_dlen ); } int64_t Url::getDomainHash64 ( ) { return hash64 ( m_domain , m_dlen ); } int32_t Url::getUrlHash32 ( ) { return hash32(m_url,m_ulen); } int64_t Url::getUrlHash64 ( ) { return hash64(m_url,m_ulen); } char *getHostFast ( char *url , int32_t *hostLen , int32_t *port ) { // point to the url char *pp = url; // skip http(s):// or ftp:// (always there?) while ( *pp && *pp != ':' ) pp++; // skip :// pp += 3; // point "uhost" to hostname right away char *uhost = pp; // advance "pp" till we hit a / or :<port> while ( *pp && *pp !='/' && *pp !=':' ) pp++; // advance "pe" over the port char *pe = pp; if ( *pp == ':' ) { // if port ptr given, do not treat port as part of hostname if ( port ) *port = atoi(pp+1); // i think this was including :1234 as part of hostname // if port was NULL! //else while ( *pe && *pe != '/' ) pe++; } // set length if ( hostLen ) *hostLen = pe - uhost; return uhost; } char *getPathFast ( char *url ) { // point to the url char *pp = url; // skip http(s):// or ftp:// (always there?) while ( *pp && *pp != ':' ) pp++; // skip :// pp += 3; // point "uhost" to hostname right away //char *uhost = pp; // advance "pp" till we hit a / or :<port> while ( *pp && *pp !='/' && *pp !=':' ) pp++; // advance "pe" over the port char *pe = pp; if ( *pp == ':' ) while ( *pe && *pe != '/' ) pe++; // but not if something follows the '/' return pe; } char *getTLDFast ( char *url , int32_t *tldLen , bool hasHttp ) { // point to the url char *pp = url; // only do this for some if ( hasHttp ) { // skip http(s):// or ftp:// (always there?) while ( *pp && *pp != ':' ) pp++; // skip :// pp += 3; } // point "uhost" to hostname right away char *uhost = pp; // advance "pp" till we hit a / or :<port> or \0 while ( *pp && *pp !='/' && *pp !=':' ) pp++; // are we a root? assume so. char isRoot = true; // advance "pe" over the port char *pe = pp; if ( *pp == ':' ) while ( *pe && *pe != '/' ) pe++; // but not if something follows the '/' if ( *pe == '/' && *(pe+1) ) isRoot = false; // set length of host int32_t uhostLen = pp - uhost; // . is the hostname just an IP address? // . if it is an ip based url make domain the hostname char *ss = uhost; bool isIp = true; for ( ; *ss && ss<pp ; ss++ ) if ( is_alpha_a(*ss) ) { isIp = false; break; } // if ip, no tld if ( isIp ) return NULL; // get the tld char *tld = ::getTLD ( uhost , uhostLen ); // if none, done if ( ! tld ) return NULL; // set length if ( tldLen ) *tldLen = pp - tld; // return it return tld; } bool hasSubdomain ( char *url ) { // point to the url char *pp = url; // skip http if there if ( pp[0] == 'h' && pp[1] == 't' && pp[2] == 't' && pp[3] == 'p' && pp[4] == ':' && pp[5] == '/' && pp[6] == '/' ) pp += 7; else if ( pp[0] == 'h' && pp[1] == 't' && pp[2] == 't' && pp[3] == 'p' && pp[4] == 's' && pp[5] == ':' && pp[6] == '/' && pp[7] == '/' ) pp += 8; // point "uhost" to hostname right away char *uhost = pp; // advance "pp" till we hit a / or :<port> while ( *pp && *pp !='/' && *pp !=':' ) pp++; // are we a root? assume so. //char isRoot = true; // advance "pe" over the port char *pe = pp; if ( *pp == ':' ) while ( *pe && *pe != '/' ) pe++; // but not if something follows the '/' //if ( *pe == '/' && *(pe+1) ) isRoot = false; // set length int32_t uhostLen = pp - uhost; // get end //char *hostEnd = uhost + uhostLen; // . is the hostname just an IP address? // . if it is an ip based url make domain the hostname char *ss = uhost; while ( *ss && !is_alpha_a(*ss) && ss<pp ) ss++; // if we are an ip, say yes if ( ss == pp ) return true; // get the tld char *utld = ::getTLD ( uhost , uhostLen ); // no tld, then no domain if ( ! utld ) return false; // the domain, can only be gotten once we know the TLD // back up a couple chars char *udom = utld - 2; // backup until we hit a '.' or hit the beginning while ( udom > uhost && *udom != '.' ) udom--; // fix http://ok/ if ( udom < uhost || *udom =='/' ) return false; // if we hit '.' advance 1 if ( *udom == '.' ) udom++; // eqal to host? if not, we do have a subdomain if ( udom != uhost ) return true; // otherwise the hostname equals the domain name return false; } // returns NULL if url was in bad format and could not get domain. this // was happening when a host gave us a bad redir url and xmldoc tried // to set extra doc's robot.txt url to it "http://2010/robots.txt" where // the host said "Location: 2010 ...". char *getDomFast ( char *url , int32_t *domLen , bool hasHttp ) { // point to the url char *pp = url; // skip http if there if ( hasHttp ) { // skip http(s):// or ftp:// (always there?) while ( *pp && *pp != ':' ) pp++; // skip :// pp += 3; } // point "uhost" to hostname right away char *uhost = pp; // advance "pp" till we hit a / or :<port> while ( *pp && *pp !='/' && *pp !=':' ) pp++; // are we a root? assume so. char isRoot = true; // advance "pe" over the port char *pe = pp; if ( *pp == ':' ) while ( *pe && *pe != '/' ) pe++; // but not if something follows the '/' if ( *pe == '/' && *(pe+1) ) isRoot = false; // set length int32_t uhostLen = pp - uhost; // get end char *hostEnd = uhost + uhostLen; // . is the hostname just an IP address? // . if it is an ip based url make domain the hostname char *ss = uhost; while ( *ss && !is_alpha_a(*ss) && ss<pp ) ss++; //bool isIp = false; //if ( ss == pp ) isIp = true; // if we are an ip, treat special if ( ss == pp ) { // . might just be empty! like "\0" // . fixes core dump from // http://www.marcom1.unimelb.edu.au/public/contact.html // parsing host email address if ( uhostLen == 0 ) return NULL; // to be consistent with how Url::m_domain/m_dlen is set we // need to remove the last .X from the ip address // skip back over digits for ( hostEnd-- ; is_digit(*hostEnd); hostEnd-- ); // must be a period if ( *hostEnd != '.' ) { log("url: getDomFast() could not find period for " "hostname in url"); return NULL; } // set length *domLen = hostEnd - uhost; // that's it return uhost; } // get the tld char *utld = ::getTLD ( uhost , uhostLen ); // no tld, then no domain if ( ! utld ) return NULL; // the domain, can only be gotten once we know the TLD // set utldLen //int32_t utldLen = hostEnd - utld; // back up a couple chars char *udom = utld - 2; // backup until we hit a '.' or hit the beginning while ( udom > uhost && *udom != '.' ) udom--; // fix http://ok/ if ( udom < uhost || *udom =='/' ) return NULL; // if we hit '.' advance 1 if ( *udom == '.' ) udom++; // set domain length *domLen = hostEnd - udom; return udom; } // is it of a permalink form? bool isPermalinky ( char *u ) { // get its path char *path = getPathFast(u); // our ptr char *p = path; // we must have a sequence of 3 or more digits in the path int32_t dcount = 0; // start scanning at the path for ( ; *p && *p !='?' ; p++ ) { // if not a digit, reset count if ( ! is_digit(*p) ) { dcount = 0; continue; } // count it if a digit if ( ++dcount == 3 ) break; } // it can also have 2+ hyphens or 2+ underscores in a single // path component to be a permalink int32_t hcount = 0; p = path; for ( ; *p && *p !='?' ; p++ ) { // if not a digit, reset count if ( *p == '/' ) { hcount = 0; continue; } // is it a thing? if ( *p != '_' && *p != '-' ) continue; // count it if ( ++hcount == 2 ) break; } // must be "permalinky" if ( hcount < 2 && dcount < 3 ) return false; // we are return true; } /* bool Url::isRSSFormat ( ) { // if it ends in .rss, .xml or .rdf ASSUME rss bool isRSS = false; char *e = getExtension(); int32_t elen = getExtensionLen(); if ( elen == 3 && strcmp(e,"rss")==0 ) isRSS = true; if ( elen == 3 && strcmp(e,"xml")==0 ) isRSS = true; if ( elen == 3 && strcmp(e,"rdf")==0 ) isRSS = true; // . but if it has wlwmanifest, then not! // . i don't know what those are, but they are not rss feeds if ( strstr ( getPath(), "wlwmanifest" ) ) isRSS = false; // same goes for foaf if ( strstr ( getPath(), "foaf" ) ) isRSS = false; return isRSS; } */ // is it http://rpc.weblogs.com/int16_tChanges.xml, etc.? bool Url::isPingServer ( ) { if ( strcmp ( m_url , "http://rpc.weblogs.com/int16_tChanges.xml") == 0 ) return true; // testing page if ( strcmp ( m_url , "http://127.0.0.1:8000/int16_tChanges.xml") == 0 ) return true; // default return false; } bool isPingServer ( char *s ) { if ( strstr ( s , "rpc.weblogs.com/int16_tChanges.xml") ) return true; // testing page if ( strstr ( s , "127.0.0.1:8000/int16_tChanges.xml") ) return true; // default return false; } // "s" point to the start of a normalized url (includes http://, etc.) char *getHost ( char *s , int32_t *hostLen ) { // skip proto while ( *s != ':' ) s++; // skip :// s += 3; // that is the host char *host = s; // get length of hostname for ( s++; *s && *s != '/' ; s++ ); // that is it *hostLen = s - host; // return it return host; } char *getFilenameFast ( char *s , int32_t *filenameLen ) { // skip proto while ( *s != ':' ) s++; // skip :// s += 3; // get length of hostname for ( s++; *s && *s != '/' ; s++ ); // should always have a / if ( *s != '/' ) { char *xx=NULL;*xx=0;} // skip that s++; // this point to the filename char *filename ; // loop over every subdir name in the path subloop: // assume that is filename filename = s; // advance s for ( ; *s && *s !='/' && *s != '?' && *s !='#' ; s++ ); // if we hit another '/' re-set filename if ( *s == '/' ) { s++; goto subloop; } // set end of it char *filenameEnd = s; // set length *filenameLen = filenameEnd - filename; // if none, return null if ( *filenameLen == 0 ) return NULL; // return it return filename; } // . return ptrs to the end // . the character it points to SHOULD NOT BE part of the site char *getPathEnd ( char *s , int32_t desiredDepth ) { // skip proto while ( *s != ':' ) s++; // skip :// s += 3; // get length of hostname for ( s++; *s && *s != '/' ; s++ ); // should always have a / if ( *s != '/' ) { char *xx=NULL;*xx=0;} // skip that s++; // init depth int32_t depth = 0; // do a character loop for ( ; depth <= desiredDepth && *s ; s++ ) // count the '/' if ( *s == '/' ) depth++; // return the end return s; /* // save for below int32_t saved = depth; // keep going while ( depth-- > 0 ) { for ( s++; *s && *s != '/' && *s != '?' ; s++ ); // if not enough path components (or cgi), return NULL if ( *s != '/' ) return NULL; } // include the last '/' if we have path components if ( saved > 0 ) s++; // . we got it // . if depth==0 just use "www.xyz.com" as site // . if depth==1 just use "www.xyz.com/foo/" as site return s; */ } // . pathDepth==0 for "www.xyz.com" // . pathDepth==0 for "www.xyz.com/" // . pathDepth==0 for "www.xyz.com/foo" // . pathDepth==1 for "www.xyz.com/foo/" // . pathDepth==1 for "www.xyz.com/foo/x" // . pathDepth==2 for "www.xyz.com/foo/x/" // . pathDepth==2 for "www.xyz.com/foo/x/y" int32_t getPathDepth ( char *s , bool hasHttp ) { // skip http:// if we got it if ( hasHttp ) { // skip proto while ( *s != ':' ) s++; // must have it! if ( ! *s ) { char *xx=NULL;*xx=0; } // skip :// s += 3; } // skip over hostname for ( s++; *s && *s != '/' ; s++ ); // no, might be a site like "xyz.com" if ( ! *s ) return 0; // should always have a / if ( *s != '/' ) { char *xx=NULL;*xx=0;} // skip that s++; // init depth int32_t depth = 0; // do a character loop for ( ; *s ; s++ ) { // stop if we hit ? or # if ( *s == '?' ) break; if ( *s == '#' ) break; // count the '/' if ( *s == '/' ) depth++; } return depth; } // must be like xyz.com/xxxx/yyyy/[a-z]*.htm format bool isHijackerFormat ( char *url ) { if ( ! url ) return false; // get the path char *p = getPathFast ( url ); if ( strstr(p,"/docs.php?id=") ) return true; if ( strstr(p,"/mods.php?id=") ) return true; if ( strstr(p,"/show.php?p=") ) return true; // count the /'s int32_t pc = 0; for ( ; *p=='-' || *p=='_' || *p=='/' || (*p>='a'&&*p<='z') || is_digit(*p); p++) if ( *p == '/' ) pc++; // too many /'s? if ( pc >= 5 ) return false; // too few. need at least 3 if ( pc <= 2 ) return false; // need a .htm if ( *p != '.' ) return false; // skip . p++; // need "htm\0" now if ( p[0] != 'h' ) return false; if ( p[1] != 't' ) return false; if ( p[2] != 'm' ) return false; if ( p[3] != 0 ) return false; return true; } bool Url::hasMediaExtension ( ) { if ( ! m_extension || ! m_elen ) return false; char *ext = m_extension; if ( to_lower_a(ext[0]) == 'c' && to_lower_a(ext[1]) == 's' && to_lower_a(ext[2]) == 's' ) return true; if ( to_lower_a(ext[0]) == 'm' && to_lower_a(ext[1]) == 'p' && to_lower_a(ext[2]) == 'g' ) return true; if ( to_lower_a(ext[0]) == 'p' && to_lower_a(ext[1]) == 'n' && to_lower_a(ext[2]) == 'g' ) return true; if ( to_lower_a(ext[0]) == 'w' && to_lower_a(ext[1]) == 'm' && to_lower_a(ext[2]) == 'v' ) return true; if ( to_lower_a(ext[0]) == 'w' && to_lower_a(ext[1]) == 'a' && to_lower_a(ext[2]) == 'v' ) return true; if ( to_lower_a(ext[0]) == 'j' && to_lower_a(ext[1]) == 'p' && to_lower_a(ext[2]) == 'g' ) return true; if ( to_lower_a(ext[0]) == 'g' && to_lower_a(ext[1]) == 'i' && to_lower_a(ext[2]) == 'f' ) return true; if ( to_lower_a(ext[0]) == 'i' && to_lower_a(ext[1]) == 'c' && to_lower_a(ext[2]) == 'o' ) return true; if ( to_lower_a(ext[0]) == 'm' && to_lower_a(ext[1]) == 'p' && to_lower_a(ext[2]) == '3' ) return true; if ( to_lower_a(ext[0]) == 'm' && to_lower_a(ext[1]) == 'p' && to_lower_a(ext[2]) == '4' ) return true; if ( to_lower_a(ext[0]) == 'm' && to_lower_a(ext[1]) == 'o' && to_lower_a(ext[2]) == 'v' ) return true; if ( to_lower_a(ext[0]) == 'a' && to_lower_a(ext[1]) == 'v' && to_lower_a(ext[2]) == 'i' ) return true; if ( to_lower_a(ext[0]) == 'm' && to_lower_a(ext[1]) == 'p' && to_lower_a(ext[2]) == 'e' && to_lower_a(ext[3]) == 'g' ) return true; if ( to_lower_a(ext[0]) == 'j' && to_lower_a(ext[1]) == 'p' && to_lower_a(ext[2]) == 'e' && to_lower_a(ext[3]) == 'g' ) return true; return false; } uint32_t Url::unitTests() { char* urls[] = { "http://сацминэнерго.рф/robots.txt", "http://www.fas.org/blog/ssp/2009/08/securing-venezuela\032s-arsenals.php", "http://topbeskæring.dk/velkommen", "www.Alliancefrançaise.nu", "française.Alliance.nu", "française.Alliance.nu/asdf", "http://française.Alliance.nu/asdf", "http://française.Alliance.nu/", "幸运.龍.com", "幸运.龍.com/asdf/运/abc", "幸运.龍.com/asdf", "http://幸运.龍.com/asdf", "http://Беларуская.org/Акадэмічная", "https://hi.Български.com", "https://fakedomain.中文.org/asdf", "https://gigablast.com/abc/文/efg", "https://gigablast.com/?q=文", "http://www.example.сайт", "http://genocidearchiverwanda.org.rw/index.php/Category:Official_Communiqués", "http://www.example.com/xn--fooled-you-into-trying-to-decode-this", "http://www.example.сайт/xn--fooled-you-into-trying-to-decode-this", "http://腕時計通販.jp/", // Lets check some bad urls too: "https://pypi.python\n\n\t\t\t\t.org/packages/source/p/pyramid/pyramid-1.5.tar.gz#md5=8747658dcbab709a9c491e43d3b0d58b" }; StackBuf(sb); uint32_t len = sizeof(urls) / sizeof(char*); for(uint32_t i = 0; i < len; i++) { Url u; u.set(urls[i], strlen(urls[i])); log("build:%s normalized to %s, printed to %s ", urls[i], u.getUrl(), Url::getDisplayUrl(u.getUrl(), &sb)); sb.reset(); } //FIXME: need to return an error if there is a problem return 0; } char* Url::getDisplayUrl(char* url, SafeBuf* sb) { char* found; char* labelCursor = url; if((found = strstr(labelCursor, "xn--"))) { sb->safeMemcpy(url, found - url); char* p = url; char* pend = url + gbstrlen(url); if(strncmp(p, "http://", 7) == 0) p += 7; else if(strncmp(p, "https://", 8) == 0) p += 8; while(p < pend && *p != '/') p++; char* domEnd = p; do { if(found > domEnd) { // Dont even look if it is past the domain break; } char* encodedStart = found + 4; uint32_t decoded [ MAX_URL_LEN]; size_t decodedLen = MAX_URL_LEN - 1 ; char* labelEnd = encodedStart; while( labelEnd < domEnd && *labelEnd != '/' && *labelEnd != '.' ) labelEnd++; punycode_status status = punycode_decode(labelEnd - encodedStart, encodedStart, &decodedLen, decoded, NULL); if(status != 0) { log("build: Bad Engineer, failed to depunycode international url %s", url); sb->safePrintf("%s", url); return url; } sb->utf32Encode(decoded, decodedLen); if(*labelEnd == '.') sb->pushChar(*labelEnd++); labelCursor = labelEnd; } while((found = strstr(labelCursor, "xn--"))); } // Copy in the rest sb->safePrintf("%s", labelCursor); sb->nullTerm(); return sb->getBufStart(); }
36,515
2,753
<gh_stars>1000+ #!/usr/bin/env python import shogun as sg from tools.load import LoadMatrix lm=LoadMatrix() traindat = lm.load_dna('../data/fm_train_dna.dat') testdat = lm.load_dna('../data/fm_test_dna.dat') parameter_list = [[traindat,testdat,5,5,1],[traindat,testdat,5,3,2]] def kernel_simple_locality_improved_string (fm_train_dna=traindat,fm_test_dna=testdat, length=5,inner_degree=5,outer_degree=1): feats_train=sg.create_string_features(fm_train_dna, sg.DNA) feats_test=sg.create_string_features(fm_test_dna, sg.DNA) kernel=sg.create_kernel("SimpleLocalityImprovedStringKernel", length=length, inner_degree=inner_degree, outer_degree=outer_degree) kernel.init(feats_train, feats_train) km_train=kernel.get_kernel_matrix() kernel.init(feats_train, feats_test) km_test=kernel.get_kernel_matrix() return km_train,km_test,kernel if __name__=='__main__': print('SimpleLocalityImprovedString') kernel_simple_locality_improved_string(*parameter_list[0])
379
1,275
<gh_stars>1000+ # Copyright (c) ZenML GmbH 2020. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing # permissions and limitations under the License. import logging import os import sys from logging.handlers import TimedRotatingFileHandler from typing import Any from absl import logging as absl_logging from zenml.constants import ZENML_LOGGING_VERBOSITY from zenml.enums import LoggingLevels from zenml.constants import ( # isort: skip ABSL_LOGGING_VERBOSITY, APP_NAME, ) FORMATTING_STRING = "%(asctime)s — %(name)s — %(levelname)s — %(message)s" FORMATTER = logging.Formatter(FORMATTING_STRING) LOG_FILE = f"{APP_NAME}_logs.log" def get_logging_level() -> LoggingLevels: """Get logging level from the env variable.""" verbosity = ZENML_LOGGING_VERBOSITY.upper() if verbosity not in LoggingLevels.__members__: raise KeyError( f"Verbosity must be one of {list(LoggingLevels.__members__.keys())}" ) return LoggingLevels[verbosity] def set_root_verbosity(): """Set the root verbosity.""" level = get_logging_level() if level != LoggingLevels.NOTSET: logging.basicConfig(level=level.value) get_logger(__name__).debug( f"Logging set to level: " f"{logging.getLevelName(level.value)}" ) else: logging.disable(sys.maxsize) logging.getLogger().disabled = True get_logger(__name__).debug("Logging NOTSET") def get_console_handler() -> Any: """Get console handler for logging.""" console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(FORMATTER) return console_handler def get_file_handler() -> Any: """Return a file handler for logging.""" file_handler = TimedRotatingFileHandler(LOG_FILE, when="midnight") file_handler.setFormatter(FORMATTER) return file_handler def get_logger(logger_name) -> Any: """Main function to get logger name,. Args: logger_name: Name of logger to initialize. Returns: A logger object. """ logger = logging.getLogger(logger_name) logger.setLevel(get_logging_level().value) logger.addHandler(get_console_handler()) # TODO: [LOW] Add a file handler for persistent handling # logger.addHandler(get_file_handler()) # with this pattern, it's rarely necessary to propagate the error up to # parent logger.propagate = False return logger def init_logging(): """Initialize logging with default levels.""" # Mute tensorflow cuda warnings os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" logging.basicConfig(format=FORMATTING_STRING) set_root_verbosity() # set absl logging absl_logging.set_verbosity(ABSL_LOGGING_VERBOSITY)
1,170
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SHARING_CLICK_TO_CALL_PHONE_NUMBER_REGEX_H_ #define CHROME_BROWSER_SHARING_CLICK_TO_CALL_PHONE_NUMBER_REGEX_H_ namespace re2 { class RE2; } // namespace re2 // Returns an RE2 instance to detect phone numbers. const re2::RE2& GetPhoneNumberRegex(); // Precompile regexes on a best effort task 15 seconds after startup. void PrecompilePhoneNumberRegexesAsync(); #endif // CHROME_BROWSER_SHARING_CLICK_TO_CALL_PHONE_NUMBER_REGEX_H_
242
3,212
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.cluster.protocol.impl; import org.apache.nifi.cluster.protocol.NodeProtocolSender; import org.apache.nifi.cluster.protocol.ProtocolException; import org.apache.nifi.cluster.protocol.ProtocolHandler; import org.apache.nifi.cluster.protocol.ProtocolListener; import org.apache.nifi.cluster.protocol.UnknownServiceAddressException; import org.apache.nifi.cluster.protocol.message.ClusterWorkloadRequestMessage; import org.apache.nifi.cluster.protocol.message.ClusterWorkloadResponseMessage; import org.apache.nifi.cluster.protocol.message.ConnectionRequestMessage; import org.apache.nifi.cluster.protocol.message.ConnectionResponseMessage; import org.apache.nifi.cluster.protocol.message.HeartbeatMessage; import org.apache.nifi.cluster.protocol.message.HeartbeatResponseMessage; import org.apache.nifi.reporting.BulletinRepository; import java.io.IOException; import java.util.Collection; public class NodeProtocolSenderListener implements NodeProtocolSender, ProtocolListener { private final NodeProtocolSender sender; private final ProtocolListener listener; public NodeProtocolSenderListener(final NodeProtocolSender sender, final ProtocolListener listener) { if (sender == null) { throw new IllegalArgumentException("NodeProtocolSender may not be null."); } else if (listener == null) { throw new IllegalArgumentException("ProtocolListener may not be null."); } this.sender = sender; this.listener = listener; } @Override public void stop() throws IOException { if (!isRunning()) { return; } listener.stop(); } @Override public void start() throws IOException { if (isRunning()) { return; } listener.start(); } @Override public boolean isRunning() { return listener.isRunning(); } @Override public boolean removeHandler(final ProtocolHandler handler) { return listener.removeHandler(handler); } @Override public Collection<ProtocolHandler> getHandlers() { return listener.getHandlers(); } @Override public void addHandler(final ProtocolHandler handler) { listener.addHandler(handler); } @Override public ConnectionResponseMessage requestConnection(final ConnectionRequestMessage msg, boolean allowConnectToSelf) throws ProtocolException, UnknownServiceAddressException { return sender.requestConnection(msg, allowConnectToSelf); } @Override public void setBulletinRepository(final BulletinRepository bulletinRepository) { listener.setBulletinRepository(bulletinRepository); } @Override public HeartbeatResponseMessage heartbeat(final HeartbeatMessage msg, final String address) throws ProtocolException { return sender.heartbeat(msg, address); } @Override public ClusterWorkloadResponseMessage clusterWorkload(ClusterWorkloadRequestMessage msg) throws ProtocolException { return sender.clusterWorkload(msg); } }
1,224
1,657
<filename>autoPyTorch/utils/benchmarking/benchmark_pipeline/set_ensemble_config.py from hpbandster.core.result import logged_results_to_HBS_result from autoPyTorch.pipeline.base.pipeline_node import PipelineNode from autoPyTorch.utils.config.config_option import ConfigOption, to_bool from autoPyTorch.utils.benchmarking.benchmark_pipeline.prepare_result_folder import get_run_result_dir from copy import copy import os import logging class SetEnsembleConfig(PipelineNode): def fit(self, pipeline_config, autonet, run_result_dir): parser = autonet.get_autonet_config_file_parser() autonet_config = parser.read(os.path.join(run_result_dir, "autonet.config")) if pipeline_config["ensemble_size"]: autonet_config["ensemble_size"] = pipeline_config["ensemble_size"] if pipeline_config["ensemble_only_consider_n_best"]: autonet_config["ensemble_only_consider_n_best"] = pipeline_config["ensemble_only_consider_n_best"] if pipeline_config["ensemble_sorted_initialization_n_best"]: autonet_config["ensemble_sorted_initialization_n_best"] = pipeline_config["ensemble_sorted_initialization_n_best"] autonet.autonet_config = autonet_config return {"result_dir": run_result_dir, "optimize_metric": autonet_config["optimize_metric"], "trajectories": []} def get_pipeline_config_options(self): options = [ ConfigOption('ensemble_size', default=0, type=int), ConfigOption('ensemble_only_consider_n_best', default=0, type=int), ConfigOption('ensemble_sorted_initialization_n_best', default=0, type=int) ] return options
699
302
<gh_stars>100-1000 /* * Copyright (C) 2015 RECRUIT LIFESTYLE CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.recruit_lifestyle.sample; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import jp.co.recruit_lifestyle.android.widget.PlayPauseButton; /** * @author amyu */ public class MainActivity extends AppCompatActivity { private MediaPlayer mMediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initMediaPlayer(); initView(); } private void initMediaPlayer() { mMediaPlayer = new MediaPlayer(); } private void initView() { final PlayPauseButton playPauseButton = (PlayPauseButton) findViewById(R.id.main_play_pause_button); playPauseButton.setOnControlStatusChangeListener( new PlayPauseButton.OnControlStatusChangeListener() { @Override public void onStatusChange(View view, boolean status) { if (status) { mMediaPlayer.start(); } else { mMediaPlayer.pause(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
823
1,144
<filename>backend/de.metas.swat/de.metas.swat.base/src/main/java/de/metas/inoutcandidate/api/impl/InOutCandidateBL.java package de.metas.inoutcandidate.api.impl; /* * #%L * de.metas.swat.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.math.BigDecimal; import org.adempiere.model.InterfaceWrapperHelper; import de.metas.inout.model.I_M_InOutLine; import de.metas.inoutcandidate.api.IInOutCandidateBL; import de.metas.inoutcandidate.api.InOutGenerateResult; import de.metas.inoutcandidate.spi.impl.ReceiptQty; import de.metas.product.ProductId; import de.metas.quantity.StockQtyAndUOMQty; import de.metas.quantity.StockQtyAndUOMQtys; import de.metas.uom.UomId; import de.metas.inoutcandidate.spi.impl.QualityNoticesCollection; public class InOutCandidateBL implements IInOutCandidateBL { @Override public InOutGenerateResult createEmptyInOutGenerateResult(final boolean storeReceipts) { return new DefaultInOutGenerateResult(storeReceipts); } @Override public ReceiptQty getQtyAndQuality(final org.compiere.model.I_M_InOutLine inoutLine0) { I_M_InOutLine inoutLine = InterfaceWrapperHelper.create(inoutLine0, I_M_InOutLine.class); final ProductId productId = ProductId.ofRepoId(inoutLine.getM_Product_ID()); // note: QtyEnetered and MovementQty are currently the same, but that's just because we are in the habit of setting M_InOutLine.C_UOM to the respective prodcuts stocking UOM. // therefore, we need to use MovementQty, unless we decide to add the UOM to this game, too (but currently i don't see the point). final BigDecimal qtyInUOM; final UomId uomId; final ReceiptQty qtys; if (InterfaceWrapperHelper.isNull(inoutLine, I_M_InOutLine.COLUMNNAME_QtyDeliveredCatch)) { qtyInUOM = null; uomId = null; qtys = ReceiptQty.newWithoutCatchWeight(productId); } else { qtyInUOM = inoutLine.getQtyDeliveredCatch(); uomId = UomId.ofRepoId(inoutLine.getCatch_UOM_ID()); qtys = ReceiptQty.newWithCatchWeight(productId, uomId); } final StockQtyAndUOMQty qtyMoved = StockQtyAndUOMQtys.create(inoutLine.getMovementQty(), productId, qtyInUOM, uomId); final StockQtyAndUOMQty qtyMovedWithIssues; if (inoutLine.isInDispute()) { qtyMovedWithIssues = qtyMoved; } else { qtyMovedWithIssues = qtyMoved.toZero(); } qtys.addQtyAndQtyWithIssues(qtyMoved, qtyMovedWithIssues); qtys.addQualityNotices(QualityNoticesCollection.valueOfQualityNoticesString(inoutLine.getQualityNote())); return qtys; } }
1,179
5,169
{ "name": "SwiftElegantDropdownMenu", "version": "0.1.4", "summary": "An elegant dropdown menu for Swift, that's easy to use.", "description": "This component provides an easy, configurable dropdown menu with the ability to place it anywhere. It comes with a simple item selected callback and a variety of configurable options. This component is inspired by the **BTNavigationDropdownMenu** from **PhamBaTho**.", "homepage": "https://github.com/arminlikic/SwiftElegantDropdownMenu", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/arminlikic/SwiftElegantDropdownMenu.git", "tag": "0.1.4" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "Pod/Classes/**/*", "screenshots": [ "https://raw.githubusercontent.com/arminlikic/SwiftElegantDropdownMenu/master/Assets/demo.gif" ], "resource_bundles": { "SwiftElegantDropdownMenu": [ "Pod/Assets/*.png" ] } }
366
432
<gh_stars>100-1000 [ { "slug": "grafana", "name": "Grafana", "description": "Graphite and InfluxDB dashboard and graph composer", "url": "http://grafana.org/", "tags": [ "linux", "open-source", "monitoring", "visualization" ] } ]
133
332
<reponame>Geertiebear/java-cef // Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. package org.cef.handler; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; /** * Implement this interface to handle events related to browser life span. The methods of this class * will be called on the UI thread unless otherwise indicated. */ public interface CefLifeSpanHandler { /** * Called on the IO thread before a new popup window is created. * @param browser The source of the popup request. * @param frame The source of the popup request. Instance only valid within the scope of this * method. * @param target_url May be empty if none is specified with the request. * @param target_frame_name May be empty if none is specified with the request. * @return True to cancel creation of the popup window or false to proceed. */ boolean onBeforePopup( CefBrowser browser, CefFrame frame, String target_url, String target_frame_name); /** * Handle creation of a new browser window. * @param browser The browser generating the event. */ void onAfterCreated(CefBrowser browser); /** * Called after a browser's native parent window has changed. * @param browser The browser generating the event. */ void onAfterParentChanged(CefBrowser browser); /** * Called when a browser has received a request to close. * * If CEF created an OS window for the browser returning false will send an OS close * notification to the browser window's top-level owner (e.g. WM_CLOSE on Windows, performClose: * on OS-X and "delete_event" on Linux). If no OS window exists (window rendering disabled) * returning false will cause the browser object to be destroyed immediately. Return true if the * browser is parented to another window and that other window needs to receive close * notification via some non-standard technique. * * @param browser The browser generating the event. * @return False to send an OS close notification to the browser window's top-level owner. */ boolean doClose(CefBrowser browser); /** * Called just before a browser is destroyed. * * Release all references to the browser object and do not attempt to execute any methods on the * browser object after this callback returns. If this is a modal window and a custom modal loop * implementation was provided in runModal() this callback should be used to exit the custom * modal loop. See doClose() documentation for additional usage information. * * @param browser The browser generating the event. */ void onBeforeClose(CefBrowser browser); }
848
1,162
<filename>digdag-cli/src/main/java/io/digdag/cli/Command.java package io.digdag.cli; import com.beust.jcommander.DynamicParameter; import com.beust.jcommander.Parameter; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import io.digdag.core.Environment; import io.digdag.client.Version; import io.digdag.core.config.PropertyUtils; import io.digdag.core.plugin.PluginSet; import io.digdag.core.plugin.LocalPluginLoader; import io.digdag.core.plugin.RemotePluginLoader; import io.digdag.core.plugin.Spec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.StringReader; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; public abstract class Command { private static final Logger log = LoggerFactory.getLogger(Command.class); @Inject @Environment protected Map<String, String> env; @Inject protected Version version; @Inject @ProgramName protected String programName; @Inject @StdIn protected InputStream in; @Inject @StdOut protected PrintStream out; @Inject @StdErr protected PrintStream err; @Parameter() protected List<String> args = new ArrayList<>(); @Parameter(names = {"-c", "--config"}) protected String configPath = null; @Parameter(names = {"-L", "--log"}) protected String logPath = "-"; @Parameter(names = {"-l", "--log-level"}) protected String logLevel = "info"; @DynamicParameter(names = "-X") protected Map<String, String> systemProperties = new HashMap<>(); @Parameter(names = {"-help", "--help"}, help = true, hidden = true) protected boolean help; public abstract void main() throws Exception; public abstract SystemExitException usage(String error); protected Properties loadSystemProperties() throws IOException { // Property order of precedence: // 1. Explicit configuration file (if --config was specified) // 2. JVM System properties (-D...) // 3. DIGDAG_CONFIG env var // 4. Default config file (unless --config was specified) // This order was chosen as the most "natural" ordering, reflecting the order in which // users may supply configuration properties to digdag. Generally properties specified "later" // should take precedence. Properties props = new Properties(); if (configPath == null) { // If no configuration file was specified, load the default configuration, if it exists. Path defaultConfigPath = ConfigUtil.defaultConfigPath(env); try { props.putAll(PropertyUtils.loadFile(defaultConfigPath)); } catch (NoSuchFileException ex) { log.trace("configuration file not found: {}", defaultConfigPath, ex); } } // Load properties from DIGDAG_CONFIG env props.load(new StringReader(env.getOrDefault("DIGDAG_CONFIG", ""))); // Load properties from system properties props.putAll(System.getProperties()); // Load explicit configuration file, if specified. if (configPath != null) { props.putAll(PropertyUtils.loadFile(Paths.get(configPath))); } return props; } protected PluginSet loadSystemPlugins(Properties systemProps) { // load plugins in classpath PluginSet localPlugins = new LocalPluginLoader().load(Command.class.getClassLoader()); // load plugins from remote repositories set at configuration Spec spec = Spec.of( ImmutableList.copyOf(PropertyUtils.toMap(systemProps, "system-plugin.repositories").values()), ImmutableList.copyOf(PropertyUtils.toMap(systemProps, "system-plugin.dependencies").values())); String localPath = systemProps.getProperty("system-plugin.local-path", ""); Path localRepositoryPath; if (localPath.equals("")) { localRepositoryPath = ConfigUtil.defaultLocalPluginPath(env); } else { localRepositoryPath = Paths.get(localPath); } PluginSet remotePlugins = new RemotePluginLoader(localRepositoryPath).load(spec); return localPlugins.withPlugins(remotePlugins); } }
1,637
4,538
src = Split(''' i2c_test.c ''') component = aos_component('i2c_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
62
1,755
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # This test reproduces an issue with vtkBandedPolyDataContourFilter # showing anomalous spikes from edges at which the difference between # end point scalar values is in the order of the internal tolerance # value. # # The ClipEdge method interpolates between two edge points, creating # extra points at the clip values. The method finds the iterators # b and e into the clip values vector for the edge points. # The clip value for the highest scalar value may be larger than the # end point scalar value. When the difference between the end point # values is very small this results in an interpolation factor # significantly larger than 1. # # The effect of this is that spikes appear extending # outside the original cell. # Scalars for contouring values = [ -10.0, -5e-6, -1e-6, -10.0, -7e-6, -1e-6, ] def generatePoly(scalars): """ Generate two quads and assign scalars 3--4--5 | | | 0--1--2 """ pts = vtk.vtkPoints() nx=3 ny=int(len(scalars)/nx) for y in range(0,ny): for x in range(0,nx): pts.InsertNextPoint(x,y,0) connectivity=[(0,1,4,3),(1,2,5,4)] quads = vtk.vtkCellArray() for quad in connectivity: quads.InsertNextCell(4,quad) poly = vtk.vtkPolyData() poly.SetPoints(pts) poly.SetPolys(quads) array=vtk.vtkDoubleArray() for s in scalars: array.InsertNextValue(s) poly.GetPointData().SetScalars(array) return poly def showBandedContours(poly,values,num): """ Generate banded contours """ high=max(values) low=min(values) bpdcf = vtk.vtkBandedPolyDataContourFilter() bpdcf.GenerateContourEdgesOn() bpdcf.SetScalarModeToValue() bpdcf.SetInputData(poly) bpdcf.GenerateValues(num,low,high) # The clip tolerance specifies a fraction of the scalar range # It is adjusted to reproduce the issue described bpdcf.SetClipTolerance(1e-6) bpdcf.SetScalarModeToIndex() #internalTol=bpdcf.GetClipTolerance()*(high-low) #print("internal clip tolerance={}".format(internalTol)) m = vtk.vtkPolyDataMapper() m.SetInputConnection(bpdcf.GetOutputPort()) m.SetScalarModeToUseCellData() m.SetScalarRange(0,num-1) bands = vtk.vtkActor() bands.SetMapper(m) m = vtk.vtkPolyDataMapper() m.SetInputConnection(bpdcf.GetOutputPort(1)) m.ScalarVisibilityOff() edges = vtk.vtkActor() edges.GetProperty().SetColor(.4,.4,.4) edges.SetMapper(m) return bands,edges def showPolyDataEdges(poly): edges=vtk.vtkExtractEdges() edges.SetInputDataObject(0,poly) m = vtk.vtkPolyDataMapper() m.SetInputConnection(edges.GetOutputPort()) m.ScalarVisibilityOff() a = vtk.vtkActor() a.GetProperty().SetColor(1,1,1) a.GetProperty().EdgeVisibilityOn() a.GetProperty().RenderLinesAsTubesOn() a.SetMapper(m) return a poly=generatePoly(values) inbounds=poly.GetBounds() bands,edges = showBandedContours(poly,values,6) bands.GetMapper().Update() # The bounds of the output of vtkBandedPolyDataContourFilter # are expected not to exceed those of its input outbounds=bands.GetMapper().GetInputDataObject(0,0).GetBounds() error=0 if (inbounds[0] > outbounds[0] or inbounds[1] < outbounds[1] or inbounds[2] > outbounds[2] or inbounds[3] < outbounds[3] or inbounds[4] > outbounds[4] or inbounds[5] < outbounds[5]): print("Output bounds exceed input bounds") print("input bounds={}".format(inbounds)) print("output bounds={}".format(outbounds)) error=1 ren = vtk.vtkRenderer() ren.AddViewProp( bands ) ren.AddViewProp( edges ) ren.AddViewProp( showPolyDataEdges(poly) ) ren.SetBackground(.6,.6,.6) renWin = vtk.vtkRenderWindow() renWin.AddRenderer( ren ) ren.GetActiveCamera().SetFocalPoint(1,.5,0) ren.GetActiveCamera().SetPosition(1,.5,5) ren.GetActiveCamera().SetViewUp(0,1,0) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Start()
1,570
2,030
import unittest from unittest.mock import Mock from kaggle_gcp import KaggleKernelCredentials, init_ucaip from test.support import EnvironmentVarGuard def _make_credentials(): import google.auth.credentials return Mock(spec=google.auth.credentials.Credentials) class TestUcaip(unittest.TestCase): def test_user_provided_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'CLOUDAI') with env: from google.cloud import aiplatform init_ucaip() aiplatform.init(credentials=credentials) self.assertNotIsInstance(aiplatform.initializer.global_config.credentials, KaggleKernelCredentials) self.assertIsNotNone(aiplatform.initializer.global_config.credentials)
364
1,178
package kg.ash.javavi.readers.source; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.ConstructorDeclaration; import com.github.javaparser.ast.body.FieldDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.body.Parameter; import com.github.javaparser.ast.expr.AnnotationExpr; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.FieldAccessExpr; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.Name; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.ast.type.Type; import com.github.javaparser.ast.type.UnionType; import com.github.javaparser.ast.visitor.TreeVisitor; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import com.github.javaparser.printer.PrettyPrinterConfiguration; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ClassNamesFetcher { private final CompilationUnit compilationUnit; private final Set<String> resultList = new HashSet<>(); private final Set<String> declarationList = new HashSet<>(); private List<String> staticImportsList = new ArrayList<>(); public static PrettyPrinterConfiguration withoutComments() { PrettyPrinterConfiguration pp = new PrettyPrinterConfiguration(); pp.setPrintComments(false); return pp; } public ClassNamesFetcher(CompilationUnit compilationUnit) { this.compilationUnit = compilationUnit; for (ImportDeclaration id : compilationUnit.getImports()) { if (id.isStatic()) { String name = id.getName().toString(); staticImportsList.add( name.substring( name.lastIndexOf(".") + 1, name.length())); } } } @SuppressWarnings("unchecked") public Set<String> getNames() { List<VoidVisitorAdapter> adapters = new ArrayList<>(); adapters.add(new ClassTypeVisitor()); adapters.add(new TypesVisitor()); adapters.add(new AnnotationsVisitor()); adapters.forEach(a -> a.visit(compilationUnit, null)); return resultList; } public Set<String> getDeclarationList() { if (resultList.isEmpty()) { getNames(); } return declarationList; } private class ClassTypeVisitor extends VoidVisitorAdapter<Object> { @Override public void visit(ClassOrInterfaceDeclaration type, Object arg) { new DeepVisitor(this, arg).visitBreadthFirst(type); if (type.getAnnotations() != null) { for (AnnotationExpr expr : type.getAnnotations()) { resultList.add(expr.getNameAsString()); List<Node> children = expr.getChildNodes(); for (Node node : children.subList(1, children.size())) { new DeepVisitor(this, arg).visitBreadthFirst(node); } } } } } private class AnnotationsVisitor extends VoidVisitorAdapter<Object> { private void addAnnotations( List<AnnotationExpr> annotations, Object arg) { if (annotations != null) { for (AnnotationExpr expr : annotations) { resultList.add(expr.getNameAsString()); List<Node> children = expr.getChildNodes(); for (Node node : children.subList(1, children.size())) { new DeepVisitor(this, arg).visitBreadthFirst(node); } } } } @Override public void visit(ConstructorDeclaration type, Object arg) { addAnnotations(type.getAnnotations(), arg); } @Override public void visit(FieldDeclaration type, Object arg) { addAnnotations(type.getAnnotations(), arg); } @Override public void visit(MethodDeclaration type, Object arg) { addAnnotations(type.getAnnotations(), arg); if (type.getParameters() != null) { for (Parameter param : type.getParameters()) { addAnnotations(param.getAnnotations(), arg); } } if (type.getThrownExceptions() != null) { for (Type expr : type.getThrownExceptions()) { resultList.add(expr.toString(withoutComments())); } } } } private class TypesVisitor extends VoidVisitorAdapter<Object> { @Override public void visit(BlockStmt type, Object arg) { new DeepVisitor(this, arg).visitBreadthFirst(type); } @Override public void visit(FieldAccessExpr type, Object arg) { addStatic(type); } @Override public void visit(MethodCallExpr type, Object arg) { addStatic(type); } private void addStatic(Expression type) { if (type.getChildNodes() != null && type.getChildNodes().size() > 0) { String name = type.getChildNodes(). get(0).toString(withoutComments()); if (!name.contains(".")) { resultList.add(name); } } } @Override public void visit(ClassOrInterfaceType type, Object arg) { String name = type.getNameAsString(); String fullName = type.toString(withoutComments()); if (!fullName.startsWith(name)) { if (!type.getChildNodes().isEmpty()) { name = type.getChildNodes(). get(0).toString(withoutComments()); } } if (name.contains(".")) { name = name.split("\\.")[0]; } resultList.add(name); if (type.getTypeArguments().isPresent()) { for (Type t : type.getTypeArguments().get()) { String typeName = t.toString(withoutComments()); if (typeName.contains(".")) { typeName = typeName.split("\\.")[0]; } resultList.add(typeName); } } } } private class DeepVisitor extends TreeVisitor { private VoidVisitorAdapter<Object> adapter; private Object arg; public DeepVisitor(VoidVisitorAdapter<Object> adapter, Object arg) { this.adapter = adapter; this.arg = arg; } public void process(Node node) { if (node instanceof ClassOrInterfaceType) { adapter.visit((ClassOrInterfaceType) node, arg); } else if (node instanceof UnionType) { ((UnionType) node).getElements() .forEach( t -> resultList.add( t.toString(withoutComments()))); } else if (node instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) node); String name = methodCall.getNameAsString(); if (staticImportsList.contains(name)) { resultList.add(name); } } else if (node instanceof NameExpr) { // javaparser has no difference on 'method call' expression, // so class name with static method call look the same as // object method call. that's why we check here for usual // class name type with upper case letter at the beginning. // it can miss some unusual class names with lower case at // the beginning. NameExpr nameExpr = (NameExpr) node; String parent = ""; if (nameExpr.getParentNode().isPresent()) { parent = nameExpr.getParentNode(). get().toString(withoutComments()); } String name = nameExpr.getNameAsString(); if (name != null) { if (!parent.startsWith("@") && !parent.equals(name) && parent.endsWith(name)) { return; } if (name.matches("^[A-Z][A-Za-z0-9_]*")) { resultList.add(name); } } } else if (node instanceof Name) { String name = node.toString(withoutComments()); if (name.matches("^[A-Z][A-Za-z0-9_]*")) { resultList.add(name); } } else if (node instanceof ClassOrInterfaceDeclaration) { ClassOrInterfaceDeclaration declaration = (ClassOrInterfaceDeclaration) node; declarationList.add( declaration.getName().toString( withoutComments())); } } } }
4,599
605
<reponame>LaudateCorpus1/llvm-project<gh_stars>100-1000 // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve -fopenmp -x c -emit-llvm %s -o - -femit-all-decls | FileCheck %s // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve -fopenmp-simd -x c -emit-llvm %s -o - -femit-all-decls | FileCheck %s // REQUIRES: aarch64-registered-target // Note: -fopemp and -fopenmp-simd behavior are expected to be the same. // This test checks the values of Widest Data Size (WDS), as defined // in https://github.com/ARM-software/abi-aa/tree/main/vfabia64 // // WDS is used to check the accepted values <N> of `simdlen(<N>)` when // targeting fixed-length SVE vector function names. The values of // `<N>` that are accepted are such that for X = WDS * <N> * 8, // 128-bit <= X <= 2048-bit and X is a multiple of 128-bit. #pragma omp declare simd simdlen(8) #pragma omp declare simd simdlen(16) #pragma omp declare simd simdlen(256) #pragma omp declare simd simdlen(272) char WDS_is_sizeof_char(char in); // WDS = 1, simdlen(8) and simdlen(272) are not generated. // CHECK-DAG: _ZGVsM16v_WDS_is_sizeof_char // CHECK-DAG: _ZGVsM256v_WDS_is_sizeof_char // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_char #pragma omp declare simd simdlen(4) #pragma omp declare simd simdlen(8) #pragma omp declare simd simdlen(128) #pragma omp declare simd simdlen(136) char WDS_is_sizeof_short(short in); // WDS = 2, simdlen(4) and simdlen(136) are not generated. // CHECK-DAG: _ZGVsM8v_WDS_is_sizeof_short // CHECK-DAG: _ZGVsM128v_WDS_is_sizeof_short // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_short #pragma omp declare simd linear(sin) notinbranch simdlen(2) #pragma omp declare simd linear(sin) notinbranch simdlen(4) #pragma omp declare simd linear(sin) notinbranch simdlen(64) #pragma omp declare simd linear(sin) notinbranch simdlen(68) void WDS_is_sizeof_float_pointee(float in, float *sin); // WDS = 4, simdlen(2) and simdlen(68) are not generated. // CHECK-DAG: _ZGVsM4vl4_WDS_is_sizeof_float_pointee // CHECK-DAG: _ZGVsM64vl4_WDS_is_sizeof_float_pointee // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_float_pointee #pragma omp declare simd linear(sin) notinbranch simdlen(2) #pragma omp declare simd linear(sin) notinbranch simdlen(4) #pragma omp declare simd linear(sin) notinbranch simdlen(32) #pragma omp declare simd linear(sin) notinbranch simdlen(34) void WDS_is_sizeof_double_pointee(float in, double *sin); // WDS = 8 because of the linear clause, simdlen(34) is not generated. // CHECK-DAG: _ZGVsM2vl8_WDS_is_sizeof_double_pointee // CHECK-DAG: _ZGVsM4vl8_WDS_is_sizeof_double_pointee // CHECK-DAG: _ZGVsM32vl8_WDS_is_sizeof_double_pointee // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_double_pointee #pragma omp declare simd simdlen(2) #pragma omp declare simd simdlen(4) #pragma omp declare simd simdlen(32) #pragma omp declare simd simdlen(34) double WDS_is_sizeof_double(double in); // WDS = 8, simdlen(34) is not generated. // CHECK-DAG: _ZGVsM2v_WDS_is_sizeof_double // CHECK-DAG: _ZGVsM4v_WDS_is_sizeof_double // CHECK-DAG: _ZGVsM32v_WDS_is_sizeof_double // CHECK-NOT: _ZGV{{.*}}_WDS_is_sizeof_double static char C; static short S; static float F; static double D; void do_something() { C = WDS_is_sizeof_char(C); C = WDS_is_sizeof_short(S); WDS_is_sizeof_float_pointee(F, &F); WDS_is_sizeof_double_pointee(F, &D); D = WDS_is_sizeof_double(D); }
1,473
10,225
<filename>independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapWagonConfigurator.java package io.quarkus.bootstrap.resolver.maven; import org.apache.maven.wagon.Wagon; import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.converters.lookup.DefaultConverterLookup; import org.codehaus.plexus.component.configurator.expression.DefaultExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.aether.transport.wagon.WagonConfigurator; public class BootstrapWagonConfigurator implements WagonConfigurator { private static final ExpressionEvaluator DEFAULT_EXPRESSION_EVALUATOR = new DefaultExpressionEvaluator(); protected ConverterLookup converterLookup = new DefaultConverterLookup(); @Override public void configure(Wagon wagon, Object configuration) throws Exception { PlexusConfiguration config; if (configuration instanceof PlexusConfiguration) { config = (PlexusConfiguration) configuration; } else if (configuration instanceof Xpp3Dom) { config = new XmlPlexusConfiguration((Xpp3Dom) configuration); } else if (configuration == null) { return; } else { throw new IllegalArgumentException("unexpected configuration type: " + configuration.getClass().getName()); } final ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration(converterLookup, wagon, null, config, DEFAULT_EXPRESSION_EVALUATOR, null); } }
677
1,171
# # Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by <NAME> <<EMAIL>> # """Implement local context attention.""" from math import sqrt import torch from torch.nn import Module, Dropout from torch.nn import functional as F from ..attention_registry import AttentionRegistry, Optional, Int, Float, \ EventDispatcherInstance from ..events import EventDispatcher from ..local_product import local_dot_product, local_weighted_average class LocalAttention(Module): """Implement fast local attention where a query can only attend to neighboring keys. In this attention module the query Q_i can only attend to a key K_j if |i-j| < local_context/2. Arguments --------- local_context: The neighborhood to consider for local attention. softmax_temp: The temperature to use for the softmax attention. (default: 1/sqrt(d_keys) where d_keys is computed at runtime) attention_dropout: The dropout rate to apply to the attention (default: 0.1) event_dispatcher: str or EventDispatcher instance to be used by this module for dispatching events (default: the default global dispatcher) """ def __init__(self, local_context, softmax_temp=None, attention_dropout=0.1, event_dispatcher=""): super(LocalAttention, self).__init__() self.local_context = local_context self.softmax_temp = softmax_temp self.dropout = Dropout(attention_dropout) self.event_dispatcher = EventDispatcher.get(event_dispatcher) def forward(self, queries, keys, values, attn_mask, query_lengths, key_lengths): """Implements the local attention. The attn_mask can be anything but the only values that will be considered will be the ones in the neighborhood of each query. Arguments --------- queries: (N, L, H, E) The tensor containing the queries keys: (N, S, H, E) The tensor containing the keys values: (N, S, H, D) The tensor containing the values attn_mask: An implementation of BaseMask that encodes where each query can attend to query_lengths: An implementation of BaseMask that encodes how many queries each sequence in the batch consists of key_lengths: An implementation of BaseMask that encodes how many queries each sequence in the batch consists of """ # Extract some shapes and compute the temperature N, L, H, E = queries.shape _, S, _, D = values.shape context = self.local_context softmax_temp = self.softmax_temp or 1./sqrt(E) # Permute the dimensions to NHLE instead of NLHE queries = queries.permute(0, 2, 1, 3).contiguous() keys = keys.permute(0, 2, 1, 3).contiguous() values = values.permute(0, 2, 1, 3).contiguous() QK = local_dot_product( queries, keys, attn_mask.additive_matrix_finite, key_lengths.lengths, self.local_context ) A = self.dropout(torch.softmax(softmax_temp * QK, dim=-1)) V_new = local_weighted_average(A, values) return V_new.permute(0, 2, 1, 3).contiguous() # Register the attention implementation so that it becomes available in our # builders AttentionRegistry.register( "local", LocalAttention, [ ("local_context", Int), ("softmax_temp", Optional(Float)), ("attention_dropout", Optional(Float, 0.1)), ("event_dispatcher", Optional(EventDispatcherInstance, "")) ] )
1,561
5,937
<reponame>jonfortescue/wpf<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "Win32Inc.hpp" #include "src\PrintQueue.cpp" #include "src\PrintSystemAttributeValueFactory.cpp" #include "src\PrintSystemNotifications.cpp" #include "src\PrintSystemAttributeValue.cpp" #include "src\PrintSystemUtil.cpp" #include "src\PrintSystemObject.cpp" #include "src\PrintSystemObjectFactory.cpp" #include "src\Driver.cpp" #include "src\Filter.cpp" #include "src\PrintProcessor.cpp" #include "src\Port.cpp" #include "src\ObjectsAttributesValuesFactory.cpp" #include "src\PrintServer.cpp" #include "src\InteropPrinterDefaults.cpp" #include "src\InteropDocInfo.cpp" #include "src\InteropDevMode.cpp" #include "src\InteropPrinterInfo.cpp" #include "src\InteropDriverInfo.cpp" #include "src\InteropInfoLevelProfile.cpp" #include "src\InteropJobInfo.cpp" #include "src\InteropAddJobInfo.cpp" #include "src\GenericTypeMappings.cpp" #include "src\GenericPrinterThunkFilter.cpp" #include "src\GenericPrinterLevelThunk.cpp" #include "src\GenericDriverThunkFilter.cpp" #include "src\GenericDriverLevelThunk.cpp" #include "src\GenericJobLevelThunk.cpp" #include "src\GenericJobThunkFilter.cpp" #include "src\GetDataThunkObject.cpp" #include "src\SetDataThunkObject.cpp" #include "src\EnumDataThunkObject.cpp" #include "src\InteropLevelCoverageList.cpp" #include "src\InteropPrinterInfoUnmanagedBuilder.cpp" #include "src\InteropPrinterHandler.cpp" #include "src\XpsDeviceSimulatingInteropPrinterHandler.cpp" #include "src\XpsCompatiblePrinter.cpp" #include "src\InternalPrintSystemException.cpp" #include "src\PrintSystemPathResolver.cpp" #include "src\LocalPrintServer.cpp" #include "src\PrintSystemAssemblyInfo.cpp" #include "src\PrintSystemJobInfo.cpp" #include "src\LegacyDevice.cpp" #include "src\GDIExporter.cpp" #include "src\XPSDocumentWriter.cpp" #include "src\PremiumPrintStream.cpp" #include "src\PrintJobSettings.cpp" #include "src\PrintDocumentImageableArea.cpp" #include "src\InteropAttributeValueDictionary.cpp"
729