code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
process.env.NODE_ENV = 'test';
// Required dev dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../server');
let should = chai.should();
chai.use(chaiHttp);
describe('/GET :network/kitties/:id/:block', () => {
it('Should return a valid response object with genes: "457849305451122794903585758459448676010482976302081674570064376741933484".', (done) => {
chai.request(server)
.get('/api/cached-kitties/v1/ropsten/kitties/12/6303417')
.end((err,res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.genes.should.be.eql("457849305451122794903585758459448676010482976302081674570064376741933484");
done();
});
});
});
describe('/GET :network/kitties/:id', () => {
it('Should return a valid response object with genes: "457849305451122794903585758459448676010482976302081674570064376741933484"', (done) => {
chai.request(server)
.get('/api/cached-kitties/v1/ropsten/kitties/12')
.end((err,res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.genes.should.be.eql("457849305451122794903585758459448676010482976302081674570064376741933484");
done();
});
});
});
describe('/GET /:network/getKittiesSoldByBlock/:fromBlock/:toBlock', () => {
it('Should return a valid response array of length 1 and returnValue.winner:"0xFAC9991178a0dE67dAa90c104AD4e722BAbea035"', (done) => {
chai.request(server)
.get('/api/cached-kitties/v1/ropsten/getKittiesSoldByBlock/6303970/6303973')
.end((err,res) => {
res.should.have.status(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(1);
res.body[0].should.have.property('returnValues');
res.body[0].returnValues.should.have.property('winner');
res.body[0].returnValues.winner.should.be.eql('0xFAC9991178a0dE67dAa90c104AD4e722BAbea035');
done();
});
});
});
|
javascript
| 21 | 0.642757 | 147 | 44.382979 | 47 |
starcoderdata
|
// Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef FXJS_GLOBAL_TIMER_H_
#define FXJS_GLOBAL_TIMER_H_
#include
#include "fxjs/cjs_app.h"
class GlobalTimer {
public:
GlobalTimer(app* pObj,
CPDFSDK_FormFillEnvironment* pFormFillEnv,
CJS_Runtime* pRuntime,
int nType,
const WideString& script,
uint32_t dwElapse,
uint32_t dwTimeOut);
~GlobalTimer();
static void Trigger(int nTimerID);
static void Cancel(int nTimerID);
bool IsOneShot() const { return m_nType == 1; }
uint32_t GetTimeOut() const { return m_dwTimeOut; }
int GetTimerID() const { return m_nTimerID; }
CJS_Runtime* GetRuntime() const { return m_pRuntime.Get(); }
WideString GetJScript() const { return m_swJScript; }
private:
using TimerMap = std::map<uint32_t, GlobalTimer*>;
static TimerMap* GetGlobalTimerMap();
uint32_t m_nTimerID;
app* const m_pEmbedObj;
bool m_bProcessing;
// data
const int m_nType; // 0:Interval; 1:TimeOut
const uint32_t m_dwTimeOut;
const WideString m_swJScript;
CJS_Runtime::ObservedPtr m_pRuntime;
CPDFSDK_FormFillEnvironment::ObservedPtr m_pFormFillEnv;
};
#endif // FXJS_GLOBAL_TIMER_H_
|
c
| 9 | 0.684989 | 80 | 27.38 | 50 |
starcoderdata
|
/*L
* Copyright Moxie Informatics.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/calims/LICENSE.txt for details.
*/
/**
*
*/
package gov.nih.nci.calims2.business.workflow.engine;
import java.util.List;
import org.drools.KnowledgeBase;
import org.drools.persistence.jpa.JPAKnowledgeService;
import org.drools.persistence.session.SessionInfo;
import org.drools.runtime.Environment;
import org.drools.runtime.StatefulKnowledgeSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import gov.nih.nci.calims2.dao.GenericDao;
/**
* @author viseem
*
*/
public class SessionLoaderImpl implements SessionLoader {
private static Logger log = LoggerFactory.getLogger(SessionLoaderImpl.class);
private GenericDao bpmGenericDao;
public StatefulKnowledgeSession loadSession(KnowledgeBase kbase, Environment environment) {
log.debug("loadSession");
List sessions = bpmGenericDao.findAll(SessionInfo.class, "id desc");
if (sessions == null || sessions.isEmpty()) {
log.debug("new StatefulKnowledgeSession");
return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, environment);
}
log.debug("Existing StatefulKnowledgeSession with id {}", sessions.get(0).getId());
return JPAKnowledgeService.loadStatefulKnowledgeSession(sessions.get(0).getId(), kbase, null, environment);
}
/**
* @param bpmGenericDao the bpmGenericDao to set
*/
public void setBpmGenericDao(GenericDao bpmGenericDao) {
this.bpmGenericDao = bpmGenericDao;
}
}
|
java
| 11 | 0.758095 | 111 | 29.288462 | 52 |
starcoderdata
|
#include "Entity.h"
Entity::Entity()
{
m_bActive = false;
}
Entity::~Entity()
{
}
void Entity::Draw(aie::Renderer2D* m_Renderer2D)
{
}
void Entity::Update(float dt)
{
}
void Entity::SetActive(bool bActive)
{
m_bActive = bActive;
}
bool Entity::GetActive()
{
return m_bActive;
}
|
c++
| 6 | 0.659722 | 48 | 8.633333 | 30 |
starcoderdata
|
import _ from 'lodash';
let devices;
Emitter.on('audiooutput:list', (event, d) => {
devices = d;
$('#audioOutputSelect option').remove();
devices.forEach((device) => {
if (device.kind === 'audiooutput') {
let label = device.label;
if (!label) {
switch (device.deviceId) {
case 'default':
label = 'System Default';
break;
case 'communications':
label = 'System Default Communications';
break;
default:
label = 'Unknown Device';
break;
}
}
const opt = $('
opt.attr('value', device.deviceId);
opt.text(label);
if (label === Settings.get('audiooutput')) {
opt.attr('selected', true);
}
$('#audioOutputSelect').append(opt);
}
});
$('select').material_select();
$('.dropdown-content li>a, .dropdown-content li>span').addClass('theme-text');
});
Emitter.fireAtGoogle('audiooutput:fetch');
$('#audioOutputSelect').on('change', (e) => {
Emitter.fireAtGoogle('audiooutput:set', $(e.currentTarget).val());
const label = _.find(devices, (device) => {
return device.deviceId === $(e.currentTarget).val();
}).label;
Emitter.fire('audiooutput:set', label);
});
let currentSelected = Settings.get('audiooutput');
setInterval(() => {
if (currentSelected !== Settings.get('audiooutput')) {
currentSelected = Settings.get('audiooutput');
$('#audioOutputSelect option').each((index, opt) => {
if ($(opt).text() === currentSelected) {
$('#audioOutputSelect').val($(opt).attr('value'));
$('#audioOutputSelect').material_select();
}
});
}
}, 500);
|
javascript
| 22 | 0.569168 | 80 | 28.413793 | 58 |
starcoderdata
|
#ifndef IMPLMAIN_HPP_INCLUDED
#define IMPLMAIN_HPP_INCLUDED
class CloneSecurityPrincipal
:
public ICloneSecurityPrincipal,
public ISupportErrorInfo,
public IADsError,
public IADsSID
{
// this is the only entity with access to the ctor of this class
friend class ClassFactory
public:
// IUnknown methods
virtual
HRESULT __stdcall
QueryInterface(const IID& riid, void **ppv);
virtual
ULONG __stdcall
AddRef();
virtual
ULONG __stdcall
Release();
// IDispatch methods
virtual
HRESULT __stdcall
GetTypeInfoCount(UINT *pcti);
virtual
HRESULT __stdcall
GetTypeInfo(UINT cti, LCID, ITypeInfo **ppti);
virtual
HRESULT __stdcall
GetIDsOfNames(
REFIID riid,
OLECHAR **prgpsz,
UINT cNames,
LCID lcid,
DISPID *prgids);
virtual
HRESULT __stdcall
Invoke(
DISPID id,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *params,
VARIANT *pVarResult,
EXCEPINFO *pei,
UINT *puArgErr);
// ISupportErrorInfo methods
virtual
HRESULT __stdcall
InterfaceSupportsErrorInfo(const IID& iid);
// ICloneSecurityPrincipal methods
virtual
HRESULT __stdcall
Connect(
BSTR srcDomainController,
BSTR srcDomain,
BSTR dstDomainController,
BSTR dstDomain);
virtual
HRESULT __stdcall
CopyDownlevelUserProperties(
BSTR srcSamName,
BSTR dstSamName,
long flags);
virtual
HRESULT __stdcall
AddSidHistory(
BSTR srcPrincipalSamName,
BSTR dstPrincipalSamName,
long flags);
virtual
HRESULT __stdcall
GetMembersSIDs(
BSTR dstGroupDN,
VARIANT* pVal);
// IADsSID methods
virtual
HRESULT __stdcall
SetAs(
long lFormat,
VARIANT varData);
virtual
HRESULT __stdcall
GetAs(
long lFormat,
VARIANT* pVar);
// IADsError methods
virtual
HRESULT __stdcall
GetErrorMsg(
long hrErr,
BSTR* Msg);
private:
// only our friend class factory can instantiate us.
CloneSecurityPrincipal();
// only Release can cause us to be deleted
virtual
~CloneSecurityPrincipal();
// not implemented: no copying allowed
CloneSecurityPrincipal(const CloneSecurityPrincipal&);
const CloneSecurityPrincipal& operator=(const CloneSecurityPrincipal&);
HRESULT
DoAddSidHistory(
const String& srcPrincipalSamName,
const String& dstPrincipalSamName,
long flags);
HRESULT
DoCopyDownlevelUserProperties(
const String& srcSamName,
const String& dstSamName,
long flags);
// represents the authenticated connection to the source and destination
// domain controllers, including ds bindings
class Connection
{
friend class CloneSecurityPrincipal;
public:
Connection();
// disconnects, unbinds.
~Connection();
HRESULT
Connect(
const String& srcDC,
const String& srcDomain,
const String& dstDC,
const String& dstDomain);
bool
IsConnected() const;
private:
Computer* dstComputer;
SAM_HANDLE dstDomainSamHandle;
HANDLE dstDsBindHandle;
PLDAP m_pldap;
Computer* srcComputer;
String srcDcDnsName;
SAM_HANDLE srcDomainSamHandle;
// not implemented: no copying allowed
Connection(const Connection&);
const Connection& operator=(const Connection&);
void
Disconnect();
};
Connection* connection;
ComServerReference dllref;
long refcount;
ITypeInfo** m_ppTypeInfo;
// used by IADsSID
PSID m_pSID;
};
#endif // IMPLMAIN_HPP_INCLUDED
|
c++
| 13 | 0.59092 | 75 | 18.60199 | 201 |
starcoderdata
|
const sendgrid = require('sendgrid')
const helper = sendgrid.mail
const config = require('../')
const isTestMode = process.env.NODE_ENV === 'test';
class Mailer extends helper.Mail {
constructor({
subject,
recipients
}, content) {
super()
let mailer = this
mailer.sgApi = sendgrid(config.SENDGRID_SECRET)
mailer.from_email = new helper.Email(config.NO_REPLY_EMAIL_ADDRESS)
mailer.subject = subject
mailer.body = new helper.Content('text/html', content)
mailer.recipients = mailer.formatAddresses(recipients)
mailer.addContent(mailer.body)
mailer.addClickTracking()
mailer.addRecipients()
}
formatAddresses(recipients) {
return recipients.map(({
email
}) => {
return new helper.Email(email)
})
}
addClickTracking() {
let mailer = this
const trackingSettings = new helper.TrackingSettings()
const clickTracking = new helper.ClickTracking(true, true)
trackingSettings.setClickTracking(clickTracking)
mailer.addTrackingSettings(trackingSettings)
}
addRecipients() {
let mailer = this
const personalize = new helper.Personalization()
mailer.recipients.forEach(recipient => {
personalize.addTo(recipient)
})
mailer.addPersonalization(personalize)
}
async send() {
let mailer = this
const request = mailer.sgApi.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mailer.toJSON()
})
if (isTestMode) return new Promise(resolve => resolve({}))
return await mailer.sgApi.API(request)
}
}
module.exports = Mailer
|
javascript
| 12 | 0.68638 | 76 | 24.769231 | 65 |
starcoderdata
|
class Solution:
def getLucky(self, s: str, k: int) -> int:
trans=""
for c in s:
trans+=str(ord(c)-ord('a')+1)
for c in range(k):
trans=self.transform(trans)
return int(trans)
def transform(self,trans):
res=0
for i in trans:
res+=(ord(i)-ord('0'))
return str(res)
if __name__ == '__main__':
sol=Solution()
# s = "iiii"
# k = 1
s = "leetcode"
k = 2
print(sol.getLucky(s,k))
|
python
| 16 | 0.492565 | 46 | 21.458333 | 24 |
starcoderdata
|
@Override
public void update(float delta) {
//reset rotations
if(verticleRot < 0) {
verticleRot = 359;
} if(verticleRot > 359) {
verticleRot = 0;
} if(horizontalRot < 0) {
horizontalRot = 359;
} if(horizontalRot > 359) {
horizontalRot = 0;
}
// r.mouseMove(500, 500);
// if(verticleRot > -90 && verticleRot < 90) {
// verticleRot = (int) (y - (0.5*posY));
// horizontalRot = -x;
// } else if(verticleRot == -90) {
// verticleRot = -89;
// } else if(verticleRot == 90) {
// verticleRot = 89;
// }
updateAllVertex();
updateAllVertexCont();
updateAllLine();
// verticleRot++;
// horizontalRot+=1;
}
|
java
| 7 | 0.548711 | 50 | 19.212121 | 33 |
inline
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace NuGet.Services.Metadata.Catalog.Monitoring
{
///
/// The possible outcomes of an <see cref="IValidator"/>.
///
public enum TestResult
{
///
/// The test completed successfully.
///
Pass,
///
/// The test failed and should be investigated.
///
Fail,
///
/// The test was skipped (<see cref="Validator.ShouldRunAsync(ValidationContext)"/> threw or returned false).
///
Skip
}
}
|
c#
| 7 | 0.596378 | 117 | 29.96 | 25 |
starcoderdata
|
package org.protobeans.security.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.protobeans.security.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
@Component
public class CurrentPasswordValidator implements ConstraintValidator<CurrentPassword, String> {
@Autowired
private SecurityService securityService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void initialize(CurrentPassword constraintAnnotation) {
//empty
}
@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
if (password == null || password.trim().isEmpty()) return true;
User currentUser = securityService.getCurrentUser();
return passwordEncoder.matches(password, currentUser.getPassword());
}
}
|
java
| 11 | 0.770889 | 95 | 32.727273 | 33 |
starcoderdata
|
#include <bits/stdc++.h>
typedef long long ll;
#define pb push_back
using namespace std;
typedef pair<ll, ll> pll;
ll n;
string s;
int main()
{
cin >> s;
n = s.length();
s = "#" + s;
if(s[n] != '0' || s[1] != '1') {
cout << "-1\n"; return 0;
}
for(ll i=1; i <= n-i; i++) {
if(s[i] != s[n-i]){
cout << "-1\n"; return 0;
}
}
vector< pll > ans;
ll curv = 1;
ll pt = 1;
for(ll i=1; i <= n-i; i++) {
if(s[i] == '1') {
ans.pb(make_pair(++pt, curv));
curv = pt;
continue;
}else {
ans.pb(make_pair(curv, ++pt));
}
}
//cout << ans.size() << endl;
ll st = (n/2)+1;
//cout << st << endl;
for(ll i=st;i<n;i++) {
if(s[i] == '0') {
ans.pb(make_pair(curv, ++pt));
}else {
ans.pb(make_pair(curv, ++pt));
curv = pt;
}
}
assert(ans.size() == n-1);
for(auto &i : ans) cout << i.first << " " << i.second << endl;
return 0;
}
|
c++
| 14 | 0.316233 | 70 | 24.115385 | 52 |
codenet
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "UObject/UObjectGlobals.h"
#include "Factories/Factory.h"
#include "Engine/Texture.h"
#include "ImportSettings.h"
#include "TextureFactory.generated.h"
class UTexture2D;
class UTextureCube;
UCLASS(customconstructor, collapsecategories, hidecategories=Object)
class UNREALED_API UTextureFactory : public UFactory, public IImportSettingsParser
{
GENERATED_UCLASS_BODY()
UPROPERTY()
uint32 NoCompression:1;
/** If enabled, the texture's alpha channel will be discarded during compression */
UPROPERTY(EditAnywhere, Category=Compression, meta=(ToolTip="If enabled, the texture's alpha channel will be discarded during compression"))
uint32 NoAlpha:1;
/** If enabled, compression is deferred until the texture is saved */
UPROPERTY(EditAnywhere, Category=Compression, meta=(ToolTip="If enabled, compression is deferred until the texture is saved"))
uint32 bDeferCompression:1;
/** Compression settings for the texture */
UPROPERTY(EditAnywhere, Category=Compression, meta=(ToolTip="Compression settings for the texture"))
TEnumAsByte<enum TextureCompressionSettings> CompressionSettings;
/** If enabled, a material will automatically be created for the texture */
UPROPERTY(EditAnywhere, Category=TextureFactory, meta=(ToolTip="If enabled, a material will automatically be created for the texture"))
uint32 bCreateMaterial:1;
/** If enabled, link the texture to the created material's base color */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, link the texture to the created material's base color"))
uint32 bRGBToBaseColor:1;
/** If enabled, link the texture to the created material's emissive color */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, link the texture to the created material's emissive color"))
uint32 bRGBToEmissive:1;
/** If enabled, link the texture's alpha to the created material's specular color */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, link the texture's alpha to the created material's roughness"))
uint32 bAlphaToRoughness:1;
/** If enabled, link the texture's alpha to the created material's emissive color */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, link the texture's alpha to the created material's emissive color"))
uint32 bAlphaToEmissive:1;
/** If enabled, link the texture's alpha to the created material's opacity */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, link the texture's alpha to the created material's opacity"))
uint32 bAlphaToOpacity:1;
/** If enabled, link the texture's alpha to the created material's opacity mask */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, link the texture's alpha to the created material's opacity mask"))
uint32 bAlphaToOpacityMask:1;
/** If enabled, the created material will be two-sided */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="If enabled, the created material will be two-sided"))
uint32 bTwoSided:1;
/** The blend mode of the created material */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="The blend mode of the created material"))
TEnumAsByte<enum EBlendMode> Blending;
/** The shading model of the created material */
UPROPERTY(EditAnywhere, Category=CreateMaterial, meta=(ToolTip="The shading model of the created material"))
TEnumAsByte<enum EMaterialShadingModel> ShadingModel;
/** The mip-map generation settings for the texture; Allows customization of the content of the mip-map chain */
UPROPERTY(EditAnywhere, Category=TextureFactory, meta=(ToolTip="The mip-map generation settings for the texture; Allows customization of the content of the mip-map chain"))
TEnumAsByte<enum TextureMipGenSettings> MipGenSettings;
/** The group the texture belongs to */
UPROPERTY(EditAnywhere, Category=LODGroup, meta=(ToolTip="The group the texture belongs to"))
TEnumAsByte<enum TextureGroup> LODGroup;
/** If enabled, mip-map alpha values will be dithered for smooth transitions */
UPROPERTY(EditAnywhere, Category=DitherMipMaps, meta=(ToolTip="If enabled, mip-map alpha values will be dithered for smooth transitions"))
uint32 bDitherMipMapAlpha:1;
/** Channel values to compare to when preserving alpha coverage from a mask. */
UPROPERTY(EditAnywhere, Category=PreserveAlphaCoverage, meta=(ToolTip="Channel values to compare to when preserving alpha coverage from a mask for mips"))
FVector4 AlphaCoverageThresholds;
/** If enabled, preserve the value of border pixels when creating mip-maps */
UPROPERTY(EditAnywhere, Category=PreserveBorder, meta=(ToolTip="If enabled, preserve the value of border pixels when creating mip-maps"))
uint32 bPreserveBorder:1;
/** If enabled, the texture's green channel will be inverted. This is useful for some normal maps */
UPROPERTY(EditAnywhere, Category=NormalMap, meta=(ToolTip="If enabled, the texture's green channel will be inverted. This is useful for some normal maps"))
uint32 bFlipNormalMapGreenChannel:1;
/** If enabled, we are using the existing settings for a texture that already existed. */
UPROPERTY(Transient)
uint32 bUsingExistingSettings:1;
public:
UTextureFactory(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
//~ Begin UObject Interface
virtual void PostInitProperties() override;
//~ End UObject Interface
//~ Begin UFactory Interface
virtual bool DoesSupportClass(UClass* Class) override;
virtual UObject* FactoryCreateBinary( UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const uint8*& Buffer, const uint8* BufferEnd, FFeedbackContext* Warn ) override;
virtual bool FactoryCanImport(const FString& Filename) override;
virtual IImportSettingsParser* GetImportSettingsParser() override;
//~ End UFactory Interface
/** IImportSettingsParser interface */
virtual void ParseFromJson(TSharedRef<class FJsonObject> ImportSettingsJson) override;
/** Create a texture given the appropriate input parameters */
virtual UTexture2D* CreateTexture2D( UObject* InParent, FName Name, EObjectFlags Flags );
virtual UTextureCube* CreateTextureCube( UObject* InParent, FName Name, EObjectFlags Flags );
/**
* Suppresses the dialog box that, when importing over an existing texture, asks if the users wishes to overwrite its settings.
* This is primarily for reimporting textures.
*/
static void SuppressImportOverwriteDialog();
/**
* Initializes the given texture from the TextureData text block supplied.
* The TextureData text block is assumed to have been generated by the UTextureExporterT3D.
*
* @param InTexture The texture to initialize
* @param Text The texture data text generated by the TextureExporterT3D
* @param Warn Where to send warnings/errors
*
* @return bool true if successful, false if not
*/
bool InitializeFromT3DTextureDataText(UTexture* InTexture, const FString& Text, FFeedbackContext* Warn);
// @todo document
bool InitializeFromT3DTexture2DDataText(UTexture2D* InTexture2D, const TCHAR*& Buffer, FFeedbackContext* Warn);
// @todo document
void FindCubeMapFace(const FString& ParsedText, const FString& FaceString, UTextureCube& TextureCube, UTexture2D*& TextureFace);
// @todo document
bool InitializeFromT3DTextureCubeDataText(UTextureCube* InTextureCube, const TCHAR*& Buffer, FFeedbackContext* Warn);
private:
/** This variable is static because in StaticImportObject() the type of the factory is not known. */
static bool bSuppressImportOverwriteDialog;
/**
* Tests if the given height and width specify a supported texture resolution to import; Can optionally check if the height/width are powers of two
*
* @param Width The width of an imported texture whose validity should be checked
* @param Height The height of an imported texture whose validity should be checked
* @param bAllowNonPowerOfTwo Whether or not non-power-of-two textures are allowed
* @param Warn Where to send warnings/errors
*
* @return bool true if the given height/width represent a supported texture resolution, false if not
*/
static bool IsImportResolutionValid(int32 Width, int32 Height, bool bAllowNonPowerOfTwo, FFeedbackContext* Warn);
/** used by CreateTexture() */
UTexture* ImportTexture(UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, const TCHAR* Type, const uint8*& Buffer, const uint8* BufferEnd, FFeedbackContext* Warn);
/** Applies import settings directly to the texture after import */
void ApplyAutoImportSettings(UTexture* Texture);
private:
/** Texture settings from the automated importer that should be applied to the new texture */
TSharedPtr<class FJsonObject> AutomatedImportSettings;
};
|
c
| 11 | 0.781775 | 222 | 48.292818 | 181 |
starcoderdata
|
public class CryptoManager {
private static final char LOWER_BOUND = ' ';
private static final char UPPER_BOUND = '_';
private static final int RANGE = UPPER_BOUND - LOWER_BOUND + 1;
/**
* This method determines if a string is within the allowable bounds of ASCII codes
* according to the LOWER_BOUND and UPPER_BOUND characters
* @param plainText a string to be encrypted, if it is within the allowable bounds
* @return true if all characters are within the allowable bounds, false if any character is outside
*/
public static boolean stringInBounds (String plainText) {
for(int i = 0; i < plainText.length(); i++) {
if(!((plainText.charAt(i) >= LOWER_BOUND) && (plainText.charAt(i) <= UPPER_BOUND))) {
return(false);
}
}
return(true);
}
/**
* Encrypts a string according to the Caesar Cipher. The integer key specifies an offset
* and each character in plainText is replaced by the character \"offset\" away from it
* @param plainText an uppercase string to be encrypted.
* @param key an integer that specifies the offset of each character
* @return the encrypted string
*/
public static String encryptCaesar(String plainText, int key) {
String outputString = "";
if(key > RANGE){
key %= RANGE;
}
for(int i = 0; i < plainText.length(); i++) {
if( (char) ((int) plainText.charAt(i) + key) > UPPER_BOUND) {
outputString += (char) ((int)(plainText.charAt(i)+key-RANGE));
}
else {
outputString += (char)((int)plainText.charAt(i)+key);
}
}
return(outputString);
}
/**
* Encrypts a string according the Bellaso Cipher. Each character in plainText is offset
* according to the ASCII value of the corresponding character in bellasoStr, which is repeated
* to correspond to the length of plainText
* @param plainText an uppercase string to be encrypted.
* @param bellasoStr an uppercase string that specifies the offsets, character by character.
* @return the encrypted string
*/
public static String encryptBellaso(String plainText, String bellasoStr) {
String outputString = "";
int max = bellasoStr.length();
int key;
for(int i = 0; i < plainText.length(); i++) {
key = ((int) bellasoStr.charAt(i%max)) % RANGE;
if( (char) ((int) plainText.charAt(i) + key) > UPPER_BOUND) {
outputString += (char) ((int)(plainText.charAt(i)+key-RANGE));
}
else {
outputString += (char)((int)plainText.charAt(i)+key);
}
}
return(outputString);
}
/**
* Decrypts a string according to the Caesar Cipher. The integer key specifies an offset
* and each character in encryptedText is replaced by the character \"offset\" characters before it.
* This is the inverse of the encryptCaesar method.
* @param encryptedText an encrypted string to be decrypted.
* @param key an integer that specifies the offset of each character
* @return the plain text string
*/
public static String decryptCaesar(String encryptedText, int key) {
String outputString = "";
if(key > RANGE){
key %= RANGE;
}
for(int i = 0; i < encryptedText.length(); i++) {
if( (char) ((int) encryptedText.charAt(i) - key) < LOWER_BOUND) {
outputString += (char) ((int)(encryptedText.charAt(i)-key+RANGE));
}
else {
outputString += (char)((int)encryptedText.charAt(i)-key);
}
}
return(outputString);
}
/**
* Decrypts a string according the Bellaso Cipher. Each character in encryptedText is replaced by
* the character corresponding to the character in bellasoStr, which is repeated
* to correspond to the length of plainText. This is the inverse of the encryptBellaso method.
* @param encryptedText an uppercase string to be encrypted.
* @param bellasoStr an uppercase string that specifies the offsets, character by character.
* @return the decrypted string
*/
public static String decryptBellaso(String encryptedText, String bellasoStr) {
String outputString = "";
int max = bellasoStr.length();
int key;
for(int i = 0; i < encryptedText.length(); i++) {
key = ((int) bellasoStr.charAt(i%max)) % RANGE;
if( (char) ((int) encryptedText.charAt(i) - key) < LOWER_BOUND) {
outputString += (char) ((int)(encryptedText.charAt(i)-key+RANGE));
}
else {
outputString += (char)((int)encryptedText.charAt(i)-key);
}
}
return(outputString);
}
}
|
java
| 19 | 0.687643 | 101 | 35.115702 | 121 |
starcoderdata
|
from string import punctuation
score = 8
CONDITIONS = {
"length" :(2,"The password lenght should be between 7 and 32."),
"special" :(1,"The password should have at least an special character."),
"digit" :(1,"The password should contain at least a digit."),
"lowercase" :(1,"The password should contain at least a lower case letter."),
"uppercase" :(1,"The password should contain at least an upper case letter."),
}
print('Enter the password:')
pwd = input()
if len(pwd) in range(7,32):
del CONDITIONS["length"]
for idx in range(len(pwd)):
if pwd[idx] in punctuation:
CONDITIONS.pop("special",None)
elif pwd[idx].isdigit():
CONDITIONS.pop("digit",None)
elif pwd[idx].islower():
CONDITIONS.pop("lowercase",None)
elif pwd[idx].isupper():
CONDITIONS.pop("uppercase",None)
# Check the ASCII code of the current character and the three next ones to see if they are consecutive. If so, add the points and the message to the list.
if ord(pwd[idx]) == ord(pwd[(idx + 1) % len(pwd)]) - 1 == ord(pwd[(idx + 2) % len(pwd)]) - 2:
CONDITIONS["consecutive"] = (2,"The password should not have more than 3 consecutive elements.")
for (i,j) in CONDITIONS.items():
score = score - j[0]
print("The score of the password is {}".format(score))
for (i,j) in CONDITIONS.items():
print(j[1])
|
python
| 12 | 0.654787 | 158 | 41.117647 | 34 |
starcoderdata
|
package authServer;
import Comms.KeyDistributor;
import Comms.Messenger;
import java.net.ServerSocket;
public class Controller {
/**
* @author Silver-VS
*/
public static void main(String[] args) {
Messenger messenger = new Messenger();
ServerSocket serverSocket = messenger.initServerSocket(5500);
System.out.println("AS iniciado y esperando peticiones...");
do {
if (KeyDistributor.importAndSavePublicKeyFromServer(messenger.acceptRequest(serverSocket))) {
System.out.println("Clave del cliente recuperada exitosamente");
} else System.out.println("Recibo de llave fallido");
if (new ProcessRequest().processUserRequest(messenger.acceptRequest(serverSocket))) {
System.out.println("Respuesta enviada del AS al cliente.");
} else {
System.out.println("Ha ocurrido un error en la respuesta.");
}
} while (!serverSocket.isClosed());
}
}
|
java
| 13 | 0.641026 | 105 | 29.727273 | 33 |
starcoderdata
|
def test_nonempty(self):
repo_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, repo_dir)
with Repo.init(repo_dir) as repo:
# Populate repo
filea = Blob.from_string(b'file a')
fileb = Blob.from_string(b'file b')
filed = Blob.from_string(b'file d')
tree = Tree()
tree[b'a'] = (stat.S_IFREG | 0o644, filea.id)
tree[b'b'] = (stat.S_IFREG | 0o644, fileb.id)
tree[b'c/d'] = (stat.S_IFREG | 0o644, filed.id)
repo.object_store.add_objects(
[(o, None) for o in [filea, fileb, filed, tree]])
build_index_from_tree(
repo.path, repo.index_path(), repo.object_store, tree.id)
# Verify index entries
index = repo.open_index()
self.assertEqual(len(index), 3)
# filea
apath = os.path.join(repo.path, 'a')
self.assertTrue(os.path.exists(apath))
self.assertReasonableIndexEntry(
index[b'a'], stat.S_IFREG | 0o644, 6, filea.id)
self.assertFileContents(apath, b'file a')
# fileb
bpath = os.path.join(repo.path, 'b')
self.assertTrue(os.path.exists(bpath))
self.assertReasonableIndexEntry(
index[b'b'], stat.S_IFREG | 0o644, 6, fileb.id)
self.assertFileContents(bpath, b'file b')
# filed
dpath = os.path.join(repo.path, 'c', 'd')
self.assertTrue(os.path.exists(dpath))
self.assertReasonableIndexEntry(
index[b'c/d'], stat.S_IFREG | 0o644, 6, filed.id)
self.assertFileContents(dpath, b'file d')
# Verify no extra files
self.assertEqual(
['.git', 'a', 'b', 'c'], sorted(os.listdir(repo.path)))
self.assertEqual(
['d'], sorted(os.listdir(os.path.join(repo.path, 'c'))))
|
python
| 15 | 0.5166 | 76 | 38 | 51 |
inline
|
#pragma once
#include
namespace docker_plugin {
template <typename T>
std::string to_json(const T& e);
template <typename T>
T from_json(const std::string& str);
} // namespace docker_plugin
|
c
| 8 | 0.720588 | 37 | 21.777778 | 9 |
starcoderdata
|
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifySubjectCredentialRequest = exports.verifySubjectCredentialRequests = void 0;
var types_1 = require("@unumid/types");
var requireAuth_1 = require("../requireAuth");
var error_1 = require("../utils/error");
var helpers_1 = require("../utils/helpers");
var lodash_1 = require("lodash");
var didHelper_1 = require("../utils/didHelper");
var config_1 = require("../config");
var verify_1 = require("../utils/verify");
var networkRequestHelper_1 = require("../utils/networkRequestHelper");
var validateProof_1 = require("../verifier/validateProof");
var logger_1 = __importDefault(require("../logger"));
/**
* Validates the attributes for a credential request to UnumID's SaaS.
* @param requests CredentialRequest
*/
var validateCredentialRequests = function (requests, subjectDid) {
if (helpers_1.isArrayEmpty(requests) || !requests) {
throw new error_1.CustError(400, 'subjectCredentialRequests must be a non-empty array.');
}
// let subjectDid = '';
for (var i = 0; i < requests.length; i++) {
var request = requests[i];
if (!request.proof) {
throw new error_1.CustError(400, "Invalid SubjectCredentialRequest[" + i + "]: proof must be defined.");
}
validateProof_1.validateProof(request.proof);
if (!request.type) {
throw new error_1.CustError(400, "Invalid SubjectCredentialRequest[" + i + "]: type must be defined.");
}
if (typeof request.type !== 'string') {
throw new error_1.CustError(400, "Invalid SubjectCredentialRequest[" + i + "]: type must be a string.");
}
if (!((request.required === false || request.required === true))) {
throw new error_1.CustError(400, "Invalid SubjectCredentialRequest[" + i + "]: required must be defined.");
}
if (!request.issuers) {
throw new error_1.CustError(400, "Invalid SubjectCredentialRequest[" + i + "]: issuers must be defined.");
}
// handle validating the subject did is the identical fr all requests
if (subjectDid !== request.proof.verificationMethod) {
throw new error_1.CustError(400, "Invalid SubjectCredentialRequest[" + i + "]: provided subjectDid, " + subjectDid + ", must match that of the credential requests' signer, " + request.proof.verificationMethod + ".");
}
}
// return the subjectDid for reference now that have validated all the same across all requests
return subjectDid;
};
/**
* Verify the CredentialRequests signatures.
*/
function verifySubjectCredentialRequests(authorization, issuerDid, subjectDid, credentialRequests) {
return __awaiter(this, void 0, void 0, function () {
var authToken, _i, credentialRequests_1, credentialRequest, result, _a, isVerified, message;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
requireAuth_1.requireAuth(authorization);
// validate credentialRequests input; and grab the subjectDid for reference later
validateCredentialRequests(credentialRequests, subjectDid);
authToken = authorization;
_i = 0, credentialRequests_1 = credentialRequests;
_b.label = 1;
case 1:
if (!(_i < credentialRequests_1.length)) return [3 /*break*/, 5];
credentialRequest = credentialRequests_1[_i];
return [4 /*yield*/, verifySubjectCredentialRequest(authToken, issuerDid, subjectDid, credentialRequest)];
case 2:
result = _b.sent();
_a = result.body, isVerified = _a.isVerified, message = _a.message;
authToken = result.authToken;
if (!!result.body.isVerified) return [3 /*break*/, 4];
return [4 /*yield*/, handleSubjectCredentialsRequestsVerificationReceipt(authToken, issuerDid, subjectDid, credentialRequests, isVerified, message)];
case 3:
// handle sending back the ReceiptSubjectCredentialRequestVerifiedData receipt with the verification failure reason
authToken = _b.sent();
return [2 /*return*/, __assign(__assign({}, result), { authToken: authToken })];
case 4:
_i++;
return [3 /*break*/, 1];
case 5: return [4 /*yield*/, handleSubjectCredentialsRequestsVerificationReceipt(authToken, issuerDid, subjectDid, credentialRequests, true)];
case 6:
// if made it this far then all SubjectCredentialRequests are verified
authToken = _b.sent();
return [2 /*return*/, {
authToken: authToken,
body: {
isVerified: true
}
}];
}
});
});
}
exports.verifySubjectCredentialRequests = verifySubjectCredentialRequests;
function verifySubjectCredentialRequest(authorization, issuerDid, subjectDid, credentialRequest) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var verificationMethod, signatureValue, didDocumentResponse, authToken, publicKeyInfos, _c, publicKey, encoding, unsignedCredentialRequest, bytes, isVerified;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
verificationMethod = (_a = credentialRequest.proof) === null || _a === void 0 ? void 0 : _a.verificationMethod;
signatureValue = (_b = credentialRequest.proof) === null || _b === void 0 ? void 0 : _b.signatureValue;
// validate that the issueDid is present in the request issuer array
if (!credentialRequest.issuers.includes(issuerDid)) {
return [2 /*return*/, {
authToken: authorization,
body: {
isVerified: false,
message: "Issuer DID, " + issuerDid + ", not found in credential request issuers " + credentialRequest.issuers
}
}];
}
return [4 /*yield*/, didHelper_1.getDIDDoc(config_1.configData.SaaSUrl, authorization, verificationMethod)];
case 1:
didDocumentResponse = _d.sent();
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
authToken = networkRequestHelper_1.handleAuthTokenHeader(didDocumentResponse, authorization);
publicKeyInfos = didHelper_1.getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
if (publicKeyInfos.length === 0) {
return [2 /*return*/, {
authToken: authToken,
body: {
isVerified: false,
message: "Public key not found for the subject did " + verificationMethod
}
}];
}
_c = publicKeyInfos[0], publicKey = _c.publicKey, encoding = _c.encoding;
unsignedCredentialRequest = lodash_1.omit(credentialRequest, 'proof');
bytes = types_1.CredentialRequestPb.encode(unsignedCredentialRequest).finish();
isVerified = verify_1.doVerify(signatureValue, bytes, publicKey, encoding);
if (!isVerified) {
return [2 /*return*/, {
authToken: authToken,
body: {
isVerified: false,
message: 'SubjectCredentialRequest signature can not be verified.'
}
}];
}
return [2 /*return*/, {
authToken: authToken,
body: {
isVerified: true
}
}];
}
});
});
}
exports.verifySubjectCredentialRequest = verifySubjectCredentialRequest;
/**
* Handle sending back the SubjectCredentialRequestVerified receipt
*/
function handleSubjectCredentialsRequestsVerificationReceipt(authorization, issuerDid, subjectDid, credentialRequests, isVerified, message) {
return __awaiter(this, void 0, void 0, function () {
var requestInfo, data, receiptOptions, receiptCallOptions, resp, authToken, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
requestInfo = credentialRequests.map(function (request) { return lodash_1.omit(request, 'proof'); });
data = {
isVerified: isVerified,
requestInfo: requestInfo,
reason: message
};
receiptOptions = {
type: 'SubjectCredentialRequestVerified',
issuer: issuerDid,
subject: subjectDid,
data: data
};
receiptCallOptions = {
method: 'POST',
baseUrl: config_1.configData.SaaSUrl,
endPoint: 'receipt',
header: { Authorization: authorization },
data: receiptOptions
};
return [4 /*yield*/, networkRequestHelper_1.makeNetworkRequest(receiptCallOptions)];
case 1:
resp = _a.sent();
authToken = networkRequestHelper_1.handleAuthTokenHeader(resp, authorization);
return [2 /*return*/, authToken];
case 2:
e_1 = _a.sent();
logger_1.default.error("Error sending SubjectCredentialRequestVerification Receipt to Unum ID SaaS. Error " + e_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/, authorization];
}
});
});
}
//# sourceMappingURL=verifySubjectCredentialRequests.js.map
|
javascript
| 28 | 0.524287 | 228 | 54.096 | 250 |
starcoderdata
|
package com.djk.spu;
import com.djk.utils.PageHelper;
import java.util.List;
/**
* Created by dujinkai on 2018/7/12.
* 商品服务接口
*/
public interface SpuService {
/**
* 分页查询商品信息
*
* @param pageHelper 分类帮助类
* @param name 商品名称
* @return 返回商品信息
*/
PageHelper querySpus(PageHelper pageHelper, String name);
/**
* 添加商品
*
* @param spu 商品信息
* @return 成功返回1 失败返回0
*/
int addSpu(Spu spu);
/**
* 删除商品
*
* @param ids 商品id集合
* @return 成功》0 失败=0
*/
int deleteSpus(Long[] ids);
/**
* 根据商品id查询商品信息
*
* @param id 商品id
* @return 返回商品信息
*/
Spu queryById(long id);
/**
* 更新商品信息
*
* @param spu 商品信息
* @return 成功1 失败=0
*/
int updateSpu(Spu spu);
/**
* 扣除商品的库存
*
* @param spuStocks 商品库存
* @return 成功返回1 失败返回0
*/
int reduceStock(List spuStocks);
}
|
java
| 8 | 0.537561 | 71 | 15.532258 | 62 |
starcoderdata
|
// Pow(x, n)
// 二分法,$x^n = x^{n/2} * x^{n/2} * x^{n\%2}$
// 时间复杂度O(logn),空间复杂度O(1)
public class Solution {
public double myPow(double x, int n) {
if (n < 0) return 1.0 / power(x, -n);
else return power(x, n);
}
private static double power(double x, int n) {
if (n == 0) return 1;
double v = power(x, n / 2);
if (n % 2 == 0) return v * v;
else return v * v * x;
}
}
|
java
| 11 | 0.481308 | 50 | 27.6 | 15 |
starcoderdata
|
package engine.tasks;
import engine.Updateable;
public class RepeatingTask implements Updateable {
private int ticks;
private int count;
private Updateable updateable;
public RepeatingTask (Updateable updateable, int ticks) {
this.ticks = ticks;
this.count = ticks - 1;
this.updateable = updateable;
}
@Override
public void update() {
count--;
if (count <= 0) {
updateable.update();
count = ticks-1;
}
}
}
|
java
| 10 | 0.589942 | 61 | 18.148148 | 27 |
starcoderdata
|
function(item){
var ai = this.activeItem,
ct = this.container;
item = ct.getComponent(item);
// Is this a valid, different card?
if(item && ai != item){
// Changing cards, hide the current one
if(ai){
ai.hide();
if (ai.hidden !== true) {
return false;
}
ai.fireEvent('deactivate', ai);
}
// Change activeItem reference
this.activeItem = item;
// The container is about to get a recursive layout, remove any deferLayout reference
// because it will trigger a redundant layout.
delete item.deferLayout;
// Show the new component
item.show();
this.layout();
if(item.doLayout){
item.doLayout();
}
item.fireEvent('activate', item);
}
}
|
javascript
| 12 | 0.46875 | 97 | 27.264706 | 34 |
inline
|
func RandomizedGenState(simState *module.SimulationState) {
var airdrops []types.Airdrop
simState.AppParams.GetOrGenerate(
simState.Cdc, "airdrops", &airdrops, simState.Rand,
func(r *rand.Rand) { airdrops = GenAirdrops(r) },
)
var claimRecords []types.ClaimRecord
simState.AppParams.GetOrGenerate(
simState.Cdc, "claim_records", &claimRecords, simState.Rand,
func(r *rand.Rand) { claimRecords = GenClaimRecords(r, simState.Accounts, airdrops) },
)
airdropBalances := map[uint64]sdk.Coins{} // airdrop id => balances
for _, claimRecord := range claimRecords {
airdropBalances[claimRecord.AirdropId] = airdropBalances[claimRecord.AirdropId].Add(claimRecord.ClaimableCoins...)
}
genState := &types.GenesisState{
Airdrops: airdrops,
ClaimRecords: claimRecords,
}
simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(genState)
// Modify x/bank module's genesis state.
var bankGenState banktypes.GenesisState
simState.Cdc.MustUnmarshalJSON(simState.GenState[banktypes.ModuleName], &bankGenState)
addedSupply := sdk.Coins{}
for _, airdrop := range airdrops {
if balances, ok := airdropBalances[airdrop.Id]; ok {
bankGenState.Balances = append(bankGenState.Balances, banktypes.Balance{
Address: airdrop.SourceAddress,
Coins: balances,
})
addedSupply = addedSupply.Add(balances...)
}
}
bankGenState.Supply = bankGenState.Supply.Add(addedSupply...)
bz := simState.Cdc.MustMarshalJSON(&bankGenState)
simState.GenState[banktypes.ModuleName] = bz
}
|
go
| 16 | 0.752475 | 116 | 35.97561 | 41 |
inline
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "audio/dsp/mfcc/mfcc.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "glog/logging.h"
#include "audio/dsp/porting.h" // auto-added.
namespace audio_dsp {
TEST(MfccTest, AgreesWithPythonGoldenValues) {
Mfcc mfcc;
std::vector input;
const int kSampleCount = 513;
for (int i = 0; i < kSampleCount; ++i) {
input.push_back(i + 1);
}
ASSERT_TRUE(mfcc.Initialize(input.size(), 22050 /*sample rate*/));
std::vector output;
mfcc.Compute(input, &output);
std::vector expected = {29.13970072, -6.41568601, -0.61903012,
-0.96778652, -0.26819878, -0.40907028,
-0.15614748, -0.23203119, -0.10481487,
-0.1543029, -0.0769791, -0.10806114,
-0.06047613};
ASSERT_EQ(expected.size(), output.size());
for (int i = 0; i < output.size(); ++i) {
EXPECT_NEAR(output[i], expected[i], 1e-04);
}
}
TEST(MfccTest, AvoidsNansWithZeroInput) {
Mfcc mfcc;
std::vector input;
const int kSampleCount = 513;
for (int i = 0; i < kSampleCount; ++i) {
input.push_back(0.0);
}
ASSERT_TRUE(mfcc.Initialize(input.size(), 22050 /*sample rate*/));
std::vector output;
mfcc.Compute(input, &output);
int expected_size = 13;
ASSERT_EQ(expected_size, output.size());
EXPECT_THAT(output, testing::Each(testing::Truly(
[](double value) { return !isnan(value); })));
}
TEST(MfccTest, SimpleInputSaneResult) {
Mfcc mfcc;
mfcc.set_lower_frequency_limit(125.0);
mfcc.set_upper_frequency_limit(3800.0);
mfcc.set_filterbank_channel_count(40);
mfcc.set_dct_coefficient_count(40);
const int kSpectrogramSize = 129;
std::vector input(kSpectrogramSize, 0.0);
// Simulate a low-frequency sinusoid from the spectrogram.
const int kHotBin = 10;
input[kHotBin] = 1.0;
ASSERT_TRUE(mfcc.Initialize(input.size(), 8000));
std::vector output;
mfcc.Compute(input, &output);
// For a single low-frequency input, output beyond c_0 should look like
// a slow cosine, with a slight delay. Largest value will be c_1.
EXPECT_EQ(output.begin() + 1, std::max_element(output.begin(), output.end()));
}
} // namespace audio_dsp
|
c++
| 18 | 0.658029 | 80 | 29.552083 | 96 |
starcoderdata
|
void AddTagItem(TagItem newTag)
{
// Add tag to tagItem List
if (tagItems.Count == 1)
{
if (tagItems[0].TimeStamp < newTag.TimeStamp)
tagItems.Add(newTag);
else
{
newTag.Tag.Tag = 0;
tagItems.Insert(0, newTag);
ResetTagItemList();
}
} else if(tagItems.Count > 1)
{
if (tagItems[0].TimeStamp > newTag.TimeStamp)
{
newTag.Tag.Tag = 0;
tagItems.Insert(0, newTag);
ResetTagItemList();
}
else if(tagItems[tagItems.Count-1].TimeStamp<newTag.TimeStamp)
{
tagItems.Add(newTag);
} else
{
for(int i = 0; i<(tagItems.Count-1); i++)
{
if((tagItems[i].TimeStamp<newTag.TimeStamp) && (tagItems[i + 1].TimeStamp > newTag.TimeStamp)){
newTag.Tag.Tag = i + 1;
tagItems.Insert(i+1, newTag);
ResetTagItemList();
}
}
}
}
else {
tagItems.Add(newTag);
}
}
|
c#
| 21 | 0.36031 | 119 | 32.069767 | 43 |
inline
|
import React, { useReducer } from 'react';
import { FeedContext } from '../../context/Context';
import { arrayReducer } from '../../reducers/arrayReducer';
import rawFeeds from '../../data/feed/feeds';
const FeedProvider = ({ children }) => {
const [feeds, feedDispatch] = useReducer(arrayReducer, rawFeeds);
return <FeedContext.Provider value={{ feeds, feedDispatch }}>{children}
};
export default FeedProvider;
|
javascript
| 11 | 0.707207 | 97 | 36 | 12 |
starcoderdata
|
using JetBrains.Application;
using JetBrains.Application.Env;
using JetBrains.Application.Extensions;
using JetBrains.DataFlow;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Vsix2ReSharper.Implementation
{
[EnvironmentComponent(Sharing.Product)]
public class VsixExtensionProvider : IExtensionProvider
{
private readonly ExtensionLocations extensionLocations;
private readonly CollectionEvents extensions;
public VsixExtensionProvider(Lifetime lifetime, ExtensionLocations extensionLocations)
{
this.extensionLocations = extensionLocations;
extensions = new CollectionEvents "VsixExtensionProvider");
}
public bool LoadExtension(string folderPath)
{
// TODO: Logging
var location = FileSystemPath.Parse(folderPath);
if (!location.ExistsDirectory)
return false;
var loaded = false;
foreach (var file in location.GetChildFiles("*.nuspec"))
{
var nuSpec = NuSpecReader.Read(file);
if (nuSpec != null)
{
extensions.Add(new VsixExtension(this, nuSpec, location, extensionLocations));
loaded = true;
}
}
return loaded;
}
public string Name { get { return "VSIX"; } }
public IViewable Extensions { get { return extensions; } }
}
}
|
c#
| 19 | 0.708543 | 90 | 29.304348 | 46 |
starcoderdata
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
use Carbon\Carbon;
class empleado extends Model
{
//public $timestamps=false;
protected $table="empleados";
protected $fillable = ['nomEmp','fotoEmp','apeEmp','NacEmp','DUIEmp','NITEmp','dirEmp','telEmp','sueldoEmp','cargoEmp','estadoEmp','sexEmp','contraEmp'];
public static function cargarEmpleado($id)
{
return empleado::where('idEmp','=',$id)
->get();
}
public static function cargarUsuario()
{
return DB::table('empleados')
->join('usuarios', 'usuarios.idemp', '=', 'empleados.id')
->select('usuarios.*','empleados.nomEmp','empleados.apeEmp','empleados.telEmp','empleados.cargoEmp','empleados.estadoEmp')
->orderBy('empleados.id')
->get();
}
public static function Rnombre($fecha)
{
return empleado::where('contraEmp','=',$fecha)->get();
// return empleado::where('nomEmp','jorge ')
}
public function users()
{
return $this->hasMany('App\usuario','login','idemp');
}
public static function detaComp(){
return DB::table('productos')
->join('detalle_compras', 'detalle_compras.idprods', '=', 'productos.id')
->join('compras', 'compras.id', '=', 'detalle_compras.idcomps')
->select('detalle_compras.*','productos.nomProd')
//->orderBy('productos.id')
->get();
}
}
|
php
| 14 | 0.597385 | 156 | 24.491228 | 57 |
starcoderdata
|
const ConnectFour = require('./ConnectFour');
const Player = require('./Player');
const Board = require('./Board');
const Bead = require('./Bead');
const Row = require('./utils/Row');
const Column = require('./utils/Column');
const Oblique = require('./utils/Oblique');
module.exports = {
ConnectFour,
Player,
Board,
Bead,
Row,
Column,
Oblique,
};
|
javascript
| 6 | 0.655647 | 45 | 20.352941 | 17 |
starcoderdata
|
from dataclasses import dataclass
@dataclass
class FilterMetadataDto:
"The front end provides this data about the requested filters"
column_header: str
value: object
|
python
| 7 | 0.779817 | 66 | 20.8 | 10 |
starcoderdata
|
# Copyright (c) 2017, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
# ARE 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.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
from . import util
def test_utf_encoding():
input_fp = os.path.join(os.getcwd(), '../data/test/encodings/test-utf-8')
encoding = util.detect_utf(input_fp)
assert encoding == "UTF-8"
# Chardet is unreliable, so we are defaulting to UTF-8 for files
# without a UTF BOM
input_fp = os.path.join(os.getcwd(),
'../data/test/encodings/test-windows-1252')
encoding = util.detect_utf(input_fp)
assert encoding == "UTF-8"
input_fp = os.path.join(os.getcwd(),
'../data/test/encodings/VariableInfo.uni')
encoding = util.detect_utf(input_fp)
assert encoding == "UTF-16-LE"
def test_read_lines_offsets():
input_fp = os.path.join(os.getcwd(), '../data/test/data/test1.py')
lines, offsets = util.read_lines_offsets(input_fp)
assert lines == [
"zero",
"one two three four",
"five",
"six",
"seven"]
assert offsets == [0, 5, 24, 29, 33, 38]
input_fp2 = os.path.join(os.getcwd(), '../data/test/encodings/_ude_euc-tw1.txt')
lines, offsets = util.read_lines_offsets(input_fp2)
assert lines[1].find('\ufffd') #Python replacment character
def test_get_lines_and_line_offsets():
lines, offsets = util.get_lines_and_line_offsets(
["a b c\n", "d e\n", "f\n", "g h i j\n"])
assert lines == ["a b c", "d e", "f", "g h i j"]
assert offsets == [0, 6, 10, 12, 20]
lines, offsets = util.get_lines_and_line_offsets(
["a b c\r\n", "d e\r\n", "f\r\n", "g h i j\r\n"])
assert lines == ["a b c", "d e", "f", "g h i j"]
assert offsets == [0, 7, 12, 15, 24]
def test_get_user_date_time_str():
assert len(util.get_user_date_time_str()) > 15
def test_is_punctuation():
assert util.is_punctuation("#")
assert util.is_punctuation("//")
assert util.is_punctuation("/*")
assert util.is_punctuation("*")
assert util.is_punctuation("1.0") is False
assert util.is_punctuation("abc123") is False
def test_files_from_path():
# Process a directory
input_dir = os.path.join(os.getcwd(), '../data/test/data')
result = util.files_from_path(input_dir)
assert len(result) == 6
assert result[0].endswith("test/data/test0.py")
assert result[1].endswith("test/data/test1.py")
assert result[2].endswith("test/data/subdir/test2.py")
assert result[3].endswith("test/data/subdir/subdir2/test3.py")
assert result[4].endswith("test/data/subdir/subdir2/test4.bogus")
assert result[5].endswith("test/data/subdir/subdir2/test5.py")
# Process a single file
input_file = os.path.join(os.getcwd(), '../data/test/data/test1.py')
result = util.files_from_path(input_file)
assert len(result) == 1
assert result[0].endswith("test/data/test1.py")
|
python
| 10 | 0.668714 | 84 | 39.694444 | 108 |
starcoderdata
|
async def refresh_authentication(self, expires_in: int = 86400) -> NoReturn:
""" Refresh authentication manually. """
if self.__refresh_token is None:
raise HekrValueError('refresh_token', 'None', 'refresh token')
if self._refresh_token_expires_at < datetime.now():
raise RefreshTokenExpiredException()
response = await self.refresh_authentication_token(self.__refresh_token, expires_in=expires_in)
_LOGGER.info('Successful token refresh for account %s' % self)
self._process_auth_response(response)
await self.update_connectors()
|
python
| 9 | 0.66721 | 103 | 46.230769 | 13 |
inline
|
from types import prepare_class
from mid import Mid
from hand import Hand
from constants import *
class State:
def __init__(self, nbr_players=6, hands=[], mid=None, turn=0, prev_player=None, text="Cheat", cur_selected=None, played=False, call=0, events=[], out=0):
self.nbr_players = nbr_players
self.hands = hands
self.mid = mid
self.prev_player = prev_player
self.ended = False
self.text = text
self.cur_selected = cur_selected
self.played = played
self.call = call
self.events = events
self.out = out
if not events:
self.events = [list() for i in range(nbr_players)]
if not cur_selected:
self.cur_selected = Hand()
if not hands:
self.hands = [Hand() for i in range(nbr_players)]
if not mid:
self.mid = Mid()
self.turn = turn
for i in range(nbr_players):
self.hands[i].clear_sets()
self.hands[i].sort()
def set_text(self, text):
self.text = text
def end_game(self):
self.ended = True
self.text = "Player " + str(self.turn + 1) + " lost."
def nbr_players_with_cards_left(self):
cnt = 0
for i in range(self.nbr_players):
if not self.hands[i].empty():
cnt += 1
return cnt
def next_turn(self):
temp = self.prev_player
self.prev_player = self.turn
for card in self.cur_selected.cards:
card.selected = False
self.cur_selected = Hand()
self.turn = (self.turn + 1) % self.nbr_players
cnt = 0
while self.hands[self.turn].empty() and cnt <= 6:
if isinstance(self.events[self.turn][-1], list) or self.events[self.turn][-1] < 0.3:
self.events[self.turn].append(1-self.out/10)
self.out += 1
self.turn = (self.turn + 1) % self.nbr_players
cnt += 1
if cnt > 6:
self.turn = self.prev_player
# If no other player has cards left, the game ends
if self.turn == self.prev_player:
self.events[self.turn].append(-.2)
self.events[temp].append(.1)
self.end_game()
def play(self, cards, call):
if self.mid.current_value != call and not self.mid.empty():
self.events[self.turn].append(-1)
return False
if not call in range(1, MAX_CARD_VALUE):
self.events[self.turn].append(-1)
return False
qparam = self.qagentparams()
qparams = self.qagentparamssmall()
if not self.hands[self.turn].delete_cards(cards.cards) or not cards:
self.events[self.turn].append(-1)
return False
was_a_lie = not self.mid.empty() and not self.mid.match()
self.mid.current_value = call
self.mid.add_cards(cards.cards)
cnt_call = cards.cnt_value(call)
# self.events[self.turn].append([qparam, '_2_' + str(call) + '_' + str(hash(cards)), [2, call, cards.cards]])
self.events[self.turn].append([qparams, '_2_' + str(cnt_call), [2, cnt_call]])
if was_a_lie:
self.events[self.turn].append(-0.0001)
self.events[self.prev_player].append(0.0001)
output = "Player " + str(self.turn+ 1) + " called " + str(cards.size()) + " card"
if cards.size() > 1:
output += "s"
output += " of value " + MP[call]
self.text = output
self.next_turn()
return True
def call_bs(self):
if self.prev_player == None or self.mid.empty():
self.text = "Invalid play"
self.events[self.turn].append(-1)
return False
self.text = "Player " + str(self.turn + 1) + " called BS on player " + str(self.prev_player + 1)
# self.events[self.turn].append([self.qagentparams(), '_1', (1,None,None)])
self.events[self.turn].append([self.qagentparamssmall(), '_1', [1, None]])
if self.mid.empty() or self.mid.match():
self.text = "It was not a lie"
self.events[self.turn].append(-0.005*self.mid.size())
self.events[self.prev_player].append(0.0025*self.mid.size())
self.mid.show()
self.hands[self.turn].add_cards(self.mid.hand.cards)
self.hands[self.turn].arrange()
self.mid.hand.clear()
self.next_turn()
self.mid.current_value = None
self.mid.last_play = None
return False
else:
self.text = "It was a lie"
self.events[self.turn].append(0.005*self.mid.size())
self.events[self.prev_player].append(-0.005*self.mid.size())
self.mid.show()
self.hands[self.prev_player].add_cards(self.mid.hand.cards)
self.hands[self.prev_player].arrange()
self.mid.hand.clear()
self.mid.current_value = None
self.mid.last_play = None
return True
def __str__(self):
output = ""
for i in range(self.nbr_players):
output += "Player " + str(i + 1) + ": "+ str(self.hands[i])+"\n"
output += "Middle: " + str(self.mid)
return output
def qagentparams(self):
ret = []
ret.append(self.nbr_players)
ret.append(self.turn)
ret.append([self.hands[i].size() for i in range(self.nbr_players)])
ret.append(self.mid.size())
ret.append(self.prev_player)
ret.append(self.call)
ret.append(self.mid.value())
ret.append(self.mid.last_play)
ret.append(hash(self.hands[self.turn]))
return '_'.join([str(elem) for elem in ret])
def qagentparamssmall(self):
ret = []
ret.append(self.nbr_players_with_cards_left())
ret.append(self.mid.size())
ret.append(self.mid.last_play)
if self.prev_player:
ret.append(self.hands[self.prev_player].size())
else: ret.append(-1)
ret.append(self.mid.value() != None and self.mid.value() != 0)
ret.append(self.hands[self.turn].size())
cnt_call = self.hands[self.turn].cnt_value(self.mid.value())
ret.append(cnt_call)
return '_'.join([str(elem) for elem in ret])
|
python
| 16 | 0.549937 | 157 | 38.061728 | 162 |
starcoderdata
|
package com.lucaskoch.movieapp.listeners;
import com.lucaskoch.movieapp.model.Video;
public interface OnSearchVideoListener {
void onResponseInfo(Video response);
void onErrorInfo(String message);
}
|
java
| 6 | 0.799043 | 42 | 25.125 | 8 |
starcoderdata
|
const assert = require('assert');
const {
getFromCli,
getFromDefault,
getFromEnv,
} = require('../../lib/config/config-utils');
const Config = require('../../lib/config');
function configHasError(args, errorFindFunction) {
const config = new Config(args, {});
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find(errorFindFunction);
assert(found);
}
describe('lib/config/from-default', function () {
it('provides expected values', function () {
const conf = getFromDefault();
assert.equal(conf.port, 80, 'default port');
assert(conf.dbPath !== '$HOME/sqlpad/db', 'dbPath should change');
});
});
describe('lib/config/from-env', function () {
it('provides expected values', function () {
const conf = getFromEnv({ SQLPAD_PORT: 8000 });
assert.equal(conf.port, 8000, 'conf.port');
});
});
describe('lib/config/from-cli', function () {
it('provides expected values', function () {
const conf = getFromCli({
keyPath: 'key/path',
certPath: 'cert/path',
admin: '
});
assert.equal(conf.keyPath, 'key/path', 'keyPath');
assert.equal(conf.certPath, 'cert/path', 'certPath');
assert.equal(conf.admin, ' 'admin');
});
});
describe('lib/config', function () {
it('Error: Unknown session store', function () {
configHasError({ sessionStore: 'not-real-store' }, (error) =>
error.includes('SQLPAD_SESSION_STORE must be one of')
);
});
it('Error: Unknown query result store', function () {
configHasError({ queryResultStore: 'not-real-store' }, (error) =>
error.includes('SQLPAD_QUERY_RESULT_STORE must be one of')
);
});
it('Error: redis store requires redis URI', function () {
configHasError({ sessionStore: 'redis' }, (error) =>
error.includes('Redis session store requires SQLPAD_REDIS_URI to be set')
);
configHasError({ queryResultStore: 'redis' }, (error) =>
error.includes(
'Redis query result store requires SQLPAD_REDIS_URI to be set'
)
);
});
it('Errors for old cli flag', function () {
const config = new Config({ debug: true }, {});
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find(
(error) => error.includes('debug') && error.includes('NOT RECOGNIZED')
);
assert(found, 'has error about old key');
});
it('Errors for old env var', function () {
const config = new Config({}, { SQLPAD_DEBUG: 'true' });
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find(
(error) =>
error.includes('SQLPAD_DEBUG') && error.includes('NOT RECOGNIZED')
);
assert(found, 'has error about old key');
});
it('Errors env connection missing name', function () {
const config = new Config(
{},
{ SQLPAD_CONNECTIONS__test__driver: 'postgres' }
);
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find((error) =>
error.includes('SQLPAD_CONNECTIONS__test__name missing')
);
assert(found, 'has error');
});
it('Errors env connection missing driver', function () {
const config = new Config(
{},
{ SQLPAD_CONNECTIONS__test__name: ' }
);
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find((error) =>
error.includes('SQLPAD_CONNECTIONS__test__driver missing')
);
assert(found, 'has error');
});
it('Errors env connection invalid driver', function () {
const config = new Config(
{},
{
SQLPAD_CONNECTIONS__test__name: '
SQLPAD_CONNECTIONS__test__driver: 'foo',
}
);
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find((error) =>
error.includes(
'Environment config SQLPAD_CONNECTIONS__test__driver invalid. "foo" not a supported driver.'
)
);
assert(found, 'has error');
});
it('Errors env connection invalid driver field', function () {
const config = new Config(
{},
{
SQLPAD_CONNECTIONS__test__name: 'My test',
SQLPAD_CONNECTIONS__test__driver: 'postgres',
SQLPAD_CONNECTIONS__test__wrongField: 'localhost',
}
);
const validations = config.getValidations();
assert(validations.errors);
const found = validations.errors.find((error) =>
error.includes(
'Environment config SQLPAD_CONNECTIONS__test__wrongField invalid. "wrongField" not a known field for postgres.'
)
);
assert(found, 'has error');
});
it('Warns for deprecated config', function () {
const config = new Config({ deprecatedTestConfig: 'just a test' }, {});
const validations = config.getValidations();
assert(validations.warnings);
const found = validations.warnings.find(
(warning) =>
warning.includes('deprecatedTestConfig') &&
warning.includes('DEPRECATED')
);
assert(found, 'has deprecated key warning');
});
it('.get() should get a value provided by default', function () {
const config = new Config({}, {});
assert.equal(config.get('ip'), '0.0.0.0');
});
it('.get() should only accept key in config items', function () {
const config = new Config({}, {});
assert.throws(() => config.get('non-existent-key'), Error);
});
it('cli args overrides env', function () {
const config = new Config(
{
appLogLevel: 'warn',
},
{
SQLPAD_APP_LOG_LEVEL: 'silent',
}
);
assert.equal(config.get('appLogLevel'), 'warn');
});
it('env provides value expected', function () {
const config = new Config(
{
appLogLevel: 'warn',
},
{
SQLPAD_APP_LOG_LEVEL: 'silent',
SQLPAD_WEB_LOG_LEVEL: 'silent',
}
);
assert.equal(config.get('webLogLevel'), 'silent');
});
it('gets validation for missing dbPath', function () {
const config = new Config({}, {});
const { errors } = config.getValidations();
assert(errors[0].includes('dbPath'));
});
});
|
javascript
| 28 | 0.620446 | 119 | 29.912621 | 206 |
starcoderdata
|
/*
* $Id: SmokeRunnerIgnoreTest.java,v 1.4 2016/12/18 20:19:38 oboehm Exp $
*
* Copyright (c) 2010 by
*
* 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 orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 23.04.2010 by oliver (
*/
package patterntesting.runtime.junit;
import static org.junit.Assert.fail;
import org.apache.logging.log4j.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* This JUnit tests should be ignored completely because the whole class is
* annotated with {@code @Ignore}.
*
* NOTE: You may find the '@Ignore' annotation commented out. The reaseon for
* this is the quality gate in SonarQube, which does not like skipped unit
* tests.
*
*
* @author oliver
* @since 1.0 (23.04.2010)
*/
@RunWith(SmokeRunner.class)
//@Ignore
public final class SmokeRunnerIgnoreTest extends SmokeRunnerTest {
private static final Logger LOG = LogManager.getLogger(SmokeRunnerIgnoreTest.class);
/**
* This test should be never called if this test class is annotated with
* '@Ignore'.
*/
@Test
public void testIgnore() {
Ignore annotation = this.getClass().getAnnotation(Ignore.class);
if (annotation == null) {
LOG.info("testIgnore() is executed because no @Ignore annotation was found.");
} else {
fail("this class should be completely ignored because of annotation " + annotation);
}
}
}
|
java
| 12 | 0.707209 | 101 | 31.365079 | 63 |
starcoderdata
|
private void selectPeriodAnyData(String dataFrom, String dataTo) {
LocalDate now = LocalDate.now();
// now.getYear();//int
// now.getMonth();//int
LocalDate from = LocalDate.parse(dataFrom, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
LocalDate to = LocalDate.parse(dataTo, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
click(By.id("dates"));
int diffMonth = from.getYear() - now.getYear()
== 0 ? from.getMonthValue() - now.getMonthValue() :
12 - now.getMonthValue() + from.getMonthValue();
// diffYear = from.getYear() - now.getYear();
// if (diffYear == 0) {
// diffMonth = from.getMonthValue() - now.getMonthValue();
//} else {
// diffMonth = 12 - now.getMonthValue() + from.getMonthValue();
//}
clickByNextMonth(diffMonth);
String locator = String.format("//div[text()=' %s ']", from.getDayOfMonth());
click(By.xpath(locator));
diffMonth = to.getYear() - from.getYear()
== 0 ? to.getMonthValue() - from.getMonthValue() :
12 - from.getMonthValue() + from.getMonthValue();
//diffYear = to.getYear() - from.getYear();
//if (diffYear == 0) {
// diffMonth = to.getMonthValue() - from.getMonthValue();
//} else {
// diffMonth = 12 - from.getMonthValue() + from.getMonthValue();
// }
clickByNextMonth(diffMonth);
locator = String.format("//div[text()=' %s ']", to.getDayOfMonth());
click(By.xpath(locator));
}
|
java
| 10 | 0.560853 | 94 | 44.571429 | 35 |
inline
|
import utils from '@weavy/dropin-js/src/common/utils';
import postal from '@weavy/dropin-js/src/common/postal';
import turbo from './turbo';
import browser from './browser';
import WeavyConsole from '@weavy/dropin-js/src/common/console';
const console = new WeavyConsole("overlay");
const _overlays = new Map();
document.addEventListener("click", utils.delegate("a[href].close-back, button.close-back", closeOverlay), true);
function closeOverlay(e) {
if (!isOpenedWindow() && !postal.isLeader) {
//console.log("close-back embedded")
if (e) {
e.stopImmediatePropagation();
e.preventDefault();
}
postal.postToParent({ name: "request:close" });
} else if (isOpenedWindow()) {
//console.log("close-back opened window")
if (e) {
e.stopImmediatePropagation();
e.preventDefault();
}
setTimeout(() => {
window.close();
}, 0);
} else {
//console.log("close-back normal navigation");
if (!e) {
var backButton = document.querySelector("a[href].close-back");
if (backButton) {
window.location.href = backButton.href;
}
}
}
}
function closeAllOverlays() {
_overlays.forEach((target, overlay) => {
try {
postal.unregisterContentWindow(overlay.name, true);
overlay.close()
}
catch (e) { /* move on */ }
});
_overlays.clear()
}
postal.whenLeader().then(function (isLeader) {
if (isLeader || isOpenedWindow()) {
document.addEventListener("keyup", function (e) {
if (e.which === 27) { // Esc
var closeBack = document.querySelector("a[href].close-back");
if (closeBack) {
e.stopImmediatePropagation();
closeBack.click();
}
}
if (e.which === 37) { // Left
if (allowedKeyTarget(e)) {
navPrev();
}
}
if (e.which === 39) { // Right
if (allowedKeyTarget(e)) {
navNext();
}
}
}, true)
} else {
postal.on("key:trigger", function (e, key) {
if (isOverlay()) {
if (key.which === 27) {
//console.log("esc requested");
postal.postToParent({ name: "request:close" });
}
if (key.which === 37) {
//console.log("prev requested");
navPrev();
}
if (key.which === 39) {
//console.log("next requested");
navNext();
}
}
});
document.addEventListener("keyup", function (e) {
if (allowedKeyTarget(e)) {
if (e.which === 27) { // Esc
if (isOpenedWindow()) {
var closeBack = document.querySelector("a[href].close-back");
if (closeBack) {
e.stopImmediatePropagation();
closeBack.click();
}
} else {
e.stopImmediatePropagation();
postal.postToParent({ name: "key:press", which: 27 });
}
}
if (e.which === 37) { // Left
e.stopImmediatePropagation();
postal.postToParent({ name: "key:press", which: 37 })
}
if (e.which === 39) { // Right
e.stopImmediatePropagation();
postal.postToParent({ name: "key:press", which: 39 })
}
}
})
}
});
function allowedKeyTarget(e) {
var noModalOpen = !document.documentElement.classList.contains("modal-open");
var notInputField = !e.target.matches("input, textarea, select") && !e.target.closest('[contenteditable="true"]');
return noModalOpen && notInputField;
}
function navPrev() {
//console.log("navigating prev", !!document.querySelector(".nav-prev a"));
var prevLink = document.querySelector(".nav-prev a");
if (prevLink && prevLink.href) {
turbo.visit(prevLink.href);
}
}
function navNext() {
//console.log("navigating next", !!document.querySelector(".nav-next a"));
var nextLink = document.querySelector(".nav-next a");
if (nextLink && nextLink.href) {
turbo.visit(nextLink.href);
}
}
function overlayNavigation(href, target) {
//console.log("wvy.overlay: overlay navigation");
var iOS = browser.platform === "iOS";
if (browser.mobile || browser.desktop /*|| document.body.classList.contains('controller-messenger')*/) {
var overlayWindow = _overlays.get(target);
if (overlayWindow && overlayWindow.closed) {
//console.debug("wvy.navigation: removing previous closed window");
try {
postal.unregisterContentWindow(overlayWindow.name, true);
} catch (e) { /* unable to unregister, no worries */ }
_overlays.delete(target);
overlayWindow = null;
}
if (overlayWindow) {
postal.postToFrame(overlayWindow.name, true, { name: "turbo-visit", url: href });
overlayWindow.focus();
} else {
if (!browser.webView && !iOS) {
//console.debug("wvy.overlay: open overlay window", target)
try {
//overlayWindow = window.open(href, "panel-overlay:" + target);
} catch (e) { /* can't open window */ }
}
if (overlayWindow) {
_overlays.set(target, overlayWindow);
postal.registerContentWindow(overlayWindow, "panel-overlay:" + target, true, window.location.origin);
} else {
console.debug("opening " + target + " via referred turbo navigation");
turbo.visit(href);
}
}
} else {
console.debug("opening overlay via turbo navigation");
turbo.visit(href);
}
}
function overlayLinkOpen(href, target, title) {
// Check url validity
var isSameDomain = window.location.origin === new URL(href, window.location).origin;
if (!isSameDomain) {
console.warn("invalid overlay url", href);
return false;
}
target = target || "overlay";
try {
// Change focus to receive keypress events
document.activeElement.blur()
document.body.focus();
} catch (e) { /* could not blur any element */ }
postal.whenLeader().then(function (isLeader) {
if (isLeader) {
overlayNavigation(href, target);
} else {
postal.postToParent({ name: "overlay-open", type: target, url: href, title: title, controls: { close: true } });
}
});
}
postal.on("overlay-open", (overlayOpen) => {
postal.whenLeader().then((isLeader) => {
if (isLeader) {
//console.debug("wvy.overlay: overlay-open received", overlayOpen.data);
overlayNavigation(overlayOpen.data.url, overlayOpen.data.type);
}
})
})
function isOverlay() {
try {
return (postal && postal.parentName && postal.parentName.startsWith("panel-overlay")) || false;
} catch (e) { /* no accessible parent name */ }
return false;
}
function isModal() {
try {
return postal && postal.parentName && postal.parentName.startsWith("panel-overlay:modal") || false;
} catch (e) { /* no accessible parent name */ }
return false;
}
function isOpenedWindow() {
try {
return window.opener && window.opener !== window.self || false;
} catch (e) { /* can't access any opener */ }
return false;
}
postal.whenLeader().then(() => {
if (isOverlay()) {
document.documentElement.classList.add("overlay");
}
})
export default {
open: overlayLinkOpen,
close: closeOverlay,
closeAll: closeAllOverlays,
isModal: isModal,
isOverlay: isOverlay,
isOpenedWindow: isOpenedWindow
}
|
javascript
| 27 | 0.601459 | 118 | 26.938462 | 260 |
starcoderdata
|
// License: https://github.com/CrendKing/avisynth_filter/blob/master/LICENSE
#include "pch.h"
#include "allocator.h"
#include "media_sample.h"
namespace SynthFilter {
CSynthFilterAllocator::CSynthFilterAllocator(HRESULT *phr, CSynthFilterInputPin &inputPin)
: CMemAllocator(NAME("CSynthFilterAllocator"), nullptr, phr)
, _inputPin(inputPin) {
}
// allocate CSynthFilterMediaSample instead of CMediaSample
auto CSynthFilterAllocator::Alloc() -> HRESULT {
const std::unique_lock lock(*this);
HRESULT hr = CBaseAllocator::Alloc();
if (FAILED(hr)) {
return hr;
}
if (hr == S_FALSE) {
ASSERT(m_pBuffer);
return NOERROR;
}
ASSERT(hr == S_OK);
if (m_pBuffer) {
ReallyFree();
}
if (m_lSize < 0 || m_lPrefix < 0 || m_lCount < 0) {
return E_OUTOFMEMORY;
}
LONG lAlignedSize = m_lSize + m_lPrefix;
if (lAlignedSize < m_lSize) {
return E_OUTOFMEMORY;
}
if (m_lAlignment > 1) {
if (const LONG lRemainder = lAlignedSize % m_lAlignment; lRemainder != 0) {
const LONG lNewSize = lAlignedSize + m_lAlignment - lRemainder;
if (lNewSize < lAlignedSize) {
return E_OUTOFMEMORY;
}
lAlignedSize = lNewSize;
}
}
ASSERT(lAlignedSize % m_lAlignment == 0);
const SIZE_T lToAllocate = m_lCount * static_cast
if (lToAllocate > MAXLONG) {
return E_OUTOFMEMORY;
}
m_pBuffer = static_cast
lToAllocate,
MEM_COMMIT,
PAGE_READWRITE));
if (m_pBuffer == nullptr) {
return E_OUTOFMEMORY;
}
ASSERT(m_lAllocated == 0);
LPBYTE pNext = m_pBuffer;
for (CMediaSample *pSample; m_lAllocated < m_lCount; m_lAllocated++, pNext += lAlignedSize) {
pSample = new CSynthFilterMediaSample(
NAME("CSynthFilter memory media sample"),
this,
&hr,
pNext + m_lPrefix,
m_lSize);
ASSERT(SUCCEEDED(hr));
if (pSample == nullptr) {
return E_OUTOFMEMORY;
}
m_lFree.Add(pSample);
}
m_bChanged = FALSE;
return NOERROR;
}
auto STDMETHODCALLTYPE CSynthFilterAllocator::SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual) -> HRESULT {
const BITMAPINFOHEADER *bmi = Format::GetBitmapInfo(_inputPin.CurrentMediaType());
pRequest->cbBuffer = max(static_cast + Format::INPUT_MEDIA_SAMPLE_BUFFER_PADDING), pRequest->cbBuffer);
return __super::SetProperties(pRequest, pActual);
}
}
|
c++
| 14 | 0.598394 | 146 | 26.666667 | 99 |
starcoderdata
|
static void pcnetUpdateRingHandlers(PPCNETSTATE pThis)
{
PPDMDEVINS pDevIns = PCNETSTATE_2_DEVINS(pThis);
int rc;
Log(("pcnetUpdateRingHandlers TD %RX32 size %#x -> %RX32 ?size? %#x\n", pThis->TDRAPhysOld, pThis->cbTDRAOld, pThis->GCTDRA, pcnetTdraAddr(pThis, 0)));
Log(("pcnetUpdateRingHandlers RX %RX32 size %#x -> %RX32 ?size? %#x\n", pThis->RDRAPhysOld, pThis->cbRDRAOld, pThis->GCRDRA, pcnetRdraAddr(pThis, 0)));
/** @todo unregister order not correct! */
#ifdef PCNET_MONITOR_RECEIVE_RING
if (pThis->GCRDRA != pThis->RDRAPhysOld || CSR_RCVRL(pThis) != pThis->cbRDRAOld)
{
if (pThis->RDRAPhysOld != 0)
PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pDevIns),
pThis->RDRAPhysOld & ~PAGE_OFFSET_MASK);
rc = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pDevIns),
pThis->GCRDRA & ~PAGE_OFFSET_MASK,
RT_ALIGN(pcnetRdraAddr(pThis, 0), PAGE_SIZE) - 1,
pThis->hNoPollingHandlerType, pDevIns,
pThis->pDevInsHC->pvInstanceDataHC,
pThis->pDevInsHC->pvInstanceDataRC,
"PCNet receive ring write access handler");
AssertRC(rc);
pThis->RDRAPhysOld = pThis->GCRDRA;
pThis->cbRDRAOld = pcnetRdraAddr(pThis, 0);
}
#endif /* PCNET_MONITOR_RECEIVE_RING */
#ifdef PCNET_MONITOR_RECEIVE_RING
/* 3 possibilities:
* 1) TDRA on different physical page as RDRA
* 2) TDRA completely on same physical page as RDRA
* 3) TDRA & RDRA overlap partly with different physical pages
*/
RTGCPHYS32 RDRAPageStart = pThis->GCRDRA & ~PAGE_OFFSET_MASK;
RTGCPHYS32 RDRAPageEnd = (pcnetRdraAddr(pThis, 0) - 1) & ~PAGE_OFFSET_MASK;
RTGCPHYS32 TDRAPageStart = pThis->GCTDRA & ~PAGE_OFFSET_MASK;
RTGCPHYS32 TDRAPageEnd = (pcnetTdraAddr(pThis, 0) - 1) & ~PAGE_OFFSET_MASK;
if ( RDRAPageStart > TDRAPageEnd
|| TDRAPageStart > RDRAPageEnd)
{
#endif /* PCNET_MONITOR_RECEIVE_RING */
/* 1) */
if (pThis->GCTDRA != pThis->TDRAPhysOld || CSR_XMTRL(pThis) != pThis->cbTDRAOld)
{
if (pThis->TDRAPhysOld != 0)
PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pDevIns),
pThis->TDRAPhysOld & ~PAGE_OFFSET_MASK);
rc = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pDevIns),
pThis->GCTDRA & ~PAGE_OFFSET_MASK,
RT_ALIGN(pcnetTdraAddr(pThis, 0), PAGE_SIZE) - 1,
pThis->hNoPollingHandlerType,
pThis->CTX_SUFF(pDevIns)->pvInstanceDataR3,
pThis->CTX_SUFF(pDevIns)->pvInstanceDataR0,
pThis->CTX_SUFF(pDevIns)->pvInstanceDataRC,
"PCNet transmit ring write access handler");
AssertRC(rc);
pThis->TDRAPhysOld = pThis->GCTDRA;
pThis->cbTDRAOld = pcnetTdraAddr(pThis, 0);
}
#ifdef PCNET_MONITOR_RECEIVE_RING
}
else
if ( RDRAPageStart != TDRAPageStart
&& ( TDRAPageStart == RDRAPageEnd
|| TDRAPageEnd == RDRAPageStart
)
)
{
/* 3) */
AssertFailed();
}
/* else 2) */
#endif
}
|
c++
| 17 | 0.538655 | 155 | 43.246914 | 81 |
inline
|
def PackageInfoToString(package_info_msg):
# Combine the components into the full CPV string that SplitCPV parses.
# TODO: Use the lib.parser.package_info.PackageInfo class instead.
if not package_info_msg.package_name:
raise ValueError('Invalid PackageInfo message.')
c = ('%s/' % package_info_msg.category) if package_info_msg.category else ''
p = package_info_msg.package_name
v = ('-%s' % package_info_msg.version) if package_info_msg.version else ''
return '%s%s%s' % (c, p, v)
|
python
| 9 | 0.712575 | 78 | 49.2 | 10 |
inline
|
def cf_type(self):
"""Gets the cf_type of this ExtendedAttributeDefinition. # noqa: E501
The type of a custom field. # noqa: E501
:return: The cf_type of this ExtendedAttributeDefinition. # noqa: E501
:rtype: CustomFieldType
"""
return self._cf_type
|
python
| 5 | 0.622517 | 79 | 32.666667 | 9 |
inline
|
int main() {
// Init Sun
particle sun;
sun.mass = sun_mass;
// Init Earth
particle earth;
earth.mass = earth_mass;
earth.position.x = -2.521092863852298E+10; // values from: https://ssd.jpl.nasa.gov/horizons.cgi
earth.position.y = 1.449279195712076E+11;
earth.position.z = -6.164888475164771E+5;
earth.velocity.x = -2.983983333368269E+4;
earth.velocity.y = -5.207633918704476E+3;
earth.velocity.z = 6.169062303484907E-2;
// Init Moon
particle moon;
moon.mass = moon_mass;
moon.position.x = -2.552857888050620E+10;
moon.position.y = 1.446860363961675E+11;
moon.position.z = 3.593933517466486E+7;
moon.velocity.x = -2.927904627038706E+4;
moon.velocity.y = -6.007566180814270E+3;
moon.velocity.z = -1.577640655646029;
/* init the array of particless */
particle particles[3] = {sun, earth, moon};
double dist[3][3] {0};
/* init time and counters for iteration */
int t{ 0 };
int dt{ min_to_sec };
int print_t{ 30 * day_to_sec };
int total_t{ year_to_sec };
std::cout << "\nEarth location: " << particles[1].position << "\n";
std::cout << "Earth velocity: " << particles[1].velocity << "\n\n";
while(t < total_t) {
update_universe(particles, dist, dt);
if ((t % (print_t)) == 0) {
std::cout << "Day " << (t / day_to_sec) << ": Earth->Sun = " << particles[0].distance(particles[1]) << " m\n";
}
t += dt;
}
std::cout << "\nEarth location: " << particles[1].position << "\n";
std::cout << "Earth velocity: " << particles[1].velocity << "\n\n";
return 0;
}
|
c++
| 14 | 0.585558 | 123 | 30.113208 | 53 |
inline
|
#include "stm32f103_hal_core.h"
void enableIRQ(int irq, int priority);
void disableIRQ(int irq);
void setPendingIRQ(int irq);
void clearPendingIRQ(int irq);
void enableInterrupts();
void disableInterrupts();
|
c
| 5 | 0.783654 | 38 | 25.125 | 8 |
starcoderdata
|
/*** Created by Shalom on 30/03/2016.*/
(function () {
angular.module('bn.DS')
.factory('Users', function (DS) {
var ctrl = this;
var usersDS = DS.defineResource({
name: 'users', type: 'Users', idAttribute: 'id',
});
usersDS.findAll().then((users)=> {
usersDS.inject(users)
});
return usersDS;
})
})();
|
javascript
| 19 | 0.449074 | 64 | 21.736842 | 19 |
starcoderdata
|
var express = require("express");
var router = express.Router();
var db = require("../models/sequelize.js");
var groupController = require("../controllers/group.js");
var userController = require("../controllers/user.js");
var eventController = require("../controllers/event.js");
/* POST new group */
//Request body: {groupName:
router.post("/createGroup", groupController.createGroup, groupController.addUser);
/* PUT (edit) existing group info */
//Request header: {groupId: body: {groupName: description:
router.put("/editGroup", groupController.findGroup, groupController.checkPermissions, groupController.editGroup);
/* PUT (edit) existing group description */
//Request header: {groupId: body: {description:
router.put("/editGroupDescription", groupController.findGroup, groupController.checkMembership, groupController.editGroupDescription);
/* GET information for one group, including users */
//Request header: {groupId:
router.get("/getGroupInfo", groupController.findGroup, groupController.checkMembership, groupController.getGroupInfo);
/* POST join logged in user to group by groupId */
//Request header: {groupId:
router.post("/joinGroup", groupController.findGroup, groupController.checkGroupJoinable, groupController.addUser);
/* PUT request to leave group by groupId */
//Request header: {groupId:
router.post("/leaveGroup", groupController.findGroup, groupController.checkMembership, groupController.leaveGroup);
/* PUT request to remove group member */
//Request header: {groupId: body: {userId:
router.put("/removeMember", groupController.findGroup, groupController.checkPermissions, groupController.removeUser);
/* GET events for some group*/
//Request header: {groupId:
router.get("/getEvents", groupController.findGroup, groupController.checkMembership, groupController.getEvents);
/* DELETE target group*/
//Request header: {groupId: <int}
router.delete("/destroyGroup", groupController.findGroup, groupController.checkPermissions, groupController.destroyGroup);
/* GET optimal availibilties for all users in group*/
//Request header: {groupId:
//Body: {threshold: day:
router.post("/getAvailabilities", groupController.findGroup, groupController.checkMembership, groupController.getAvailabilities);
module.exports = router;
|
javascript
| 3 | 0.767585 | 134 | 45.75 | 52 |
starcoderdata
|
Vue.component('recommendation', {
props: ['user'],
data() {
return {
recommendation: {},
recommendation_loaded: false,
busy: false,
};
},
created() {
this.loadRecommenation();
},
computed: {
slug() {
return window.location.href.split('/')[4];
},
},
methods: {
accept(){
var self = this;
var sent = {
slugs: [this.recommendation.slug]
};
this.busy = true;
axios.post('/api/recommendations/accept', sent)
.then(response => {
self.loadRecommenation();
self.busy = false;
}, response => {
$("#modal-error").modal('show');
setTimeout(function(){
$("#modal-error").modal('hide');
}, 8000);
})
},
reject(){
var self = this;
var sent = {
slugs: [this.recommendation.slug]
};
this.busy = true;
axios.post('/api/recommendations/reject', sent)
.then(response => {
self.loadRecommenation();
self.busy = false;
}, response => {
$("#modal-error").modal('show');
setTimeout(function(){
$("#modal-error").modal('hide');
}, 8000);
})
},
makePending(){
var self = this;
var sent = {
slugs: [this.recommendation.slug]
};
this.busy = true;
axios.post('/api/recommendations/make_pending', sent)
.then(response => {
self.loadRecommenation();
self.busy = false;
}, response => {
$("#modal-error").modal('show');
setTimeout(function(){
$("#modal-error").modal('hide');
}, 8000);
})
},
loadRecommenation() {
var self = this;
this.recommendation_loaded = false;
axios.get('/api/recommendations/' + this.slug)
.then(response => {
self.recommendation = response.data;
self.recommendation_loaded = true;
},
response => {
switch (response.status){
case 401:
window.location.href = '/';
break;
default:
$("#modal-error").modal('show');
setTimeout(function(){
$("#modal-error").modal('hide');
}, 8000);
break;
}
});
}
}
});
|
javascript
| 23 | 0.375521 | 69 | 32.212766 | 94 |
starcoderdata
|
#include "../git-compat-util.h"
char *gitmkdtemp(char *template)
{
if (!*mktemp(template) || mkdir(template, 0700))
return NULL;
return template;
}
|
c
| 10 | 0.718182 | 66 | 23.444444 | 9 |
starcoderdata
|
import React, { useState, useEffect } from 'react';
// import sections
import Hero from '../components/sections/Hero';
import FeaturesTiles from '../components/sections/FeaturesTiles';
import FeaturesSplit from '../components/sections/FeaturesSplit';
import Testimonial from '../components/sections/Testimonial';
import Cta from '../components/sections/Cta';
import { getDeveloper, createDeveloper } from '../utils/DataService.mjs'
import firebase from 'firebase/app'
var firebaseui = require('firebaseui');
const SignIn = (props) => {
const [ui, setUI] = useState();
//setUI(props.ui);
useEffect(() => {
if (!ui) {
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
// User successfully signed in.
// Return type determines whether we continue the redirect automatically
// or whether we leave that to developer to handle.
return true;
},
uiShown: function() {
// The widget is rendered.
// Hide the loader.
//document.getElementById('loader').style.display = 'none';
}
},
// Will use popup for IDP Providers sign-in flow instead of the default, redirect.
signInFlow: 'popup',
signInSuccessUrl: 'apis',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID
],
// Terms of service url.
tosUrl: '
// Privacy policy url.
privacyPolicyUrl: '
};
props.ui.start('#firebaseui-auth-container', uiConfig);
setUI(props.ui);
}
}, ui);
return (
<>
<section className="testimonial section center-content illustration-section-01">
<div className="container">
<div className="testimonial-inner section-inner">
<div className="testimonial-content">
<h1 class="mt-0 mb-16 reveal-from-bottom" data-reveal-delay="200">Sign <span class="text-color-primary">in
<div className="container-xs">
<p className="m-0 mb-32 reveal-from-bottom" data-reveal-delay="400">
Embrace the API revolution with React web templates connected to Apigee X 🚀.
<div class="tiles-wrap">
<div id="firebaseui-auth-container">
);
}
export default SignIn;
|
javascript
| 20 | 0.595099 | 130 | 31.559524 | 84 |
starcoderdata
|
@PostMapping("/myUser/{privateUserId}/challenge_status/{challengeId}")
@ApiOperation(value = "This interface is called whenever a user is starting or finishing a challenge.", response = DefaultResponse.class)
@ApiResponses(value = {@ApiResponse(code = 404, message = "MyUser not found."), @ApiResponse(code = 404, message = "Challenge not found.")})
public Object setChallengeResult(@PathVariable String privateUserId, @PathVariable Long challengeId, @RequestParam State state) {
MyUser user = userService.getUserByPrivateUserId(privateUserId);
if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("MyUser not found.");
}
Challenge challenge = challengeService.getChallengeFromId(challengeId);
if (challenge == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Challenge not found.");
}
// Achievements preAchievements;
// try {
// preAchievements = userService.getUserAchievements(user, imageUrlPrefix);
// } catch (IOException e) {
// logger.error("Error retrieving achievements.", e);
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving achievements.");
// }
// System.out.println("precooking: " + preAchievements.getAchievementsByCategory().get(Category.cooking).get(0));
ChallengeStatus challengeResult = new ChallengeStatus();
challengeResult.setUserId(user.getId());
challengeResult.setChallengeId(challenge.getId());
challengeResult.setTimeStamp(Instant.now());
challengeResult.setState(state);
challengeService.save(challengeResult);
return DefaultResponse.SUCCESS;
// Achievements postAchievements;
// try {
// postAchievements = userService.getUserAchievements(user, imageUrlPrefix);
// } catch (IOException e) {
// logger.error("Error retrieving achievements.", e);
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving achievements.");
// }
//
// System.out.println("postcooking: " + postAchievements.getAchievementsByCategory().get(Category.cooking).get(0));
//
// // remove all achievements that were present before saving that challenge result
// removeAllButNewAchievements(postAchievements.getOveralLevel(), preAchievements.getOveralLevel());
// Iterator<Entry<Category, List<Achievement>>> categoryAndAchievementIterator = postAchievements.getAchievementsByCategory().entrySet().iterator();
// while (categoryAndAchievementIterator.hasNext()) {
// Entry<Category, List<Achievement>> entry = categoryAndAchievementIterator.next();
// List<Achievement> preList = preAchievements.getAchievementsByCategory().get(entry.getKey());
// removeAllButNewAchievements(entry.getValue(), preList);
// if (entry.getValue().size() == 0) {
// categoryAndAchievementIterator.remove();
// }
// }
//
// return postAchievements;
}
|
java
| 11 | 0.738829 | 151 | 47.949153 | 59 |
inline
|
package ejb.container;
import java.util.HashMap;
import java.util.Map;
import ejb.exceptions.InvokeAnnotatedMethodException;
public class ClientHolder {
private Map<Object, Client> mClientBeans;
public ClientHolder()
{
mClientBeans = new HashMap<Object, Client>();
}
public boolean checkClient(Object inClient)
{
if(mClientBeans.containsKey(inClient))
return true;
mClientBeans.put(inClient, new Client(inClient));
return false;
}
public Client getClient(Object inClient)
{
checkClient(inClient);
return mClientBeans.get(inClient);
}
public void releaseClient(Object inClient)
{
if(mClientBeans.containsKey(inClient))
{
mClientBeans.remove(inClient);
}
}
public void destroyClient(Client inClient) throws InvokeAnnotatedMethodException
{
if(mClientBeans.containsKey(inClient.getId()))
{
mClientBeans.remove(inClient);
inClient.release();
}
}
}
|
java
| 11 | 0.745875 | 81 | 18.76087 | 46 |
starcoderdata
|
/** ` Micro Mezzo Macro Flation -- Overheated Economy ., **/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define REP(i, n) for (int i=0;i<int(n);++i)
#define FOR(i, a, b) for (int i=int(a);i<int(b);++i)
#define DWN(i, b, a) for (int i=int(b-1);i>=int(a);--i)
#define REP_1(i, n) for (int i=1;i<=int(n);++i)
#define FOR_1(i, a, b) for (int i=int(a);i<=int(b);++i)
#define DWN_1(i, b, a) for (int i=int(b);i>=int(a);--i)
#define REP_C(i, n) for (int n____=int(n),i=0;i<n____;++i)
#define FOR_C(i, a, b) for (int b____=int(b),i=a;i<b____;++i)
#define DWN_C(i, b, a) for (int a____=int(a),i=b-1;i>=a____;--i)
#define REP_N(i, n) for (i=0;i<int(n);++i)
#define FOR_N(i, a, b) for (i=int(a);i<int(b);++i)
#define DWN_N(i, b, a) for (i=int(b-1);i>=int(a);--i)
#define REP_1_C(i, n) for (int n____=int(n),i=1;i<=n____;++i)
#define FOR_1_C(i, a, b) for (int b____=int(b),i=a;i<=b____;++i)
#define DWN_1_C(i, b, a) for (int a____=int(a),i=b;i>=a____;--i)
#define REP_1_N(i, n) for (i=1;i<=int(n);++i)
#define FOR_1_N(i, a, b) for (i=int(a);i<=int(b);++i)
#define DWN_1_N(i, b, a) for (i=int(b);i>=int(a);--i)
#define REP_C_N(i, n) for (n____=int(n),i=0;i<n____;++i)
#define FOR_C_N(i, a, b) for (b____=int(b),i=a;i<b____;++i)
#define DWN_C_N(i, b, a) for (a____=int(a),i=b-1;i>=a____;--i)
#define REP_1_C_N(i, n) for (n____=int(n),i=1;i<=n____;++i)
#define FOR_1_C_N(i, a, b) for (b____=int(b),i=a;i<=b____;++i)
#define DWN_1_C_N(i, b, a) for (a____=int(a),i=b;i>=a____;--i)
#define DO(n) while(n--)
#define DO_C(n) int n____ = n; while(n____--)
#define TO(i, a, b) int s_=a<b?1:-1,b_=b+s_;for(int i=a;i!=b_;i+=s_)
#define TO_1(i, a, b) int s_=a<b?1:-1,b_=b;for(int i=a;i!=b_;i+=s_)
#define SQZ(i, j, a, b) for (int i=int(a),j=int(b)-1;i<j;++i,--j)
#define SQZ_1(i, j, a, b) for (int i=int(a),j=int(b);i<=j;++i,--j)
#define REP_2(i, j, n, m) REP(i, n) REP(j, m)
#define REP_2_1(i, j, n, m) REP_1(i, n) REP_1(j, m)
#define ALL(A) A.begin(), A.end()
#define LLA(A) A.rbegin(), A.rend()
#define CPY(A, B) memcpy(A, B, sizeof(A))
#define INS(A, P, B) A.insert(A.begin() + P, B)
#define ERS(A, P) A.erase(A.begin() + P)
#define BSC(A, X) find(ALL(A), X) // != A.end()
#define CTN(T, x) (T.find(x) != T.end())
#define SZ(A) int(A.size())
#define PB push_back
#define MP(A, B) make_pair(A, B)
#define Rush int T____; RD(T____); DO(T____)
#pragma comment(linker, "/STACK:36777216")
#pragma GCC optimize ("O2")
#define Ruby system("ruby main.rb")
#define Haskell system("runghc main.hs")
#define Pascal system("fpc main.pas")
/** I/O Accelerator **/
/* ... :" We are I/O Accelerator ... Use us at your own risk ;) ... " .. */
template<class T> inline void RD(T &);
template<class T> inline void OT(const T &);
inline int RD(){ int x; RD(x); return x;}
template<class T> inline T& _RD(T &x){ RD(x); return x;}
inline void RS(char *s){scanf("%s", s);}
template<class T0, class T1> inline void RD(T0 &x0, T1 &x1){RD(x0), RD(x1);}
template<class T0, class T1, class T2> inline void RD(T0 &x0, T1 &x1, T2 &x2){RD(x0), RD(x1), RD(x2);}
template<class T0, class T1, class T2, class T3> inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3){RD(x0), RD(x1), RD(x2), RD(x3);}
template<class T0, class T1, class T2, class T3, class T4> inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4){RD(x0), RD(x1), RD(x2), RD(x3), RD(x4);}
template<class T0, class T1, class T2, class T3, class T4, class T5> inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5){RD(x0), RD(x1), RD(x2), RD(x3), RD(x4), RD(x5);}
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6> inline void RD(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5, T6 &x6){RD(x0), RD(x1), RD(x2), RD(x3), RD(x4), RD(x5), RD(x6);}
template<class T0, class T1> inline void OT(T0 &x0, T1 &x1){OT(x0), OT(x1);}
template<class T0, class T1, class T2> inline void OT(T0 &x0, T1 &x1, T2 &x2){OT(x0), OT(x1), OT(x2);}
template<class T0, class T1, class T2, class T3> inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3){OT(x0), OT(x1), OT(x2), OT(x3);}
template<class T0, class T1, class T2, class T3, class T4> inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4){OT(x0), OT(x1), OT(x2), OT(x3), OT(x4);}
template<class T0, class T1, class T2, class T3, class T4, class T5> inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5){OT(x0), OT(x1), OT(x2), OT(x3), OT(x4), OT(x5);}
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6> inline void OT(T0 &x0, T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5, T6 &x6){OT(x0), OT(x1), OT(x2), OT(x3), OT(x4), OT(x5), OT(x6);}
template<class T> inline void RST(T &A){memset(A, 0, sizeof(A));}
template<class T0, class T1> inline void RST(T0 &A0, T1 &A1){RST(A0), RST(A1);}
template<class T0, class T1, class T2> inline void RST(T0 &A0, T1 &A1, T2 &A2){RST(A0), RST(A1), RST(A2);}
template<class T0, class T1, class T2, class T3> inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3){RST(A0), RST(A1), RST(A2), RST(A3);}
template<class T0, class T1, class T2, class T3, class T4> inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4){RST(A0), RST(A1), RST(A2), RST(A3), RST(A4);}
template<class T0, class T1, class T2, class T3, class T4, class T5> inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5){RST(A0), RST(A1), RST(A2), RST(A3), RST(A4), RST(A5);}
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6> inline void RST(T0 &A0, T1 &A1, T2 &A2, T3 &A3, T4 &A4, T5 &A5, T6 &A6){RST(A0), RST(A1), RST(A2), RST(A3), RST(A4), RST(A5), RST(A6);}
/** Add - On **/
// <<= ` 0. Daily Use .,
template<class T> inline void checkMin(T &a,const T b){if (b<a) a=b;}
template<class T> inline void checkMax(T &a,const T b){if (b>a) a=b;}
template <class T, class C> inline void checkMin(T& a, const T b, C c){if (c(b,a)) a = b;}
template <class T, class C> inline void checkMax(T& a, const T b, C c){if (c(a,b)) a = b;}
template<class T> inline T min(T a, T b, T c){return min(min(a, b), c);}
template<class T> inline T max(T a, T b, T c){return max(max(a, b), c);}
template<class T> inline T sqr(T a){return a*a;}
template<class T> inline T cub(T a){return a*a*a;}
int Ceil(int x, int y){return (x - 1) / y + 1;}
// <<= ` 1. Bitwise Operation .,
inline bool _1(int x, int i){return x & 1<<i;}
inline int _1(int i){return 1<<i;}
inline int _U(int i){return _1(i) - 1;};
inline int count_bits(int x){
x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1);
x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2);
x = (x & 0x0f0f0f0f) + ((x & 0xf0f0f0f0) >> 4);
x = (x & 0x00ff00ff) + ((x & 0xff00ff00) >> 8);
x = (x & 0x0000ffff) + ((x & 0xffff0000) >> 16);
return x;
}
template<class T> inline T low_bit(T x) {
return x & -x;
}
template<class T> inline T high_bit(T x) {
T p = low_bit(x);
while (p != x) x -= p, p = low_bit(x);
return p;
}
// <<= ' 0. I/O Accelerator interface .,
template<class T> inline void RD(T &x){
//cin >> x;
//scanf("%d", &x);
char c; for (c = getchar(); c < '0'; c = getchar()); x = c - '0'; for (c = getchar(); c >= '0'; c = getchar()) x = x * 10 + c - '0';
//char c; c = getchar(); x = c - '0'; for (c = getchar(); c >= '0'; c = getchar()) x = x * 10 + c - '0';
}
template<class T> inline void OT(const T &x){
printf("%d\n", x);
}
/* .................................................................................................................................. */
const int N = 100001;
int l[N], r[N], p[N], rev[N]; bool rt[N];
int n;
#define lx l[x]
#define rx r[x]
inline void Release(int x){
if (x == 0) return;
if (rev[x]){
swap(lx, rx);
rev[lx] ^= 1, rev[rx] ^= 1;
rev[x] = 0;
}
}
inline void Set(int l[], int y, int x){
l[y] = x, p[x] = y;
}
#define z p[y]
inline void Rotate(int x){
int y = p[x];
if (!rt[y]) Release(z), Set(y == l[z] ? l : r, z, x);
else p[x] = z;
Release(y), Release(x);
if (x == l[y]) Set(l, y, rx), Set(r, x, y);
else Set(r, y, lx), Set(l, x, y);
if (rt[y]) rt[y] = false, rt[x] = true;
}
inline void Splay(int x){
while (!rt[x]) Rotate(x);
}
int Access(int x){
int y = 0; do{
Splay(x), Release(x);
rt[rx] = true, rt[rx = y] = false;
x = p[y = x];
} while (x);
return y;
}
inline int Root(int x){
for (x = Access(x); Release(x), lx ; x = lx);
return x;
}
inline void Evert(int x){
rev[Access(x)] ^= 1;
}
// Public :
void Query(int x, int y){
puts(Root(x) == Root(y) ? "YES" : "NO");
}
void Link(int x, int y){
if (Root(x) == Root(y)) return;
Evert(x), Splay(x), p[x] = y, Access(x);
}
void Cut(int x, int y){
Evert(y), Splay(y), Access(x), Splay(x);
if (lx != y) return;
p[lx] = p[x], rt[lx] = true, p[x] = lx = 0;
}
int main(){
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
REP_1_C(i, _RD(n)) rt[i] = true;
int a, b; char cmd[9]; DO_C(RD()){
RS(cmd); RD(a, b); if (cmd[0] == 'c') Query(a, b);
else if (cmd[0] == 'a') Link(a, b);
else Cut(a, b);
}
}
|
c++
| 13 | 0.541635 | 214 | 35.400778 | 257 |
starcoderdata
|
namespace basic {
// Does nothing if pointer of type `Base` points
// to something that is not exactly of type 'DerivedPtr'
template <class DerivedPtr, class Base>
DerivedPtr exact_pointer_cast(Base* basePtr)
{
static_assert(std::is_pointer<DerivedPtr>::value);
using Derived
= typename std::remove_cv<
typename std::remove_pointer<DerivedPtr>::type
>::type;
static_assert(std::is_final<Derived>::value);
if (basePtr != nullptr
&& typeid(*basePtr) == typeid(Derived))
{
DCHECK_VALID_PTR(basePtr); // Supports memory tools like ASAN
return static_cast<DerivedPtr>(basePtr);
}
return nullptr;
}
|
c
| 11 | 0.691589 | 65 | 25.791667 | 24 |
inline
|
#!/usr/bin/env python
import os
import json
# from deploy import Compose
# from play import Playbook
# from run_etcd_cmd import Deploy
from set_auth_cmd import Auth
from data import Data
from utils import logging
PATH = os.path.dirname(os.path.abspath(__file__))
logger = logging.getLogger('ssh_auth')
class SSHAuth(object):
def __init__(self):
self.server = 'localhost'
self.port = 12379
self.key = 'nodes'
self.former = set()
def watch(self, inst):
inst.watch(key=self.key, timeout=0)
cur_nodes = set(inst.get(key=self.key).value.split(','))
logger.debug(cur_nodes)
diff = cur_nodes.difference(self.former)
self.former = self.former.union(cur_nodes)
logger.debug('diff is {}'.format(diff))
return diff
def gen_hosts(self, nodes):
fd = open('./playbook/hosts', 'w+')
fd.write('[cluster]\n')
for node in nodes:
host_line = '{} ansible_ssh_user=userxxx ansible_ssh_pass=***'.format(node)
fd.write(host_line)
fd.close()
def callback(self, diff):
# Update 'hosts' file with diff
logger.debug('Update hosts file, data: %s', tuple(diff))
Data.dump(diff)
a = Auth()
a.run()
def main():
logger.info('Program running...')
s = SSHAuth()
d = Data(host=s.server, port=s.port)
s.nodes = d.get(key=s.key).value
logger.debug(s.nodes)
while True:
diff = s.watch(d)
if not diff:
logger.info('No valid change occurred')
continue
s.callback(diff)
if __name__ == "__main__":
main()
|
python
| 16 | 0.584597 | 87 | 25.596774 | 62 |
starcoderdata
|
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* BQPaymentTermsRetrieveOutputModelPaymentTermsInstanceReport
*/
public class BQPaymentTermsRetrieveOutputModelPaymentTermsInstanceReport {
private Object paymentTermsInstanceReportRecord = null;
private String paymentTermsInstanceReportType = null;
private String paymentTermsInstanceReportParameters = null;
private Object paymentTermsInstanceReport = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The input information used to assemble the report that can be on-going, periodic and actual and projected
* @return paymentTermsInstanceReportRecord
**/
public Object getPaymentTermsInstanceReportRecord() {
return paymentTermsInstanceReportRecord;
}
public void setPaymentTermsInstanceReportRecord(Object paymentTermsInstanceReportRecord) {
this.paymentTermsInstanceReportRecord = paymentTermsInstanceReportRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external report available
* @return paymentTermsInstanceReportType
**/
public String getPaymentTermsInstanceReportType() {
return paymentTermsInstanceReportType;
}
public void setPaymentTermsInstanceReportType(String paymentTermsInstanceReportType) {
this.paymentTermsInstanceReportType = paymentTermsInstanceReportType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the report (e.g. period, content type)
* @return paymentTermsInstanceReportParameters
**/
public String getPaymentTermsInstanceReportParameters() {
return paymentTermsInstanceReportParameters;
}
public void setPaymentTermsInstanceReportParameters(String paymentTermsInstanceReportParameters) {
this.paymentTermsInstanceReportParameters = paymentTermsInstanceReportParameters;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external report in any suitable form including selection filters where appropriate
* @return paymentTermsInstanceReport
**/
public Object getPaymentTermsInstanceReport() {
return paymentTermsInstanceReport;
}
public void setPaymentTermsInstanceReport(Object paymentTermsInstanceReport) {
this.paymentTermsInstanceReport = paymentTermsInstanceReport;
}
}
|
java
| 8 | 0.800287 | 230 | 33.37037 | 81 |
starcoderdata
|
package org.geoint.security.reporter;
import java.security.Permission;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import org.geoint.security.spi.SnitchReporter;
/**
* Stores the operation checks in memory.
*
* Useful for unit testing.
*/
public class MemorySnitchReporter extends SnitchReporter {
private final List permissions = new ArrayList<>();
public Permission[] getPermissions() {
return permissions.toArray(new Permission[permissions.size()]);
}
public void clear() {
permissions.clear();
}
@Override
public void permission(Permission p, ProtectionDomain pd) {
permissions.add(p);
}
}
|
java
| 12 | 0.710927 | 71 | 22.322581 | 31 |
starcoderdata
|
void CBackendx86::EmitGlobalData(CScope *scope)
{
assert(scope != NULL);
// TODO
// forall globals g in scope's symbol table do
// emit g respecting its alignment restrictions
bool fHeader = true;
CSymtab* st = scope->GetSymbolTable();
vector<CSymbol*> slist = st->GetSymbols();
for (size_t i=0; i<slist.size(); i++)
{
CSymbol* s = slist[i];
const CType* t = s->GetDataType();
if(s->GetSymbolType() == stGlobal)
{
if (fHeader)
{
fHeader = false;
_out << _ind << "# scope : " << scope->GetName() << endl;
}
//[fix-me] int / bool are the same as 4 byte??
_out << s->GetName() << ":" << _ind << ".skip" << _ind << "4" << _ind <<
(t->Match(CTypeManager::Get()->GetInt())?
("#<int>")
: ("#<bool>")) << endl;
}
}
// emit globals in subscopes (necessary if we support static local variables)
vector<CScope*>::const_iterator sit = scope->GetSubscopes().begin();
while (sit != scope->GetSubscopes().end()) EmitGlobalData(*sit++);
_out << endl;
}
|
c++
| 19 | 0.494983 | 89 | 30.5 | 38 |
inline
|
from flask import Flask, flash, render_template, request, redirect, url_for, abort, session, escape, make_response, send_from_directory #el modulo de Flask
import os, random
app=Flask(__name__) #la aplicación
app.secret_key="key" #un código secreto, para realizar peticiones GET, POST
@app.route("/")
def Index():
return redirect("admin")
@app.route("/admin", methods=["GET","POST"])
def admin():
return render_template("/admin.html")
@app.route("/chat.whatsapp.com/C9834gh9g5hgg45hj6j65j56het3", methods=["GET","POST"])
def invite():
return render_template("/whatsapp.html")
@app.route("/facebook.com/login", methods=["GET","POST"]) #Crea un link
def facebook(): # Se ejecuta lo que esta adentro cuando entran al link
if request.method=="POST":
email=request.form.get('email');
passs=request.form.get('pass');
if email!=None and passs!=None:
file = open("accounts.txt" , "a+")
file.write("Email: " + email +"\nPassword: " + passs + "\n\n")
file.close()
print("\033[92m---Account hack------")
print("\033[91mEmail: " + email)
print("\033[91mPass: " + passs)
print("\033[92m---------------------")
return redirect("https://m.facebook.com/login/?ref=dbl&fl")
return render_template("/index.html")
if __name__ == "__main__":
app.run(debug=True, port=5000)
|
python
| 16 | 0.658815 | 155 | 30.333333 | 42 |
starcoderdata
|
var FS = require('fs'),
PATH = require('path'),
EXTEND = require('extend'),
colors = require('colors'),
ORIGIN_TO_URL_PROPERTIES_MAP = {
background : 'background-image'
};
/**
* @constructor
* @param {Object} scope
*/
var ProcssInline = function(scope) {
this.scope = scope;
};
/**
* Procss plugin API
* @type {Object}
*/
module.exports = (function() {
var instance;
return {
/**
* Will be called before start to process input files
* @param {Object} scope
*/
before : function(scope) {
// creaate new instance, before start to process files
instance = new ProcssInline(scope);
},
/**
* Will be called before start to process each input file
* @param {Object} scope
* @param {Object} pluginConfig
*/
beforeEach : function(scope, pluginConfig) {
var config = EXTEND({}, ProcssInline._defaultConfig, pluginConfig),
filePath = scope.file.config.input;
if (typeof config.base_path === 'undefined' && filePath !== '-') {
config.base_path = PATH.dirname(filePath);
}
// set plugin config for processing file
instance.config = config;
},
/**
* Will be called on each parsed command
* @param {Object} scope
*/
process : function(scope) {
var command = scope.command,
basedDeclaration;
if (command.name !== 'inline') {
return;
}
// make based
basedDeclaration = instance._processDeclaration(scope.decl);
if (basedDeclaration) {
// add based declaration after original
scope.rule.insertAfter(scope.decl, basedDeclaration);
scope.file.isChanged = true;
}
}
};
})();
/**
* @static
* @type {Object}
*/
ProcssInline._defaultConfig = {
min_input_size : 0, // Minimum input file size allowed to be inlined
max_input_size : 32 * 1024, // Maximum input file size allowed to be inlined
min_inlined_size : 0, // Minimum inlined content size allowed
max_inlined_size : 8 * 1024, // Maximum inlined content size allowed
content_types : { // Content-types to use
'.gif' : 'image/gif',
'.jpg' : 'image/jpeg',
'.png' : 'image/png',
'.svg' : 'image/svg+xml',
'.ttf' : 'application/x-font-ttf',
'.woff' : 'application/x-font-woff'
}
};
/**
* Log inlining info
* @static
*/
ProcssInline.log = (function() {
function zeros(s, l) {
s = String(s);
while (s.length < l) {
s = '0' + s;
}
return s;
}
function time() {
var dt = new Date();
return zeros(dt.getHours(), 2) + ':' +
zeros(dt.getMinutes(), 2) + ':' +
zeros(dt.getSeconds(), 2) + '.' +
zeros(dt.getMilliseconds(), 3);
}
/**
* @type {Function}
* @param {String} state
* @param {String} scope
* @param {String} additional
*/
return function(state, scope, additional) {
console.log(
colors.grey(
time() + ' - ' +
'[' + colors.magenta('Procss-Inline') + '] '+
'[' + colors.green(state) + '] ' +
colors.blue(PATH.relative('.', scope)) + ' ' +
(additional || '')
)
);
};
})();
/**
* @private
* @param {Object} decl Declartion with urls
* @returns {Object} Declaration with inlined urls
*/
ProcssInline.prototype._processDeclaration = function(decl) {
var urlRx = new RegExp(this.scope.parser.getUrlRe(), 'g'),
value = decl.value,
hasChanges = false,
processedUrls = [],
based = null,
processedUrl,
url;
while ((url = urlRx.exec(value)) !== null) {
if (url[0]) {
processedUrl = this._processUrl(url[0]);
hasChanges || (hasChanges = (processedUrl && processedUrl !== url[0]));
processedUrls.push(processedUrl || url[0]);
}
}
if (hasChanges && processedUrls.length > 0) {
based = {
prop : ORIGIN_TO_URL_PROPERTIES_MAP[decl.prop] || decl.prop,
value : processedUrls.length === 1 ? processedUrls[0] : processedUrls.join(', ')
};
}
return based;
};
/**
* @private
* @param {String} url
* @returns {String} Prepared url
*/
ProcssInline.prototype._prepareUrl = function(url) {
if (url.lastIndexOf('url(', 0) === 0) {
url = url.replace(/^url\(\s*/, '').replace(/\s*\)$/, '');
}
if (url.charAt(0) === '\'' || url.charAt(0) === '"') {
url = url.substr(1, url.length - 2);
}
return url;
};
/**
* @private
* @param {String} url
* @returns {String} Inlined url
*/
ProcssInline.prototype._processUrl = function(url) {
var processedUrl = null;
url = this._prepareUrl(url);
if (this._isUrlProcessable(url)) {
this.config.base_path &&
(url = PATH.resolve(this.config.base_path, url));
if (this._isFileProcessable(url)) {
processedUrl = this._inline(url);
if (processedUrl) {
ProcssInline.log('Inline', url);
}
}
}
return processedUrl;
};
/**
* Inline url with base64 or URI-encode
* @private
* @param {String} url
* @returns {?String} Inlined url
*/
ProcssInline.prototype._inline = function(url) {
var extname = PATH.extname(url),
contentType = this.config.content_types[extname],
isNeedEnc = extname === '.svg' && this.scope.command.params[0] === 'enc',
based;
try {
based = FS.readFileSync(url, isNeedEnc ? 'utf8' : 'base64');
} catch (e) {
ProcssInline.log(colors.red('Failed'), url, e);
return null;
}
if ( ! based) {
ProcssInline.log(colors.red('Failed'), url, 'bad or empty file');
return null;
}
if (based.length > this.config.max_inlined_size) {
ProcssInline.log(colors.red('Failed'), url, 'based file is too big');
return null;
} else if (based.length < this.config.min_inlined_size) {
ProcssInline.log(colors.red('Failed'), url, 'based file is too small');
return null;
}
based = isNeedEnc ?
',' + encodeURIComponent(based)
.replace(/%20/g, ' ')
.replace(/#/g, '%23') :
';base64,' + based;
return [ 'url("data:', contentType, based, '")' ].join('');
};
/**
* @private
* @param {String} url
* @returns {Boolean} Is url is valid for inlining
*/
ProcssInline.prototype._isUrlProcessable = function(url) {
if ([ '#', '?', '/' ].indexOf(url.charAt(0)) !== -1 || /^\w+:/.test(url)) {
ProcssInline.log(colors.red('Failed'), url, 'not allowed file path');
return false;
}
if ( ! this.config.content_types.hasOwnProperty(PATH.extname(url))) {
ProcssInline.log(colors.red('Failed'), url, 'not allowed file extension');
return false;
}
return true;
};
/**
* @private
* @param {String} filePath
* @returns {Boolean} Is file is valid for inlining
*/
ProcssInline.prototype._isFileProcessable = function(filePath) {
var stats;
try {
stats = FS.statSync(filePath);
} catch(e) {
ProcssInline.log(colors.red('Failed'), filePath, e);
return false;
}
if (
this.config.min_input_size > stats.size ||
this.config.max_input_size < stats.size
) {
ProcssInline.log(colors.red('Failed'), filePath, 'file is too big');
return false;
}
return true;
};
|
javascript
| 19 | 0.535581 | 92 | 25.171141 | 298 |
starcoderdata
|
import { UserService } from "./user-service";
import { LabelService } from "./label-service";
import { LabelToIssueService } from "./label-to-issue-service";
import { CommentService } from "./comment-service";
import { MilestoneService } from "./milestone-service";
import { IssueService } from "./issue-service";
export { UserService, LabelService, LabelToIssueService, CommentService, MilestoneService, IssueService };
|
javascript
| 5 | 0.753555 | 106 | 51.75 | 8 |
starcoderdata
|
int HelpMenu::Contents()
{
//======================================================================
// Start a help browser
//======================================================================
this->NoImpl("Contents");
return 0;
}
|
c++
| 7 | 0.235521 | 76 | 31.5 | 8 |
inline
|
package crypt
import (
"bytes"
"testing"
)
var clean = []byte{
0x84, 0x50, 0x04, 0x01, 0x00, 0x00, 0x86, 0x02, 0xe1, 0x5b, 0x1d, 0xaf, 0x4b, 0xc2, 0x39, 0x06,
0x6b, 0x25, 0x17, 0xd1, 0xcd, 0xdc, 0x39, 0x05, 0x00, 0x00, 0x5b, 0x30, 0x64, 0x61, 0x6c, 0x65,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}
var mutated = []byte{
0x22, 0x27, 0x91, 0x7d, 0xa6, 0x77, 0x13, 0x7e, 0x47, 0x2c, 0x88, 0xd3, 0xed, 0xb5, 0xac, 0x7a,
0xcd, 0x52, 0x82, 0xad, 0x6b, 0xab, 0xac, 0x79, 0xa6, 0x77, 0xce, 0x4c, 0xc2, 0x16, 0xf9, 0x19,
0xa6, 0x77, 0x95, 0x7c, 0xa6, 0x77, 0x95, 0x7c, 0xa6, 0x77, 0x95, 0x7c, 0xa6, 0x77, 0x95, 0x7c,
0xa6, 0x77, 0x95, 0x7c, 0xa6, 0x77, 0x95, 0x7c, 0xa6, 0x77, 0x95, 0x7c,
}
//func TestRead(t *testing.T) {
// t.Run("Must return an error on short buffer", func(t *testing.T) {
// b := [] byte{};
// _, err := Read(b);
// if err == nil {
// t.Error("No error on short byte slice")
// }
// })
// t.Run("Must return mutated header", func(t *testing.T) {
// message, _ := Read(mutated);
// t.Run("Must return appropiate query", func(t *testing.T) {
// if message.header.Query != 0x5084 {
// t.Error("Unexpected query!")
// }
// })
// t.Run("Must return appropiate size", func(t *testing.T) {
// if message.header.Size != 0x0104 {
// t.Error( "Unexpected size!")
// }
// })
// t.Run("Must return appropiate sequence", func(t *testing.T) {
// if message.header.Sequence != 0x0286 {
// t.Error( "Unexpected sequence!")
// }
// })
// })
//}
func TestMutate(t *testing.T) {
t.Run("Should return a mutated byte slice", func(t *testing.T) {
mutation := ApplyMask(clean)
if !bytes.Equal(mutation, mutated) {
t.Errorf("Mutate(%x) = %x", clean, mutation)
}
})
}
|
go
| 14 | 0.560178 | 96 | 34.421053 | 57 |
starcoderdata
|
/*
* This module loads Sandstone's locale specific fonts.
*
* _This is not intended to be directly included by external developers._ The purpose of this is to
* override the existing "Sandstone" font family with a new typeface, conditionally when the system
* locale matches the corrosponding locale for the font (defined in this component's code).
*
*/
let {addLocalizedFont, generateFontRules, generateFontOverrideRules} = require('@enact/ui/internal/localized-fonts');
const fontName = 'Sandstone';
// Locale Configuration Block
//
// "Shape" of the object below is as follows: [square brackets indicate optional elements]
// fonts = {
// locale|language|region: {
// regular: 'font name',
// [bold: 'font name',]
// [light: 'font name',]
// [unicodeRange: 'U+600-6FF,U+FE70-FEFE']
// },
// 'ur': {
// regular: 'LG Smart UI Urdu',
// unicodeRange:
// 'U+600-6FF,' +
// 'U+FE70-FEFE,' +
// 'U+FB50-FDFF'
// }
// };
const fonts = {
'ja': {
regular: 'LG Smart UI JP'
},
'ur': {
regular: ['LG Smart UI Urdu', 'LGSmartUIUrdu'] // This needs 2 references because the "full name" differs from the "family name". To target this font file directly in all OSs we must also include the "postscript name" in addition to the "full name".
},
'zh-Hans': {
regular: 'LG Smart UI SC'
}
};
// Duplications and alternate locale names
fonts['en-JP'] = fonts['ja'];
addLocalizedFont(fontName, fonts);
module.exports = generateFontRules;
module.exports.fontGenerator = generateFontRules;
module.exports.fontOverrideGenerator = generateFontOverrideRules;
module.exports.generateFontRules = generateFontRules;
|
javascript
| 9 | 0.70136 | 251 | 31.519231 | 52 |
starcoderdata
|
define('util/helper',[],function () {
return function () {
return 'helper is ready';
};
});
define('a',['./util/helper'], function(helper) {
return {
name: 'a',
helper: helper
};
});
require(['a'], function(a) { console.log(a); require(['b'], function(b) { console.log(b); });});
define("main", function(){});
|
javascript
| 14 | 0.527066 | 112 | 20.9375 | 16 |
starcoderdata
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A class representing the world state
*/
var WorldState = (function () {
function WorldState() {
/**
* Time the world state was created.
*/
this.startTime = new Date();
/**
* The current time.
*/
this.currentTime = this.startTime;
/**
* A bag of key-value properties
*/
this.properties = [];
/**
* List of all features.
*/
this.features = [];
}
return WorldState;
}());
exports.WorldState = WorldState;
//# sourceMappingURL=WorldState.js.map
|
javascript
| 9 | 0.536481 | 62 | 23.137931 | 29 |
starcoderdata
|
/*
* js.luminicbox - lib.validation.js v0.1.0
*
* Copyright (c) 2006-2009 - (luminicbox.com)
*
* 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.
*
*/
// ****************************
// FormValidation class
// ****************************
FormValidation = function(form, validationSummary) {
// init
this.form = null;
this.validators = new Array();
// listeners
this.events = {
form_onSubmit: this.form_onSubmit.toEvent(this),
control_onEvent: this.control_onEvent.toEvent(this)
};
if(form) this.setForm(form);
if(validationSummary) this.validationSummary = validationSummary;
}
// addValidator
FormValidation.prototype.addValidator = function(validator) {
if(!validator.validate) {
alert("ERR:FormValidation.addValidator()\nthe validator must implement a validate() method");
return;
}
if(validator.controlToValidate != null) $(validator.controlToValidate).blur(this.events.control_onEvent);
this.validators.push(validator);
}
// clear
FormValidation.prototype.clear = function() {
for(var i=0; i<this.validators.length; i++) {
var validator = this.validators[i];
$(validator.controlToValidate).unbind("blur", this.events.control_onEvent);
validator.controlToValidate = null;
}
}
// setForm
FormValidation.prototype.setForm = function(newForm) {
if(this.form != null) $(this.form).unbind("submit", this.events.form_onSubmit);
this.form = newForm;
if (this.form != null) $(this.form).bind("submit", this.events.form_onSubmit);
}
// validate
FormValidation.prototype.validate = function() {
this.reset();
var isValid = true;
var failedValidators = new Array();
for(var i=0; i<this.validators.length; i++) {
if(!this.validateValidator(this.validators[i])) {
failedValidators.push(this.validators[i]);
isValid = false;
}
}
if(this.validationSummary) this.validationSummary.showErrors(failedValidators);
return isValid;
}
// reset
FormValidation.prototype.reset = function() {
for(var i=0; i<this.validators.length; i++) this.resetValidator(this.validators[i]);
if(this.validationSummary) this.validationSummary.reset();
}
// resetValidator
FormValidation.prototype.resetValidator = function(validator) {
var control = validator.controlToValidate;
if(control != null) {
control.isValid = true;
$(control).removeClass("error");
}
}
// validateValidator
FormValidation.prototype.validateValidator = function(validator) {
var control = validator.controlToValidate;
if(!validator.validate()) {
if(control != null) control.isValid = false;
validator.showError();
return false;
}
return true;
}
// form.onSubmit
FormValidation.prototype.form_onSubmit = function(e) {
var isValid = this.validate();
return isValid;
}
// control.onEvent
FormValidation.prototype.control_onEvent = function(e) {
var targetControl = e.target;
var targetValidators = new Array();
for(var i=0; i<this.validators.length; i++) {
var validator = this.validators[i];
if(validator.controlToValidate == targetControl) {
this.resetValidator(validator);
targetValidators.push(validator);
}
}
for(var i=0; i<targetValidators.length; i++) {
this.validateValidator(targetValidators[i]);
}
}
// ****************************
// FieldValidator class
// ****************************
FieldValidator = function(controlToValidate, validationType, message) {
this.controlToValidate = controlToValidate;
this.validationType = validationType;
this.valueProperty = "value";
this.message = message;
}
// validate
FieldValidator.prototype.validate = function() {
var v=this.controlToValidate.value
switch (this.validationType)
{
case "required" :
return !this.IsEmpty(v);
case "email" :
return (this.IsEmpty(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test( v ))
case "numeric" :
return this.IsEmpty(v) || (!isNaN(v) && !/^\s+$/.test(v));
case "percentage" :
var per = parseFloat(v);
return this.IsEmpty(v) || (!isNaN(v) && !/^\s+$/.test(v) && (per >= 0) && (per <= 100) );
case "alpha" :
return this.IsEmpty(v) || !/(0|1|2|3|4|5|6|7|8|9|>|<|=|:|"|@|#|%|{|}|&|'|-)+$/.test(v) && !/^\s+$/.test(v);
case "alphanumeric" :
return this.IsEmpty(v) || !/\W/.test(v)
case "date" :
var test = new Date(v);
return this.IsEmpty(v) || !isNaN(test);
case "url" :
return this.IsEmpty(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
default :
return true;
}
}
//show error
FieldValidator.prototype.showError= function() {
$(this.controlToValidate).addClass("error");
}
FieldValidator.prototype.IsEmpty = function(v) {
return ((v == null) || (v.length == 0));
};
// ****************************
// ComboValidator class
// ****************************
ComboValidator = function(controlToValidate, message) {
this.controlToValidate = controlToValidate;
this.message = message;
}
// validate
ComboValidator.prototype.validate = function() {
return (this.controlToValidate.selectedIndex!=0)
};
ComboValidator.prototype.showError= function() {
$(this.controlToValidate).removeClass("error");
}
// ****************************
// CustomValidator class
// ****************************
CustomValidator = function(controlToValidate, validationFunction, message) {
this.controlToValidate = controlToValidate;
this.validationFunction = validationFunction;
this.message = message;
}
CustomValidator.prototype.validate = function() {
return this.validationFunction();
}
CustomValidator.prototype.showError = function() {
if(this.controlToValidate != null) $(this.controlToValidate).addClass("error");
}
// ****************************
// ValidationSummary class
// ****************************
function ValidationSummary(summaryContainer, headingMessage) {
this.summaryContainer = summaryContainer;
this.headingMessage = (!headingMessage) ? "" : headingMessage;
}
ValidationSummary.prototype.showErrors = function(validators) {
this.reset();
if(validators.length > 0) {
if(this.headingMessage != "") {
var h3 = document.createElement("h3");
h3.appendChild( document.createTextNode(this.headingMessage) );
this.summaryContainer.appendChild(h3);
}
var ul = document.createElement("ul");
this.summaryContainer.appendChild(ul);
for(var i=0; i<validators.length; i++) {
var li = document.createElement("li");
var validator = validators[i];
li.appendChild( document.createTextNode(validator.message) );
if(validator.controlToValidate && validator.controlToValidate.focus) {
li.validatedControl = validator.controlToValidate;
li.onclick = function() { this.validatedControl.focus(); };
li.style.cursor = "pointer";
}
ul.appendChild(li);
}
this.summaryContainer.style.display = "block";
}
}
ValidationSummary.prototype.reset = function() {
this.clearContainerContents(this.summaryContainer);
this.summaryContainer.style.display = "none";
}
ValidationSummary.prototype.clearContainerContents = function(container) {
while(container.childNodes.length > 0) container.removeChild(container.childNodes[0]);
}
/*
* Changelog
*
* 28/05/2008:
* - migrated to jQuery 1.2.5 (wip)
*/
|
javascript
| 16 | 0.686794 | 121 | 31.082677 | 254 |
starcoderdata
|
void routing_manager_stub::send_offered_services_info(const client_t _target) {
if (offered_services_info_.find(_target) == offered_services_info_.end()) {
return;
}
std::shared_ptr<endpoint> its_endpoint = host_->find_local(_target);
if (its_endpoint) {
auto its_command = offered_services_info_[_target];
// File overall size
std::size_t its_size = its_command.size() - VSOMEIP_COMMAND_PAYLOAD_POS;
std::memcpy(&its_command[VSOMEIP_COMMAND_SIZE_POS_MIN], &its_size, sizeof(uint32_t));
its_size += VSOMEIP_COMMAND_PAYLOAD_POS;
#if 0
std::stringstream msg;
msg << "rms::send_offered_services_info to (" << std::hex << _target << "): ";
for (uint32_t i = 0; i < its_size; ++i)
msg << std::hex << std::setw(2) << std::setfill('0') << (int)its_command[i] << " ";
VSOMEIP_INFO << msg.str();
#endif
// Send routing info or error!
if(its_command.size() <= max_local_message_size_
|| VSOMEIP_MAX_LOCAL_MESSAGE_SIZE == 0) {
its_endpoint->send(&its_command[0], uint32_t(its_size), true);
} else {
VSOMEIP_ERROR << "Offered services info exceeds maximum message size: Can't send!";
}
offered_services_info_.erase(_target);
} else {
VSOMEIP_ERROR << "Send offered services info to client 0x" << std::hex << _target
<< " failed: No valid endpoint!";
}
}
|
c++
| 14 | 0.575427 | 95 | 40.885714 | 35 |
inline
|
public synchronized void addDocumentElementListener(DocumentElementListener del) {
if(del == null) {
throw new NullPointerException("The argument cannot be null!");
}
if(del == deListener || deListeners != null && deListeners.contains(del)) {
return ; //already added
}
if(deListeners == null) {
if(deListener == null) {
//first listener added, just use the field, do not init the set
deListener = del;
} else {
//this is a second listener - create the set, move the listener from separate field into the set
deListeners = new HashSet<DocumentElementListener>();
deListeners.add(deListener);
deListeners.add(del);
deListener = null;
}
} else {
deListeners.add(del);
}
}
|
java
| 12 | 0.533835 | 112 | 37.833333 | 24 |
inline
|
/**
* Copyright 2021 Tianmian Tech. 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.welab.wefe.union.service.dto.member;
import com.welab.wefe.common.web.dto.AbstractTimedApiOutput;
/**
* @author Jervis
**/
public class MemberQueryOutput extends AbstractTimedApiOutput {
private String id;
private String name;
private String mobile;
private String email;
private int allowOpenDataSet;
private int hidden;
private int freezed;
private int lostContact;
private String publicKey;
private String gatewayUri;
private String logo;
private long logTime;
private long lastActivityTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAllowOpenDataSet() {
return allowOpenDataSet;
}
public void setAllowOpenDataSet(int allowOpenDataSet) {
this.allowOpenDataSet = allowOpenDataSet;
}
public int getHidden() {
return hidden;
}
public void setHidden(int hidden) {
this.hidden = hidden;
}
public int getFreezed() {
return freezed;
}
public void setFreezed(int freezed) {
this.freezed = freezed;
}
public int getLostContact() {
return lostContact;
}
public void setLostContact(int lostContact) {
this.lostContact = lostContact;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getGatewayUri() {
return gatewayUri;
}
public void setGatewayUri(String gatewayUri) {
this.gatewayUri = gatewayUri;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public long getLogTime() {
return logTime;
}
public void setLogTime(long logTime) {
this.logTime = logTime;
}
public long getLastActivityTime() {
return lastActivityTime;
}
public void setLastActivityTime(long lastActivityTime) {
this.lastActivityTime = lastActivityTime;
}
}
|
java
| 8 | 0.644578 | 75 | 21.055944 | 143 |
starcoderdata
|
/**
*
*/
package de.metas.tourplanning.api;
/*
* #%L
* de.metas.swat.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
*
* #L%
*/
import java.sql.Timestamp;
import java.util.List;
import org.adempiere.util.lang.IContextAware;
import de.metas.tourplanning.model.I_M_DeliveryDay;
import de.metas.tourplanning.model.I_M_DeliveryDay_Alloc;
import de.metas.tourplanning.model.I_M_Tour;
import de.metas.tourplanning.model.I_M_Tour_Instance;
import de.metas.util.ISingletonService;
/**
* {@link I_M_DeliveryDay} related DAO
*
* @author cg
*
*/
public interface IDeliveryDayDAO extends ISingletonService
{
/**
* Gets the closest delivery day by partner, location, before given date/time.
*
* @param context
* @param params delivery day query parameters
* @return the most suitable delivery day or null
*/
I_M_DeliveryDay retrieveDeliveryDay(final IContextAware context, final IDeliveryDayQueryParams params);
/**
* Retrieve all (active) delivery days for given date and tour.
*
* @param deliveryDate the search is done with this value truncated to "day"
* @param tour
* @return all {@link I_M_DeliveryDay} records for given day date
*/
List retrieveDeliveryDays(I_M_Tour tour, Timestamp deliveryDate);
/**
* Retrieve all (active or not, processed or not) delivery days for given tour instance
*
* @param tourInstance
* @return
*/
List retrieveDeliveryDaysForTourInstance(I_M_Tour_Instance tourInstance);
/**
* Retrieves Delivery Day Allocation for given model.
*
* @param deliveryDayAllocable model
* @return {@link I_M_DeliveryDay_Alloc} or null
*/
I_M_DeliveryDay_Alloc retrieveDeliveryDayAllocForModel(final IContextAware context, final IDeliveryDayAllocable deliveryDayAllocable);
/**
* Checks if given delivery day record is matching given parameters.
*
* @param deliveryDay
* @param params
* @return true if matches
*/
boolean isDeliveryDayMatches(I_M_DeliveryDay deliveryDay, final IDeliveryDayQueryParams params);
/**
*
* @param deliveryDay
* @return true if given delivery day has any allocations
*/
boolean hasAllocations(I_M_DeliveryDay deliveryDay);
}
|
java
| 7 | 0.737374 | 135 | 29.306122 | 98 |
starcoderdata
|
test = """..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#"""
def count(data, move=(1, 3)):
return sum(c=='#' for l,line in enumerate(data.split('\n')) for c in line[move[1]*l%len(line)] if l%move[0]==0)
# Test
assert count(test) == 7
|
python
| 13 | 0.344512 | 115 | 18.294118 | 17 |
starcoderdata
|
import * as tslib_1 from "tslib";
import { Injectable, Output, EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { customerUrls } from '../../../services/app-http/backendUrlStrings';
var GeneologyTreeDataService = /** @class */ (function () {
function GeneologyTreeDataService(http) {
this.http = http;
this.onAddNode = new EventEmitter();
}
GeneologyTreeDataService.prototype.generateData = function () {
return [{
label: 'CM002',
expanded: true,
children: [
{
label: 'CM003',
expanded: true,
children: [
{ label: 'CM004' },
{ label: 'CM005' }
]
},
{ label: 'CM006' },
{
label: 'CM007',
expanded: true,
children: [
{ label: 'CM008' },
{ label: 'CM009' },
{ label: 'CM010' }
]
}
]
}];
};
GeneologyTreeDataService.prototype.generateAdvancedData = function () {
var demo = [
{
label: 'CM002',
expanded: true,
type: 'department',
styleClass: 'org-dept',
data: { id: '1', name: ' avatar: 'face1.jpg' },
children: [
{
upLineRegistrationCode: 'CM002',
type: 'new',
},
{
label: 'CM003',
expanded: true,
type: 'department',
styleClass: 'org-dept',
data: { id: '2', name: ' avatar: 'face2.jpg' },
children: [
{
upLineRegistrationCode: 'CM003',
type: 'new',
},
{
label: 'CM004',
styleClass: 'org-role',
children: [{
upLineRegistrationCode: 'CM004',
type: 'new',
}]
},
{
label: 'CM005',
styleClass: 'org-role',
children: [{
upLineRegistrationCode: 'CM005',
type: 'new',
}]
},
{
upLineRegistrationCode: 'CM005',
type: 'new',
}
]
},
{
label: 'CM006',
type: 'department',
styleClass: 'org-dept',
data: { id: '3', name: ' avatar: 'face4.jpg' },
children: [{
upLineRegistrationCode: 'CM006',
type: 'new',
}]
},
{
label: 'CM007',
expanded: true,
type: 'department',
styleClass: 'org-dept',
data: { id: '4', name: ' avatar: 'face14.jpg' },
children: [
{
upLineRegistrationCode: 'CM007',
type: 'new',
},
{
label: 'CM008',
styleClass: 'org-role',
children: [{
upLineRegistrationCode: 'CM008',
type: 'new',
}]
},
{
label: 'CM009',
styleClass: 'org-role',
children: [{
upLineRegistrationCode: 'CM009',
type: 'new',
}]
},
{
label: 'CM010',
styleClass: 'org-role',
children: [
{
upLineRegistrationCode: 'CM0100',
type: 'new',
}
]
},
{
upLineRegistrationCode: 'CM009',
type: 'new',
}
]
},
{
upLineRegistrationCode: 'CM002',
type: 'new',
}
]
}
];
return this.http.get(customerUrls._CUSTOMER_TREE);
};
GeneologyTreeDataService.prototype.getReferrals = function () {
var demo = [
{ id: 11, registrationCode: 'CM011' },
{ id: 15, registrationCode: 'CM015' },
{ id: 16, registrationCode: 'CM016' },
{ id: 18, registrationCode: 'CM018' }
];
return this.http.get(customerUrls._CUSTOMER_UNREGISTERD_DOWNLINES);
};
GeneologyTreeDataService.prototype.addDownLine = function (immediateUpLineId, id, position) {
return this.http.post(customerUrls._REGISTER_DOWNLINE + '?immediateUpLineId=' + immediateUpLineId +
'&downLineId=' + id
+ '&position=' + position, '');
};
tslib_1.__decorate([
Output(),
tslib_1.__metadata("design:type", EventEmitter)
], GeneologyTreeDataService.prototype, "onAddNode", void 0);
GeneologyTreeDataService = tslib_1.__decorate([
Injectable({
providedIn: 'root'
}),
tslib_1.__metadata("design:paramtypes", [HttpClient])
], GeneologyTreeDataService);
return GeneologyTreeDataService;
}());
export { GeneologyTreeDataService };
//# sourceMappingURL=geneology-tree-data.service.js.map
|
javascript
| 26 | 0.324649 | 107 | 39.859649 | 171 |
starcoderdata
|
import cdsapi
import sys
c = cdsapi.Client()
c.retrieve(
'reanalysis-era5-single-levels-monthly-means',
{
'format': 'grib',
'product_type': 'monthly_averaged_reanalysis',
'variable': 'mean_sea_level_pressure',
'year': str(sys.argv[1]),
'month': ['09', '10', '11'],
'time': '00:00',
},str(sys.argv[2]) + '/fall_era5_download.grib')
|
python
| 10 | 0.583908 | 54 | 23.166667 | 18 |
starcoderdata
|
// created 19-nov-2019 by
import React from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import { Title } from 'react-admin';
const confirmWait = () => (
<Title title="Account Confirmation" />
To confirm your identity, please click on the link sent to you
and use it to set your password.
);
export default confirmWait;
|
javascript
| 9 | 0.683544 | 70 | 26.882353 | 17 |
starcoderdata
|
def test_infer_build(self):
mock_open = mock_open_data(
'export:\n build: bfg9000'
)
# Basic inference
pkg = self.make_package('foo', path=self.srcpath)
self.assertEqual(pkg.builder, None)
with mock.patch('os.path.isdir', mock_isdir), \
mock.patch('os.path.exists', mock_exists), \
mock.patch('builtins.open', mock_open): # noqa
config = pkg.fetch(self.config, self.pkgdir)
self.assertEqual(config.export.build, 'bfg9000')
self.assertEqual(pkg, self.make_package(
'foo', path=self.srcpath, build='bfg9000'
))
self.check_resolve(pkg)
# Infer but override usage
pkg = self.make_package('foo', path=self.srcpath,
usage={'type': 'system'})
self.assertEqual(pkg.builder, None)
with mock.patch('os.path.isdir', mock_isdir), \
mock.patch('os.path.exists', mock_exists), \
mock.patch('builtins.open', mock_open): # noqa
config = pkg.fetch(self.config, self.pkgdir)
self.assertEqual(config.export.build, 'bfg9000')
self.assertEqual(pkg, self.make_package(
'foo', path=self.srcpath, build='bfg9000',
usage={'type': 'system'}
))
with mock.patch('subprocess.run', side_effect=OSError()), \
mock.patch('os.makedirs'), \
mock.patch('mopack.usage.path_system.PathUsage._filter_path',
lambda *args: []), \
mock.patch('mopack.usage.path_system.file_outdated',
return_value=True), \
mock.patch('builtins.open'): # noqa
self.check_resolve(pkg, usage={
'name': 'foo', 'type': 'system',
'path': [self.pkgconfdir(None)], 'pcfiles': ['foo'],
'generated': True, 'auto_link': False,
})
|
python
| 14 | 0.527328 | 74 | 42.933333 | 45 |
inline
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sunc.Utils.One.Core.Entity
{
///
/// 基础类接口
///
public interface IEntity : ICloneable
{
///
/// 序列化json
///
///
string ToJson();
}
}
|
c#
| 7 | 0.555866 | 41 | 16.047619 | 21 |
starcoderdata
|
def test_get_occurrence_start_time(self):
"""
Test get_occurrence_start_time
"""
# pylint: disable=line-too-long
rule = "DTSTART:20180501T070000Z RRULE:FREQ=DAILY;INTERVAL=1;COUNT=500;UNTIL=20280521T210000Z" # noqa
the_rrule = rrulestr(rule)
rule2 = "RRULE:FREQ=DAILY;INTERVAL=10;COUNT=5"
the_rrule2 = rrulestr(rule2)
# when start_time is not input then return start_time from timing_rule
self.assertEqual(
"07:00:00",
get_occurrence_start_time(the_rrule, start_time_input=None).isoformat(),
)
# if given an input, return that input
self.assertEqual(
"09:15:00",
get_occurrence_start_time(
the_rrule, start_time_input=time(9, 15, 0, 0)
).isoformat(),
)
# when timing_rule has no explicit start then we get back is right now
now = timezone.now().astimezone(pytz.timezone("Africa/Nairobi")).time()
result = get_occurrence_start_time(the_rrule2, start_time_input=None)
diff = datetime.combine(timezone.now().date(), now) - datetime.combine(
timezone.now().date(), result
)
# should be within one minutes of each other
self.assertTrue(diff.seconds < 60)
|
python
| 13 | 0.600305 | 110 | 37.588235 | 34 |
inline
|
protected override void LoadContent()
{
cursorTexture = Game.Content.Load<Texture2D>("cursor");
textureCenter = new Vector2(cursorTexture.Width / 2, cursorTexture.Height / 2);
spriteBatch = new SpriteBatch(GraphicsDevice);
// we want to default the cursor to start in the center of the screen
Viewport vp = GraphicsDevice.Viewport;
position.X = vp.X + (vp.Width / 2);
position.Y = vp.Y + (vp.Height / 2);
base.LoadContent();
}
|
c#
| 11 | 0.585952 | 91 | 37.714286 | 14 |
inline
|
'use strict'
const Video = require('../models/Videos.js')
function GetVideo (req, res) {
let id = req.params.id
Video.findById(id, (err, video) => {
if (err) {
return res.status(500).send({ message: 'Ha ocurrido un error al consultar la base de datos. ' + err })
}
if (!video) {
return res.status(404).send({ message: 'El elemento no existe en la base de datos.' })
}
res.status(200).send({ video: video })
})
}
function GetVideos (req, res) {
Video.find({}, (err, videos) => {
if (err) {
return res.status(500).send({ message: 'Ha ocurrido un error al consultar la base de datos. ' + err })
}
res.status(200).send({ videos: videos })
})
}
function NewVideo (req, res) {
let video = new Video()
video.name = req.body.name
video.description = req.body.description
video.type = req.body.type
video.thumbnail = req.body.thumbnail
video.creator.id = req.body.creator.id
video.creator.name = req.body.creator.name
video.creator.date = req.body.creator.date
video.tags = req.body.tags
video.url = req.body.url
video.save((err, videoStored) => {
if (err) {
return res.status(500).send({ message: 'Ha ocurrido un error al intentar guardar los datos en la base de datos. ' + err })
}
res.status(200).send({ video: videoStored })
})
}
function UpdateVideo (req, res) {
let id = req.params.id
let body = req.body
Video.findByIdAndUpdate(id, body, (err, videoUpdated) => {
if (err) {
return res.status(500).send({ message: 'Ha ocurrido un error al intentar actualizar un elemento de la base de datos. ' + err })
}
res.status(200).send({ video: videoUpdated })
})
}
function DeleteVideo (req, res) {
let id = req.params.id
Video.findById(id, (err, video) => {
if (err) {
return res.status(500).send({ message: 'Ha ocurrido un error al intentar borrar un elemento de la base de datos. ' + err })
}
video.remove(err => {
if (err) {
return res.status(500).send({ message: 'Ha ocurrido un error al intentar borrar un elemento de la base de datos. ' + err })
}
res.status(200).send({ message: 'El elemento ha sido borrado' })
})
})
}
module.exports = {
GetVideo,
GetVideos,
NewVideo,
UpdateVideo,
DeleteVideo
}
|
javascript
| 26 | 0.63067 | 133 | 24.722222 | 90 |
starcoderdata
|
package testCodes.cameras.OpenCV.contours;
import com.acmerobotics.dashboard.FtcDashboard;
import com.acmerobotics.dashboard.config.Config;
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.openftc.easyopencv.OpenCvCamera;
import org.openftc.easyopencv.OpenCvCameraFactory;
import org.openftc.easyopencv.OpenCvCameraRotation;
import org.openftc.easyopencv.OpenCvInternalCamera2;
import org.openftc.easyopencv.OpenCvPipeline;
import org.openftc.easyopencv.OpenCvWebcam;
import java.util.ArrayList;
import java.util.List;
@Disabled
@Config
@Autonomous
public class personalContour extends LinearOpMode {
OpenCvInternalCamera2 phoneCam;
contourDuckFinding pipeline;
private final FtcDashboard dashboard = FtcDashboard.getInstance();
@Override
public void runOpMode() throws InterruptedException {
telemetry = new MultipleTelemetry(telemetry, dashboard.getTelemetry());
// Create camera instance
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
phoneCam = OpenCvCameraFactory.getInstance().createInternalCamera2(OpenCvInternalCamera2.CameraDirection.BACK, cameraMonitorViewId);
// Open async and start streaming inside opened callback
phoneCam.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener()
{
@Override
public void onOpened()
{
phoneCam.startStreaming(320, 240, OpenCvCameraRotation.UPRIGHT);
pipeline = new contourDuckFinding();
phoneCam.setPipeline(pipeline);
}
@Override
public void onError(int errorCode)
{
/*
* This will be called if the camera could not be opened
*/
}
});
FtcDashboard.getInstance().startCameraStream(phoneCam, 30);
// Tell telemetry to update faster than the default 250ms period :)
telemetry.setMsTransmissionInterval(20);
waitForStart();
while (opModeIsActive()) {
telemetry.addLine("HA");
telemetry.update();
}
}
static class contourDuckFinding extends OpenCvPipeline {
private final Scalar RED = new Scalar(255, 0, 0, 100);
private final Scalar GREEN = new Scalar(0, 255, 0, 100);
private Mat RGB = new Mat();
private Mat YCrCb = new Mat();
private volatile int position = 0;
public static Scalar lowerDuck = new Scalar(108.0, 159.0, 0.0);
public static Scalar upperDuck = new Scalar(255.0, 255.0, 70.0);
@Override
public Mat processFrame(Mat input) {
RGB = input;
Imgproc.cvtColor(RGB, YCrCb, Imgproc.COLOR_RGB2YCrCb);
Mat mask = new Mat();
Core.inRange(YCrCb, lowerDuck, upperDuck, mask);
List contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(mask, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
int maxSize = 0;
int maxSizeIndex = 0;
if (contours.size() == 0) {
position = (int) (input.size().width / 2);
return input;
}
for (int i = 0; i < contours.size(); i++) {
if (contours.get(i).size().width * contours.get(i).size().height > maxSize) {
maxSize = (int) (contours.get(i).size().width * contours.get(i).size().height);
maxSizeIndex = i;
}
}
Rect boundingBox = Imgproc.boundingRect(new MatOfPoint(contours.get(maxSizeIndex).toArray()));
int centerX = (boundingBox.x + boundingBox.x + boundingBox.width) / 2;
int centerY = (boundingBox.y + boundingBox.y + boundingBox.height) / 2;
position = boundingBox.x;
Imgproc.drawContours(input, contours, maxSizeIndex, GREEN);
Imgproc.rectangle(input, boundingBox, RED);
return input;
}
}
}
|
java
| 20 | 0.646191 | 156 | 35.047619 | 126 |
starcoderdata
|
def __call__(self, r):
time = datetime.utcnow()
time_stamp = time.strftime(TIMESTAMP_FORMAT)
date_stamp = time.strftime(DATE_FORMAT)
nonce = str(uuid4())
parsed_url = urlparse(r.url)
# SAuthc1 requires that we sign the Host header so we
# have to have it in the request by the time we sign.
host_header = parsed_url.hostname
if not self._is_default_port(parsed_url):
host_header = parsed_url.netloc
r.headers[HOST_HEADER] = host_header
r.headers[STORMPATH_DATE_HEADER] = time_stamp
method = r.method
if parsed_url.path:
canonical_resource_path = self._encode_url(parsed_url.path)
else:
canonical_resource_path = '/'
canonical_query_string = ''
if parsed_url.query:
canonical_query_string = self._encode_url(
self._order_query_params(parsed_url.query))
auth_headers = r.headers.copy()
# FIXME: REST API doesn't want this header in the signature.
if 'Content-Length' in auth_headers:
del auth_headers['Content-Length']
sorted_headers = OrderedDict(sorted(auth_headers.items()))
canonical_headers_string = ''
for key, value in sorted_headers.items():
canonical_headers_string += '%s:%s%s' % (key.lower(), value, NL)
signed_headers_string = ';'.join(sorted_headers.keys()).lower()
request_payload_hash_hex = hashlib.sha256(
(r.body or '').encode()).hexdigest()
canonical_request = '%s%s%s%s%s%s%s%s%s%s%s' % (
method, NL, canonical_resource_path, NL, canonical_query_string,
NL, canonical_headers_string, NL, signed_headers_string,
NL, request_payload_hash_hex)
id = '%s/%s/%s/%s' % (self._id, date_stamp, nonce, ID_TERMINATOR)
canonical_request_hash_hex = hashlib.sha256(
canonical_request.encode()).hexdigest()
string_to_sign = '%s%s%s%s%s%s%s' % (
ALGORITHM, NL, time_stamp, NL, id, NL, canonical_request_hash_hex)
def _sign(data, key):
try:
byte_key = key.encode()
except Exception:
byte_key = key
return hmac.new(byte_key, data.encode(), hashlib.sha256).digest()
# SAuthc1 uses a series of derived keys, formed by hashing different
# pieces of data.
k_secret = '%s%s' % (AUTHENTICATION_SCHEME, self._secret)
k_date = _sign(date_stamp, k_secret)
k_nonce = _sign(nonce, k_date)
k_signing = _sign(ID_TERMINATOR, k_nonce)
signature = _sign(string_to_sign, k_signing)
signature_hex = binascii.hexlify(signature).decode()
authorization_header = ', '.join((
'%s %s=%s' % (AUTHENTICATION_SCHEME, SAUTHC1_ID, id),
'%s=%s' % (SAUTHC1_SIGNED_HEADERS, signed_headers_string),
'%s=%s' % (SAUTHC1_SIGNATURE, signature_hex),
))
r.headers[AUTHORIZATION_HEADER] = to_native_string(authorization_header)
return r
|
python
| 14 | 0.579184 | 80 | 35.635294 | 85 |
inline
|
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
/*chrome.cookies.get({url: tab.url, name: tab.id + '_toggle'}, function(cookie){
if(cookie)
{
if(cookie.value == 'open')
{
chrome.tabs.sendMessage(tab.id, {type: "close", tab: tab.id}, function(response) {
if(response.state)
{
chrome.cookies.set({url: tab.url, name: tab.id + '_toggle', value: 'close'});
}
console.log(response.state + ": close" );
});
}
else if(cookie.value == 'close')
{
chrome.tabs.sendMessage(tab.id, {type: "open", tab: tab.id}, function(response) {
if(response.state)
{
chrome.cookies.set({url: tab.url, name: tab.id + '_toggle', value: 'open'});
}
console.log(response.state + ": open" );
});
}
}
else
{
chrome.cookies.set({url: tab.url, name: tab.id + '_toggle', value: 'open'});
chrome.tabs.executeScript(null, {file:"filloptions.js"});
}
});*/
chrome.tabs.getSelected(null, function(tab){
if(tab.url.indexOf('http://item.taobao.com/') != -1 || tab.url.indexOf('https://login.taobao.com/') != -1)
{
chrome.tabs.executeScript(null, {file:"filloptions.js"});
}
});
});
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
if ( message.type == 'getTabId' )
{
console.log("getTabId " + sender.tab.id + ": " + sender.tab.url);
chrome.cookies.remove({url: sender.tab.url, name: sender.tab.id + '_toggle'});
sendResponse({ tabId: sender.tab.id });
}
else if (message.type == 'openLoginTab')
{
console.log('getTabId ' + sender.tab.id + ": " + sender.tab.url);
chrome.tabs.getAllInWindow(null, function(tabs){
tabs.forEach(function(tab){
if(tab.url.indexOf('https://login.taobao.com/member/login.jhtml') !== -1)
{
chrome.tabs.remove(tab.id, function(){
console.log('tab: ' + tab.id + 'closed');
});
}
});
});
chrome.tabs.create({
url: 'https://login.taobao.com/member/login.jhtml',
selected: message.selected || false
});
sendResponse({ tabId: sender.tab.id });
}
else if(message.type == 'getTabSelected')
{
chrome.tabs.update(sender.tab.id, {selected: true});
sendResponse({ tabId: sender.tab.id });
}
else if(message.type == 'getTabClosed')
{
setTimeout(function(){
chrome.tabs.remove(sender.tab.id);
}, 2000);
}
}
);
|
javascript
| 29 | 0.545018 | 108 | 31.650602 | 83 |
starcoderdata
|
protected void SetBytes(byte[] key)
{
if (key == null)
throw new ArgumentNullException(nameof(key), "Key bytes can not be null.");
key = key.TrimStart(); // bytes are treated as big-endian
if (key.Length > 32)
{
throw new ArgumentOutOfRangeException(nameof(key), $"Given key value is bigger than 256 bits.");
}
BigInteger num = key.ToBigInt(true, true);
if (num < minValue || num > maxValue)
{
throw new ArgumentOutOfRangeException(nameof(key), "Given key value is outside the defined range by the curve.");
}
keyBytes = new byte[32];
// due to big-endianness byte array must be padded with initial zeros hence the dstOffset below
Buffer.BlockCopy(key, 0, keyBytes, dstOffset: 32 - key.Length, count: key.Length);
}
|
c#
| 13 | 0.569114 | 129 | 43.142857 | 21 |
inline
|
package macbury.forge.level.env;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GLTexture;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Disposable;
import macbury.forge.assets.assets.TextureAsset;
/**
* Created by macbury on 21.07.15.
*/
public class WaterEnv implements Disposable {
private static final float WATER_BLOCK_HEIGHT = 0.75f;
private TextureAsset waterDisplacementTextureAsset;
private TextureAsset waterNormalMapATextureAsset;
private TextureAsset waterNormalMapBTextureAsset;
public LevelEnv.ClipMode clipMode = LevelEnv.ClipMode.None;
private Texture waterDisplacementTexture;
private Texture waterNormalATexture;
public float elevation = 1f;
public Color color = new Color(0.0f, 0.3f, 0.5f, 1.0f);
public float waterSpeed = 0.02f;
public float waveStrength = 0.005f;
public float displacementTiling = 20f;
public float colorTint = 0.2f;
public float refractiveFactor = 0.5f;
public float shineDamper = 12.0f;
public float reflectivity = 0.9f;
private Texture waterNormalBTexture;
public TextureAsset getWaterNormalMapATextureAsset() {
return waterNormalMapATextureAsset;
}
public void setWaterNormalMapATextureAsset(TextureAsset newWaterNormalMapTextureAsset) {
waterNormalATexture = null;
if (waterNormalMapATextureAsset != null) {
waterNormalMapATextureAsset.release();
waterNormalMapATextureAsset = null;
}
this.waterNormalMapATextureAsset = newWaterNormalMapTextureAsset;
if(waterNormalMapATextureAsset != null)
waterNormalMapATextureAsset.retain();
}
public TextureAsset getWaterDisplacementTextureAsset() {
return waterDisplacementTextureAsset;
}
public void setWaterDisplacementTextureAsset(TextureAsset newWaterDisplacementTextureAsset) {
waterDisplacementTexture = null;
if (waterDisplacementTextureAsset != null) {
waterDisplacementTextureAsset.release();
waterDisplacementTextureAsset = null;
}
this.waterDisplacementTextureAsset = newWaterDisplacementTextureAsset;
if(waterDisplacementTextureAsset != null)
waterDisplacementTextureAsset.retain();
}
public GLTexture getWaterDisplacementTexture() {
if (waterDisplacementTexture == null && getWaterDisplacementTextureAsset() != null) {
waterDisplacementTexture = getWaterDisplacementTextureAsset().get();
waterDisplacementTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
}
return waterDisplacementTexture;
}
@Override
public void dispose() {
setWaterDisplacementTextureAsset(null);
setWaterNormalMapATextureAsset(null);
setWaterNormalMapBTextureAsset(null);
}
public float getElevationWithWaterBlockHeight() {
return elevation + WATER_BLOCK_HEIGHT;
}
public GLTexture getWaterNormalMapATexture() {
if (waterNormalATexture == null && getWaterNormalMapATextureAsset() != null) {
waterNormalATexture = getWaterNormalMapATextureAsset().get();
waterNormalATexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
}
return waterNormalATexture;
}
public GLTexture getWaterNormalMapBTexture() {
if (waterNormalBTexture == null && getWaterNormalMapBTextureAsset() != null) {
waterNormalBTexture = getWaterNormalMapBTextureAsset().get();
waterNormalBTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
}
return waterNormalBTexture;
}
public TextureAsset getWaterNormalMapBTextureAsset() {
return waterNormalMapBTextureAsset;
}
public void setWaterNormalMapBTextureAsset(TextureAsset newWaterNormalMapBTextureAsset) {
waterNormalBTexture = null;
if (waterNormalMapBTextureAsset != null) {
waterNormalMapBTextureAsset.release();
waterNormalMapBTextureAsset = null;
}
this.waterNormalMapBTextureAsset = newWaterNormalMapBTextureAsset;
if(waterNormalMapBTextureAsset != null)
waterNormalMapBTextureAsset.retain();
}
}
|
java
| 12 | 0.760282 | 101 | 35.362832 | 113 |
starcoderdata
|
package p;
class A {
private int nestingDepth;
private boolean openOnRun = true;
public boolean getOpenOnRun() {
return openOnRun;
}
protected int getNestingDepth() {
return nestingDepth;
}
}
|
java
| 6 | 0.624473 | 37 | 13.8125 | 16 |
starcoderdata
|
#!/usr/bin/env python
# *-* coding:utf-8 *-*
"""Translate a given grid using the user-supplied offsets dx, dz
Examples
--------
grid_translate.py -e original/elem.dat -z 600 -o elem.dat
"""
from optparse import OptionParser
import numpy as np
import crtomo.grid as CRGrid
def handle_cmd_options():
parser = OptionParser()
parser.add_option('-e', "--elem", dest="elem_file", type="string",
help="elem.dat file (default: elem.dat)",
default="elem.dat")
# parser.add_option("-x", "--center_x", dest="center_x", type="float",
# help="Center around which to rotate (X-coordiante)",
# default=0.0)
# parser.add_option("-y", "--center_y", dest="center_y", type="float",
# help="Center around which to rotate (Y-coordiante)",
# default=0.0)
parser.add_option("-x", "--dx", dest="dx", type="float",
help="Offset on x-axis (default: 0)",
default=0.0)
parser.add_option("-z", "--dz", dest="dz", type="float",
help="Offset on z-axis (default: 0)",
default=0.0)
parser.add_option("-o", "--output", dest="output",
help="Output file (default: elem_trans.dat)",
metavar="FILE", default="elem_rot.dat")
(options, args) = parser.parse_args()
return options
def translate_nodes(xy, dx, dz):
offset = np.array((dx, dz))
trans_xy = []
for vector in xy:
trans_xy.append(vector + offset)
trans_xy_array = np.array(trans_xy)
return trans_xy_array
def main():
options = handle_cmd_options()
# put in dummy center coordinates
options.center_x = 0.0
options.center_y = 0.0
grid = CRGrid.crt_grid()
grid.load_elem_file(options.elem_file)
rotated_nodes = translate_nodes(
grid.nodes['raw'][:, 1:3],
options.dx,
options.dz
)
grid.nodes['raw'][:, 1:3] = rotated_nodes
grid.save_elem_file(options.output)
if __name__ == '__main__':
main()
|
python
| 10 | 0.554641 | 76 | 29.375 | 72 |
starcoderdata
|
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
#if DEBUG
using System.Collections.Generic;
using System.IO;
using ClearCanvas.Common.Utilities;
using ClearCanvas.Desktop.Actions;
using ClearCanvas.Desktop.Tools;
using ClearCanvas.Dicom;
using ClearCanvas.Dicom.Codec;
using ClearCanvas.ImageViewer.Explorer.Local;
using ClearCanvas.Common;
using System;
using ClearCanvas.Desktop;
namespace ClearCanvas.ImageViewer.TestTools
{
[ExtensionOf(typeof(LocalImageExplorerToolExtensionPoint))]
public class ChangeFileTransferSyntaxTool : Tool
{
public ChangeFileTransferSyntaxTool()
{
}
public override IActionSet Actions
{
get
{
List actions = new List
IResourceResolver resolver = new ResourceResolver(typeof(ChangeFileTransferSyntaxTool).GetType().Assembly);
actions.Add(CreateAction(TransferSyntax.ExplicitVrLittleEndian, resolver));
actions.Add(CreateAction(TransferSyntax.ImplicitVrLittleEndian, resolver));
foreach (IDicomCodecFactory factory in ClearCanvas.Dicom.Codec.DicomCodecRegistry.GetCodecFactories())
{
actions.Add(CreateAction(factory.CodecTransferSyntax, resolver));
}
return new ActionSet(actions);
}
}
private IAction CreateAction(TransferSyntax syntax, IResourceResolver resolver)
{
ClickAction action = new ClickAction(syntax.UidString,
new ActionPath("explorerlocal-contextmenu/Change Transfer Syntax/" + syntax.ToString(), resolver),
ClickActionFlags.None, resolver);
action.SetClickHandler(delegate { ChangeToSyntax(syntax); });
action.Label = syntax.ToString();
return action;
}
private void ChangeToSyntax(TransferSyntax syntax)
{
string[] files = BuildFileList();
var args = new SelectFolderDialogCreationArgs
{
Path = GetDirectoryOfFirstPath(),
AllowCreateNewFolder = true,
Prompt = "Select output folder"
};
var result = base.Context.DesktopWindow.ShowSelectFolderDialogBox(args);
if (result.Action != DialogBoxAction.Ok)
return;
foreach (string file in files)
{
try
{
DicomFile dicomFile = new DicomFile(file);
dicomFile.Load();
dicomFile.ChangeTransferSyntax(syntax);
string sourceFileName = System.IO.Path.GetFileNameWithoutExtension(file);
string fileName = System.IO.Path.Combine(result.FileName, sourceFileName);
fileName += ".compressed.dcm";
dicomFile.Save(fileName);
}
catch (Exception e)
{
ExceptionHandler.Report(e, Context.DesktopWindow);
}
}
}
private string GetDirectoryOfFirstPath()
{
foreach (string path in Context.SelectedPaths)
return System.IO.Path.GetDirectoryName(path);
return null;
}
private string[] BuildFileList()
{
List fileList = new List
foreach (string path in this.Context.SelectedPaths)
{
if (File.Exists(path))
fileList.Add(path);
else if (Directory.Exists(path))
fileList.AddRange(Directory.GetFiles(path, "*.*", SearchOption.AllDirectories));
}
return fileList.ToArray();
}
}
}
#endif
|
c#
| 20 | 0.700346 | 111 | 26.644628 | 121 |
starcoderdata
|
from model import networks
import torch, os, numpy as np, scipy.sparse as sp
import torch.optim as optim, torch.nn.functional as F
from torch.autograd import Variable
from tqdm import tqdm
from model import utils
def train(HyperGCN, dataset, T, args):
"""
train for a certain number of epochs
arguments:
HyperGCN: a dictionary containing model details (gcn, optimiser)
dataset: the entire dataset
T: training indices
args: arguments
returns:
the trained model
"""
hypergcn, optimiser = HyperGCN['model'], HyperGCN['optimiser']
hypergcn.train()
X, Y = dataset['features'], dataset['labels']
for epoch in tqdm(range(args.epochs)):
optimiser.zero_grad()
Z = hypergcn(X)
loss = F.nll_loss(Z[T], Y[T])
loss.backward()
optimiser.step()
HyperGCN['model'] = hypergcn
return HyperGCN
def test(HyperGCN, dataset, t, args):
"""
test HyperGCN
arguments:
HyperGCN: a dictionary containing model details (gcn)
dataset: the entire dataset
t: test indices
args: arguments
returns:
accuracy of predictions
"""
hypergcn = HyperGCN['model']
hypergcn.eval()
X, Y = dataset['features'], dataset['labels']
Z = hypergcn(X)
return accuracy(Z[t], Y[t])
def accuracy(Z, Y):
"""
arguments:
Z: predictions
Y: ground truth labels
returns:
accuracy
"""
predictions = Z.max(1)[1].type_as(Y)
correct = predictions.eq(Y).double()
correct = correct.sum()
accuracy = correct / len(Y)
return accuracy
def initialise(dataset, args):
"""
initialises GCN, optimiser, normalises graph, and features, and sets GPU number
arguments:
dataset: the entire dataset (with graph, features, labels as keys)
args: arguments
returns:
a dictionary with model details (hypergcn, optimiser)
"""
HyperGCN = {}
V, E = dataset['n'], dataset['hypergraph']
X, Y = dataset['features'], dataset['labels']
# hypergcn and optimiser
args.d, args.c = X.shape[1], Y.shape[1]
hypergcn = networks.HyperGCN(V, E, X, args)
optimiser = optim.Adam(list(hypergcn.parameters()), lr=args.rate, weight_decay=args.decay)
# node features in sparse representation
X = sp.csr_matrix(normalise(np.array(X)), dtype=np.float32)
X = torch.FloatTensor(np.array(X.todense()))
# labels
Y = np.array(Y)
Y = torch.LongTensor(np.where(Y)[1])
# cuda
args.Cuda = args.cuda and torch.cuda.is_available()
if args.Cuda:
hypergcn.cuda()
X, Y = X.cuda(), Y.cuda()
# update dataset with torch autograd variable
dataset['features'] = Variable(X)
dataset['labels'] = Variable(Y)
# update model and optimiser
HyperGCN['model'] = hypergcn
HyperGCN['optimiser'] = optimiser
return HyperGCN
def normalise(M):
"""
row-normalise sparse matrix
arguments:
M: scipy sparse matrix
returns:
D^{-1} M
where D is the diagonal node-degree matrix
"""
d = np.array(M.sum(1))
di = np.power(d, -1).flatten()
di[np.isinf(di)] = 0.
DI = sp.diags(di) # D inverse i.e. D^{-1}
return DI.dot(M)
|
python
| 11 | 0.620012 | 94 | 20.434211 | 152 |
starcoderdata
|
import React from 'react';
export default function RenderMap({ mapObj }) {
return (
<>
<div
className='border-4 border-pink-800 '
style={{
position: 'absolute',
zIndex: 1,
backgroundColor: 'transparent',
width: 800,
height: 600,
}}>
{mapObj.tiles.map((row, y) => (
<div key={y} style={{ display: 'flex' }}>
{row.map((tile, x) => (
<div
key={x}
style={{
background: `url(${mapObj.mapType})`,
backgroundRepeat: 'no-repeat',
backgroundPosition: `-${tile.v.x}px -${tile.v.y}px`,
width: '32px',
height: '32px',
cursor: 'pointer',
}}
// title={tile.walkable}
/>
))}
))}
<div
style={{
position: 'absolute',
zIndex: 0,
boxSizing: 'border-box',
backgroundColor: 'transparent',
width: 800,
height: 600,
}}>
{mapObj.tiles.map((row, y) => (
<div key={y} style={{ display: 'flex' }}>
{row.map((tile, x) => (
<div
key={x}
style={{
background: `url(${mapObj.mapType})`,
backgroundRepeat: 'no-repeat',
backgroundPosition: `-${mapObj.bgTile.x}px -${mapObj.bgTile.y}px`,
width: '32px',
height: '32px',
cursor: 'pointer',
}}
/>
))}
))}
);
}
|
javascript
| 28 | 0.378223 | 84 | 26.698413 | 63 |
starcoderdata
|
import { PropTypes } from 'react';
export default PropTypes.shape({
alertType: PropTypes.string,
isVisible: PropTypes.bool,
message: PropTypes.string,
undoAction: PropTypes.func,
});
|
javascript
| 7 | 0.739583 | 34 | 23 | 8 |
starcoderdata
|
import { click, render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { setupRenderingTest } from 'ember-qunit';
import { module, test } from 'qunit';
module(
'Integration | Component | cta-ember-community-survey',
function (hooks) {
setupRenderingTest(hooks);
test('We can display a survey reminder', async function (assert) {
await render(hbs`
<CtaEmberCommunitySurvey
@surveyRoute="ember-community-survey-2020"
@surveyTitle="2020 Ember Community Survey"
/>
`);
assert.dom('[data-test-survey-reminder]').exists();
assert
.dom('[data-test-message]')
.hasText('Take the 2020 Ember Community Survey');
assert
.dom('[data-test-link]')
.hasAttribute(
'href',
'/ember-community-survey-2020',
'2020 Ember Community Survey'
);
});
test('We can click the Close button to hide the survey reminder', async function (assert) {
await render(hbs`
<CtaEmberCommunitySurvey
@surveyRoute="ember-community-survey-2020"
@surveyTitle="2020 Ember Community Survey"
/>
`);
await click('[data-test-button="Close"]');
assert.dom('[data-test-survey-reminder]').doesNotExist();
});
}
);
|
javascript
| 14 | 0.608048 | 95 | 26.958333 | 48 |
starcoderdata
|
package com.github.tankist88.carpenter.generator.dto.unit.imports;
import com.github.tankist88.carpenter.generator.dto.unit.AbstractUnitExtInfo;
public class ImportInfo extends AbstractUnitExtInfo implements Comparable {
public ImportInfo() {
super();
}
public ImportInfo(String className, String unitName, String body) {
super(className, unitName, body);
}
@Override
public int compareTo(ImportInfo o) {
return this.getUnitName().compareTo(o.getUnitName());
}
}
|
java
| 10 | 0.722642 | 87 | 30.176471 | 17 |
starcoderdata
|
//
// GTUIFormBaseCell.h
// GTCatalog
//
// Created by liuxc on 2018/10/22.
//
#import
#import "GTUIFormDescriptorCell.h"
#import "GTUIFormViewController.h"
@class GTUIFormViewController;
@class GTUIFormRowDescriptor;
@interface GTUIFormBaseCell : UITableViewCell
@property (nonatomic, weak) GTUIFormRowDescriptor * rowDescriptor;
@property (nonatomic, strong) NSIndexPath *indexPath;
-(GTUIFormViewController *)formViewController;
@end
@protocol GTUIFormReturnKeyProtocol
@property UIReturnKeyType returnKeyType;
@property UIReturnKeyType nextReturnKeyType;
@end
|
c
| 6 | 0.794629 | 70 | 19.419355 | 31 |
starcoderdata
|
<?php
use Illuminate\Database\Seeder;
use App\Role;
class RoleTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$role_staff = new Role();
$role_staff->name_role = 'Staff';
$role_staff->save();
$role_spv = new Role();
$role_spv->name_role = 'Spv';
$role_spv->save();
$role_manager = new Role();
$role_manager->name_role = 'Manager';
$role_manager->save();
$role_admin = new Role();
$role_admin->name_role = 'Admin';
$role_admin->save();
}
}
|
php
| 9 | 0.512698 | 45 | 19.322581 | 31 |
starcoderdata
|
from .wishes_base import WishesBase
class CharacterWishes(WishesBase):
def init_params(self):
self.params['gacha_type'] = '301'
self.file_name = 'genshine_character_wishes.csv'
self.rst_file_name = 'character_analysis.txt'
self.table = 'character_wishes'
|
python
| 9 | 0.668852 | 56 | 29.5 | 10 |
starcoderdata
|
unsafe extern "system" fn callback<D: FmodDebug>(
flags: FMOD_DEBUG_FLAGS,
file: *const c_char,
line: c_int,
func: *const c_char,
msg: *const c_char,
) -> FMOD_RESULT {
catch_user_unwind(|| {
let flags = DebugFlags::from_raw(flags);
// SAFETY: these strings are produced directly by FMOD, so they
// should *actually* be guaranteed to be UTF-8 like FMOD claims.
let file = ptr::NonNull::new(file as *mut _)
.map(|x| str_from_nonnull_unchecked(x))
.map(str::trim_end);
let func = ptr::NonNull::new(func as *mut _)
.map(|x| str_from_nonnull_unchecked(x))
.map(str::trim_end);
let message = ptr::NonNull::new(msg as *mut _)
.map(|x| str_from_nonnull_unchecked(x))
.map(str::trim_end);
D::log(flags, file, line, func, message)
})
.unwrap_or(Err(Error::InternalRs))
.map_or_else(Error::into_raw, |()| FMOD_OK)
}
|
rust
| 20 | 0.568041 | 72 | 37.84 | 25 |
inline
|
import tables from '../tables/tables.js'
/* 清除测试数据
select * from ad_role where rolename like '测试%';
select * from ad_rolemenu where uuid_role in (select r.uuid_role from ad_role r where rolename like '测试%') ;
select * from ad_menu where type=0 and menuname='test' or menuname='a';
select * from ad_userrole where uuid_role in (select r.uuid_role from ad_role r where rolename like '测试%') ;
delete from ad_role where rolename like '测试%';
*/
export default {
//获取所有角色列表
getAllRoleSql() {
return {
select: '*',
from: "{" + tables.role.name + "}",
where: " where dr=0 and uuid_role in ( select uuid_role from ad_rolemenu where dr=0 and uuid_menu in (select uuid_menu from ad_menu where dr=0 and menulevel!=0 and parentid is not null and type=0 ) )"
}
},
//获取所有权限列表
getAllPermissionSql() {
return {
select: '*',
from: "{" + tables.permission.name + "}",
where: " where dr=0 and type=0 "
}
},
//根据角色获取权限列表
getPermissionByRoleSql(currentRole) {
return {
select: '*',
from: "{" + tables.permission.name + "}",
where: " where dr=0 and type=0 and " + tables.permission.colum.pk + " in (select " + tables.role_permission
.colum.pkPermission + " from " + tables.role_permission.name + " where dr=0 and " + tables.role_permission
.colum.pkRole + "='" + currentRole + "')"
}
},
//根据帐号获取当前所拥有的角色
getRoleByCode(code) {
return {
select: " f.rolename ,a.user_name, g.uuid_userrole",
from: "{ad_userrole g} ,{ad_role f},{sm_user a} ",
where: " where g.dr=0 and f.dr=0 and a.cuserid= g.cuserid and g.uuid_role= f.uuid_role and a.user_code='" +
code + "'"
}
},
//分配权限 ~根据员工帐号获取pk,用于判断更新或添加
getPersonPkByCode(code) {
return "$(select cuserid from sm_user where user_code='" + code + "')"
}
}
|
javascript
| 21 | 0.642171 | 209 | 32.396226 | 53 |
starcoderdata
|
/* Copyright(c) 1986 Association of Universities for Research in Astronomy Inc.
*/
#define import_spp
#define import_libc
#define import_knames
#include
/* SYSTEM -- Send a command to the host system. OK is returned if the command
** executes properly, else a positive integer error code identifying the error
** which occurred.
*/
int
system (
char *cmd /* command to be sent to host system */
)
{
PKCHAR nullstr[1];
XINT status;
nullstr[0] = EOS;
ZOSCMD (cmd, nullstr, nullstr, nullstr, &status);
return ((int) status);
}
|
c
| 7 | 0.708029 | 79 | 20.076923 | 26 |
starcoderdata
|
package ru.siksmfp.serialization.harness.serializer.impl.custom;
import ru.siksmfp.serialization.harness.converter.impl.custom.CustomConverter;
import ru.siksmfp.serialization.harness.dto.custom.CustomDto;
import ru.siksmfp.serialization.harness.model.custom.CustomModel;
import ru.siksmfp.serialization.harness.serializer.api.Serializer;
public class CustomSerializer implements Serializer {
private CustomConverter converter = new CustomConverter();
@Override
public byte[] serialize(CustomModel dto) {
CustomDto customDto = converter.toDto(dto);
//implement serialization of dto to byte array
return new byte[0];
}
@Override
public CustomModel deSerialize(byte[] bytes) {
CustomDto dto = new CustomDto("1");
//implement deserialization of byte array into dto
return converter.toModel(dto);
}
}
|
java
| 10 | 0.744681 | 78 | 32.074074 | 27 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.