repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
gaizkadc/public-api
|
cmd/public-api-cli/commands/variables.go
|
/*
* Copyright 2020 Nalej
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This file contains the variables that are used through the commands.
package commands
var loginPort int
var email string
var password string
var publicKeyPath string
var title string
var phone string
var location string
var lastName string
var key string
var value string
// organization update
var address string
var city string
var state string
var country string
var zipCode string
var photoPath string
var name string
var roleID string
var organizationID string
var clusterID string
var username string
var privateKeyPath string
var kubeConfigPath string
var hostname string
var nodes []string
var targetPlatform string
var useStaticIPAddresses bool
var ipAddressIngress string
var descriptorID string
var descriptorPath string
var params string
var connections string
var instanceID string
var sgInstanceID string
var sgID string
var serviceID string
var serviceInstanceID string
var internal bool
var exampleName string
var storageType string
var enabled bool
var disabled bool
var enabledDefaultConnectivity bool
var disabledDefaultConnectivity bool
var deviceGroupID string
var deviceID string
var rawLabels string
var nodeID string
var message string
var from string
var to string
var redirectLog bool
var desc bool
var follow bool
var nFirst bool
var metadata bool
var rangeMinutes int32
var clusterStatFields string
var watch bool
// cluster update
var millicoresConversionFactor float64
var clusterName string
var orderBy string
var outputPath string
var edgeControllerID string
var assetID string
var activate bool
var geolocation string
var assetDeviceId string
var force bool
var agentTypeRaw string
var sudoer bool
var sourceInstanceID string
var targetInstanceID string
var inbound string
var outbound string
var requestId string
var provisionClusterName string
var provisionAzureCredentialsPath string
var provisionAzureDnsZoneName string
var provisionAzureResourceGroup string
var provisionClusterType string
var provisionIsProductionCluster bool
var provisionKubernetesVersion string
var provisionNodeType string
var provisionNumNodes int
var provisionTargetPlatform string
var provisionZone string
var provisionKubeConfigOutputPath string
|
mkrmpotic/SignMeApp
|
src/eu/signme/app/api/response/LoginResponse.java
|
<filename>src/eu/signme/app/api/response/LoginResponse.java
package eu.signme.app.api.response;
public class LoginResponse {
private String token;
private String name;
private int id;
private int beers;
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getBeers() {
return this.beers;
}
public void setBeers(int beers) {
this.beers = beers;
}
}
|
jmswen/eden
|
eden/fs/utils/test/LazyInitializeTest.cpp
|
<gh_stars>0
/*
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "eden/fs/utils/LazyInitialize.h"
#include <gtest/gtest.h>
using namespace facebook::eden;
template <typename T>
using SynchronizedSharedPtr = folly::Synchronized<std::shared_ptr<T>>;
auto unimplemented = []() -> std::shared_ptr<std::string> {
throw std::runtime_error("unimplemented!");
};
TEST(LazyInitializeTest, returnValue) {
SynchronizedSharedPtr<std::string> ptr(
std::make_shared<std::string>("hello"));
auto result = lazyInitialize(true, ptr, unimplemented);
EXPECT_EQ(result->compare("hello"), 0);
}
TEST(LazyInitializeTest, returnNull) {
SynchronizedSharedPtr<std::string> ptr(nullptr);
auto result = lazyInitialize(false, ptr, unimplemented);
EXPECT_EQ(result, nullptr);
}
TEST(LazyInitializeTest, initialize) {
SynchronizedSharedPtr<std::string> ptr(nullptr);
auto result = lazyInitialize(
true, ptr, []() { return std::make_shared<std::string>("called"); });
EXPECT_EQ(result->compare("called"), 0);
// another check to make sure it won't initialize twice
lazyInitialize(true, ptr, unimplemented);
}
TEST(LazyInitializeTest, deletePtr) {
SynchronizedSharedPtr<std::string> ptr(
std::make_shared<std::string>("hello"));
auto result = lazyInitialize(false, ptr, unimplemented);
EXPECT_EQ(result, nullptr);
EXPECT_EQ(*ptr.rlock(), nullptr);
}
|
markovandooren/jnome
|
src/org/aikodi/java/tool/Tool.java
|
package org.aikodi.java.tool;
public abstract class Tool {
public Tool(String name) {
_name = name;
}
/**
* Execute this tool with the given arguments.
*
* @param arguments The arguments for this tool.
* The array cannot be null.
*/
public abstract void execute(String[] arguments);
private String _name;
public String name() {
return _name;
}
}
|
testuser-aj/temptest
|
gcloud-java-core/src/main/java/com/google/gcloud/AuthCredentials.java
|
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gcloud;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.compute.ComputeCredential;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.util.Objects;
import java.util.Set;
/**
* Credentials for accessing Google Cloud services.
*/
public abstract class AuthCredentials implements Serializable {
private static final long serialVersionUID = 236297804453464604L;
private static class AppEngineAuthCredentials extends AuthCredentials {
private static final long serialVersionUID = 7931300552744202954L;
private static final AuthCredentials INSTANCE = new AppEngineAuthCredentials();
@Override
protected HttpRequestInitializer httpRequestInitializer(HttpTransport transport,
Set<String> scopes) {
return new AppIdentityCredential(scopes);
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
public static class ServiceAccountAuthCredentials extends AuthCredentials {
private static final long serialVersionUID = 8007708734318445901L;
private final String account;
private final PrivateKey privateKey;
private static final AuthCredentials NO_CREDENTIALS = new ServiceAccountAuthCredentials();
ServiceAccountAuthCredentials(String account, PrivateKey privateKey) {
this.account = checkNotNull(account);
this.privateKey = checkNotNull(privateKey);
}
ServiceAccountAuthCredentials() {
account = null;
privateKey = null;
}
@Override
protected HttpRequestInitializer httpRequestInitializer(
HttpTransport transport, Set<String> scopes) {
GoogleCredential.Builder builder = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(new JacksonFactory());
if (privateKey != null) {
builder.setServiceAccountPrivateKey(privateKey);
builder.setServiceAccountId(account);
builder.setServiceAccountScopes(scopes);
}
return builder.build();
}
public String account() {
return account;
}
public PrivateKey privateKey() {
return privateKey;
}
@Override
public int hashCode() {
return Objects.hash(account, privateKey);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ServiceAccountAuthCredentials)) {
return false;
}
ServiceAccountAuthCredentials other = (ServiceAccountAuthCredentials) obj;
return Objects.equals(account, other.account)
&& Objects.equals(privateKey, other.privateKey);
}
}
private static class ComputeEngineAuthCredentials extends AuthCredentials {
private static final long serialVersionUID = -5217355402127260144L;
private transient ComputeCredential computeCredential;
ComputeEngineAuthCredentials() throws IOException, GeneralSecurityException {
computeCredential = getComputeCredential();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
try {
computeCredential = getComputeCredential();
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
@Override
protected HttpRequestInitializer httpRequestInitializer(HttpTransport transport,
Set<String> scopes) {
return computeCredential;
}
}
private static class ApplicationDefaultAuthCredentials extends AuthCredentials {
private static final long serialVersionUID = -8306873864136099893L;
private transient GoogleCredentials googleCredentials;
ApplicationDefaultAuthCredentials() throws IOException {
googleCredentials = GoogleCredentials.getApplicationDefault();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
googleCredentials = GoogleCredentials.getApplicationDefault();
}
@Override
protected HttpRequestInitializer httpRequestInitializer(HttpTransport transport,
Set<String> scopes) {
return new HttpCredentialsAdapter(googleCredentials);
}
}
protected abstract HttpRequestInitializer httpRequestInitializer(HttpTransport transport,
Set<String> scopes);
public static AuthCredentials createForAppEngine() {
return AppEngineAuthCredentials.INSTANCE;
}
public static AuthCredentials createForComputeEngine()
throws IOException, GeneralSecurityException {
return new ComputeEngineAuthCredentials();
}
/**
* Returns the Application Default Credentials.
*
* <p>Returns the Application Default Credentials which are credentials that identify and
* authorize the whole application. This is the built-in service account if running on
* Google Compute Engine or the credentials file from the path in the environment variable
* GOOGLE_APPLICATION_CREDENTIALS.
* </p>
*
* @return the credentials instance.
* @throws IOException if the credentials cannot be created in the current environment.
*/
public static AuthCredentials createApplicationDefaults() throws IOException {
return new ApplicationDefaultAuthCredentials();
}
public static ServiceAccountAuthCredentials createFor(String account, PrivateKey privateKey) {
return new ServiceAccountAuthCredentials(account, privateKey);
}
public static AuthCredentials noCredentials() {
return ServiceAccountAuthCredentials.NO_CREDENTIALS;
}
static ComputeCredential getComputeCredential() throws IOException, GeneralSecurityException {
NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
// Try to connect using Google Compute Engine service account credentials.
ComputeCredential credential = new ComputeCredential(transport, new JacksonFactory());
// Force token refresh to detect if we are running on Google Compute Engine.
credential.refreshToken();
return credential;
}
}
|
nicknameismos/coffeehub-server
|
modules/categoryshops/client/config/categoryshops.client.routes.js
|
(function () {
'use strict';
angular
.module('categoryshops')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('categoryshops', {
abstract: true,
url: '/categoryshops',
template: '<ui-view/>'
})
.state('categoryshops.list', {
url: '',
templateUrl: 'modules/categoryshops/client/views/list-categoryshops.client.view.html',
controller: 'CategoryshopsListController',
controllerAs: 'vm',
data: {
pageTitle: 'Categoryshops List'
}
})
.state('categoryshops.create', {
url: '/create',
templateUrl: 'modules/categoryshops/client/views/form-categoryshop.client.view.html',
controller: 'CategoryshopsController',
controllerAs: 'vm',
resolve: {
categoryshopResolve: newCategoryshop
},
data: {
roles: ['user', 'admin'],
pageTitle: 'Categoryshops Create'
}
})
.state('categoryshops.edit', {
url: '/:categoryshopId/edit',
templateUrl: 'modules/categoryshops/client/views/form-categoryshop.client.view.html',
controller: 'CategoryshopsController',
controllerAs: 'vm',
resolve: {
categoryshopResolve: getCategoryshop
},
data: {
roles: ['user', 'admin'],
pageTitle: 'Edit Categoryshop {{ categoryshopResolve.name }}'
}
})
.state('categoryshops.view', {
url: '/:categoryshopId',
templateUrl: 'modules/categoryshops/client/views/view-categoryshop.client.view.html',
controller: 'CategoryshopsController',
controllerAs: 'vm',
resolve: {
categoryshopResolve: getCategoryshop
},
data: {
pageTitle: 'Categoryshop {{ categoryshopResolve.name }}'
}
});
}
getCategoryshop.$inject = ['$stateParams', 'CategoryshopsService'];
function getCategoryshop($stateParams, CategoryshopsService) {
return CategoryshopsService.get({
categoryshopId: $stateParams.categoryshopId
}).$promise;
}
newCategoryshop.$inject = ['CategoryshopsService'];
function newCategoryshop(CategoryshopsService) {
return new CategoryshopsService();
}
}());
|
haojunliu/OpenFPGA
|
vtr/toro/TAS_ArchitectureSpec/TAS_TimingDelay.cxx
|
//===========================================================================//
// Purpose : Method definitions for the TAS_TimingDelay class.
//
// Public methods include:
// - TAS_TimingDelay_c, ~TAS_TimingDelay_c
// - operator=
// - operator==, operator!=
// - Print
// - PrintXML
//
//===========================================================================//
//---------------------------------------------------------------------------//
// Copyright (C) 2012 <NAME>, Texas Instruments (<EMAIL>) //
// //
// 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; version 3 of the License, or any later version. //
// //
// This program is distributed in the hope that it will be useful, but //
// WITHOUT ANY WARRANTY; without even an implied warranty of MERCHANTABILITY //
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License //
// for more details. //
// //
// You should have received a copy of the GNU General Public License along //
// with this program; if not, see <http://www.gnu.org/licenses>. //
//---------------------------------------------------------------------------//
#include "TC_MinGrid.h"
#include "TCT_Generic.h"
#include "TIO_PrintHandler.h"
#include "TAS_StringUtils.h"
#include "TAS_TimingDelay.h"
//===========================================================================//
// Method : TAS_TimingDelay_c
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
TAS_TimingDelay_c::TAS_TimingDelay_c(
void )
:
mode( TAS_TIMING_MODE_UNDEFINED ),
type( TAS_TIMING_TYPE_UNDEFINED ),
valueMin( 0.0 ),
valueMax( 0.0 ),
valueNom( 0.0 ),
valueMatrix( TAS_TIMING_VALUE_MATRIX_DEF_CAPACITY,
TAS_TIMING_VALUE_MATRIX_DEF_CAPACITY )
{
}
//===========================================================================//
TAS_TimingDelay_c::TAS_TimingDelay_c(
const TAS_TimingDelay_c& timingDelay )
:
mode( timingDelay.mode ),
type( timingDelay.type ),
valueMin( timingDelay.valueMin ),
valueMax( timingDelay.valueMax ),
valueNom( timingDelay.valueNom ),
valueMatrix( timingDelay.valueMatrix ),
srInputPortName( timingDelay.srInputPortName ),
srOutputPortName( timingDelay.srOutputPortName ),
srClockPortName( timingDelay.srClockPortName ),
srPackPatternName( timingDelay.srPackPatternName )
{
}
//===========================================================================//
// Method : ~TAS_TimingDelay_c
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
TAS_TimingDelay_c::~TAS_TimingDelay_c(
void )
{
}
//===========================================================================//
// Method : operator=
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
TAS_TimingDelay_c& TAS_TimingDelay_c::operator=(
const TAS_TimingDelay_c& timingDelay )
{
if( &timingDelay != this )
{
this->mode = timingDelay.mode;
this->type = timingDelay.type;
this->valueMin = timingDelay.valueMin;
this->valueMax = timingDelay.valueMax;
this->valueNom = timingDelay.valueNom;
this->valueMatrix = timingDelay.valueMatrix;
this->srInputPortName = timingDelay.srInputPortName;
this->srOutputPortName = timingDelay.srOutputPortName;
this->srClockPortName = timingDelay.srClockPortName;
this->srPackPatternName = timingDelay.srPackPatternName;
}
return( *this );
}
//===========================================================================//
// Method : operator==
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
bool TAS_TimingDelay_c::operator==(
const TAS_TimingDelay_c& timingDelay ) const
{
return(( this->mode == timingDelay.mode ) &&
( this->type == timingDelay.type ) &&
( TCTF_IsEQ( this->valueMin, timingDelay.valueMin )) &&
( TCTF_IsEQ( this->valueMax, timingDelay.valueMax )) &&
( TCTF_IsEQ( this->valueNom, timingDelay.valueNom )) &&
( this->valueMatrix == timingDelay.valueMatrix ) &&
( this->srInputPortName == timingDelay.srInputPortName ) &&
( this->srOutputPortName == timingDelay.srOutputPortName ) &&
( this->srClockPortName == timingDelay.srClockPortName ) &&
( this->srPackPatternName == timingDelay.srPackPatternName ) ?
true : false );
}
//===========================================================================//
// Method : operator!=
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
bool TAS_TimingDelay_c::operator!=(
const TAS_TimingDelay_c& timingDelay ) const
{
return( !this->operator==( timingDelay ) ? true : false );
}
//===========================================================================//
// Method : Print
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
void TAS_TimingDelay_c::Print(
FILE* pfile,
size_t spaceLen ) const
{
TC_MinGrid_c& MinGrid = TC_MinGrid_c::GetInstance( );
unsigned int precision = MinGrid.GetPrecision( );
TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( );
printHandler.Write( pfile, spaceLen, "<timing" );
string srMode;
TAS_ExtractStringTimingMode( this->mode, &srMode );
printHandler.Write( pfile, 0, " mode=\"%s\"",
TIO_SR_STR( srMode ));
string srType;
TAS_ExtractStringTimingType( this->type, &srType );
if( this->mode == TAS_TIMING_MODE_DELAY_CONSTANT )
{
printHandler.Write( pfile, 0, " input=\"%s\" output=\"%s\"",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
if( TCTF_IsGT( this->valueMin, 0.0 ))
{
printHandler.Write( pfile, 0, " %s=\"%0.*e\"",
TIO_SR_STR( srType ),
precision + 1, this->valueMin );
}
if( TCTF_IsGT( this->valueMax, 0.0 ))
{
printHandler.Write( pfile, 0, " %s=\"%0.*e\"",
TIO_SR_STR( srType ),
precision + 1, this->valueMax );
}
printHandler.Write( pfile, 0, "/>\n" );
}
else if( this->mode == TAS_TIMING_MODE_DELAY_MATRIX )
{
printHandler.Write( pfile, 0, " input=\"%s\" output=\"%s\"\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
spaceLen += 3;
string srTimingDelayMatrix;
this->valueMatrix.ExtractString( TC_DATA_EXP, &srTimingDelayMatrix,
4, SIZE_MAX, spaceLen + 12, 0 );
printHandler.Write( pfile, spaceLen, " %s=%s",
TIO_SR_STR( srType ),
TIO_SR_STR( srTimingDelayMatrix ));
spaceLen -= 3;
printHandler.Write( pfile, spaceLen, "/>\n" );
}
else if( this->mode == TAS_TIMING_MODE_T_SETUP )
{
printHandler.Write( pfile, 0, "input=\"%s\" clock=\"%s\" value=\"%0.*e\"/>\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srClockPortName ),
precision + 1, this->valueNom );
}
else if( this->mode == TAS_TIMING_MODE_T_HOLD )
{
printHandler.Write( pfile, 0, "input=\"%s\" clock=\"%s\" value=\"%0.*e\"/>\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srClockPortName ),
precision + 1, this->valueNom );
}
else if( this->mode == TAS_TIMING_MODE_CLOCK_TO_Q )
{
printHandler.Write( pfile, 0, " output=\"%s\" clock=\"%s\"",
TIO_SR_STR( this->srOutputPortName ),
TIO_SR_STR( this->srClockPortName ));
if( TCTF_IsGT( this->valueMin, 0.0 ))
{
printHandler.Write( pfile, 0, " %s=\"%0.*e\"",
TIO_SR_STR( srType ),
precision + 1, this->valueMin );
}
if( TCTF_IsGT( this->valueMax, 0.0 ))
{
printHandler.Write( pfile, 0, " %s=\"%0.*e\"",
TIO_SR_STR( srType ),
precision + 1, this->valueMax );
}
printHandler.Write( pfile, 0, "/>\n" );
}
else if( this->mode == TAS_TIMING_MODE_CAP_CONSTANT )
{
printHandler.Write( pfile, 0, " input=\"%s\" output=\"%s\" value=\"%0.*f\"\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ),
precision, this->valueNom );
}
else if( this->mode == TAS_TIMING_MODE_CAP_MATRIX )
{
printHandler.Write( pfile, 0, " input=\"%s\" output=\"%s\"\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
spaceLen += 3;
string srTimingDelayMatrix;
this->valueMatrix.ExtractString( TC_DATA_FLOAT, &srTimingDelayMatrix,
4, SIZE_MAX, spaceLen + 10, 0 );
printHandler.Write( pfile, spaceLen, "matrix=\"%s\"",
TIO_SR_STR( srTimingDelayMatrix ));
spaceLen -= 3;
printHandler.Write( pfile, spaceLen, "/>\n" );
}
else if( this->mode == TAS_TIMING_MODE_PACK_PATTERN )
{
printHandler.Write( pfile, 0, " input=\"%s\" output=\"%s\" name=\"%s\"/>\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ),
TIO_SR_STR( this->srPackPatternName ));
}
}
//===========================================================================//
// Method : PrintXML
// Author : <NAME>
//---------------------------------------------------------------------------//
// Version history
// 05/15/12 jeffr : Original
//===========================================================================//
void TAS_TimingDelay_c::PrintXML(
void ) const
{
FILE* pfile = 0;
size_t spaceLen = 0;
this->PrintXML( pfile, spaceLen );
}
//===========================================================================//
void TAS_TimingDelay_c::PrintXML(
FILE* pfile,
size_t spaceLen ) const
{
TC_MinGrid_c& MinGrid = TC_MinGrid_c::GetInstance( );
unsigned int precision = MinGrid.GetPrecision( ) + 1;
TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( );
const char* pszType = "";
if(( this->type == TAS_TIMING_TYPE_MAX_VALUE ) ||
( this->type == TAS_TIMING_TYPE_MAX_MATRIX ))
{
pszType = "max";
}
if(( this->type == TAS_TIMING_TYPE_MIN_VALUE ) ||
( this->type == TAS_TIMING_TYPE_MIN_MATRIX ))
{
pszType = "min";
}
switch( this->mode )
{
case TAS_TIMING_MODE_DELAY_CONSTANT:
if( TCTF_IsGT( this->valueMin, 0.0 ) && TCTF_IsGT( this->valueMax, 0.0 ))
{
printHandler.Write( pfile, spaceLen, "<delay_constant min=\"%0.*e\" max=\"%0.*e\" in_port=\"%s\" out_port=\"%s\"/>\n",
precision + 1, this->valueMin,
precision + 1, this->valueMax,
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
}
else if( TCTF_IsGT( this->valueMin, 0.0 ))
{
printHandler.Write( pfile, spaceLen, "<delay_constant min=\"%0.*e\" in_port=\"%s\" out_port=\"%s\"/>\n",
precision + 1, this->valueMin,
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
}
else if( TCTF_IsGT( this->valueMax, 0.0 ))
{
printHandler.Write( pfile, spaceLen, "<delay_constant max=\"%0.*e\" in_port=\"%s\" out_port=\"%s\"/>\n",
precision + 1, this->valueMax,
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
}
break;
case TAS_TIMING_MODE_DELAY_MATRIX:
printHandler.Write( pfile, spaceLen, "<delay_matrix type=\"%s\" in_port=\"%s\" out_port=\"%s\">\n",
TIO_PSZ_STR( pszType ),
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
for( size_t j = 0; j < this->valueMatrix.GetHeight( ); ++j )
{
printHandler.Write( pfile, spaceLen + 3, "" );
for( size_t i = 0; i < this->valueMatrix.GetWidth( ); ++i )
{
printHandler.Write( pfile, 0, "%0.*e%s",
precision + 1, this->valueMatrix[i][j],
i + 1 == this->valueMatrix.GetWidth( ) ? "" : " " );
}
printHandler.Write( pfile, 0, "\n" );
}
printHandler.Write( pfile, spaceLen, "</delay_matrix>\n" );
break;
case TAS_TIMING_MODE_T_SETUP:
printHandler.Write( pfile, spaceLen, "<T_setup value=\"%0.*e\" port=\"%s\" clock=\"%s\"/>\n",
precision + 1, this->valueNom,
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srClockPortName ));
break;
case TAS_TIMING_MODE_T_HOLD:
printHandler.Write( pfile, spaceLen, "<T_hold value=\"%0.*e\" port=\"%s\" clock=\"%s\"/>\n",
precision + 1, this->valueNom,
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srClockPortName ));
break;
case TAS_TIMING_MODE_CLOCK_TO_Q:
if( TCTF_IsGT( this->valueMin, 0.0 ) && TCTF_IsGT( this->valueMax, 0.0 ))
{
printHandler.Write( pfile, spaceLen, "<T_clock_to_Q min=\"%0.*e\" max=\"%0.*e\" port=\"%s\" clock=\"%s\"/>\n",
precision + 1, this->valueMin,
precision + 1, this->valueMax,
TIO_SR_STR( this->srOutputPortName ),
TIO_SR_STR( this->srClockPortName ));
}
else if( TCTF_IsGT( this->valueMin, 0.0 ))
{
printHandler.Write( pfile, spaceLen, "<T_clock_to_Q min=\"%0.*e\" port=\"%s\" clock=\"%s\"/>\n",
precision + 1, this->valueMin,
TIO_SR_STR( this->srOutputPortName ),
TIO_SR_STR( this->srClockPortName ));
}
else if( TCTF_IsGT( this->valueMax, 0.0 ))
{
printHandler.Write( pfile, spaceLen, "<T_clock_to_Q max=\"%0.*e\" port=\"%s\" clock=\"%s\"/>\n",
precision + 1, this->valueMax,
TIO_SR_STR( this->srOutputPortName ),
TIO_SR_STR( this->srClockPortName ));
}
break;
case TAS_TIMING_MODE_CAP_CONSTANT:
printHandler.Write( pfile, spaceLen, "<cap_constant C=\"%0.*f\" in_port=\"%s\" out_port=\"%s\"/>\n",
precision, this->valueNom,
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
break;
case TAS_TIMING_MODE_CAP_MATRIX:
printHandler.Write( pfile, spaceLen, "<cap_matrix in_port=\"%s\" out_port=\"%s\">\n",
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
for( size_t j = 0; j < this->valueMatrix.GetHeight( ); ++j )
{
printHandler.Write( pfile, spaceLen + 3, "" );
for( size_t i = 0; i < this->valueMatrix.GetWidth( ); ++i )
{
printHandler.Write( pfile, 0, "%0.*f%s",
precision, this->valueMatrix[i][j],
i + 1 == this->valueMatrix.GetWidth( ) ? "" : " " );
}
printHandler.Write( pfile, 0, "\n" );
}
printHandler.Write( pfile, spaceLen, "</cap_matrix>\n" );
break;
case TAS_TIMING_MODE_PACK_PATTERN:
printHandler.Write( pfile, spaceLen, "<pack_pattern name=\"%s\" in_port=\"%s\" out_port=\"%s\"/>\n",
TIO_SR_STR( this->srPackPatternName ),
TIO_SR_STR( this->srInputPortName ),
TIO_SR_STR( this->srOutputPortName ));
break;
case TAS_TIMING_MODE_UNDEFINED:
break;
}
}
|
Bortize/42Madrid
|
Ecole/cub3d/aborboll/libft/srcs/ft_get_next_line/get_next_line.c
|
<reponame>Bortize/42Madrid<filename>Ecole/cub3d/aborboll/libft/srcs/ft_get_next_line/get_next_line.c<gh_stars>10-100
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aborboll <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/31 08:08:19 by aborboll #+# #+# */
/* Updated: 2020/09/23 20:02:04 by aborboll ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/get_next_line.h"
static int ft_new_line(char **cache, char **line, int fd)
{
char *tmp;
int len;
len = 0;
while (cache[fd][len] != '\n' && cache[fd][len] != '\0')
len++;
if (cache[fd][len] == '\n')
{
*line = ft_substr(cache[fd], 0, len);
tmp = ft_strdup(&cache[fd][len + 1]);
free(cache[fd]);
cache[fd] = tmp;
if (cache[fd][0] == '\0')
ft_strdel(&cache[fd]);
}
else
{
*line = ft_strdup(cache[fd]);
ft_strdel(&cache[fd]);
return (0);
}
return (1);
}
static int ft_return(char **cache, char **line, int fd, int ret)
{
if (ret < 0)
return (-1);
if (ret == 0 && cache[fd] == NULL)
{
*line = ft_strdup("");
return (0);
}
return (ft_new_line(cache, line, fd));
}
int get_next_line(int fd, char **line)
{
static char *cache[4096];
char *buff;
char *tmp;
int ret;
if (fd < 0 || line == NULL || BUFF_SIZE < 1
|| !(buff = malloc((sizeof(char) * BUFF_SIZE) + 1)))
return (-1);
while ((ret = read(fd, buff, BUFF_SIZE)) > 0)
{
buff[ret] = '\0';
if (cache[fd] == NULL)
cache[fd] = ft_strnew(1);
tmp = ft_strjoin(cache[fd], buff);
free(cache[fd]);
cache[fd] = tmp;
if (ft_strchr(buff, '\n'))
break ;
}
free(buff);
return (ft_return(cache, line, fd, ret));
}
|
prasadkovai/elasticshell
|
src/main/java/org/elasticsearch/shell/client/builders/cluster/ClusterRerouteRequestBuilder.java
|
<gh_stars>10-100
/*
* Licensed to <NAME> (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.shell.client.builders.cluster;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteRequest;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommand;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.shell.client.builders.AbstractRequestBuilderJsonOutput;
import org.elasticsearch.shell.json.JsonToString;
import org.elasticsearch.shell.json.StringToJson;
import java.io.IOException;
/**
* @author <NAME>
*
* Request builder for cluster reroute API
*/
@SuppressWarnings("unused")
public class ClusterRerouteRequestBuilder<JsonInput, JsonOutput> extends AbstractRequestBuilderJsonOutput<ClusterRerouteRequest, ClusterRerouteResponse, JsonInput, JsonOutput> {
public ClusterRerouteRequestBuilder(Client client, JsonToString<JsonInput> jsonToString, StringToJson<JsonOutput> stringToJson) {
super(client, new ClusterRerouteRequest(), jsonToString, stringToJson);
}
public ClusterRerouteRequestBuilder<JsonInput, JsonOutput> add(AllocationCommand... commands) {
request.add(commands);
return this;
}
public ClusterRerouteRequestBuilder<JsonInput, JsonOutput> dryRun(boolean dryRun) {
request.dryRun(dryRun);
return this;
}
public ClusterRerouteRequestBuilder<JsonInput, JsonOutput> source(JsonInput source) throws Exception {
request.source(new BytesArray(jsonToString(source)));
return this;
}
@Override
protected ActionFuture<ClusterRerouteResponse> doExecute(ClusterRerouteRequest request) {
return client.admin().cluster().reroute(request);
}
@Override
protected XContentBuilder toXContent(ClusterRerouteRequest request, ClusterRerouteResponse response, XContentBuilder builder) throws IOException {
builder.startObject();
builder.field(Fields.OK, true);
builder.startObject("state");
response.getState().settingsFilter(new SettingsFilter(ImmutableSettings.settingsBuilder().build())).toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
builder.endObject();
return builder;
}
}
|
arraycto/qshop_bbc
|
java后台代码/qshop-core/src/main/java/co/lq/modules/shop/rest/StoreCollectController.java
|
<filename>java后台代码/qshop-core/src/main/java/co/lq/modules/shop/rest/StoreCollectController.java
package co.lq.modules.shop.rest;
import co.lq.aop.log.Log;
import co.lq.modules.shop.domain.StoreCollect;
import co.lq.modules.shop.service.StoreCollectService;
import co.lq.modules.shop.service.dto.StoreCollectQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @author billy
* @date 2020-04-05
*/
@Api(tags = "店铺收藏表管理")
@RestController
@RequestMapping("/api/storeCollect")
public class StoreCollectController {
private final StoreCollectService storeCollectService;
public StoreCollectController(StoreCollectService storeCollectService) {
this.storeCollectService = storeCollectService;
}
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('storeCollect:list')")
public void download(HttpServletResponse response, StoreCollectQueryCriteria criteria) throws IOException {
storeCollectService.download(storeCollectService.queryAll(criteria), response);
}
@GetMapping
@Log("查询店铺收藏表")
@ApiOperation("查询店铺收藏表")
@PreAuthorize("@el.check('storeCollect:list')")
public ResponseEntity<Object> getStoreCollects(StoreCollectQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(storeCollectService.queryAll(criteria,pageable),HttpStatus.OK);
}
@PostMapping
@Log("新增店铺收藏表")
@ApiOperation("新增店铺收藏表")
@PreAuthorize("@el.check('storeCollect:add')")
public ResponseEntity<Object> create(@Validated @RequestBody StoreCollect resources){
return new ResponseEntity<>(storeCollectService.create(resources),HttpStatus.CREATED);
}
@PutMapping
@Log("修改店铺收藏表")
@ApiOperation("修改店铺收藏表")
@PreAuthorize("@el.check('storeCollect:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody StoreCollect resources){
storeCollectService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除店铺收藏表")
@ApiOperation("删除店铺收藏表")
@PreAuthorize("@el.check('storeCollect:del')")
@DeleteMapping
public ResponseEntity<Object> deleteAll(@RequestBody Long[] ids) {
storeCollectService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
henrymliu/UBC-Thunderbots-Software
|
src/firmware/test/unit_tests/quadratic_test.c
|
<filename>src/firmware/test/unit_tests/quadratic_test.c<gh_stars>0
#include "main/util/quadratic.h"
#include <math.h>
#include "check.h"
#include "test.h"
// This is an M matrix that is used for multiple tests
// It is primarily related to the Q matrix from the optimization
// where Q = M.T * M
static float M[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
START_TEST(test_build_M_matrix)
{
PhysBot pb = {.rot = {.disp = 0}, .major_vec = {1, 1}, .minor_vec = {1, 0}};
dr_data_t state;
state.angle = 0;
float M[3][4];
build_M_matrix(pb, state, M);
// check wheel 1 of matrix
ck_assert_float_eq_tol(-0.5f + sqrt(3.0f) / 2.0f, M[0][0], TOL);
ck_assert_float_eq_tol(-0.5f, M[1][0], TOL);
ck_assert_float_eq(1, M[2][0]);
// check wheel 2 of matrix
ck_assert_float_eq_tol(-0.5f - sqrt(3.0f) / 2.0f, M[0][1], TOL);
ck_assert_float_eq_tol(-sqrt(3.0f) / 2.0f, M[1][1], TOL);
ck_assert_float_eq(1, M[2][1]);
// check wheel 3 of matrix
ck_assert_float_eq_tol(0.5f + sqrt(3.0f) / 2.0f, M[0][2], TOL);
ck_assert_float_eq_tol(0.5f, M[1][2], TOL);
ck_assert_float_eq(1, M[2][2]);
// check wheel 4 of matrix
ck_assert_float_eq_tol(-0.5f + sqrt(3.0f) / 2.0f, M[0][3], TOL);
ck_assert_float_eq_tol(sqrt(3.0f) / 2.0f, M[1][3], TOL);
ck_assert_float_eq(1, M[2][3]);
}
END_TEST
START_TEST(test_transpose)
{
float M_T[4][3];
transpose_qp(M, M_T);
float expected_result[4][3] = {{1, 5, 9}, {2, 6, 10}, {3, 7, 11}, {4, 8, 12}};
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
ck_assert_float_eq(expected_result[i][j], M_T[i][j]);
}
}
}
END_TEST
START_TEST(test_build_Q_matrix)
{
float M_T[4][3];
float Q[4][4];
transpose_qp(M, M_T);
build_Q_matrix(M, M_T, Q);
float expected_result[4][4] = {{107, 122, 137, 152},
{122, 140, 158, 176},
{137, 158, 179, 200},
{152, 176, 200, 224}};
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
ck_assert_float_eq(expected_result[i][j], Q[i][j]);
}
}
}
END_TEST
START_TEST(test_build_c_matrix)
{
float a_req[3] = {0.1, 0.5, 0.4};
float c[4];
build_c_matrix(a_req, M, c);
float expected_result[4] = {6.2, 7.2, 8.2, 9.2};
for (int i = 0; i < 4; i++)
{
ck_assert_float_eq_tol(2 * expected_result[i], c[i], TOL);
}
}
END_TEST
START_TEST(quadratic_test)
{
PhysBot pb = {
.rot = {.disp = 30.0f * M_PI / 180.0f}, .major_vec = {1, 1}, .minor_vec = {1, 0}};
float a_req[3] = {0.1, 0.5, 0.4};
dr_data_t state;
state.angle = 0;
quad_optimize(pb, state, a_req);
}
END_TEST
/**
* Test function manager for quadratic.c
*/
void run_quadratic_test()
{
// Put the name of the suite of tests in here
Suite *s = suite_create("Qudratic Test");
// Creates a test case that you can add all of the tests to
TCase *tc = tcase_create("Core");
// add the tests for this file here
tcase_add_test(tc, quadratic_test);
tcase_add_test(tc, test_build_M_matrix);
tcase_add_test(tc, test_transpose);
tcase_add_test(tc, test_build_Q_matrix);
tcase_add_test(tc, test_build_c_matrix);
// run the tests
run_test(tc, s);
}
|
arturopala/agents-external-stubs
|
app/uk/gov/hmrc/agentsexternalstubs/controllers/SsoDomainController.scala
|
<reponame>arturopala/agents-external-stubs<filename>app/uk/gov/hmrc/agentsexternalstubs/controllers/SsoDomainController.scala
/*
* Copyright 2021 HM Revenue & Customs
*
* 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 uk.gov.hmrc.agentsexternalstubs.controllers
import javax.inject.{Inject, Singleton}
import play.api.Configuration
import play.api.mvc.{Action, _}
import uk.gov.hmrc.play.bootstrap.backend.controller.BackendController
import scala.concurrent.Future.successful
@Singleton
class SsoDomainController @Inject()(cc: MessagesControllerComponents)(implicit val configuration: Configuration)
extends BackendController(cc) {
def validate(domain: String): Action[AnyContent] = Action {
if (domain != "www.google.com") NoContent else BadRequest
}
def digitalFlag(flag: String): Action[AnyContent] = Action {
Ok
}
def getDomains: Action[AnyContent] = Action.async { implicit request =>
successful(Ok(domainsJson))
}
def domainsJson =
s"""
{
| "internalDomains" : [
| "localhost"
| ],
| "externalDomains" : [
| "127.0.0.1",
| "online-qa.ibt.hmrc.gov.uk",
| "ibt.hmrc.gov.uk"
| ]
|}
|
""".stripMargin
}
|
cljohnso/terracotta-platform
|
lease/entity-common/src/test/java/org/terracotta/lease/LeaseReconnectDataTest.java
|
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terracotta.lease;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LeaseReconnectDataTest {
@Test
public void roundtripLeaseReconnectData() throws Exception {
LeaseReconnectData reconnectData = new LeaseReconnectData(7);
byte[] bytes = reconnectData.encode();
LeaseReconnectData roundtrippedData = LeaseReconnectData.decode(bytes);
assertEquals(7, roundtrippedData.getConnectionSequenceNumber());
}
}
|
isuhao/ravl2
|
RAVL2/MSVC/include/Ravl/PatternRec/ClassifierAverageNearestNeighbour.hh
|
#include "../.././PatternRec/Classify/ClassifierAverageNearestNeighbour.hh"
|
osidorkin85/nno
|
backend/n2o/n2o-test/src/test/java/net/n2oapp/framework/test/TestRedisConfiguration.java
|
package net.n2oapp.framework.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Import;
import redis.embedded.RedisServer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@TestConfiguration
@Import(RedisAutoConfiguration.class)
public class TestRedisConfiguration {
private RedisServer redisServer;
public TestRedisConfiguration(@Value("${spring.redis.port}") int port) {
this.redisServer = RedisServer.builder()
.port(port)
.setting("maxmemory 128M")
.build();
}
@PostConstruct
public void postConstruct() {
redisServer.start();
}
@PreDestroy
public void preDestroy() {
redisServer.stop();
}
}
|
ch1huizong/Scode
|
stdlib3-src/textwrap.py
|
<filename>stdlib3-src/textwrap.py
"""Text wrapping and filling.
"""
# Copyright (C) 1999-2001 <NAME>.
# Copyright (C) 2002, 2003 Python Software Foundation.
# Written by <NAME> <<EMAIL>>
import re
__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
# Hardcode the recognized whitespace characters to the US-ASCII
# whitespace characters. The main reason for doing this is that
# some Unicode spaces (like \u00a0) are non-breaking whitespaces.
_whitespace = '\t\n\x0b\x0c\r '
class TextWrapper:
"""
Object for wrapping/filling text. The public interface consists of
the wrap() and fill() methods; the other methods are just there for
subclasses to override in order to tweak the default behaviour.
If you want to completely replace the main wrapping algorithm,
you'll probably have to override _wrap_chunks().
Several instance attributes control various aspects of wrapping:
width (default: 70)
the maximum width of wrapped lines (unless break_long_words
is false)
initial_indent (default: "")
string that will be prepended to the first line of wrapped
output. Counts towards the line's width.
subsequent_indent (default: "")
string that will be prepended to all lines save the first
of wrapped output; also counts towards each line's width.
expand_tabs (default: true)
Expand tabs in input text to spaces before further processing.
Each tab will become 0 .. 'tabsize' spaces, depending on its position
in its line. If false, each tab is treated as a single character.
tabsize (default: 8)
Expand tabs in input text to 0 .. 'tabsize' spaces, unless
'expand_tabs' is false.
replace_whitespace (default: true)
Replace all whitespace characters in the input text by spaces
after tab expansion. Note that if expand_tabs is false and
replace_whitespace is true, every tab will be converted to a
single space!
fix_sentence_endings (default: false)
Ensure that sentence-ending punctuation is always followed
by two spaces. Off by default because the algorithm is
(unavoidably) imperfect.
break_long_words (default: true)
Break words longer than 'width'. If false, those words will not
be broken, and some lines might be longer than 'width'.
break_on_hyphens (default: true)
Allow breaking hyphenated words. If true, wrapping will occur
preferably on whitespaces and right after hyphens part of
compound words.
drop_whitespace (default: true)
Drop leading and trailing whitespace from lines.
max_lines (default: None)
Truncate wrapped lines.
placeholder (default: ' [...]')
Append to the last line of truncated text.
"""
unicode_whitespace_trans = {}
uspace = ord(' ')
for x in _whitespace:
unicode_whitespace_trans[ord(x)] = uspace
# This funky little regex is just the trick for splitting
# text up into word-wrappable chunks. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option!
# (after stripping out empty strings).
word_punct = r'[\w!"\'&.,?]'
letter = r'[^\d\W]'
whitespace = r'[%s]' % re.escape(_whitespace)
nowhitespace = '[^' + whitespace[1:]
wordsep_re = re.compile(r'''
( # any whitespace
%(ws)s+
| # em-dash between words
(?<=%(wp)s) -{2,} (?=\w)
| # word, possibly hyphenated
%(nws)s+? (?:
# hyphenated word
-(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
(?= %(lt)s -? %(lt)s)
| # end of word
(?=%(ws)s|\Z)
| # em-dash
(?<=%(wp)s) (?=-{2,}\w)
)
)''' % {'wp': word_punct, 'lt': letter,
'ws': whitespace, 'nws': nowhitespace},
re.VERBOSE)
del word_punct, letter, nowhitespace
# This less funky little regex just split on recognized spaces. E.g.
# "Hello there -- you goof-ball, use the -b option!"
# splits into
# Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
del whitespace
# XXX this is not locale- or charset-aware -- string.lowercase
# is US-ASCII only (and therefore English-only)
sentence_end_re = re.compile(r'[a-z]' # lowercase letter
r'[\.\!\?]' # sentence-ending punct.
r'[\"\']?' # optional end-of-quote
r'\Z') # end of chunk
def __init__(self,
width=70,
initial_indent="",
subsequent_indent="",
expand_tabs=True,
replace_whitespace=True,
fix_sentence_endings=False,
break_long_words=True,
drop_whitespace=True,
break_on_hyphens=True,
tabsize=8,
*,
max_lines=None,
placeholder=' [...]'):
self.width = width
self.initial_indent = initial_indent
self.subsequent_indent = subsequent_indent
self.expand_tabs = expand_tabs
self.replace_whitespace = replace_whitespace
self.fix_sentence_endings = fix_sentence_endings
self.break_long_words = break_long_words
self.drop_whitespace = drop_whitespace
self.break_on_hyphens = break_on_hyphens
self.tabsize = tabsize
self.max_lines = max_lines
self.placeholder = placeholder
# -- Private methods -----------------------------------------------
# (possibly useful for subclasses to override)
def _munge_whitespace(self, text):
"""_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
becomes " foo bar baz".
"""
if self.expand_tabs:
text = text.expandtabs(self.tabsize)
if self.replace_whitespace:
text = text.translate(self.unicode_whitespace_trans)
return text
def _split(self, text):
"""_split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the following chunks:
'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', 'option!'
if break_on_hyphens is True, or in:
'Look,', ' ', 'goof-ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', option!'
otherwise.
"""
if self.break_on_hyphens is True:
chunks = self.wordsep_re.split(text)
else:
chunks = self.wordsep_simple_re.split(text)
chunks = [c for c in chunks if c]
return chunks
def _fix_sentence_endings(self, chunks):
"""_fix_sentence_endings(chunks : [string])
Correct for sentence endings buried in 'chunks'. Eg. when the
original text contains "... foo.\\nBar ...", munge_whitespace()
and split() will convert that to [..., "foo.", " ", "Bar", ...]
which has one too few spaces; this method simply changes the one
space to two.
"""
i = 0
patsearch = self.sentence_end_re.search
while i < len(chunks)-1:
if chunks[i+1] == " " and patsearch(chunks[i]):
chunks[i+1] = " "
i += 2
else:
i += 1
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
"""_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long to fit in any line.
"""
# Figure out when indent is larger than the specified width, and make
# sure at least one character is stripped off on every pass
if width < 1:
space_left = 1
else:
space_left = width - cur_len
# If we're allowed to break long words, then do so: put as much
# of the next chunk onto the current line as will fit.
if self.break_long_words:
cur_line.append(reversed_chunks[-1][:space_left])
reversed_chunks[-1] = reversed_chunks[-1][space_left:]
# Otherwise, we have to preserve the long word intact. Only add
# it to the current line if there's nothing already there --
# that minimizes how much we violate the width constraint.
elif not cur_line:
cur_line.append(reversed_chunks.pop())
# If we're not allowed to break long words, and there's already
# text on the current line, do nothing. Next time through the
# main loop of _wrap_chunks(), we'll wind up here again, but
# cur_len will be zero, so the next line will be entirely
# devoted to the long word that we can't handle right now.
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and the whitespace between them: each chunk is
indivisible (modulo 'break_long_words'), but a line break can
come between any two chunks. Chunks should not have internal
whitespace; ie. a chunk is either all whitespace or a "word".
Whitespace chunks will be removed from the beginning and end of
lines, but apart from that whitespace is preserved.
"""
lines = []
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
if self.max_lines is not None:
if self.max_lines > 1:
indent = self.subsequent_indent
else:
indent = self.initial_indent
if len(indent) + len(self.placeholder.lstrip()) > self.width:
raise ValueError("placeholder too large for max width")
# Arrange in reverse order so items can be efficiently popped
# from a stack of chucks.
chunks.reverse()
while chunks:
# Start the list of chunks that will make up the current line.
# cur_len is just the length of all the chunks in cur_line.
cur_line = []
cur_len = 0
# Figure out which static string will prefix this line.
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
# Maximum width for this line.
width = self.width - len(indent)
# First chunk on line is whitespace -- drop it, unless this
# is the very beginning of the text (ie. no lines started yet).
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
del chunks[-1]
while chunks:
l = len(chunks[-1])
# Can at least squeeze this chunk onto the current line.
if cur_len + l <= width:
cur_line.append(chunks.pop())
cur_len += l
# Nope, this line is full.
else:
break
# The current line is full, and the next chunk is too big to
# fit on *any* line (not just this one).
if chunks and len(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
cur_len = sum(map(len, cur_line))
# If the last chunk on this line is all whitespace, drop it.
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
cur_len -= len(cur_line[-1])
del cur_line[-1]
if cur_line:
if (self.max_lines is None or
len(lines) + 1 < self.max_lines or
(not chunks or
self.drop_whitespace and
len(chunks) == 1 and
not chunks[0].strip()) and cur_len <= width):
# Convert current line back to a string and store it in
# list of all lines (return value).
lines.append(indent + ''.join(cur_line))
else:
while cur_line:
if (cur_line[-1].strip() and
cur_len + len(self.placeholder) <= width):
cur_line.append(self.placeholder)
lines.append(indent + ''.join(cur_line))
break
cur_len -= len(cur_line[-1])
del cur_line[-1]
else:
if lines:
prev_line = lines[-1].rstrip()
if (len(prev_line) + len(self.placeholder) <=
self.width):
lines[-1] = prev_line + self.placeholder
break
lines.append(indent + self.placeholder.lstrip())
break
return lines
def _split_chunks(self, text):
text = self._munge_whitespace(text)
return self._split(text)
# -- Public interface ----------------------------------------------
def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
converted to space.
"""
chunks = self._split_chunks(text)
if self.fix_sentence_endings:
self._fix_sentence_endings(chunks)
return self._wrap_chunks(chunks)
def fill(self, text):
"""fill(text : string) -> string
Reformat the single paragraph in 'text' to fit in lines of no
more than 'self.width' columns, and return a new string
containing the entire wrapped paragraph.
"""
return "\n".join(self.wrap(text))
# -- Convenience interface ---------------------------------------------
def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
def fill(text, width=70, **kwargs):
"""Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.fill(text)
def shorten(text, width, **kwargs):
"""Collapse and truncate the given text to fit in the given width.
The text first has its whitespace collapsed. If it then fits in
the *width*, it is returned as is. Otherwise, as many words
as possible are joined and then the placeholder is appended::
>>> textwrap.shorten("Hello world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello world!", width=11)
'Hello [...]'
"""
w = TextWrapper(width=width, max_lines=1, **kwargs)
return w.fill(' '.join(text.strip().split()))
# -- Loosely related functionality -------------------------------------
_whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
def dedent(text):
"""Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, but they
are not equal: the lines " hello" and "\\thello" are
considered to have no common leading whitespace. (This behaviour is
new in Python 2.5; older versions of this module incorrectly
expanded tabs before searching for common leading whitespace.)
"""
# Look for the longest leading string of spaces and tabs common to
# all lines.
margin = None
text = _whitespace_only_re.sub('', text)
indents = _leading_whitespace_re.findall(text)
for indent in indents:
if margin is None:
margin = indent
# Current line more deeply indented than previous winner:
# no change (previous winner is still on top).
elif indent.startswith(margin):
pass
# Current line consistent with and no deeper than previous winner:
# it's the new winner.
elif margin.startswith(indent):
margin = indent
# Find the largest common whitespace between current line and previous
# winner.
else:
for i, (x, y) in enumerate(zip(margin, indent)):
if x != y:
margin = margin[:i]
break
# sanity check (testing/debugging only)
if 0 and margin:
for line in text.split("\n"):
assert not line or line.startswith(margin), \
"line = %r, margin = %r" % (line, margin)
if margin:
text = re.sub(r'(?m)^' + margin, '', text)
return text
def indent(text, prefix, predicate=None):
"""Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters.
"""
if predicate is None:
def predicate(line):
return line.strip()
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())
if __name__ == "__main__":
# print dedent("\tfoo\n\tbar")
# print dedent(" \thello there\n \t how are you?")
print(dedent("Hello there.\n This is indented."))
|
yuigoto/angularjs-boilerplate
|
src/js/dummy/DummyController.js
|
/**
* Dummy/Dummy.Controller
* ----------------------------------------------------------------------
* Descrição.
*
* @type {angular.Module.controller}
* @author <NAME> <<EMAIL>>
* @since 0.0.1
*/
Dummy.controller("DummyController", DummyController);
// DI
DummyController.$inject = ["$scope", "$http", "$timeout"];
/**
* DummyController.
*
* @param {angular.$scope} $scope
* Serviço de gerenciamento de escopo do Angular
* @param {angular.IHttpService} $http
* Serviço para execução de requests via HTTP do AngularJS
* @param {angular.ITimeoutService} $timeout
* Wrapper de `setTimeout` do AngularJS
*/
function DummyController ($scope, $http, $timeout) {
// Lifecycle
// --------------------------------------------------------------------
/**
* Executa ao inicializar.
*/
this.$onInit = function () {
console.log("[DummyController] initialized.");
};
/**
* Executa ao receber atualizações.
*/
this.$doCheck = function () {
console.log("[DummyController] updated.");
};
// Métodos + Propriedades do Escopo
// --------------------------------------------------------------------
/**
* Método de teste.
*/
$scope.test = function () {
return "Este é um teste.";
};
}
|
sijo4123/SSHygieia
|
api-audit/src/main/java/com/capitalone/dashboard/response/DashboardReviewResponse.java
|
<reponame>sijo4123/SSHygieia<filename>api-audit/src/main/java/com/capitalone/dashboard/response/DashboardReviewResponse.java
package com.capitalone.dashboard.response;
import java.util.List;
public class DashboardReviewResponse extends AuditReviewResponse {
private String dashboardTitle;
List<PeerReviewResponse> allPeerReviewResponses;
JobReviewResponse jobReviewResponse;
public String getDashboardTitle() {
return dashboardTitle;
}
public void setDashboardTitle(String dashboardTitle) {
this.dashboardTitle = dashboardTitle;
}
public List<PeerReviewResponse> getAllPeerReviewResponses() {
return allPeerReviewResponses;
}
public void setAllPeerReviewResponses(List<PeerReviewResponse> allPeerReviewResponses) {
this.allPeerReviewResponses = allPeerReviewResponses;
}
public JobReviewResponse getJobReviewResponse() {
return jobReviewResponse;
}
public void setJobReviewResponse(JobReviewResponse jobReviewResponse) {
this.jobReviewResponse = jobReviewResponse;
}
}
|
all3g/pieces
|
misc/ig/ig/ig.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from optparse import OptionParser
from optparse import OptionGroup
from optparse import OptionError
import sys
from idns import idns
from webspider_domain import baidu_domain_spider
from webspider_domain import bing_domain_spider
from webspider_domain import yahoo_domain_spider
from webspider_domain import google_domain_spider
from webspider_domain import netcraft_domain_spider
from webspider_domain import zoomeye_domain_spider
from webspider_domain import censys_domain_spider
from webspider_domain import github_domain_spider
from bruteforce_domain import idns_bruteforce
from pprint import pprint
class cmdline(object):
def getArgs(self):
"""This function parses the command line parameters and arguments.
"""
usage = "python %prog [options]"
parser = OptionParser(usage=usage)
try:
domainopt = OptionGroup(parser, "DOMAIN INFORMATION",
"scan domains/subdomains information")
domainopt.add_option('-d', '--domain', dest='domain', type='str',
help='domain name')
domainopt.add_option('--query_a', action='store_true',
help='query dns A records')
domainopt.add_option('--query_cname', action='store_true',
help='query dns CNAME records')
domainopt.add_option('--query_mx', action='store_true',
help='query dns MX records')
domainopt.add_option('--query_ns', action='store_true',
help='query dns NS records')
domainopt.add_option('--query_soa', action='store_true',
help='query dns SOA records')
domainopt.add_option('--query_srv', action='store_true',
help='query dns SRV records')
domainopt.add_option('--query_txt', action='store_true',
help='query dns TXT records')
domainopt.add_option('--query_axfr', action='store_true',
help='query dns AXFR records')
domainopt.add_option('--enable_wildcard', action='store_true',
help='check if dns wildcard exists (default: disable)')
domainopt.add_option('--bruteforce', action='store_true',
help='brute force subdomains')
domainopt.add_option('--wordlist', dest='wordlist', type='str',
help='wordlist for subdomains bruteforce')
domainopt.add_option('--pages', dest='pages', type='int',
help='pages number to spider')
domainopt.add_option('--sleep', action='store_true',
help='enable sleep to bypass spider ban')
domainopt.add_option('--baidu', action='store_true',
help='search domains from baidu.com')
domainopt.add_option('--bing', action='store_true',
help='search domains from bing.com')
domainopt.add_option('--google', action='store_true',
help='search domains from google.com')
domainopt.add_option('--yahoo', action='store_true',
help='search domains from yahoo.com')
domainopt.add_option('--censys', action='store_true',
help='search domains from censys.io')
domainopt.add_option('--censys_uid', dest='censys_uid',
help='a censys api id')
domainopt.add_option('--censys_secret', dest='censys_secret',
help='a censys api secret')
domainopt.add_option('--github', action='store_true',
help='search domains from github.com')
domainopt.add_option('--netcraft', action='store_true',
help='search domains from netcraft.com')
domainopt.add_option('--zoomeye', action='store_true',
help='search domains from zoomeye.org')
domainopt.add_option('--zoomeye_username', dest='zoomeye_username',
type='str', help='a zoomeye username')
domainopt.add_option('--zoomeye_password', dest='zoomeye_password',
type='str', help='a zoomeye password')
parser.add_option_group(domainopt)
(args, _) = parser.parse_args()
except (OptionError, TypeError) as e:
parser.error(e)
else:
return args
def main():
"""parse cmdline options
"""
c = cmdline()
args = c.getArgs()
domains = [] # save all domains result
if not args.domain:
print('[!] please a domain to scan subdomains, ex: google.com')
sys.exit(0)
domain = args.domain
dnsqry = idns()
result = {}
result[domain] = {}
if args.query_a:
data = dnsqry.query_A(domain)
result[domain].update(data[domain])
if args.query_cname:
data = dnsqry.query_CNAME(domain)
result[domain].update(data[domain])
if args.query_mx:
data = dnsqry.query_MX(domain)
result[domain].update(data[domain])
if args.query_ns:
data = dnsqry.query_NS(domain)
result[domain].update(data[domain])
if args.query_soa:
data = dnsqry.query_SOA(domain)
result[domain].update(data[domain])
if args.query_srv:
data = dnsqry.query_SRV(domain)
result[domain].update(data[domain])
if args.query_txt:
data = dnsqry.query_TXT(domain)
result[domain].update(data[domain])
if args.query_axfr: # If no axfr records, pleae try to read query_AXFR code
try:
data = dnsqry.query_AXFR(domain)
except Exception as err:
import traceback
traceback.print_exc(err)
result[domain].update(data[domain])
if args.enable_wildcard:
dnsqry.dns_wildcard(domain)
if args.bruteforce:
print('[!] bruteforce domain may cost long time')
if args.wordlist:
idns_bt = idns_bruteforce(domain, subdomains_wd=args.wordlist)
else:
print('[!] use default wordlist to bruteforce subdomains')
idns_bt = idns_bruteforce(domain)
idns_bt.work()
idns_btret = []
for item in idns_bt.domains:
idns_btret.extend(item.keys())
domains.extend(idns_btret)
# merge domain bruteforce records
result[domain].update({'BRUTEFORCE': domains})
# pprint(idns_btret)
# if not args.pages:
# print('[!] please set pages num to spider domains from searchengine')
# sys.exit(0)
# default search pages: 1
pages = args.pages if args.pages else 1
sleep = True if args.sleep else False
if args.baidu:
print('[*] search domains from baidu.com')
bd = baidu_domain_spider()
bdret = bd.baidu_domain_search(domain, page=pages, random_sleep=sleep)
domains.extend(bdret[domain]['baidu'])
result[domain].update({'BAIDU': bdret[domain]['baidu']})
if args.bing:
print('[*] search domains from bing.com')
bi = bing_domain_spider()
biret = bi.bing_domain_search(domain, page=pages, random_sleep=sleep)
domains.extend(biret[domain]['bing'])
result[domain].update({'BING': biret[domain]['bing']})
if args.google:
print('[*] search domains from google.com')
gg = google_domain_spider()
ggret = gg.google_domain_search(domain, pages=pages, random_sleep=sleep)
domains.extend(ggret[domain]['google'])
result[domain].update({'GOOGLE': ggret[domain]['google']})
if args.yahoo:
print('[*] search domains from yahoo.com')
yh = yahoo_domain_spider()
yhret = yh.yahoo_domain_search(domain, page=pages, random_sleep=sleep)
domains.extend(yhret[domain]['yahoo'])
result[domain].update({'YAHOO': yhret[domain]['yahoo']})
if args.censys:
print('[*] search domains from censys.io')
uid = args.censys_uid
secret = args.censys_secret
assert (uid and secret)
cs = censys_domain_spider(uid, secret)
csret = cs.censys_domain_search(domain, page=2)
domains.extend(csret[domain]['censys'])
result[domain].update({'CENSYS': csret[domain]['censys']})
if args.github:
print('[*] search domains from github.com')
gh = github_domain_spider()
# domain = 'google.com'
ghret = gh.github_domain_search(domain)
domains.extend(ghret[domain]['github'])
result[domain].update({'GITHUB': ghret[domain]['github']})
if args.netcraft:
print('[*] search domains from netcraft.net')
nt = netcraft_domain_spider()
ntret = nt.netcraft_domain_search(domain, page=pages,
random_sleep=sleep)
domains.extend(ntret[domain]['netcraft'])
result[domain].update({'NETCRAFT': ntret[domain]['netcraft']})
if args.zoomeye:
print('[*] search domains from zoomeye.org')
zoomeye_user = args.zoomeye_username
zoomeye_pass = args.zoomeye_password
assert (zoomeye_user and zoomeye_pass)
zms = zoomeye_domain_spider(zoomeye_user, zoomeye_pass)
zmret = zms.zoomeye_domain_search(domain)
domains.extend(zmret[domain]['zoomeye'])
result[domain].update({'ZOOMEYE': zmret[domain]['zoomeye']})
print('[+] all domains as follow:')
pprint(domains)
print('[+] all domains records:')
print(result)
return domains, result
if __name__ == '__main__':
try:
main()
except Exception as err:
print(err)
|
huahang/incubator-nuttx
|
boards/arm/stm32/nucleo-l152re/include/board.h
|
/****************************************************************************
* boards/arm/stm32/nucleo-l152re/include/board.h
* include/arch/board/board.h
*
* Copyright (C) 2018 <NAME>. All rights reserved.
* Author: <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. Neither the name NuttX 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.
*
****************************************************************************/
#ifndef __BOARDS_ARM_STM32_NUCLEOL152RE_INCLUDE_BOARD_H
#define __BOARDS_ARM_STM32_NUCLEOL152RE_INCLUDE_BOARD_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#ifndef __ASSEMBLY__
# include <stdint.h>
# include <stdbool.h>
#endif
#ifdef __KERNEL__
# include "stm32.h"
#endif
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Clocking *****************************************************************/
/* Four different clock sources can be used to drive the system clock (SYSCLK):
*
* - HSI high-speed internal oscillator clock
* Generated from an internal 16 MHz RC oscillator
* - HSE high-speed external oscillator clock. 8 MHz from MCO output of ST-LINK.
* - PLL clock
* - MSI multispeed internal oscillator clock
* The MSI clock signal is generated from an internal RC oscillator. Seven frequency
* ranges are available: 65.536 kHz, 131.072 kHz, 262.144 kHz, 524.288 kHz, 1.048 MHz,
* 2.097 MHz (default value) and 4.194 MHz.
*
* The devices have the following two secondary clock sources
* - LSI low-speed internal RC clock
* Drives the watchdog and RTC. Approximately 37KHz
* - LSE low-speed external oscillator clock
* Driven by 32.768KHz crystal (X2) on the OSC32_IN and OSC32_OUT pins.
*/
#define STM32_BOARD_XTAL 8000000ul
#define STM32_HSI_FREQUENCY 16000000ul
#define STM32_LSI_FREQUENCY 37000 /* Approximately 37KHz */
#define STM32_HSE_FREQUENCY STM32_BOARD_XTAL
#define STM32_LSE_FREQUENCY 32768 /* X2 on board */
/* PLL Configuration
*
* - PLL source is HSE -> 8MHz
* - PLL multipler is 12 -> 96MHz PLL VCO clock output
* - PLL output divider 3 -> 32MHz divided down PLL VCO clock output
*
* Resulting SYSCLK frequency is 8MHz x 12 / 3 = 32MHz
*
* USB/SDIO:
* If the USB or SDIO interface is used in the application, the PLL VCO
* clock (defined by STM32_CFGR_PLLMUL) must be programmed to output a 96
* MHz frequency. This is required to provide a 48 MHz clock to the USB or
* SDIO (SDIOCLK or USBCLK = PLLVCO/2).
* SYSCLK
* The system clock is derived from the PLL VCO divided by the output division factor.
* Limitations:
* 96 MHz as PLLVCO when the product is in range 1 (1.8V),
* 48 MHz as PLLVCO when the product is in range 2 (1.5V),
* 24 MHz when the product is in range 3 (1.2V).
* Output division to avoid exceeding 32 MHz as SYSCLK.
* The minimum input clock frequency for PLL is 2 MHz (when using HSE as PLL source).
*/
#if 1
#define STM32_CFGR_PLLSRC RCC_CFGR_PLLSRC /* PLL clocked by the HSE */
#define STM32_HSEBYP_ENABLE 1
#define STM32_CFGR_PLLMUL RCC_CFGR_PLLMUL_CLKx12 /* PLLMUL = 12 */
#define STM32_CFGR_PLLDIV RCC_CFGR_PLLDIV_3 /* PLLDIV = 3 */
#define STM32_PLL_FREQUENCY (12*STM32_BOARD_XTAL) /* PLL VCO Frequency is 96MHz */
#else
#define STM32_CFGR_PLLSRC 0 /* PLL clocked by the HSI RC */
#define STM32_CFGR_PLLMUL RCC_CFGR_PLLMUL_CLKx6 /* PLLMUL = 6 */
#define STM32_CFGR_PLLDIV RCC_CFGR_PLLDIV_3 /* PLLDIV = 3 */
#define STM32_PLL_FREQUENCY (6*STM32_HSI_FREQUENCY) /* PLL VCO Frequency is 96MHz */
#endif
/* Use the PLL and set the SYSCLK source to be the divided down PLL VCO output
* frequency (STM32_PLL_FREQUENCY divided by the PLLDIV value).
*/
#define STM32_SYSCLK_SW RCC_CFGR_SW_PLL
#define STM32_SYSCLK_SWS RCC_CFGR_SWS_PLL
#define STM32_SYSCLK_FREQUENCY (STM32_PLL_FREQUENCY/3)
/* AHB clock (HCLK) is SYSCLK (32MHz) */
#define STM32_RCC_CFGR_HPRE RCC_CFGR_HPRE_SYSCLK
#define STM32_HCLK_FREQUENCY STM32_SYSCLK_FREQUENCY
#define STM32_BOARD_HCLK STM32_HCLK_FREQUENCY /* Same as above, to satisfy compiler */
/* APB2 clock (PCLK2) is HCLK (32MHz) */
#define STM32_RCC_CFGR_PPRE2 RCC_CFGR_PPRE2_HCLK
#define STM32_PCLK2_FREQUENCY STM32_HCLK_FREQUENCY
#define STM32_APB2_CLKIN STM32_PCLK2_FREQUENCY
/* APB1 clock (PCLK1) is HCLK (32MHz) */
#define STM32_RCC_CFGR_PPRE1 RCC_CFGR_PPRE1_HCLK
#define STM32_PCLK1_FREQUENCY STM32_HCLK_FREQUENCY
/* TODO: Timers */
/* LED definitions **********************************************************/
/* The Nucleo L152RE board has three LEDs. Two of these are controlled by
* logic on the board and are not available for software control:
*
* LD1 COM: LD1 default status is red. LD1 turns to green to indicate that
* communications are in progress between the PC and the
* ST-LINK/V2-1.
* LD3 PWR: red LED indicates that the board is powered.
*
* And one can be controlled by software:
*
* User LD2: green LED is a user LED connected to the I/O PA5 of the
* STM32L152RET6.
*
* If CONFIG_ARCH_LEDS is not defined, then the user can control the LED in
* any way. The following definition is used to access the LED.
*/
/* LED index values for use with board_userled() */
#define BOARD_LED1 0 /* User LD2 */
#define BOARD_NLEDS 1
/* LED bits for use with board_userled_all() */
#define BOARD_LED1_BIT (1 << BOARD_LED1)
/* If CONFIG_ARCH_LEDs is defined, then NuttX will control the LED on board
* the Nucleo L152RE. The following definitions describe how NuttX controls
* the LED:
*
* SYMBOL Meaning LED1 state
* ------------------ ----------------------- ----------
* LED_STARTED NuttX has been started OFF
* LED_HEAPALLOCATE Heap has been allocated OFF
* LED_IRQSENABLED Interrupts enabled OFF
* LED_STACKCREATED Idle stack created ON
* LED_INIRQ In an interrupt No change
* LED_SIGNAL In a signal handler No change
* LED_ASSERTION An assertion failed No change
* LED_PANIC The system has crashed Blinking
* LED_IDLE STM32 is is sleep mode Not used
*/
#define LED_STARTED 0
#define LED_HEAPALLOCATE 0
#define LED_IRQSENABLED 0
#define LED_STACKCREATED 1
#define LED_INIRQ 2
#define LED_SIGNAL 2
#define LED_ASSERTION 2
#define LED_PANIC 1
/* Button definitions *******************************************************/
/* The Nucleo L152RE supports two buttons; only one button is controllable
* by software:
*
* B1 USER: user button connected to the I/O PC13 of the STM32L152RET6.
* B2 RESET: push button connected to NRST is used to RESET the
* STM32L152RET6.
*/
#define BUTTON_USER 0
#define NUM_BUTTONS 1
#define BUTTON_USER_BIT (1 << BUTTON_USER)
/* Alternate function pin selections ****************************************/
/* USART */
/* By default the USART2 is connected to STLINK Virtual COM Port:
* USART2_RX - PA3
* USART2_TX - PA2
*/
#define GPIO_USART2_RX GPIO_USART2_RX_1 /* PA3 */
#define GPIO_USART2_TX GPIO_USART2_TX_1 /* PA2 */
#endif /* __BOARDS_ARM_STM32_NUCLEO_L152RE_INCLUDE_BOARD_H */
|
lavishabhambri/Weekly-Algo-Newsletter
|
Number Theory/Codes/Bitwise/findUniqueAmongArrayOfTriplets.cpp
|
<filename>Number Theory/Codes/Bitwise/findUniqueAmongArrayOfTriplets.cpp
#include <bits/stdc++.h>
using namespace std;
#define INT_SIZE 32
int getSingle(vector<int>arr, int n)
{
// Initialize result
int result = 0;
int x, sum;
// Iterate through every bit
for (int i = 0; i < INT_SIZE; i++) {
// Find sum of set bits at ith position in all
// array elements
sum = 0;
x = (1 << i); // mask
for (int j = 0; j < n; j++) {
if (arr[j] & x)
sum++;
}
// The bits with sum not multiple of 3, are the
// bits of element with single occurrence.
if ((sum % 3) != 0)
result |= x;
}
return result;
}
int main()
{
int n;
cin >> n;
vector<int>v;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
}
cout << getSingle(v, n) << endl;
return 0;
}
|
senRsl/AndroidRtmpPublisher
|
rtmpPublisher/app/src/main/java/com/spark/live/PreviewActivity.java
|
package com.spark.live;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.spark.live.sdk.engine.ISimpleLiveEngine;
import com.spark.live.sdk.engine.SimpleLivePulisherEngine;
public class PreviewActivity extends Activity implements View.OnClickListener{
Button btnSwitch;
ISimpleLiveEngine engine;
String url;
long lastTimeFlag = 0;
boolean isRunning = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
Intent intent = getIntent();
url = intent.getStringExtra("url");
SurfaceView preview = (SurfaceView)findViewById(R.id.camera_preview);
btnSwitch = (Button) findViewById(R.id.btn_switch);
btnSwitch.setOnClickListener(this);
engine = SimpleLivePulisherEngine.getInstance();
engine.Init(this);
assert preview != null;
SurfaceHolder holder = preview.getHolder();
holder.addCallback(engine);
}
@Override
protected void onResume() {
if(!isRunning) {
engine.Start(url);
isRunning = true;
}
super.onResume();
}
@Override
public void onClick(View v) {
if (v == btnSwitch) {
long curTime = System.currentTimeMillis();
if (curTime - lastTimeFlag > 3000) {
lastTimeFlag = curTime;
engine.SwitchCamera();
} else {
Toast.makeText(getApplicationContext(), "切换太快了,休息下", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onDestroy() {
engine.Destroy();
super.onDestroy();
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
|
laaners/progetto-labiagi_pick_e_delivery
|
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_messages/messages/navsat_fix_message.h
|
<reponame>laaners/progetto-labiagi_pick_e_delivery
#pragma once
#include "base_sensor_message.h"
#include <srrg_property/property_eigen.h>
namespace srrg2_core {
class NavsatFixMessage : public BaseSensorMessage {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
//! @brief confortable enums
enum FixStatus : int8_t { NO_FIX = -1, FIX = 0, SBAS_FIX = 1, GBAS_FIX = 2 };
enum ServiceType : uint16_t { GPS = 1, GLONASS = 2, COMPASS = 4, GALILEO = 8 };
enum CovarianceType : uint8_t { UNKNOWN = 0, APPROXIMATED = 1, DIAGONAL_KNOWN = 2, KNOWN = 3 };
//! @brief default ctor
NavsatFixMessage(const std::string& topic_ = "",
const std::string& frame_id_ = "",
const int& seq_ = -1,
const double& timestamp_ = -1.f);
//! @brief gets the 3d coordinates from the current reading using a non spherical model of the
//! earth: link [ https://stackoverflow.com/a/8982005 ]
void getPosition(Vector3f& position_xyz_);
//! @brief status of the service
//! {-1: no fix; 0 = unaugmented fix; 1: fix w/ satellite-based augmentation, 2: fix w/
//! ground-based augmentation}
PropertyInt status;
//! @brief service type
//! {1: gps; 2: glonass; 4: compass (also beidou); 8: galileo}
PropertyUnsignedInt service;
//! @brief covariance can be fully known, partially known (only diagonal),
//! approximated or not known at all
PropertyUInt8 covariance_type;
//! @brief confortable bool that tells me if the altitude is set in this message
PropertyBool has_altitude;
//! @brief latitude[degrees].Positive is north of equator; negative is south.
PropertyDouble latitude;
//! @brief longitude[degrees].Positive is east of prime meridian; negative is west.
PropertyDouble longitude;
//! @brief altitude [m]. Positive is above the WGS 84 ellipsoid
//! std::numeric_limits<double>::max means that there is no altitude information
PropertyDouble altitude;
//! @brief row major covariance type of the fix - row major reading from ros
PropertyEigen_<Matrix3f> covariance;
};
using NavsatFixMessagePtr = std::shared_ptr<NavsatFixMessage>;
} // namespace srrg2_core
|
IBMStreams/vscode-ide
|
src/webviews/cloudPakForDataAppService/resources/data-table/components/Table/Table.js
|
<filename>src/webviews/cloudPakForDataAppService/resources/data-table/components/Table/Table.js
import {
Add16,
NotSent16,
Save16,
Send16,
SendAlt16,
TrashCan16
} from '@carbon/icons-react';
import {
Button,
DataTable,
DataTableSkeleton,
Dropdown,
ListItem,
Loading,
Modal,
Table,
TableBatchAction,
TableBatchActions,
TableBody,
TableCell,
TableContainer,
TableHead,
TableHeader,
TableRow,
TableSelectAll,
TableSelectRow,
TableToolbar,
TableToolbarContent,
TableToolbarSearch,
TextInput,
Tooltip,
UnorderedList
} from 'carbon-components-react';
import PropTypes from 'prop-types';
import React, { useEffect, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import noDataForTable from '../../images/noDataForTable.svg';
import noSearchResultsForTable from '../../images/noSearchResultsForTable.svg';
import {
ACTION,
DataUtils,
ROW_HEADER_ID,
ROW_HEADER_ID_ADD_NEW,
ROW_HEADER_ID_RENAMED,
ROW_HEADER_STATUS,
ROW_ID_PREFIX,
STATUS
} from '../../utils';
import { useApp } from '../App/context';
import { DefaultModalProps, ModalType, StatusModal } from '../StatusModal';
import OverflowTooltip from './OverflowTooltip';
const TupleTable = ({ receiveData, sendData, action, schema }) => {
const { data, isLoading, setData, setIsLoading } = useApp();
const [rowNum, setRowNum] = useState(10);
const [tableRows, setTableRows] = useState(
DataUtils.transformData(data.slice(0, rowNum))
);
const [isAddingNew, setIsAddingNew] = useState(false);
const [newRowValues, setNewRowValues] = useState({});
const [
isShowingDeleteConfirmationModal,
setIsShowingDeleteConfirmationModal
] = useState(false);
const [isSendingData, setIsSendingData] = useState(false);
const [rowsSelected, setRowsSelected] = useState(null);
const [isFiltered, setIsFiltered] = useState(false);
const [modalProps, setModalProps] = useState(DefaultModalProps);
const [inputValueError, setInputValueError] = useState(false);
// Retrieve data on load
useEffect(() => {
async function init() {
if (action === ACTION.RECEIVE) {
const { data: responseData, error } = await receiveData();
if (error) {
setModalProps({
isShowing: true,
type: ModalType.Error,
title: `Error retrieving the data`,
description: error
});
} else {
// Sort newest to oldest if retrieving data
setData(
action === ACTION.RECEIVE ? responseData.reverse() : responseData
);
}
setIsLoading(false);
}
}
init();
}, []);
// When data changes (i.e., data is imported), update table rows
useEffect(() => {
setTableRows(DataUtils.transformData(data.slice(0, rowNum)));
}, [data, rowNum]);
const statusHeader =
action === ACTION.SEND
? [{ key: ROW_HEADER_STATUS, header: 'Status', attr: null }]
: [];
const schemaHeaders = Object.keys(schema).map((key) => ({
key: key === ROW_HEADER_ID ? ROW_HEADER_ID_RENAMED : key,
header: key,
attr: schema[key]
}));
const tableHeaders = [...statusHeader, ...schemaHeaders];
const handleAdd = () => {
if (isAddingNew) {
const newTableRows = [...tableRows];
newTableRows.shift();
const newTableRow = {
[ROW_HEADER_ID]: `${ROW_ID_PREFIX}-${uuidv4()}`,
...newRowValues
};
newTableRows.unshift(newTableRow);
setTableRows(newTableRows);
setData(DataUtils.transformTableRows(newTableRows));
setIsAddingNew(false);
setNewRowValues({});
} else {
const emptyRow = {};
const emptyRowValues = {};
tableHeaders.forEach(({ key, attr }) => {
if (key === ROW_HEADER_STATUS) {
emptyRow[key] = ROW_HEADER_STATUS;
emptyRowValues[key] = { status: STATUS.NONE, detail: null };
} else {
emptyRow[key] = attr.enum ? attr.enum[0] : '';
emptyRowValues[key] = attr.enum ? attr.enum[0] : null;
}
});
emptyRow[ROW_HEADER_ID] = ROW_HEADER_ID_ADD_NEW;
setTableRows([emptyRow, ...tableRows]);
setIsAddingNew(true);
setNewRowValues(emptyRowValues);
}
};
const handleAddNewInputChange = (value, id) => {
const newValues = { ...newRowValues };
const schemaKey = id === ROW_HEADER_ID_RENAMED ? ROW_HEADER_ID : id;
const schemaAttr = schema[schemaKey];
let realValue = value.trim() === '' ? null : value;
if (schemaAttr.type === 'boolean') {
realValue = value === 'true';
} else if (
schemaAttr.type === 'object' ||
schemaAttr.type === 'array' ||
(schemaAttr.type === undefined && schemaAttr.properties)
) {
// Object or array type
try {
realValue = JSON.parse(value);
setInputValueError(false);
} catch (err) {
const jsonError = err && err.message ? ` ${err.message.trim()}` : '';
setInputValueError({ id, error: jsonError });
}
} else if (schemaAttr?.description?.startsWith('SPL type: optional')) {
realValue = value === 'null' || value.trim() === '' ? null : value;
}
newValues[id] = realValue;
setNewRowValues(newValues);
};
const handleDeleteConfirmation = (selectedRows, hideBatchActions) => {
setIsShowingDeleteConfirmationModal(true);
setRowsSelected(selectedRows);
hideBatchActions();
};
const handleDelete = () => {
setIsShowingDeleteConfirmationModal(false);
const rowIdsToDelete = rowsSelected.reduce((rows, row) => {
if (row.id !== ROW_HEADER_ID_ADD_NEW) {
rows.push(row.id);
}
return rows;
}, []);
const tableRowsToKeep = tableRows.filter(
(tableRow) => !rowIdsToDelete.includes(tableRow.id)
);
setTableRows(tableRowsToKeep);
setData(DataUtils.transformTableRows(tableRowsToKeep));
};
const handleSendAll = async () => {
const dataToSend = { items: data };
setIsSendingData(true);
const { error } = await sendData(dataToSend);
setIsSendingData(false);
let status;
const detail = { timestamp: new Date() };
if (error) {
status = STATUS.FAILED;
detail.error = error;
setModalProps({
isShowing: true,
type: ModalType.Error,
title: `Error sending the data`,
description: error
});
} else {
status = STATUS.SENT;
setModalProps({
isShowing: true,
type: ModalType.Success,
title: `Successfully sent the data`,
description: null
});
}
// Update rows with status
const newTableRows = [...tableRows];
newTableRows.forEach((row) => {
// eslint-disable-next-line no-param-reassign
row[ROW_HEADER_STATUS] = { status, detail };
});
setTableRows(newTableRows);
setData(DataUtils.transformTableRows(newTableRows));
};
const handleSend = async (selectedRows, hideBatchActions) => {
const rowsToSend = selectedRows.reduce((rows, row) => {
if (row.id !== ROW_HEADER_ID_ADD_NEW) {
rows.push(tableRows.find((tableRow) => tableRow.id === row.id));
}
return rows;
}, []);
const dataToSend = {
items: DataUtils.transformTableRows(rowsToSend)
};
const { error } = await sendData(dataToSend);
let status;
const detail = { timestamp: new Date() };
if (error) {
status = STATUS.FAILED;
detail.error = error;
setModalProps({
isShowing: true,
type: ModalType.Error,
title: `Error sending the data`,
description: error
});
} else {
status = STATUS.SENT;
setModalProps({
isShowing: true,
type: ModalType.Success,
title: `Successfully sent the data`,
description: null
});
}
hideBatchActions();
// Update rows with status
const newTableRows = [...tableRows];
selectedRows.forEach((row) => {
const matchingTableRowIndex = tableRows.findIndex(
(tableRow) => tableRow.id === row.id
);
newTableRows[matchingTableRowIndex][ROW_HEADER_STATUS] = {
status,
detail
};
});
setTableRows(newTableRows);
setData(DataUtils.transformTableRows(newTableRows));
};
const getSchemaInfo = (key) => {
const schemaKey = key === ROW_HEADER_ID_RENAMED ? ROW_HEADER_ID : key;
const info = Object.keys(schema[schemaKey]).map((prop) => {
let propValue = schema[schemaKey][prop];
let isJson = false;
if (
Array.isArray(propValue) ||
Object.prototype.toString.call(propValue) === '[object Object]'
) {
propValue = JSON.stringify(propValue, null, 2);
isJson = true;
}
return (
<ListItem key={prop}>
<strong>{prop}</strong>: {isJson ? <pre>{propValue}</pre> : propValue}
</ListItem>
);
});
return info;
};
const handleScroll = (e) => {
const bottom =
e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
setRowNum(rowNum + 10);
}
};
const handleKeyPress = (event) => {
if (event.key === 'Enter') {
handleAdd();
}
};
const numRows = isAddingNew ? tableRows.length - 1 : tableRows.length;
return (
<>
<Loading active={isSendingData} description="Sending data..." />
<StatusModal
isShowingModal={modalProps.isShowing}
onClose={() => setModalProps(DefaultModalProps)}
type={modalProps.type}
title={modalProps.title}
description={modalProps.description}
/>
<div className="table-container">
<Modal
danger
modalHeading="Are you sure you want to delete the selected rows?"
onRequestClose={() => setIsShowingDeleteConfirmationModal(false)}
onRequestSubmit={() => handleDelete()}
open={isShowingDeleteConfirmationModal}
primaryButtonText="Delete"
secondaryButtonText="Cancel"
size="sm"
/>
{isLoading ? (
<DataTableSkeleton rowCount={10} showHeader={false} />
) : (
<DataTable
rows={tableRows}
headers={tableHeaders}
stickyHeader
isSortable
>
{({
rows,
headers,
getHeaderProps,
getRowProps,
getSelectionProps,
getToolbarProps,
getBatchActionProps,
onInputChange,
selectedRows,
getTableProps,
getTableContainerProps
}) => (
<TableContainer className="table" {...getTableContainerProps()}>
<TableToolbar {...getToolbarProps()}>
<TableBatchActions
{...getBatchActionProps()}
totalSelected={
isAddingNew
? getBatchActionProps().totalSelected - 1
: getBatchActionProps().totalSelected
}
>
<TableBatchAction
// prettier-ignore
onClick={() =>
handleDeleteConfirmation(selectedRows, getBatchActionProps().onCancel)}
renderIcon={TrashCan16}
tabIndex={
getBatchActionProps().shouldShowBatchActions ? 0 : -1
}
>
Delete
</TableBatchAction>
<Button
disabled={
rows.length === 0 ||
(rows.length === 1 ? isAddingNew : false)
}
iconDescription="Send"
kind="primary"
onClick={() =>
handleSend(selectedRows, getBatchActionProps().onCancel)
}
renderIcon={Send16}
size="small"
tabIndex={
getBatchActionProps().shouldShowBatchActions ? -1 : 0
}
>
Send
</Button>
</TableBatchActions>
<TableToolbarContent>
<TableToolbarSearch
onChange={(e) => {
setIsFiltered(e.target.value !== '');
onInputChange(e);
}}
tabIndex={
getBatchActionProps().shouldShowBatchActions ? -1 : 0
}
/>
{action === ACTION.SEND && isAddingNew && (
<Button
kind="ghost"
onClick={() => {
const newTableRows = [...tableRows];
newTableRows.shift();
setTableRows(newTableRows);
setIsAddingNew(false);
setNewRowValues({});
getBatchActionProps().onCancel();
}}
size="small"
tabIndex={
getBatchActionProps().shouldShowBatchActions ? -1 : 0
}
>
Cancel
</Button>
)}
{action === ACTION.SEND && (
<>
<Button
disabled={
isAddingNew &&
(!!inputValueError ||
Object.keys(newRowValues).some((key) => {
const schemaKey =
key === ROW_HEADER_ID_RENAMED
? ROW_HEADER_ID
: key;
const isOptionalType = schema[
schemaKey
]?.description?.startsWith(
'SPL type: optional'
);
if (key !== ROW_HEADER_STATUS) {
if (isOptionalType) {
return false;
}
if (newRowValues[key] === null) {
return true;
}
}
return false;
}))
}
iconDescription={isAddingNew ? 'Save' : 'Add'}
kind="secondary"
onClick={handleAdd}
renderIcon={isAddingNew ? Save16 : Add16}
size="small"
tabIndex={
getBatchActionProps().shouldShowBatchActions
? -1
: 0
}
>
{isAddingNew ? 'Save' : 'Add'}
</Button>
<Button
disabled={
rows.length === 0 ||
(rows.length === 1 ? isAddingNew : false) ||
isAddingNew
}
iconDescription="Send all"
kind="primary"
onClick={handleSendAll}
renderIcon={Send16}
size="small"
tabIndex={
getBatchActionProps().shouldShowBatchActions
? -1
: 0
}
>
Send all
</Button>
</>
)}
</TableToolbarContent>
</TableToolbar>
<Table onScroll={handleScroll} {...getTableProps()}>
<TableHead>
<TableRow>
{/* eslint-disable-next-line no-nested-ternary */}
{action === ACTION.SEND ? (
rows.length &&
(rows.length === 1 ? !isAddingNew : true) ? (
<TableSelectAll {...getSelectionProps()} />
) : (
<th className="table-container__select-placeholder">
<div />
</th>
)
) : null}
{headers.map((header, index) => {
let tooltipDirection;
if (
(action === ACTION.RECEIVE && index === 0) ||
(action === ACTION.SEND && index === 1)
) {
tooltipDirection = 'right';
} else if (index === headers.length - 1) {
tooltipDirection = 'left';
} else {
tooltipDirection = 'top';
}
return (
<TableHeader
key={header.key}
className={
header.key === ROW_HEADER_STATUS
? 'table-container__status'
: null
}
{...getHeaderProps({ header })}
>
{header.key !== ROW_HEADER_STATUS ? (
<Tooltip
className="table-container__schema-tooltip"
direction={tooltipDirection}
showIcon={false}
triggerClassName="table-container__schema-tooltip-trigger"
triggerText={header.header}
>
<UnorderedList>
{getSchemaInfo(header.key)}
</UnorderedList>
</Tooltip>
) : (
header.header
)}
</TableHeader>
);
})}
</TableRow>
</TableHead>
<TableBody className="table-container__table-body">
{rows.length ? (
rows.map((row, i) => {
let firstCellComponent = null;
if (action === ACTION.SEND) {
firstCellComponent =
row.id === ROW_HEADER_ID_ADD_NEW ? (
<td className="table-container__select-placeholder">
<div />
</td>
) : (
<TableSelectRow {...getSelectionProps({ row })} />
);
}
return (
// eslint-disable-next-line react/no-array-index-key
<TableRow key={i} {...getRowProps({ row })}>
{firstCellComponent}
{row.cells.map((cell) => {
const {
id,
info: { header },
value
} = cell;
if (header === ROW_HEADER_STATUS) {
let statusTooltip = null;
const { status, detail } = value;
if (status === STATUS.FAILED) {
statusTooltip = (
<Tooltip
align="end"
className="table-container__status-tooltip"
direction="right"
iconDescription="Failed to send"
renderIcon={NotSent16}
showIcon
triggerClassName="table-container__status-icon"
>
<strong>Time</strong>
{`: ${detail.timestamp.toLocaleString()}`}
<br />
<strong>Error</strong>
{`: ${detail.error}`}
</Tooltip>
);
} else if (status === STATUS.SENT) {
statusTooltip = (
<Tooltip
align="end"
className="table-container__status-tooltip"
direction="right"
iconDescription="Sent"
renderIcon={SendAlt16}
showIcon
triggerClassName="table-container__status-icon"
>
<strong>Time</strong>
{`: ${detail.timestamp.toLocaleString()}`}
</Tooltip>
);
}
return (
<TableCell
className="table-container__status"
key={id}
>
{statusTooltip}
</TableCell>
);
}
const cellSchema =
header === ROW_HEADER_ID_RENAMED
? schema[ROW_HEADER_ID]
: schema[header];
let dropdownItems = null;
if (cellSchema.enum) {
dropdownItems = cellSchema.enum.map(
(enumValue) => ({
label: enumValue
})
);
} else if (cellSchema.type === 'boolean') {
dropdownItems = ['true', 'false'].map(
(bool) => ({
label: bool
})
);
}
const addNewComponent = dropdownItems ? (
<Dropdown
id={`dropdown-${id}`}
items={dropdownItems}
label=""
light
onChange={(e) => {
handleAddNewInputChange(
e.selectedItem.label,
header
);
}}
selectedItem={dropdownItems.find(
(item) =>
item.label === newRowValues[header]
)}
size="sm"
/>
) : (
<TextInput
id={`text-input-${id}`}
labelText=""
light
onChange={(e) =>
handleAddNewInputChange(
e.target.value,
header
)
}
onKeyPress={handleKeyPress}
size="sm"
warn={
inputValueError &&
inputValueError.id === header
}
warnText={
inputValueError &&
inputValueError.id === header
? inputValueError.error
: null
}
/>
);
return (
<TableCell
className={
row.id === ROW_HEADER_ID_ADD_NEW
? 'table-container__add-new-input'
: null
}
key={id}
>
{row.id === ROW_HEADER_ID_ADD_NEW ? (
addNewComponent
) : (
<OverflowTooltip
direction="bottom"
tooltipText={value}
>
{value}
</OverflowTooltip>
)}
</TableCell>
);
})}
</TableRow>
);
})
) : (
<tr className="table-container__no-data-row">
<td className="table-container__no-data-cell">
<div className="table-container__no-data-container">
<div className="table-container__no-data-image">
<img
src={
isFiltered
? noSearchResultsForTable
: noDataForTable
}
alt="No data"
/>
</div>
<div className="table-container__no-data-message">
{isFiltered
? 'There were no results found.'
: 'There is no data.'}
</div>
</div>
</td>
</tr>
)}
</TableBody>
</Table>
</TableContainer>
)}
</DataTable>
)}
<footer className="table-footer">
<div className="table-footer__label">Data set:</div>
<div className="table-footer__value">{`${numRows} row${
numRows === 1 ? '' : 's'
}`}</div>
</footer>
</div>
</>
);
};
TupleTable.propTypes = {
receiveData: PropTypes.func.isRequired,
sendData: PropTypes.func.isRequired,
action: PropTypes.string.isRequired,
schema: PropTypes.object.isRequired
};
export default TupleTable;
|
emayer2/dataverse
|
src/main/java/edu/harvard/iq/dataverse/export/DDIExporter.java
|
<gh_stars>1-10
package edu.harvard.iq.dataverse.export;
import com.google.auto.service.AutoService;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.export.ddi.DdiExportUtil;
import edu.harvard.iq.dataverse.export.spi.Exporter;
import edu.harvard.iq.dataverse.util.BundleUtil;
import edu.harvard.iq.dataverse.util.SystemConfig;
import java.io.OutputStream;
import javax.ejb.EJB;
import javax.json.JsonObject;
import javax.xml.stream.XMLStreamException;
/**
*
* @author <NAME>
* (based on the original DDIExporter by
* @author skraffmi
* - renamed OAI_DDIExporter)
*/
@AutoService(Exporter.class)
public class DDIExporter implements Exporter {
// TODO:
// move these into the ddi export utility
private static String DEFAULT_XML_NAMESPACE = "ddi:codebook:2_5";
private static String DEFAULT_XML_SCHEMALOCATION = "http://www.ddialliance.org/Specification/DDI-Codebook/2.5/XMLSchema/codebook.xsd";
private static String DEFAULT_XML_VERSION = "2.5";
// This exporter is for the "full" DDI, that includes the file-level,
// <data> and <var> metadata.
@Override
public String getProviderName() {
return "ddi";
}
@Override
public String getDisplayName() {
return BundleUtil.getStringFromBundle("dataset.exportBtn.itemLabel.ddi") != null ? BundleUtil.getStringFromBundle("dataset.exportBtn.itemLabel.ddi") : "DDI";
}
@Override
public void exportDataset(DatasetVersion version, JsonObject json, OutputStream outputStream) throws ExportException {
try {
DdiExportUtil.datasetJson2ddi(json, version, outputStream);
} catch (XMLStreamException xse) {
throw new ExportException ("Caught XMLStreamException performing DDI export");
}
}
@Override
public Boolean isXMLFormat() {
return true;
}
@Override
public Boolean isHarvestable() {
// No, we don't want this format to be harvested!
// For datasets with tabular data the <data> portions of the DDIs
// become huge and expensive to parse; even as they don't contain any
// metadata useful to remote harvesters. -- L.A. 4.5
return false;
}
@Override
public Boolean isAvailableToUsers() {
return true;
}
@Override
public String getXMLNameSpace() throws ExportException {
return this.DEFAULT_XML_NAMESPACE;
}
@Override
public String getXMLSchemaLocation() throws ExportException {
return this.DEFAULT_XML_SCHEMALOCATION;
}
@Override
public String getXMLSchemaVersion() throws ExportException {
return this.DEFAULT_XML_VERSION;
}
@Override
public void setParam(String name, Object value) {
// this exporter does not uses or supports any parameters as of now.
}
}
|
xiaobing007/dagli
|
math-vector/src/main/java/com/linkedin/dagli/math/vector/LazyClippedVector.java
|
<filename>math-vector/src/main/java/com/linkedin/dagli/math/vector/LazyClippedVector.java
package com.linkedin.dagli.math.vector;
/**
* Lazily clips a vector's values; the clipping range must include 0 (to be consistent with the semantics of a vector--
* otherwise there would be an infinite number of non-zero elements.)
*/
class LazyClippedVector extends LazyTransformedValueVector {
private static final long serialVersionUID = 1;
private final double _min;
private final double _max;
/**
* Default constructor for the benefit of Kryo serialization. Results in an invalid instance (Kryo will fill in the
* fields with deserialized values after instantiation).
*/
private LazyClippedVector() {
this(null, 0, 0);
}
/**
* Creates a new lazy clipping vector that lazily transforms the values of a wrapped vector
*
* @param wrapped the vector whose values will be transformed
* @param min the minimum value for each clipped element; must be <= 0
* @param max the maximum value for each clipped element; must be >= 0
*/
public LazyClippedVector(Vector wrapped, double min, double max) {
super(wrapped);
if (min > 0) {
throw new IllegalArgumentException("Minimum clipping value cannot be > 0");
} else if (max < 0) {
throw new IllegalArgumentException("Maximum clipping value cannot be < 0");
}
_min = min;
_max = max;
}
@Override
protected double compute(long index, double value) {
if (value > _max) {
return _max;
} else if (value < _min) {
return _min;
} else {
return value; // note that value may be NaN
}
}
@Override
public Class<? extends Number> valueType() {
return getWrappedVector().valueType();
}
}
|
harigad/Car_Keys_UI
|
app/controllers/poll/poll_profile/poll_profile.js
|
<gh_stars>0
var login = require('Login');
var _colors = ["#990000"];
var args = arguments[0] || {};
var _data = args._data || {};
var poll_data = JSON.parse(_data.data);
$.question.setText(poll_data.question);
load();
$.header.openWindow($.poll_profile);
function load(created){
var url = Alloy.Globals._search;
var data = {type:"poll",pollid:_data.ouid,action:"summary",accessToken:login.getAccessToken()};
if(created){
data.created = created;
}
var client = Ti.Network.createHTTPClient({
onload : function(e) {
var response = JSON.parse(this.responseText);
build(response,created);
},
onerror: function(e){
Ti.API.error("User.load error " + e);
}
});
// Prepare the connection.
client.open("POST", url);
// Send the request.
client.send(data);
}
function build(response){
var poll_info = response.info;
var options = JSON.parse(poll_info.options);
var countObjArr = response.feed;
for(var i=0;i<options.length;i++){
var countObj = getCountObjForOption(options[i],countObjArr);
var feed_item = Alloy.createController("poll/poll_profile/poll_profile_answer_item",{_answer:options[i],_countObj:countObj});
$.main.add(feed_item.getView());
}
drawPie();
}
function drawPie(){
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
Ti.App.fireEvent("drawPie",{data:data});
}
function getCountObjForOption(option,countObjArr){
for(var i=0;i<countObjArr.length;i++){
if(countObjArr[i].answer == option){
return countObjArr[i];
}
}
return {};
}
exports.refresh = function(){
load();
};
function more(){
$.more.setText("please wait...");
load(_created);
}
function clear(){
var len = $.main.children.length;
for(var i=0;i<len;i++){
$.main.remove($.main.children[0]);
}
}
|
SeanTBooker/edgefs
|
src/ccow/test/cmcache_test.c
|
<reponame>SeanTBooker/edgefs<gh_stars>10-100
/*
* Copyright (c) 2015-2018 Nexenta Systems, inc.
*
* This file is part of EdgeFS Project
* (see https://github.com/Nexenta/edgefs).
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "ccowutil.h"
#include "cmocka.h"
#include "common.h"
#include "ccow.h"
#include "ccowd.h"
#include "../src/libccow/ccow-impl.h"
ccow_t tc, *tc_list;
int dd = 0;
#define NUM_TENANTS 3
int num_tenants_init = 0;
static void
libccowd_setup(void **state)
{
if(!dd)
assert_int_equal(ccow_daemon_init(NULL), 0);
usleep(2 * 1000000L);
}
static void
libccow_setup(void **state)
{
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/etc/ccow/ccow.json", nedge_path());
int fd = open(path, O_RDONLY);
assert_true(fd >= 0);
char *buf = je_calloc(1, 16384);
assert_non_null(buf);
assert_true(read(fd, buf, 16384) != -1);
assert_int_equal(close(fd), 0);
assert_int_equal(ccow_admin_init(buf, "cltest", 7, &tc), 0);
je_free(buf);
tc_list = je_malloc(NUM_TENANTS * sizeof (ccow_t));
assert_non_null(tc_list);
}
static void
tenant_create(void **state)
{
assert_non_null(tc);
int err = ccow_tenant_create(tc, "test1", 6, NULL);
if (err && err != -EEXIST)
assert_int_equal(0, 1);
}
static void
tenant_init(void **state)
{
assert_non_null(tc_list);
int err = 0;
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/etc/ccow/ccow.json", nedge_path());
int fd = open(path, O_RDONLY);
assert_true(fd >= 0);
char *buf = je_calloc(1, 16384);
assert_non_null(buf);
assert_true(read(fd, buf, 16384) != -1);
assert_int_equal(close(fd), 0);
for (int i = 0; i < NUM_TENANTS; i++) {
err = ccow_tenant_init(buf, "cltest", 7, "test1", 6, &tc_list[i]);
if (err) {
printf("Tenant Init has failed on i = %d\n", i);
je_free(buf);
num_tenants_init = i == 0 ? i : i - 1;
return;
}
}
je_free(buf);
num_tenants_init = NUM_TENANTS;
}
static void
tenant_delete(void **state)
{
assert_non_null(tc);
assert_non_null(tc_list);
assert_int_equal(ccow_tenant_delete(tc, "test1", 6), 0);
}
static void
libccow_teardown(void **state)
{
assert_non_null(tc);
sleep(10);
for (int i = 0; i < num_tenants_init; i++) {
ccow_tenant_term(tc_list[i]);
}
je_free(tc_list);
ccow_tenant_term(tc);
}
static void
libccowd_teardown(void **state)
{
if (!dd)
ccow_daemon_term();
}
int
main(int argc, char **argv)
{
if (argc == 2) {
if (strcmp(argv[1], "-n") == 0)
dd = 1;
}
const UnitTest tests[] = {
unit_test(libccowd_setup),
unit_test(libccow_setup),
unit_test(tenant_create),
unit_test(tenant_init),
unit_test(tenant_delete),
unit_test(libccow_teardown),
unit_test(libccowd_teardown)
};
return run_tests(tests);
}
|
alashworth/stan-monorepo
|
src/stan/language/generator/generate_program_reader_fun.hpp
|
<reponame>alashworth/stan-monorepo
#ifndef STAN_LANG_GENERATOR_GENERATE_PROGRAM_READER_FUN_HPP
#define STAN_LANG_GENERATOR_GENERATE_PROGRAM_READER_FUN_HPP
#include "constants.hpp"
#include <stan/util/io/program_reader.hpp>
#include <ostream>
#include <vector>
namespace stan {
namespace lang {
/**
* Generate a top-level function that returns the program reader
* for the specified history.
*
* <p>Implementation note: Because this is only called when there
* is an error to report, reconstructing on each call has
* acceptable performance.
*
* @param[in] history record of I/O path for lines in compound program
* @param[in, out] o stream to which generated code is written
*/
void generate_program_reader_fun(const std::vector<io::preproc_event>& history,
std::ostream& o) {
o << "static stan::io::program_reader prog_reader__() {" << std::endl;
o << INDENT << "stan::io::program_reader reader;" << std::endl;
for (size_t i = 0; i < history.size(); ++i)
o << INDENT << "reader.add_event(" << history[i].concat_line_num_ << ", "
<< history[i].line_num_ << ", \"" << history[i].action_ << "\""
<< ", \"" << history[i].path_ << "\");" << std::endl;
o << INDENT << "return reader;" << std::endl;
o << "}" << std::endl << std::endl;
}
} // namespace lang
} // namespace stan
#endif
|
AMS21/PreyRun
|
src/Prey/ai_mutate.h
|
<filename>src/Prey/ai_mutate.h
#ifndef __PREY_AI_MUTATE_H__
#define __PREY_AI_MUTATE_H__
#ifndef ID_DEMO_BUILD //HUMANHEAD jsh PCF 5/26/06: code removed for demo build
class hhMutate : public hhMonsterAI {
public:
CLASS_PROTOTYPE(hhMutate);
protected:
void Event_OnProjectileLaunch(hhProjectile *proj);
void LinkScriptVariables();
idScriptBool AI_COMBAT;
};
#endif //HUMANHEAD jsh PCF 5/26/06: code removed for demo build
#endif
|
sklinkert/at
|
internal/trader/trader.go
|
<filename>internal/trader/trader.go
package trader
import (
"context"
"errors"
"fmt"
"github.com/shopspring/decimal"
log "github.com/sirupsen/logrus"
"github.com/sklinkert/at/internal/broker"
"github.com/sklinkert/at/internal/strategy"
"github.com/sklinkert/at/pkg/ohlc"
"github.com/sklinkert/at/pkg/tick"
"gorm.io/gorm"
"sort"
"sync"
"time"
)
type Trader struct {
ctx context.Context
StartTime time.Time
Instrument string
TickChan chan tick.Tick
running bool
clog *log.Entry
broker broker.Broker
strategy strategy.Strategy
persistTickData bool
persistCandleData bool
today *ohlc.OHLC
maxConcurrentPositions int
MaxAggregatedDrawdownInPips decimal.Decimal
reversedPerformanceInPips map[ohlc.OHLC]float64
gormDB *gorm.DB
positionBuyTime map[string]time.Time
openCandles []*ohlc.OHLC // strategy's candle + today's candle
closedCandles []*ohlc.OHLC
lastReceivedTick *tick.Tick
gitRev string
candleSubscribers []CandleSubscriber
positionSubscribers []PositionSubscriber
orderSubscribers []OrderSubscriber
closedPositionReferences map[string]bool
currencyCode string
sync.Mutex
}
type PositionSubscriber interface {
OnPosition(position broker.Position)
}
type CandleSubscriber interface {
OnCandle(candle ohlc.OHLC)
}
type OrderSubscriber interface {
OnOrder(order broker.Order)
}
type Option func(*Trader)
func WithBroker(broker broker.Broker) Option {
return func(trader *Trader) {
trader.broker = broker
}
}
func WithCandleSubscription(subscriber CandleSubscriber) Option {
return func(trader *Trader) {
trader.candleSubscribers = append(trader.candleSubscribers, subscriber)
}
}
func WithPositionSubscription(subscriber PositionSubscriber) Option {
return func(trader *Trader) {
trader.positionSubscribers = append(trader.positionSubscribers, subscriber)
}
}
//func WithOrderSubscription(subscriber OrderSubscriber) Option {
// return func(trader *Trader) {
// trader.orderSubscribers = append(trader.orderSubscribers, subscriber)
// }
//}
//
//func WithGatherPerformanceData() Option {
// return func(trader *Trader) {
// trader.gatherPerformanceData = true
// }
//}
func WithPersistTickData(persist bool) Option {
return func(trader *Trader) {
trader.persistTickData = persist
}
}
func WithPersistCandleData(persist bool) Option {
return func(trader *Trader) {
trader.persistCandleData = persist
}
}
func WithStrategy(strategy strategy.Strategy) Option {
return func(trader *Trader) {
trader.strategy = strategy
}
}
func WithCurrencyCode(currencyCode string) Option {
return func(trader *Trader) {
trader.currencyCode = currencyCode
}
}
func WithFeedStoredCandles(strategy strategy.Strategy) Option {
return func(trader *Trader) {
var limit = int(strategy.GetWarmUpCandleAmount())
var candlePeriod = strategy.GetCandleDuration()
log.Infof("Searching for warmup candles with period %s", candlePeriod)
var candles ohlc.OHLCList
if err := trader.gormDB.Limit(limit).Order("\"end\" DESC").Where("instrument = ? AND duration = ?", trader.Instrument, candlePeriod).Find(&candles).Error; err != nil {
log.WithError(err).Fatal("fetching stored candles failed")
}
sort.Sort(candles)
log.Infof("WithFeedStoredCandles: Sending %d candles to strategy for warming up", len(candles))
for _, candle := range candles {
candle.ForceClose()
strategy.OnWarmUpCandle(&candle)
}
}
}
func New(ctx context.Context, instrument, gitRev string, db *gorm.DB, options ...Option) *Trader {
var clog = log.WithFields(log.Fields{
"INSTRUMENT": instrument,
"GIT_REV": gitRev,
})
tr := &Trader{
ctx: ctx,
Instrument: instrument,
StartTime: time.Now(),
clog: clog,
TickChan: make(chan tick.Tick),
reversedPerformanceInPips: make(map[ohlc.OHLC]float64),
positionBuyTime: make(map[string]time.Time),
closedPositionReferences: make(map[string]bool),
gitRev: gitRev,
gormDB: db,
currencyCode: "USD", // default
}
for _, option := range options {
option(tr)
}
if tr.gormDB == nil {
if tr.persistTickData || tr.persistCandleData {
log.Fatalf("Persistence of ticks or/and candles requested but no DB given!")
}
} else {
if err := tr.gormDB.AutoMigrate(&ohlc.OHLC{}, &PerformanceRecord{}, &tick.Tick{}, &broker.Position{}); err != nil {
log.WithError(err).Fatal("db.AutoMigrate() failed")
}
}
return tr
}
func (tr *Trader) ID() string {
return fmt.Sprintf("rev_%s_strategy_%s", tr.gitRev, tr.strategy.Name())
}
func (tr *Trader) Start() error {
if tr.running {
return errors.New("already running")
}
tr.running = true
tr.clog.Info("Starting trader")
go tr.receiveTicks()
tr.broker.ListenToPriceFeed(tr.TickChan)
return nil
}
func (tr *Trader) Stop() error {
if !tr.running {
return errors.New("already stopped")
}
tr.clog.Info("Stopping trader")
tr.Lock()
defer tr.Unlock()
close(tr.TickChan)
tr.running = false
tr.printPositionPerformanceByNotes()
return nil
}
func (tr *Trader) GetClosedPositions() ([]broker.Position, error) {
positions, err := tr.broker.GetClosedPositions()
if err != nil {
return []broker.Position{}, err
}
for i := range positions {
positions[i].CandleBuyTime = tr.positionBuyTime[positions[i].Reference]
}
return positions, nil
}
func (tr *Trader) processTodayCandle(currentTick tick.Tick) {
const eodPeriod = time.Hour * 24 * 1 // 1d
if tr.today == nil || tr.today.Start.Day() != currentTick.Datetime.Day() {
if tr.today != nil {
tr.today.ForceClose()
}
tr.today = ohlc.New(tr.Instrument, currentTick.Datetime, eodPeriod, false)
}
tr.today.NewPrice(currentTick.Bid, currentTick.Datetime)
}
func (tr *Trader) getOpenPositions() ([]broker.Position, error) {
positions, err := tr.broker.GetOpenPositions()
if err != nil {
return []broker.Position{}, err
}
for i := range positions {
positions[i].CandleBuyTime = tr.positionBuyTime[positions[i].Reference]
}
return positions, nil
}
func (tr *Trader) persistTick(t tick.Tick) {
if err := tr.gormDB.Create(&t).Error; err != nil {
log.WithError(err).Errorf("Cannot persist tick: %+v", t)
}
}
func (tr *Trader) receiveTicks() {
var locBerlin, err = time.LoadLocation("Europe/Berlin")
if err != nil {
log.WithError(err).Fatal("Unable to load Europe/Berlin timezone")
}
for currentTick := range tr.TickChan {
if tr.persistTickData {
go tr.persistTick(currentTick)
}
currentTick.Datetime = currentTick.Datetime.In(locBerlin)
if err := currentTick.Validate(); err != nil {
tr.clog.WithError(err).Debugf("Invalid tick data received: %+v", currentTick)
continue
}
//tr.clog.Debugf("New tick received %s", currentTick.String())
tr.Lock()
tr.processTodayCandle(currentTick)
tr.processTick(currentTick)
tr.Unlock()
}
}
func (tr *Trader) processTick(currentTick tick.Tick) {
var closedCandles = tr.processTickByOpenCandles(currentTick)
tr.strategy.OnTick(currentTick)
for _, closedCandle := range closedCandles {
tr.processClosedCandle(closedCandle, currentTick)
}
}
func (tr *Trader) processClosedCandle(closedCandle *ohlc.OHLC, currentTick tick.Tick) {
tr.clog.Debugf("Processing closed candle: %s", closedCandle)
if !closedCandle.HasPriceData() {
tr.clog.Debugf("processClosedCandle: candle has missing price data, cannot process further: %s", closedCandle)
return
}
if tr.strategy.GetCandleDuration() != closedCandle.Duration {
return
}
// Orders
openOrders, err := tr.broker.GetOpenOrders()
if err != nil {
tr.clog.WithError(err).Error("Cannot get open orders")
return
}
tr.strategy.OnOrder(openOrders)
// Positions
openPositions, err := tr.getOpenPositions()
if err != nil {
tr.clog.WithError(err).Error("Cannot get open positions")
return
}
closedPositions, err := tr.GetClosedPositions()
if err != nil {
tr.clog.WithError(err).Error("Cannot get closed positions")
return
}
tr.detectClosedPositions(closedPositions)
tr.processOpenPositions(closedCandle, openPositions)
tr.strategy.OnPosition(openPositions, closedPositions)
// Candle
toOpen, toClose, toClosePositions := tr.strategy.OnCandle(tr.closedCandles)
tr.processClosableOrders(toClose)
tr.processClosablePositions(toClosePositions)
tr.processOrders(closedCandle, currentTick, toOpen)
for _, subscriber := range tr.candleSubscribers {
subscriber.OnCandle(*closedCandle)
}
}
func (tr *Trader) processClosableOrders(orders []broker.Order) {
for _, order := range orders {
if err := tr.broker.CancelOrder(order.ID); err != nil {
tr.clog.WithError(err).WithFields(log.Fields{"OrderID": order.ID}).Error("Unable to cancel order")
}
}
}
func (tr *Trader) processOpenPositions(candle *ohlc.OHLC, openPositions []broker.Position) {
for _, openPosition := range openPositions {
_, exists := tr.positionBuyTime[openPosition.Reference]
if !exists {
tr.positionBuyTime[openPosition.Reference] = candle.Start
}
}
}
func (tr *Trader) processClosablePositions(toClose []broker.Position) {
for _, position := range toClose {
if err := tr.broker.Sell(position); err != nil {
tr.clog.WithError(err).WithFields(log.Fields{"Reference": position.Reference}).Error("Unable to sell position")
}
}
}
// processOrders - Execute order and open new positions
func (tr *Trader) processOrders(candle *ohlc.OHLC, currentTick tick.Tick, toOpen []broker.Order) {
for _, order := range toOpen {
order.CurrencyCode = tr.currencyCode
_, err := tr.broker.Buy(order)
if err != nil {
tr.clog.WithError(err).Errorf("Unable to open position: %+v", order)
continue
}
tr.clog.Infof("Got new order: %s", order.String())
for _, subscriber := range tr.orderSubscribers {
subscriber.OnOrder(order)
}
}
}
func (tr *Trader) processTickByOpenCandles(currentTick tick.Tick) (closedCandles []*ohlc.OHLC) {
var stillOpenCandles []*ohlc.OHLC
defer func() {
lastReceivedTick := currentTick
tr.lastReceivedTick = &lastReceivedTick
tr.openCandles = stillOpenCandles
}()
if len(tr.openCandles) == 0 {
candle := ohlc.New(tr.Instrument, currentTick.Datetime, tr.strategy.GetCandleDuration(), true)
tr.openCandles = append(tr.openCandles, candle)
if tr.persistCandleData && tr.strategy.GetCandleDuration() != time.Hour*24 {
candle := ohlc.New(tr.Instrument, currentTick.Datetime, time.Hour*24, true)
tr.openCandles = append(tr.openCandles, candle)
}
}
for _, candle := range tr.openCandles {
switch candle.Duration {
case time.Hour * 24:
if tr.lastReceivedTick != nil && tr.lastReceivedTick.Datetime.Day() != currentTick.Datetime.Day() {
candle.ForceClose()
}
case time.Hour:
if tr.lastReceivedTick != nil && tr.lastReceivedTick.Datetime.Hour() != currentTick.Datetime.Hour() {
candle.ForceClose()
}
}
isOpen := candle.NewPrice(currentTick.Price(), currentTick.Datetime)
if isOpen {
stillOpenCandles = append(stillOpenCandles, candle)
continue
}
newCandle := tr.closeCandle(currentTick, candle)
stillOpenCandles = append(stillOpenCandles, newCandle)
closedCandles = append(closedCandles, candle)
}
return
}
func (tr *Trader) closeCandle(tick tick.Tick, candle *ohlc.OHLC) (newCandle *ohlc.OHLC) {
tr.closedCandles = append(tr.closedCandles, candle)
var candlesToKeep = 100
if len(tr.closedCandles) > candlesToKeep {
tr.closedCandles = tr.closedCandles[len(tr.closedCandles)-candlesToKeep:]
}
if tr.gormDB != nil && tr.persistCandleData {
go func() {
if err := candle.Store(tr.gormDB); err != nil {
tr.clog.WithError(err).Errorf("Failed to store OHLC: %+v", candle)
}
}()
}
// Replace closed OHLC from openOHLCs list
openCandle := ohlc.New(candle.Instrument, tick.Datetime, candle.Duration, true)
openCandle.NewPrice(tick.Price(), tick.Datetime)
return openCandle
}
func (tr *Trader) detectClosedPositions(brokerClosedPositions []broker.Position) {
for _, closedByBroker := range brokerClosedPositions {
_, exists := tr.closedPositionReferences[closedByBroker.Reference]
if !exists {
tr.closePosition(closedByBroker)
tr.closedPositionReferences[closedByBroker.Reference] = true
}
}
}
func (tr *Trader) closePosition(position broker.Position) {
for _, subscriber := range tr.positionSubscribers {
subscriber.OnPosition(position)
}
}
|
lan-mao/ComputerWorld
|
Study_Old/TacoCloud/src/main/java/top/lan_mao/tacocloud/jdbc/IngredientRepository.java
|
<reponame>lan-mao/ComputerWorld<filename>Study_Old/TacoCloud/src/main/java/top/lan_mao/tacocloud/jdbc/IngredientRepository.java<gh_stars>1-10
package top.lan_mao.tacocloud.jdbc;
import top.lan_mao.tacocloud.data.Ingredient;
/**
* Create Date 2021/04/20 18:33:04 <br>
*
* @author lan-mao.top <br>
* @version 1.0
* <br>
*/
public interface IngredientRepository {
Iterable<Ingredient> findAll();
Ingredient findOne(String id);
int saveOne(Ingredient ingredient);
}
|
MikeAmy/django
|
tests/update_only_fields/models.py
|
<filename>tests/update_only_fields/models.py
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Account(models.Model):
num = models.IntegerField()
@python_2_unicode_compatible
class Person(models.Model):
name = models.CharField(max_length=20)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
pid = models.IntegerField(null=True, default=None)
def __str__(self):
return self.name
class Employee(Person):
employee_num = models.IntegerField(default=0)
profile = models.ForeignKey('Profile', models.SET_NULL, related_name='profiles', null=True)
accounts = models.ManyToManyField('Account', related_name='employees', blank=True)
@python_2_unicode_compatible
class Profile(models.Model):
name = models.CharField(max_length=200)
salary = models.FloatField(default=1000.0)
def __str__(self):
return self.name
class ProxyEmployee(Employee):
class Meta:
proxy = True
|
poanchen/azure-sdk-for-ruby
|
data/azure_cognitiveservices_textanalytics/lib/v2.1/generated/azure_cognitiveservices_textanalytics/models/entity_record.rb
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::CognitiveServices::TextAnalytics::V2_1
module Models
#
# Model object.
#
#
class EntityRecord
include MsRestAzure
# @return [String] Entity formal name.
attr_accessor :name
# @return [Array<MatchRecord>] List of instances this entity appears in
# the text.
attr_accessor :matches
# @return [String] Wikipedia language for which the WikipediaId and
# WikipediaUrl refers to.
attr_accessor :wikipedia_language
# @return [String] Wikipedia unique identifier of the recognized entity.
attr_accessor :wikipedia_id
# @return [String] URL for the entity's Wikipedia page.
attr_accessor :wikipedia_url
# @return [String] Bing unique identifier of the recognized entity. Use
# in conjunction with the Bing Entity Search API to fetch additional
# relevant information.
attr_accessor :bing_id
# @return [String] Entity type from Named Entity Recognition model
attr_accessor :type
# @return [String] Entity sub type from Named Entity Recognition model
attr_accessor :sub_type
#
# Mapper for EntityRecord class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'EntityRecord',
type: {
name: 'Composite',
class_name: 'EntityRecord',
model_properties: {
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
matches: {
client_side_validation: true,
required: false,
serialized_name: 'matches',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'MatchRecordElementType',
type: {
name: 'Composite',
class_name: 'MatchRecord'
}
}
}
},
wikipedia_language: {
client_side_validation: true,
required: false,
serialized_name: 'wikipediaLanguage',
type: {
name: 'String'
}
},
wikipedia_id: {
client_side_validation: true,
required: false,
serialized_name: 'wikipediaId',
type: {
name: 'String'
}
},
wikipedia_url: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'wikipediaUrl',
type: {
name: 'String'
}
},
bing_id: {
client_side_validation: true,
required: false,
serialized_name: 'bingId',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
serialized_name: 'type',
type: {
name: 'String'
}
},
sub_type: {
client_side_validation: true,
required: false,
serialized_name: 'subType',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
myoo/sabatora
|
spec/routing/communities/joinings_routing_spec.rb
|
<gh_stars>1-10
require "rails_helper"
RSpec.describe Communities::JoiningsController, :type => :routing do
describe "routing" do
end
end
|
ECLAIRWaveS/ForestClaw
|
src/solvers/fc2d_cudaclaw/fc2d_cudaclaw_fort.h
|
/*
Copyright (c) 2012 <NAME>, <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:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FC2D_CUDACLAW_FORT_H
#define FC2D_CUDACLAW_FORT_H
#include <fclaw_base.h>
#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif
/* --------------------------------- Clawpack functions ------------------------------- */
#define CUDACLAW_BC2_DEFAULT FCLAW_F77_FUNC(cudaclaw_bc2_default,CUDACLAW_BC2_DEFAULT)
void CUDACLAW_BC2_DEFAULT(const int* maxmx, const int* maxmy, const int* meqn,
const int* mbc, const int* mx, const int* my,
const double* xlower, const double* ylower,
const double* dx, const double* dy, const double q[],
const int* maux, const double aux[], const double* t,
const double* dt, const int mthbc[]);
#define CUDACLAW_FLUX2 FCLAW_F77_FUNC(cudaclaw_flux2,CUDACLAW_FLUX2)
void CUDACLAW_FLUX2(const int* ixy,const int* maxm, const int* meqn,
const int* maux,const int* mbc,const int* mx,
double q1d[], double dtdx1d[],
double aux1[], double aux2[], double aux3[],
double faddm[],double faddp[], double gaddm[],
double gaddp[],double cfl1d[], double fwave[],
double s[], double amdq[],double apdq[],double cqxx[],
double bmasdq[], double bpasdq[],
cudaclaw_fort_rpn2_t rpn2, cudaclaw_fort_rpt2_t rpt2,
const int* mwaves, const int* mcapa,
int method[], int mthlim[]);
#define CUDACLAW_FLUX2FW FCLAW_F77_FUNC(cudaclaw_flux2fw,CUDACLAW_FLUX2FW)
void CUDACLAW_FLUX2FW(const int* ixy,const int* maxm, const int* meqn, //
const int* maux,const int* mbc,const int* mx,
double q1d[], double dtdx1d[],
double aux1[], double aux2[], double aux3[],
double faddm[],double faddp[], double gaddm[],
double gaddp[],double cfl1d[], double fwave[],
double s[], double amdq[],double apdq[],double cqxx[],
double bmasdq[], double bpasdq[],
cudaclaw_fort_rpn2_t rpn2,cudaclaw_fort_rpt2_t rpt2,
const int* mwaves, const int* mcapa,
int method[], int mthlim[]);
#define CUDACLAW_SET_CAPACITY FCLAW_F77_FUNC(cudaclaw_set_capacity,CUDACLAW_SET_CAPACITY)
void CUDACLAW_SET_CAPACITY(const int* mx, const int *my, const int *mbc,
const double *dx, const double* dy, double area[],
const int *mcapa, const int* maux, double aux[]);
#define CUDACLAW_FLUX_ADD FCLAW_F77_FUNC(cudaclaw_flux_add, CUDACLAW_FLUX_ADD)
void CUDACLAW_FLUX_ADD(const int* mx, const int* my, const int *mbc,
const int* meqn, const double* dx, const double *dy,
const double *dt, double qnew[],
double flux[], const int *iface,
double buffer[]);
/* ------------------------------- Time stepping functions ---------------------------- */
#define CUDACLAW_STEP2_WRAP FCLAW_F77_FUNC(cudaclaw_step2_wrap,CUDACLAW_STEP2_WRAP)
void CUDACLAW_STEP2_WRAP(const int* maxm, const int* meqn, const int* maux,
const int* mbc, const int method[], const int mthlim[],
const int* mcapa, const int* mwaves, const int* mx,
const int* my, double qold[], double auxold[],
const double* dx, const double* dy, const double* dt,
const double* cfl, double work[], const int* mwork,
const double* xlower, const double* ylower, const int* level,
const double* t, double fp[], double fm[], double gp[],
double gm[],
cudaclaw_fort_rpn2_t rpn2,
cudaclaw_fort_rpt2_t rpt2,
cudaclaw_fort_flux2_t flux2,
int block_corner_count[],int* ierror);
/* ----------------------------- Misc ClawPack specific functions ------------------------------ */
#define CUDACLAW_SET_BLOCK FCLAW_F77_FUNC(cudaclaw_set_block,CUDACLAW_SET_BLOCK)
void CUDACLAW_SET_BLOCK(int* blockno);
#define FC2D_CUDACLAW_GET_BLOCK FCLAW_F77_FUNC(fc2d_cudaclaw_get_block, \
FC2D_CUDACLAW_GET_BLOCK)
int FC2D_CUDACLAW_GET_BLOCK();
#define CUDACLAW_UNSET_BLOCK FCLAW_F77_FUNC(cudaclaw_unset_block, \
CUDACLAW_UNSET_BLOCK)
void CUDACLAW_UNSET_BLOCK();
#ifdef __cplusplus
#if 0
{
#endif
}
#endif
#endif
|
jeanleflambeur/silkopter
|
silkopter/libs/common/node/IGenerator.h
|
#pragma once
#include "common/node/INode.h"
namespace silk
{
namespace node
{
class IGenerator : public Node_Base<Type::GENERATOR>
{
public:
};
}
}
|
f4k-73/adventofcode21
|
scala/eeedean/src/main/scala/de/edean/aoc2021/day6/Day6.scala
|
<filename>scala/eeedean/src/main/scala/de/edean/aoc2021/day6/Day6.scala<gh_stars>1-10
package de.edean.aoc2021.day6
import scala.io.Source
import scala.language.postfixOps
import scala.collection.parallel.CollectionConverters._
object Day6 extends App {
val INPUT_PATH = if (System.getProperty("os.name").startsWith("Mac") &&
System.getenv("USER").toLowerCase.equals("edean"))
"src/main/resources/input6.txt"
else "../../data/day6.txt"
val input = Source.fromFile(INPUT_PATH, "UTF-8").getLines().toSeq
val initialFishes = input.head.split(",").map(_.toInt)
val daysToMaturity = 8
val daysToReproduce = 6
val daysToSimulate = 256
def fishSimulation(fishes: Seq[Int], remainingDays: Int): Seq[Int] = {
if (remainingDays == 0) fishes
else {
fishSimulation(fishes.par.flatMap(
fish =>
if (fish == 0)
Seq(daysToReproduce, daysToMaturity)
else
Seq(fish - 1)).toIndexedSeq, remainingDays - 1)
}
}
def fasterFishSimulation(fishes: Seq[Int], remainingDays: Int): Seq[Int] = {
if (remainingDays == 0) fishes
else if (remainingDays % daysToReproduce != 0) {
val daysToCorrect = remainingDays % daysToReproduce
val correctedInitialFishes = fishSimulation(fishes, daysToCorrect)
fasterFishSimulation(correctedInitialFishes, remainingDays - daysToCorrect)
} else {
fasterFishSimulation(fishes.par.flatMap(
fish =>
if (fish < daysToReproduce)
Seq(fish + 1, daysToMaturity-daysToReproduce + fish + 1)
else
Seq(fish - daysToReproduce)).toIndexedSeq, remainingDays - daysToReproduce)
}
}
def ultimateFishSimulation(fishesPerSize: Map[Int, Long], remainingDays: Int): Map[Int, Long] = {
if (remainingDays == 0) fishesPerSize
else {
ultimateFishSimulation(fishesPerSize.toSeq.flatMap({
case (daysUntilReproduction, amount) =>
if (daysUntilReproduction == 0)
Seq(daysToReproduce -> (amount), daysToMaturity -> amount)
else
Seq(daysUntilReproduction - 1 -> amount)
}).groupMapReduce(_._1)(_._2)((left, right) => left + right), remainingDays - 1)
}
}
//println(fishSimulation(initialFishes, daysToSimulate))
//println(fasterFishSimulation(initialFishes, daysToSimulate).size)
println(ultimateFishSimulation((0 to 8).map(i => (i, initialFishes.filter(_ == i).size.toLong)).toMap, daysToSimulate).map(_._2).sum)
/*(0 to 200).foreach(i => {
val oldAmount = fasterFishSimulation(initialFishes, i).size
val newAmount = newFishSimulation((0 to 8).map(i => (i, initialFishes.filter(_ == i).size)).toMap, i).map(_._2).sum
if (oldAmount == newAmount) println(s"$i: $oldAmount") else System.err.println(s"$i: $oldAmount vs $newAmount")
})*/
}
|
flipkart-incubator/spark-transformers
|
adapters-1.6/src/main/java/com/flipkart/fdp/ml/utils/Constants.java
|
package com.flipkart.fdp.ml.utils;
import java.io.Serializable;
public class Constants implements Serializable {
public static final String SUPPORTED_SPARK_VERSION_PREFIX = "1.6";
public static final String LIBRARY_VERSION = "1.0";
}
|
project-zerus/cpp-netlib
|
message/src/network/message/message.ipp
|
// Copyright 2011 <NAME> (<EMAIL>).
// Copyright 2011 Google, Inc.
// 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)
#ifndef NETWORK_MESSAGE_IPP_20111020
#define NETWORK_MESSAGE_IPP_20111020
#include <iterator>
#include <utility>
#include <algorithm>
#include <network/message/message.hpp>
namespace network {
struct message_pimpl {
message_pimpl()
: destination_(),
source_(),
headers_(),
body_(),
body_read_pos(0) {}
void set_destination(std::string const& destination) {
destination_ = destination;
}
void set_source(std::string const& source) { source_ = source; }
void append_header(std::string const& name, std::string const& value) {
headers_.insert(std::make_pair(name, value));
}
void remove_headers(std::string const& name) { headers_.erase(name); }
void remove_headers() {
std::multimap<std::string, std::string>().swap(headers_);
}
void set_body(std::string const& body) { body_ = body; }
void append_body(std::string const& data) { body_.append(data); }
// Retrievers
void get_destination(std::string& destination) const {
destination = destination_;
}
void get_source(std::string& source) const { source = source_; }
void get_headers(std::function<
void(std::string const&, std::string const&)> inserter) const {
std::multimap<std::string, std::string>::const_iterator it =
headers_.begin(), end = headers_.end();
for (; it != end; ++it)
inserter(it->first, it->second);
}
void get_headers(std::string const& name,
std::function<void(std::string const&,
std::string const&)> inserter) const {
std::multimap<std::string, std::string>::const_iterator it =
headers_.find(name), end = headers_.end();
while (it != end) {
inserter(it->first, it->second);
++it;
}
}
void get_headers(
std::function<bool(std::string const&, std::string const&)> predicate,
std::function<
void(std::string const&, std::string const&)> inserter) const {
std::multimap<std::string, std::string>::const_iterator it =
headers_.begin(), end = headers_.end();
while (it != end) {
if (predicate(it->first, it->second))
inserter(it->first, it->second);
++it;
}
}
void get_body(std::string& body) { body = body_; }
void get_body(
std::function<void(std::string::const_iterator, size_t)> chunk_reader,
size_t size) const {
if (body_read_pos == body_.size())
chunk_reader(body_.end(), 0);
std::string::const_iterator it = body_.begin(), end = body_.end();
std::advance(it, body_read_pos);
size_t max_size = std::distance(it, end);
size_t max_read = std::min(max_size, size);
std::string::const_iterator start = it;
end = start;
std::advance(end, max_read);
body_read_pos += max_read;
chunk_reader(start, max_read);
}
message_pimpl* clone() {
message_pimpl* other = new (std::nothrow) message_pimpl;
other->destination_ = this->destination_;
other->source_ = this->source_;
other->headers_ = this->headers_;
other->body_ = this->body_;
return other;
}
private:
std::string destination_, source_;
std::multimap<std::string, std::string> headers_;
// TODO: use Boost.IOStreams here later on.
std::string body_;
mutable size_t body_read_pos;
};
message::message() : pimpl(new (std::nothrow) message_pimpl) {}
message::message(message const& other) : pimpl(other.pimpl->clone()) {}
message& message::operator=(message const & other) {
*pimpl = *other.pimpl;
return *this;
}
message& message::operator=(message && other) {
*pimpl = *std::move(other.pimpl);
return *this;
}
message::~message() { delete pimpl; }
void message::set_destination(std::string const& destination) {
pimpl->set_destination(destination);
}
void message::set_source(std::string const& source) {
pimpl->set_source(source);
}
void message::append_header(std::string const& name, std::string const& value) {
pimpl->append_header(name, value);
}
void message::remove_headers(std::string const& name) {
pimpl->remove_headers(name);
}
void message::remove_headers() { pimpl->remove_headers(); }
void message::set_body(std::string const& body) { pimpl->set_body(body); }
void message::append_body(std::string const& data) { pimpl->append_body(data); }
void message::get_destination(std::string& destination) const {
pimpl->get_destination(destination);
}
void message::get_source(std::string& source) const {
pimpl->get_source(source);
}
void message::get_headers(std::function<
void(std::string const&, std::string const&)> inserter) const {
pimpl->get_headers(inserter);
}
void message::get_headers(
std::string const& name,
std::function<
void(std::string const&, std::string const&)> inserter) const {
pimpl->get_headers(name, inserter);
}
void message::get_headers(
std::function<bool(std::string const&, std::string const&)> predicate,
std::function<
void(std::string const&, std::string const&)> inserter) const {
pimpl->get_headers(predicate, inserter);
}
void message::get_body(std::string& body) const { pimpl->get_body(body); }
void message::get_body(
std::function<void(std::string::const_iterator, size_t)> chunk_reader,
size_t size) const {
pimpl->get_body(chunk_reader, size);
}
void message::swap(message& other) { std::swap(this->pimpl, other.pimpl); }
} /* network */
#endif /* NETWORK_MESSAGE_IPP_20111020 */
|
shgysk8zer0/std-js
|
polyfills/classes/CSS.js
|
export default class {
static supports(prop, value) {
var el = document.createElement('div');
el.style = prop + ':' + value;
return (getComputedStyle(el)[prop] === value);
}
static escape(value) {
var string = String(value), length = string.length, index = -1, codeUnit, result = '', firstCodeUnit = string.charCodeAt(0);
while (++index < length) {
codeUnit = string.charCodeAt(index);
if (codeUnit == 0x0000) {
throw new Error('Invalid character: the input contains U+0000.');
}
if (
(codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F ||
(index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
(
index == 1 &&
codeUnit >= 0x0030 && codeUnit <= 0x0039 &&
firstCodeUnit == 0x002D
)
) {
result += '\\' + codeUnit.toString(16) + ' ';
continue;
}
if (
codeUnit >= 0x0080 ||
codeUnit == 0x002D ||
codeUnit == 0x005F ||
codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
codeUnit >= 0x0041 && codeUnit <= 0x005A ||
codeUnit >= 0x0061 && codeUnit <= 0x007A
) {
result += string.charAt(index);
continue;
}
result += '\\' + string.charAt(index);
}
return result;
}
}
|
EasySolutionsIO/DevExtreme
|
testing/tests/DevExpress.ui.widgets/loadPanel.tests.js
|
var $ = require("jquery"),
hideTopOverlayCallback = require("mobile/hide_top_overlay").hideCallback,
keyboardMock = require("../../helpers/keyboardMock.js"),
fx = require("animation/fx");
require("common.css!");
require("ui/load_panel");
QUnit.testStart(function() {
var markup =
'<div id="qunit-fixture" class="dx-viewport">\
<div id="target" style="position: absolute; top: 0; left: 0; width: 100px; height: 100px;">\
<div id="container">\
<div id="loadPanel" style="width: 100px; height: 100px;"></div>\
<div id="loadPanel2"></div>\
</div>\
</div>\
</div>';
$("#qunit-fixture").replaceWith(markup);
});
var LOADPANEL_CLASS = "dx-loadpanel",
LOADPANEL_MESSAGE_CLASS = "dx-loadpanel-message",
MESSAGE_SELECTOR = "." + LOADPANEL_MESSAGE_CLASS,
LOADPANEL_CONTENT_CLASS = "dx-loadpanel-content",
LOADPANEL_PANE_HIDDEN_CLASS = "dx-loadpanel-pane-hidden";
QUnit.module("init", {
beforeEach: function() {
fx.off = true;
},
afterEach: function() {
fx.off = false;
}
});
QUnit.test("rendered markup", function(assert) {
var $element = $("#loadPanel").dxLoadPanel({ message: "Test Loading Message", visible: true }),
$content = $element.dxLoadPanel("instance").$content();
assert.ok($element.hasClass(LOADPANEL_CLASS));
assert.ok($content.hasClass(LOADPANEL_CONTENT_CLASS), "Load Indicator created");
assert.ok($content.find(MESSAGE_SELECTOR).length);
assert.equal($content.find(MESSAGE_SELECTOR).text(), "Test Loading Message");
});
QUnit.test("load panel created with templatesRenderAsynchronously option should be shown without delay", function(assert) {
var clock = sinon.useFakeTimers();
try {
var onShowingSpy = sinon.spy();
$("#loadPanel").dxLoadPanel({
templatesRenderAsynchronously: true,
visible: true,
onShowing: onShowingSpy
});
assert.equal(onShowingSpy.called, 1);
clock.tick();
assert.equal(onShowingSpy.called, 1);
} finally {
clock.restore();
}
});
QUnit.test("shows on init if loading option is true", function(assert) {
$("#loadPanel").dxLoadPanel({ message: "Test Loading Message", visible: true });
assert.ok($("#loadPanel").is(":visible"));
});
QUnit.test("visible changes visibility", function(assert) {
var $loadPanel = $("#loadPanel").dxLoadPanel({
message: "",
visible: false
}),
loadPanel = $loadPanel.dxLoadPanel("instance"),
$content = loadPanel.$content();
assert.ok(!$content.is(":visible"));
loadPanel.option("visible", false);
assert.ok(!$content.is(":visible"));
loadPanel.option("visible", true);
assert.ok($content.is(":visible"));
loadPanel.option("visible", false);
assert.ok($content.is(":hidden"));
});
QUnit.test("visible changes visibility option", function(assert) {
var element = $("#loadPanel2").dxLoadPanel({
visible: false,
message: "Text"
}),
$content = element.dxLoadPanel("instance").$content();
var loadIndicator = element.dxLoadPanel("instance");
assert.ok(!$content.is(":visible"));
loadIndicator.option("visible", false);
assert.ok(!$content.is(":visible"));
loadIndicator.option("visible", true);
assert.ok($content.is(":visible"));
loadIndicator.option("visible", false);
assert.ok($content.is(":hidden"));
});
QUnit.test("keep user defined position.of", function(assert) {
var instance = $("#loadPanel").dxLoadPanel({
targetContainer: "#container",
position: { of: "body" }
}).dxLoadPanel("instance");
assert.equal(instance.option("position.of"), "body");
});
QUnit.test("widget should be rendered with non-existing target in position", function(assert) {
assert.expect(0);
$("#loadPanel").dxLoadPanel({
visible: true,
position: { of: "#non-exist" }
}).dxLoadPanel("instance");
});
QUnit.module("options changed callbacks", {
beforeEach: function() {
this.element = $("#loadPanel").dxLoadPanel();
this.instance = this.element.dxLoadPanel("instance");
}
});
QUnit.test("message", function(assert) {
this.instance.option("message", "new message");
this.instance.show();
assert.equal(this.instance.$content().text(), "new message");
});
QUnit.test("width/height", function(assert) {
this.instance.option("visible", true);
this.instance.option("width", 123);
assert.equal(this.instance.$content().outerWidth(), 123);
this.instance.option("height", 321);
assert.equal(this.instance.$content().outerHeight(), 321);
});
QUnit.test("showIndicator option", function(assert) {
var instance = this.element
.dxLoadPanel({ showIndicator: false })
.dxLoadPanel("instance");
var indicator = instance.$content().find(".dx-loadindicator");
instance.show();
assert.equal(indicator.length, 0, "indicator is hidden");
instance.option("showIndicator", true);
indicator = instance.$content().find(".dx-loadindicator");
assert.equal(indicator.length, 1, "indicator is shown");
instance.option("showIndicator", false);
indicator = instance.$content().find(".dx-loadindicator");
assert.equal(indicator.length, 0, "indicator is hidden");
});
QUnit.test("showPane option", function(assert) {
var instance = this.element
.dxLoadPanel({ showPane: true })
.dxLoadPanel("instance");
assert.ok(!instance.$content().hasClass(LOADPANEL_PANE_HIDDEN_CLASS));
instance.option("showPane", false);
assert.ok(instance.$content().hasClass(LOADPANEL_PANE_HIDDEN_CLASS));
instance.option("showPane", true);
assert.ok(!instance.$content().hasClass(LOADPANEL_PANE_HIDDEN_CLASS));
});
QUnit.test("LoadPanel with custom indicator", function(assert) {
var url = "../../testing/content/customLoadIndicator.png",
instance = this.element
.dxLoadPanel({
showIndicator: true,
indicatorSrc: url
})
.dxLoadPanel("instance");
instance.show();
var loadIndicatorInstance = this.instance.$content().find(".dx-loadindicator").dxLoadIndicator().dxLoadIndicator("instance");
assert.equal(loadIndicatorInstance.option("indicatorSrc"), url, "custom indicator option installed successfully");
instance.option("indicatorSrc", "");
assert.equal(instance.option("indicatorSrc"), loadIndicatorInstance.option("indicatorSrc"), "custom indicator option changed successfully");
});
QUnit.test("Load panel should not close on esc button when focusStateEnabled is true", function(assert) {
var instance = this.element
.dxLoadPanel({
focusStateEnabled: true,
width: 1,
height: 1,
visible: true
}).dxLoadPanel("instance"),
keyboard = keyboardMock(instance.$content());
keyboard.keyDown("esc");
assert.ok(instance.option("visible"), "load panel stay visible after esc press");
});
QUnit.testInActiveWindow("Load panel with shading should grab focus from inputs under the shading when focusStateEnabled is true", function(assert) {
var $input = $("<input/>").val("");
try {
var instance = this.element
.dxLoadPanel({
focusStateEnabled: true,
shading: true,
delay: 0,
width: 1,
height: 1
}).dxLoadPanel("instance");
$input.appendTo("body");
$input.focus().focusin();
instance.show();
assert.equal(document.activeElement, instance.$content().get(0), "load panel is focused");
} finally {
$input.remove();
}
});
QUnit.module("regressions");
QUnit.test("it's possible to close loadPanel with hardware back button (B251568)", function(assert) {
var instance = $("#loadPanel").dxLoadPanel({ }).dxLoadPanel("instance");
instance.show();
hideTopOverlayCallback.fire();
assert.equal(instance.option("visible"), true, "callback changed to noop");
});
QUnit.module("delay", {
beforeEach: function() {
this.clock = sinon.useFakeTimers();
},
afterEach: function() {
this.clock.restore();
}
});
QUnit.test("option 'delay' delays showing", function(assert) {
var delayTimeout = 500;
var $loadPanel = $("#loadPanel").dxLoadPanel({
delay: delayTimeout
});
$loadPanel.dxLoadPanel("show");
var $content = $loadPanel.dxLoadPanel("$content");
assert.equal($content.is(":visible"), false, "load panel showing delayed");
this.clock.tick(delayTimeout);
assert.equal($content.is(":visible"), true, "load panel shown after delay");
});
QUnit.test("onShowing and onShown action delayed", function(assert) {
var showingFired = 0;
var shownFired = 0;
var delayTimeout = 500;
var $loadPanel = $("#loadPanel").dxLoadPanel({
delay: delayTimeout,
animation: null,
onShowing: function() {
showingFired++;
},
onShown: function() {
shownFired++;
}
});
$loadPanel.dxLoadPanel("show");
assert.equal(showingFired, 0, "showing action was not fired");
assert.equal(shownFired, 0, "shown action was not fired");
this.clock.tick(delayTimeout);
assert.equal(showingFired, 1, "showing action was fired after delay timeout");
assert.equal(shownFired, 1, "shown action was fired after delay timeout");
});
QUnit.test("hiding rejects delayed showing", function(assert) {
var delayTimeout = 500;
var $loadPanel = $("#loadPanel").dxLoadPanel({
delay: delayTimeout
}),
$content = $loadPanel.dxLoadPanel("$content");
$loadPanel.dxLoadPanel("show");
$loadPanel.dxLoadPanel("hide");
this.clock.tick(delayTimeout);
assert.equal($content.is(":visible"), false, "load panel was not shown after hide");
});
|
vincenttran-msft/azure-sdk-for-python
|
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py
|
<gh_stars>1-10
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._models_py3 import AlertRuleResource
from ._models_py3 import AlertRuleResourceCollection
from ._models_py3 import AlertRuleResourcePatch
from ._models_py3 import AutoscaleNotification
from ._models_py3 import AutoscaleProfile
from ._models_py3 import AutoscaleSettingResource
from ._models_py3 import AutoscaleSettingResourceCollection
from ._models_py3 import AutoscaleSettingResourcePatch
from ._models_py3 import EmailNotification
from ._models_py3 import ErrorResponse
from ._models_py3 import EventCategoryCollection
from ._models_py3 import EventData
from ._models_py3 import EventDataCollection
from ._models_py3 import HttpRequestInfo
from ._models_py3 import LocalizableString
from ._models_py3 import LocationThresholdRuleCondition
from ._models_py3 import ManagementEventAggregationCondition
from ._models_py3 import ManagementEventRuleCondition
from ._models_py3 import MetricTrigger
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import OperationListResult
from ._models_py3 import Recurrence
from ._models_py3 import RecurrentSchedule
from ._models_py3 import Resource
from ._models_py3 import RuleAction
from ._models_py3 import RuleCondition
from ._models_py3 import RuleDataSource
from ._models_py3 import RuleEmailAction
from ._models_py3 import RuleManagementEventClaimsDataSource
from ._models_py3 import RuleManagementEventDataSource
from ._models_py3 import RuleMetricDataSource
from ._models_py3 import RuleWebhookAction
from ._models_py3 import ScaleAction
from ._models_py3 import ScaleCapacity
from ._models_py3 import ScaleRule
from ._models_py3 import ScaleRuleMetricDimension
from ._models_py3 import SenderAuthorization
from ._models_py3 import ThresholdRuleCondition
from ._models_py3 import TimeWindow
from ._models_py3 import WebhookNotification
from ._monitor_management_client_enums import (
ComparisonOperationType,
ConditionOperator,
EventLevel,
MetricStatisticType,
RecurrenceFrequency,
ScaleDirection,
ScaleRuleMetricDimensionOperationType,
ScaleType,
TimeAggregationOperator,
TimeAggregationType,
)
__all__ = [
'AlertRuleResource',
'AlertRuleResourceCollection',
'AlertRuleResourcePatch',
'AutoscaleNotification',
'AutoscaleProfile',
'AutoscaleSettingResource',
'AutoscaleSettingResourceCollection',
'AutoscaleSettingResourcePatch',
'EmailNotification',
'ErrorResponse',
'EventCategoryCollection',
'EventData',
'EventDataCollection',
'HttpRequestInfo',
'LocalizableString',
'LocationThresholdRuleCondition',
'ManagementEventAggregationCondition',
'ManagementEventRuleCondition',
'MetricTrigger',
'Operation',
'OperationDisplay',
'OperationListResult',
'Recurrence',
'RecurrentSchedule',
'Resource',
'RuleAction',
'RuleCondition',
'RuleDataSource',
'RuleEmailAction',
'RuleManagementEventClaimsDataSource',
'RuleManagementEventDataSource',
'RuleMetricDataSource',
'RuleWebhookAction',
'ScaleAction',
'ScaleCapacity',
'ScaleRule',
'ScaleRuleMetricDimension',
'SenderAuthorization',
'ThresholdRuleCondition',
'TimeWindow',
'WebhookNotification',
'ComparisonOperationType',
'ConditionOperator',
'EventLevel',
'MetricStatisticType',
'RecurrenceFrequency',
'ScaleDirection',
'ScaleRuleMetricDimensionOperationType',
'ScaleType',
'TimeAggregationOperator',
'TimeAggregationType',
]
|
nermeen100/domino-mvp
|
domino-apt/apt-client/src/test/resources/org/dominokit/domino/apt/client/SomeResponse.java
|
package org.dominokit.domino.apt.client;
import org.dominokit.domino.api.shared.request.ResponseBean;
public class SomeResponse implements ResponseBean {
}
|
aj148/slogo
|
src/view/panes/InputPaneModule.java
|
<gh_stars>0
package view.panes;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import view.CommandString;
import view.Constants;
/**
* Subclass of Pane that implements a scrollable textfield that allows for user
* input. Hitting enter or hitting the submit button pushes the command inputed
* by the user.
*
* @author Team14
*
*/
public class InputPaneModule extends PaneModule {
private HBox myHBox = new HBox();
private ScrollPane myScrollPane = new ScrollPane();
private TextField myTextField = new TextField();
private CommandString myCommandString;
/**
* Initializes the parameters of the InputPane.
*
* @param cs
* CommandString containing the String that represents the
* current command
*/
public InputPaneModule (CommandString cs) {
myCommandString = cs;
myScrollPane.setContent(myTextField);
myTextField.setPrefColumnCount(70);
myTextField.setOnKeyPressed(new SubmitHandler());
Button submit = new Button("Submit");
submit.setOnAction(event -> submit());
Button save = new Button("Save");
save.setOnAction(event -> save());
myHBox.getChildren().addAll(myScrollPane, submit, save);
}
/**
* Submits the current command by updating the CommandString with the String
* contained by the TextField. Then clear the field in preparation for the
* next command.
*/
private void submit () {
if (!myTextField.getText().equals("")) {
myCommandString.setCommand(myTextField.getText(), Constants.COMMAND);
myTextField.clear();
}
}
/**
* Saves the current command as a user defined command for future use by
* update the CommandString with the String contained by the TextField.
*/
private void save () {
if (!myTextField.getText().equals("")) {
myCommandString.setCommand(myTextField.getText(), Constants.USER_DEFINE);
myTextField.clear();
}
}
/**
* Adds the pane to the BorderPane
*/
@Override
public BorderPane addPane (BorderPane p) {
p.setBottom(myHBox);
return p;
}
/**
* EventHandler which submits the command input when the enter key is
* pressed.
*
* @author Team 14
*
*/
private class SubmitHandler implements EventHandler<KeyEvent> {
@Override
public void handle (KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
submit();
}
}
}
}
|
tetrafolium/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/random/RandomItemFragment.java
|
package org.wikipedia.random;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.dataclient.restbase.page.RbPageSummary;
import org.wikipedia.page.PageTitle;
import org.wikipedia.views.FaceAndColorDetectImageView;
import org.wikipedia.views.GoneIfEmptyTextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
public class RandomItemFragment extends Fragment {
@BindView(R.id.random_item_container) ViewGroup containerView;
@BindView(R.id.random_item_progress) View progressBar;
@BindView(R.id.view_featured_article_card_image) FaceAndColorDetectImageView imageView;
@BindView(R.id.view_featured_article_card_article_title) TextView articleTitleView;
@BindView(R.id.view_featured_article_card_article_subtitle) GoneIfEmptyTextView articleSubtitleView;
@BindView(R.id.view_featured_article_card_extract) TextView extractView;
private Unbinder unbinder;
@Nullable private RbPageSummary summary;
private int pagerPosition = -1;
@NonNull
public static RandomItemFragment newInstance() {
return new RandomItemFragment();
}
public void setPagerPosition(int position) {
pagerPosition = position;
}
public int getPagerPosition() {
return pagerPosition;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_random_item, container, false);
unbinder = ButterKnife.bind(this, view);
imageView.setLegacyVisibilityHandlingEnabled(true);
setContents(null);
new RandomSummaryClient().request(WikipediaApp.getInstance().getWikiSite(), new RandomSummaryClient.Callback() {
@Override
public void onSuccess(@NonNull Call<RbPageSummary> call, @NonNull RbPageSummary pageSummary) {
if (!isAdded()) {
return;
}
setContents(pageSummary);
}
@Override
public void onError(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) {
// TODO: show error.
}
});
return view;
}
@Override
public void onDestroyView() {
unbinder.unbind();
unbinder = null;
super.onDestroyView();
}
@OnClick(R.id.view_featured_article_card_text_container) void onClick(View v) {
if (getTitle() != null) {
parent().onSelectPage(getTitle());
}
}
public void setContents(@Nullable RbPageSummary pageSummary) {
containerView.setVisibility(pageSummary == null ? View.GONE : View.VISIBLE);
progressBar.setVisibility(pageSummary == null ? View.VISIBLE : View.GONE);
if (summary == pageSummary) {
return;
}
summary = pageSummary;
if (summary == null) {
return;
}
articleTitleView.setText(summary.getNormalizedTitle());
articleSubtitleView.setText(null); //summary.getDescription());
extractView.setText(summary.getExtract());
imageView.loadImage(TextUtils.isEmpty(summary.getThumbnailUrl()) ? null
: Uri.parse(summary.getThumbnailUrl()));
}
@Nullable public PageTitle getTitle() {
return summary == null ? null
: new PageTitle(summary.getTitle(), WikipediaApp.getInstance().getWikiSite());
}
private RandomFragment parent() {
return (RandomFragment) getActivity().getSupportFragmentManager().getFragments().get(0);
}
}
|
Acidburn0zzz/test262
|
test/built-ins/Atomics/compareExchange/non-views.js
|
<gh_stars>1-10
// Copyright (C) 2017 Mozilla Corporation. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: >
Test Atomics.compareExchange on view values other than TypedArrays
includes: [testAtomics.js]
---*/
testWithAtomicsNonViewValues(function(view) {
assert.throws(TypeError, (() => Atomics.compareExchange(view, 0, 0, 0)));
});
|
comprakt/comprakt-fuzz-tests
|
output/9f5c5d2450434ab296e540be02f1252e.java
|
class c43UqVPUKGw {
public static void VyOEN (String[] y) throws So4c9Rnj {
boolean TL9xS9aGrY;
while ( !50[ --( MZ3J0OM8h1v()[ false[ -!-!new v[ -tO.WXQa].cvW()]])[ true[ null[ ( ANqR8.OyFxe0d7c5w).Ln3vjOJmRsLta()]]]]) {
if ( --!910.dpVqAC2g6HTa1()) while ( 768643871.E24k8NO835mb()) if ( p0[ -!41754084.RGWYR3IDB]) return;
}
if ( null[ -y7ywVtK().Mr13xHLbPZUU5]) ;
int oJCxm9EO3e;
JQQBoNX fG;
int zRAMO_yBOp;
boolean[] ehFEfA;
int cRm4wGzDR9r5;
int[][][][] rCY;
int[] qGj8 = HFor_oM().X70TdVw8Etc;
return SQ4[ !true.K0r7d];
-50876202.Q4gsiW();
}
public static void SYmLi (String[] iNEY3R9_Qr7O) {
;
{
;
boolean[][] omMZzfmMzSP9;
4644251[ new Ei[ 83087.R1qpVVA()].Y()];
void[] HffW;
}
void[] mqch2ox0A;
{
{
89021.DngCByx4();
}
qU[] E5HJnkx5;
int[][] xTGM0hMTwRX;
;
boolean mU9GNshqfhr;
}
{
;
;
return;
--this[ null[ null[ !-314863879.Jr()]]];
}
KeoUhVvZaMjO[][][] er;
void cn2jT;
void[] NqeBRKUO9 = this[ --true.yt2()];
void[] X5otVKEnT9xn = new Xyh0Umbi9R[ false[ new void[ null.UwnX].Uxqgrk5mOT()]][ this[ -!!new C6()[ true[ -!null[ !true.e0()]]]]];
boolean[][] PRt144Z9eX6D = -!!-!Xgjfe8KAtwC().fS2bGfSQrj;
bC8iG0Hs.uEC0UxTPOXQ;
while ( !null[ -this[ -new dREZ7H()[ -!!new void[ -!false[ -true.CKen]].uBln8rh()]]]) while ( --( !!( !!-!true[ new Go()[ !!-false.Q3huk0ojMo9lL]])[ ( KkV4Ruc().HIf())[ 512[ !-true.oOyStLvt9bx38()]]])[ null[ -false[ !true[ !new buur()[ -true[ new ijKelDkA()[ -U7B5bYh5Xh()[ true.cnPNIUDhDG]]]]]]]]) return;
new boolean[ -!3824462.kH][ !this.sMPC()];
return;
( ( !true.f0())[ true[ !-!!!!-!-!!false.A0tiR57li6JMn()]]).xB_Go;
boolean[] cTOee6H = -false[ WfifAWmpQL77x.Ty1f95n];
sX[][][] yFGCON_AfSV;
!hqZ5fQd.OdzmQc689mjm4v;
}
public V[] nLbsXo774XxRxU;
public TVUjIjhsV3[] CE;
public static void laOu2TJRlz (String[] zuspItwlYqnWvr) {
int[] DbV00YaH9q;
}
public static void RyMCq (String[] W1goix) throws mOriLh2 {
void avk2z;
if ( !!Jnyv4jIZK().VjO6gmnJH6a6a()) ;else return;
{
int[] H1MR9XZmbU3;
boolean iNlNXoUz2;
boolean Zxr9kRO1;
int qgL;
void Jy;
{
if ( ( 9.N5).uD5k1hT0()) ;
}
int[] p;
int[][][][][] KmFZWeTn;
Wskx9gtGVlq1x[] J;
while ( !-true.ZBjqa()) {
nYJBh8l143hL zQQetIKFGQ5E;
}
701[ ----false.ovb()];
boolean[] f;
{
boolean o;
}
}
int K = -new int[ MmOzYUYKU.KaSgAIo][ false.Jj_b0a_a] = !-this[ -!xSBnbJ()[ null.zlDqlrp33tdX()]];
while ( --769.N82pv0h4W33()) -new int[ aozf().zd71DgwTx].XU36dunFws;
;
while ( 696.K0UPw8dPPq0rh) true.dev9eTrvnS2();
;
;
while ( new int[ -!!this[ new _()[ !!!false[ gIWxxjzukEaU.FlMCE7E7c()]]]].XseQ()) {
while ( new void[ zi1xZcHvdS0a.H()].E7aQ) -!-false.xQ1nG8T1sqS;
}
;
Uff[][][][][][][] QWDd0OOGwFs10;
int[] Wc04n7D9VY = this[ !!new ZMhI6obhKPxk().cIfiPUpO1] = !( true[ new int[ htkHvr_.USwnmxD2c54C()].aVzF0KDcB6b]).s;
}
public void rlssUSO_0_9yeU () throws R {
int A20PTJ7JE = fV8NIR6sOcFfM()[ kY()[ 525.yarnjWn]] = -this._9lZdh;
while ( !new boolean[ gxBkz6.IvfczVbbU_J()][ -!new void[ new void[ !562896053[ ( true[ new TBv().jp]).zIZ67ZZ0HSNJ()]][ !PhzvxA0Y3uHdoZ.XzzL0YFldU1WgB]].YnPWomC()]) ;
{
boolean[] c;
{
int olZVLviS;
}
while ( !!new y().UQs()) ;
;
if ( ( --new FWRPg91si[ new d92bhge4AF28()[ false.fxEVdD9G]].vGUSdHWBi).L5V1) while ( true.GDo1Hvb()) while ( true[ !-ShGNmuic3._ORSP()]) {
while ( -glw0fh.gR_f()) {
return;
}
}
return;
void Hm3GWjYH0j;
int zUg89;
boolean[][] m3b;
boolean[][] sCjOYGNWh9r3l;
o3jk5MVQsxXH[] CXhe5nkr;
return;
null[ ( !!----null._nVi7q7cElSI).yvIPeeyG()];
q5cBvtl[][] ZFTCxWJeaPra;
!-( !-new void[ --null.BwM].reFuo4tV6faGl())._5Vt5kQG();
;
{
while ( null[ 707507.nVCWHtSbYU]) if ( !qO_Qr92xyIwKW().sJ05EwbO) while ( -!916402[ this.p4lpCw0K]) return;
}
;
}
{
false.j3wr();
VFKv0Rxd2pqGrv Q7;
{
boolean[][] ii;
}
{
while ( !!-true[ false.xuQ2dIF]) ;
}
{
boolean[] A6;
}
if ( new xCfp_ewoH8Sie().SJRKTEeUFyfI()) if ( JrguqfnA().lF()) {
while ( -lV9nK[ -NRMsH()[ -new void[ -----false[ 8087[ this.Nw()]]].BOn_caxWOV()]]) return;
}
}
;
Q8i8muy RsuaV2dvZ;
void[] Z5E2ZkJ8K8Ba;
H807ntWQ1nzF[][] e8q73EPbha = !this[ Zujx().Tuagv72FhD()] = true.rxDyDerK;
void F70HJWVGHi5Z9M = !!-new void[ ( zPhjQ()[ new L9YeGEJKDzE().wwkBcoMllEfab])[ -783695762[ this.lhKrfmfmvq]]][ new oFBUDAxX58m()[ true.Jg64z6TE4cZX()]];
}
public int Z;
public int iM;
public static void qSzUE6RW (String[] x) throws GuCZzq3SQ {
if ( -!-new y1h().pkH6NrAyQBHI8A) return;else if ( false.M1rZC2x1EF) if ( !!true[ !false.t43()]) _zzf[ new C().qa5TJu4xSugUG9()];
void[] Ty6qvvwa = !-!!-false.xk24_o;
void XGnr2FUjNMOi;
if ( 643969.DJUbSWVPZx4r9) ;
true.vm_DQrBjQc;
while ( --new boolean[ -null.tnzkSNee7AbKR].ycj) return;
void qUjAl7O_vr2 = false.G() = false._DKMLXVr9ea();
{
false[ -!this.XbhBUu2OCK()];
if ( --false.zlMSZt7uT0) if ( 5[ new WQfp7yyWJK().FiCVc8exDdZu]) {
jVR4KS YmKvskZ;
}
int KX;
while ( new u1fh6jnYFI()[ new M1M6xdMKtq()[ --false[ !U6FWvPE8WFd[ -!---!DtyW6[ -null.MAl()]]]]]) if ( true[ -new EMcxw()[ ( !true.lB()).mFlRq_oUBqT]]) return;
boolean Hs9a;
boolean YF;
int[] Pm;
void aobkM;
boolean[] favVGEBNVE9cdu;
{
int[][][][] Si;
}
if ( Hgl.ZXlYRHMe()) if ( tn6dCMC().Z3X()) ;
true[ wK3YFA7.ZWzwivYDOz1Q8d()];
{
void[][][] ZzqsRBNwfz;
}
c4S045vy tvmDtIT;
!-!!-!null[ new boolean[ new void[ ( DvxvSwpvOxYJ.T1m0pWHjR()).Tc6z4fd()][ !-1547.BvGw_fS7D9Z()]].GZ82k4JXD()];
}
void[][][] HklJ = -new boolean[ !!-this.W5qmVvc7Dd()].ZZCLad5k85cq2M = -U3TpeI8h.bygIA;
void[] TYUugceZGz_X;
return null.pImh09B6;
return;
if ( !GZ.lb()) while ( !false.awZp4()) if ( -!-true.HpXWwCxozrXV) while ( new eU().nENc5jbtav()) {
void R3BNZYRjV;
}
YDQQUYd[][] rMQ;
while ( new boolean[ new gStFToQjAA()[ true.bFCxDOPZYR]][ new Lh79kpbRZ1BLbm().YIYJ6WMcJTQJ()]) --new boolean[ -( !( imyYf4().osoLT6FVNPg).Y0pAQMLknqP).JgsCRQJb_X][ new _vA7l_s1().HCALz0ohlD];
COZ36Qs6I[] FK_XSs = -428207668.Z() = new mE0YML2c().K07ZyaN();
if ( !!!!null.SmqF) while ( new aCEt_q0hUu0kW8().g4uGkG) if ( !new FwVjCLmhBfG()[ --false.BRLgIMQ4e]) while ( -false.yKKIkWjKWM5()) while ( false.Rac()) !-new boolean[ --false.B3aNKDvdaXtA].caRghXuz;
DZfaelBbewFl[] btWAexjFSx7 = !-25.ZH_1QQ();
-3669.G1IMxIjf0aRpH;
}
public void[][][] b (void[] rZRVz6Xe, void j, void mX7VCWfSb1AnMO, void Ok8) throws RZnJEBEDUPJW {
;
{
IvgWcG().tHoPgvtwS();
int[][][] gNDf;
UKl3FQO FjI5HI_Bd1yMtr;
if ( this[ --59385.axcwtsEhJfDPo()]) return;
int[][][][] O4I1NtrBY;
return;
return;
return;
int[][][][] NDMbvnP5HgEs;
{
while ( true.tDuPpXF_) !!L().njU();
}
void Lt6PaV6B2;
void[][] AZ65C;
return;
ntYiATZdbV3WH2 ZLdBlVNKpmcv;
if ( null[ !!!6662.JGwV]) while ( new Ttm()[ -gk4YlegAJ.xjTp4pQxVkG79U()]) {
while ( -false.P) !new void[ new void[ s().ZOdyw3M0qIL5A1][ -!Ko_S4Csi().naqlDq1LYX]].JP;
}
while ( false.E5fwd_yuvpdQHH) {
-this[ new _dmg()[ !!this.hVnK()]];
}
!ot3ArL[ false.iJileTshYb];
}
;
while ( this.SN1a2HsjAf) {
int[][][] GI7Tht;
}
void BK1tZ00ml8q;
void s;
boolean yOgPfo9Mr;
YzR0yFBy2Dem xak = !!!null[ !false.RJf];
UN_wXAMZc[][][][] Zo0aztzmW1oU;
-true.zt;
while ( null.OLcWItRQYiWzWA()) return;
}
}
class sBqSAfFBZ0 {
}
class YfkzoYt_KHjjX {
public static void Ur (String[] hq6) {
boolean[] t6a0l0VTHaeu = new cULl().TpnkC = -new nj66os8Z().eGQD1();
true.P();
-EYXCfdYjlV[ true.EYwP5j7vWbo9Ki()];
while ( new NMcazBGs().u4xTj6Yonq7) ;
;
;
-!!--!null.Ob;
void[][] K8xLz1ZHr;
;
int[][][] XPkd6LlfUy = !!-135978048[ null[ !-this.DsNqGWbx()]] = new UkEvHTg().FEPbu4t;
boolean y6VEP01A7v = !true.C() = true.gftvqew2;
void yK1ZwyRx;
while ( qzZIhrZmf.zlL2YfqI9rQ4fo()) true.VNaVmcR7q();
;
boolean NVjwP;
boolean[][] Ap6qtls8jr;
NjL[] V4mlW2ILIpjo;
;
void FYRhBU2CZj = !( !!new He3pPDsvCIpw3()[ DsuCEf2hJrxUeQ().NLsFy6nHpTURL0]).D8To_();
if ( ( ( -new int[ !!!-new x5v().wQ].sQs89()).xbd7INGn).VRBkAVD()) -( 1709398.ALMv())[ !7428155[ --new void[ this[ -false[ null[ !new boolean[ !352125.S8X][ nNUH().FfV7LNhdEMk()]]]]].B3bFOKs_CXPo()]];else while ( !!!this.OOaxCU5Dy) !!null.OLmRH;
}
public static void fm (String[] _m) {
while ( !-!UlpFh.hemco8N5JOuh) -!--!!439683.Y7noiq5E_TEu4k();
return;
eP[ new aXpbpF_().lqeQFAhxz7SVQn];
QXoa[][] C0PWbbccvudSk;
pjTbW YsKnRYkZ4;
while ( new void[ ( --!new DCPfbq().aJrj8)[ -true.B4mQSVpz]].w3()) -q5M.gyoAgq7;
( -( -!249375[ false.z5Flkc]).oBa9J)[ -!( 885330.BfocAz35Ywt())[ !544.GcTY()]];
while ( new S7bOAzL1hxFSw().eOnCo0NF4APMb) if ( -!!new void[ ACPXbsKXyB2U9g().lXaHVfd9Y5qVHC].H) !-!-!( ( CS()[ null.oLqFp])[ -!-new WJTkTG()[ ( -qJuGU.xjNpVXrr8VTcH)[ -null.yFxGRAGKAStI4()]]]).PEjW9LvFHYFg;
int wJanbnfD;
return 39102748.YxJ4wDquJ9QN;
boolean dMGShhiavbI = --HZHFT3DBHRpoRM.UqQBZVlc0d = !false[ -07390340.nS0qmAmt1XzEN1];
boolean[] dZKGJ0GhHEp;
return;
q6Qw d = this.hJSN1rTUmJ();
}
}
class C8R4S {
}
class ekGkeGQ {
public boolean X48HbfPzqQRVVP;
public NldyC[] q1se6Mnt0Q;
public void[] va8sqWB_S (int Ok0TnkW, boolean[] RscZ2V, int[] QrtX5JFutDkyh) {
OLzu P1sAA46y;
TLdYZ KWYLZDc6Q2RCS;
{
{
void fgA6w;
}
boolean T24JTiU7QRc;
int[] IluBiuzNc7s;
TD i2b3UqT7wav;
boolean[] TyDX;
int TuQ_Of;
boolean cYDKW5IrH4u8g;
sTwXvBveD8 Y;
boolean FYPGs5U6nL4;
return;
void[] i;
co TS5pO;
{
boolean Yy3;
}
y EZmuiKtY;
;
;
}
return oIbaGvUZD6gU()[ -( --this.vNAoGOykKua()).pGPta2VEca()];
while ( -new fil8QfuHHTH()[ !false.q]) while ( this[ ---false.z2HPh()]) if ( null.gHQ4J7PzNP0I) return;
{
if ( this[ -null[ true.YD2MbEG]]) {
boolean Zpy0ckTHqKOG6x;
}
int WlHbAPC1VdcsN;
boolean[][] cPHeKsxPy;
-null[ this[ ---!!null.qao23m()]];
return;
{
void[][] RaMMjEU;
}
boolean[] qJr6;
!true.soqK6CCmxO;
boolean[] tzlpo_x;
!!new H62qP().GB30vk();
void[][] LPh4L7Wa0pF;
MYkyQr[][][][][] NRObKkpR3;
new mwq().LNHlLb();
void[][][] MvkRZLMUI;
pd aQQyWAU;
void rG;
return;
while ( !-new fzgSvkG()[ -new void[ true.dbQF8HhECp].p]) {
return;
}
while ( this.PKSPb) return;
int x90BQaaGYOzjX;
}
boolean HUQl7iRr8 = aI9Tg()[ ( -new jQS8VPos[ 712[ !null[ -( !null.PBCKiMapKq9z8w).E8hP]]][ Efev11blZ()[ true.kK]]).AytK7rZyxtvzbQ];
int FiBFca;
Yh5()[ !true.f()];
pdP[] NP2oRVnV57Ke = -pdRcEfHyddh_n().V63iAlaRS = 64918871.PkLwZqJE1E_kM;
{
;
ADGt6uk[][] iLs;
if ( qVfmEfvtwp2.l) return;
egRL[][] lfF_8H77rpm;
;
{
void[][][][] C;
}
int JcAkHU;
void[] eXSFYZoxt;
if ( new void[ this.Q7VeQD1NtXw()].OnxhUENSwBNG()) if ( -false.W4zqk()) return;
boolean ctTtqp8kECzp;
true.OYymiepsYIG;
!!!new EYKxz_B().iz();
int[] P_vxz_nPEQTTU;
if ( !-24472.z1Nm7f()) while ( !!v_JErx2_Da9b().Hv5Ny()) 9616016[ this.rllOKIJFXit];
while ( !null[ VoUvX23dB().n()]) while ( !null[ --true[ false[ new C().HhkTe6yhw5iP()]]]) LOD_UiJf.RlEBQ5U7Qkwm();
xZwbPi6ni[][][] oFHcC0XO;
return;
while ( !!-true.q) while ( V7JmyCk().y()) if ( !!-72618705[ --new void[ -ql.lon5VHoCrr].Tmf5LJqp8Re()]) ;
}
boolean vNDVqA8 = 7.PrxOiM = !!new void[ -null.hh6hn_oP].NxRxUa0();
}
public static void slHlwcJE (String[] MLpBHQ) {
while ( null[ !-false.YhSyvzVAhSEmJg]) return;
;
boolean BA;
-new int[ -!!!new P3_I3un[ -96656948.Y3K9O1()].Px4hz].a6bQpVJYC36R6o;
-new ohX().kLOo7kh1gfKqtX;
if ( -60076563.Ek2I) --null[ false[ -70.kP]];else if ( -this.nCIi6TjWF50YIq()) return;
if ( !-false.Gtd) return;else if ( !x6LrbdsOiv()[ false.c10MeW3()]) !iGWpOCHsqvA().ahy0eO();
}
public static void UjhvSY (String[] pAFn) {
_K[] N = -null[ this.Fj0HoZF6()] = -!true.WpuTptJQ2l();
;
boolean[] FV2ybbeejVan = !d2S1z[ true.Lh0nULB6gJ2()] = !!jXL[ 92231205[ !-!true.zq_9DSvErt0x0()]];
while ( -new s05FrUYv[ !( -new S().M9q())._1jsZu22uqAAO()].U0dE9H2V2k()) return;
int xhEznlVSdmc = -this[ true[ ---new int[ -!w54SVFJbMpZ91().ICO94DkJvKKK9].vjTmsxp8WiO3mh]];
if ( !-false.x) if ( true.ahTDfPPvR) ;
}
public static void mQ1CD (String[] fZ) throws uXi5jf7JGNny {
!!new xqtYZNxuw7_u7().lM9S;
{
{
null.B5TUyA8;
}
}
if ( jEaDmVJ0rlbW4q()[ new boolean[ WvQiMV4b.lrfjlHk].FBmaa1DO4E7EU()]) return;else {
void W3jPgJIpfaUH;
}
int[][][] bhUSqSHit5Aw;
if ( -new _TNvZ().SL) {
BxkgwXufUOBrU CfpD;
}else {
if ( !new lzuS().jqK5OXitm9rr()) if ( !false.Thg7) return;
}
boolean YLYdGejzY;
boolean[] f9B6juTpU4b = !new void[ this.zy9qM()][ ---!!new void[ !!f.pCAd1A]._9im5I4];
}
public int[] gjb3zV;
public static void MQ (String[] L6VzDBHNuG7Aa) throws BGLtgK4sGaRyL {
while ( null.opVuYlNDTlKw()) while ( -new v()[ --null[ JqW8XFV().uVgxutRy]]) while ( new int[ -null.qlQ5xrxj()].oUcy) kv8xo6i4M()[ !true.V6rMfC3];
null[ 1818579.XIIt_OhTYplms1];
;
boolean IH2eLiMatlLUV;
return;
int[][][][][] YmcwCjP;
return;
s76HjTecczIUoz[][] D = false.jOGTSnQiWmI = -false[ !!428.kY1K1_()];
boolean lErPPpPhW9d2w = ---5043.OiOtNzI6Ok();
while ( ----this[ 851304[ !!-true.mF9z3I3LqX3X()]]) return;
while ( --ViOLz0vuNyQ.vDLf9BHS()) ;
void[] mGztcTWOqdk = 30866272[ CJ9u2q0Cjq.NW0a];
while ( --758269103[ this[ !!!!!!( new Ppu()[ false[ 24374[ !!!new B7().TdWy0jA()]]]).H2w_sqh()]]) true.lwA35Y8w();
void[][][] oHXB9N;
return !( --( -new void[ !!this.kgf7pvYJ()].Mwh9)[ true[ !( -na_RH_Vf6zB.oefx4()).N]])[ new M9b5lt8HIfm().r4kIwk_eFGJpJ];
void[][][] BsNyBanbRl;
boolean dzmDXM;
}
public void xIWd8PTPXA;
public static void ay (String[] Cps5) throws KUY3sEja {
boolean wY3R4H;
int qlF_VEwEqD5PHW = !false.lO7ZfStR0Q;
PEwxkfbw sGknJM;
;
int myiUn;
g7IhMWyByknIT7 i;
!--6329.KfK1kVeFbomET;
this[ -ji9oxD6V3()[ omtG8Eg1Y8orG().B7ymEPg4if()]];
;
boolean[] ZG4wB;
kryjKnm_Z[] Kji = -GX0csAIxSgDGrN.mpSCdkFRuX4u79 = false[ !-new void[ this.Sas].lWyqo()];
{
PKqZtgTDTO5IT[] QdboJ84;
;
int[][][][] TQMIu5NuN7d8;
void vuIBXx;
}
return;
}
public static void XEgjMQL6wu (String[] K3k3r4PFnuAqO2) throws vD {
pojwa9doKbPg b;
void[] q;
boolean RMaXmsR9j0o;
r[] yxXG9xxiCl87Dt;
-new boolean[ !this.fBGo84yAnZG()].sx();
if ( 522076[ new void[ -new oIUaEhf5Af5F[ -!( new NaqFO7yuh8OVs()[ --!!jF.clTVC5RuNaZfm()])[ !Ttwcnwi[ null.Y50JDHjVGiqWL]]].c].qa()]) 1287[ ( !-null[ !new boolean[ SJhVtQbPU_R3G.qhVk2avt2Ai].LCa()])[ true.phat0Jrjm]];
}
public static void cdea (String[] L9k4IfW) throws xW0zPeu5 {
return;
ltVTsxXbNgjO eRve9dTpZWna;
ybIVPsPIOp lC = x1().KxlRZzsDzUeY() = !( ( -!this[ -new _S2ZhcWAHT().HT2bl0ot7l])[ new boolean[ --null.QzWp].ugGby])[ this.PmANQnwg0fO()];
{
JzuKv kZQGOyebxJLMv;
boolean wpJ12Zc;
{
{
boolean vCJ0pc7v34K4;
}
}
while ( -true[ -new vnDqZLXkv().kbk4TQAtO()]) 75173529.JmgJ();
int CR;
int ho;
}
while ( false[ null.Gb2i]) 22229073.Op;
new Z_VsIJ().s0ySW();
int[] f7oRKpt;
while ( -null.iP7r()) return;
int[][][] g7CXVFPDYjVA;
int IGmWq;
;
while ( -!!-new H4qoPw().QjZeSwVsMN()) {
boolean D3j_PoVEWEFD;
}
}
public tEeNXZUv4s_ YbNoRJp () {
while ( new void[ null.k5xpw].sPSvLFhY()) while ( !new NC1p().YOvEUi5bCs()) false.DvsZ_cE;
Z4[][] uGel99g = !zvxyLdkl0().XF;
}
public static void CzM (String[] _VVykNq5dP2K) {
return;
if ( new boolean[ null.z4rjK7S8U()].bQUMje) if ( ( !true.RCVT)[ false.I1KXareDxUD()]) if ( false[ ( !true.bMEsXYj()).JOFLq()]) {
if ( -!-!!!true.KqzxL) EoIZ0UP6PA9A9i()[ null[ !!false[ new void[ false.m8Xc0pML6v].zo7B()]]];
}
boolean[][] ex8EPt4EVP = !!!-PWRpEjCXM9().eTD() = !true.bU;
;
boolean jIyHgWOUjM = new void[ !false.YKTEPpFFp5Xx1][ --PCiP3fJyRmF[ -new od22lqMG().ITcCNv()]] = --!new int[ -false.wG()].T7JoESmop6z;
boolean IkE;
p6Z[][][][][] Tm = -!!new int[ -!!false.s()][ new T4VHMLwux()[ igjyQ8bQSvsf().lzjVWXfGOVA()]] = !!----true[ -new boolean[ false.JSTzg].XjBSJ()];
gU lF9s1 = -Gl_bcdS_Ap7t51.ZqRFSMXLxS3AE = false.zm7zp;
AvufXfKdJDtQ7().Xtx4j7D8RIBl9g;
}
public static void z8PAg6g (String[] Bn3w) throws LMC8w2JV {
return;
void[][][] ld = true[ new WT1XkF().g];
while ( NL_izG4BDQww.pPBAU_) while ( this.K3N8VDE6zKBA()) ;
-gBBfkwX.AKmNa();
-!Qt[ -this[ !-new void[ -new iS()[ null.j3bnzLAs1zDZZe()]].yAHb97xPzfFnOw()]];
return -!-!lava2Y.Wpi_UB;
boolean[][][] yJ7tFSxZM;
while ( false[ -!!( false.gmEh3v05A()).W]) while ( null.gwyGvwcwr) null.tRmj8();
void[] RL1frFWAQ = false.eoz() = false.lya9P6ZRPO2;
{
if ( dJN.V) {
;
}
boolean eR;
boolean FIuIYqpG7JL;
--!-new wu939cHUFyEi().hh4;
while ( X()[ Z[ -!( Xr2xUqzWmg6.va5)[ true.kfun()]]]) while ( null[ ( new s()[ !!QOKov.jnRfw]).flKW3hyuo6FE]) return;
return;
if ( _nT4()[ y().Avk3W]) while ( !new F6a().njwfFfs) ;
IFuIEV5cqCc wL5My2s;
if ( ---!new w().FHBMuY1A8hNO77()) if ( 42[ null.U()]) ;
;
int[][][][][][] Qu5gt9xLfqk;
return;
while ( ( -!this[ !U211jS().yG6g1H]).kSvnPvhF) ;
while ( this.oq7()) {
while ( -true.Hln5H()) -false.ZNgP7V8hk82fZ1;
}
boolean y3fZS8q_cc9u7;
if ( -481294742.e3u()) while ( ( this.GFatwk1()).K6r()) {
boolean[] k;
}
}
iaIMK4Gqay ILV3Kg = -!-!!dWOfJjf()._c84() = !!( !true.D5wDw4V).TmOVlVC();
-644.vo();
boolean IUnCSdc = ( --new int[ _o7Z6Ja[ ( 2990125.GwuKdDATjx7())[ -( new i1Ib3()[ -true[ null.U_vqTaxP2Yv()]]).gR8oKqa]]].oLE9HVty()).r8M8Dzn() = new O5tCp6PH1i6()[ xI8xrmZLY49oRq.sN];
}
}
class sq {
}
class AmvR {
}
|
lina128/ikelab-studio
|
tests/routes/Design/containers/Trash.spec.js
|
<filename>tests/routes/Design/containers/Trash.spec.js
import React from 'react'
import { shallow } from 'enzyme'
import { Trash } from 'routes/Design/containers/Trash'
describe('(Design/contianers) Trash', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Trash />)
})
it('Should render as a div.', () => {
expect(_wrapper.is('div')).to.equal(true)
})
it('Should have class design_trash_default.', () => {
expect(_wrapper.hasClass('design_trash_default')).to.equal(true)
})
it('Should render an img with a trashcan icon.', () => {
let img = _wrapper.find('img')
expect(img).to.exist
expect(img).to.have.attr('alt', 'Trash')
})
})
|
HugoFdezVega/reservasAulas-v3
|
src/main/java/org/iesalandalus/programacion/reservasaulas/mvc/controlador/IControlador.java
|
package org.iesalandalus.programacion.reservasaulas.mvc.controlador;
import java.util.List;
import javax.naming.OperationNotSupportedException;
import org.iesalandalus.programacion.reservasaulas.mvc.modelo.dominio.Aula;
import org.iesalandalus.programacion.reservasaulas.mvc.modelo.dominio.Permanencia;
import org.iesalandalus.programacion.reservasaulas.mvc.modelo.dominio.Profesor;
import org.iesalandalus.programacion.reservasaulas.mvc.modelo.dominio.Reserva;
public interface IControlador {
//Método comenzar, que corre el método homónimo de la Vista
void comenzar();
//Método terminar, que simplemente corre el método exit y cierra la ejecución
void terminar();
//Los siguientes métodos simplemente corren los métodos homónimos del modelo, recogen los parámetros que se les pasa desde la Vista
//(que es desde donde estos métodos serán llamados) y le devuelve a la Vista los datos que retorna el modelo. También propaga las
//excepciones para que sean tratadas más arriba
void insertarAula(Aula aula) throws OperationNotSupportedException;
void insertarProfesor(Profesor profesor) throws OperationNotSupportedException;
void borrarAula(Aula aula) throws OperationNotSupportedException;
void borrarProfesor(Profesor profesor) throws OperationNotSupportedException;
Aula buscarAula(Aula aula);
Profesor buscarProfesor(Profesor profesor);
List<String> representarAulas();
List<String> representarProfesores();
List<String> representarReservas();
void realizarReserva(Reserva reserva) throws OperationNotSupportedException;
void anularReserva(Reserva reserva) throws OperationNotSupportedException;
List<Reserva> getReservasAula(Aula aula);
List<Reserva> getReservasProfesor(Profesor profesor);
List<Reserva> getReservasPermanencia(Permanencia permanencia);
boolean consultarDisponibilidad(Aula aula, Permanencia permanencia);
}
|
Tanc009/jdcloud-sdk-nodejs
|
src/repo/domainservice/v2/domainservice.js
|
/*
* Copyright 2018 JDCLOUD.COM
*
* 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.
*
* 实例信息
* 云解析OpenAPI实例信息接口
*
* OpenAPI spec version: v2
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
require('../../../lib/node_loader')
var JDCloud = require('../../../lib/core')
var Service = JDCloud.Service
var serviceId = 'domainservice'
Service._services[serviceId] = true
/**
* domainservice service.
* @version 2.0.3
*/
JDCloud.DOMAINSERVICE = class DOMAINSERVICE extends Service {
constructor (options = {}) {
options._defaultEndpoint = {}
options._defaultEndpoint.protocol =
options._defaultEndpoint.protocol || 'https'
options._defaultEndpoint.host =
options._defaultEndpoint.host || 'domainservice.jdcloud-api.com'
options.basePath = '/v2' // 默认要设为空""
super(serviceId, options)
}
/**
* 查看用户在云解析服务下的操作记录
* @param {Object} opts - parameters
* @param {integer} opts.pageNumber - 分页参数,页的序号,默认是1
* @param {integer} opts.pageSize - 分页参数,每页含有的结果的数目,默认是10
* @param {string} opts.startTime - 记录的起始时间,格式:UTC时间例如2017-11-10T23:00:00Z
* @param {string} opts.endTime - 记录的终止时间,格式:UTC时间例如2017-11-10T23:00:00Z
* @param {string} [opts.keyWord] - 日志需要匹配的关键词 optional
* @param {boolean} [opts.success] - 日志里面的结果是成功还是失败 optional
* @param {integer} [opts.type] - 日志的类型 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param actionlog dataList
* @param integer currentCount 当前页的操作记录列表里的个数
* @param integer totalCount 所有操作记录的个数
* @param integer totalPage 操作记录列表按照分页参数一共的页数
*/
describeActionLog (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeActionLog"
)
}
opts = opts || {}
if (opts.pageNumber === undefined || opts.pageNumber === null) {
throw new Error(
"Missing the required parameter 'opts.pageNumber' when calling describeActionLog"
)
}
if (opts.pageSize === undefined || opts.pageSize === null) {
throw new Error(
"Missing the required parameter 'opts.pageSize' when calling describeActionLog"
)
}
if (opts.startTime === undefined || opts.startTime === null) {
throw new Error(
"Missing the required parameter 'opts.startTime' when calling describeActionLog"
)
}
if (opts.endTime === undefined || opts.endTime === null) {
throw new Error(
"Missing the required parameter 'opts.endTime' when calling describeActionLog"
)
}
let postBody = null
let queryParams = {}
if (opts.pageNumber !== undefined && opts.pageNumber !== null) {
queryParams['pageNumber'] = opts.pageNumber
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
if (opts.startTime !== undefined && opts.startTime !== null) {
queryParams['startTime'] = opts.startTime
}
if (opts.endTime !== undefined && opts.endTime !== null) {
queryParams['endTime'] = opts.endTime
}
if (opts.keyWord !== undefined && opts.keyWord !== null) {
queryParams['keyWord'] = opts.keyWord
}
if (opts.success !== undefined && opts.success !== null) {
queryParams['success'] = opts.success
}
if (opts.type !== undefined && opts.type !== null) {
queryParams['type'] = opts.type
}
let pathParams = {
regionId: regionId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeActionLog with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/actionLog',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 获取用户所属的主域名列表。
请在调用域名相关的接口之前,调用此接口获取相关的domainId和domainName。
主域名的相关概念,请查阅<a href="https://docs.jdcloud.com/cn/jd-cloud-dns/product-overview">云解析文档</a>
* @param {Object} opts - parameters
* @param {integer} opts.pageNumber - 分页查询时查询的每页的序号,起始值为1,默认为1
* @param {integer} opts.pageSize - 分页查询时设置的每页行数,默认为10
* @param {string} [opts.domainName] - 关键字,按照”%domainName%”模式匹配主域名 optional
* @param {integer} [opts.domainId] - 域名ID。不为0时,只查此domainId的域名 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param domainInfo dataList
* @param integer currentCount 当前页的域名列表里域名的个数
* @param integer totalCount 所有匹配的域名列表的个数
* @param integer totalPage 所有匹配的域名列表按照分页参数一共的页数
*/
describeDomains (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeDomains"
)
}
opts = opts || {}
if (opts.pageNumber === undefined || opts.pageNumber === null) {
throw new Error(
"Missing the required parameter 'opts.pageNumber' when calling describeDomains"
)
}
if (opts.pageSize === undefined || opts.pageSize === null) {
throw new Error(
"Missing the required parameter 'opts.pageSize' when calling describeDomains"
)
}
let postBody = null
let queryParams = {}
if (opts.pageNumber !== undefined && opts.pageNumber !== null) {
queryParams['pageNumber'] = opts.pageNumber
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
if (opts.domainName !== undefined && opts.domainName !== null) {
queryParams['domainName'] = opts.domainName
}
if (opts.domainId !== undefined && opts.domainId !== null) {
queryParams['domainId'] = opts.domainId
}
let pathParams = {
regionId: regionId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeDomains with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 添加主域名
如何添加免费域名,详细情况请查阅<a href="https://docs.jdcloud.com/cn/jd-cloud-dns/domainadd">文档</a>
添加收费域名,请查阅<a href="https://docs.jdcloud.com/cn/jd-cloud-dns/purchase-process">文档</a>,
添加收费域名前,请确保用户的京东云账户有足够的资金支付,Openapi接口回返回订单号,可以用此订单号向计费系统查阅详情。
* @param {Object} opts - parameters
* @param {integer} opts.packId - 主域名的套餐类型, 免费:0 企业版:1 企业高级版:2
* @param {string} opts.domainName - 要添加的主域名
* @param {integer} [opts.domainId] - 主域名的ID,升级套餐必填,请使用describeDomains获取 optional
* @param {integer} [opts.buyType] - 新购买:1、升级:3,收费套餐的域名必填 optional
* @param {integer} [opts.timeSpan] - 取值1,2,3 ,含义:时长,收费套餐的域名必填 optional
* @param {integer} [opts.timeUnit] - 时间单位,收费套餐的域名必填,1:小时,2:天,3:月,4:年 optional
* @param {integer} [opts.billingType] - 计费类型,可以不传此参数。 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param domainAdded data 新添加的的域名结构
* @param string order 添加收费版域名的订单号
*/
createDomain (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling createDomain"
)
}
opts = opts || {}
if (opts.packId === undefined || opts.packId === null) {
throw new Error(
"Missing the required parameter 'opts.packId' when calling createDomain"
)
}
if (opts.domainName === undefined || opts.domainName === null) {
throw new Error(
"Missing the required parameter 'opts.domainName' when calling createDomain"
)
}
let postBody = {}
if (opts.packId !== undefined && opts.packId !== null) {
postBody['packId'] = opts.packId
}
if (opts.domainName !== undefined && opts.domainName !== null) {
postBody['domainName'] = opts.domainName
}
if (opts.domainId !== undefined && opts.domainId !== null) {
postBody['domainId'] = opts.domainId
}
if (opts.buyType !== undefined && opts.buyType !== null) {
postBody['buyType'] = opts.buyType
}
if (opts.timeSpan !== undefined && opts.timeSpan !== null) {
postBody['timeSpan'] = opts.timeSpan
}
if (opts.timeUnit !== undefined && opts.timeUnit !== null) {
postBody['timeUnit'] = opts.timeUnit
}
if (opts.billingType !== undefined && opts.billingType !== null) {
postBody['billingType'] = opts.billingType
}
let queryParams = {}
let pathParams = {
regionId: regionId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call createDomain with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 修改主域名
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.domainName - 需要修改的主域名,请使用describeDomains接口获取
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
modifyDomain (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling modifyDomain"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling modifyDomain"
)
}
if (opts.domainName === undefined || opts.domainName === null) {
throw new Error(
"Missing the required parameter 'opts.domainName' when calling modifyDomain"
)
}
let postBody = {}
if (opts.domainName !== undefined && opts.domainName !== null) {
postBody['domainName'] = opts.domainName
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call modifyDomain with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}',
'PUT',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 删除主域名
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
deleteDomain (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling deleteDomain"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling deleteDomain"
)
}
let postBody = null
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call deleteDomain with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}',
'DELETE',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查看主域名的解析次数
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.domainName - 查询的主域名,请使用describeDomains接口获取
* @param {string} opts.start - 查询时间段的起始时间, UTC时间格式,例如2017-11-10T23:00:00Z
* @param {string} opts.end - 查询时间段的终止时间, UTC时间格式,例如2017-11-10T23:00:00Z
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param integer time
* @param integer traffic
*/
describeDomainQueryCount (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeDomainQueryCount"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeDomainQueryCount"
)
}
if (opts.domainName === undefined || opts.domainName === null) {
throw new Error(
"Missing the required parameter 'opts.domainName' when calling describeDomainQueryCount"
)
}
if (opts.start === undefined || opts.start === null) {
throw new Error(
"Missing the required parameter 'opts.start' when calling describeDomainQueryCount"
)
}
if (opts.end === undefined || opts.end === null) {
throw new Error(
"Missing the required parameter 'opts.end' when calling describeDomainQueryCount"
)
}
let postBody = null
let queryParams = {}
if (opts.domainName !== undefined && opts.domainName !== null) {
queryParams['domainName'] = opts.domainName
}
if (opts.start !== undefined && opts.start !== null) {
queryParams['start'] = opts.start
}
if (opts.end !== undefined && opts.end !== null) {
queryParams['end'] = opts.end
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeDomainQueryCount with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/queryCount',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查看域名的查询流量
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.domainName - 主域名,请使用describeDomains接口获取
* @param {string} opts.start - 时间段的起始时间, UTC时间格式,例如2017-11-10T23:00:00Z
* @param {string} opts.end - 时间段的终止时间, UTC时间格式,例如2017-11-10T23:00:00Z
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param integer time
* @param string unit 数据序列的单位
* @param number traffic
*/
describeDomainQueryTraffic (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeDomainQueryTraffic"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeDomainQueryTraffic"
)
}
if (opts.domainName === undefined || opts.domainName === null) {
throw new Error(
"Missing the required parameter 'opts.domainName' when calling describeDomainQueryTraffic"
)
}
if (opts.start === undefined || opts.start === null) {
throw new Error(
"Missing the required parameter 'opts.start' when calling describeDomainQueryTraffic"
)
}
if (opts.end === undefined || opts.end === null) {
throw new Error(
"Missing the required parameter 'opts.end' when calling describeDomainQueryTraffic"
)
}
let postBody = null
let queryParams = {}
if (opts.domainName !== undefined && opts.domainName !== null) {
queryParams['domainName'] = opts.domainName
}
if (opts.start !== undefined && opts.start !== null) {
queryParams['start'] = opts.start
}
if (opts.end !== undefined && opts.end !== null) {
queryParams['end'] = opts.end
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeDomainQueryTraffic with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/queryTraffic',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查询主域名的解析记录。
在使用解析记录相关的接口之前,请调用此接口获取解析记录的列表。
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {integer} [opts.pageNumber] - 当前页数,起始值为1,默认为1 optional
* @param {integer} [opts.pageSize] - 分页查询时设置的每页行数, 默认为10 optional
* @param {string} [opts.search] - 关键字,按照”%search%”模式匹配解析记录的主机记录 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param rRInfo dataList
* @param integer totalCount 所有解析记录的个数
* @param integer totalPage 所有解析记录的页数
* @param integer currentCount 当前页解析记录的个数
*/
describeResourceRecord (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeResourceRecord"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeResourceRecord"
)
}
let postBody = null
let queryParams = {}
if (opts.pageNumber !== undefined && opts.pageNumber !== null) {
queryParams['pageNumber'] = opts.pageNumber
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
if (opts.search !== undefined && opts.search !== null) {
queryParams['search'] = opts.search
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeResourceRecord with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/ResourceRecord',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 添加主域名的解析记录
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {addRR} opts.req - RR参数
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param rR dataList 添加成功后的解析记录结果
*/
createResourceRecord (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling createResourceRecord"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling createResourceRecord"
)
}
if (opts.req === undefined || opts.req === null) {
throw new Error(
"Missing the required parameter 'opts.req' when calling createResourceRecord"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call createResourceRecord with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/ResourceRecord',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 修改主域名的某个解析记录
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.resourceRecordId - 解析记录ID,请使用describeResourceRecord接口获取。
* @param {updateRR} opts.req - updateRR参数
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
modifyResourceRecord (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling modifyResourceRecord"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling modifyResourceRecord"
)
}
if (opts.resourceRecordId === undefined || opts.resourceRecordId === null) {
throw new Error(
"Missing the required parameter 'opts.resourceRecordId' when calling modifyResourceRecord"
)
}
if (opts.req === undefined || opts.req === null) {
throw new Error(
"Missing the required parameter 'opts.req' when calling modifyResourceRecord"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId,
resourceRecordId: opts.resourceRecordId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call modifyResourceRecord with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/ResourceRecord/{resourceRecordId}',
'PUT',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 删除主域名下的解析记录
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.resourceRecordId - 解析记录ID,请使用describeResourceRecord接口获取。
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
deleteResourceRecord (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling deleteResourceRecord"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling deleteResourceRecord"
)
}
if (opts.resourceRecordId === undefined || opts.resourceRecordId === null) {
throw new Error(
"Missing the required parameter 'opts.resourceRecordId' when calling deleteResourceRecord"
)
}
let postBody = null
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId,
resourceRecordId: opts.resourceRecordId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call deleteResourceRecord with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/ResourceRecord/{resourceRecordId}',
'DELETE',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 启用、停用主域名下的解析记录
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.resourceRecordId - 解析记录ID,请使用describeResourceRecord接口获取。
* @param {string} opts.action - 要修改的状态,enable:启用 disable:停用
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
modifyResourceRecordStatus (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling modifyResourceRecordStatus"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling modifyResourceRecordStatus"
)
}
if (opts.resourceRecordId === undefined || opts.resourceRecordId === null) {
throw new Error(
"Missing the required parameter 'opts.resourceRecordId' when calling modifyResourceRecordStatus"
)
}
if (opts.action === undefined || opts.action === null) {
throw new Error(
"Missing the required parameter 'opts.action' when calling modifyResourceRecordStatus"
)
}
let postBody = {}
if (opts.action !== undefined && opts.action !== null) {
postBody['action'] = opts.action
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId,
resourceRecordId: opts.resourceRecordId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call modifyResourceRecordStatus with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/ResourceRecord/{resourceRecordId}/status',
'PUT',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查询云解析所有的基础解析线路。
在使用解析线路的参数之前,请调用此接口获取解析线路的ID。
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {integer} [opts.loadMode] - 展示方式,暂时不使用 optional
* @param {integer} opts.packId - 套餐ID,0->免费版 1->企业版 2->企业高级版
* @param {integer} opts.viewId - view ID,默认为-1
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param viewTree data
*/
describeViewTree (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeViewTree"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeViewTree"
)
}
if (opts.packId === undefined || opts.packId === null) {
throw new Error(
"Missing the required parameter 'opts.packId' when calling describeViewTree"
)
}
if (opts.viewId === undefined || opts.viewId === null) {
throw new Error(
"Missing the required parameter 'opts.viewId' when calling describeViewTree"
)
}
let postBody = null
let queryParams = {}
if (opts.loadMode !== undefined && opts.loadMode !== null) {
queryParams['loadMode'] = opts.loadMode
}
if (opts.packId !== undefined && opts.packId !== null) {
queryParams['packId'] = opts.packId
}
if (opts.viewId !== undefined && opts.viewId !== null) {
queryParams['viewId'] = opts.viewId
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeViewTree with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/viewTree',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 同一个主域名下,批量新增或者批量更新导入解析记录。
如果解析记录的ID为0,是新增解析记录,如果不为0,则是更新解析记录。
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {array} [opts.req] - 需要设置的解析记录列表 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param string data
*/
batchSetResourceRecords (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling batchSetResourceRecords"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling batchSetResourceRecords"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call batchSetResourceRecords with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/BatchSetResourceRecords',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查询主域名的自定义解析线路
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {integer} opts.viewId - 自定义线路ID
* @param {string} [opts.viewName] - 自定义线路名称, 最多64个字节,允许:数字、字母、下划线,-,中文 optional
* @param {integer} opts.pageNumber - 分页参数,页的序号
* @param {integer} opts.pageSize - 分页参数,每页含有的结果的数目
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param userViewInput dataList
* @param integer currentCount 当前页的自定义线路列表里的个数
* @param integer totalCount 所有自定义线路列表的个数
* @param integer totalPage 所有自定义线路列表按照分页参数一共的页数
*/
describeUserView (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeUserView"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeUserView"
)
}
if (opts.viewId === undefined || opts.viewId === null) {
throw new Error(
"Missing the required parameter 'opts.viewId' when calling describeUserView"
)
}
if (opts.pageNumber === undefined || opts.pageNumber === null) {
throw new Error(
"Missing the required parameter 'opts.pageNumber' when calling describeUserView"
)
}
if (opts.pageSize === undefined || opts.pageSize === null) {
throw new Error(
"Missing the required parameter 'opts.pageSize' when calling describeUserView"
)
}
let postBody = null
let queryParams = {}
if (opts.viewId !== undefined && opts.viewId !== null) {
queryParams['viewId'] = opts.viewId
}
if (opts.viewName !== undefined && opts.viewName !== null) {
queryParams['viewName'] = opts.viewName
}
if (opts.pageNumber !== undefined && opts.pageNumber !== null) {
queryParams['pageNumber'] = opts.pageNumber
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeUserView with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/UserView',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 添加主域名的自定义解析线路
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {addView} opts.req - 添加自定义线路的参数
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param userview data 添加成功后返回的自定义线路的结构
*/
createUserView (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling createUserView"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling createUserView"
)
}
if (opts.req === undefined || opts.req === null) {
throw new Error(
"Missing the required parameter 'opts.req' when calling createUserView"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call createUserView with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/UserView',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 删除主域名的自定义解析线路
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {delView} opts.req - 删除自定义线路的参数
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
deleteUserView (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling deleteUserView"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling deleteUserView"
)
}
if (opts.req === undefined || opts.req === null) {
throw new Error(
"Missing the required parameter 'opts.req' when calling deleteUserView"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call deleteUserView with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/DeleteUserView',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查询主域名的自定义解析线路的IP段
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {integer} opts.viewId - 自定义线路ID
* @param {string} [opts.viewName] - 自定义线路名称, 最多64个字节,允许:数字、字母、下划线,-,中文 optional
* @param {integer} opts.pageNumber - 分页参数,页的序号, 默认为1
* @param {integer} opts.pageSize - 分页参数,每页含有的结果的数目,默认为10
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param string dataList
* @param integer currentCount 当前页的IP列表里的个数
* @param integer totalCount IP列表里的IP段的个数
* @param integer totalPage IP列表按照分页参数一共的页数
*/
describeUserViewIP (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeUserViewIP"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeUserViewIP"
)
}
if (opts.viewId === undefined || opts.viewId === null) {
throw new Error(
"Missing the required parameter 'opts.viewId' when calling describeUserViewIP"
)
}
if (opts.pageNumber === undefined || opts.pageNumber === null) {
throw new Error(
"Missing the required parameter 'opts.pageNumber' when calling describeUserViewIP"
)
}
if (opts.pageSize === undefined || opts.pageSize === null) {
throw new Error(
"Missing the required parameter 'opts.pageSize' when calling describeUserViewIP"
)
}
let postBody = null
let queryParams = {}
if (opts.viewId !== undefined && opts.viewId !== null) {
queryParams['viewId'] = opts.viewId
}
if (opts.viewName !== undefined && opts.viewName !== null) {
queryParams['viewName'] = opts.viewName
}
if (opts.pageNumber !== undefined && opts.pageNumber !== null) {
queryParams['pageNumber'] = opts.pageNumber
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeUserViewIP with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/UserViewIP',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 添加主域名的自定义解析线路的IP段
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {addViewIP} opts.req - 添加域名的自定义解析线路的IP段的参数
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
createUserViewIP (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling createUserViewIP"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling createUserViewIP"
)
}
if (opts.req === undefined || opts.req === null) {
throw new Error(
"Missing the required parameter 'opts.req' when calling createUserViewIP"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call createUserViewIP with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/UserViewIP',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 删除主域名的自定义解析线路的IP段
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {delViewIP} opts.req - 删除域名的自定义解析线路的IP段的参数
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
deleteUserViewIP (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling deleteUserViewIP"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling deleteUserViewIP"
)
}
if (opts.req === undefined || opts.req === null) {
throw new Error(
"Missing the required parameter 'opts.req' when calling deleteUserViewIP"
)
}
let postBody = {}
if (opts.req !== undefined && opts.req !== null) {
postBody['req'] = opts.req
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call deleteUserViewIP with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/DeleteUserViewIP',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查看主域名的监控项的配置以及状态
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {integer} [opts.pageIndex] - 当前页数,起始值为1,默认为1 optional
* @param {integer} [opts.pageSize] - 分页查询时设置的每页行数 optional
* @param {string} [opts.searchValue] - 查询的值 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param integer currentCount 当前页面网站监控项的个数
* @param integer totalCount 所有网站监控项的个数
* @param integer totalPage 所有网站监控项的页数
* @param monitor dataList
*/
describeMonitor (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeMonitor"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeMonitor"
)
}
let postBody = null
let queryParams = {}
if (opts.pageIndex !== undefined && opts.pageIndex !== null) {
queryParams['pageIndex'] = opts.pageIndex
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
if (opts.searchValue !== undefined && opts.searchValue !== null) {
queryParams['searchValue'] = opts.searchValue
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeMonitor with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitor',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 添加子域名的监控项,默认把子域名的所有监控项都添加上监控
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.subDomainName - 子域名
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
createMonitor (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling createMonitor"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling createMonitor"
)
}
if (opts.subDomainName === undefined || opts.subDomainName === null) {
throw new Error(
"Missing the required parameter 'opts.subDomainName' when calling createMonitor"
)
}
let postBody = {}
if (opts.subDomainName !== undefined && opts.subDomainName !== null) {
postBody['subDomainName'] = opts.subDomainName
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call createMonitor with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitor',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 域名的监控项修改
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {updateMonitor} opts.updateMonitor - 监控项设置信息
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
modifyMonitor (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling modifyMonitor"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling modifyMonitor"
)
}
if (opts.updateMonitor === undefined || opts.updateMonitor === null) {
throw new Error(
"Missing the required parameter 'opts.updateMonitor' when calling modifyMonitor"
)
}
let postBody = {}
if (opts.updateMonitor !== undefined && opts.updateMonitor !== null) {
postBody['updateMonitor'] = opts.updateMonitor
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call modifyMonitor with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitor',
'PUT',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 查询子域名的可用监控对象
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.subDomainName - 子域名
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param string data
*/
describeMonitorTarget (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeMonitorTarget"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeMonitorTarget"
)
}
if (opts.subDomainName === undefined || opts.subDomainName === null) {
throw new Error(
"Missing the required parameter 'opts.subDomainName' when calling describeMonitorTarget"
)
}
let postBody = null
let queryParams = {}
if (opts.subDomainName !== undefined && opts.subDomainName !== null) {
queryParams['subDomainName'] = opts.subDomainName
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeMonitorTarget with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitorTarget',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 添加子域名的某些特定监控对象为监控项
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.subDomainName - 子域名
* @param {array} [opts.targets] - 子域名可用监控对象的数组 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
createMonitorTarget (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling createMonitorTarget"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling createMonitorTarget"
)
}
if (opts.subDomainName === undefined || opts.subDomainName === null) {
throw new Error(
"Missing the required parameter 'opts.subDomainName' when calling createMonitorTarget"
)
}
let postBody = {}
if (opts.subDomainName !== undefined && opts.subDomainName !== null) {
postBody['subDomainName'] = opts.subDomainName
}
if (opts.targets !== undefined && opts.targets !== null) {
postBody['targets'] = opts.targets
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call createMonitorTarget with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitorTarget',
'POST',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 监控项的操作集合,包括:暂停,启动, 手动恢复, 手动切换
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.monitorId - 监控项ID,请使用describeMonitor接口获取。
* @param {string} opts.action - 暂停stop, 开启start, 手动恢复recover,手动切换switch,手动恢复和手动切换时候不支持批量操作
* @param {string} [opts.switchTarget] - 监控项的主机值, 手动切换时必填 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
modifyMonitorStatus (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling modifyMonitorStatus"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling modifyMonitorStatus"
)
}
if (opts.monitorId === undefined || opts.monitorId === null) {
throw new Error(
"Missing the required parameter 'opts.monitorId' when calling modifyMonitorStatus"
)
}
if (opts.action === undefined || opts.action === null) {
throw new Error(
"Missing the required parameter 'opts.action' when calling modifyMonitorStatus"
)
}
let postBody = {}
if (opts.action !== undefined && opts.action !== null) {
postBody['action'] = opts.action
}
if (opts.switchTarget !== undefined && opts.switchTarget !== null) {
postBody['switchTarget'] = opts.switchTarget
}
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId,
monitorId: opts.monitorId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call modifyMonitorStatus with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitor/{monitorId}/status',
'PUT',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 监控项的删除
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {string} opts.monitorId - 监控项ID,请使用describeMonitor接口获取。
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
*/
deleteMonitor (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling deleteMonitor"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling deleteMonitor"
)
}
if (opts.monitorId === undefined || opts.monitorId === null) {
throw new Error(
"Missing the required parameter 'opts.monitorId' when calling deleteMonitor"
)
}
let postBody = null
let queryParams = {}
let pathParams = {
regionId: regionId,
domainId: opts.domainId,
monitorId: opts.monitorId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call deleteMonitor with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitor/{monitorId}',
'DELETE',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
/**
* 主域名的监控项的报警信息
* @param {Object} opts - parameters
* @param {string} opts.domainId - 域名ID,请使用describeDomains接口获取。
* @param {integer} [opts.pageIndex] - 当前页数,起始值为1,默认为1 optional
* @param {integer} [opts.pageSize] - 分页查询时设置的每页行数 optional
* @param {string} [opts.searchValue] - 关键字 optional
* @param {string} regionId - ID of the region
* @param {string} callback - callback
@return {Object} result
* @param integer currentCount 当前页面报警信息的个数
* @param integer totalCount 所有报警信息的个数
* @param integer totalPage 所有报警信息的页数
* @param monitorAlarmInfo dataList
*/
describeMonitorAlarm (opts, regionId = this.config.regionId, callback) {
if (typeof regionId === 'function') {
callback = regionId
regionId = this.config.regionId
}
if (regionId === undefined || regionId === null) {
throw new Error(
"Missing the required parameter 'regionId' when calling describeMonitorAlarm"
)
}
opts = opts || {}
if (opts.domainId === undefined || opts.domainId === null) {
throw new Error(
"Missing the required parameter 'opts.domainId' when calling describeMonitorAlarm"
)
}
let postBody = null
let queryParams = {}
if (opts.pageIndex !== undefined && opts.pageIndex !== null) {
queryParams['pageIndex'] = opts.pageIndex
}
if (opts.pageSize !== undefined && opts.pageSize !== null) {
queryParams['pageSize'] = opts.pageSize
}
if (opts.searchValue !== undefined && opts.searchValue !== null) {
queryParams['searchValue'] = opts.searchValue
}
let pathParams = {
regionId: regionId,
domainId: opts.domainId
}
let headerParams = {
'User-Agent': 'JdcloudSdkNode/1.0.0 domainservice/2.0.3'
}
let contentTypes = ['application/json']
let accepts = ['application/json']
// 扩展自定义头
if (opts['x-extra-header']) {
for (let extraHeader in opts['x-extra-header']) {
headerParams[extraHeader] = opts['x-extra-header'][extraHeader]
}
if (Array.isArray(opts['x-extra-header']['content-type'])) {
contentTypes = opts['x-extra-header']['content-type']
} else if (typeof opts['x-extra-header']['content-type'] === 'string') {
contentTypes = opts['x-extra-header']['content-type'].split(',')
}
if (Array.isArray(opts['x-extra-header']['accept'])) {
accepts = opts['x-extra-header']['accept']
} else if (typeof opts['x-extra-header']['accept'] === 'string') {
accepts = opts['x-extra-header']['accept'].split(',')
}
}
let formParams = {}
let returnType = null
this.config.logger(
`call describeMonitorAlarm with params:\npathParams:${JSON.stringify(
pathParams
)},\nqueryParams:${JSON.stringify(
queryParams
)}, \nheaderParams:${JSON.stringify(
headerParams
)}, \nformParams:${JSON.stringify(
formParams
)}, \npostBody:${JSON.stringify(postBody)}`,
'DEBUG'
)
let request = this.makeRequest(
'/regions/{regionId}/domain/{domainId}/monitorAlarm',
'GET',
pathParams,
queryParams,
headerParams,
formParams,
postBody,
contentTypes,
accepts,
returnType,
callback
)
return request.then(
function (result) {
if (callback && typeof callback === 'function') {
return callback(null, result)
}
return result
},
function (error) {
if (callback && typeof callback === 'function') {
return callback(error)
}
return Promise.reject(error)
}
)
}
}
module.exports = JDCloud.DOMAINSERVICE
|
AbelRapha/Python-Exercicios-CeV
|
Mundo 2/ex065 Maior ou Menor valor.py
|
<gh_stars>0
decisao = ''
lista_numeros = []
while(decisao != "N"):
num = input("Digite um numero ")
decisao = input("Quer continuar? [S/N] ").strip().upper()
lista_numeros.append(num)
if decisao not in "N":
continue
else:
break
#convertendo lista de numeros para todos os elementos do tipo inteiro
for item in range(0, len(lista_numeros)):
lista_numeros[item] = int(lista_numeros[item])
print(f"Voce digitou {len(lista_numeros)} numeros e a media foi de {sum(lista_numeros)/len(lista_numeros)} \n O maior valor foi {max(lista_numeros):.1f} e o menor valor foi o {min(lista_numeros)}")
|
AndreiKononov/ui-orders
|
src/settings/OrderTemplates/OrderTemplatesEditor/POLineVendorForm/POLineVendorForm.js
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Row,
Col,
} from '@folio/stripes/components';
import {
FieldRefNumberType,
FieldVendorRefNumber,
FieldVendorInstructions,
FieldVendorAccountNumber,
} from '../../../../common/POLFields';
const POLineVendorForm = ({ accounts }) => {
return (
<Row>
<Col
xs={3}
data-col-order-template-vendor-number
>
<FieldVendorRefNumber required={false} />
</Col>
<Col
xs={3}
data-col-order-template-vendor-ref-type
>
<FieldRefNumberType required={false} />
</Col>
<Col
xs={3}
data-col-order-template-vendor-account
>
<FieldVendorAccountNumber accounts={accounts} />
</Col>
<Col
xs={3}
data-col-order-template-vendor-instruction
>
<FieldVendorInstructions />
</Col>
</Row>
);
};
POLineVendorForm.propTypes = {
accounts: PropTypes.arrayOf(PropTypes.object),
};
POLineVendorForm.defaultProps = {
accounts: [],
};
export default POLineVendorForm;
|
Rishabh570/flipit
|
src/config/vars.js
|
'use-strict';
// import .env variables
require('dotenv-safe').config();
const { env } = process; // this has ".env" keys & values
const MULTER_UPLOAD_DEST = `${__dirname}/../../uploads`;
module.exports = {
env: env.NODE_ENV,
BASE_URL: env.BASE_URL,
port: env.PORT,
JWT_SECRET: env.JWT_SECRET,
JWT_EXPIRATION_MINUTES: env.JWT_EXPIRATION_MINUTES,
RESET_TOKEN_EXPIRATION_MINUTES: env.RESET_TOKEN_EXPIRATION_MINUTES,
GOOGLE_CLIENT_ID: env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: env.GOOGLE_CLIENT_SECRET,
FACEBOOK_APP_ID: env.FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET: env.FACEBOOK_APP_SECRET,
COOKIE_TTL: env.COOKIE_TTL,
COOKIE_SECRET: env.COOKIE_SECRET,
SENDGRID_USERNAME: env.SENDGRID_USERNAME,
SENDGRID_API_KEY: env.SENDGRID_API_KEY,
EMAIL_TEMPLATE_BASE: env.EMAIL_TEMPLATE_BASE,
EMAIL_FROM_SUPPORT: env.EMAIL_FROM_SUPPORT,
MULTER_UPLOAD_DEST: MULTER_UPLOAD_DEST,
UPLOAD_LIMIT: 5, // MB
mongo: {
uri: env.NODE_ENV === 'test' ? env.MONGO_URI_TESTS : env.MONGO_URI,
},
logs: env.NODE_ENV === 'production' ? 'combined' : 'dev',
STRIPE_SECRET_KEY: env.STRIPE_SECRET_KEY,
STRIPE_PUBLISHABLE_KEY: env.STRIPE_PUBLISHABLE_KEY,
STRIPE_WEBHOOK_SECRET: env.STRIPE_WEBHOOK_SECRET,
MAX_PRODUCT_IMAGES_ALLOWED: env.MAX_PRODUCT_IMAGES_ALLOWED,
MULTER_UPLOAD_MAX_FILE_SIZE_ALLOWED:
env.MULTER_UPLOAD_MAX_FILE_SIZE_ALLOWED,
SENTRY_DSN: env.SENTRY_DSN,
AWS_ACCESS_KEY_ID: env.AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY: env.AWS_SECRET_ACCESS_KEY,
AWS_BUCKET_NAME: env.AWS_BUCKET_NAME,
CLOUDFRONT_URL: env.CLOUDFRONT_URL,
REDIS_URL: env.REDIS_URL,
};
|
comprakt/comprakt-fuzz-tests
|
output/d9613aeb6b154d23a05ec3bdf99e1e72.java
|
<filename>output/d9613aeb6b154d23a05ec3bdf99e1e72.java
class iP9 {
}
class pucvtwOVgxM {
public static void POTPd6yTw_nJdK (String[] rTqtEuf) {
;
int[][] RpFaD = false.EoeeSB();
;
;
boolean[] _xcT3nMh_uDKT;
--new yw7n().M7();
int[][][] NOVU18Evf = false.tQaTzbrYJS;
void[][] ej7xOshS0j;
void[] fayuJOF4wy4 = -!!null.t3tGe20c3YWb49;
}
}
class GXtkRlBh6 {
public static void cDNHTEDoRe (String[] ZGG26_R3ivbj) {
boolean eWk4NbXgXcJlov = this[ eEvHr()[ !!( false[ IY_R4zu()[ !----false[ !this.neBbEutz4m59()]]]).Eay()]];
if ( !this.FRfA5qV3QvPIXF) {
;
}else while ( 536390[ M7KYn55ahIwIkl.HXiMxDztiaszII]) if ( -false.jSwT1w0x2vHI()) {
boolean[] ZDa_MO;
}
RzH7z N85 = -true[ !--!new boolean[ ( !!new Hq_Qi9[ 7383[ -this.ix1xMfa0qW9]].Y()).ySjcCKT][ --Gn528.GFr1D203kJQp()]] = new boolean[ -10759[ new vXuptJ7oaJd()[ ( kAyG1UJY2iRhn[ rUMUTE4M0X().qzRT308zhwTuq]).vpjuLdiWwi()]]].IW;
if ( false.dGON()) while ( new Q6LPg5XA().n()) return;else return;
}
public static void pAlz7 (String[] mXGbL8gCE) {
if ( 811.sQUXTLj5BW4Be) ;
int T = ( ---NPmotNA6KRdLC().kwk()).B4tvJ4pCWAKA();
--!!false.F1NdcU8mn;
int zzBux_m = ( true.uCGLRmqtO7).Pdgi0g;
return;
{
boolean[][][] v;
if ( -585410.IVoKg0QYAnM) {
;
}
boolean[][] SUe1H0zA5Uuw;
void ooTdlchQATkcyh;
while ( qj9()[ this.G6wyV6]) if ( ( -false.MmrJG()).gTd()) if ( !!-!-new int[ !03212862.T()].FZMu9GMg()) ;
boolean[][][][] x;
;
int[] JmwpmgWbnSy8;
{
VTgy7dm_L RRb;
}
;
i4_bhUCYry8 nmx7hS;
void[] ty;
Kcyx[][] pKK;
{
return;
}
!60055.Mxu20z;
while ( infnP1QdWt.Xq()) ;
lCYMl[ hjFruKQjm0KvE().EhsY2EgrB4k];
;
}
int[] XqA2ZA5 = true.TxpTN2N_() = !-false.nIiZxoj9;
return;
Y8U5KaDTJMmwSo O7MqCaTYJSJJm = true.CY1qn();
}
public ZuvoLhzjRCj esLnwd6q () throws sk6Jg75n {
keZsgYw5_B_2[][] ulshHgqQ4;
return;
boolean f51Qsu;
void[] wosI;
TgFGY6A[][] M4A = !M6zn_2d().zqUU();
while ( !!new orr3UiC()[ 25322677.BDX20C5U8]) if ( null.IVO0fE()) return;
int[][] JymY1iimtEv = !!new kwt[ ( -( pd2E4T0HDSA7().zs7jN9__()).X).uN6DlfRL1HJg5][ !IDRtaEb.AOnJPPU()];
( this.lrA0)[ -!false.DzziHd];
return !!!-this.O;
;
}
public static void nT_PKOSyHpze (String[] h4ZLWZVuSzbF1) throws Jqze3T2lM3R {
{
while ( !new IH()[ this[ -true.IHys()]]) while ( -sNX().NSH6Hq) false.Iiif();
boolean[] ZlHCEp;
if ( -!true[ this.fW90]) {
{
;
}
}
}
int gbIy8hrrHKHE = ( new Z().D131L)[ !new AKF[ ( true[ --!new xUSZuPQ()[ --new boolean[ 27.W2oQNRii()].D2aHQGYwh72()]]).b3Jqy162g()].mMSVDRTPf8MKCw()];
void NX1_owcNwah = -true[ true.fiM()] = !( !---!!new void[ -!VXDs_jT.g99kF6].IzXydi6_gp()).v9Z;
!!false.dQYM_HUab;
if ( --new HjFqrF4f()[ !!( 689885[ true[ new int[ -!IZ2BWJp025soW.vT5].zXQUhTBO1A]]).T2rZbP]) return;else ;
}
}
class JlmJYeQBiQ {
public void[][][][] N9Ug1GdTHyjaj;
}
class Ozpwb6YvQ {
}
class dTNhJm {
}
class hIw55cm830 {
}
class t {
public static void mo6gHM8L (String[] dYmDf8) throws pzJS3QtT3WQox {
BPBkg47Yxxk9wS[] s;
return;
while ( E9VpG7esjEEG2h.VBe5vTPjZmBk()) while ( -false.V) if ( null[ Ul44Uu51q().v]) return;
int[] SgXV;
void[] ldkJy8q = o().gbss0ME() = false.mm2kYXk();
int J6BPkPGA2s1dbX;
int JBc0IRVNCKtOA;
-( -( !!true[ new boolean[ -!-JweBhRXC[ !!3[ true.UPhVF82]]][ !iLvQ4hR().D7]])._2EskzW16GKcv).ZWPGTsH1DT();
if ( ( --true.leeQ()).cv) return;else {
int VmZyT9xOQgvO;
}
boolean dE8JMGWzghZZ;
}
public boolean[][] hs0 () throws QgJiwM {
;
!!!!-WrUcf0LxFvRx().dAIe0rQAxHPpZ_;
zyw skdeNB0_EsKeoY;
boolean[][] FJeqKs2o5M2Hd8;
int HUqFa1cudxM2 = !vSA7.EsfhtIXX2eySJU();
boolean[] NXzA4cUcxKhvfI = --true.sD3Ss28X0bhJj();
}
public boolean[][][][][] qVFi;
public static void doa (String[] BRn6m) {
int leWlXXbDAcNTmU = !new W2r91R()[ ( !05632[ !-PY().XmNiEzS]).YNigdxb8iN];
int qe;
return !!false.TZyxuM1Ep();
!new int[ ZqlW[ VpJ().gzM7Mw()]].Zh4k0N3g7;
if ( -null.Kxo8hQj()) if ( !!!-true[ !-o6w_uLPg[ !!!--( -kmdbOV().dyHhDdDRQvYGTQ())[ new void[ !null.gJCeMAp4TZP()][ _lvgGPQe6().ZILSTQIIVV()]]]]) ;
PqG2().I_emz8WkjmDn;
void[] PmlsCDEn6 = 99151.VcDpCE;
yYlM9tJkH y = !!!this.OB0GLvmSaBHI;
while ( -!!P4().r31) return;
return;
_5Dp_MF CDMspnX_ZJ = null.CTj8aBRVfPG() = !null[ 575748390.FTzf4()];
}
public int[] ducmMmOt () {
int DQmhbtXXuQ;
}
public NJNMjQQzzm58Qy[] AFp4 (boolean P3, espa[][] lDfj8iCimj4Y2G) {
boolean wyakHITRUt3PVP = -( new int[ jNMpkH.BCMU][ !new pU[ -false[ -( true[ ------false.d9fH4c()]).NMWxvzcG0Rs]].rgUOaF()]).pjVeQpon = -!false.Ec;
return ( cMWNCkEQJeSi.nAIFlzbd()).P9w1hln;
;
void[][][] SKPLPehH = -!this.PzzbB7() = true.MYQAQ1K;
{
int[][] STtqjDPyFp3A_Y;
return;
}
;
if ( -oE5DX7vfSDi()._1luz()) {
if ( dU9C75AWm().m0OCqJo3nOJoR) C[ b0lOSt().cnqmFWjPCYeFZ()];
}else while ( !268658.A()) ;
int[][][][][][][] FX2r;
void F1HdnT;
void Ucoc = -!!new int[ !!--( -ubv80Pw41Rt.kYSx())[ -( !true.TV)[ null[ this[ -!new By0Ds8[ -new OF().DtlT][ new Gu2C8CdLv().zpWp()]]]]]].o67L66Spg5bZBz;
{
boolean BSj7k6dkOZCAZt;
{
TAhjm[][][] SKpe;
}
kPG hN4ngN;
}
;
boolean N3u = --xhI.e1BCeqhZ5QB() = -true.mwTIEaQC_4fO;
while ( -true[ new ZccNVVr9RU().F]) !SDPvgo().lm;
return null.KjUsPr();
K[][][][] oOGnN_;
if ( -E7xkYmWkl()[ -new W9NACtmXD0().udnEz]) {
while ( hjwG7LZUh6().PuQhETtdug7RVi()) {
return;
}
}else ;
;
KQNa9EPIJ2j sP = ---!!!!--343446.IWWzZ7po0();
}
public O1Y[][][][][][] eiIieRJL3_tj1 (void wt9gTdK37wCT, boolean i4I, V9v q1qT9, boolean[] XbM7W, boolean i, int jamULLW5tRKI, Gq82Cj8ivs[][][] j) throws h {
fqaF[] UFyedJ;
Q mg;
int SAj_TYkT = 20599002.WntWewU3() = !!!null.mx;
return null.ijaHoCo2g6Vo();
boolean KmlbDX4zuF;
int WBY = myc7e1OVvY[ -true.RdCxKE_SJg()] = this._B();
-true.jxvt0GsnMivoq;
int kBQ73ONRCx = --OzliabTumW.qJhCfe9OE = false.Yqa_jDbga();
while ( new fVAt()[ !--670252025[ -TkSGRQPOo9.CeoatNhq1Ssa()]]) return;
!-new boolean[ ( !--false.is9L51).s17phfMacm()].Tl1fh5();
void[] RJaQgIvfaM = 6.__qOPd0uB29W0p();
return;
}
public static void JS6QRSY7Iy9i (String[] XTu9k) {
return !!-!-null.YW();
false.lHnfM6I();
;
while ( rU5H6WGNoOkhq().uJ2zc40) while ( !null.qV()) ;
int[][][][] DmOWujVW6FH = !5541409.Mr6AnVlqME = this[ -!true.CllMbu()];
;
void x7oDXgWQKyhtpC = vc1KI8r4j.hOrGfNJPFd = -!---!( !hHAELS().h1fCagz9bep())[ !-86661.XQGy6UTr4()];
}
public boolean[][][] Okra3ZkDyJi4E (void t4ID7YvlG, AjE5CbkG4WsQp VGy899qqQRQhz) {
void dvAVe = 86799013[ -!!this[ true.LcY()]] = !CU26R9w6M.y();
z zAO4;
{
if ( -!tOG5yPHoN5MWGl.JwxP4UzgY65()) {
;
}
void[][] old5Ov0wuZeAIz;
while ( !-!!!!!-!new A[ -new boolean[ --new void[ -SLiooc4sNgdm3y.y()][ wHr3o[ !97267.Zr9dN4UV5oMg]]].wGWZ][ !new SZ9vTAm_c5().Ouo3SqREs3H9O]) ;
boolean[][][] mw6;
void Edd8;
oS8Cu hK;
void[][][] QXYUW2;
void ju2iU2lRu;
{
return;
}
while ( new mmDM6[ true[ !null.FOe5shik0d4n]][ !aA().xCSKZXY3()]) return;
void K;
FGAredk[][] xIUXEC;
yJLdDpId[] uwdVcbXJCc;
boolean up1xCC;
}
bYWFc HuMBmCoQc = -64.kPlgf5YN5oP9X();
if ( qvhM.d) {
while ( --this.a0iLdnE75sp3gV) return;
}
}
public K36Z2DvSb9CHrh[] X8ZGQEj;
}
class RsdiYt_WYdof {
}
|
mariapesm/myyna
|
public/default/js/plugins.js
|
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function() {
};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Place any jQuery/helper plugins in here.
$(document).ready(function()
{
var ml, mr, mrb, mlb, mlp, mrp;
$(".close").css("display", "none");
var isMenuOpen = false;
$('.menu_btn').click(function()
{
if (isMenuOpen == false)
{
if ($.browser.mozilla && (!ml || !mr)) {
if ($('#container').length > 0)
{
mr = ml = $("#container").position().left;
}
if ($('.leftmenu_adjst').length > 0)
{
mrb = mlb = $(".leftmenu_adjst").position().left;
}
if ($('#pop_container').length > 0)
{
mrp = mlp = $("#pop_container").position().left;
}
} else {
ml = $("#container").css('margin-left');
mr = $("#container").css('margin-right');
if ($('.leftmenu_adjst').length > 0)
{
mlb = $(".leftmenu_adjst").css('margin-left');
mrb = $(".leftmenu_adjst").css('margin-right');
}
if ($('#pop_container').length > 0)
{
mlp = $("#pop_container").css('margin-left');
mrp = $("#pop_container").css('margin-right');
}
}
//alert('je suis dans le bon cas')
$("#menu").clearQueue().animate({
left: '0'
})
$("#container").clearQueue().animate({
"margin-left": '290px',
"margin-right": '-290px'
})
if ($('.leftmenu_adjst').length > 0)
{
$(".leftmenu_adjst").clearQueue().animate({
"margin-left": '290px',
"margin-right": '-290px'
})
}
if ($('#pop_container').length > 0)
{
$("#pop_container").clearQueue().animate({
"margin-left": '290px',
"margin-right": '-290px'
})
}
$(this).fadeOut(200);
$(".close").fadeIn(300);
isMenuOpen = true;
}
});
$('.close').click(function()
{
if (isMenuOpen == true)
{
$("#menu").clearQueue().animate({
left: '-240px'
})
$("#container").clearQueue().animate({
"margin-right": mr,
"margin-left": ml
})
$(".leftmenu_adjst").clearQueue().animate({
"margin-right": mrb,
"margin-left": mlb
})
$("#pop_container").clearQueue().animate({
"margin-right": mrp,
"margin-left": mlp
})
$(this).fadeOut(200);
$(".menu_btn").fadeIn(300);
setTimeout(function() {
$("#container").css({"margin": "0 auto"});
$(".leftmenu_adjst").css({"margin": "0 1%"});
$("#pop_container").css({"margin": "0 1%"});
ml = mr = false;
}, 500);
isMenuOpen = false;
}
});
});
$(document).ready(function()
{
$(".close").css("display", "none");
var isMenuOpen = false;
$('.menu_btn').click(function()
{
if (isMenuOpen == false)
{
//alert('je suis dans le bon cas')
$("#menu").clearQueue().animate({
left: '0'
})
$(".leftmenu_adjst").clearQueue().animate({
"margin-left": '290px',
"margin-right": '-290px'
})
$("#pop_container").clearQueue().animate({
"margin-left": '290px',
"margin-right": '-290px'
})
$(this).fadeOut(200);
$(".close").fadeIn(300);
isMenuOpen = true;
}
});
$('.close').click(function()
{
if (isMenuOpen == true)
{
$("#menu").clearQueue().animate({
left: '-240px'
})
$(".row_min").clearQueue().animate({
"margin-left": '0%',
"margin-right": '0%'
})
$(this).fadeOut(200);
$(".menu_btn").fadeIn(300);
isMenuOpen = false;
}
});
});
$(document).ready(function()
{
$(".close").css("display", "none");
var isMenuOpen = false;
$('.menu_btn').click(function()
{
if (isMenuOpen == false)
{
//alert('je suis dans le bon cas')
$("#menu").clearQueue().animate({
left: '0'
})
$(".row_min").clearQueue().animate({
"margin-left": '240px',
"margin-right": '-290px'
})
$(this).fadeOut(200);
$(".close").fadeIn(300);
isMenuOpen = true;
}
});
$('.close').click(function()
{
if (isMenuOpen == true)
{
$("#menu").clearQueue().animate({
left: '-240px'
})
$(".leftmenu_adjst").clearQueue().animate({
"margin-left": '0%',
"margin-right": '0%'
})
$("#pop_container").clearQueue().animate({
"margin-left": '0%',
"margin-right": '0%'
})
$(this).fadeOut(200);
$(".menu_btn").fadeIn(300);
isMenuOpen = false;
}
});
});
//---------------------------//
//**** mplayer start ****//
//---------------------------//
var mySound;
/*
soundManager.setup({
// location: path to SWF files, as needed (SWF file name is appended later.)
url: 'js/soundmanager/swf/',
onready: function() {
// SM2 has started - now you can create and play sounds!
mySound = soundManager.createSound({
id: 'aSound'
});
},
onfinish: function () {
alert("Finished");
},
ontimeout: function() {
// Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
// See the flashblock demo when you want to start getting fancy.
}
});
*/
function play() {
soundManager.play('mySound', {
url: 'placeholders/mp3/adg3com_coreissues.mp3',
onPlay: function() {
alert('The sound ' + this.id + ' finished playing.');
},
onfinish: function() {
alert('The sound ' + this.id + ' finished playing.');
}
});
}
//---------------------------//
//**** mplayer end ****//
//---------------------------//
|
viyadb/viyadb
|
src/cluster/query/load_runner.cc
|
/*
* Copyright (c) 2017-present ViyaDB Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cluster/query/load_runner.h"
#include "cluster/controller.h"
#include "cluster/query/client.h"
#include "cluster/query/query.h"
#include "cluster/query/worker_state.h"
#include "query/query.h"
#include "util/config.h"
#include "util/scope_guard.h"
#include <unordered_set>
namespace viya {
namespace cluster {
namespace query {
LoadQueryRunner::LoadQueryRunner(Controller &controller,
WorkersStates &workers_states,
query::RowOutput &output)
: controller_(controller), workers_states_(workers_states),
output_(output) {}
void LoadQueryRunner::Run(const LoadQuery *load_query) {
auto &load_desc = load_query->query();
WorkersClient http_client(workers_states_,
[](const char *buf __attribute__((unused)),
size_t buf_size __attribute__((unused))) {});
std::unordered_set<std::string> controller_ids;
auto &table_plan = controller_.tables_plans().at(load_desc.str("table"));
for (auto &parts_it : table_plan.workers_partitions()) {
auto worker_id = parts_it.first;
auto controller_id =
worker_id.substr(0, worker_id.find(":")) + ":" +
std::to_string(controller_.cluster_config().num("http_port"));
controller_ids.emplace(controller_id);
}
auto data = load_desc.dump();
for (const auto &controller_id : controller_ids) {
http_client.Send(std::vector<std::string>{controller_id}, "/load", data);
}
http_client.Await();
output_.Start();
output_.Flush();
}
} // namespace query
} // namespace cluster
} // namespace viya
|
Kirk-Wang/Hello-Go
|
__before/history/17.4/crawler/scheduler/simple.go
|
package scheduler
import (
"github.com/Kirk-Wang/Hello-Gopher/history/17.4/crawler/engine"
)
type SimpleScheduler struct {
workerChan chan engine.Request
}
func (s *SimpleScheduler) WorkerReady(w chan engine.Request) {}
func (s *SimpleScheduler) WorkerChan() chan engine.Request {
return s.workerChan
}
func (s *SimpleScheduler) Submit(r engine.Request) {
go func() { s.workerChan <- r }()
}
func (s *SimpleScheduler) Run() {
s.workerChan = make(chan engine.Request)
}
|
cuiyuemin365/books
|
HowTomcatWorks/HowTomcatWorks/tomcat/4/4.1.12/jakarta-tomcat-connectors-4.1.12-src/jk/native2/include/jk_uriMap.h
|
/* ========================================================================= *
* *
* The Apache Software License, Version 1.1 *
* *
* Copyright (c) 1999-2001 The Apache Software Foundation. *
* All rights reserved. *
* *
* ========================================================================= *
* *
* Redistribution and use in source and binary forms, with or without modi- *
* fication, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice *
* 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 end-user documentation included with the redistribution, if any, *
* must include the following acknowlegement: *
* *
* "This product includes software developed by the Apache Software *
* Foundation <http://www.apache.org/>." *
* *
* Alternately, this acknowlegement may appear in the software itself, if *
* and wherever such third-party acknowlegements normally appear. *
* *
* 4. The names "The Jakarta Project", "Jk", and "Apache Software *
* Foundation" 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 "Apache" nor may *
* "Apache" appear in their names without prior written permission of the *
* Apache Software Foundation. *
* *
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY *
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS *
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN *
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= *
* *
* This software consists of voluntary contributions made by many indivi- *
* duals on behalf of the Apache Software Foundation. For more information *
* on the Apache Software Foundation, please see <http://www.apache.org/>. *
* *
* ========================================================================= */
/**
* Manages the request mappings. It includes the internal mapper and all
* properties associated with a location ( or virtual host ). The information
* is set using:
* - various autoconfiguration mechanisms.
* - uriworkers.properties
* - JkMount directives
* - <SetHandler> and apache specific directives.
* - XXX workers.properties-like directives ( for a single config file )
* - other server-specific directives
*
* The intention is to allow the user to use whatever is more comfortable
* and fits his needs. For 'basic' configuration the autoconf will be enough,
* server-specific configs are the best for fine-tunning, properties are
* easy to generate and edit.
*
*
* Author: <NAME> <<EMAIL>>
* author: <NAME>
*/
#ifndef JK_URIMAP_H
#define JK_URIMAP_H
#include "jk_global.h"
#include "jk_env.h"
#include "jk_logger.h"
#include "jk_uriEnv.h"
#include "jk_map.h"
#include "jk_pool.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct jk_uriMap;
struct jk_map;
struct jk_env;
struct jk_pool;
typedef struct jk_uriMap jk_uriMap_t;
struct jk_uriMap {
struct jk_bean *mbean;
/* All mappings */
struct jk_map *maps;
struct jk_workerEnv *workerEnv;
/* Virtual host map. For each host and alias there is one
* entry, the value is a uriEnv that corresponds to the vhost top
* level.
*/
struct jk_map *vhosts;
struct jk_uriEnv *defaultVhost;
/* ---------- Methods ---------- */
/** Initialize the map. This should be called after all workers
were added. It'll check if mappings have valid workers.
*/
int (*init)( struct jk_env *env, jk_uriMap_t *_this);
void (*destroy)( struct jk_env *env, jk_uriMap_t *_this );
int (*addUriEnv)(struct jk_env *env,
struct jk_uriMap *uriMap,
struct jk_uriEnv *uriEnv);
/** Check the uri for potential security problems
*/
int (*checkUri)( struct jk_env *env, jk_uriMap_t *_this,
const char *uri );
/** Mapping the uri. To be thread safe, we need to pass a pool.
Or even better, create the jk_service structure already.
mapUri() can set informations on it as well.
MapUri() method should behave exactly like the native apache2
mapper - we need it since the mapping rules for servlets are
different ( or we don't know yet how to 'tweak' apache config
to do what we need ). Even when we'll know, uriMap will be needed
for other servers.
*/
struct jk_uriEnv *(*mapUri)(struct jk_env *env, jk_uriMap_t *_this,
const char *vhost,
const char *uri);
/* -------------------- @deprecated -------------------- */
/* used by the mapper, temp storage ( ??? )*/
/* pool for mappings. Mappings will change at runtime, we can't
* recycle the main pool.
*/
struct jk_pool *pool;
};
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* JK_URI_MAP_H */
|
HappyHippyHippo/gapp
|
migration/provider_test.go
|
package migration
import (
"github.com/DATA-DOG/go-sqlmock"
"github.com/golang/mock/gomock"
"github.com/happyhippyhippo/gapp"
"github.com/happyhippyhippo/gapp/config"
"github.com/happyhippyhippo/gapp/rdb"
"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"os"
"testing"
)
func Test_NewProvider(t *testing.T) {
t.Run("construct", func(t *testing.T) {
if p := NewProvider(); p == nil {
t.Error("didn't returned a valid reference")
}
})
}
func Test_Provider_Register(t *testing.T) {
t.Run("nil container", func(t *testing.T) {
p := NewProvider()
_ = p.Register(nil)
expected := errNilPointer("container")
if err := p.Register(nil); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expected (%v)", err, expected)
}
})
t.Run("register components", func(t *testing.T) {
container := gapp.NewContainer()
p := NewProvider()
if err := p.Register(container); err != nil {
t.Errorf("returned the (%v) error", err)
} else if !container.Has(ContainerID) {
t.Errorf("didn't registered the migrator : %v", p)
}
})
t.Run("error retrieving db connection factory when retrieving migrator", func(t *testing.T) {
expected := errors.Errorf("error message")
container := gapp.NewContainer()
_ = NewProvider().Register(container)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return nil, expected })
if _, err := container.Get(ContainerID); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("invalid db connection factory when retrieving migrator", func(t *testing.T) {
expected := errConversion("string", "rdb.ConnectionFactory")
container := gapp.NewContainer()
_ = NewProvider().Register(container)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return "string", nil })
if _, err := container.Get(ContainerID); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("error retrieving db connection config when retrieving migrator", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
expected := errors.Errorf("error message")
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
cfg.EXPECT().AddObserver("rdb", gomock.Any()).Return(nil).Times(1)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
_ = NewProvider().Register(container)
_ = container.Service(rdb.ContainerConfigID, func() (interface{}, error) { return nil, expected })
if _, err := container.Get(ContainerID); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("invalid db connection config when retrieving migrator", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
expected := errConversion("string", "*gorm.Config")
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
cfg.EXPECT().AddObserver("rdb", gomock.Any()).Return(nil).Times(1)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
_ = NewProvider().Register(container)
_ = container.Service(rdb.ContainerConfigID, func() (interface{}, error) { return "string", nil })
if _, err := container.Get(ContainerID); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("error retrieving connection when retrieving migrator", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
expected := errors.Errorf("error message")
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
_ = NewProvider().Register(container)
factory := NewMockDatabaseConnectionFactory(ctrl)
factory.EXPECT().Get(Database, gomock.Any()).Return(nil, expected).Times(1)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return factory, nil })
if _, err := container.Get(ContainerID); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("error instantiating migrations dao when retrieving migrator", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
expected := errors.Errorf("error message")
db, dbmock, _ := sqlmock.New()
defer func() { _ = db.Close() }()
dbmock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("MariaDB"))
dbmock.ExpectExec("CREATE TABLE `__version`").WillReturnError(expected)
gdb, _ := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{Logger: gormLogger.Discard})
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
_ = NewProvider().Register(container)
factory := NewMockDatabaseConnectionFactory(ctrl)
factory.EXPECT().Get(Database, gomock.Any()).Return(gdb, nil).Times(1)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return factory, nil })
if _, err := container.Get(ContainerID); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("retrieving migrator", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
db, dbmock, _ := sqlmock.New()
defer func() { _ = db.Close() }()
dbmock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("MariaDB"))
dbmock.ExpectExec("CREATE TABLE `__version`").WillReturnResult(sqlmock.NewResult(0, 0))
gdb, _ := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{Logger: gormLogger.Discard})
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
_ = NewProvider().Register(container)
factory := NewMockDatabaseConnectionFactory(ctrl)
factory.EXPECT().Get(Database, gomock.Any()).Return(gdb, nil).Times(1)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return factory, nil })
if sut, err := container.Get(ContainerID); err != nil {
t.Errorf("returned the unexpected error (%v)", err)
} else if sut == nil {
t.Error("didn't returned a reference to the migrator")
} else {
switch sut.(type) {
case *migrator:
default:
t.Error("didn't returned a migrator reference")
}
}
})
t.Run("retrieving migrator using db container id from env", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
db, dbmock, _ := sqlmock.New()
_ = os.Setenv(EnvDatabase, "dummy.db.connection")
defer func() { _ = db.Close(); _ = os.Setenv(EnvDatabase, "primary") }()
dbmock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("MariaDB"))
dbmock.ExpectExec("CREATE TABLE `__version`").WillReturnResult(sqlmock.NewResult(0, 0))
gdb, _ := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{Logger: gormLogger.Discard})
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
_ = NewProvider().Register(container)
factory := NewMockDatabaseConnectionFactory(ctrl)
factory.EXPECT().Get("dummy.db.connection", gomock.Any()).Return(gdb, nil).Times(1)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return factory, nil })
if sut, err := container.Get(ContainerID); err != nil {
t.Errorf("returned the unexpected error (%v)", err)
} else if sut == nil {
t.Error("didn't returned a reference to the migrator")
} else {
switch sut.(type) {
case *migrator:
default:
t.Error("didn't returned a migrator reference")
}
}
})
}
func Test_Provider_Boot(t *testing.T) {
t.Run("nil container", func(t *testing.T) {
p := NewProvider()
expected := errNilPointer("container")
if err := p.Boot(nil); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expected (%v)", err, expected)
}
})
t.Run("disable auto migration", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
AutoMigrate = false
defer func() { AutoMigrate = true }()
container := gapp.NewContainer()
p := NewProvider()
if err := p.Boot(container); err != nil {
t.Errorf("returned the unexpected error, (%v)", err)
}
})
t.Run("disable migrator auto migration by environment variable", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
_ = os.Setenv(EnvAutoMigrate, "false")
defer func() { _ = os.Setenv(EnvAutoMigrate, "") }()
container := gapp.NewContainer()
p := NewProvider()
_ = p.Register(container)
if err := p.Boot(container); err != nil {
t.Errorf("returned the unexpected error, (%v)", err)
}
})
t.Run("error on retrieving migrator", func(t *testing.T) {
expected := errors.Errorf("error message")
container := gapp.NewContainer()
p := NewProvider()
_ = p.Register(container)
_ = container.Service(ContainerID, func() (interface{}, error) { return nil, expected })
if err := p.Boot(container); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("invalid retrieved migrator", func(t *testing.T) {
expected := errConversion("string", "migration.Migrator")
container := gapp.NewContainer()
p := NewProvider()
_ = p.Register(container)
_ = container.Service(ContainerID, func() (interface{}, error) { return "string", nil })
if err := p.Boot(container); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("error on retrieving migrations", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
db, dbmock, _ := sqlmock.New()
defer func() { _ = db.Close() }()
dbmock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("MariaDB"))
dbmock.ExpectExec("CREATE TABLE `__version`").WillReturnResult(sqlmock.NewResult(0, 0))
gdb, _ := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{Logger: gormLogger.Discard})
expected := errors.Errorf("error message")
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
factory := NewMockDatabaseConnectionFactory(ctrl)
factory.EXPECT().Get(Database, gomock.Any()).Return(gdb, nil).Times(1)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return factory, nil })
_ = container.Service("id", func() (interface{}, error) { return nil, expected }, ContainerMigrationTag)
p := NewProvider()
_ = p.Register(container)
if err := p.Boot(container); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("invalid migration on retrieving migrations", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
db, dbmock, _ := sqlmock.New()
defer func() { _ = db.Close() }()
dbmock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow("MariaDB"))
dbmock.ExpectExec("CREATE TABLE `__version`").WillReturnResult(sqlmock.NewResult(0, 0))
gdb, _ := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{Logger: gormLogger.Discard})
expected := errConversion("string", "migration.Migration")
container := gapp.NewContainer()
cfg := NewMockConfig(ctrl)
_ = container.Service(config.ContainerID, func() (interface{}, error) { return cfg, nil })
_ = rdb.NewProvider().Register(container)
factory := NewMockDatabaseConnectionFactory(ctrl)
factory.EXPECT().Get(Database, gomock.Any()).Return(gdb, nil).Times(1)
_ = container.Service(rdb.ContainerID, func() (interface{}, error) { return factory, nil })
_ = container.Service("id", func() (interface{}, error) { return "string", nil }, ContainerMigrationTag)
p := NewProvider()
_ = p.Register(container)
if err := p.Boot(container); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("run migrator auto migration", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
container := gapp.NewContainer()
p := NewProvider()
_ = p.Register(container)
migration := NewMockMigration(ctrl)
_ = container.Service("id", func() (interface{}, error) { return migration, nil }, ContainerMigrationTag)
migrator := NewMockMigrator(ctrl)
migrator.EXPECT().AddMigration(migration).Return(nil).Times(1)
migrator.EXPECT().Migrate().Return(nil).Times(1)
_ = container.Service(ContainerID, func() (interface{}, error) { return migrator, nil })
if err := p.Boot(container); err != nil {
t.Errorf("returned the unexpected error, (%v)", err)
}
})
t.Run("error running migrator auto migration", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
expected := errors.Errorf("error message")
container := gapp.NewContainer()
p := NewProvider()
_ = p.Register(container)
migration := NewMockMigration(ctrl)
_ = container.Service("id", func() (interface{}, error) { return migration, nil }, ContainerMigrationTag)
migrator := NewMockMigrator(ctrl)
migrator.EXPECT().AddMigration(migration).Return(nil).Times(1)
migrator.EXPECT().Migrate().Return(expected).Times(1)
_ = container.Service(ContainerID, func() (interface{}, error) { return migrator, nil })
if err := p.Boot(container); err == nil {
t.Error("didn't returned the expected error")
} else if err.Error() != expected.Error() {
t.Errorf("returned the (%v) error when expecting (%v)", err, expected)
}
})
t.Run("running migrator", func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
container := gapp.NewContainer()
p := NewProvider()
_ = p.Register(container)
migration := NewMockMigration(ctrl)
_ = container.Service("id", func() (interface{}, error) { return migration, nil }, ContainerMigrationTag)
migrator := NewMockMigrator(ctrl)
migrator.EXPECT().AddMigration(migration).Return(nil).Times(1)
migrator.EXPECT().Migrate().Return(nil).Times(1)
_ = container.Service(ContainerID, func() (interface{}, error) { return migrator, nil })
if err := p.Boot(container); err != nil {
t.Errorf("returned the unexpected error : %v", err)
}
})
}
|
truthiswill/intellij-community
|
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA78402.java
|
<filename>java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA78402.java
import java.util.Collection;
import java.util.List;
class Reference<T> {}
class Bug {
private static <T> void foo(List<T> x, Reference<String> y) {
System.out.println(x);
}
private static <T> void foo(Collection<T> x, Reference<T> y) {
System.out.println(x);
}
public static void bazz(List<String> bar) {
foo<error descr="Ambiguous method call: both 'Bug.foo(List<String>, Reference<String>)' and 'Bug.foo(Collection<String>, Reference<String>)' match">(bar, null)</error>;
}
}
|
S-Coyle/safe-web-hosting-manager-electron
|
app/actions/public_names.js
|
/**
* Actions handling Public Names
*/
/* eslint-disable import/no-named-as-default-member, import/no-named-as-default */
import api from '../safenet_comm/api';
/* eslint-enable import/no-named-as-default-member, import/no-named-as-default */
import ACTION_TYPES from './action_types';
/**
* check can access service container
* @param publicName
*/
export const canAccessPublicName = publicName => ({
type: ACTION_TYPES.CAN_ACCESS_PUBLIC_NAME,
payload: api.canAccessServiceContainer(publicName),
});
/**
* Set Public names to application state
* @param publicNames
*/
export const setPublicNames = publicNames => ({
type: ACTION_TYPES.SET_PUBLIC_NAMES,
data: publicNames,
});
/**
* Set service container details to application state
* @param containers
*/
export const setServiceContainers = containers => ({
type: ACTION_TYPES.SET_SERVICE_CONTAINERS,
data: containers,
});
/**
* Create new Public Name
* @param publicName
*/
export const createPublicName = publicName => (
(dispatch) => {
dispatch({
type: ACTION_TYPES.CREATE_PUBLIC_NAME,
payload: api.createPublicName(publicName)
.then(() => api.fetchPublicNames())
.then(publicNames => dispatch(setPublicNames(publicNames))),
});
}
);
/**
* Get all available service containers
*/
export const getServiceContainers = () => (
(dispatch) => {
dispatch({
type: ACTION_TYPES.FETCH_SERVICE_CONTAINERS,
payload: api.getServiceFolderNames()
.then(containers => dispatch(setServiceContainers(containers))),
});
}
);
|
jseward/solar
|
src/solar_platforms/d3d9/d3d9_mesh_vertex.h
|
<reponame>jseward/solar
#pragma once
#include "solar/utility/type_convert.h"
namespace solar {
class d3d9_mesh_vertex {
public:
float _px;
float _py;
float _pz;
float _nx;
float _ny;
float _nz;
float _u_0;
float _v_0;
float _tx;
float _ty;
float _tz;
float _binormal_sign;
uint8_t _bone_index_0;
uint8_t _bone_index_1;
uint8_t _bone_index_2;
uint8_t _bone_index_3;
float _bone_weight_0;
float _bone_weight_1;
float _bone_weight_2;
float _bone_weight_3;
public:
d3d9_mesh_vertex& operator=(const mesh_vertex& rhs) {
_px = rhs._position._x;
_py = rhs._position._y;
_pz = rhs._position._z;
_nx = rhs._normal._x;
_ny = rhs._normal._y;
_nz = rhs._normal._z;
_u_0 = rhs._uv._u;
_v_0 = rhs._uv._v;
_tx = rhs._tangent._x;
_ty = rhs._tangent._y;
_tz = rhs._tangent._z;
_binormal_sign = rhs._binormal_sign;
copy_bone_weight(rhs, 0, _bone_index_0, _bone_weight_0);
copy_bone_weight(rhs, 1, _bone_index_1, _bone_weight_1);
copy_bone_weight(rhs, 2, _bone_index_2, _bone_weight_2);
copy_bone_weight(rhs, 3, _bone_index_3, _bone_weight_3);
return *this;
}
private:
static void copy_bone_weight(const mesh_vertex& src, unsigned int i, uint8_t& dst_bone_index, float& dst_bone_weight) {
if (src._bone_weights.size() > i) {
dst_bone_index = src._bone_weights[i]._bone_index;
dst_bone_weight = src._bone_weights[i]._weight;
}
else {
dst_bone_index = 0;
dst_bone_weight = 0.f;
}
}
};
}
|
Randy-Hodges/ZooCollect
|
scripts/characters/companions/companion_class.js
|
<reponame>Randy-Hodges/ZooCollect<gh_stars>1-10
var companionGroup;
var piggyUnlocked = false;
var froggyUnlocked = false;
var slimeUnlocked = false;
Companion = function(game, spritesheetStrID, x = gameWidth/2, y = gameHeight/2, followOn = false, isEquipped = false){
// instantiate Sprite object
Phaser.Sprite.call(this, game, x, y, spritesheetStrID);
this.anchor.setTo(.5,.5);
var scale = .6;
this.scale.setTo(scale, scale);
// Sprite Variables
this.spritesheetStrID = spritesheetStrID;
this.followOn = followOn;
this.isEquipped = isEquipped;
this.followObject;
// animations
this.stopMovementAnimations = false;
/* #region Physics */
this.accelx = basePlayer.accelx;
game.physics.enable(this);
this.body.allowGravity = false;
this.body.setSize(32,32);
this.body.drag.x = 500;
this.body.maxVelocity.x = 150;
this.body.maxVelocity.y = 300;
// Text
this.equipText = game.add.text(this.body.position.x, this.body.position.y,"Q", { fontSize: '12px', fill: '#000' });
this.equipTextShowing = false;
this.equipText.alpha = 0;
this.equipText2 = game.add.text(this.body.position.x, this.body.position.y,"Q", { fontSize: '12px', fill: '#fff' });
this.equipText2.alpha = 0;
}
Companion.prototype = Object.create(Phaser.Sprite.prototype);
Companion.prototype.constructor = Companion;
// (Automatically called by World.update)
Companion.prototype.update = function(companion = this) {
// Equipping
var overlapped = game.physics.arcade.overlap(currentPlayer, companionGroup, function(player, companion){
if (!companion.isEquipped && !companion.equipTextShowing){
companion.equipText.x = companion.body.position.x + 3;
companion.equipText.y = companion.body.position.y - 12;
companion.equipText.alpha = 1;
companion.equipTextShowing = true;
companion.equipText2.x = companion.body.position.x + 2;
companion.equipText2.y = companion.body.position.y - 13;
companion.equipText2.alpha = 1;
}
customKeys = new CustomKeys();
if (customKeys.isDown("Q") && !companion.isEquipped){
equipCompanion(companion);
}
});
if (!overlapped){
companion.equipText.alpha = 0;
companion.equipTextShowing = false;
companion.equipText2.alpha = 0;
}
// Follow Logic
if (companion.isEquipped){
companion.followOn = true;
}
if (companion.followObject == undefined){
companion.followOn = false;
}
if (companion.followOn){
game.physics.arcade.moveToObject(companion, companion.followObject, 30, 500);
}
else{
companion.body.velocity.x = 0;
companion.body.velocity.y = 0;
}
// ----Animation----
// left
if (companion.body.velocity.x < 0){
companion.scale.x = Math.abs(companion.scale.x);
}
// right
else if (companion.body.velocity.x > 0){
companion.scale.x = -Math.abs(companion.scale.x);
}
};
Companion.prototype.returnHome = function(){
this.equipTextShowing = false;
if (game.state.current == 'level0'){
this.followObject = this.home;
}
else{
this.followObject = undefined;
}
}
Companion.prototype.equip = function(){
console.log('equipping ' + this.name)
}
Companion.prototype.unequip = function(){
console.log('unequipping ' + this.name)
}
|
ORNL-QCI/armish-fireplace
|
module/brazil/proc_unit/lcc_and_fpga.cpp
|
#include "lcc_and_fpga.hpp"
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
namespace module {
namespace brazil {
namespace proc_unit {
lcc_and_fpga::lcc_and_fpga()
: controller0(0), controller1(0), isReceiving(false) {
}
lcc_and_fpga::~lcc_and_fpga() {
if(controller0 != 0) {
delete controller0;
}
if(controller1 != 0) {
delete controller1;
}
boost::system::error_code ec;
}
::module::iproc_unit* lcc_and_fpga::initialize() {
return new lcc_and_fpga();
}
void lcc_and_fpga::string_initialize_parameters(const char* const parameters) {
std::string tempParameters(parameters);
std::string configurationFile;
std::vector<std::string> parameterTokenStrings;
std::string lccDev0;
std::uint_fast32_t lccSpeed0 = 0;
std::string lccDev1;
std::uint_fast32_t lccSpeed1 = 0;
std::string zedboardIp;
std::uint_fast16_t zedboardPort = 0;
std::string handshakeIp;
nIp = 0;
qPort = 0;
std::string ppVoltage1;
std::string ppVoltage2;
std::string pspVoltage1;
std::string pspVoltage2;
std::string pmVoltage1;
std::string pmVoltage2;
std::string psmVoltage1;
std::string psmVoltage2;
boost::escaped_list_separator<char> seperator("\\", "= ", "\"\'");
boost::tokenizer<boost::escaped_list_separator<char> > tokens(tempParameters, seperator);
std::copy_if(tokens.begin(), tokens.end(), std::back_inserter(parameterTokenStrings), !boost::bind(&std::string::empty, _1));
try {
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("config", po::value<std::string>(&configurationFile)->required(), "configuration file")
("lccDev0", po::value<std::string>(&lccDev0), "lcc device 0")
("lccSpeed0", po::value<std::uint_fast16_t>(&lccSpeed0), "lcc speed 0")
("lccDev1", po::value<std::string>(&lccDev1), "lcc device 1")
("lccSpeed1", po::value<std::uint_fast16_t>(&lccSpeed1), "lcc speed 1")
("zedboardIp", po::value<std::string>(&zedboardIp), "zedboard IP")
("zedboardPort", po::value<std::uint_fast16_t>(&zedboardPort), "zedboard Port")
("handshakeIp", po::value<std::string>(&handshakeIp), "handshake IP")
("handshakePort", po::value<std::uint_fast16_t>(&qPort), "handshake Port")
("ppVoltage1", po::value<std::string>(&ppVoltage1), "psiplus voltage 1")
("ppVoltage2", po::value<std::string>(&ppVoltage2), "psiplus voltage 2")
("pspVoltage1", po::value<std::string>(&pspVoltage1), "phiplus voltage 1")
("pspVoltage2", po::value<std::string>(&pspVoltage2), "phiplus voltage 2")
("pmVoltage1", po::value<std::string>(&pmVoltage1), "psiminus voltage 1")
("pmVoltage2", po::value<std::string>(&pmVoltage2), "psiminus voltage 2")
("psmVoltage1", po::value<std::string>(&psmVoltage1), "phiminus voltage 1")
("psmVoltage2", po::value<std::string>(&psmVoltage2), "phiminus voltage 2");
po::variables_map vm;
po::store(po::command_line_parser(parameterTokenStrings).options(desc).run(), vm);
po::notify(vm);
po::store(po::parse_config_file<char>(configurationFile.c_str(), desc), vm);
po::notify(vm);
} catch(boost::program_options::required_option &e) {
std::cerr << e.what() << std::endl;
exit(-1);
} catch(boost::program_options::error &e) {
std::cerr << e.what() << std::endl;
exit(-1);
}
if(lccDev0.empty() != lccDev1.empty()) {
throw std::invalid_argument("Missing lc controller");
} else if(!lccDev0.empty()) {
if(lccSpeed0 == 0 || lccSpeed1 == 0) {
throw std::invalid_argument("Missing lc controller speed");
} else {
controller0 = new serial_connection(lccDev0.c_str(), lccSpeed0);
controller1 = new serial_connection(lccDev1.c_str(), lccSpeed1);
if(ppVoltage1.empty() || ppVoltage2.empty() ||
pspVoltage1.empty() || pspVoltage2.empty() ||
pmVoltage1.empty() || pmVoltage2.empty() ||
psmVoltage1.empty() || psmVoltage2.empty()) {
throw std::invalid_argument("Missing voltage");
}
}
}
if(!zedboardIp.empty() && zedboardPort == 0) {
throw std::invalid_argument("Missing zedboard port");
} else if(!zedboardIp.empty()) {
isRx = true;
// Compute numerical ip address for quicker matching
char* end = 0;
char* pnIP = (char*)&nIp;
pnIP[3] = strtoul(handshakeIp.c_str(), &end, 10);
end++;
char* end2 = 0;
pnIP[2] = strtoul(end, &end2, 10);
end2++;
char* end3 = 0;
pnIP[1] = strtoul(end2, &end3, 10);
end3++;
char* end4 = 0;
pnIP[0] = strtoul(end3, &end4, 10);
// Connection to zedboard
//hardwareConnection = new ::net::tcp_client<response, request>(ioService, zedboardIp.c_str(), zedboardPort);
// Server for requests
/** \todo fix memory leak here! (well it should be strdup) */
auto tip = new char[strlen(handshakeIp.c_str()) + 1];
strcpy(tip, handshakeIp.c_str());
//thread = new std::thread(&lcc_and_fpga::work, this, std::ref(ioService), tip, qPort);
} else {
isRx = false;
}
}
void lcc_and_fpga::async_work(::buffer::queue_buffer& out) {
UNUSED(out);
}
::module::iproc_unit::response* lcc_and_fpga::proc_act_request(
const ::module::iproc_unit::request& request) {
UNUSED(request);
return NULL;
}
bool lcc_and_fpga::proc_act_push(
const ::module::iproc_unit::request& request) {
UNUSED(request);
return false;
}
/*
void lcc_and_fpga::source_work(::buffer::queue_buffer& buffer) {
auto items = buffer.pop_all();
while(items.size() != 0) {
::buffer::buffer_item& item(items.front());
switch(((char*)item.data())[0]) {
case 0:
case '0':
controller0->write("mode=1\r");
controller0->dump();
controller1->write("mode=1\r");
controller1->dump();
break;
case 1:
case '1':
controller0->write("mode=2\r");
controller0->dump();
controller1->write("mode=1\r");
controller1->dump();
break;
case 2:
case '2':
controller0->write("mode=1\r");
controller0->dump();
controller1->write("mode=2\r");
controller1->dump();
break;
case 3:
case '3':
controller0->write("mode=2\r");
controller0->dump();
controller1->write("mode=2\r");
controller1->dump();
break;
default:
throw std::exception();
}
::net::client<::net::response, ::net::request>* requestClient;
std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(400));
std::uint_fast32_t ipNum = item.parameters()[0][0] +
(item.parameters()[0][1] << 8) +
(item.parameters()[0][2] << 16) +
(item.parameters()[0][3] << 24);
requestClient = new ::net::client<::net::response, ::net::request>(ioService, ipNum, qPort);
requestClient->write(std::move(::net::request(nIp, ipNum, 2, 0)));
requestClient->read();
std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(30000));
requestClient->write(std::move(::net::request(nIp, ipNum, 2, 0)));
requestClient->read();
delete requestClient;
items.pop();
}
}*/
/*
void lcc_and_fpga::sink_work(::buffer::queue_buffer& buffer) {
if(isRx) {
std::unique_lock<std::mutex> lock(_bufferMutex);
if(_buffer.size() != 0) {
for(auto i : _buffer) {
std::string temps = std::string("{\"result\":")+std::to_string(i)+std::string("}");
buffer.push(::buffer::buffer_item((char*)temps.data(), temps.size(), 0, 0, false));
}
_buffer.clear();
}
}
}*/
void lcc_and_fpga::work(boost::asio::io_service& ioService,
const char* const address,
const std::uint_fast16_t port) {
//auto requestServer = new ::net::server<lcc_and_fpga, ::net::request, ::net::response>(ioService,
// address,
// port,
// *this,
// &lcc_and_fpga::process);
// Block until ioService.stop() is called
boost::asio::io_service::work work(ioService);
ioService.run();
UNUSED(port);
//delete requestServer;
delete[] address;
}
void lcc_and_fpga::process(::net::request& incomingMessage,
::net::response& outgoingMessage) {
UNUSED(incomingMessage);
outgoingMessage.set_status(::net::response_status_code::OK);
if(isReceiving) {
hardwareConnection->write(request(false));
response data(hardwareConnection->read());
std::size_t count[4] = {0};
for(std::size_t i = 0; i < data.length(); i++) {
switch(data.data()[i]) {
case 0:
count[0]++;
break;
case 1:
count[1]++;
break;
case 2:
count[2]++;
break;
case 3:
count[3]++;
break;
}
}
char temp[1];
auto max = std::max_element(count, count+4);
if(*max == count[0]) {
temp[0] = 0;
} else if(*max == count[1]) {
temp[0] = 1;
} else if(*max == count[2]) {
temp[0] = 2;
} else if(*max == count[3]) {
temp[0] = 3;
} else {
throw std::exception();
}
std::unique_lock<std::mutex> lock(_bufferMutex);
_buffer.push_back(temp[0]);
} else {
hardwareConnection->write(request(true));
}
isReceiving = !isReceiving;
}
}
}
}
|
cesswairimu/WebsiteOne
|
features/support/capybara.rb
|
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, js_errors: false,
phantomjs: Phantomjs.path,
phantomjs_options: ['--ssl-protocol=tlsv1.2', '--ignore-ssl-errors=yes'])
end
test_options = {
phantomjs_options: [
'--ignore-ssl-errors=yes',
"--proxy=#{Billy.proxy.host}:#{Billy.proxy.port}"
],
phantomjs: Phantomjs.path,
js_errors: true,
}
plain_options = {
phantomjs_options: [
'--ignore-ssl-errors=yes'
],
phantomjs: Phantomjs.path,
js_errors: true,
}
debug_options = {
phantomjs_options: [
'--ignore-ssl-errors=yes',
],
phantomjs: Phantomjs.path,
inspector: true,
debug: true,
js_errors: true,
}
Capybara.register_driver :poltergeist_billy do |app|
Capybara::Poltergeist::Driver.new(app, test_options)
end
Capybara.default_max_wait_time = 5
Capybara.javascript_driver = :poltergeist_billy
Capybara.save_path = 'tmp/capybara'
Capybara.asset_host = 'http://localhost:3000'
|
sbellware/test-bench
|
test/automated/output/session/errors/file.rb
|
require_relative '../../../automated_init'
context "Output" do
context "Session" do
context "Errors" do
context "File" do
path = Controls::TestFile.example
error = Controls::Error.example
output = Output::Session.new
Output::PrintError.configure(output, writer: output.writer)
output.enter_file(path)
output.error(error)
output.exit_file(path, false)
test "Prints the error after the file name" do
control_text = <<~TEXT
Running #{path}
#{error.backtrace[0]}: #{error.message} (#{error.class.name})
\tfrom #{error.backtrace[1]}
\tfrom #{error.backtrace[2]}
TEXT
assert(output.writer.written?(control_text))
end
end
end
end
end
|
clementleger/pocl
|
include/pocl_file_util.h
|
<filename>include/pocl_file_util.h
/* pocl_file_util.h: global declarations of portable file utility functions
defined in lib/llvmopencl, due to using llvm::sys::fs & other llvm APIs
Copyright (c) 2015 pocl developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef POCL_FILE_UTIL_H
#define POCL_FILE_UTIL_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __GNUC__
#pragma GCC visibility push(hidden)
#endif
#define LOCK_ACQUIRE_FAIL 3210
void* acquire_lock(const char* path, int shared);
void release_lock(void* lock);
/* Remove a directory, recursively */
int pocl_rm_rf(const char* path);
/* Make a directory, including all directories along path */
int pocl_mkdir_p(const char* path);
/* Remove a file or empty directory */
int pocl_remove(const char* path);
int pocl_exists(const char* path);
int pocl_filesize(const char* path, uint64_t* res);
/* Touch file to change last modified time. For portability, this
* removes & creates the file. */
int pocl_touch_file(const char* path);
/* Writes or appends data to a file. */
int pocl_write_file(const char* path, const char* content,
uint64_t count, int append, int dont_rewrite);
/* Allocates memory and places file contents in it.
* Returns negative errno on error, zero otherwise. */
int pocl_read_file(const char* path, char** content, uint64_t *filesize);
int pocl_write_module(void *module, const char* path, int dont_rewrite);
int pocl_remove_locked(const char* path);
#ifdef __GNUC__
#pragma GCC visibility pop
#endif
#ifdef __cplusplus
}
#endif
#endif
|
yadickson/flex-debs
|
core/src/main/java/flex/messaging/io/amf/ActionContext.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 flex.messaging.io.amf;
import flex.messaging.io.MessageIOConstants;
import flex.messaging.messages.MessagePerformanceInfo;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
/**
* A context for reading and writing messages.
*
*/
public class ActionContext implements Serializable
{
static final long serialVersionUID = 2300156738426801921L;
private int messageNumber;
private ActionMessage requestMessage;
private ActionMessage responseMessage;
private ByteArrayOutputStream outBuffer;
private int status;
private int version;
private boolean legacy;
public boolean isPush;
public boolean isDebug;
/**
*
* Performance metrics related field, keeps track of bytes deserialized using this context
*/
private int deserializedBytes;
/**
*
* Performance metrics related field, keeps track of bytes serialized using this context
*/
private int serializedBytes;
/**
*
* Performance metrics related field, recordMessageSizes flag
*/
private boolean recordMessageSizes;
/**
*
* Performance metrics related field, recordMessageTimes flag
*/
private boolean recordMessageTimes;
/**
*
* Performance metrics related field, incoming MPI object, will only be populated when one of
* the record-message-* params is enabled
*/
private MessagePerformanceInfo mpii;
/**
*
* Performance metrics related field, outgoing MPI object, will only be populated when one of
* the record-message-* params is enabled
*/
private MessagePerformanceInfo mpio;
public ActionContext()
{
status = MessageIOConstants.STATUS_OK;
}
public boolean isLegacy()
{
return legacy;
}
public void setLegacy(boolean legacy)
{
this.legacy = legacy;
}
public int getMessageNumber()
{
return messageNumber;
}
public void setMessageNumber(int messageNumber)
{
this.messageNumber = messageNumber;
}
public MessageBody getRequestMessageBody()
{
return requestMessage.getBody(messageNumber);
}
public ActionMessage getRequestMessage()
{
return requestMessage;
}
public void setRequestMessage(ActionMessage requestMessage)
{
this.requestMessage = requestMessage;
}
public ActionMessage getResponseMessage()
{
return responseMessage;
}
public MessageBody getResponseMessageBody()
{
return responseMessage.getBody(messageNumber);
}
public void setResponseMessage(ActionMessage responseMessage)
{
this.responseMessage = responseMessage;
}
public void setResponseOutput(ByteArrayOutputStream out)
{
outBuffer = out;
}
public ByteArrayOutputStream getResponseOutput()
{
return outBuffer;
}
public int getStatus()
{
return status;
}
public void setStatus(int status)
{
this.status = status;
}
public void setVersion(int v)
{
version = v;
}
public int getVersion()
{
return version;
}
public void incrementMessageNumber()
{
messageNumber++;
}
public int getDeserializedBytes()
{
return deserializedBytes;
}
public void setDeserializedBytes(int deserializedBytes)
{
this.deserializedBytes = deserializedBytes;
}
public int getSerializedBytes()
{
return serializedBytes;
}
public void setSerializedBytes(int serializedBytes)
{
this.serializedBytes = serializedBytes;
}
public MessagePerformanceInfo getMPII()
{
return mpii;
}
public void setMPII(MessagePerformanceInfo mpii)
{
this.mpii = mpii;
}
public MessagePerformanceInfo getMPIO()
{
return mpio;
}
public void setMPIO(MessagePerformanceInfo mpio)
{
this.mpio = mpio;
}
public boolean isRecordMessageSizes()
{
return recordMessageSizes;
}
public void setRecordMessageSizes(boolean recordMessageSizes)
{
this.recordMessageSizes = recordMessageSizes;
}
public boolean isRecordMessageTimes()
{
return recordMessageTimes;
}
public boolean isMPIenabled()
{
return recordMessageTimes || recordMessageSizes;
}
public void setRecordMessageTimes(boolean recordMessageTimes)
{
this.recordMessageTimes = recordMessageTimes;
}
}
|
renesas/rx-driver-package
|
source/r_comms_i2c_rx/r_comms_i2c_rx_vx.xx/r_comms_i2c_rx/inc/instances/rm_comms_i2c.h
|
<reponame>renesas/rx-driver-package<gh_stars>1-10
/***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No
* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
* applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM
* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES
* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS
* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of
* this software. By using this software, you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2021 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/
/*******************************************************************************************************************//**
* @addtogroup RM_COMMS_I2C
* @{
**********************************************************************************************************************/
#ifndef RM_COMMS_I2C_H
#define RM_COMMS_I2C_H
/***********************************************************************************************************************
* Includes
**********************************************************************************************************************/
#include "rm_comms_api.h"
#if defined(__CCRX__) || defined(__ICCRX__) || defined(__RX__)
#include "r_comms_i2c_rx_config.h"
#if BSP_CFG_RTOS_USED == 1 // FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#define BSP_CFG_RTOS 2
#elif BSP_CFG_RTOS_USED == 5 // ThreadX
#define BSP_CFG_RTOS 1
#else
#define BSP_CFG_RTOS 0
#endif
#elif defined(__CCRL__) || defined(__ICCRL__) || defined(__RL78__)
#include "r_comms_i2c_rl_config.h"
#else
#include "r_i2c_master_api.h"
#include "rm_comms_i2c_cfg.h"
#if BSP_CFG_RTOS == 1 // ThreadX
#include "tx_api.h"
#elif BSP_CFG_RTOS == 2 // FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#endif
/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */
FSP_HEADER
#endif
/**********************************************************************************************************************
* Macro definitions
**********************************************************************************************************************/
/***********************************************************************************************************************
* Typedef definitions
**********************************************************************************************************************/
#if BSP_CFG_RTOS
/* Mutex structure */
typedef struct st_rm_comms_i2c_mutex
{
#if BSP_CFG_RTOS == 1 // ThreadX
TX_MUTEX * p_mutex_handle;
CHAR * p_mutex_name;
#elif BSP_CFG_RTOS == 2 // FreeRTOS
SemaphoreHandle_t * p_mutex_handle;
StaticSemaphore_t * p_mutex_memory;
#else
#endif
} rm_comms_i2c_mutex_t;
/* Semaphore Structure */
typedef struct st_rm_comms_i2c_semaphore
{
#if BSP_CFG_RTOS == 1 // ThreadX
TX_SEMAPHORE * p_semaphore_handle;
CHAR * p_semaphore_name;
#elif BSP_CFG_RTOS == 2 // FreeRTOS
SemaphoreHandle_t * p_semaphore_handle;
StaticSemaphore_t * p_semaphore_memory;
#else
#endif
} rm_comms_i2c_semaphore_t;
#endif
/* I2C bus configuration */
typedef struct st_rm_comms_i2c_bus_extended_cfg
{
#if BSP_CFG_RTOS
rm_comms_i2c_mutex_t const * p_bus_recursive_mutex; ///< The mutex for the bus. If this is NULL then operations will not lock the bus while it is in use.
rm_comms_i2c_semaphore_t const * p_blocking_semaphore; ///< The semaphore for blocking operations. If this is NULL then operations will be non-blocking and require a callback.
#endif
uint32_t bus_timeout; ///< Possible in ticks.
rm_comms_ctrl_t * p_current_ctrl; ///< Current device using the bus (by switching the address)
void const * p_driver_instance; ///< Pointer to I2C HAL interface to be used in the framework
} rm_comms_i2c_bus_extended_cfg_t;
/** Communications middleware control structure. */
typedef struct st_rm_comms_i2c_instance_ctrl
{
rm_comms_cfg_t const * p_cfg; ///< middleware configuration.
rm_comms_i2c_bus_extended_cfg_t * p_bus; ///< Bus using this device;
void * p_lower_level_cfg; ///< Used to reconfigure I2C driver
uint32_t open; ///< Open flag.
uint32_t transfer_data_bytes; ///< Size of transfer data.
uint8_t * p_transfer_data; ///< Pointer to transfer data buffer.
/* Pointer to callback and optional working memory */
void (* p_callback)(rm_comms_callback_args_t * p_args);
void const * p_context; ///< Pointer to the user-provided context
} rm_comms_i2c_instance_ctrl_t;
/**********************************************************************************************************************
* Exported global variables
**********************************************************************************************************************/
/** @cond INC_HEADER_DEFS_SEC */
/** Filled in Interface API structure for this Instance. */
extern rm_comms_api_t const g_comms_on_comms_i2c;
/** @endcond */
/**********************************************************************************************************************
* Public Function Prototypes
**********************************************************************************************************************/
fsp_err_t RM_COMMS_I2C_Open(rm_comms_ctrl_t * const p_api_ctrl, rm_comms_cfg_t const * const p_cfg);
fsp_err_t RM_COMMS_I2C_Close(rm_comms_ctrl_t * const p_api_ctrl);
fsp_err_t RM_COMMS_I2C_Read(rm_comms_ctrl_t * const p_api_ctrl, uint8_t * const p_dest, uint32_t const bytes);
fsp_err_t RM_COMMS_I2C_Write(rm_comms_ctrl_t * const p_api_ctrl, uint8_t * const p_src, uint32_t const bytes);
fsp_err_t RM_COMMS_I2C_WriteRead(rm_comms_ctrl_t * const p_api_ctrl,
rm_comms_write_read_params_t const write_read_params);
#if defined(__CCRX__) || defined(__ICCRX__) || defined(__RX__)
void rm_comms_i2c_callback(rm_comms_ctrl_t const * p_api_ctrl);
#elif defined(__CCRL__) || defined(__ICCRL__) || defined(__RL78__)
void rm_comms_i2c_callback(rm_comms_ctrl_t const * p_api_ctrl, bool aborted);
#else
void rm_comms_i2c_callback(i2c_master_callback_args_t * p_args);
/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */
FSP_FOOTER
#endif
#endif /* RM_COMM_I2C_BUS_H */
/*******************************************************************************************************************//**
* @} (end addtogroup COMM_I2C_BUS)
**********************************************************************************************************************/
|
DanielGuoVT/symsc
|
cloud9_root/src/cloud9/lib/Core/Threading.cpp
|
/*
* Cloud9 Parallel Symbolic Execution Engine
*
* Copyright (c) 2011, Dependable Systems Laboratory, EPFL
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Dependable Systems Laboratory, EPFL 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 DEPENDABLE SYSTEMS LABORATORY, EPFL 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.
*
* All contributors are listed in CLOUD9-AUTHORS file.
*
*/
#include "klee/Threading.h"
#include "klee/ExecutionState.h"
#include "klee/Internal/Module/KModule.h"
#include "klee/Internal/Module/Cell.h"
namespace klee {
/* StackFrame Methods */
StackFrame::StackFrame(KInstIterator _caller, KFunction *_kf) :
caller(_caller), kf(_kf), callPathNode(0), minDistToUncoveredOnReturn(0), varargs(0) {
locals = new Cell[kf->numRegisters];
}
StackFrame::StackFrame(const StackFrame &s) :
caller(s.caller), kf(s.kf), callPathNode(s.callPathNode), allocas(s.allocas), minDistToUncoveredOnReturn(s.minDistToUncoveredOnReturn), varargs(
s.varargs) {
locals = new Cell[s.kf->numRegisters];
for (unsigned i = 0; i < s.kf->numRegisters; i++)
locals[i] = s.locals[i];
}
StackFrame& StackFrame::operator=(const StackFrame &s) {
if (this != &s) {
caller = s.caller;
kf = s.kf;
callPathNode = s.callPathNode;
allocas = s.allocas;
minDistToUncoveredOnReturn = s.minDistToUncoveredOnReturn;
varargs = s.varargs;
if (locals) delete[] locals;
locals = new Cell[s.kf->numRegisters];
for (unsigned i = 0; i < s.kf->numRegisters; i++)
locals[i] = s.locals[i];
}
return *this;
}
StackFrame::~StackFrame() {
delete[] locals;
}
/* Thread class methods */
Thread::Thread(thread_id_t tid, process_id_t pid, KFunction * kf) :
enabled(true), waitingList(0), reachInterleavingPoint(false), crtPeriodIndex(0), priority(0), period(0), uniqueID(0){
tuid = std::make_pair(tid, pid);
reachBoundaryStart = false;
highestPrio = false;
lastTransitionType = ExecutionState::null;
lastTransitionAddr = 0;
if (kf) {
stack.push_back(StackFrame(0, kf));
pc = kf->instructions;
prevPC = pc;
}
}
}
|
chi-sea-lions-2015/house-rules-frontend2
|
node_modules/gulp-jest/node_modules/jest-cli/node_modules/node-haste/lib/ResourceMapSerializer.js
|
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require('fs');
var ResourceMap = require('./ResourceMap');
/**
* A class that loads and stores ResourceMaps from and to a given file.
* Usese simple JSON functions to seralize/deserialize the data
*
* @class
* @param {Array.<ResourceLoader>} loaders
*/
function ResourceMapSerializer(loaders, options) {
options = options || {};
this.version = options.version || '0.1';
this.typeMap = {};
loaders.forEach(function(loader) {
loader.getResourceTypes().forEach(function(type) {
this.typeMap[type.prototype.type] = type;
}, this);
}, this);
}
/**
* Loads and deserializes a map from a given path
* @param {String} path
* @param {ResourceMap} map
* @param {Function} callback
*/
ResourceMapSerializer.prototype.loadFromPath = function(path, callback) {
var me = this;
fs.readFile(path, 'utf-8', function(err, code) {
if (err || !code) {
callback(err, null);
return;
}
var ser = JSON.parse(code);
var map = me.fromObject(ser);
callback(null, map);
});
};
ResourceMapSerializer.prototype.loadFromPathSync = function(path) {
var code;
try {
code = fs.readFileSync(path, 'utf-8');
} catch (e) {
return null;
}
if (!code) {
return null;
}
var ser = JSON.parse(code);
var map = this.fromObject(ser);
return map;
};
ResourceMapSerializer.prototype.fromObject = function(ser) {
if (ser.version === this.version) {
var map = new ResourceMap();
ser.objects.forEach(function(obj) {
var type = this.typeMap[obj.type];
map.addResource(type.fromObject(obj));
}, this);
return map;
} else {
return null;
}
};
/**
* Serializes and stores a map to a given path
* @param {String} path
* @param {ResourceMap} map
* @param {Function} callback
*/
ResourceMapSerializer.prototype.storeToPath = function(path, map, callback) {
var ser = this.toObject(map);
fs.writeFile(path, JSON.stringify(ser), 'utf-8', callback);
};
ResourceMapSerializer.prototype.toObject = function(map) {
var ser = {
version: this.version,
objects: map.getAllResources().map(function(resource) {
return resource.toObject();
})
};
return ser;
};
module.exports = ResourceMapSerializer;
|
Ashwanigupta9125/code-DS-ALGO
|
Data Structures/Arrays/9. String Compression.cpp
|
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
string compressIt(string s){
char a[1000];
int j=0;
string s2;
int len = s.length();
int i;
for(i=0;i<len;){
char current = s[i];
int count=1;
while(s[i]==s[++i]){
count++;
}
s2.push_back(current);
char cnt = (char)(((int)'0')+count);
s2.push_back(cnt);
}
return s2;
}
int main(){
string s = "aaabbcddeeee";
cout<<compressIt(s);
return 0;
}
|
Arthur-San/Desenvolvimento-de-sistemas-web-III
|
Aulas/Aula16ArrayList/src/aula16arraylist/ListaCompras.java
|
/*
Criar um programa em Java que consiste em uma lista de compras:
1 - Adicionar itens na lista de compras;
2 - Consultar itens pelo seu índice;
3 - Alterar itens da Lista de compras;
4 - Exibir o tamanho da lista de compras;
5 - Remover itens da lista de compras;
6 - Classificar em ordem alfabética
7 - Limpar a lista de compras
Obs: Criar uma interface que exibe o que está acontecendo com o programa
*/
package aula16arraylist;
import java.util.ArrayList;
import java.util.Collections;
public class ListaCompras {
public static void main(String[] args) {
ArrayList<String> produtos = new ArrayList<>();
System.out.println("*****Lista de compras*****");
produtos.add("Pizza");
produtos.add("Sorvete");
produtos.add("Lasanha");
produtos.add("Água");
System.out.println(produtos); //lista de compras
//Consultar itens pelo seu índice
System.out.println("\n****Consultar itens pelo seu índice****");
System.out.println("O item consultado é: " + produtos.get(2));
//Alterar itens da Lista de compras
System.out.println("\n______Alterar itens de:______ ");
System.out.println(produtos);
System.out.println("\n______Para:______");
produtos.set(3, "Coquinha gelada");
System.out.println(produtos);
//exibir o tamanho do ArrayList
System.out.println("\nO tamanho da lista é: " + produtos.size());
//Remover itens da lista de compras
System.out.println("\n✖✖✖ Remover itens ✖✖✖");
produtos.remove(3);
System.out.println("A quantidade produtos que a minha lista tem é: " + produtos.size());
//Classificar em ordem alfabética
System.out.println("\n▷▷▷▷▷▷ ordem alfabética ◁◁◁◁◁◁");
Collections.sort(produtos);
for(String i : produtos){
System.out.println(i);
}
//limpar tudo da lista de compra
System.out.println("\n*****Removendo****");
produtos.clear();
System.out.println( produtos);
}
}
|
Sphinx-Society/kaizen-web-client
|
src/client/utils/date.js
|
<reponame>Sphinx-Society/kaizen-web-client
export const getStringFromDate = (date) => {
if (date instanceof Date === false) {
return null;
}
const yyyy = date.getFullYear();
let dd = date.getDate();
let mm = date.getMonth() + 1;
if (dd < 10) { dd = `0${dd}`; }
if (mm < 10) { mm = `0${mm}`; }
return `${dd}/${mm}/${yyyy}`;
};
export const getCalendarWeeks = (month, year) => {
if (
typeof month === 'number'
&& typeof year === 'number'
&& Number.isInteger(month)
&& Number.isInteger(year)
) {
const monthStartingColumn = new Date(year, month).getDay();
const monthLength = 32 - new Date(year, month, 32).getDate();
const minimumDaysRequired = monthStartingColumn + monthLength;
const weeks = Math.ceil(minimumDaysRequired / 7);
const monthDays = [];
const prevMonth = month > 0 ? month - 1 : 11;
const prevMonthYear = month > 0 ? year : year - 1;
const prevMonthLength = 32 - new Date(prevMonthYear, prevMonth, 32).getDate();
const nextMonth = month < 11 ? month + 1 : 0;
let date = 0;
let nextMonthDay = 1;
for (let week = 0; week < weeks; week++) {
for (let day = 0; day < 7; day++) {
if (week === 0 && day < monthStartingColumn) {
const prevMonthDay = prevMonthLength - monthStartingColumn + 1 + day;
const prevMonthDate = {
value: new Date(prevMonthYear, prevMonth, prevMonthDay).getTime(),
isOtherMonth: true,
};
if (monthDays[week]) {
monthDays[week].days.push(prevMonthDate);
} else {
monthDays[week] = { days: [prevMonthDate], id: week };
}
}
if (week === weeks - 1 && date > monthLength) {
const nextMonthDate = {
value: new Date(year, nextMonth, nextMonthDay).getTime(),
isOtherMonth: true,
};
if (monthDays[week]) {
monthDays[week].days.push(nextMonthDate);
} else {
monthDays[week] = { days: [nextMonthDate], id: week };
}
nextMonthDay += 1;
}
if ((day >= monthStartingColumn && week === 0) || (date < monthLength && week !== 0)) {
date += 1;
const actualMonthDate = {
value: new Date(year, month, date).getTime(),
isOtherMonth: false,
};
if (monthDays[week]) {
monthDays[week].days.push(actualMonthDate);
} else {
monthDays[week] = { days: [actualMonthDate], id: week };
}
if (date === monthLength) {
date += 1;
}
}
}
}
return monthDays;
}
return [];
};
|
marcus8448/Mekanism
|
Mekanism-Additions/src/main/java/mekanism/additions/client/render/entity/RenderObsidianTNTPrimed.java
|
package mekanism.additions.client.render.entity;
import javax.annotation.Nonnull;
import mekanism.additions.common.entity.EntityObsidianTNT;
import mekanism.additions.common.registries.AdditionsBlocks;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.client.render.entity.EntityRenderer;
import net.minecraft.client.render.entity.TntMinecartEntityRenderer;
import net.minecraft.client.texture.SpriteAtlasTexture;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.util.math.Vector3f;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper;
public class RenderObsidianTNTPrimed extends EntityRenderer<EntityObsidianTNT> {
public RenderObsidianTNTPrimed(EntityRenderDispatcher renderManager) {
super(renderManager);
shadowRadius = 0.5F;
}
@Override
public void render(@Nonnull EntityObsidianTNT tnt, float entityYaw, float partialTick, @Nonnull MatrixStack matrix, @Nonnull VertexConsumerProvider renderer, int light) {
matrix.push();
matrix.translate(0, 0.5, 0);
if (tnt.getFuseTimer() - partialTick + 1.0F < 10.0F) {
float f = 1.0F - (tnt.getFuseTimer() - partialTick + 1.0F) / 10.0F;
f = MathHelper.clamp(f, 0.0F, 1.0F);
f = f * f;
f = f * f;
float f1 = 1.0F + f * 0.3F;
matrix.scale(f1, f1, f1);
}
matrix.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(-90.0F));
matrix.translate(-0.5, -0.5, 0.5);
matrix.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(90.0F));
TntMinecartEntityRenderer.method_23190(AdditionsBlocks.OBSIDIAN_TNT.getBlock().getDefaultState(), matrix, renderer, light, tnt.getFuseTimer() / 5 % 2 == 0);
matrix.pop();
super.render(tnt, entityYaw, partialTick, matrix, renderer, light);
}
@Nonnull
@Override
public Identifier getEntityTexture(@Nonnull EntityObsidianTNT entity) {
return SpriteAtlasTexture.BLOCK_ATLAS_TEX;
}
}
|
LZ0211/eReader
|
node_modules/Wedge-eBooks/lib/htmlz/html.js
|
<reponame>LZ0211/eReader
function encode(str){
str = String(str) || "";
return str.replace(/&/g,"&")
.replace(/</g,"<")
.replace(/>/g,">")
.replace(/'/g,"'")
.replace(/"/g,""");
}
function html(book){
var array = [
'<html>',
' <head>',
' <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />',
` <title>${book.meta.title}</title>`,
' <style type="text/css">',
' @font-face {',
' font-family:"cnepub";',
' src:url(res:///opt/sony/ebook/FONT/tt0011m_.ttf), url(res:///tt0011m_.ttf);',
' }',
' body {',
' padding: 0%;',
' margin-top: 0%;',
' margin-bottom: 0%;',
' margin-left: 1%;',
' margin-right: 1%;',
' line-height:130%;',
' text-align: justify;',
' font-family:"cnepub", serif;',
' }',
' div {',
' margin:0px;',
' padding:0px;',
' line-height:130%;',
' text-align: justify;',
' font-family:"cnepub", serif;',
' }',
' p {',
' text-align: justify;',
' text-indent: 2em;',
' line-height:130%;',
' }',
' .cover {',
' width:100%;',
' padding:0px;',
' }',
' .center {',
' text-align: center;',
' margin-left: 0%;',
' margin-right: 0%;',
' }',
' .left {',
' text-align: center;',
' margin-left: 0%;',
' margin-right: 0%;',
' }',
' .right {',
' text-align: right;',
' margin-left: 0%;',
' margin-right: 0%;',
' }',
' .quote {',
' margin-top: 0%;',
' margin-bottom: 0%;',
' margin-left: 1em;',
' margin-right: 1em;',
' text-align: justify;',
' font-family:"cnepub", serif;',
' }',
' h1 {',
' line-height:130%;',
' text-align: center;',
' font-weight:bold;',
' font-size:xx-large;',
' }',
' h2 {',
' line-height:130%;',
' text-align: center;',
' font-weight:bold;',
' font-size:x-large;',
' }',
' h3 {',
' line-height:130%;',
' text-align: center;',
' font-weight:bold;',
' font-size:large;',
' }',
' h4 {',
' line-height:130%;',
' text-align: center;',
' font-weight:bold;',
' font-size:medium;',
' }',
' h5 {',
' line-height:130%;',
' text-align: center;',
' font-weight:bold;',
' font-size:small;',
' }',
' h6 {',
' line-height:130%;',
' text-align: center;',
' font-weight:bold;',
' font-size:x-small;',
' }',
' </style>',
' </head>',
' <body>',
' <div class="metadata">',
' <div style="text-align:center">',
` <img class="cover" src="data:image/jpeg;base64,${book.meta.cover}"/>`,
' </div>',
` <h1>${book.meta.title}</h1>`,
` <h2>${book.meta.author}</h2>`,
' <div class="brief">',
' <b>【简介】</b>'
];
encode(book.meta.brief).split('\n').forEach(line=>array.push(
` <p>${line}</p>`
));
array.push(' </div>');
array.push(' </div>');
array.push(' <div class="list">');
array.push(' <ul>');
book.list.forEach(chapter=>array.push(
` <li><a href="#${chapter.id}">${chapter.title}</a></li>`
));
array.push(' </ul>');
array.push(' </div>');
book.list.forEach(chapter=>{
array.push(` <div class="chapter" id="${chapter.id}" name="${chapter.id}">`);
array.push(` <h3 class="title">${chapter.title}</h3>`);
array.push(' <div id="content">');
encode(chapter.content).split('\n').forEach(line=>array.push(` <p>${line}</p>`));
array.push(' </div>');
array.push(' </div>');
});
array.push(' </body>');
array.push('</html>');
return array.join('\n')
}
module.exports = function (book,fn){
fn(html(book));
}
|
targetsm/dace
|
samples/simple/ddot.py
|
<reponame>targetsm/dace
# Copyright 2019-2020 ETH Zurich and the DaCe authors. All rights reserved.
from __future__ import print_function
import argparse
import dace
import numpy as np
N = dace.symbol("N")
@dace.program
def dot(A: dace.float32[N], B: dace.float32[N], out: dace.float64[1]):
@dace.map
def product(i: _[0:N]):
a << A[i]
b << B[i]
o >> out(1, lambda x, y: x + y)
o = a * b
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("N", type=int, nargs="?", default=64)
args = vars(parser.parse_args())
# Create two numpy ndarrays of size 1
out_AB = dace.scalar(dace.float64)
out_AA = dace.scalar(dace.float64)
N.set(args["N"])
print('Dot product %d' % (N.get()))
A = np.random.rand(N.get()).astype(np.float32)
B = np.random.rand(N.get()).astype(np.float32)
out_AB[0] = np.float64(0)
out_AA[0] = np.float64(0)
cdot = dot.compile(A, B, out_AB)
cdot(A=A, B=B, out=out_AB, N=N)
# To allow reloading the SDFG code file with the same name
del cdot
cdot_self = dot.compile(A, A, out_AA)
cdot_self(A=A, B=A, out=out_AA, N=N)
diff_ab = np.linalg.norm(np.dot(A, B) - out_AB) / float(N.get())
diff_aa = np.linalg.norm(np.dot(A, A) - out_AA) / float(N.get())
print("Difference (A*B):", diff_ab)
print("Difference (A*A):", diff_aa)
exit(0 if (diff_ab <= 1e-5 and diff_aa <= 1e-5) else 1)
|
Ruil1n/themis
|
src/main/java/dangod/themis/model/po/common/Inform.java
|
package dangod.themis.model.po.common;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Calendar;
@Entity
@Table(name = "common_inform")
public class Inform {
@Id
@GeneratedValue
private Long id;
@Column(length = 100)
private String title;
@Column(length = 6000)
private String content;
private Timestamp date;
private Timestamp modified;
@ManyToOne(fetch=FetchType.EAGER, cascade= CascadeType.DETACH)
@JoinColumn(name="user_id",nullable=true)
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
public Timestamp getModified() {
return modified;
}
public void setModified(Timestamp modified) {
this.modified = modified;
}
public void updateDate() {
this.modified = new Timestamp(Calendar.getInstance().getTime().getTime());
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Inform(String title, String content, User user) {
this.title = title;
this.content = content;
this.date = new Timestamp(Calendar.getInstance().getTime().getTime());
this.modified = this.date;
this.user = user;
}
public Inform() {
this.date = new Timestamp(Calendar.getInstance().getTime().getTime());
this.modified = this.date;
}
}
|
tobiasheine/BitcoinWatcher
|
wear/src/main/java/eu/tobiasheine/bitcoinwatcher/price_sync/Storage.java
|
<reponame>tobiasheine/BitcoinWatcher
package eu.tobiasheine.bitcoinwatcher.price_sync;
import android.content.Context;
import android.content.SharedPreferences;
import eu.tobiasheine.bitcoinwatcher.core.domain.BitcoinPrice;
import eu.tobiasheine.bitcoinwatcher.core.domain.Currency;
public class Storage {
private static final String KEY_CURRENCY = "CURRENCY";
private static final String KEY_PRICE = "PRICE";
private final SharedPreferences sharedPreferences;
public Storage(Context context) {
sharedPreferences = context.getSharedPreferences("Bitcoin Watcher Watchface", Context.MODE_PRIVATE);
}
public void storePrice(BitcoinPrice bitcoinPrice) {
sharedPreferences.edit().putString(KEY_CURRENCY, bitcoinPrice.currency.name()).apply();
sharedPreferences.edit().putFloat(KEY_PRICE, bitcoinPrice.rate).apply();
}
public Currency getCurrency() {
return Currency.valueOf(sharedPreferences.getString(KEY_CURRENCY, "EUR"));
}
public float getPrice() {
return sharedPreferences.getFloat(KEY_PRICE, -1f);
}
}
|
scm-manager/scm-review-plugin
|
src/main/java/com/cloudogu/scm/review/comment/api/MentionMapper.java
|
<reponame>scm-manager/scm-review-plugin<gh_stars>1-10
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.cloudogu.scm.review.comment.api;
import com.cloudogu.scm.review.comment.service.BasicComment;
import sonia.scm.user.DisplayUser;
import sonia.scm.user.UserDisplayManager;
import javax.inject.Inject;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MentionMapper {
private UserDisplayManager userDisplayManager;
private static final Pattern mentionPattern =
Pattern.compile("@\\[([A-Za-z0-9\\.\\-_][A-Za-z0-9\\.\\-_@]*)]");
@Inject
public MentionMapper(UserDisplayManager userDisplayManager) {
this.userDisplayManager = userDisplayManager;
}
Set<DisplayUser> mapMentions(Set<String> userIds) {
Set<DisplayUser> mentions = new HashSet<>();
if (userIds != null) {
for (String id : userIds) {
Optional<DisplayUser> displayUser = userDisplayManager.get(id);
displayUser.ifPresent(mentions::add);
}
}
return mentions;
}
public Set<String> extractMentionsFromComment(String comment) {
Set<String> mentions = new HashSet<>();
Matcher matcher = mentionPattern.matcher(comment);
while (matcher.find()) {
String matchingId = matcher.group(1);
Optional<DisplayUser> displayUser = userDisplayManager.get(matchingId);
displayUser.ifPresent(user -> mentions.add(user.getId()));
}
return mentions;
}
public BasicComment parseMentionsUserIdsToDisplayNames(BasicComment rootComment) {
BasicComment comment = rootComment.clone();
for (String mentionUserId : rootComment.getMentionUserIds()) {
Optional<DisplayUser> user = userDisplayManager.get(mentionUserId);
user.ifPresent(displayUser -> comment.setComment(comment.getComment().replaceAll("\\[" + mentionUserId + "]", displayUser.getDisplayName())));
}
return comment;
}
}
|
itssundeep/presto
|
presto-parquet/src/main/java/com/facebook/presto/parquet/writer/ColumnChunk.java
|
<filename>presto-parquet/src/main/java/com/facebook/presto/parquet/writer/ColumnChunk.java
/*
* 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.facebook.presto.parquet.writer;
import com.facebook.presto.parquet.writer.levels.DefinitionLevelIterable;
import com.facebook.presto.parquet.writer.levels.RepetitionLevelIterable;
import com.facebook.presto.spi.block.Block;
import com.google.common.collect.ImmutableList;
import java.util.List;
import static java.util.Objects.requireNonNull;
public class ColumnChunk
{
private final Block block;
private final List<DefinitionLevelIterable> definitionLevelIterables;
private final List<RepetitionLevelIterable> repetitionLevelIterables;
public ColumnChunk(Block block)
{
this(block, ImmutableList.of(), ImmutableList.of());
}
public ColumnChunk(Block block, List<DefinitionLevelIterable> definitionLevelIterables, List<RepetitionLevelIterable> repetitionLevelIterables)
{
this.block = requireNonNull(block, "block is null");
this.definitionLevelIterables = ImmutableList.copyOf(definitionLevelIterables);
this.repetitionLevelIterables = ImmutableList.copyOf(repetitionLevelIterables);
}
public List<DefinitionLevelIterable> getDefinitionLevelIterables()
{
return definitionLevelIterables;
}
public List<RepetitionLevelIterable> getRepetitionLevelIterables()
{
return repetitionLevelIterables;
}
public Block getBlock()
{
return block;
}
}
|
npmcomponent/josdejong-mathjs
|
test/function/utils/clone.test.js
|
var assert = require('assert'),
error = require('../../../lib/error/index'),
math = require('../../../index')();
describe('clone', function() {
it('should clone a number', function() {
var a = 1;
var b = math.clone(a);
a = 2;
assert.strictEqual(b, 1);
});
it('should throw an error on wrong number of arguments', function() {
assert.throws (function () {math.clone()}, error.ArgumentsError);
assert.throws (function () {math.clone(2, 4)}, error.ArgumentsError);
});
it('should clone a bignumber', function() {
var a = math.bignumber('2.3e500');
var b = math.clone(a);
assert.deepEqual(a, b);
assert.notStrictEqual(a,b);
});
it('should clone a string', function() {
var a = 'hello world';
var b = math.clone(a);
a = 'bye!';
assert.strictEqual(a, 'bye!');
assert.strictEqual(b, 'hello world');
});
it('should clone a complex number', function() {
var a = math.complex(2, 3);
var b = math.clone(a);
assert.notEqual(a, b);
a.re = 5;
assert.strictEqual(a.toString(), '5 + 3i');
assert.strictEqual(b.toString(), '2 + 3i');
});
it('should clone a unit', function() {
var a = math.unit('5mm');
var b = math.clone(a);
a.value = 10;
assert.equal(a.toString(), '10 m');
assert.equal(b.toString(), '5 mm');
});
it('should clone an array', function() {
var a = [1,2,[3,4]];
var b = math.clone(a);
a[2][1] = 5;
assert.equal(b[2][1], 4);
});
it('should clone a matrix', function() {
var a = math.matrix([[1, 2], [3, 4]]);
var b = math.clone(a);
a.valueOf()[0][0] = 5;
assert.equal(b.valueOf()[0][0], 1);
a = math.matrix([1, 2, new math.complex(2, 3), 4]);
b = math.clone(a);
a.valueOf()[2].re = 5;
assert.equal(b.valueOf()[2].re, 2);
});
});
|
mr-bammby/42_WB_2022_Minishell
|
srcs/ft_utils_join.c
|
<reponame>mr-bammby/42_WB_2022_Minishell
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_utils_join.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbanfi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/26 13:04:50 by dbanfi #+# #+# */
/* Updated: 2022/02/26 15:25:04 by dbanfi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../incl/minishell.h"
/**
@brief Joins strings s1 and s2, frees s1.
@param s1: First string to join.
@param s2: Second string to join.
@return Returns joined string.
*/
char *ft_strjoin_with_free(char *s1, char const *s2)
{
char *return_s;
if (!s1 || !s2)
return (NULL);
return_s = ft_calloc(sizeof(char) * (ft_strlen(s1) + ft_strlen(s2)) + 1, 1);
if (return_s == NULL)
return (NULL);
ft_memcpy(return_s, s1, ft_strlen(s1));
ft_memcpy(return_s + ft_strlen(s1), s2, ft_strlen(s2));
if (s1 != NULL)
free (s1);
s1 = NULL;
return (return_s);
}
/**
@brief Joins strings s1 and s2, both strings.
@param s1: First string to join.
@param s2: Second string to join.
@return Returns joined string.
*/
char *ft_strjoin_with_dfree(char *s1, char *s2)
{
char *return_s;
if (!s1 || !s2)
return (NULL);
return_s = ft_calloc(sizeof(char) * (ft_strlen(s1) + ft_strlen(s2)) + 1, 1);
if (return_s == NULL)
return (NULL);
ft_memcpy(return_s, s1, ft_strlen(s1));
ft_memcpy(return_s + ft_strlen(s1), s2, ft_strlen(s2));
if (s1 != NULL)
free (s1);
s1 = NULL;
if (s2 != NULL)
free (s2);
s2 = NULL;
return (return_s);
}
/**
@brief Joins strings s1 and s2, frees s2.
@param s1: First string to join.
@param s2: Second string to join.
@return Returns joined string.
*/
char *ft_strjoin_with_scnd_free(char *s1, char *s2)
{
char *return_s;
if (!s1 || !s2)
return (NULL);
return_s = ft_calloc(sizeof(char) * (ft_strlen(s1) + ft_strlen(s2)) + 1, 1);
if (return_s == NULL)
return (NULL);
ft_memcpy(return_s, s1, ft_strlen(s1));
ft_memcpy(return_s + ft_strlen(s1), s2, ft_strlen(s2));
if (s2 != NULL)
free (s2);
s2 = NULL;
return (return_s);
}
|
MacHundt/e4_MP
|
src/impl/JungGraphTEST1.java
|
package impl;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import org.piccolo2d.extras.pswing.PSwing;
import org.piccolo2d.extras.pswing.PSwingCanvas;
import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
import edu.uci.ics.jung.algorithms.layout.KKLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.TestGraphs;
import edu.uci.ics.jung.visualization.GraphZoomScrollPane;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
public class JungGraphTEST1 extends JApplet {
private PSwingCanvas canvasSwing;
public void start() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setUpView();
}
});
}
private void setUpView() {
// Container content = getContentPane();
// content.add(new GraphZoomScrollPane(vv));
// JPanel south = new JPanel();
// JPanel grid = new JPanel(new GridLayout(2,1));
// grid.add(scramble);
// grid.add(groupVertices);
// south.add(grid);
// south.add(eastControls);
// JPanel p = new JPanel();
// p.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
// p.add(gm.getModeComboBox());
// south.add(p);
// content.add(south, BorderLayout.SOUTH);
canvasSwing = new PSwingCanvas();
// canvasSwing.removeInputEventListener(canvasSwing.getZoomEventHandler());
// PMouseWheelEventHandler wheelHandler = new PMouseWheelEventHandler();
// canvasSwing.addInputEventListener(wheelHandler);
Graph<String, Number> ig = TestGraphs.createTestGraph(true);
AbstractLayout layout = new KKLayout(ig);
VisualizationViewer<String, Number> vv = new VisualizationViewer<>(layout);
vv.setBackground(Color.WHITE);
DefaultModalGraphMouse<Number, Number> gm = new DefaultModalGraphMouse<Number, Number>();
vv.setGraphMouse(gm);
vv.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
e.getComponent().setBackground(
(e.getComponent().getBackground().equals(Color.YELLOW) ? Color.white : Color.YELLOW));
}
});
GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
gzsp.setPreferredSize(new Dimension(200, 200));
// graphComponentPanel.add(gzsp);
PSwing pNodeGraph1 = new PSwing(gzsp);
canvasSwing.getLayer().addChild(pNodeGraph1);
ig = TestGraphs.createTestGraph(false);
layout = new KKLayout<>(ig);
vv = new VisualizationViewer<>(layout);
vv.setBackground(Color.WHITE);
vv.setGraphMouse(gm);
vv.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
e.getComponent().setBackground(
(e.getComponent().getBackground().equals(Color.YELLOW) ? Color.white : Color.YELLOW));
}
});
GraphZoomScrollPane gzsp2 = new GraphZoomScrollPane(vv);
gzsp2.setPreferredSize(new Dimension(200, 200));
PSwing pNodeGraph2 = new PSwing(gzsp2);
pNodeGraph2.setOffset(205, 0);
canvasSwing.getLayer().addChild(pNodeGraph2);
// graphComponentPanel.add(gzsp2);
ig = TestGraphs.getOneComponentGraph();
layout = new KKLayout<>(ig);
vv = new VisualizationViewer<>(layout);
vv.setBackground(Color.WHITE);
vv.setGraphMouse(gm);
vv.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
e.getComponent().setBackground(
(e.getComponent().getBackground().equals(Color.YELLOW) ? Color.white : Color.YELLOW));
}
});
GraphZoomScrollPane gzsp3 = new GraphZoomScrollPane(vv);
gzsp3.setPreferredSize(new Dimension(200, 200));
PSwing pNodeGraph3 = new PSwing(gzsp3);
pNodeGraph3.setOffset(410, 0);
canvasSwing.getLayer().addChild(pNodeGraph3);
// graphComponentPanel.add(gzsp3);
add(canvasSwing);
validate();
}
}
|
akshaybahadur21/Emancipitaion-of-Apache-Spark
|
Basics/src/main/java/SparkSQL/_09_DataFrames.java
|
package SparkSQL;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.DataTypes;
import static org.apache.spark.sql.functions.*;
import java.util.Scanner;
public class _09_DataFrames {
/**
* DataFrames API : Set of Java APIs for Spark SQL
* Alternatives to traditional SQL.
* SparkSQL has 3 sets of API
* - SparkSQL : Processing using traditional SQL
* - DataFrames API : Java APIs instead of traditional SQL (Dataset<Rows>)
* - Datasets API : Identical to DataFrames API but it creates Dataset<CUSTOM_OBJECTS>
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
System.setProperty("hadoop.home.dir", "C:\\Akshay GitHub\\winutils-master\\hadoop-2.7.1");
Logger.getLogger("org.apache").setLevel(Level.WARN);
SparkSession spark = SparkSession.builder().appName("Spark SQL").master("local[*]")
.config("spark.sql.warehouse", "file:///C:/Akshay Github/tmp")
.getOrCreate();
/**
* We will use the example from _08_Ordering.java and convert the SparkSQL to Spark DataFrame
* */
Dataset<Row> dataset = spark.read().option("header", true).csv("src\\main\\resources\\biglog.txt.txt");
dataset.createOrReplaceTempView("logging_big_table");
Dataset<Row> result = spark.sql("SELECT level, date_format(datetime,'MMMM') AS month, count(1) FROM logging_big_table GROUP BY month, level ORDER BY cast(first(date_format(datetime, 'M')) AS int) , level");
result.show(60, false);
// dataset.selectExpr("level", "date_format(datetime,'MMMM') as month"); We can use this technique but this is not purely Java sp we will skip it for now
dataset = dataset.select(col("level"),
date_format(col("datetime"),"MMMM").alias("month"),
date_format(col("datetime"),"M").alias("month_num").cast(DataTypes.IntegerType));
/**
* Now we want to group by level and month.
* dataset.groupBy(col("level"), col("month")) return a RelationalGroupedDatase<Row> and not Dataset<Row>.
* To fix, we have to perform aggregation on columns which are not grouped.
* */
dataset = dataset.groupBy(col("level"), col("month"), col("month_num")).count();
dataset = dataset.orderBy(col("month_num"), col("level"));
dataset.show(60, false);
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
spark.close();
}
}
|
teddywen/leetcode
|
leetcode_395.go
|
/*
https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters/
*/
package main
import "fmt"
func main() {
var (
s = "aaabb"
k = 3
//s = "ababbc"
//k = 2
//s = "ababacb"
//k = 3
)
fmt.Printf("%d", longestSubstring(s, k))
}
// 分治
func longestSubstring(s string, k int) int {
return findLSS(0, len(s)-1, k, s)
}
func findLSS(left, right, k int, s string) int {
if left > right {
return 0
}
var cntDict = make(map[byte]int)
for i := left; i <= right; i++ {
cntDict[s[i]]++
}
for i := left; i <= right; i++ {
if cntDict[s[i]] < k {
return max395(findLSS(left, i-1, k, s), findLSS(i+1, right, k, s))
}
}
return right - left + 1
}
// 滑动窗口
//func longestSubstring(s string, k int) int {
// var res int
//
// // 自己制造限制,让其满足滑窗条件
// for t := 1; t <= 26; t++ {
// var (
// left, right, spec, bad int
// cntDict = make(map[byte]int)
// )
//
// for right < len(s) {
// c := s[right]
// right++
//
// if cntDict[c] == 0 {
// spec++
// bad++
// }
// cntDict[c]++
// if cntDict[c] == k {
// bad--
// }
//
// for left < right && spec > t {
// c2 := s[left]
// left++
//
// if cntDict[c2] == k {
// bad++
// }
// if cntDict[c2] > 0 {
// cntDict[c2]--
// if cntDict[c2] == 0 {
// bad--
// spec--
// }
// }
// }
//
// if bad == 0 {
// res = max395(res, right-left)
// }
// }
// }
//
// return res
//}
func max395(x, y int) int {
if x > y {
return x
} else {
return y
}
}
|
ngageoint/mrgeo
|
mrgeo-dataprovider/mrgeo-dataprovider-mbvectortiles/src/main/java/org/mrgeo/data/vector/mbvectortiles/MbVectorTilesRecordReader.java
|
<reponame>ngageoint/mrgeo<filename>mrgeo-dataprovider/mrgeo-dataprovider-mbvectortiles/src/main/java/org/mrgeo/data/vector/mbvectortiles/MbVectorTilesRecordReader.java<gh_stars>100-1000
/*
* Copyright 2009-2017. DigitalGlobe, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.mrgeo.data.vector.mbvectortiles;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.mrgeo.data.vector.FeatureIdWritable;
import org.mrgeo.geometry.*;
import org.mrgeo.mapbox.vector.tile.VectorTile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.zip.GZIPInputStream;
public class MbVectorTilesRecordReader extends RecordReader<FeatureIdWritable, Geometry>
{
private static final int maxAllowableZoom = 32;
private MbVectorTilesSettings dbSettings;
private long offset;
private long limit;
private int zoomLevel;
private long currIndex;
private SQLiteConnection conn;
private SQLiteStatement tileStmt;
// private double left;
// private double bottom;
private WritableGeometry currGeom;
private FeatureIdWritable currKey = new FeatureIdWritable();
private Iterator<VectorTile.Tile.Layer> layerIter = null;
private Iterator<VectorTile.Tile.Feature> featureIter = null;
private VectorTile.Tile.Layer currLayer;
private long tileColumn = -1;
private long tileRow = -1;
public MbVectorTilesRecordReader(MbVectorTilesSettings dbSettings)
{
this.dbSettings = dbSettings;
}
// @SuppressFBWarnings(value = {"SQL_INJECTION_JDBC", "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING"}, justification = "User supplied queries are a requirement")
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException
{
if (!(split instanceof MbVectorTilesInputSplit)) {
throw new IOException("Expected an instance of PgInputSplit");
}
offset = ((MbVectorTilesInputSplit) split).getOffset();
limit = ((MbVectorTilesInputSplit) split).getLimit();
zoomLevel = ((MbVectorTilesInputSplit) split).getZoomLevel();
currIndex = (offset < 0) ? 0 : offset - 1;
try
{
conn = MbVectorTilesDataProvider.getDbConnection(dbSettings,
context.getConfiguration());
// If the offset is < 0, then there is only one partition, so no need
// for a limit query.
String query ="SELECT tile_column, tile_row, tile_data FROM tiles WHERE zoom_level=? order by zoom_level, tile_column, tile_row";
if (offset >= 0 && limit >= 0) {
query = query + " LIMIT ? OFFSET ?";
}
tileStmt = conn.prepare(query);
tileStmt.bind(1, zoomLevel);
if (offset >= 0 && limit >= 0) {
tileStmt.bind(2, limit);
tileStmt.bind(3, offset);
}
}
catch (SQLiteException e)
{
throw new IOException("Could not open database.", e);
}
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException
{
// Loops until it finds the next geometry. If the feature iterator has
// been created and has a feature available, process it. If not, then
// see if the layer iterator has been created and has an available layer
// to process. If not, then see if there is another tile record
// available to process
while (true) {
if (featureIter != null && featureIter.hasNext() && currLayer != null) {
// We got a feature, convert it to MrGeo Geometry and return
currGeom = geometryFromFeature(featureIter.next(), tileColumn, tileRow, currLayer);
currIndex++;
return true;
} else {
// We're done processing features in the current layer, see if
// there are any more layers in the current tile.
featureIter = null;
if (layerIter != null && layerIter.hasNext()) {
currLayer = layerIter.next();
if (currLayer != null) {
featureIter = currLayer.getFeaturesList().iterator();
// We got another layer in the current tile, continue so we can
// process the features in this layer.
}
}
else {
// There are no layers remaining in the current tile. See if there
// are more tiles to process.
layerIter = null;
try {
if (tileStmt == null || !tileStmt.step()) {
return false;
}
// Read the blob for the tile and decode the protobuf according to
// the vector tiles spec. When converting to Geometry, I'll have to
// re-project from the mercator (in the vector tiles) to WGS-84 that
// we use in our Geometry. I also need to grab all of the attribute
// values from the feature.
tileColumn = tileStmt.columnLong(0);
tileRow = tileStmt.columnLong(1);
// The following was taken from tippecanoe
tileRow = (1L << zoomLevel) - 1 - tileRow;
// System.out.println("Processing tile x = " + tileColumn + ", y = " + tileRow);
byte[] rawTileData = tileStmt.columnBlob(2);
byte[] tileData = null;
if (isGZIPStream(rawTileData)) {
tileData = gunzip(rawTileData);
}
else {
tileData = rawTileData;
}
VectorTile.Tile tile = VectorTile.Tile.parseFrom(tileData);
layerIter = tile.getLayersList().iterator();
// Compute spatial characteristics of this tile and store the
// results (used later to compute points for geometries).
// calculate bounds
// Bounds wldwgs84 = new Bounds(-180.0, -85.06, 180.0, 85.06);
//// Bounds wldwgs84 = Bounds.WORLD;
//
//// SpatialReference sourceSrs = new SpatialReference();
//// sourceSrs.SetFromUserInput("EPSG:4326");
//// SpatialReference destSrs = new SpatialReference();
//// destSrs.SetFromUserInput("EPSG:3857");
//// CoordinateTransformation tx = new CoordinateTransformation(sourceSrs, destSrs);
//// double[] leftTop = tx.TransformPoint(wldwgs84.w, wldwgs84.n);
//// double[] rightBottom = tx.TransformPoint(wldwgs84.e, wldwgs84.s);
//// double l = leftTop[0];
//// double t = leftTop[1];
//// double r = rightBottom[0];
//// double b = rightBottom[1];
// double l = -180.0;
// double t = 90.0;
// double r = 180.0;
// double b = -90.0;
//
// Bounds bounds = new Bounds(l, b, r, t);
//// Bounds bounds = new Bounds(l, l, -l, -l);
//
// double w = bounds.width();
// double h = bounds.height();
//
// double scale = Math.pow(2, zoomLevel);
//
// double tw = w / scale;
// double th = h / scale;
//
// bottom = bounds.s + (tileRow * th);
// left = bounds.w + (tileColumn * tw);
// Continue processing against the new layerIter
}
catch(SQLiteException e) {
throw new IOException("Error getting next key/value pair", e);
}
}
}
}
}
public static boolean isGZIPStream(byte[] bytes)
{
return bytes[0] == (byte) GZIPInputStream.GZIP_MAGIC
&& bytes[1] == (byte) (GZIPInputStream.GZIP_MAGIC >>> 8);
}
private static byte[] gunzip(byte[] bytes) throws IOException
{
GZIPInputStream is = new GZIPInputStream(new ByteArrayInputStream(bytes));
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int count = is.read(buf, 0, buf.length);
while (count >= 0) {
os.write(buf, 0, count);
count = is.read(buf, 0, buf.length);
}
os.close();
is.close();
return os.toByteArray();
}
// private static byte[] gzip(byte[] input) throws Exception
// {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// GZIPOutputStream gzip = new GZIPOutputStream(bos);
// gzip.write(input);
// gzip.close();
// return bos.toByteArray();
// }
// public static byte[] decompress(byte[] data) throws IOException, DataFormatException
// {
// Inflater inflater = new Inflater(true);
// inflater.setInput(data);
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
// try {
// byte[] buffer = new byte[1024];
// while (!inflater.finished()) {
// int count = inflater.inflate(buffer);
// outputStream.write(buffer, 0, count);
// }
// }
// finally {
// outputStream.close();
// }
// return outputStream.toByteArray();
// }
private double tile2lon(long x, int zoom)
{
long n = 1L << zoom;
return 360.0 * x / n - 180.0;
}
private double tile2lat(long y, int zoom)
{
long n = 1L << zoom;
return Math.atan(Math.sinh(Math.PI* (1 - 2.0 * y / n))) * 180.0 / Math.PI;
}
private WritableGeometry geometryFromFeature(VectorTile.Tile.Feature feature,
long tilex,
long tiley,
VectorTile.Tile.Layer layer)
{
if (!feature.hasType()) {
return null;
}
int cursorx = 0;
int cursory = 0;
List<Point> points = new ArrayList<Point>();
int ndx = 0;
// final int maxAllowableZoom = 32;
final int extent = layer.getExtent();
List<List<Point>> geometries = new ArrayList<List<Point>>();
while (ndx < feature.getGeometryCount()) {
int f = feature.getGeometry(ndx);
ndx++;
int cid = f & 0x07;
int count = f >> 3;
for (int c = 0; c < count; c++) {
if (cid == 1) {
// MoveTo
int dx_bitwise_result = (feature.getGeometry(ndx) >> 1) ^ (-(feature.getGeometry(ndx) & 1));
cursorx += dx_bitwise_result;
ndx++;
int dy_bitwise_result = (feature.getGeometry(ndx) >> 1) ^ (-(feature.getGeometry(ndx) & 1));
cursory += dy_bitwise_result;
// System.out.println("px = " + cursorx);
// System.out.println("py = " + cursory);
ndx++;
if (!points.isEmpty()) {
geometries.add(points);
}
points = new ArrayList<Point>();
Point pt = computePoint(tilex, tiley, extent, cursorx, cursory);
points.add(pt);
}
else if (cid == 2) {
// LineTo
int dx_bitwise_result = (feature.getGeometry(ndx) >> 1) ^ (-(feature.getGeometry(ndx) & 1));
cursorx += dx_bitwise_result;
ndx++;
int dy_bitwise_result = (feature.getGeometry(ndx) >> 1) ^ (-(feature.getGeometry(ndx) & 1));
cursory += dy_bitwise_result;
ndx++;
Point pt = computePoint(tilex, tiley, extent, cursorx, cursory);
points.add(pt);
}
else if (cid == 7) {
// ClosePath
points.add(points.get(0));
geometries.add(points);
points = new ArrayList<Point>();
}
}
}
if (!points.isEmpty()) {
geometries.add(points);
}
WritableGeometry geom = null;
if (feature.getType() == VectorTile.Tile.GeomType.POLYGON) {
// The first geometry from the vector tile is the outer ring of
// the polygon, and each subsequent geometry is an inner ring
WritablePolygon polygon = GeometryFactory.createPolygon(geometries.get(0));
geom = polygon;
for (int i=1; i < geometries.size(); i++) {
WritableLinearRing ring = GeometryFactory.createLinearRing();
ring.setPoints(geometries.get(i));
polygon.addInteriorRing(ring);
}
}
else if (feature.getType() == VectorTile.Tile.GeomType.LINESTRING) {
if (geometries.size() > 1) {
WritableGeometryCollection geoms = GeometryFactory.createGeometryCollection();
geom = geoms;
for (List<Point> g: geometries) {
WritableLineString lineString = GeometryFactory.createLineString();
lineString.setPoints(g);
geoms.addGeometry(lineString);
}
}
else {
WritableLineString lineString = GeometryFactory.createLineString();
geom = lineString;
lineString.setPoints(geometries.get(0));
}
}
else if (feature.getType() == VectorTile.Tile.GeomType.POINT) {
Point p = geometries.get(0).get(0);
geom = GeometryFactory.createPoint(p.getX(), p.getY());
}
// Assign attributes to Geometry
Map<String, String> tags = new HashMap<String, String>();
if (geom != null) {
boolean isKey = true;
String tagKey = "";
for (int tagIndex : feature.getTagsList()) {
if (isKey) {
tagKey = layer.getKeys(tagIndex);
}
else {
VectorTile.Tile.Value v = layer.getValues(tagIndex);
String value = null;
if (v.hasBoolValue()) {
value = Boolean.toString(v.getBoolValue());
}
else if (v.hasDoubleValue()) {
value = Double.toString(v.getDoubleValue());
}
else if (v.hasFloatValue()) {
value = Float.toString(v.getFloatValue());
}
else if (v.hasIntValue()) {
value = Long.toString(v.getIntValue());
}
else if (v.hasSintValue()) {
value = Long.toString(v.getSintValue());
}
else if (v.hasStringValue()) {
value = v.getStringValue();
}
else if (v.hasUintValue()) {
value = Long.toString(v.getUintValue());
}
if (value != null) {
tags.put(tagKey, value);
}
}
isKey = !isKey;
}
}
if (geom != null) {
geom.setAttributes(tags);
}
return geom;
}
private Point computePoint(long tilex, long tiley, int extent, int cursorx, int cursory)
{
// From tippecanoe converting to GeoJSON (in write_json.cpp)
long scale = 1L << (maxAllowableZoom - zoomLevel);
long wx = scale * tilex + (scale / extent) * cursorx;
long wy = scale * tiley + (scale / extent) * cursory;
// System.out.println("wx = " + wx);
// System.out.println("wy = " + wy);
double lat = tile2lat(wy, maxAllowableZoom);
double lon = tile2lon(wx, maxAllowableZoom);
return GeometryFactory.createPoint(lon, lat);
}
@Override
public FeatureIdWritable getCurrentKey() throws IOException, InterruptedException
{
currKey.set(currIndex);
return currKey;
}
@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "Null return value is ok")
@Override
public Geometry getCurrentValue() throws IOException, InterruptedException
{
return currGeom;
}
@Override
public float getProgress() throws IOException, InterruptedException
{
return (float)(currIndex + 1 - offset) / (float)limit;
}
@Override
public void close() throws IOException
{
if (tileStmt != null) {
tileStmt.dispose();
tileStmt = null;
}
if (conn != null) {
conn.dispose();
conn = null;
}
}
}
|
bio-hpc/metascreener
|
MetaScreener/external_sw/mgltools/MGLToolsPckgs/DejaVu/ShadowMap.py
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 1 17:00:56 2014
@author: ludo
"""
#import the shader
from opengltk.OpenGL.GL import *
from opengltk.extent import _gllib,_glextlib
from opengltk.extent._glextlib import *
from opengltk.OpenGL.GLU import gluPerspective, gluPickMatrix, gluUnProject, gluErrorString, gluLookAt
#for now use the simple shader for shadow
from DejaVu.shaders.shaderShadow import fshadow,pcf_fshadow, vshadow
GL_DEPTH_COMPONENT32=0x81A7
import numpy
from numpy import matrix
import math
class Shadow:
def __init__(self,viewer=None, camera=None ,light=None):
self.light=light
self.viewer=viewer
self.camera=camera
# self.light_direction = self.light.direction
self.width=1024#self.camera.width # 2048
self.height=1024#self.camera.height #
self.uniforms={}
self.shadow_depthtextureName=None
self.initialized = False
self.shader_initialized = False
# self.setupFBO()
# self.fragmentShaderCode=frag_shadow_gem
# self.vertexShaderCode=vert_shadow_gem
self.fragmentShaderCode=pcf_fshadow#fshadow
self.vertexShaderCode=vshadow
self.lookAt = numpy.zeros(3)
self.lookFrom = numpy.zeros(3)#self.camera.far
self.cam_model = numpy.eye(4)
self.distance = 100.0
self.near = 0.1
self.far = self.camera.far*2.0#too far for orthographic
self.bias = numpy.array([
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0],'f');
self.distance = self.camera.far
self.d=0
def setLight(self,light):
self.light=light
nc = numpy.sqrt(numpy.add.reduce(self.camera.lookFrom*self.camera.lookFrom))
v = self.camera.lookAt + numpy.array(self.light.direction)[:3]
nv = numpy.sqrt(numpy.add.reduce(v*v))
v = (v/nv)*self.distance#self.light.length
self.lookAt = self.camera.lookAt#numpy.array(self.light.direction)[:3]
self.lookFrom = v#numpy.array(self.light.direction)[:3]*-self.camera.far#self.distance#self.camera.far#self.camera.far
aspect = self.width / float(self.height)
fov2 = (45.0*math.pi) / 360.0 # fov/2 in radian
self.d = self.near + (self.far - self.near)*0.5
# d = self.light.length
self.top = self.d*math.tan(fov2)
self.bottom = -self.top
self.right = aspect*self.top
self.left = -self.right
#projection ? this actually the view matrix...
self.lightRot = numpy.array(self.getLookAtMatrix(self.lookFrom,self.lookAt,numpy.array([0.,1.,0.])),'f').flatten()
# print "setLight",self.lightRot#,self.lightView
def setShader(self,):
self.program=None
f = _glextlib.glCreateShader(_glextlib.GL_FRAGMENT_SHADER)
v = _glextlib.glCreateShader(_glextlib.GL_VERTEX_SHADER)
lStatus = 0x7FFFFFFF
_glextlib.glShaderSource(v, 1, self.vertexShaderCode, lStatus)
_glextlib.glCompileShader(v)
_glextlib.glShaderSource(f, 1, self.fragmentShaderCode, lStatus)
_glextlib.glCompileShader(f)
lStatus1 = _glextlib.glGetShaderiv(f, _glextlib.GL_COMPILE_STATUS, lStatus )
lStatus2 = _glextlib.glGetShaderiv(v, _glextlib.GL_COMPILE_STATUS, lStatus )
if lStatus1 == 0 or lStatus2 == 0:
# print "compile status", lStatus
charsWritten = 0
shaderInfoLog = '\0' * 2048
charsWritten, infoLog = _glextlib.glGetShaderInfoLog(f, len(shaderInfoLog),
charsWritten, shaderInfoLog)
print "shaderInfoLog", shaderInfoLog
print "shader didn't compile",infoLog
else:
self.program = _glextlib.glCreateProgram()
_glextlib.glAttachShader(self.program,v)
_glextlib.glAttachShader(self.program,f)
_glextlib.glLinkProgram(self.program)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetProgramiv(self.program,
_glextlib.GL_LINK_STATUS,
lStatus )
if lStatus == 0:
# print "link status", lStatus
log = ""
charsWritten = 0
progInfoLog = '\0' * 2048
charsWritten, infoLog = _glextlib.glGetProgramInfoLog(self.program, len(progInfoLog),
charsWritten, progInfoLog)
print "shader didn't link"
print "log ",progInfoLog
else:
_glextlib.glValidateProgram(self.program)
lStatus = 0x7FFFFFFF
lStatus = _glextlib.glGetProgramiv(self.program,
_glextlib.GL_VALIDATE_STATUS,
lStatus )
if lStatus == 0:
print "shader did not validate, status:", lStatus
# else:
# Get location
#
def getUniforms1(self):
self.uniforms['camMatrix'] = glGetUniformLocation(self.program, 'camMatrix')
self.uniforms['shadowMatrix'] = glGetUniformLocation(self.program, 'shadowMatrix')
self.uniforms['shadowMap'] = glGetUniformLocation(self.program, 'shadowMap')
self.uniforms['useShadow'] = glGetUniformLocation(self.program, 'useShadow')
def getUniforms(self):
self.uniforms['camModel'] = glGetUniformLocation(self.program, 'camModel')
self.uniforms['lightProj'] = glGetUniformLocation(self.program, 'lightProj')
self.uniforms['lightView'] = glGetUniformLocation(self.program, 'lightView')
self.uniforms['lightRot'] = glGetUniformLocation(self.program, 'lightRot')
self.uniforms['lightNear'] = glGetUniformLocation(self.program, 'lightNear')
self.uniforms['lightFar'] = glGetUniformLocation(self.program, 'lightFar')
self.uniforms['shadowMap'] = glGetUniformLocation(self.program, 'shadowMap')
self.uniforms['shadowMapSize'] = glGetUniformLocation(self.program, 'shadowMapSize')
self.uniforms['LightSourcePos'] = glGetUniformLocation(self.program, 'LightSourcePos')
def setModeMAtrixUniform(self,matrice):
glUniformMatrix4fv(self.uniforms['camModel'], 1, False, matrice)
def setUniforms(self):
glUniformMatrix4fv(self.uniforms['camModel'], 1, False, self.light_mvp)#self.cam_model)
glUniformMatrix4fv(self.uniforms['lightProj'], 1, False, self.lightProj)
glUniformMatrix4fv(self.uniforms['lightView'], 1, False, self.lightView)
glUniformMatrix4fv(self.uniforms['lightRot'], 1, False, self.cam_model)
glUniform1i(self.uniforms['shadowMap'],7)
glUniform1f(self.uniforms['lightNear'],float(self.near))
glUniform1f(self.uniforms['lightFar'],float(self.far))
glUniform2f(self.uniforms['shadowMapSize'],float(self.width), float(self.height))
glUniform3f(self.uniforms['LightSourcePos'],float(self.lookFrom[0]),float(self.lookFrom[1]),float(self.lookFrom[2]))
#glUniformMatrix4fv(self.shader.uniforms['shadowMatrix'], 1, False, glGetFloatv(GL_MODELVIEW_MATRIX))
def setShadowTexture(self):
self.shadow_depthtextureName=int(glGenTextures(1)[0])
glActiveTexture(GL_TEXTURE7)
glPrioritizeTextures(numpy.array([self.shadow_depthtextureName]),
numpy.array([1.]))
_gllib.glBindTexture (GL_TEXTURE_2D, self.shadow_depthtextureName);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
# glTexParameteri (GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
# glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE )
_gllib.glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, self.width,
self.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None);
# _gllib.glBindTexture (GL_TEXTURE_2D, 0);
def setupFBO(self):
# if not self.initialized:
# self.setShadowTexture()
# self.setShader()
# self.getUniforms()
# return
glClearColor(0,0,0,1.0);
# glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
if not self.initialized:
self.initialized = True
self.setShadowTexture()
self.fbo = 0#glGenFramebuffers(1);
self.fbo = _glextlib.glGenFramebuffersEXT(1, self.fbo)
#self.shadowTexture = glGenTextures(1)
lCheckMessage = _glextlib.glCheckFramebufferStatusEXT(_glextlib.GL_FRAMEBUFFER_EXT)
if lCheckMessage != _glextlib.GL_FRAMEBUFFER_COMPLETE_EXT: # 0x8CD5
print 'glCheckFramebufferStatusEXT %x'%lCheckMessage
print "fbo ",self.fbo,lCheckMessage
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, self.fbo )
glDrawBuffer(GL_NONE)
glReadBuffer(GL_NONE)
# glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, self.fbo, 0)
## attaching the current stencil to the FBO (Frame Buffer Object)
_glextlib.glFramebufferTexture2DEXT(_glextlib.GL_FRAMEBUFFER_EXT,
_glextlib.GL_DEPTH_ATTACHMENT_EXT,
GL_TEXTURE_2D, self.shadow_depthtextureName,0)
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, 0)
# else :
# _glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, self.fbo )
# glActiveTexture(GL_TEXTURE7)
# _gllib.glBindTexture (GL_TEXTURE_2D, self.shadow_depthtextureName);
# _gllib.glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, self.width,
# self.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None);
#glActiveTexture(GL_TEXTURE0)
print "OK"
def shadow_pass(self,):
self.setupFBO()
#glUniform1i(self.uniforms['useShadow'], 0)
# glBindFramebuffer(GL_FRAMEBUFFER, self.fbo)
glEnable(GL_DEPTH_TEST)
glClearColor(0.0,0.0,0.0,1.0)
glEnable(GL_CULL_FACE)
# glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, self.fbo )
glClear(GL_DEPTH_BUFFER_BIT)
self.viewer.rootObject.culling=GL_FRONT
# self.viewer.rootObject.Set(culling=GL_FRONT)
# glCullFace(GL_FRONT)
# glCullFace(GL_BACK)
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
self.setProjection()
#FORCE FRONT CULLING?
self.camera.RedrawObjectHierarchy()
_glextlib.glBindFramebufferEXT(_glextlib.GL_FRAMEBUFFER_EXT, 0)
#grab the depth buffer
_gllib.glBindTexture (GL_TEXTURE_2D, 0);
# glCopyTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT, 0, 0, self.width,
# self.height, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
def normal_pass(self):
if not self.shader_initialized:
self.setShader()
self.getUniforms()
self.shader_initialized=True
# self.cam_model = self.camera.GetMatrixInverse().flatten()#.transpose().flatten()
self.setProjection()
self.cam_model = self.viewer.rootObject.GetMatrix(transpose=False).flatten()
glActiveTexture(GL_TEXTURE7);#is this working ?
glBindTexture(GL_TEXTURE_2D,self.shadow_depthtextureName);
# self.setTextureMatrix()
self.setMVPLight()
glUseProgram( self.program )
self.setUniforms()
self.camera.SetupProjectionMatrix()
self.viewer.rootObject.culling=GL_BACK
# self.viewer.rootObject.Set(culling=GL_BACK)
# glCullFace(GL_BACK)
# glCullFace(GL_FRONT)
def getLookAtMatrix(self,_eye, _lookat, _up):
ez = _eye - _lookat
ez = ez / numpy.linalg.norm(ez)
ex = numpy.cross(_up, ez)
ex = ex / numpy.linalg.norm(ex)
ey = numpy.cross(ez, ex)
ey = ey / numpy.linalg.norm(ey)
rmat = numpy.eye(4)
rmat[0][0] = ex[0]
rmat[0][1] = ex[1]
rmat[0][2] = ex[2]
rmat[1][0] = ey[0]
rmat[1][1] = ey[1]
rmat[1][2] = ey[2]
rmat[2][0] = ez[0]
rmat[2][1] = ez[1]
rmat[2][2] = ez[2]
tmat = numpy.eye(4)
tmat[0][3] = -_eye[0]
tmat[1][3] = -_eye[1]
tmat[2][3] = -_eye[2]
# numpy.array * is element-wise multiplication, use dot()
lookatmat = numpy.dot(rmat, tmat).transpose()
return lookatmat
def setProjectionOLD(self):
# oldType = self.camera.projectionType
# self.camera.projectionType = self.camera.ORTHOGRAPHIC
# self.camera.SetupProjectionMatrix()
# self.camera.projectionType = oldType
self.lightProj = glGetFloatv(GL_PROJECTION_MATRIX)
self.lightView = glGetDoublev(GL_MODELVIEW_MATRIX);#pointer or actual matrix
fx, fy, fz = self.lookFrom
ax, ay, az = self.lookAt#[0,0,0]#self.lookAt / should be center o fmolecule
gluLookAt( float(fx), float(fy), float(fz),
float(ax), float(ay), float(az),
float(0), float(1), float(0))
def setProjection(self):
glViewport(0, 0, self.width, self.height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
# gluPerspective(90.0, self.width/float(self.height), 1, 1000)
# gluPerspective(float(45.0),
# float(self.width)/float(self.height),
# float(self.camera.near), float(self.camera.far))#
# glOrtho(-40,40,-40,40, 0.1,500.0);
glOrtho(float(self.left), float(self.right),
float(self.bottom), float(self.top),
float(self.near),float(self.far))
self.lightProj = numpy.array(glGetFloatv(GL_PROJECTION_MATRIX)[:],'f')
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
fx, fy, fz = self.lookFrom
ax, ay, az = self.lookAt#[0,0,0]#self.lookAt / should be center o fmolecule
#ux, uy, uz = self.up
#thats what change
gluLookAt( float(fx), float(fy), float(fz),
float(ax), float(ay), float(az),
float(0), float(1), float(0))
self.lightView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)[:],'f')
# self.shadow_model_view = glGetDoublev(GL_MODELVIEW_MATRIX);
# self.shadow_projection = glGetDoublev(GL_PROJECTION_MATRIX);
# glMatrixMode(GL_MODELVIEW)
# glLoadIdentity()
# glMultMatrixd(self.shadow_projection)
# glMultMatrixd(self.shadow_model_view)
## #glUniformMatrix4fv(self.uniforms['camMatrix'], 1, False, glGetFloatv(GL_MODELVIEW_MATRIX))
# glLoadIdentity()
# gluLookAt( float(fx), float(fy), float(fz),
# float(ax), float(ay), float(az),
# float(0), float(1), float(0))
def setMVPLightNumpy(self):
m1=matrix(self.bias.reshape(4,4))
m2=matrix(self.lightProj.reshape(4,4))
m3=matrix(self.lightView.reshape(4,4))
m4=matrix(self.cam_model.reshape(4,4))
self.light_mvp = m4 * m3 * m2
def setMVPLight(self):
# static double modelView[16];
# static double projection[16];
# // Moving from unit cube [-1,1] to [0,1]
# // Grab modelview and transformation matrices
# self.lightView =glGetDoublev(GL_MODELVIEW_MATRIX)#, modelView);
# self.lightProj =glGetDoublev(GL_PROJECTION_MATRIX)#, projection);
glMatrixMode(GL_TEXTURE);
# glActiveTextureARB(GL_TEXTURE7);
_glextlib.glActiveTexture(GL_TEXTURE7);
glLoadIdentity();
glLoadMatrixf(self.bias);
# print "bias",self.bias
# // concatating all matrices into one.
glMultMatrixf (self.lightProj);
# print self.lightProj
glMultMatrixf (self.lightView);
# print self.lightView
# glMultMatrixf (self.cam_model);
# print self.cam_model
# // Go back to normal matrix mode
self.light_mvp = glGetFloatv(GL_TEXTURE_MATRIX)
# print "mvp",self.light_mvp
glMatrixMode(GL_MODELVIEW);
# glGetDoublev(GL_MODELVIEW_MATRIX)
# print "OK set TextureMatrix",self.lightProj,self.lightView,self.cam_model
|
modist-io/modist-api
|
alembic/versions/79ee5a7a99a4_create_tag_table.py
|
"""Create tag table.
Revision ID: 79ee5a7a99a4
Revises: <PASSWORD>
Create Date: 2020-04-15 17:49:26.406297
"""
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from alembic import op
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "<PASSWORD>"
branch_labels = None
depends_on = None
def upgrade():
"""Pushes changes into the database."""
op.create_table(
"tag",
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
server_default=sa.text("uuid_generate_v4()"),
nullable=False,
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("is_active", sa.Boolean(), server_default="true", nullable=False),
sa.Column("name", sa.String(length=64), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_refresh_updated_at_trigger("tag")
def downgrade():
"""Reverts changes performed by upgrade()."""
op.drop_refresh_updated_at_trigger("tag")
op.drop_table("tag")
|
prometheas/CommunityAllyWebApp
|
website/ngApp/watch/manager/WatchSettingsCtrl.js
|
<filename>website/ngApp/watch/manager/WatchSettingsCtrl.js
function WatchSettingsCtrl($http, $rootScope, $resource, SiteInfo)
{
var vm = this;
// Test data
vm.settings = {};
vm.defaultBGImage = $( document.documentElement ).css( "background-image" );
vm.showQaButton = $rootScope.userInfo.emailAddress === "<EMAIL>";
var SettingsResource = $resource( '/api/Settings', null,
{
'update': { method: 'PUT' }
} );
///////////////////////////////////////////////////////////////////////////////////////////////
// Populate the page from the server
///////////////////////////////////////////////////////////////////////////////////////////////
vm.refreshData = function()
{
vm.isLoading = true;
vm.settings = SettingsResource.get( function()
{
vm.isLoading = false;
} );
};
///////////////////////////////////////////////////////////////////////////////////////////////
// Occurs when the user wants to save a new site title
///////////////////////////////////////////////////////////////////////////////////////////////
vm.onSiteTitleChange = function()
{
vm.isLoading = true;
SettingsResource.update( { siteTitle: vm.settings.siteTitle }, function()
{
location.reload();
vm.isLoading = false;
} );
};
///////////////////////////////////////////////////////////////////////////////////////////////
// Occurs when the user wants to save a new welcome message
///////////////////////////////////////////////////////////////////////////////////////////////
vm.onWelcomeMessageUpdate = function()
{
vm.isLoading = true;
SettingsResource.update( { welcomeMessage: vm.settings.welcomeMessage }, function()
{
SiteInfo.privateSiteInfo.welcomeMessage = vm.settings.welcomeMessage;
vm.isLoading = false;
} );
};
///////////////////////////////////////////////////////////////////////////////////////////////
// Occurs when the user clicks a new background image
///////////////////////////////////////////////////////////////////////////////////////////////
vm.onImageClick = function( bgImage )
{
vm.settings.bgImageFileName = bgImage;
SettingsJS._defaultBG = bgImage;
SettingsResource.update( { BGImageFileName: vm.settings.bgImageFileName }, function()
{
$( ".test-bg-image" ).removeClass( "test-bg-image-selected" );
$( "img[src='" + $rootScope.bgImagePath + bgImage + "']" ).addClass( "test-bg-image-selected" );
vm.isLoading = false;
} );
};
vm.onImageHoverOver = function( bgImage )
{
$( document.documentElement ).css( "background-image", "url(" + $rootScope.bgImagePath + bgImage + ")" );
};
vm.onImageHoverOut = function()
{
if( typeof ( vm.settings.bgImageFileName ) === "string" && vm.settings.bgImageFileName.length > 0 )
$( document.documentElement ).css( "background-image", "url(" + $rootScope.bgImagePath + vm.settings.bgImageFileName + ")" );
else
$( document.documentElement ).css( "background-image", vm.defaultBGImage );
};
vm.onQaDeleteSite = function()
{
$http.get( "/api/QA/DeleteThisAssociation" ).then( function()
{
location.reload();
}, function( httpResponse )
{
alert( "Failed to delete site: " + httpResponse.data.message );
} );
};
vm.mapInstance = new google.maps.Map( document.getElementById( 'map-canvas' ), vm.mapInfo );
vm.refreshData();
}
WatchSettingsCtrl.$inject = ["$http", "$rootScope", "$resource", "SiteInfo"];
|
renchao-lu/ogs5
|
FileIO/readNonBlankLineFromInputStream.cpp
|
/*
* readNonBlankLineFromInputStream.cpp
*
* Created on: Apr 19, 2011
* Author: TF
* \copyright
* Copyright (c) 2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*/
#include "readNonBlankLineFromInputStream.h"
std::string readNonBlankLineFromInputStream(std::istream& in)
{
std::string line;
bool not_finished(true);
while (not_finished)
{
// read line
getline(in, line);
if (!in.fail())
{
// skip initial space characters
std::string::size_type i(line.find_first_not_of(" ", 0));
// search comment symbol ;
std::string::size_type j(line.find(";", i));
if (j ==
i) // first non space character is equal to the comment symbol
not_finished = true;
else
{
if ((i != std::string::npos))
// cut string from first non blank space character until the
// first comment character
line = line.substr(i, j - i);
// remove last blank spaces
i = line.find_last_not_of(" ");
if (i != std::string::npos)
line = line.substr(0, i + 1);
not_finished = false;
}
}
else
{
line = "";
not_finished = false;
}
}
return line;
}
|
jeven2016/react-windy-ui
|
packages/docs/src/pages/tooltip/samples/Tooltip3.js
|
<filename>packages/docs/src/pages/tooltip/samples/Tooltip3.js
import React, {useState} from 'react';
import {Button, Toggle, Tooltip} from 'react-windy-ui';
export default function Tooltip3() {
const [active, setActive] = useState(true);
const [locked, setLocked] = useState(true);
return <>
<div className="doc doc-row">
<Toggle active={locked} onChange={val => {
setActive(true);
setLocked(val);
}} label='Lock'/>
</div>
<div className="doc doc-row">
<Tooltip defaultActive={true}
body={<span>This is a tooltip</span>}>
<Button outline={true} color="blue"
style={{marginLeft: '1rem'}}>Default Active</Button>
</Tooltip>
<Tooltip active={active}
onChange={(val) => {
!locked && setActive(val);
}}
body={<span>A tooltip</span>}>
<Button outline={true} color="purple"
style={{marginLeft: '1rem'}}>Active</Button>
</Tooltip>
</div>
</>;
}
|
Team-SpoonClass/BE
|
src/main/java/com/likelion/spoonclass/domain/member/auth/AuthService.java
|
<filename>src/main/java/com/likelion/spoonclass/domain/member/auth/AuthService.java
package com.likelion.spoonclass.domain.member.auth;
import com.likelion.spoonclass.domain.member.Member;
import com.likelion.spoonclass.domain.member.auth.token.TokenSet;
import com.likelion.spoonclass.domain.member.dto.request.RequestAuthSignInDto;
import com.likelion.spoonclass.domain.member.dto.request.RequestAuthSignUpDto;
import org.springframework.http.ResponseEntity;
public interface AuthService {
TokenSet login(RequestAuthSignInDto requestDto);
Long join(RequestAuthSignUpDto requestDto);
}
|
openvcx/openvcx
|
openvsx/include/server/srvfidx.h
|
<filename>openvsx/include/server/srvfidx.h
/** <!--
*
* Copyright (C) 2014 OpenVCX <EMAIL>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you would like this software to be made available to you under an
* alternate license please email <EMAIL> for more information.
*
* -->
*/
#ifndef __SERVER_FILE_IDX_H__
#define __SERVER_FILE_IDX_H__
#include "unixcompat.h"
#include "util/fileutil.h"
#define FILE_LIST_IDXNAME ".fidx.txt"
#define FILE_LIST_ENTRY_NAME_LEN 128
typedef struct FILE_LIST_ENTRY {
char name[FILE_LIST_ENTRY_NAME_LEN];
FILE_OFFSET_T size;
double duration;
char vstr[64];
char astr[64];
int flag;
int numTn;
time_t tm;
struct FILE_LIST_ENTRY *pnext;
} FILE_LIST_ENTRY_T;
typedef struct FILE_LIST_T {
char pathmedia[VSX_MAX_PATH_LEN];
unsigned int count;
FILE_LIST_ENTRY_T *pentries;
FILE_LIST_ENTRY_T *pentriesLast;
} FILE_LIST_T;
int file_list_read(const char *dir, FILE_LIST_T *pFilelist);
int file_list_write(const char *dir, const FILE_LIST_T *pFilelist);
void file_list_close(FILE_LIST_T *pFilelist);
FILE_LIST_ENTRY_T *file_list_find(const FILE_LIST_T *pFilelist, const char *filename);
FILE_LIST_ENTRY_T *file_list_addcopy(FILE_LIST_T *pFilelist, FILE_LIST_ENTRY_T *pEntry);
int file_list_removeunmarked(FILE_LIST_T *pFilelist);
//int file_list_getdirlen(const char *path);
//int file_list_read_file_entry(const char *path, FILE_LIST_ENTRY_T *pEntry);
#endif // __SERVER_FILE_IDX_H__
|
nlp-compromise/es-compromise
|
src/preTagger/plugin.js
|
<gh_stars>1-10
import tagger from './compute/index.js'
import model from './model/index.js'
import methods from './methods/index.js'
export default {
compute: {
tagger
},
model: {
two: model
},
methods,
hooks: ['tagger']
}
|
belikesayantan/daily-problem-solving
|
LEETCODE/Medium/Longest Substring Without Repeating Characters/longestsubstring.py
|
def lengthOfLongestSubstring(s: str) -> int:
left = length = 0
visited = dict()
for pos, char in enumerate(s):
if char in visited and visited[char] >= left:
left = visited[char] + 1
else:
length = max(length, pos - left + 1)
visited[char] = pos
return length
# def lengthOfLongestSubstring(s: str) -> int:
# left = pos = length = 0
# visited = dict()
# while pos < len(s):
# if visited.__contains__(s[pos]):
# left = max(visited.get(s[pos]), left)
# length = max(length, pos - left + 1)
# visited[s[pos]] = pos + 1
# pos += 1
# return length
if __name__ == "__main__":
print(lengthOfLongestSubstring(input()))
|
muddessir/framework
|
machine/qemu/sources/u-boot/drivers/net/pic32_mdio.c
|
// SPDX-License-Identifier: GPL-2.0+
/*
* pic32_mdio.c: PIC32 MDIO/MII driver, part of pic32_eth.c.
*
* Copyright 2015 Microchip Inc.
* <NAME> <<EMAIL>>
*/
#include <common.h>
#include <phy.h>
#include <miiphy.h>
#include <errno.h>
#include <wait_bit.h>
#include <asm/io.h>
#include <linux/delay.h>
#include "pic32_eth.h"
static int pic32_mdio_write(struct mii_dev *bus,
int addr, int dev_addr,
int reg, u16 value)
{
u32 v;
struct pic32_mii_regs *mii_regs = bus->priv;
/* Wait for the previous operation to finish */
wait_for_bit_le32(&mii_regs->mind.raw, MIIMIND_BUSY,
false, CONFIG_SYS_HZ, true);
/* Put phyaddr and regaddr into MIIMADD */
v = (addr << MIIMADD_PHYADDR_SHIFT) | (reg & MIIMADD_REGADDR);
writel(v, &mii_regs->madr.raw);
/* Initiate a write command */
writel(value, &mii_regs->mwtd.raw);
/* Wait 30 clock cycles for busy flag to be set */
udelay(12);
/* Wait for write to complete */
wait_for_bit_le32(&mii_regs->mind.raw, MIIMIND_BUSY,
false, CONFIG_SYS_HZ, true);
return 0;
}
static int pic32_mdio_read(struct mii_dev *bus, int addr, int devaddr, int reg)
{
u32 v;
struct pic32_mii_regs *mii_regs = bus->priv;
/* Wait for the previous operation to finish */
wait_for_bit_le32(&mii_regs->mind.raw, MIIMIND_BUSY,
false, CONFIG_SYS_HZ, true);
/* Put phyaddr and regaddr into MIIMADD */
v = (addr << MIIMADD_PHYADDR_SHIFT) | (reg & MIIMADD_REGADDR);
writel(v, &mii_regs->madr.raw);
/* Initiate a read command */
writel(MIIMCMD_READ, &mii_regs->mcmd.raw);
/* Wait 30 clock cycles for busy flag to be set */
udelay(12);
/* Wait for read to complete */
wait_for_bit_le32(&mii_regs->mind.raw,
MIIMIND_NOTVALID | MIIMIND_BUSY,
false, CONFIG_SYS_HZ, false);
/* Clear the command register */
writel(0, &mii_regs->mcmd.raw);
/* Grab the value read from the PHY */
v = readl(&mii_regs->mrdd.raw);
return v;
}
static int pic32_mdio_reset(struct mii_dev *bus)
{
struct pic32_mii_regs *mii_regs = bus->priv;
/* Reset MII (due to new addresses) */
writel(MIIMCFG_RSTMGMT, &mii_regs->mcfg.raw);
/* Wait for the operation to finish */
wait_for_bit_le32(&mii_regs->mind.raw, MIIMIND_BUSY,
false, CONFIG_SYS_HZ, true);
/* Clear reset bit */
writel(0, &mii_regs->mcfg);
/* Wait for the operation to finish */
wait_for_bit_le32(&mii_regs->mind.raw, MIIMIND_BUSY,
false, CONFIG_SYS_HZ, true);
/* Set the MII Management Clock (MDC) - no faster than 2.5 MHz */
writel(MIIMCFG_CLKSEL_DIV40, &mii_regs->mcfg.raw);
/* Wait for the operation to finish */
wait_for_bit_le32(&mii_regs->mind.raw, MIIMIND_BUSY,
false, CONFIG_SYS_HZ, true);
return 0;
}
int pic32_mdio_init(const char *name, ulong ioaddr)
{
struct mii_dev *bus;
bus = mdio_alloc();
if (!bus) {
printf("Failed to allocate PIC32-MDIO bus\n");
return -ENOMEM;
}
bus->read = pic32_mdio_read;
bus->write = pic32_mdio_write;
bus->reset = pic32_mdio_reset;
strncpy(bus->name, name, sizeof(bus->name));
bus->priv = (void *)ioaddr;
return mdio_register(bus);
}
|
redoclag/plaidml
|
pmlc/conversion/affine_to_stripe/convert_affine_to_stripe.cc
|
// Copyright 2019 Intel Corporation
#include "pmlc/conversion/affine_to_stripe/convert_affine_to_stripe.h"
#include "pmlc/dialect/stripe/affine_poly.h"
#include "pmlc/dialect/stripe/dialect.h"
#include "pmlc/dialect/stripe/ops.h"
#include "pmlc/dialect/stripe/util.h"
#include "mlir/Dialect/AffineOps/AffineOps.h"
#include "mlir/Dialect/StandardOps/Ops.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#define PASS_NAME "convert-affine-to-stripe"
#define DEBUG_TYPE PASS_NAME
namespace {
// Pass to convert Affine dialect to Stripe dialect.
struct ConvertAffineToStripe : public mlir::FunctionPass<ConvertAffineToStripe> {
void runOnFunction() override;
};
void ConvertAffineToStripe::runOnFunction() {
mlir::OwningRewritePatternList patterns;
pmlc::conversion::affine_to_stripe::populateAffineToStripeConversionPatterns(patterns, &getContext());
// Add Stripe dialect legal ops to conversion target.
mlir::ConversionTarget target(getContext());
target.addLegalOp<mlir::ModuleOp, mlir::ModuleTerminatorOp>();
target.addLegalDialect<pmlc::dialect::stripe::Dialect>();
target.addDynamicallyLegalOp<mlir::FuncOp>([&](mlir::FuncOp op) {
// TODO: FuncOp is legal only if types have been converted to Eltwise types.
return true; // typeConverter.isSignatureLegal(op.getType());
});
auto funcOp = getFunction();
if (failed(mlir::applyFullConversion(funcOp, target, patterns))) {
signalPassFailure();
}
// Wrap function body with a ParallelForOp to represent Stripe's 'main' block.
pmlc::dialect::stripe::createMainParallelFor(funcOp);
}
} // namespace
namespace pmlc {
namespace conversion {
namespace affine_to_stripe {
using mlir::AffineForOp;
using mlir::AffineTerminatorOp;
using mlir::ConstantIndexOp;
using mlir::OpRewritePattern;
using mlir::PatternMatchResult;
using mlir::PatternRewriter;
using pmlc::dialect::stripe::AffinePolynomial;
using pmlc::dialect::stripe::AffinePolyOp;
using pmlc::dialect::stripe::TerminateOp;
// Declaration of Affine ops converters for supported ops.
#define AFFINE_OP(OP) \
struct OP##Converter : public OpRewritePattern<OP> { \
using OpRewritePattern<OP>::OpRewritePattern; \
\
PatternMatchResult matchAndRewrite(OP Op, PatternRewriter& rewriter) const override; \
};
#include "supported_ops.inc"
PatternMatchResult ConstantIndexOpConverter::matchAndRewrite(ConstantIndexOp constOp, PatternRewriter& rewriter) const {
int64_t val = constOp.value().cast<mlir::IntegerAttr>().getInt();
// AffinePolyOp currently has a fixed 64-bit integer type.
rewriter.replaceOpWithNewOp<AffinePolyOp>(constOp, AffinePolynomial(val));
return matchSuccess();
}
PatternMatchResult AffineForOpConverter::matchAndRewrite(AffineForOp forOp, PatternRewriter& rewriter) const {
llvm_unreachable("ParallelForOp not supported yet");
}
// Converts AffineTerminatorOp to TerminateOp. If an AffineTerminatorOp requires a special context-dependent treatment,
// that must be implemented in the Op providing the context.
PatternMatchResult AffineTerminatorOpConverter::matchAndRewrite(AffineTerminatorOp terminatorOp,
PatternRewriter& rewriter) const {
rewriter.replaceOpWithNewOp<TerminateOp>(terminatorOp);
return matchSuccess();
}
void populateAffineToStripeConversionPatterns(mlir::OwningRewritePatternList& patterns, mlir::MLIRContext* ctx) {
#define AFFINE_OP(OP) OP##Converter,
#define AFFINE_LAST_OP(OP) OP##Converter
patterns.insert<
#include "supported_ops.inc" // NOLINT(build/include)
>(ctx);
}
} // namespace affine_to_stripe
} // namespace conversion
} // namespace pmlc
std::unique_ptr<mlir::FunctionPassBase> mlir::createConvertAffineToStripePass() {
return std::make_unique<ConvertAffineToStripe>();
}
static mlir::PassRegistration<ConvertAffineToStripe> pass(PASS_NAME, "Convert Affine dialect to Stripe dialect");
|
venosyd/opensyd_commons
|
src/main/java/com/venosyd/open/commons/util/JSONUtil.java
|
<reponame>venosyd/opensyd_commons
package com.venosyd.open.commons.util;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.*;
/**
* @author <NAME> <<EMAIL>>
*
* Utilidades para tratar JSON
*/
public class JSONUtil {
/**
* objeto para json
*/
public static String toJSON(Object objeto) {
return createGson().toJson(objeto);
}
/**
* objeto para json
*/
public static String toJSON(Object objeto, TypeAdapterFactory adapter) {
return registerTypeAdapter(adapter).toJson(objeto);
}
/**
* json para objeto
*/
public static <T> T fromJSON(String json) {
return createGson().fromJson(json, new TypeToken<T>() {
}.getType());
}
/**
* json para objeto
*/
public static <T> T fromJSON(String json, Class<T> type) {
return createGson().fromJson(json, type);
}
/**
* json para objeto
*/
public static <T> T fromJSON(String json, Class<T> type, TypeAdapterFactory adapter) {
return registerTypeAdapter(adapter).fromJson(json, type);
}
/**
* json para lista de objetos
*/
public static <T> List<T> fromJSONToList(String json) {
return createGson().fromJson(json, new TypeToken<List<T>>() {
}.getType());
}
/**
* json para lista de objetos
*/
public static <T> List<T> fromJSONToList(String json, TypeAdapterFactory adapter) {
return registerTypeAdapter(adapter).fromJson(json, new TypeToken<List<T>>() {
}.getType());
}
/**
* json para lista de objetos
*/
public static <T> List<T> fromJSONToList(String json, Class<T> clazz) {
var toReturn = new ArrayList<T>();
List<String> list = createGson().fromJson(json, new TypeToken<List<String>>() {
}.getType());
for (var element : list) {
toReturn.add(fromJSON(element, clazz));
}
return toReturn;
}
/**
* json para lista de objetos
*/
public static <T> List<T> fromJSONToList(String json, Class<T> clazz, TypeAdapterFactory adapter) {
var toReturn = new ArrayList<T>();
List<String> list = registerTypeAdapter(adapter).fromJson(json, new TypeToken<List<String>>() {
}.getType());
for (var element : list) {
toReturn.add(fromJSON(element, clazz));
}
return toReturn;
}
/**
* mapa para json. nao, o metodo toJSON nao basta
*/
public static String fromMapToJSON(Map<?, ?> map) {
return new GsonBuilder().create().toJson(map);
}
/**
* faz o inverso do de cima
*/
public static <T, K> Map<T, K> fromJSONToMap(String json) {
return createGson().fromJson(json, new TypeToken<Map<T, K>>() {
}.getType());
}
/**
* faz o inverso do de cima
*/
public static <T, K> Map<T, K> fromJSONToMap(String json, TypeAdapterFactory adapter) {
return registerTypeAdapter(adapter).fromJson(json, new TypeToken<Map<T, K>>() {
}.getType());
}
/**
* faz o inverso do de cima
*/
@SuppressWarnings("rawtypes")
public static <T, K> Map<T, K> fromJSONToMap(String json, Class<T> t, Class<K> k) {
var converted = new HashMap<T, K>();
Map map = createGson().fromJson(json, new TypeToken<Map<T, K>>() {
}.getType());
for (var obj : map.keySet()) {
T key = fromJSON(toJSON(obj), t);
K element = fromJSON(toJSON(map.get(obj)), k);
converted.put(key, element);
}
return converted;
}
/**
* faz o inverso do de cima
*/
@SuppressWarnings("rawtypes")
public static <T, K> Map<T, K> fromJSONToMap(String json, Class<T> t, Class<K> k, TypeAdapterFactory adapter) {
var converted = new HashMap<T, K>();
Map map = registerTypeAdapter(adapter).fromJson(json, new TypeToken<Map<T, K>>() {
}.getType());
for (var obj : map.keySet()) {
T key = fromJSON(toJSON(obj), t);
K element = fromJSON(toJSON(map.get(obj)), k);
converted.put(key, element);
}
return converted;
}
/**
* associa um adaptador especifico ao Gson
*/
private static Gson registerTypeAdapter(TypeAdapterFactory adapter) {
var b = new GsonBuilder();
b.registerTypeAdapterFactory(adapter);
b.registerTypeAdapter(Date.class, new DateDeserializer());
b.registerTypeAdapter(Date.class, new DateSerializer());
return b.create();
}
/**
* gson with personalized date
*/
private static Gson createGson() {
var b = new GsonBuilder();
b.registerTypeAdapter(Date.class, new DateDeserializer());
b.registerTypeAdapter(Date.class, new DateSerializer());
return b.create();
}
/**
* desserializador de datas personalizado
*/
private static class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2)
throws JsonParseException {
return json == null ? null : new Date(json.getAsLong());
}
}
/**
* desserializador de datas personalizado
*/
private static class DateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return src == null ? null : new JsonPrimitive(src.getTime());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.