repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
hosomi/LeetCode
#0105.construct-binary-tree-from-preorder-and-inorder-traversal.cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if (preorder.empty()) { return nullptr; } TreeNode* result = new TreeNode(preorder[0]); int index = std::find(inorder.begin(), inorder.end(), preorder[0]) - inorder.begin(); vector<int> vinorder(inorder.begin(), inorder.begin() + index); vector<int> vpreorder(preorder.begin() + 1, preorder.begin() + 1 + vinorder.size()); result->left = buildTree(vpreorder, vinorder); vpreorder = {preorder.begin() + 1 + vinorder.size(), preorder.end()}; vinorder = {inorder.begin() + index + 1, inorder.end()}; result->right = buildTree(vpreorder, vinorder); return result; } };
Hellorin/stickyMoss
stickymossCoreServices/src/main/java/com/hellorin/stickyMoss/jobHunting/services/ApplicantService.java
<gh_stars>0 package com.hellorin.stickyMoss.jobHunting.services; import com.hellorin.stickyMoss.jobHunting.domain.Applicant; import com.hellorin.stickyMoss.jobHunting.exceptions.ApplicantNotFoundException; import com.hellorin.stickyMoss.jobHunting.repositories.ApplicantRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.Optional; import java.util.logging.Logger; /** * Created by hellorin on 04.07.17. */ @Service @Transactional public class ApplicantService implements IApplicantService { static Logger logger = Logger.getLogger(ApplicantService.class.getName()); @Autowired protected ApplicantRepository applicantRepository; @Override public Applicant getApplicant(final Long id) { Optional<Applicant> applicant = Optional.ofNullable(applicantRepository.findOne(id)); return applicant .orElseThrow(() -> new ApplicantNotFoundException("Applicant not found with id " + id)); } @Override public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException { Optional<Applicant> applicant = applicantRepository.findByEmail(email); return applicant .orElseThrow(() -> new UsernameNotFoundException("Cannot find user with email " + email)); } }
gmlueck/llvm-test-suite
MultiSource/Benchmarks/Prolangs-C/TimberWolfMC/bellman.c
#include "geo.h" #define DEBUG extern FILE *fpo ; void bellman(void) { int i , j , D , distance ; WCPTR ptr ; xBellArray = (BELLBOXPTR) malloc((1 + numXnodes) * sizeof(BELLBOX)); yBellArray = (BELLBOXPTR) malloc((1 + numYnodes) * sizeof(BELLBOX)); xBellArray[1].from = 0 ; xBellArray[1].distance = 0 ; for( i = 2 ; i <= numXnodes ; i++ ) { xBellArray[i].distance = VBIG ; } for( i = 1 ; i <= numXnodes ; i++ ) { D = xBellArray[i].distance ; for( ptr = xNodeArray[i]; ptr != (WCPTR) NULL ; ptr = ptr->next ){ j = ptr->node ; distance = - (ptr->length) ; if( xBellArray[j].distance > D + distance ) { xBellArray[j].distance = D + distance ; xBellArray[j].from = i ; } } } yBellArray[1].from = 0 ; yBellArray[1].distance = 0 ; for( i = 2 ; i <= numYnodes ; i++ ) { yBellArray[i].distance = VBIG ; } for( i = 1 ; i <= numYnodes ; i++ ) { D = yBellArray[i].distance ; for( ptr = yNodeArray[i]; ptr != (WCPTR) NULL ; ptr = ptr->next ){ j = ptr->node ; distance = - (ptr->length) ; if( yBellArray[j].distance > D + distance ) { yBellArray[j].distance = D + distance ; yBellArray[j].from = i ; } } } #ifdef DEBUG fprintf(fpo,"Longest Hori. Path in Circuit Graph has span: <%d>\n", - xBellArray[numXnodes].distance ) ; fprintf(fpo,"Longest Vert. Path in Circuit Graph has span: <%d>\n", - yBellArray[numYnodes].distance ) ; #endif return ; }
Expander/polylogarithm
test/alt/algorithm_327/algorithm_327.c
#include <math.h> /* Algorithm 327, Dilogarithm [S22] <NAME> (Rect. 10 Oct. 1967) Applied Mathematics Group, Data Handling Division, European Organization for Nuclear Research (CERN) 1211 Genea 23, Switzerland Published in Communications of the ACM, Volume 11, Number 4, p. 270f, April 1968 Translated to C by <NAME> */ double algorithm_327(double x) { const double PI = 3.141592653589793; const double PI2 = PI*PI; const double PI3 = PI2/3; const double PI6 = PI2/6; double f, u, y, z, l; if (x >= 2) { l = log(x); z = 1/x; u = -0.5*l*l + PI3; f = -1; } else if (x > 1) { z = (x - 1)/x; u = -0.5*log(x)*log(z*x - z) + PI6; f = 1; } else if (x == 1) { return PI6; } else if (x > 0.5) { z = 1 - x; u = -log(x)*log(z) + PI6; f = -1; } else if (x > 0) { z = x; u = 0; f = 1; } else if (x == 0) { return 0; } else if (x >= -1) { l = log(1 - x); z = x/(x - 1); u = -0.5*l*l; f = -1; } else { z = 1/(1 - x); u = 0.5*log(z)*log(x*x*z) - PI6; f = 1; } y = 0.008048124718341*z + 0.008288074835108; y = y*z - 0.001481786416153; y = y*z - 0.000912777413024; y = y*z + 0.005047192127203; y = y*z + 0.005300972587634; y = y*z + 0.004091615355944; y = y*z + 0.004815490327461; y = y*z + 0.005966509196748; y = y*z + 0.006980881130380; y = y*z + 0.008260083434161; y = y*z + 0.009997129506220; y = y*z + 0.012345919431569; y = y*z + 0.015625134938703; y = y*z + 0.020408155605916; y = y*z + 0.027777774308288; y = y*z + 0.040000000124677; y = y*z + 0.062500000040762; y = y*z + 0.111111111110322; y = y*z + 0.249999999999859; y = y*z + 1; return f*y*z + u; }
autuanthinh/react-template-full
internals/generators/index.js
/** * generator/index.js * * Exports the generators so plop knows them */ const fs = require('fs'); const path = require('path'); const languageGenerator = require('./language/index.js'); module.exports = plop => { plop.setGenerator('language', languageGenerator); plop.addHelper('directory', comp => { try { fs.accessSync(path.join(__dirname, `../../src/components/${comp}`), fs.F_OK); return `components/${comp}`; } catch (e) { return `containers/${comp}`; } }); plop.addHelper('curly', (object, open) => (open ? '{' : '}')); };
zouzhihao1992/DataStucture
DataStructure/Arena_1782.cpp
// // Arena_1782.cpp // DataStructure // // Created by zzh on 15/5/3. // Copyright (c) 2015年 zzh. All rights reserved. // #include "Arena_1782.h" #include <stdio.h> int main_Arena_1782() { int n,m; scanf("%d%d",&n,&m); int book[m+1]; for (int j=0; j<=m+1; j++) { book[j]=0; } int person[n+1]; int i; for (i=1; i<=n; i++) { int temp; scanf("%d",&temp); book[temp]++; person[i]=temp; } for (i=1; i<=n; i++) { if (book[person[i]]>1) { printf("%d\n",book[person[i]]-1); } else { printf("BeiJu\n"); } } return 0; }
bt-nia/Application-Gateway
oag/src/test/java/org/owasp/oag/services/crypto/jwt/HmacJwtSignerTest.java
<reponame>bt-nia/Application-Gateway package org.owasp.oag.services.crypto.jwt; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.MACVerifier; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import org.apache.commons.codec.binary.Hex; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class HmacJwtSignerTest { @Test public void testHmacJwtSigner() throws Exception { // Arrange String key = "DEADBEEFdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"; // hex string with mixed case String keyId = "KeyID"; String subject = "<NAME>"; var signer = new HmacJwtSigner(key, keyId); var claims = new JWTClaimsSet.Builder().subject(subject).build(); JWSVerifier verifier = new MACVerifier(Hex.decodeHex(key)); // Act var jwt = signer.createSignedJwt(claims); // Assert SignedJWT parsedJwt = SignedJWT.parse(jwt); assertEquals(keyId, parsedJwt.getHeader().getKeyID()); assertEquals(subject, parsedJwt.getJWTClaimsSet().getSubject()); assertEquals(JWSAlgorithm.HS256, parsedJwt.getHeader().getAlgorithm()); assertTrue(parsedJwt.verify(verifier)); } @Test public void testHmacJwtSignerInvalidParameters() throws Exception { assertThrows(Exception.class, () -> new HmacJwtSigner(null, null), "Null key should result in exception"); assertThrows(Exception.class, () -> new HmacJwtSigner("DEADBEEF", null), "Invalid key length should result in exception"); assertThrows(Exception.class, () -> new HmacJwtSigner("XXXXXXXXdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", null), "Non hex string should result in exception"); } }
bobozhengsir/DesignPatternsStories
src/main/java/com/programcreek/designpatterns/observer/SimpleSwingExample.java
<filename>src/main/java/com/programcreek/designpatterns/observer/SimpleSwingExample.java package com.programcreek.designpatterns.observer; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import javax.swing.*; /** * Created with IntelliJ IDEA. * User: wujiaoniao * Date: 13-12-17 * Time: 上午9:58 * Description: To change this template use File | Settings | File Templates. */ public class SimpleSwingExample { public static void run() { JFrame frame = new JFrame("Frame Title"); final JTextArea comp = new JTextArea(); JButton btn = new JButton("click"); frame.getContentPane().add(comp, BorderLayout.CENTER); frame.getContentPane().add(btn, BorderLayout.SOUTH); btn.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { comp.setText("Button has been clicked"); } }); int width = 300; int height = 300; frame.setSize(width, height); frame.setVisible(true); } }
Excentrics/publication-backbone
publication_backbone/admin/forms.py
<filename>publication_backbone/admin/forms.py #-*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django import forms from django.contrib import admin from django.forms import models from mptt.forms import TreeNodeMultipleChoiceField, TreeNodeChoiceField from publication_backbone.models import ( Publication, Rubric, Category, BaseCategory, PublicationGroup, PublicationRelation, ) from publication_backbone.forms_bases.mptt.forms import FullPathTreeNodeChoiceField from ckeditor.widgets import CKEditorWidget from salmonella.widgets import SalmonellaIdWidget from publication_backbone.admin.widgets import RubricTreeWidget #============================================================================== # PublicationAdminForm #============================================================================== class PublicationAdminForm(forms.ModelForm): rubrics = forms.ModelMultipleChoiceField(queryset=Rubric.objects.active().exclude(system_flags=Rubric.system_flags.tagged_restriction), required=False, widget=RubricTreeWidget(), label=_("Rubrics")) class Meta: model = Publication #============================================================================== # CategoryAdminForm #============================================================================== class CategoryAdminForm(forms.ModelForm): rubrics = forms.ModelMultipleChoiceField(queryset=Rubric.objects.all(), #active(), required=False, widget=RubricTreeWidget(), label=_("Rubrics")) parent = TreeNodeChoiceField(queryset=BaseCategory.objects.all(), level_indicator=u'+--', #empty_label='-'*9, label=_('Parent'), required=False) class Meta: model = BaseCategory #============================================================================== # RubricAdminForm #============================================================================== class RubricAdminForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Rubric.objects.all(), level_indicator=u'+--', label=_('Parent'), required=False) class Meta: model = Rubric def clean(self): cleaned_data = self.cleaned_data #if not cleaned_data.get("main_object"): # raise forms.ValidationError("Closed for editing") try: result = super(RubricAdminForm, self).clean() # important- let admin do its work on data! except Rubric.EditNotAllowedError as e: raise forms.ValidationError(e) return result #============================================================================== # PublicationCharacteristicOrMarkInlineForm #============================================================================== class PublicationCharacteristicOrMarkInlineForm(models.ModelForm): rubric = FullPathTreeNodeChoiceField(queryset=Rubric.objects.attribute_is_characteristic_or_mark(), joiner=' / ', label=_('Characteristic or mark')) #============================================================================== # PublicationRelationInlineForm #============================================================================== class PublicationRelationInlineForm(models.ModelForm): rubric = FullPathTreeNodeChoiceField(queryset=Rubric.objects.attribute_is_relation(), joiner=' / ', label=_('Relation')) to_publication = forms.ModelChoiceField(queryset=Publication.objects.all(), widget=SalmonellaIdWidget(PublicationRelation._meta.get_field("to_publication").rel, admin.site), label=_('Target')) #============================================================================== # CategoryPublicationRelationInlineForm #============================================================================== class CategoryPublicationRelationInlineForm(models.ModelForm): rubric = FullPathTreeNodeChoiceField(queryset=Rubric.objects.attribute_is_relation(), required=False, joiner=' / ', label=_('Relation filter')) #============================================================================== # CategoryPromotionAdminForm #============================================================================== class CategoryPromotionAdminForm(forms.ModelForm): category = TreeNodeChoiceField(queryset=Category.objects.all(), level_indicator=u'+--', label=_("Category")) #============================================================================== # PublicationSelectRubricsAdminForm #============================================================================== class PublicationSelectRubricsAdminForm(forms.Form): rubrics_set = TreeNodeMultipleChoiceField(queryset=Rubric.objects.all(), level_indicator=u'+--', #empty_label='-'*9, required=False, label=_("Rubrics to set"), help_text=_( """Use "ctrl" key for choose multiple rubrics""")) rubrics_unset = TreeNodeMultipleChoiceField(queryset=Rubric.objects.all(), level_indicator=u'+--', #empty_label='-'*9, required=False, label=_("Rubrics to unset"), help_text=_( """Use "ctrl" key for choose multiple rubrics""")) def __init__(self, *args, **kwargs): super(PublicationSelectRubricsAdminForm, self).__init__(*args, **kwargs) # change a widget attribute: self.fields['rubrics_set'].widget.attrs["size"] = 40 self.fields['rubrics_unset'].widget.attrs["size"] = 40 #============================================================================== # PublicationSetDescriptionAdminForm #============================================================================== class PublicationSetDescriptionAdminForm(forms.Form): description = forms.CharField(widget=CKEditorWidget(), label=_('Description'), required=False) #============================================================================== # PublicationSelectGroupsAdminForm #============================================================================== class PublicationSelectGroupsAdminForm(forms.Form): group = forms.ModelChoiceField(queryset=PublicationGroup.objects.all(), widget=SalmonellaIdWidget(Publication._meta.get_field("group").rel, admin.site), label=_('Group')) #============================================================================== # PublicationSetEstimatedDeliveryAdminForm #============================================================================== class PublicationSetEstimatedDeliveryAdminForm(forms.Form): estimated_delivery = forms.CharField(label=_('estimated delivery'), required=False) #============================================================================== # MergeRubricsAdminForm #============================================================================== class MergeRubricsAdminForm(forms.Form): to_rubric = TreeNodeChoiceField(queryset=Rubric.objects.all(), level_indicator=u'+--', label=_("Destination rubric"), help_text=_( """Select destination rubric to merge""")) #============================================================================== # MakeRubricsByPublicationsAttributesAdminForm #============================================================================== class MakeRubricsByPublicationsAttributesAdminForm(forms.Form): pass
HedgehogFog/TimeOfDeath
build/linux-build/Sources/src/zpp_nape/space/ZPP_AABBPair.cpp
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_zpp_nape_dynamics_ZPP_Arbiter #include <hxinc/zpp_nape/dynamics/ZPP_Arbiter.h> #endif #ifndef INCLUDED_zpp_nape_space_ZPP_AABBNode #include <hxinc/zpp_nape/space/ZPP_AABBNode.h> #endif #ifndef INCLUDED_zpp_nape_space_ZPP_AABBPair #include <hxinc/zpp_nape/space/ZPP_AABBPair.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_6f23172c9b6055f0_273_new,"zpp_nape.space.ZPP_AABBPair","new",0x01861dfa,"zpp_nape.space.ZPP_AABBPair.new","zpp_nape/space/DynAABBPhase.hx",273,0x55500cf1) HX_LOCAL_STACK_FRAME(_hx_pos_6f23172c9b6055f0_310_alloc,"zpp_nape.space.ZPP_AABBPair","alloc",0x8e280c8f,"zpp_nape.space.ZPP_AABBPair.alloc","zpp_nape/space/DynAABBPhase.hx",310,0x55500cf1) HX_LOCAL_STACK_FRAME(_hx_pos_6f23172c9b6055f0_321_free,"zpp_nape.space.ZPP_AABBPair","free",0x4e9435d2,"zpp_nape.space.ZPP_AABBPair.free","zpp_nape/space/DynAABBPhase.hx",321,0x55500cf1) HX_LOCAL_STACK_FRAME(_hx_pos_6f23172c9b6055f0_282_boot,"zpp_nape.space.ZPP_AABBPair","boot",0x4bed1d58,"zpp_nape.space.ZPP_AABBPair.boot","zpp_nape/space/DynAABBPhase.hx",282,0x55500cf1) namespace zpp_nape{ namespace space{ void ZPP_AABBPair_obj::__construct(){ HX_STACKFRAME(&_hx_pos_6f23172c9b6055f0_273_new) HXLINE( 281) this->next = null(); HXLINE( 280) this->arb = null(); HXLINE( 279) this->di = 0; HXLINE( 278) this->id = 0; HXLINE( 277) this->sleeping = false; HXLINE( 276) this->first = false; HXLINE( 275) this->n2 = null(); HXLINE( 274) this->n1 = null(); } Dynamic ZPP_AABBPair_obj::__CreateEmpty() { return new ZPP_AABBPair_obj; } void *ZPP_AABBPair_obj::_hx_vtable = 0; Dynamic ZPP_AABBPair_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZPP_AABBPair_obj > _hx_result = new ZPP_AABBPair_obj(); _hx_result->__construct(); return _hx_result; } bool ZPP_AABBPair_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x0a1d3fd4; } void ZPP_AABBPair_obj::alloc(){ HX_STACKFRAME(&_hx_pos_6f23172c9b6055f0_310_alloc) } HX_DEFINE_DYNAMIC_FUNC0(ZPP_AABBPair_obj,alloc,(void)) void ZPP_AABBPair_obj::free(){ HX_STACKFRAME(&_hx_pos_6f23172c9b6055f0_321_free) HXLINE( 330) this->n1 = (this->n2 = null()); HXLINE( 331) this->sleeping = false; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_AABBPair_obj,free,(void)) ::zpp_nape::space::ZPP_AABBPair ZPP_AABBPair_obj::zpp_pool; hx::ObjectPtr< ZPP_AABBPair_obj > ZPP_AABBPair_obj::__new() { hx::ObjectPtr< ZPP_AABBPair_obj > __this = new ZPP_AABBPair_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZPP_AABBPair_obj > ZPP_AABBPair_obj::__alloc(hx::Ctx *_hx_ctx) { ZPP_AABBPair_obj *__this = (ZPP_AABBPair_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZPP_AABBPair_obj), true, "zpp_nape.space.ZPP_AABBPair")); *(void **)__this = ZPP_AABBPair_obj::_hx_vtable; __this->__construct(); return __this; } ZPP_AABBPair_obj::ZPP_AABBPair_obj() { } void ZPP_AABBPair_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZPP_AABBPair); HX_MARK_MEMBER_NAME(n1,"n1"); HX_MARK_MEMBER_NAME(n2,"n2"); HX_MARK_MEMBER_NAME(first,"first"); HX_MARK_MEMBER_NAME(sleeping,"sleeping"); HX_MARK_MEMBER_NAME(id,"id"); HX_MARK_MEMBER_NAME(di,"di"); HX_MARK_MEMBER_NAME(arb,"arb"); HX_MARK_MEMBER_NAME(next,"next"); HX_MARK_END_CLASS(); } void ZPP_AABBPair_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(n1,"n1"); HX_VISIT_MEMBER_NAME(n2,"n2"); HX_VISIT_MEMBER_NAME(first,"first"); HX_VISIT_MEMBER_NAME(sleeping,"sleeping"); HX_VISIT_MEMBER_NAME(id,"id"); HX_VISIT_MEMBER_NAME(di,"di"); HX_VISIT_MEMBER_NAME(arb,"arb"); HX_VISIT_MEMBER_NAME(next,"next"); } hx::Val ZPP_AABBPair_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"n1") ) { return hx::Val( n1 ); } if (HX_FIELD_EQ(inName,"n2") ) { return hx::Val( n2 ); } if (HX_FIELD_EQ(inName,"id") ) { return hx::Val( id ); } if (HX_FIELD_EQ(inName,"di") ) { return hx::Val( di ); } break; case 3: if (HX_FIELD_EQ(inName,"arb") ) { return hx::Val( arb ); } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { return hx::Val( next ); } if (HX_FIELD_EQ(inName,"free") ) { return hx::Val( free_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"first") ) { return hx::Val( first ); } if (HX_FIELD_EQ(inName,"alloc") ) { return hx::Val( alloc_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"sleeping") ) { return hx::Val( sleeping ); } } return super::__Field(inName,inCallProp); } bool ZPP_AABBPair_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { outValue = ( zpp_pool ); return true; } } return false; } hx::Val ZPP_AABBPair_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"n1") ) { n1=inValue.Cast< ::zpp_nape::space::ZPP_AABBNode >(); return inValue; } if (HX_FIELD_EQ(inName,"n2") ) { n2=inValue.Cast< ::zpp_nape::space::ZPP_AABBNode >(); return inValue; } if (HX_FIELD_EQ(inName,"id") ) { id=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"di") ) { di=inValue.Cast< int >(); return inValue; } break; case 3: if (HX_FIELD_EQ(inName,"arb") ) { arb=inValue.Cast< ::zpp_nape::dynamics::ZPP_Arbiter >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"next") ) { next=inValue.Cast< ::zpp_nape::space::ZPP_AABBPair >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"first") ) { first=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"sleeping") ) { sleeping=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool ZPP_AABBPair_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"zpp_pool") ) { zpp_pool=ioValue.Cast< ::zpp_nape::space::ZPP_AABBPair >(); return true; } } return false; } void ZPP_AABBPair_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("n1",03,60,00,00)); outFields->push(HX_("n2",04,60,00,00)); outFields->push(HX_("first",30,78,9d,00)); outFields->push(HX_("sleeping",2b,58,93,10)); outFields->push(HX_("id",db,5b,00,00)); outFields->push(HX_("di",85,57,00,00)); outFields->push(HX_("arb",51,fe,49,00)); outFields->push(HX_("next",f3,84,02,49)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZPP_AABBPair_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::zpp_nape::space::ZPP_AABBNode */ ,(int)offsetof(ZPP_AABBPair_obj,n1),HX_("n1",03,60,00,00)}, {hx::fsObject /* ::zpp_nape::space::ZPP_AABBNode */ ,(int)offsetof(ZPP_AABBPair_obj,n2),HX_("n2",04,60,00,00)}, {hx::fsBool,(int)offsetof(ZPP_AABBPair_obj,first),HX_("first",30,78,9d,00)}, {hx::fsBool,(int)offsetof(ZPP_AABBPair_obj,sleeping),HX_("sleeping",2b,58,93,10)}, {hx::fsInt,(int)offsetof(ZPP_AABBPair_obj,id),HX_("id",db,5b,00,00)}, {hx::fsInt,(int)offsetof(ZPP_AABBPair_obj,di),HX_("di",85,57,00,00)}, {hx::fsObject /* ::zpp_nape::dynamics::ZPP_Arbiter */ ,(int)offsetof(ZPP_AABBPair_obj,arb),HX_("arb",51,fe,49,00)}, {hx::fsObject /* ::zpp_nape::space::ZPP_AABBPair */ ,(int)offsetof(ZPP_AABBPair_obj,next),HX_("next",f3,84,02,49)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo ZPP_AABBPair_obj_sStaticStorageInfo[] = { {hx::fsObject /* ::zpp_nape::space::ZPP_AABBPair */ ,(void *) &ZPP_AABBPair_obj::zpp_pool,HX_("zpp_pool",81,5d,d4,38)}, { hx::fsUnknown, 0, null()} }; #endif static ::String ZPP_AABBPair_obj_sMemberFields[] = { HX_("n1",03,60,00,00), HX_("n2",04,60,00,00), HX_("first",30,78,9d,00), HX_("sleeping",2b,58,93,10), HX_("id",db,5b,00,00), HX_("di",85,57,00,00), HX_("arb",51,fe,49,00), HX_("next",f3,84,02,49), HX_("alloc",75,a4,93,21), HX_("free",ac,9c,c2,43), ::String(null()) }; static void ZPP_AABBPair_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ZPP_AABBPair_obj::zpp_pool,"zpp_pool"); }; #ifdef HXCPP_VISIT_ALLOCS static void ZPP_AABBPair_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ZPP_AABBPair_obj::zpp_pool,"zpp_pool"); }; #endif hx::Class ZPP_AABBPair_obj::__mClass; static ::String ZPP_AABBPair_obj_sStaticFields[] = { HX_("zpp_pool",81,5d,d4,38), ::String(null()) }; void ZPP_AABBPair_obj::__register() { ZPP_AABBPair_obj _hx_dummy; ZPP_AABBPair_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.space.ZPP_AABBPair",08,59,75,3f); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &ZPP_AABBPair_obj::__GetStatic; __mClass->mSetStaticField = &ZPP_AABBPair_obj::__SetStatic; __mClass->mMarkFunc = ZPP_AABBPair_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(ZPP_AABBPair_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(ZPP_AABBPair_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZPP_AABBPair_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ZPP_AABBPair_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZPP_AABBPair_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZPP_AABBPair_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void ZPP_AABBPair_obj::__boot() { { HX_STACKFRAME(&_hx_pos_6f23172c9b6055f0_282_boot) HXDLIN( 282) zpp_pool = null(); } } } // end namespace zpp_nape } // end namespace space
liumapp/jks-core
src/main/java/com/liumapp/jks/core/job/JobDetail.java
package com.liumapp.jks.core.job; import com.alibaba.fastjson.JSONObject; /** * author liumapp * file JobDetail.java * email <EMAIL> * homepage http://www.liumapp.com * date 6/28/18 */ public abstract class JobDetail<T extends JobData> { protected JSONObject jobResult; public JobDetail() { this.jobResult = new JSONObject(); } public abstract JSONObject handle(T data); }
akiyamayami/KLTN
src/main/java/com/tlcn/model/SttDriver.java
<filename>src/main/java/com/tlcn/model/SttDriver.java<gh_stars>0 package com.tlcn.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity(name = "sttdriver") public class SttDriver { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int sttdriverID; private String name; @OneToMany(mappedBy="sttdriver") private List<Driver> listdriver; public SttDriver() { super(); } public SttDriver(int sttdriverID, String name, List<Driver> listdriver) { super(); this.sttdriverID = sttdriverID; this.name = name; this.listdriver = listdriver; } public int getSttdriverID() { return sttdriverID; } public void setSttdriverID(int sttdriverID) { this.sttdriverID = sttdriverID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Driver> getListdriver() { return listdriver; } public void setListdriver(List<Driver> listdriver) { this.listdriver = listdriver; } }
ruifly2012/server-1
store/db/db.go
package db import ( "context" "errors" "time" "github.com/urfave/cli/v2" "go.mongodb.org/mongo-driver/mongo/options" ) // db find no result var ErrNoResult = errors.New("db return no result") var ( DatabaseWriteTimeout = time.Second * 5 DatabaseLoadTimeout = time.Second * 5 DatabaseBulkWriteTimeout = time.Second * 10 ) type DB interface { MigrateTable(colName string, indexNames ...string) error FindOne(ctx context.Context, colName string, filter any, result any) error Find(ctx context.Context, colName string, filter any) (map[string]any, error) InsertOne(ctx context.Context, colName string, insert any) error InsertMany(ctx context.Context, colName string, inserts []any) error UpdateOne(ctx context.Context, colName string, filter any, update any, opts ...*options.UpdateOptions) error DeleteOne(ctx context.Context, colName string, filter any) error BulkWrite(ctx context.Context, colName string, model any) error Flush() Exit() } func NewDB(ctx *cli.Context) DB { return NewMongoDB(ctx) }
gruz0/inspirer-web
spec/services/activity/yoga/asanas/contracts/update_contract_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Activity::Yoga::Asanas::Contracts::UpdateContract do let(:input) do { attributes: { notes: 'Asana', feeling: 'good' } } end include_examples 'it validates contract' end
mccollek/itjobstudyv2
db/migrate/20131230185446_add_data_type_id_to_bls_column_mapper.rb
<reponame>mccollek/itjobstudyv2 class AddDataTypeIdToBlsColumnMapper < ActiveRecord::Migration def change add_column :bls_column_mappers, :data_type_id, :integer end end
datagym-ai/datagym-core
datagym-backend/src/main/java/ai/datagym/application/labelTask/controller/UserTaskController.java
package ai.datagym.application.labelTask.controller; import ai.datagym.application.labelTask.models.viewModels.LabelTaskViewModel; import ai.datagym.application.labelTask.models.viewModels.UserTaskViewModel; import ai.datagym.application.labelTask.service.UserTaskService; import org.hibernate.validator.constraints.Length; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.constraints.NotBlank; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.security.NoSuchAlgorithmException; import java.util.List; @RestController @RequestMapping(value = "/api/user") @Validated public class UserTaskController { private final UserTaskService userTaskService; @Autowired public UserTaskController(UserTaskService userTaskService) { this.userTaskService = userTaskService; } @GetMapping(value = "/taskList") public List<UserTaskViewModel> getUserTasks() throws NoSuchMethodException, NoSuchAlgorithmException, IOException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { return userTaskService.getUserTasks(); } @GetMapping(value = "/nextTask") public LabelTaskViewModel getNextTask() { return userTaskService.getNextTask(null); } @GetMapping(value = "/nextTask/{projectId}") public LabelTaskViewModel getNextTaskFromProject(@PathVariable("projectId") @NotBlank @Length(min = 1) String projectId) { return userTaskService.getNextTask(projectId); } @GetMapping(value = "/nextReview/{projectId}") public LabelTaskViewModel getNextReviewTaskFromProject(@PathVariable("projectId") @NotBlank @Length(min = 1) String projectId) { return userTaskService.getNextReviewTask(projectId); } }
nelcolon/pocket-core
util/http.go
package util import ( "bytes" "encoding/json" "errors" "io/ioutil" "net/http" ) type Method int const ( POST Method = iota + 1 GET ) func (m Method) String() string { return [...]string{"GET", "POST"}[m] } func RPCRequ(url string, data []byte, m Method) (string, error) { req, err := http.NewRequest(m.String(), url, bytes.NewBuffer(data)) // handle error if err != nil { return "", errors.New("Cannot convert struct to json " + err.Error()) } return rpcRequ(url, req) } // "StructRPCReq" sends an RPC request and returns the response func StructRPCReq(url string, data interface{}, m Method) (string, error) { // convert structure to json j, err := json.Marshal(data) // handle error if err != nil { return "", errors.New("Cannot convert struct to json " + err.Error()) } // create new post request req, err := http.NewRequest(m.String(), url, bytes.NewBuffer(j)) // hanlde error if err != nil { return "", errors.New("Cannot create request " + err.Error()) } return rpcRequ(url, req) } func rpcRequ(url string, req *http.Request) (string, error) { // setup header for json data req.Header.Set("Content-Type", "application/json") // setup http client client := &http.Client{} resp, err := client.Do(req) if err != nil { return "", errors.New("Unable to do request " + err.Error()) } if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) return "", errors.New(string(body)) } // get body of response body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", errors.New("Unable to unmarshal response: " + err.Error()) } return string(body), nil }
onehilltech/backbone
backbone-gatekeeper/src/main/java/com/onehilltech/backbone/gatekeeper/http/JsonChangePassword.java
<reponame>onehilltech/backbone package com.onehilltech.backbone.gatekeeper.http; import com.google.gson.annotations.SerializedName; public class JsonChangePassword { @SerializedName ("current") public String currentPassword; @SerializedName ("new") public String newPassword; }
zrj-rimwis/DeltaPorts
ports/math/cado-nfs/dragonfly/patch-utils_select__mpi.h
<reponame>zrj-rimwis/DeltaPorts --- utils/select_mpi.h.orig 2021-09-16 01:25:08 UTC +++ utils/select_mpi.h @@ -3,7 +3,7 @@ #include "cado_mpi_config.h" #include "macros.h" -#if !(defined(__OpenBSD__) || defined(__FreeBSD__)) +#if !(defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)) #if !(defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) #ifdef HAVE_GLIBC #include <features.h> // we must be sure to include something from the glibc...
duweiwang/java-playground
src/main/java/com/wangduwei/java_basic/collection/queue/QueueApi.java
<reponame>duweiwang/java-playground package com.wangduwei.java_basic.collection.queue; import java.util.Deque; import java.util.LinkedList; import java.util.Queue; /** * <p>队列的相关操作 * * @auther: wangduwei * @since: 2019/7/25 **/ public class QueueApi { public static void main(String[] args) { QueueApi.testQueue(); QueueApi.testDequeue(); QueueApi.containsTest(); QueueApi.testQueue2(); } public static void testQueue2(){ Queue<String> queue = new LinkedList<>(); queue.add("1"); queue.add("2"); queue.add("3"); queue.remove("1"); queue.peek(); queue.remove(); } public static void testQueue() { Deque<String> deque = new LinkedList<>(); //队尾追加 deque.add("add-1"); deque.add("add-2"); deque.add("add-3"); // deque.addFirst("addFirst-1"); deque.addLast("addLast-1"); deque.offer("offer-1"); deque.offer("offer-2"); deque.offer("offer-3"); deque.offerFirst("offerFirst-1"); deque.offerLast("offerLast-1"); while (!deque.isEmpty()) { deque.poll(); } } public static void testDequeue() { Deque<String> deque = new LinkedList<>(); for (int i = 0; i < 20; i++) { if (deque.size() < 10) { deque.add(i + ""); } else { deque.poll(); deque.add(i + ""); } } } public static void containsTest() { Queue<TestObject> queue = new LinkedList<>(); queue.offer(new TestObject("sss")); TestObject two = new TestObject("sss"); if (!queue.contains(two)) { queue.add(two); } } public static class TestObject { public String name; public TestObject(String name){ this.name = name; } @Override public boolean equals(Object o) { if (o == this){ return true; } if (o instanceof TestObject){ TestObject t = ((TestObject) o); if (t.name.equals(name)){ return true; } } return false; } } }
katemihalikova/test262
test/built-ins/Object/defineProperty/15.2.3.6-4-290.js
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.6-4-290 description: > Object.defineProperty - 'O' is an Arguments object, 'name' is own property of 'O', and is deleted afterwards, and 'desc' is accessor descriptor, test 'name' is redefined in 'O' with all correct attribute values (10.6 [[DefineOwnProperty]] step 3) includes: [propertyHelper.js] ---*/ (function() { delete arguments[0]; function getFunc() { return 10; } function setFunc(value) { this.setVerifyHelpProp = value; } Object.defineProperty(arguments, "0", { get: getFunc, set: setFunc, enumerable: true, configurable: true }); verifyEqualTo(arguments, "0", getFunc()); verifyWritable(arguments, "0", "setVerifyHelpProp"); verifyEnumerable(arguments, "0"); verifyConfigurable(arguments, "0"); }(0, 1, 2));
basho-labs/riak-explorer-gui
app/pods/node/monitoring/controller.js
import Ember from 'ember'; import Modal from '../../../mixins/controller/modal'; export default Ember.Controller.extend(Modal, { currentGraphs: [], availableGraphs: [], actions: { updateGraphName: function(graph, newStat) { return this.set('currentGraphs', this.get('currentGraphs').map(function(graphName) { return (graphName === graph) ? newStat : graphName; })); }, addNewGraph: function(graph) { this.get('currentGraphs').pushObject(graph); this.send('hideModal'); }, removeGraph: function(graph) { this.set('currentGraphs', this.get('currentGraphs').filter(function(graphName) { return graphName !== graph; })); } } });
maidiHaitai/haitaibrowser
third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
<reponame>maidiHaitai/haitaibrowser /* * Copyright (C) 2004 <NAME> <<EMAIL>> * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved. * Copyright (C) 2007 <NAME> <<EMAIL>> * Copyright (C) 2007 <NAME> <<EMAIL>> * Copyright (C) 2011 Sencha, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "core/css/CSSComputedStyleDeclaration.h" #include "bindings/core/v8/ExceptionState.h" #include "core/CSSPropertyNames.h" #include "core/css/CSSPrimitiveValueMappings.h" #include "core/css/CSSPropertyMetadata.h" #include "core/css/CSSSelector.h" #include "core/css/CSSValuePool.h" #include "core/css/CSSVariableData.h" #include "core/css/ComputedStyleCSSValueMapping.h" #include "core/css/parser/CSSParser.h" #include "core/css/parser/CSSVariableParser.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/Document.h" #include "core/dom/ExceptionCode.h" #include "core/dom/PseudoElement.h" #include "core/layout/LayoutObject.h" #include "core/style/ComputedStyle.h" #include "wtf/text/StringBuilder.h" namespace blink { // List of all properties we know how to compute, omitting shorthands. // NOTE: Do not use this list, use computableProperties() instead // to respect runtime enabling of CSS properties. static const CSSPropertyID staticComputableProperties[] = { CSSPropertyAnimationDelay, CSSPropertyAnimationDirection, CSSPropertyAnimationDuration, CSSPropertyAnimationFillMode, CSSPropertyAnimationIterationCount, CSSPropertyAnimationName, CSSPropertyAnimationPlayState, CSSPropertyAnimationTimingFunction, CSSPropertyBackgroundAttachment, CSSPropertyBackgroundBlendMode, CSSPropertyBackgroundClip, CSSPropertyBackgroundColor, CSSPropertyBackgroundImage, CSSPropertyBackgroundOrigin, CSSPropertyBackgroundPosition, // more-specific background-position-x/y are non-standard CSSPropertyBackgroundRepeat, CSSPropertyBackgroundSize, CSSPropertyBorderBottomColor, CSSPropertyBorderBottomLeftRadius, CSSPropertyBorderBottomRightRadius, CSSPropertyBorderBottomStyle, CSSPropertyBorderBottomWidth, CSSPropertyBorderCollapse, CSSPropertyBorderImageOutset, CSSPropertyBorderImageRepeat, CSSPropertyBorderImageSlice, CSSPropertyBorderImageSource, CSSPropertyBorderImageWidth, CSSPropertyBorderLeftColor, CSSPropertyBorderLeftStyle, CSSPropertyBorderLeftWidth, CSSPropertyBorderRightColor, CSSPropertyBorderRightStyle, CSSPropertyBorderRightWidth, CSSPropertyBorderTopColor, CSSPropertyBorderTopLeftRadius, CSSPropertyBorderTopRightRadius, CSSPropertyBorderTopStyle, CSSPropertyBorderTopWidth, CSSPropertyBottom, CSSPropertyBoxShadow, CSSPropertyBoxSizing, CSSPropertyBreakAfter, CSSPropertyBreakBefore, CSSPropertyBreakInside, CSSPropertyCaptionSide, CSSPropertyClear, CSSPropertyClip, CSSPropertyColor, CSSPropertyContent, CSSPropertyCursor, CSSPropertyDirection, CSSPropertyDisplay, CSSPropertyEmptyCells, CSSPropertyFloat, CSSPropertyFontFamily, CSSPropertyFontKerning, CSSPropertyFontSize, CSSPropertyFontSizeAdjust, CSSPropertyFontStretch, CSSPropertyFontStyle, CSSPropertyFontVariant, CSSPropertyFontVariantLigatures, CSSPropertyFontVariantCaps, CSSPropertyFontVariantNumeric, CSSPropertyFontWeight, CSSPropertyHeight, CSSPropertyImageOrientation, CSSPropertyImageRendering, CSSPropertyIsolation, CSSPropertyJustifyItems, CSSPropertyJustifySelf, CSSPropertyLeft, CSSPropertyLetterSpacing, CSSPropertyLineHeight, CSSPropertyListStyleImage, CSSPropertyListStylePosition, CSSPropertyListStyleType, CSSPropertyMarginBottom, CSSPropertyMarginLeft, CSSPropertyMarginRight, CSSPropertyMarginTop, CSSPropertyMaxHeight, CSSPropertyMaxWidth, CSSPropertyMinHeight, CSSPropertyMinWidth, CSSPropertyMixBlendMode, CSSPropertyMotionOffset, CSSPropertyMotionPath, CSSPropertyMotionRotation, CSSPropertyObjectFit, CSSPropertyObjectPosition, CSSPropertyOpacity, CSSPropertyOrphans, CSSPropertyOutlineColor, CSSPropertyOutlineOffset, CSSPropertyOutlineStyle, CSSPropertyOutlineWidth, CSSPropertyOverflowWrap, CSSPropertyOverflowX, CSSPropertyOverflowY, CSSPropertyPaddingBottom, CSSPropertyPaddingLeft, CSSPropertyPaddingRight, CSSPropertyPaddingTop, CSSPropertyPointerEvents, CSSPropertyPosition, CSSPropertyResize, CSSPropertyRight, CSSPropertyScrollBehavior, CSSPropertySnapHeight, CSSPropertySpeak, CSSPropertyTableLayout, CSSPropertyTabSize, CSSPropertyTextAlign, CSSPropertyTextAlignLast, CSSPropertyTextDecoration, CSSPropertyTextDecorationLine, CSSPropertyTextDecorationStyle, CSSPropertyTextDecorationColor, CSSPropertyTextJustify, CSSPropertyTextUnderlinePosition, CSSPropertyTextIndent, CSSPropertyTextRendering, CSSPropertyTextShadow, CSSPropertyTextOverflow, CSSPropertyTextTransform, CSSPropertyTop, CSSPropertyTouchAction, CSSPropertyTransitionDelay, CSSPropertyTransitionDuration, CSSPropertyTransitionProperty, CSSPropertyTransitionTimingFunction, CSSPropertyUnicodeBidi, CSSPropertyVerticalAlign, CSSPropertyVisibility, CSSPropertyWhiteSpace, CSSPropertyWidows, CSSPropertyWidth, CSSPropertyWillChange, CSSPropertyWordBreak, CSSPropertyWordSpacing, CSSPropertyWordWrap, CSSPropertyZIndex, CSSPropertyZoom, CSSPropertyWebkitAppearance, CSSPropertyBackfaceVisibility, CSSPropertyWebkitBackgroundClip, CSSPropertyWebkitBackgroundOrigin, CSSPropertyWebkitBorderHorizontalSpacing, CSSPropertyWebkitBorderImage, CSSPropertyWebkitBorderVerticalSpacing, CSSPropertyWebkitBoxAlign, CSSPropertyWebkitBoxDecorationBreak, CSSPropertyWebkitBoxDirection, CSSPropertyWebkitBoxFlex, CSSPropertyWebkitBoxFlexGroup, CSSPropertyWebkitBoxLines, CSSPropertyWebkitBoxOrdinalGroup, CSSPropertyWebkitBoxOrient, CSSPropertyWebkitBoxPack, CSSPropertyWebkitBoxReflect, CSSPropertyWebkitClipPath, CSSPropertyColumnCount, CSSPropertyColumnGap, CSSPropertyColumnRuleColor, CSSPropertyColumnRuleStyle, CSSPropertyColumnRuleWidth, CSSPropertyColumnSpan, CSSPropertyColumnWidth, CSSPropertyWebkitFilter, CSSPropertyBackdropFilter, CSSPropertyAlignContent, CSSPropertyAlignItems, CSSPropertyAlignSelf, CSSPropertyFlexBasis, CSSPropertyFlexGrow, CSSPropertyFlexShrink, CSSPropertyFlexDirection, CSSPropertyFlexWrap, CSSPropertyJustifyContent, CSSPropertyWebkitFontSmoothing, CSSPropertyGridAutoColumns, CSSPropertyGridAutoFlow, CSSPropertyGridAutoRows, CSSPropertyGridColumnEnd, CSSPropertyGridColumnStart, CSSPropertyGridTemplateAreas, CSSPropertyGridTemplateColumns, CSSPropertyGridTemplateRows, CSSPropertyGridRowEnd, CSSPropertyGridRowStart, CSSPropertyGridColumnGap, CSSPropertyGridRowGap, CSSPropertyWebkitHighlight, CSSPropertyHyphens, CSSPropertyWebkitHyphenateCharacter, CSSPropertyWebkitLineBreak, CSSPropertyWebkitLineClamp, CSSPropertyWebkitLocale, CSSPropertyWebkitMarginBeforeCollapse, CSSPropertyWebkitMarginAfterCollapse, CSSPropertyWebkitMaskBoxImage, CSSPropertyWebkitMaskBoxImageOutset, CSSPropertyWebkitMaskBoxImageRepeat, CSSPropertyWebkitMaskBoxImageSlice, CSSPropertyWebkitMaskBoxImageSource, CSSPropertyWebkitMaskBoxImageWidth, CSSPropertyWebkitMaskClip, CSSPropertyWebkitMaskComposite, CSSPropertyWebkitMaskImage, CSSPropertyWebkitMaskOrigin, CSSPropertyWebkitMaskPosition, CSSPropertyWebkitMaskRepeat, CSSPropertyWebkitMaskSize, CSSPropertyOrder, CSSPropertyPerspective, CSSPropertyPerspectiveOrigin, CSSPropertyWebkitPrintColorAdjust, CSSPropertyWebkitRtlOrdering, CSSPropertyShapeOutside, CSSPropertyShapeImageThreshold, CSSPropertyShapeMargin, CSSPropertyWebkitTapHighlightColor, CSSPropertyWebkitTextCombine, CSSPropertyWebkitTextDecorationsInEffect, CSSPropertyWebkitTextEmphasisColor, CSSPropertyWebkitTextEmphasisPosition, CSSPropertyWebkitTextEmphasisStyle, CSSPropertyWebkitTextFillColor, CSSPropertyWebkitTextOrientation, CSSPropertyWebkitTextSecurity, CSSPropertyWebkitTextStrokeColor, CSSPropertyWebkitTextStrokeWidth, CSSPropertyTransform, CSSPropertyTransformOrigin, CSSPropertyTransformStyle, CSSPropertyWebkitUserDrag, CSSPropertyWebkitUserModify, CSSPropertyWebkitUserSelect, CSSPropertyWebkitWritingMode, CSSPropertyWebkitAppRegion, CSSPropertyBufferedRendering, CSSPropertyClipPath, CSSPropertyClipRule, CSSPropertyMask, CSSPropertyFilter, CSSPropertyFloodColor, CSSPropertyFloodOpacity, CSSPropertyLightingColor, CSSPropertyStopColor, CSSPropertyStopOpacity, CSSPropertyColorInterpolation, CSSPropertyColorInterpolationFilters, CSSPropertyColorRendering, CSSPropertyFill, CSSPropertyFillOpacity, CSSPropertyFillRule, CSSPropertyMarkerEnd, CSSPropertyMarkerMid, CSSPropertyMarkerStart, CSSPropertyMaskType, CSSPropertyMaskSourceType, CSSPropertyShapeRendering, CSSPropertyStroke, CSSPropertyStrokeDasharray, CSSPropertyStrokeDashoffset, CSSPropertyStrokeLinecap, CSSPropertyStrokeLinejoin, CSSPropertyStrokeMiterlimit, CSSPropertyStrokeOpacity, CSSPropertyStrokeWidth, CSSPropertyAlignmentBaseline, CSSPropertyBaselineShift, CSSPropertyDominantBaseline, CSSPropertyTextAnchor, CSSPropertyWritingMode, CSSPropertyVectorEffect, CSSPropertyPaintOrder, CSSPropertyD, CSSPropertyCx, CSSPropertyCy, CSSPropertyX, CSSPropertyY, CSSPropertyR, CSSPropertyRx, CSSPropertyRy, CSSPropertyScrollSnapType, CSSPropertyScrollSnapPointsX, CSSPropertyScrollSnapPointsY, CSSPropertyScrollSnapCoordinate, CSSPropertyScrollSnapDestination, CSSPropertyTranslate, CSSPropertyRotate, CSSPropertyScale, }; static const Vector<CSSPropertyID>& computableProperties() { DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ()); if (properties.isEmpty()) CSSPropertyMetadata::filterEnabledCSSPropertiesIntoVector(staticComputableProperties, WTF_ARRAY_LENGTH(staticComputableProperties), properties); return properties; } CSSComputedStyleDeclaration::CSSComputedStyleDeclaration(Node* n, bool allowVisitedStyle, const String& pseudoElementName) : m_node(n) , m_allowVisitedStyle(allowVisitedStyle) { unsigned nameWithoutColonsStart = pseudoElementName[0] == ':' ? (pseudoElementName[1] == ':' ? 2 : 1) : 0; m_pseudoElementSpecifier = CSSSelector::pseudoId(CSSSelector::parsePseudoType( AtomicString(pseudoElementName.substring(nameWithoutColonsStart)), false)); } CSSComputedStyleDeclaration::~CSSComputedStyleDeclaration() { } String CSSComputedStyleDeclaration::cssText() const { StringBuilder result; const Vector<CSSPropertyID>& properties = computableProperties(); for (unsigned i = 0; i < properties.size(); i++) { if (i) result.append(' '); result.append(getPropertyName(properties[i])); result.appendLiteral(": "); result.append(getPropertyValue(properties[i])); result.append(';'); } return result.toString(); } void CSSComputedStyleDeclaration::setCSSText(const String&, ExceptionState& exceptionState) { exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore read-only."); } static CSSValueID cssIdentifierForFontSizeKeyword(int keywordSize) { DCHECK_NE(keywordSize, 0); DCHECK_LE(keywordSize, 8); return static_cast<CSSValueID>(CSSValueXxSmall + keywordSize - 1); } inline static CSSPrimitiveValue* zoomAdjustedPixelValue(double value, const ComputedStyle& style) { return cssValuePool().createValue(adjustFloatForAbsoluteZoom(value, style), CSSPrimitiveValue::UnitType::Pixels); } CSSValue* CSSComputedStyleDeclaration::getFontSizeCSSValuePreferringKeyword() const { if (!m_node) return nullptr; m_node->document().updateStyleAndLayoutIgnorePendingStylesheets(); const ComputedStyle* style = m_node->ensureComputedStyle(m_pseudoElementSpecifier); if (!style) return nullptr; if (int keywordSize = style->getFontDescription().keywordSize()) return cssValuePool().createIdentifierValue(cssIdentifierForFontSizeKeyword(keywordSize)); return zoomAdjustedPixelValue(style->getFontDescription().computedPixelSize(), *style); } bool CSSComputedStyleDeclaration::isMonospaceFont() const { if (!m_node) return false; const ComputedStyle* style = m_node->ensureComputedStyle(m_pseudoElementSpecifier); if (!style) return false; return style->getFontDescription().isMonospace(); } static void logUnimplementedPropertyID(CSSPropertyID propertyID) { DEFINE_STATIC_LOCAL(HashSet<CSSPropertyID>, propertyIDSet, ()); if (!propertyIDSet.add(propertyID).isNewEntry) return; DLOG(ERROR) << "Blink does not yet implement getComputedStyle for '" << getPropertyName(propertyID) << "'."; } static bool isLayoutDependent(CSSPropertyID propertyID, const ComputedStyle* style, LayoutObject* layoutObject) { if (!layoutObject) return false; // Some properties only depend on layout in certain conditions which // are specified in the main switch statement below. So we can avoid // forcing layout in those conditions. The conditions in this switch // statement must remain in sync with the conditions in the main switch. // FIXME: Some of these cases could be narrowed down or optimized better. switch (propertyID) { case CSSPropertyBottom: case CSSPropertyHeight: case CSSPropertyLeft: case CSSPropertyRight: case CSSPropertyTop: case CSSPropertyPerspectiveOrigin: case CSSPropertyTransform: case CSSPropertyTranslate: case CSSPropertyTransformOrigin: case CSSPropertyWidth: return layoutObject->isBox(); case CSSPropertyMargin: return layoutObject->isBox() && (!style || !style->marginBottom().isFixed() || !style->marginTop().isFixed() || !style->marginLeft().isFixed() || !style->marginRight().isFixed()); case CSSPropertyMarginLeft: return layoutObject->isBox() && (!style || !style->marginLeft().isFixed()); case CSSPropertyMarginRight: return layoutObject->isBox() && (!style || !style->marginRight().isFixed()); case CSSPropertyMarginTop: return layoutObject->isBox() && (!style || !style->marginTop().isFixed()); case CSSPropertyMarginBottom: return layoutObject->isBox() && (!style || !style->marginBottom().isFixed()); case CSSPropertyPadding: return layoutObject->isBox() && (!style || !style->paddingBottom().isFixed() || !style->paddingTop().isFixed() || !style->paddingLeft().isFixed() || !style->paddingRight().isFixed()); case CSSPropertyPaddingBottom: return layoutObject->isBox() && (!style || !style->paddingBottom().isFixed()); case CSSPropertyPaddingLeft: return layoutObject->isBox() && (!style || !style->paddingLeft().isFixed()); case CSSPropertyPaddingRight: return layoutObject->isBox() && (!style || !style->paddingRight().isFixed()); case CSSPropertyPaddingTop: return layoutObject->isBox() && (!style || !style->paddingTop().isFixed()); case CSSPropertyGridTemplateColumns: case CSSPropertyGridTemplateRows: case CSSPropertyGridTemplate: case CSSPropertyGrid: return layoutObject->isLayoutGrid(); default: return false; } } const ComputedStyle* CSSComputedStyleDeclaration::computeComputedStyle() const { Node* styledNode = this->styledNode(); ASSERT(styledNode); return styledNode->ensureComputedStyle(styledNode->isPseudoElement() ? PseudoIdNone : m_pseudoElementSpecifier); } Node* CSSComputedStyleDeclaration::styledNode() const { if (!m_node) return nullptr; if (m_node->isElementNode()) { if (PseudoElement* element = toElement(m_node)->pseudoElement(m_pseudoElementSpecifier)) return element; } return m_node.get(); } CSSValue* CSSComputedStyleDeclaration::getPropertyCSSValue(AtomicString customPropertyName) const { Node* styledNode = this->styledNode(); if (!styledNode) return nullptr; styledNode->document().updateStyleAndLayoutTreeForNode(styledNode); const ComputedStyle* style = computeComputedStyle(); if (!style) return nullptr; return ComputedStyleCSSValueMapping::get(customPropertyName, *style); } std::unique_ptr<HashMap<AtomicString, RefPtr<CSSVariableData>>> CSSComputedStyleDeclaration::getVariables() const { const ComputedStyle* style = computeComputedStyle(); if (!style) return nullptr; return ComputedStyleCSSValueMapping::getVariables(*style); } CSSValue* CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropertyID propertyID) const { Node* styledNode = this->styledNode(); if (!styledNode) return nullptr; Document& document = styledNode->document(); document.updateStyleAndLayoutTreeForNode(styledNode); // The style recalc could have caused the styled node to be discarded or replaced // if it was a PseudoElement so we need to update it. styledNode = this->styledNode(); LayoutObject* layoutObject = styledNode->layoutObject(); const ComputedStyle* style = computeComputedStyle(); bool forceFullLayout = isLayoutDependent(propertyID, style, layoutObject) || styledNode->isInShadowTree() || (document.localOwner() && document.ensureStyleResolver().hasViewportDependentMediaQueries()); if (forceFullLayout) { document.updateStyleAndLayoutIgnorePendingStylesheetsForNode(styledNode); styledNode = this->styledNode(); style = computeComputedStyle(); layoutObject = styledNode->layoutObject(); } if (!style) return nullptr; CSSValue* value = ComputedStyleCSSValueMapping::get(propertyID, *style, layoutObject, styledNode, m_allowVisitedStyle); if (value) return value; logUnimplementedPropertyID(propertyID); return nullptr; } String CSSComputedStyleDeclaration::getPropertyValue(CSSPropertyID propertyID) const { CSSValue* value = getPropertyCSSValue(propertyID); if (value) return value->cssText(); return ""; } unsigned CSSComputedStyleDeclaration::length() const { if (!m_node || !m_node->inActiveDocument()) return 0; return computableProperties().size(); } String CSSComputedStyleDeclaration::item(unsigned i) const { if (i >= length()) return ""; return getPropertyNameString(computableProperties()[i]); } bool CSSComputedStyleDeclaration::cssPropertyMatches(CSSPropertyID propertyID, const CSSValue* propertyValue) const { if (propertyID == CSSPropertyFontSize && propertyValue->isPrimitiveValue() && m_node) { m_node->document().updateStyleAndLayoutIgnorePendingStylesheets(); const ComputedStyle* style = m_node->ensureComputedStyle(m_pseudoElementSpecifier); if (style && style->getFontDescription().keywordSize()) { CSSValueID sizeValue = cssIdentifierForFontSizeKeyword(style->getFontDescription().keywordSize()); const CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(propertyValue); if (primitiveValue->isValueID() && primitiveValue->getValueID() == sizeValue) return true; } } CSSValue* value = getPropertyCSSValue(propertyID); return value && propertyValue && value->equals(*propertyValue); } MutableStylePropertySet* CSSComputedStyleDeclaration::copyProperties() const { return copyPropertiesInSet(computableProperties()); } MutableStylePropertySet* CSSComputedStyleDeclaration::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const { HeapVector<CSSProperty, 256> list; list.reserveInitialCapacity(properties.size()); for (unsigned i = 0; i < properties.size(); ++i) { CSSValue* value = getPropertyCSSValue(properties[i]); if (value) list.append(CSSProperty(properties[i], value, false)); } return MutableStylePropertySet::create(list.data(), list.size()); } CSSRule* CSSComputedStyleDeclaration::parentRule() const { return nullptr; } String CSSComputedStyleDeclaration::getPropertyValue(const String& propertyName) { CSSPropertyID propertyID = cssPropertyID(propertyName); if (!propertyID) { if (RuntimeEnabledFeatures::cssVariablesEnabled() && CSSVariableParser::isValidVariableName(propertyName)) { CSSValue* value = getPropertyCSSValue(AtomicString(propertyName)); if (value) return value->cssText(); } return String(); } ASSERT(CSSPropertyMetadata::isEnabledProperty(propertyID)); return getPropertyValue(propertyID); } String CSSComputedStyleDeclaration::getPropertyPriority(const String&) { // All computed styles have a priority of not "important". return ""; } String CSSComputedStyleDeclaration::getPropertyShorthand(const String&) { return ""; } bool CSSComputedStyleDeclaration::isPropertyImplicit(const String&) { return false; } void CSSComputedStyleDeclaration::setProperty(const String& name, const String&, const String&, ExceptionState& exceptionState) { exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + name + "' property is read-only."); } String CSSComputedStyleDeclaration::removeProperty(const String& name, ExceptionState& exceptionState) { exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + name + "' property is read-only."); return String(); } CSSValue* CSSComputedStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID) { return getPropertyCSSValue(propertyID); } String CSSComputedStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID) { return getPropertyValue(propertyID); } void CSSComputedStyleDeclaration::setPropertyInternal(CSSPropertyID id, const String&, const String&, bool, ExceptionState& exceptionState) { // TODO(leviw): This code is currently unreachable, but shouldn't be. exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + getPropertyNameString(id) + "' property is read-only."); } DEFINE_TRACE(CSSComputedStyleDeclaration) { visitor->trace(m_node); CSSStyleDeclaration::trace(visitor); } } // namespace blink
jtravee/neuvector
vendor/modernc.org/sqlite/lib/mutex.go
<gh_stars>100-1000 // Copyright 2021 The Sqlite Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sqlite3 import ( "fmt" "sync" "sync/atomic" "unsafe" "modernc.org/libc" "modernc.org/libc/sys/types" ) func init() { tls := libc.NewTLS() if Xsqlite3_threadsafe(tls) == 0 { panic(fmt.Errorf("sqlite: thread safety configuration error")) } varArgs := libc.Xmalloc(tls, types.Size_t(unsafe.Sizeof(uintptr(0)))) if varArgs == 0 { panic(fmt.Errorf("cannot allocate memory")) } // int sqlite3_config(int, ...); if rc := Xsqlite3_config(tls, SQLITE_CONFIG_MUTEX, libc.VaList(varArgs, uintptr(unsafe.Pointer(&mutexMethods)))); rc != SQLITE_OK { p := Xsqlite3_errstr(tls, rc) str := libc.GoString(p) panic(fmt.Errorf("sqlite: failed to configure mutex methods: %v", str)) } libc.Xfree(tls, varArgs) tls.Close() } var ( mutexMethods = Sqlite3_mutex_methods{ FxMutexInit: *(*uintptr)(unsafe.Pointer(&struct{ f func(*libc.TLS) int32 }{mutexInit})), FxMutexEnd: *(*uintptr)(unsafe.Pointer(&struct{ f func(*libc.TLS) int32 }{mutexEnd})), FxMutexAlloc: *(*uintptr)(unsafe.Pointer(&struct { f func(*libc.TLS, int32) uintptr }{mutexAlloc})), FxMutexFree: *(*uintptr)(unsafe.Pointer(&struct{ f func(*libc.TLS, uintptr) }{mutexFree})), FxMutexEnter: *(*uintptr)(unsafe.Pointer(&struct{ f func(*libc.TLS, uintptr) }{mutexEnter})), FxMutexTry: *(*uintptr)(unsafe.Pointer(&struct { f func(*libc.TLS, uintptr) int32 }{mutexTry})), FxMutexLeave: *(*uintptr)(unsafe.Pointer(&struct{ f func(*libc.TLS, uintptr) }{mutexLeave})), FxMutexHeld: *(*uintptr)(unsafe.Pointer(&struct { f func(*libc.TLS, uintptr) int32 }{mutexHeld})), FxMutexNotheld: *(*uintptr)(unsafe.Pointer(&struct { f func(*libc.TLS, uintptr) int32 }{mutexNotheld})), } mutexApp1 mutex mutexApp2 mutex mutexApp3 mutex mutexLRU mutex mutexMaster mutex mutexMem mutex mutexOpen mutex mutexPMem mutex mutexPRNG mutex mutexVFS1 mutex mutexVFS2 mutex mutexVFS3 mutex ) type mutex struct { cnt int32 id int32 sync.Mutex wait sync.Mutex recursive bool } func (m *mutex) enter(id int32) { if !m.recursive { m.Lock() m.id = id return } for { m.Lock() switch m.id { case 0: m.cnt = 1 m.id = id m.wait.Lock() m.Unlock() return case id: m.cnt++ m.Unlock() return } m.Unlock() m.wait.Lock() //lint:ignore SA2001 TODO report staticcheck issue m.wait.Unlock() } } func (m *mutex) try(id int32) int32 { if !m.recursive { return SQLITE_BUSY } m.Lock() switch m.id { case 0: m.cnt = 1 m.id = id m.wait.Lock() m.Unlock() return SQLITE_OK case id: m.cnt++ m.Unlock() return SQLITE_OK } m.Unlock() return SQLITE_BUSY } func (m *mutex) leave(id int32) { if !m.recursive { m.id = 0 m.Unlock() return } m.Lock() m.cnt-- if m.cnt == 0 { m.id = 0 m.wait.Unlock() } m.Unlock() } // int (*xMutexInit)(void); // // The xMutexInit method defined by this structure is invoked as part of system // initialization by the sqlite3_initialize() function. The xMutexInit routine // is called by SQLite exactly once for each effective call to // sqlite3_initialize(). // // The xMutexInit() method must be threadsafe. It must be harmless to invoke // xMutexInit() multiple times within the same process and without intervening // calls to xMutexEnd(). Second and subsequent calls to xMutexInit() must be // no-ops. xMutexInit() must not use SQLite memory allocation (sqlite3_malloc() // and its associates). // // If xMutexInit fails in any way, it is expected to clean up after itself // prior to returning. func mutexInit(tls *libc.TLS) int32 { return SQLITE_OK } // int (*xMutexEnd)(void); func mutexEnd(tls *libc.TLS) int32 { return SQLITE_OK } // sqlite3_mutex *(*xMutexAlloc)(int); // // The sqlite3_mutex_alloc() routine allocates a new mutex and returns a // pointer to it. The sqlite3_mutex_alloc() routine returns NULL if it is // unable to allocate the requested mutex. The argument to // sqlite3_mutex_alloc() must one of these integer constants: // // SQLITE_MUTEX_FAST // SQLITE_MUTEX_RECURSIVE // SQLITE_MUTEX_STATIC_MASTER // SQLITE_MUTEX_STATIC_MEM // SQLITE_MUTEX_STATIC_OPEN // SQLITE_MUTEX_STATIC_PRNG // SQLITE_MUTEX_STATIC_LRU // SQLITE_MUTEX_STATIC_PMEM // SQLITE_MUTEX_STATIC_APP1 // SQLITE_MUTEX_STATIC_APP2 // SQLITE_MUTEX_STATIC_APP3 // SQLITE_MUTEX_STATIC_VFS1 // SQLITE_MUTEX_STATIC_VFS2 // SQLITE_MUTEX_STATIC_VFS3 // // The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) cause // sqlite3_mutex_alloc() to create a new mutex. The new mutex is recursive when // SQLITE_MUTEX_RECURSIVE is used but not necessarily so when SQLITE_MUTEX_FAST // is used. The mutex implementation does not need to make a distinction // between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does not want to. // SQLite will only request a recursive mutex in cases where it really needs // one. If a faster non-recursive mutex implementation is available on the host // platform, the mutex subsystem might return such a mutex in response to // SQLITE_MUTEX_FAST. // // The other allowed parameters to sqlite3_mutex_alloc() (anything other than // SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return a pointer to a // static preexisting mutex. Nine static mutexes are used by the current // version of SQLite. Future versions of SQLite may add additional static // mutexes. Static mutexes are for internal use by SQLite only. Applications // that use SQLite mutexes should use only the dynamic mutexes returned by // SQLITE_MUTEX_FAST or SQLITE_MUTEX_RECURSIVE. // // Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST or // SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() returns a // different mutex on every call. For the static mutex types, the same mutex is // returned on every call that has the same type number. func mutexAlloc(tls *libc.TLS, typ int32) uintptr { defer func() { }() switch typ { case SQLITE_MUTEX_FAST: return libc.Xcalloc(tls, 1, types.Size_t(unsafe.Sizeof(mutex{}))) case SQLITE_MUTEX_RECURSIVE: p := libc.Xcalloc(tls, 1, types.Size_t(unsafe.Sizeof(mutex{}))) (*mutex)(unsafe.Pointer(p)).recursive = true return p case SQLITE_MUTEX_STATIC_MASTER: return uintptr(unsafe.Pointer(&mutexMaster)) case SQLITE_MUTEX_STATIC_MEM: return uintptr(unsafe.Pointer(&mutexMem)) case SQLITE_MUTEX_STATIC_OPEN: return uintptr(unsafe.Pointer(&mutexOpen)) case SQLITE_MUTEX_STATIC_PRNG: return uintptr(unsafe.Pointer(&mutexPRNG)) case SQLITE_MUTEX_STATIC_LRU: return uintptr(unsafe.Pointer(&mutexLRU)) case SQLITE_MUTEX_STATIC_PMEM: return uintptr(unsafe.Pointer(&mutexPMem)) case SQLITE_MUTEX_STATIC_APP1: return uintptr(unsafe.Pointer(&mutexApp1)) case SQLITE_MUTEX_STATIC_APP2: return uintptr(unsafe.Pointer(&mutexApp2)) case SQLITE_MUTEX_STATIC_APP3: return uintptr(unsafe.Pointer(&mutexApp3)) case SQLITE_MUTEX_STATIC_VFS1: return uintptr(unsafe.Pointer(&mutexVFS1)) case SQLITE_MUTEX_STATIC_VFS2: return uintptr(unsafe.Pointer(&mutexVFS2)) case SQLITE_MUTEX_STATIC_VFS3: return uintptr(unsafe.Pointer(&mutexVFS3)) default: return 0 } } // void (*xMutexFree)(sqlite3_mutex *); func mutexFree(tls *libc.TLS, m uintptr) { libc.Xfree(tls, m) } // The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt to enter // a mutex. If another thread is already within the mutex, // sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return // SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK upon // successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can be // entered multiple times by the same thread. In such cases, the mutex must be // exited an equal number of times before another thread can enter. If the same // thread tries to enter any mutex other than an SQLITE_MUTEX_RECURSIVE more // than once, the behavior is undefined. // // If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or // sqlite3_mutex_leave() is a NULL pointer, then all three routines behave as // no-ops. // void (*xMutexEnter)(sqlite3_mutex *); func mutexEnter(tls *libc.TLS, m uintptr) { if m == 0 { return } (*mutex)(unsafe.Pointer(m)).enter(tls.ID) } // int (*xMutexTry)(sqlite3_mutex *); func mutexTry(tls *libc.TLS, m uintptr) int32 { if m == 0 { return SQLITE_OK } return (*mutex)(unsafe.Pointer(m)).try(tls.ID) } // void (*xMutexLeave)(sqlite3_mutex *); func mutexLeave(tls *libc.TLS, m uintptr) { if m == 0 { return } (*mutex)(unsafe.Pointer(m)).leave(tls.ID) } // The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines are intended // for use inside assert() statements. The SQLite core never uses these // routines except inside an assert() and applications are advised to follow // the lead of the core. The SQLite core only provides implementations for // these routines when it is compiled with the SQLITE_DEBUG flag. External // mutex implementations are only required to provide these routines if // SQLITE_DEBUG is defined and if NDEBUG is not defined. // // These routines should return true if the mutex in their argument is held or // not held, respectively, by the calling thread. // // The implementation is not required to provide versions of these routines // that actually work. If the implementation does not provide working versions // of these routines, it should at least provide stubs that always return true // so that one does not get spurious assertion failures. // // If the argument to sqlite3_mutex_held() is a NULL pointer then the routine // should return 1. This seems counter-intuitive since clearly the mutex cannot // be held if it does not exist. But the reason the mutex does not exist is // because the build is not using mutexes. And we do not want the assert() // containing the call to sqlite3_mutex_held() to fail, so a non-zero return is // the appropriate thing to do. The sqlite3_mutex_notheld() interface should // also return 1 when given a NULL pointer. // int (*xMutexHeld)(sqlite3_mutex *); func mutexHeld(tls *libc.TLS, m uintptr) int32 { if m == 0 { return 1 } return libc.Bool32(atomic.LoadInt32(&(*mutex)(unsafe.Pointer(m)).id) == tls.ID) } // int (*xMutexNotheld)(sqlite3_mutex *); func mutexNotheld(tls *libc.TLS, m uintptr) int32 { if m == 0 { return 1 } return libc.Bool32(atomic.LoadInt32(&(*mutex)(unsafe.Pointer(m)).id) != tls.ID) }
thanhtrang0493/on-demand-youtube-player
app/src/main/java/com/vcoders/on_demand_youtube_player/features/home/HomeView.java
<filename>app/src/main/java/com/vcoders/on_demand_youtube_player/features/home/HomeView.java package com.vcoders.on_demand_youtube_player.features.home; import com.vcoders.on_demand_youtube_player.architecture.BaseView; import com.vcoders.on_demand_youtube_player.database.DatabaseResponseListener; public interface HomeView extends BaseView { }
suisen-cp/cp-library-cpp
test/src/tree/rerooting/abc160_f.test.cpp
#define PROBLEM "https://atcoder.jp/contests/abc160/tasks/abc160_f" #include <iostream> #include <atcoder/modint> using mint = atcoder::modint1000000007; #include "library/tree/rerooting.hpp" using suisen::ReRooting; int n; std::vector<int> sub; std::vector<int> par; mint op(mint x, mint y) { return x * y; } mint e() { return 1; } mint add_subtree_root(mint val, int u, int p) { return val / (p == par[u] ? sub[u] : n - (p < 0 ? 0 : sub[p])); } mint trans_to_par(mint val, int, int, int) { return val; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cin >> n; ReRooting<mint, op, e, add_subtree_root, int, trans_to_par> g(n); for (int i = 0; i < n - 1; ++i) { int u, v; std::cin >> u >> v; --u, --v; g.add_edge(u, v, 0); } sub.resize(n, 1); par.resize(n, -1); auto dfs = [&](auto dfs, int u, int p) -> void { par[u] = p; for (auto [v, w] : g[u]) { if (v == p) continue; dfs(dfs, v, u); sub[u] += sub[v]; } }; dfs(dfs, 0, -1); mint fac = 1; for (int i = 1; i <= n; ++i) { fac *= i; } for (mint e : g.rerooting()) { std::cout << (e * fac).val() << '\n'; } return 0; }
poecao/RLibrary
imagepicker/src/main/java/com/lzy/imagepicker/YImageControl.java
package com.lzy.imagepicker; import android.text.TextUtils; import android.widget.ImageView; /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:图片涉黄控制 * 创建人员:Robi * 创建时间:2017/05/24 15:27 * 修改人员:Robi * 修改时间:2017/05/24 15:27 * 修改备注: * Version: 1.0.0 */ public class YImageControl { /** * 判断图片是否涉黄 */ public static boolean isYellowImage(String url) { if (TextUtils.isEmpty(url)) { return false; } if (url.contains("|porn")) { return true; } return false; } /** * 返回正确的url */ public static String url(String url) { if (!TextUtils.isEmpty(url)) { return url.replaceAll("\\|porn", ""); } return url; } public static void showYellowImageXiao(ImageView imageView) { if (imageView == null) { return; } imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.drawable.jinhuang_xiao); } }
ZipFile/pytest-alembic
src/pytest_alembic/plugin/plugin.py
import re from dataclasses import dataclass from typing import Callable, Dict, List, Optional import pytest from _pytest import fixtures from pytest_alembic.plugin.error import AlembicReprError, AlembicTestFailure @dataclass(frozen=True) class PytestAlembicTest: raw_name: str function: Callable is_experimental: bool @property def name(self): # Chop off the "test_" prefix. return self.raw_name[5:] @dataclass class _TestCollector: available_tests: Dict[str, PytestAlembicTest] included_tests: Optional[List[str]] = None included_experimental_tests: Optional[List[str]] = None excluded_tests: Optional[List[str]] = None @classmethod def collect(cls, default=True, experimental=True): import pytest_alembic.tests import pytest_alembic.tests.experimental test_groups = [(pytest_alembic.tests, False)] if experimental: test_groups.append((pytest_alembic.tests.experimental, True)) all_tests = {} for test_group, is_experimental in test_groups: for name in dir(test_group): if name.startswith("test_"): pytest_alembic_test = PytestAlembicTest( name, getattr(test_group, name), is_experimental ) all_tests[pytest_alembic_test.name] = pytest_alembic_test return cls(all_tests) def include(self, *tests): if tests: if self.included_tests is None: self.included_tests = [] self.included_tests.extend(tests) return self def include_experimental(self, *tests): if tests: if self.included_experimental_tests is None: self.included_experimental_tests = [] self.included_experimental_tests.extend(tests) return self def exclude(self, *tests): if tests: if self.excluded_tests is None: self.excluded_tests = [] self.excluded_tests.extend(tests) return self def sorted_tests(self): return sorted(self.tests(), key=lambda t: t.raw_name) def tests(self): selected_tests = [] invalid_tests = [] excluded_set = set(self.excluded_tests or []) for excluded_test in excluded_set: if excluded_test not in self.available_tests: invalid_tests.append(excluded_test) if self.included_tests is None: included_tests = [ t.name for t in self.available_tests.values() if t.is_experimental is False ] else: included_tests = self.included_tests for test_group in [included_tests, self.included_experimental_tests or []]: for included_test in test_group: if included_test in excluded_set: continue if included_test not in self.available_tests: invalid_tests.append(included_test) continue selected_tests.append(included_test) if invalid_tests: invalid_str = ", ".join(sorted(invalid_tests)) raise ValueError(f"The following tests were unrecognized: {invalid_str}") return [self.available_tests[t] for t in selected_tests] def parse_test_names(raw_test_names): test_names = re.split(r"[,\n]", raw_test_names) result = set() for test_name in test_names: test_name = test_name.strip() if not test_name: continue result.add(test_name) return result def collect_tests(session, config): cli_enabled = config.option.pytest_alembic_enabled if not cli_enabled: return [] option = config.option raw_included_tests = parse_test_names(config.getini("pytest_alembic_include")) raw_experimental_included_tests = parse_test_names( config.getini("pytest_alembic_include_experimental") ) raw_excluded_tests = parse_test_names( option.pytest_alembic_exclude or config.getini("pytest_alembic_exclude") ) # The tests folder field is important because we cannot predict the test location # of user tests. And so if someone invokes pytest like `pytest mytests/`, the user # would need to attach **these** tests to the `mytests/` namespace, or else run # `pytest mytests tests`. tests_folder = config.getini("pytest_alembic_tests_folder") test_collector = ( _TestCollector.collect(default=True, experimental=True) .include(*raw_included_tests) .include_experimental(*raw_experimental_included_tests) .exclude(*raw_excluded_tests) ) result = [] for test in test_collector.sorted_tests(): result.append( PytestAlembicItem.from_parent( session, name=f"{tests_folder}::pytest_alembic::{test.raw_name}", test_fn=test.function, ) ) return result class PytestAlembicItem(pytest.Item): """Pytest representation of each built-in test. Tests such as these are more complex because they are not represented in the users' source, which means we need to act as pytest does when producing tests normally. In particular, fixture resolution is the main complicating factor, and seemingly not an external detail for which pytest has an officially recommended public API. """ obj = None @classmethod def from_parent(cls, parent, *, name, test_fn): kwargs = dict(name=name, parent=parent, nodeid=name) if hasattr(super(), "from_parent"): self = super().from_parent(**kwargs) else: self = cls(**kwargs) self.test_fn = test_fn self.funcargs = {} self.add_marker("alembic") return self def runtest(self): fm = self.session._fixturemanager self._fixtureinfo = fm.getfixtureinfo(node=self, func=self.test_fn, cls=None) try: # Pytest deprecated direct construction of this, but there doesn't appear to # be an obvious non-deprecated way to produce `pytest.Item`s (i.e. tests) # which fullfill fixtures depended on by this plugin. fixture_request = fixtures.FixtureRequest(self, _ispytest=True) except TypeError: # For backwards compatibility, attempt to make the `fixture_request` in the interface # shape pre pytest's addition of this warning-producing parameter. fixture_request = fixtures.FixtureRequest(self) except Exception: # Just to avoid a NameError in an unforeseen error constructing the `fixture_request`. raise NotImplementedError( "Failed to fill the fixtures. " "This is almost certainly a pytest version incompatibility, please submit a bug report!" ) fixture_request._fillfixtures() params = {arg: self.funcargs[arg] for arg in self._fixtureinfo.argnames} self.test_fn(**params) def reportinfo(self): return (self.fspath, 0, f"[pytest-alembic] {self.name}") def repr_failure(self, excinfo): if isinstance(excinfo.value, AlembicTestFailure): return AlembicReprError(excinfo, self) return super().repr_failure(excinfo)
relaton/relaton-bib-py
tests/test_medium.py
<gh_stars>0 import dataclasses import inspect import pytest import xml.etree.ElementTree as ET from relaton_bib import Medium @pytest.fixture def subject(): return Medium(form="form", size="size", scale="scale") @pytest.fixture def subject_none(): return Medium() def test_to_xml(subject): host = ET.Element("host") result = subject.to_xml(host) assert host.find("./medium/form").text == "form" assert host.find("./medium/size").text == "size" assert result.find("./scale").text == "scale" def test_to_xml_with_no_props(subject_none): host = ET.Element("host") result = subject_none.to_xml(host) assert result is not None assert host.find("./medium") is not None def test_to_asciibib(subject): result = subject.to_asciibib() assert result == inspect.cleandoc("""medium.form:: form medium.size:: size medium.scale:: scale""") def test_to_asciibib_with_pref(subject): result = subject.to_asciibib("p") assert result == inspect.cleandoc("""p.medium.form:: form p.medium.size:: size p.medium.scale:: scale""") def test_hash(subject): result = dataclasses.asdict(subject) assert result["form"] == "form" assert result["size"] == "size" assert result["scale"] == "scale"
zeterain/phaser
examples/geometry/rotate point.js
<reponame>zeterain/phaser<filename>examples/geometry/rotate point.js var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', {create: create, update: update, render: render }); var p1; var p2; var d = 0; function create() { p1 = new Phaser.Point(200, 300); p2 = new Phaser.Point(300, 300); } function update() { p1.rotate(p2.x, p2.y, game.math.wrapAngle(d), true); d++; } function render() { game.context.fillStyle = 'rgb(255,255,0)'; game.context.fillRect(p1.x, p1.y, 4, 4); game.context.fillStyle = 'rgb(255,0,0)'; game.context.fillRect(p2.x, p2.y, 4, 4); }
Ankitkurani1997/maya
vendor/github.com/hashicorp/nomad/testutil/vault.go
package testutil import ( "fmt" "os" "os/exec" "testing" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/nomad/nomad/structs/config" vapi "github.com/hashicorp/vault/api" ) // TestVault is a test helper. It uses a fork/exec model to create a test Vault // server instance in the background and can be initialized with policies, roles // and backends mounted. The test Vault instances can be used to run a unit test // and offers and easy API to tear itself down on test end. The only // prerequisite is that the Vault binary is on the $PATH. const ( // vaultStartPort is the starting port we use to bind Vault servers to vaultStartPort uint64 = 40000 ) // vaultPortOffset is used to atomically increment the port numbers. var vaultPortOffset uint64 // TestVault wraps a test Vault server launched in dev mode, suitable for // testing. type TestVault struct { cmd *exec.Cmd t *testing.T Addr string HTTPAddr string RootToken string Config *config.VaultConfig Client *vapi.Client } // NewTestVault returns a new TestVault instance that has yet to be started func NewTestVault(t *testing.T) *TestVault { port := getPort() token := structs.GenerateUUID() bind := fmt.Sprintf("-dev-listen-address=127.0.0.1:%d", port) http := fmt.Sprintf("http://127.0.0.1:%d", port) root := fmt.Sprintf("-dev-root-token-id=%s", token) cmd := exec.Command("vault", "server", "-dev", bind, root) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr // Build the config conf := vapi.DefaultConfig() conf.Address = http // Make the client and set the token to the root token client, err := vapi.NewClient(conf) if err != nil { t.Fatalf("failed to build Vault API client: %v", err) } client.SetToken(token) enable := true tv := &TestVault{ cmd: cmd, t: t, Addr: bind, HTTPAddr: http, RootToken: token, Client: client, Config: &config.VaultConfig{ Enabled: &enable, Token: token, Addr: http, }, } return tv } // Start starts the test Vault server and waits for it to respond to its HTTP // API func (tv *TestVault) Start() *TestVault { if err := tv.cmd.Start(); err != nil { tv.t.Fatalf("failed to start vault: %v", err) } tv.waitForAPI() return tv } // Stop stops the test Vault server func (tv *TestVault) Stop() { if tv.cmd.Process == nil { return } if err := tv.cmd.Process.Kill(); err != nil { tv.t.Errorf("err: %s", err) } tv.cmd.Wait() } // waitForAPI waits for the Vault HTTP endpoint to start // responding. This is an indication that the agent has started. func (tv *TestVault) waitForAPI() { WaitForResult(func() (bool, error) { inited, err := tv.Client.Sys().InitStatus() if err != nil { return false, err } return inited, nil }, func(err error) { defer tv.Stop() tv.t.Fatalf("err: %s", err) }) } // getPort returns the next available port to bind Vault against func getPort() uint64 { p := vaultStartPort + vaultPortOffset vaultPortOffset += 1 return p } // VaultVersion returns the Vault version as a string or an error if it couldn't // be determined func VaultVersion() (string, error) { cmd := exec.Command("vault", "version") out, err := cmd.Output() return string(out), err }
rerorero/meshtest
src/model/service_test.go
package model import ( "testing" "github.com/stretchr/testify/assert" ) func TestServiceValidate(t *testing.T) { depends := []DependentService{ DependentService{ Name: "valid1", EgressPort: 9001, }, DependentService{ Name: "valid2", EgressPort: 9002, }, } s := Service{ Name: "service", HostNames: []string{"valid"}, Protocol: ProtocolHTTP, DependentServices: depends, } s.Name = "valid-01_32" assert.NoError(t, s.Validate()) // invalid service name s.Name = "ivalid.aaa" assert.Error(t, s.Validate()) // invalid host names s.Name = "valid" s.HostNames = append(s.HostNames, "in.valid") assert.Error(t, s.Validate()) // invalid protocol s.HostNames = []string{"valid"} s.Protocol = "invalid" assert.Error(t, s.Validate()) // duplicated service names s.Protocol = ProtocolHTTP err := s.AppendDependent(DependentService{Name: "valid1", EgressPort: 9003}) assert.Error(t, err) s.DependentServices = append(depends, DependentService{Name: "valid1", EgressPort: 9003}) assert.Error(t, s.Validate()) // duplicated service port s.DependentServices = depends err = s.AppendDependent(DependentService{Name: "valid3", EgressPort: 9001}) assert.Error(t, err) s.DependentServices = append(depends, DependentService{Name: "valid3", EgressPort: 9001}) assert.Error(t, s.Validate()) // invalid egress port s.DependentServices = depends err = s.AppendDependent(DependentService{Name: "valid3"}) assert.Error(t, err) s.DependentServices = append(depends, DependentService{Name: "valid3"}) assert.Error(t, s.Validate()) // can append s.DependentServices = depends err = s.AppendDependent(DependentService{Name: "valid3", EgressPort: 9003}) assert.NoError(t, err) assert.Equal(t, len(depends)+1, len(s.DependentServices)) // can remove ok := s.RemoveDependent("valid3") assert.NoError(t, err) assert.True(t, ok) assert.Equal(t, len(depends), len(s.DependentServices)) } func TestEqualsSserviceDependencies(t *testing.T) { a := []DependentService{ DependentService{ Name: "abc", EgressPort: 9002, }, DependentService{ Name: "ab", EgressPort: 9001, }, DependentService{ Name: "abcd", EgressPort: 9003, }, } sameA := []DependentService{ DependentService{ Name: "abcd", EgressPort: 9003, }, DependentService{ Name: "ab", EgressPort: 9001, }, DependentService{ Name: "abc", EgressPort: 9002, }, } b := []DependentService{ DependentService{ Name: "abcd", EgressPort: 9003, }, DependentService{ Name: "abc", EgressPort: 9002, }, } c := []DependentService{ DependentService{ Name: "abcd", EgressPort: 9003, }, DependentService{ Name: "abc", EgressPort: 9001, }, DependentService{ Name: "ab", EgressPort: 9002, }, } assert.True(t, EqualsServiceDependencies(a, sameA)) assert.False(t, EqualsServiceDependencies(a, b)) assert.False(t, EqualsServiceDependencies(a, c)) }
QualityInformationFramework/QIFResourcesEditor
src/qif191/QIFDocument/type_t.COppositePlanesTransformType.h
<reponame>QualityInformationFramework/QIFResourcesEditor<filename>src/qif191/QIFDocument/type_t.COppositePlanesTransformType.h #pragma once #include "type_t.CConstructionMethodBaseType.h" namespace qif191 { namespace t { class COppositePlanesTransformType : public ::qif191::t::CConstructionMethodBaseType { public: QIF191_EXPORT COppositePlanesTransformType(xercesc::DOMNode* const& init); QIF191_EXPORT COppositePlanesTransformType(COppositePlanesTransformType const& init); void operator=(COppositePlanesTransformType const& other) { m_node = other.m_node; } static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_t_altova_COppositePlanesTransformType); } MemberElement<t::CBaseFeatureType, _altova_mi_t_altova_COppositePlanesTransformType_altova_BaseOppositePlanes> BaseOppositePlanes; struct BaseOppositePlanes { typedef Iterator<t::CBaseFeatureType> iterator; }; MemberElement<t::CTransformationReferenceType, _altova_mi_t_altova_COppositePlanesTransformType_altova_Transformation> Transformation; struct Transformation { typedef Iterator<t::CTransformationReferenceType> iterator; }; QIF191_EXPORT void SetXsiType(); }; } // namespace t } // namespace qif191 //#endif // _ALTOVA_INCLUDED_QIFDocument_ALTOVA_t_ALTOVA_COppositePlanesTransformType
harveywangdao/ants
app/goods/model/goods_model.go
package model import ( "github.com/harveywangdao/ants/logger" "github.com/jinzhu/gorm" "time" ) type GoogsModel struct { ID int64 `gorm:"column:id"` GoodsID string `gorm:"column:goods_id"` SellerID string `gorm:"column:seller_id"` GoodsName string `gorm:"column:goods_name"` Price float64 `gorm:"column:price"` Category uint32 `gorm:"column:category"` Stock int32 `gorm:"column:stock"` Brand string `gorm:"column:brand"` Remark string `gorm:"column:remark"` CreateTime time.Time `gorm:"column:create_time;-"` UpdateTime time.Time `gorm:"column:update_time;-"` IsDelete uint8 `gorm:"column:is_delete"` } func (m GoogsModel) TableName() string { return "goods_tb" } func GetGoodsListByCategory(db *gorm.DB, category string) ([]*GoogsModel, error) { var goodsList []*GoogsModel err := db.Where("category = ?", category).Find(&goodsList).Error if err != nil { logger.Error(err) return nil, err } return goodsList, nil } type PurchaseRecordModel struct { ID int64 `gorm:"column:id"` GoodsID string `gorm:"column:goods_id"` OrderID string `gorm:"column:order_id"` PayID string `gorm:"column:pay_id"` Remark string `gorm:"column:remark"` CreateTime time.Time `gorm:"column:create_time;-"` UpdateTime time.Time `gorm:"column:update_time;-"` IsDelete uint8 `gorm:"column:is_delete"` } func (m PurchaseRecordModel) TableName() string { return "purchase_record_tb" }
afeng11/tomato-arm
release/src-rt-6.x.4708/router/apcupsd/src/win32/winconfig.h
<filename>release/src-rt-6.x.4708/router/apcupsd/src/win32/winconfig.h /* * Copyright (C) 2009 <NAME> * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General * Public License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef __WINCONFIG_H #define __WINCONFIG_H #include "astring.h" #include "instmgr.h" #include <windows.h> // Object implementing the Status dialogue for apcupsd class upsConfig { public: // Constructor/destructor upsConfig(HINSTANCE appinst, InstanceManager *instmgr); ~upsConfig(); // General void Show(MonitorConfig &mcfg); private: // The dialog box window proc static BOOL CALLBACK DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); BOOL DialogProcess(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // Private data HWND _hwnd; HINSTANCE _appinst; InstanceManager *_instmgr; MonitorConfig _config; HWND _hhost, _hport, _hrefresh, _hpopups; bool _hostvalid, _portvalid, _refreshvalid; }; #endif // WINCONFIG_H
pelican/pelican
pelican/output/test/src/OutputStreamManagerTest.cpp
/* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "OutputStreamManagerTest.h" #include "OutputStreamManager.h" #include "output/test/TestOutputStreamer.h" namespace pelican { using test::TestOutputStreamer; CPPUNIT_TEST_SUITE_REGISTRATION( OutputStreamManagerTest ); /** *@details OutputStreamManagerTest */ OutputStreamManagerTest::OutputStreamManagerTest() : CppUnit::TestFixture() { } /** *@details */ OutputStreamManagerTest::~OutputStreamManagerTest() { } void OutputStreamManagerTest::setUp() { _config = new Config(); } void OutputStreamManagerTest::tearDown() { delete _config; } void OutputStreamManagerTest::test_connectToStream() { QString all("all"); QString stream1("stream1"); QString stream2("stream2"); TestOutputStreamer s1("Streamer1"); TestOutputStreamer s2("Streamer2"); { // Use Case: // Simple one-one association OutputStreamManager* os = _getManager(); os->connectToStream( &s1, stream1 ); CPPUNIT_ASSERT(os->connected(stream1).size() == 1 ); CPPUNIT_ASSERT(os->connected(stream1)[0] == &s1 ); delete os; } { // Use Case: // "all" association followed by an association adding // a new stream. // Expect: // "all" stream to be connected to the new stream // and correct association for new stream OutputStreamManager* os = _getManager(); os->connectToStream( &s1, all ); os->connectToStream( &s2, stream1 ); CPPUNIT_ASSERT(os->connected(stream1)[0] == &s1 ); CPPUNIT_ASSERT(os->connected(stream1)[1] == &s2 ); delete os; } { // Use Case: // "all" association following by an existing association // // Expect: // exisiting associations stream to be connected to the "all" stream // and exisiting connections maintained OutputStreamManager* os = _getManager(); os->connectToStream( &s1, stream1 ); os->connectToStream( &s2, all ); CPPUNIT_ASSERT(os->connected(stream1)[0] == &s1 ); CPPUNIT_ASSERT(os->connected(stream1)[1] == &s2 ); delete os; } } void OutputStreamManagerTest::test_configuration() { { // Use Case: // configuration contains a dataStreams, and a known Output Streamers defined // Expect: // throw QString xml = "<output>" " <streamers>" " <TestOutputStreamer />" " </streamers>" " <dataStreams>" " <stream name=\"a\" listeners=\"TestOutputStreamer\" />" " </dataStreams>" "</output>" ; OutputStreamManager* os = 0; try { os = _getManager(xml, "output"); CPPUNIT_ASSERT(os->connected("a").size() == 1 ); } catch( const QString& msg ) { CPPUNIT_FAIL( msg.toStdString() ); } delete os; } { // Use Case: // configuration contains an unknown output streamer type // Expect: // throw QString xml = "<output>" " <streamers>" " <UnknownStreamer />" " </streamers>" " <dataStreams>" " <stream name=\"a\" listeners=\"UnknownStreamer\" />" " </dataStreams>" "</output>" ; CPPUNIT_ASSERT_THROW( _getManager(xml, "output"), QString ); } { // Use Case: // configuration contains no dataStreams, but output Streamers defined // Expect: // throw QString xml = "<output>" " <streamers>" " <TestOutputStreamer />" " </streamers>" "</output>" ; CPPUNIT_ASSERT_THROW( _getManager(xml, "output") , QString ); } { // Use Case: // configuration contains multiple output streamers of the same type // and the same identifier // Expect: // throw QString xml = "<output>" " <streamers>" " <TestOutputStreamer />" " <TestOutputStreamer />" " </streamers>" " <dataStreams>" " <stream name=\"a\" listeners=\"TestOutputStreamer\" />" " </dataStreams>" "</output>" ; CPPUNIT_ASSERT_THROW( _getManager(xml, "output") , QString ); } { // Use Case: // configuration contains multiple output streamers of the same type // but with different identifiers and associated with different streams // Expect: // correct associations QString xml = "<output>" " <streamers>" " <TestOutputStreamer name=\"s1\"/>" " <TestOutputStreamer name=\"s2\"/>" " </streamers>" " <dataStreams>" " <stream name=\"a\" listeners=\"s1,s2\" />" " </dataStreams>" "</output>" ; OutputStreamManager* os = _getManager(xml, "output"); CPPUNIT_ASSERT(os->connected("a").size() == 2 ); delete os; } { // Use Case: // configuration contains multiple output streamers // and associated with different streams // Expect: // correct associations QString xml = "<output>" " <streamers>" " <TestOutputStreamer name=\"s1\"/>" " <TestOutputStreamer name=\"s2\"/>" " <TestOutputStreamer name=\"s3\"/>" " </streamers>" " <dataStreams>" " <stream name=\"a\" listeners=\"s1\" />" " <stream name=\"b\" listeners=\"s2\" />" " <stream name=\"all\" listeners=\"s3\" />" " </dataStreams>" "</output>" ; OutputStreamManager* os = _getManager(xml, "output"); CPPUNIT_ASSERT(os->connected("a").size() == 2 ); CPPUNIT_ASSERT(os->connected("b").size() == 2 ); delete os; } { // Use Case: // Configuration contains an inactive output streamer // that is refered to as a listener // Expect: // no associations to be made QString xml = "<output>" " <streamers>" " <TestOutputStreamer active=\"false\"/>" " </streamers>" " <dataStreams>" " <stream name=\"a\" listeners=\"TestOutputStreamer\" />" " </dataStreams>" "</output>" ; OutputStreamManager* os = _getManager(xml, "output"); CPPUNIT_ASSERT(os->connected("a").size() == 0 ); delete os; } } OutputStreamManager* OutputStreamManagerTest::_getManager(const QString& xml, const QString& base) { _address = Config::TreeAddress() << Config::NodeId(base, ""); if( xml == "" ) return new OutputStreamManager(0, _address); _config->setXML(xml); return new OutputStreamManager(_config, _address); } } // namespace pelican
scottwedge/OpenStack-Stein
openstack-congress-9.0.0/congress/tests/datasources/json_ingester/test_json_ingester.py
# Copyright (c) 2019 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from __future__ import print_function from __future__ import division from __future__ import absolute_import import uuid import mock from congress.datasources import datasource_driver from congress.datasources.json_ingester import json_ingester from congress import exception from congress.tests import base class TestJsonIngester(base.TestCase): @mock.patch('congress.datasources.datasource_utils.get_keystone_session') @mock.patch.object( datasource_driver.PollingDataSourceDriver, '_init_end_start_poll') @mock.patch.object( json_ingester.JsonIngester, '_create_schema_and_tables') def setUp(self, _create_schema_and_tables, _init_end_start_poll, get_keystone_session): super(TestJsonIngester, self).setUp() self.test_config = { "api_endpoint": "http://127.0.0.1/compute/v2.1/", "tables": { "flavors": { "poll": { "api_method": "get", "api_path": "flavors/detail", "jsonpath": "$.flavors[:]" } }, "servers": { "poll": { "api_method": "get", "api_path": "servers/detail", "jsonpath": "$.servers[:]" } }, "alarms": { "webhook": { "record_jsonpath": "$.payload", "id_jsonpath": "$.id" } } }, "authentication": { "type": "keystone", "config": { "username": "admin", "project_name": "admin", "password": "password", "auth_url": "http://127.0.0.1/identity" } }, "poll_interval": 1, "name": "nova" } from congress.datasources.json_ingester import exec_api # exec_manager = exec_api.ExecApiManager([]) exec_manager_mock = mock.Mock(spec=exec_api.ExecApiManager) self.test_driver = json_ingester.JsonIngester( self.test_config['name'], self.test_config, exec_manager_mock) def test_invalid_config_poll_plus_webhook(self): invalid_config = self.test_config invalid_config['tables']['servers']['webhook'] = { "record_jsonpath": "$.payload", "id_jsonpath": "$.id"} self.assertRaises( exception.BadConfig, json_ingester.JsonIngester, invalid_config['name'], invalid_config, None) @mock.patch.object(json_ingester.JsonIngester, '_update_table') def test_poll(self, _update_table): mock_api_result = { "servers": [ {"server": 1}, {"server": 2}, {"server": 3} ], "flavors": [], "servers_links": [ { "href": "blah", "rel": "next" } ] } servers_api_result_str_set = set( ['{"server": 1}', '{"server": 2}', '{"server": 3}']) self.test_driver._session.get.return_value.json.return_value = \ mock_api_result # test initial poll self.test_driver.poll() self.assertEqual(_update_table.call_count, 2) _update_table.assert_any_call( 'servers', new_data=servers_api_result_str_set, old_data=set([]), use_snapshot=True) _update_table.assert_any_call( 'flavors', new_data=set([]), old_data=set([]), use_snapshot=True) _update_table.reset_mock() # test subsequent poll self.test_driver.poll() self.assertEqual(_update_table.call_count, 2) _update_table.assert_any_call( 'servers', new_data=servers_api_result_str_set, old_data=servers_api_result_str_set, use_snapshot=False) _update_table.assert_any_call( 'flavors', new_data=set([]), old_data=set([]), use_snapshot=False) @mock.patch.object(json_ingester.JsonIngester, '_webhook_update_table') def test_json_ingester_webhook_handler(self, _webhook_update_table): test_body = {"payload": {"id": 42, "other": "stuff"}} self.test_driver.json_ingester_webhook_handler('alarms', test_body) _webhook_update_table.assert_called_once_with( 'alarms', key=42, data=test_body['payload']) (self.test_driver.exec_manager. evaluate_and_execute_actions.assert_called_once()) @mock.patch.object(json_ingester.JsonIngester, '_webhook_update_table') def test_json_ingester_webhook_handler_non_primitive_key( self, _webhook_update_table): test_key = {1: [2, 3], "2": "4"} test_body = {"payload": {"id": test_key, "other": "stuff"}} self.test_driver.json_ingester_webhook_handler('alarms', test_body) _webhook_update_table.assert_called_once_with( 'alarms', key=test_key, data=test_body['payload']) (self.test_driver.exec_manager. evaluate_and_execute_actions.assert_called_once()) @mock.patch.object(json_ingester.JsonIngester, '_webhook_update_table') def test_json_ingester_webhook_handler_missing_payload( self, _webhook_update_table): test_body = {"not_payload": {"id": 42, "other": "stuff"}} self.assertRaises( exception.BadRequest, self.test_driver.json_ingester_webhook_handler, 'alarms', test_body) @mock.patch.object(json_ingester.JsonIngester, '_webhook_update_table') def test_json_ingester_webhook_handler_missing_id( self, _webhook_update_table): test_body = {"payload": {"not_id": 42, "other": "stuff"}} self.assertRaises( exception.BadRequest, self.test_driver.json_ingester_webhook_handler, 'alarms', test_body) def test_json_ingester_webhook_key_too_long(self): test_body = {"payload": {"id": "X"*2713, "other": "stuff"}} self.assertRaises( exception.BadRequest, self.test_driver.json_ingester_webhook_handler, 'alarms', test_body) def test_json_ingester_webhook_nonexistent_table(self): test_body = {"payload": {"id": 42, "other": "stuff"}} self.assertRaises( exception.NotFound, self.test_driver.json_ingester_webhook_handler, 'no_such_table', test_body) def test_json_ingester_webhook_non_webhook_table(self): test_body = {"payload": {"id": 42, "other": "stuff"}} self.assertRaises( exception.NotFound, self.test_driver.json_ingester_webhook_handler, 'servers', test_body) class TestKeyMap(base.TestCase): def setUp(self): super(TestKeyMap, self).setUp() self.key_map = json_ingester.KeyMap() def test_init(self): self.assertEqual(len(self.key_map), 0, 'key set not empty upon init') def test_add_then_remove(self): datum = str(uuid.uuid4()) key_on_add = self.key_map.add_and_get_key(datum) self.assertEqual(len(self.key_map), 1) key_on_remove = self.key_map.remove_and_get_key(datum) self.assertEqual(len(self.key_map), 0) self.assertEqual(key_on_add, key_on_remove) def test_increment(self): datum1 = str(uuid.uuid4()) datum2 = datum1 + 'diff' key1 = self.key_map.add_and_get_key(datum1) key2 = self.key_map.add_and_get_key(datum2) self.assertEqual(len(self.key_map), 2) self.assertEqual(key2, key1 + 1) def test_reclaim(self): datum1 = str(uuid.uuid4()) datum2 = datum1 + 'diff' datum3 = datum1 + 'diffdiff' key1 = self.key_map.add_and_get_key(datum1) self.key_map.add_and_get_key(datum2) self.key_map.remove_and_get_key(datum1) key3 = self.key_map.add_and_get_key(datum3) self.assertEqual(key1, key3) def test_repeat_add(self): datum = str(uuid.uuid4()) key1 = self.key_map.add_and_get_key(datum) key2 = self.key_map.add_and_get_key(datum) self.assertEqual(len(self.key_map), 1) self.assertEqual(key1, key2) def test_remove_nonexistent(self): self.assertRaises(KeyError, self.key_map.remove_and_get_key, 'datum')
SmarterApp/TechnologyReadinessTool
core-components/src/main/java/net/techreadiness/persistence/domain/OrgPartExtDO_.java
package net.techreadiness.persistence.domain; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(OrgPartExtDO.class) public abstract class OrgPartExtDO_ { public static volatile SingularAttribute<OrgPartExtDO, OrgPartDO> orgPart; public static volatile SingularAttribute<OrgPartExtDO, String> value; public static volatile SingularAttribute<OrgPartExtDO, Long> orgPartExtId; public static volatile SingularAttribute<OrgPartExtDO, EntityFieldDO> entityField; }
DreadMoirai/SamuraiBot
src/main/java/com/github/breadmoirai/samurai/plugins/trivia/TriviaPlugin.java
<reponame>DreadMoirai/SamuraiBot<filename>src/main/java/com/github/breadmoirai/samurai/plugins/trivia/TriviaPlugin.java /* * Copyright 2017-2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.breadmoirai.samurai.plugins.trivia; import com.github.breadmoirai.breadbot.framework.BreadBot; import com.github.breadmoirai.breadbot.framework.CommandPlugin; import com.github.breadmoirai.breadbot.framework.annotation.command.Command; import com.github.breadmoirai.breadbot.framework.annotation.parameter.Author; import com.github.breadmoirai.breadbot.framework.annotation.parameter.Content; import com.github.breadmoirai.breadbot.framework.builder.BreadBotBuilder; import com.github.breadmoirai.breadbot.plugins.admin.Admin; import com.github.breadmoirai.breadbot.plugins.waiter.EventWaiter; import com.github.breadmoirai.breadbot.plugins.waiter.EventWaiterPlugin; import com.github.breadmoirai.samurai.plugins.derby.DerbyDatabase; import com.github.breadmoirai.samurai.plugins.points.DerbyPointPlugin; import com.github.breadmoirai.samurai.plugins.trivia.triviaquestionsdotnet.TriviaQuestionsDotNetProvider; import com.sedmelluq.discord.lavaplayer.tools.ExecutorTools; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.hash.TLongObjectHashMap; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.events.ShutdownEvent; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; public class TriviaPlugin implements CommandPlugin { private final List<TriviaProvider> providers; private final ScheduledExecutorService service; private final TLongObjectMap<TriviaManager> managers; private TriviaChannelDatabase database; private JDA jda; private EventWaiter waiter; private DerbyPointPlugin points; public TriviaPlugin() { this.providers = new ArrayList<>(); this.service = Executors.newSingleThreadScheduledExecutor(); managers = new TLongObjectHashMap<>(); } @Override public void initialize(BreadBotBuilder builder) { builder.addCommand(this); } @Override public void onBreadReady(BreadBot client) { waiter = client.getPlugin(EventWaiterPlugin.class).getEventWaiter(); final DerbyDatabase databasePlugin = client.getPlugin(DerbyDatabase.class); points = client.getPlugin(DerbyPointPlugin.class); database = databasePlugin.getExtension(TriviaChannelDatabase::new); registerProvider(new TriviaQuestionsDotNetProvider(databasePlugin)); waiter.waitFor(ReadyEvent.class).action(this::onReady); waiter.waitFor(ShutdownEvent.class).action(event -> ExecutorTools.shutdownExecutor(service, "Trivia Service")); } public void registerProvider(TriviaProvider provider) { providers.add(provider); } private void onReady(ReadyEvent event) { jda = event.getJDA(); database.getTriviaChannels().forEachEntry((a, b) -> { final TextChannel channel = jda.getTextChannelById(b); if (channel == null) { return true; } managers.put(a, new TriviaManager(channel, waiter, this, points)); return true; }); } public ScheduledExecutorService getService() { return service; } public TriviaProvider getRandomProvider() { return providers.get(0); } public void setNextTime(long guildId, Instant time) { database.setNextTime(guildId, time); } public Instant getNextTime(long guildId) { return database.getNextTime(guildId); } @Admin @Command public String enableTrivia(TextChannel channel) { final TriviaManager triviaManager = managers.get(channel.getGuild().getIdLong()); if (triviaManager == null || triviaManager.getChannelId() != channel.getIdLong()) managers.put(channel.getGuild().getIdLong(), new TriviaManager(channel, waiter, this, points)); database.setTriviaChannel(channel.getGuild().getIdLong(), channel.getIdLong()); return "Trivia has been enabled in this channel"; } @Command public String disableTrivia(Guild guild) { final TriviaManager manager = managers.remove(guild.getIdLong()); if (manager != null) { manager.shutdown(); } database.removeTriviaChannel(guild.getIdLong()); return "Trivia has been disabled on this server"; } @Command public void answer(Guild guild, Message m, @Content String ans, @Author Member author) { if (ans == null) return; final TriviaManager triviaManager = managers.get(guild.getIdLong()); if (triviaManager == null) { m.getTextChannel().sendMessage("Trivia is not enabled").queue(); return; } if (!triviaManager.isActive()) { question(m.getTextChannel(), guild); return; } String s = ans.toLowerCase() .replaceAll("\\s+", " ") .replaceAll(",\\s*", " ") .replaceAll("&", "and"); if (s.startsWith("the")) { s = s.substring(4); } triviaManager.answer(s, m, author); } @Command public void question(TextChannel channel, Guild guild) { final TriviaManager triviaManager = managers.get(guild.getIdLong()); if (triviaManager == null) { channel.sendMessage("Trivia is not enabled").queue(); } else if (channel.getIdLong() == triviaManager.getChannelId()) { triviaManager.repeatQuestion(); } } }
twagner/noidcp
main/lib/model/tokenRequest.js
"use strict"; const config = require('../../config'), AccessToken = require('./accessToken'), RefreshToken = require('./refreshToken'), TokenResponse = require('./tokenResponse'), IdToken = require('./idToken'), TokenError = require('./tokenError'), Q = require('q'), S = require('string'), validator = require('validator'); function TokenRequest(parameters, config) { this.grantType = null; this.code = null; this.redirectUri = null; this.client = null; this.clientId = null; this.clientSecret = null; this.refreshToken = null; // initialize with the parameters. for (let param in parameters) { if (this.hasOwnProperty(S(param).camelize().s)) { this[S(param).camelize().s] = parameters[param]; } } if (!config.clientService || !config.authorizationCodeService || !config.accessTokenService || !config.refreshTokenService || !config.idTokenService) { console.log('TokenRequest: unsatisfied dependency!'); throw new Error('TokenRequest: unsatisfied dependency!'); } this.clientService = config.clientService; this.authorizationCodeService = config.authorizationCodeService; this.accessTokenService = config.accessTokenService; this.refreshTokenService = config.refreshTokenService; this.idTokenService = config.idTokenService; } TokenRequest.prototype.authenticateClient = function() { console.log('TokenRequest#authenticateClient'); const self = this; return this.clientService.authenticate(this.clientId, this.clientSecret).then(function(client) { self.client = client; }, function(error) { console.log('TokenRequest#authenticateClient: error ' + error); throw new TokenError('invalid_client'); }); }; TokenRequest.prototype.token = function() { console.log('TokenRequest#token'); const self = this; return this.validateAccessTokenRequest().then(function() { return self.authenticateClient().then(function(client) { console.log('TokenRequest#token: Client authenticated!'); return self.authorizationCodeService.findByCode(self.code).then(function(ac) { return ac; }, function(error) { console.log('TokenRequest#token: find authorization code: ' + error); throw new TokenError('invalid_grant'); }); }); }).then(function(authorizationCode) { console.log('TokenRequest#token: validating authorization code'); // Verify that the Authorization Code is valid. if (!authorizationCode || !authorizationCode.isValidSync()) { console.log('TokenRequest#token: The authorization code is invalid!'); throw new TokenError('invalid_grant', 'Invalid authorization code'); } // Ensure the Authorization Code was issued to the authenticated Client. if (authorizationCode.clientId !== self.clientId) { console.log('TokenRequest#token: Client id doesn\'t match!'); throw new TokenError('invalid_grant', 'Client id doesn\'t match!'); } // Ensure that the redirect_uri parameter value is identical to the redirect_uri // parameter value that was included in the initial Authorization Request. if (!self.compareRedirectUri_(authorizationCode.redirectUri)) { console.log('TokenRequest#token: Redirect uri doesn\'t match!'); throw new TokenError('invalid_grant'); } // If possible, verify that the Authorization Code has not been previously used. // TODO return self._refreshToken(authorizationCode).then(function(refreshToken) { return self._accessToken(authorizationCode, refreshToken).then(function(accessToken) { if (authorizationCode.isOpenIDSync()) { return self._idToken(authorizationCode).then(function(idToken) { return new TokenResponse({ accessToken: accessToken.token, refreshToken: refreshToken.token, idToken: idToken, expiresIn: accessToken.expiresIn }); }); } else { return new TokenResponse({ accessToken: accessToken.token, refreshToken: refreshToken.token, expiresIn: accessToken.expiresIn }); } }); }).catch(function(error) { throw new TokenError('invalid_request'); }); }); }; TokenRequest.prototype.refresh = function() { const self = this; return this.validateRefreshTokenRequest().then(function() { return self.authenticateClient().then(function(client) { return self.refreshTokenService.findByRefreshToken(self.refreshToken).then(function(refreshToken) { return refreshToken; }, function(error) { throw new TokenError('invalid_grant', 'Refresh Token not found!'); }); }).then(function(refreshToken) { // Verify that the refresh token is valid. if (!refreshToken || !refreshToken.isValidSync()) { console.log('TokenRequest#refresh: The refresh token is invalid!'); throw new TokenError('invalid_grant', 'The refresh token is invalid!'); } // Ensure the refresh token was issued to the authenticated Client. if (refreshToken.clientId !== self.clientId) { console.log('TokenRequest#refresh: Client id doesn\'t match!'); throw new TokenError('invalid_client'); } return self._accessToken(refreshToken, refreshToken.token).then(function(accessToken) { if (refreshToken.isOpenIDSync()) { return self._idToken(refreshToken).then(function(idToken) { return new TokenResponse({ accessToken: accessToken.token, expiresIn: accessToken.expiresIn, refreshToken: refreshToken.token, idToken: idToken }); }); } else { return new TokenResponse({ accessToken: accessToken.token, expiresIn: accessToken.expiresIn, refreshToken: refreshToken.token }); } }).catch(function(error) { console.log('TokenRequest#refresh: ' + error); throw new TokenError('invalid_request'); }); }); }); }; TokenRequest.prototype.isAccessTokenRequestSync = function() { return this.grantType === 'authorization_code'; }; TokenRequest.prototype.isRefreshTokenRequestSync = function() { return this.grantType === 'refresh_token'; }; TokenRequest.prototype.error_ = function(status, msg) { const e = new Error(msg); e.status = status; return e; }; TokenRequest.prototype.compareRedirectUri_ = function(uri) { return decodeURIComponent(this.redirectUri) === decodeURIComponent(uri); }; TokenRequest.prototype.validateAccessTokenRequest = function() { const self = this; return Q.fcall(function() { let validRequest = validator.equals(self.grantType, 'authorization_code') && validator.isLength(self.code, 1) && validator.isLength(self.redirectUri, 1) && validator.isLength(self.clientId, 1); validRequest = validRequest && validator.isURL(decodeURIComponent(self.redirectUri)); console.log('TokenRequest#validateAccessTokenRequest: request valid ' + validRequest); if (!validRequest) { throw new TokenError('invalid_request'); } return true; }); }; TokenRequest.prototype.validateRefreshTokenRequest = function() { const self = this; return Q.fcall(function() { let validRequest = validator.equals(self.grantType, 'refresh_token') && validator.isLength(self.refreshToken, 1); console.log('TokenRequest#validateRefreshTokenRequest: request valid ' + validRequest); if (!validRequest) { throw new TokenError('invalid_request'); } return true; }); }; TokenRequest.prototype._accessToken = function(data, refreshToken) { return this.accessTokenService.createAccessToken({ sub: data.sub, clientId: data.clientId, refreshToken: refreshToken, scope: data.scope }); }; TokenRequest.prototype._refreshToken = function(data) { return this.refreshTokenService.createRefreshToken({ sub: data.sub, clientId: data.clientId, scope: data.scope }); }; TokenRequest.prototype._idToken = function(data) { return this.idTokenService.createIdToken({ sub: data.sub, authTime: data.authTime, clientId: data.clientId, scope: data.scope, nonce: data.nonce }); }; module.exports = TokenRequest;
shreyasvj25/turicreate
deps/src/boost_1_65_1/libs/integer/test/gcd_noexcept_test.cpp
// (C) Copyright <NAME> 2017. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/integer/common_factor.hpp> #if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) // // These tests don't pass with GCC-4.x: // #if !defined(BOOST_GCC) || (BOOST_GCC >= 50000) void test_noexcept(unsigned char a, unsigned char b) { static_assert(noexcept(boost::integer::gcd(static_cast<unsigned char>(a), static_cast<unsigned char>(b))), "Expected a noexcept function."); #ifndef _MSC_VER // This generates an internal compiler error if enabled as well as the following test: static_assert(noexcept(boost::integer::gcd(static_cast<char>(a), static_cast<char>(b))), "Expected a noexcept function."); #endif static_assert(noexcept(boost::integer::gcd(static_cast<signed char>(a), static_cast<signed char>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<short>(a), static_cast<short>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<unsigned short>(a), static_cast<unsigned short>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<int>(a), static_cast<int>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<unsigned int>(a), static_cast<unsigned int>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<long>(a), static_cast<long>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<unsigned long>(a), static_cast<unsigned long>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<long long>(a), static_cast<long long>(b))), "Expected a noexcept function."); static_assert(noexcept(boost::integer::gcd(static_cast<unsigned long long>(a), static_cast<unsigned long long>(b))), "Expected a noexcept function."); } #endif #endif
dougreside/MOVER
Releases/January2014/src/src/org/nypl/drag/DragLayer.java
<filename>Releases/January2014/src/src/org/nypl/drag/DragLayer.java /* * This is a modified version of a class from the Android Open Source Project. * The original copyright and license information follows. * * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nypl.drag; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.KeyEvent; import android.view.View; import android.widget.Toast; /** * A ViewGroup that coordinates dragging across its dscendants. * * <p> This class used DragLayer in the Android Launcher activity as a model. * It is a bit different in several respects: * (1) It extends MyAbsoluteLayout rather than FrameLayout; (2) it implements DragSource and DropTarget methods * that were done in a separate Workspace class in the Launcher. */ public class DragLayer extends MyAbsoluteLayout implements DragSource, DropTarget { DragController mDragController; /** * Used to create a new DragLayer from XML. * * @param context The application's context. * @param attrs The attribtues set containing the Workspace's customization values. */ public DragLayer (Context context, AttributeSet attrs) { super(context, attrs); } public void setDragController(DragController controller) { mDragController = controller; } @Override public boolean dispatchKeyEvent(KeyEvent event) { return mDragController.dispatchKeyEvent(event) || super.dispatchKeyEvent(event); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return mDragController.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { return mDragController.onTouchEvent(ev); } @Override public boolean dispatchUnhandledMove(View focused, int direction) { return mDragController.dispatchUnhandledMove(focused, direction); } /** */ // DragSource interface methods /** * This method is called to determine if the DragSource has something to drag. * * @return True if there is something to drag */ public boolean allowDrag () { // In this simple demo, any view that you touch can be dragged. return true; } /** * setDragController * */ /* setDragController is already defined. See above. */ /** * onDropCompleted * */ public void onDropCompleted (View target, boolean success) { } /** */ // DropTarget interface implementation /** * Handle an object being dropped on the DropTarget. * This is the where a dragged view gets repositioned at the end of a drag. * * @param source DragSource where the drag started * @param x X coordinate of the drop location * @param y Y coordinate of the drop location * @param xOffset Horizontal offset with the object being dragged where the original * touch happened * @param yOffset Vertical offset with the object being dragged where the original * touch happened * @param dragView The DragView that's being dragged around on screen. * @param dragInfo Data associated with the object being dragged * */ public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { View v = (View) dragInfo; int w = v.getWidth (); int h = v.getHeight (); int left = x - xOffset; int top = y - yOffset; DragLayer.LayoutParams lp = new DragLayer.LayoutParams (w, h, left, top); this.updateViewLayout(v, lp); } public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { } public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { } public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { } /** * Check if a drop action can occur at, or near, the requested location. * This may be called repeatedly during a drag, so any calls should return * quickly. * * @param source DragSource where the drag started * @param x X coordinate of the drop location * @param y Y coordinate of the drop location * @param xOffset Horizontal offset with the object being dragged where the * original touch happened * @param yOffset Vertical offset with the object being dragged where the * original touch happened * @param dragView The DragView that's being dragged around on screen. * @param dragInfo Data associated with the object being dragged * @return True if the drop will be accepted, false otherwise. */ public boolean acceptDrop(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo) { return true; } /** * Estimate the surface area where this object would land if dropped at the * given location. * * @param source DragSource where the drag started * @param x X coordinate of the drop location * @param y Y coordinate of the drop location * @param xOffset Horizontal offset with the object being dragged where the * original touch happened * @param yOffset Vertical offset with the object being dragged where the * original touch happened * @param dragView The DragView that's being dragged around on screen. * @param dragInfo Data associated with the object being dragged * @param recycle {@link Rect} object to be possibly recycled. * @return Estimated area that would be occupied if object was dropped at * the given location. Should return null if no estimate is found, * or if this target doesn't provide estimations. */ public Rect estimateDropLocation(DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo, Rect recycle) { return null; } } // end class
automenta/trex-autonomy
agent/base/Utilities.hh
#ifndef H_Utilities #define H_Utilities /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2007. MBARI. * 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 TREX Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include "Constraint.hh" #include "PlanDatabaseDefs.hh" using namespace EUROPA; namespace TREX { #define RETURN_IF_NO_EVAL if (getenv("TREX_NO_EVAL") != NULL) { if (std::string(getenv("TREX_NO_EVAL")) == "1") { return; } } void computeConnectedTokens(const TokenId token, TokenSet& results); class ConfigurationException { public: ConfigurationException(const std::string& description); const std::string& toString() const; static void configurationCheckError(bool check, const std::string& description); private: const std::string m_description; }; /** * @brief Output current time as a string */ std::string timeString(); void runAgent(const char* configFile, unsigned int stepsPerTick, const char* problemName); bool validateResults(const char* problemName); bool hasValidFile(const char* problemName); bool isValid(const std::string& testStr, const char* problemName); void makeValidFile(const std::string& validStr, const char* problemName); void makeInvalidFile(const std::string& validStr, const char* problemName); void makeFile(const std::string& outputStr, const char* prefix, const char* suffix); /** * Generate a display string for a token */ std::string tokenToString(const TokenId& tok); /** * @brief Obatin the fully qualified path name for the given file by searching the local directory and then the path */ std::string findFile(const std::string& fileName, bool forceRebuild = false); /** * @brief Helper method to access the object name of a token. Assumes object var is a singleton */ const LabelStr& getObjectName(const TokenId& token); std::vector<ConstrainedVariableId> appendStateVar(const std::vector<ConstrainedVariableId>& variables); /** * @brief Utililty for accessing the parent token of a token or rule variable */ TokenId getParentToken(const ConstrainedVariableId& var); /** * @brief Utility to convert an observation to an xml string. */ //std::string observationToString(const Observation& obs); /** * @brief Utility convert a string to an observation */ //Observation* observationFromXml(const TiXmlElement& elem); /** * @brief Binds default values for token parameters if they are not singletons. */ class SetDefault : public Constraint { public: SetDefault(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, const std::vector<ConstrainedVariableId>& variables); protected: void setSource(const ConstraintId& constraint); void handleExecute(); virtual bool defaultGuardSatisfied(); TokenId m_token; AbstractDomain& m_param; AbstractDomain& m_default; }; /** * @brief Binds default values when a token is committed */ class SetDefaultOnCommit : public SetDefault { public: SetDefaultOnCommit(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, const std::vector<ConstrainedVariableId>& variables); protected: bool defaultGuardSatisfied(); }; /** * @brief Binds default values when a token is committed */ class AbsMaxOnCommit : public Constraint { public: AbsMaxOnCommit(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, const std::vector<ConstrainedVariableId>& variables); private: void setSource(const ConstraintId& constraint); void handleExecute(); TokenId m_token; AbstractDomain& m_param; }; /** * @brief bindMax: binds the target with the max possible value from the source */ class BindMax : public Constraint { public: BindMax(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, const std::vector<ConstrainedVariableId>& variables); void handleExecute(); private: AbstractDomain& m_target; AbstractDomain& m_source; static const unsigned int ARG_COUNT = 2; }; /** * @brief neighborhood(int a, int b, int n): computes a neighborhood n in a with b elements. n must be enumerated. */ class Neighborhood : public Constraint { public: Neighborhood(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, const std::vector<ConstrainedVariableId>& variables); void handleExecute(); private: const AbstractDomain& m_element; const AbstractDomain& m_cardinality; AbstractDomain& m_neighborhood; std::vector<double> m_basis; unsigned int m_position; }; } #endif
wiechula/AliPhysics
PWGGA/CaloTrackCorrelations/AliAnaOmegaToPi0Gamma.cxx
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // --- ROOT system class TROOT; #include "TH2F.h" #include "TLorentzVector.h" #include "TParticle.h" #include "TCanvas.h" #include "TFile.h" //---- AliRoot system ---- #include "AliAnaOmegaToPi0Gamma.h" #include "AliCaloTrackReader.h" #include "AliCaloPID.h" #include "AliStack.h" #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliAODMCParticle.h" /// \cond CLASSIMP ClassImp(AliAnaOmegaToPi0Gamma) ; /// \endcond //______________________________________________________________________________ /// Default constructor. //______________________________________________________________________________ AliAnaOmegaToPi0Gamma::AliAnaOmegaToPi0Gamma() : AliAnaCaloTrackCorrBaseClass(), fInputAODPi0(0), fInputAODGammaName(""), fEventsList(0x0),fNVtxZBin(0), fNCentBin(0), fNRpBin(0), fNBadChDistBin(0), fNpid(0), fVtxZCut(0), fCent(0), fRp(0), fPi0Mass(0),fPi0MassWindow(0),fPi0OverOmegaPtCut(0), fGammaOverOmegaPtCut(0), fEOverlapCluster(0), fhEtalon(0), fRealOmega0(0), fMixAOmega0(0), fMixBOmega0(0), fMixCOmega0(0), fRealOmega1(0), fMixAOmega1(0), fMixBOmega1(0), fMixCOmega1(0), fRealOmega2(0), fMixAOmega2(0), fMixBOmega2(0), fMixCOmega2(0), fhFakeOmega(0), fhOmegaPriPt(0) { InitParameters(); } //_____________________________________________ /// Destructor //_____________________________________________ AliAnaOmegaToPi0Gamma::~AliAnaOmegaToPi0Gamma() { // Done by the maker // if(fInputAODPi0){ // fInputAODPi0->Clear(); // delete fInputAODPi0; // } if(fEventsList){ for(Int_t i=0;i<fNVtxZBin;i++) { for(Int_t j=0;j<fNCentBin;j++) { for(Int_t k=0;k<fNRpBin;k++) { fEventsList[i*fNCentBin*fNRpBin+j*fNRpBin+k]->Clear(); delete fEventsList[i*fNCentBin*fNRpBin+j*fNRpBin+k]; } } } } delete [] fEventsList; fEventsList=0; delete [] fVtxZCut; delete [] fCent; delete [] fRp; } //__________________________________________ /// Init parameters when first called the analysis. /// Set default parameters. //__________________________________________ void AliAnaOmegaToPi0Gamma::InitParameters() { fInputAODGammaName="PhotonsDetector"; fNVtxZBin=1; fNCentBin=1; fNRpBin=1; fNBadChDistBin=3; fNpid=1; fPi0Mass=0.1348; fPi0MassWindow=0.015; fPi0OverOmegaPtCut=0.8; fGammaOverOmegaPtCut=0.2; fEOverlapCluster=6; } //_____________________________________________________ /// Create histograms to be saved in output file. //_____________________________________________________ TList * AliAnaOmegaToPi0Gamma::GetCreateOutputObjects() { fVtxZCut = new Double_t [fNVtxZBin]; for(Int_t i=0;i<fNVtxZBin;i++) fVtxZCut[i]=10*(i+1); fCent=new Double_t[fNCentBin]; for(int i = 0;i<fNCentBin;i++)fCent[i]=0; fRp=new Double_t[fNRpBin]; for(int i = 0;i<fNRpBin;i++)fRp[i]=0; // Int_t nptbins = GetHistogramRanges()->GetHistoPtBins(); Float_t ptmax = GetHistogramRanges()->GetHistoPtMax(); Float_t ptmin = GetHistogramRanges()->GetHistoPtMin(); Int_t nmassbins = GetHistogramRanges()->GetHistoMassBins(); Float_t massmin = GetHistogramRanges()->GetHistoMassMin(); Float_t massmax = GetHistogramRanges()->GetHistoMassMax(); fhEtalon = new TH2F("hEtalon","Histo with binning parameters", nptbins,ptmin,ptmax,nmassbins,massmin,massmax) ; fhEtalon->SetXTitle("P_{T} (GeV)") ; fhEtalon->SetYTitle("m_{inv} (GeV)") ; // store them in fOutputContainer fEventsList = new TList*[fNVtxZBin*fNCentBin*fNRpBin]; for(Int_t i=0;i<fNVtxZBin;i++){ for(Int_t j=0;j<fNCentBin;j++){ for(Int_t k=0;k<fNRpBin;k++){ fEventsList[i*fNCentBin*fNRpBin+j*fNRpBin+k] = new TList(); fEventsList[i*fNCentBin*fNRpBin+j*fNRpBin+k]->SetOwner(kFALSE); } } } TList * outputContainer = new TList() ; outputContainer->SetName(GetName()); const Int_t buffersize = 255; char key[buffersize] ; char title[buffersize] ; const char * detectorName= fInputAODGammaName.Data(); Int_t ndim=fNVtxZBin*fNCentBin*fNRpBin*fNBadChDistBin*fNpid; fRealOmega0 =new TH2F*[ndim]; fMixAOmega0 =new TH2F*[ndim]; fMixBOmega0 =new TH2F*[ndim]; fMixCOmega0 =new TH2F*[ndim]; fRealOmega1 =new TH2F*[ndim]; fMixAOmega1 =new TH2F*[ndim]; fMixBOmega1 =new TH2F*[ndim]; fMixCOmega1 =new TH2F*[ndim]; fRealOmega2 =new TH2F*[ndim]; fMixAOmega2 =new TH2F*[ndim]; fMixBOmega2 =new TH2F*[ndim]; fMixCOmega2 =new TH2F*[ndim]; fhFakeOmega = new TH2F*[fNCentBin]; for(Int_t i=0;i<fNVtxZBin;i++){ for(Int_t j=0;j<fNCentBin;j++){ for(Int_t k=0;k<fNRpBin;k++){ //at event level Int_t idim=i*fNCentBin*fNRpBin+j*fNRpBin+k; for(Int_t ipid=0;ipid<fNpid;ipid++){ for(Int_t idist=0;idist<fNBadChDistBin;idist++){ //at particle level Int_t index=idim*fNpid*fNBadChDistBin+ipid*fNBadChDistBin+idist; snprintf(key,buffersize,"RealToPi0Gamma_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s Real Pi0GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fRealOmega0[index]=(TH2F*)fhEtalon->Clone(key) ; fRealOmega0[index]->SetName(key) ; fRealOmega0[index]->SetTitle(title); outputContainer->Add(fRealOmega0[index]); snprintf(key,buffersize,"MixAToPi0Gamma_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixA Pi0GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixAOmega0[index]=(TH2F*)fhEtalon->Clone(key) ; fMixAOmega0[index]->SetName(key) ; fMixAOmega0[index]->SetTitle(title); outputContainer->Add(fMixAOmega0[index]); snprintf(key,buffersize,"<KEY>dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixB Pi0GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixBOmega0[index]=(TH2F*)fhEtalon->Clone(key) ; fMixBOmega0[index]->SetName(key) ; fMixBOmega0[index]->SetTitle(title); outputContainer->Add(fMixBOmega0[index]); snprintf(key,buffersize,"MixCToPi0Gamma_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixC Pi0GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixCOmega0[index]=(TH2F*)fhEtalon->Clone(key) ; fMixCOmega0[index]->SetName(key) ; fMixCOmega0[index]->SetTitle(title); outputContainer->Add(fMixCOmega0[index]); snprintf(key,buffersize,"RealToPi0Gamma1_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s Real Pi0(A<0.7)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fRealOmega1[index]=(TH2F*)fhEtalon->Clone(key) ; fRealOmega1[index]->SetName(key) ; fRealOmega1[index]->SetTitle(title); outputContainer->Add(fRealOmega1[index]); snprintf(key,buffersize,"MixAToPi0Gamma1_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixA Pi0(A<0.7)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixAOmega1[index]=(TH2F*)fhEtalon->Clone(key) ; fMixAOmega1[index]->SetName(key) ; fMixAOmega1[index]->SetTitle(title); outputContainer->Add(fMixAOmega1[index]); snprintf(key,buffersize,"MixBToPi0Gamma1_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixB Pi0(A<0.7)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixBOmega1[index]=(TH2F*)fhEtalon->Clone(key) ; fMixBOmega1[index]->SetName(key) ; fMixBOmega1[index]->SetTitle(title); outputContainer->Add(fMixBOmega1[index]); snprintf(key,buffersize,"MixCToPi0Gamma1_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixC Pi0(A<0.7)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixCOmega1[index]=(TH2F*)fhEtalon->Clone(key) ; fMixCOmega1[index]->SetName(key) ; fMixCOmega1[index]->SetTitle(title); outputContainer->Add(fMixCOmega1[index]); snprintf(key,buffersize,"RealToPi0Gamma2_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s Real Pi0(A<0.8)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fRealOmega2[index]=(TH2F*)fhEtalon->Clone(key) ; fRealOmega2[index]->SetName(key) ; fRealOmega2[index]->SetTitle(title); outputContainer->Add(fRealOmega2[index]); snprintf(key,buffersize,"MixAToPi0Gamma2_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixA Pi0(A<0.8)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixAOmega2[index]=(TH2F*)fhEtalon->Clone(key) ; fMixAOmega2[index]->SetName(key) ; fMixAOmega2[index]->SetTitle(title); outputContainer->Add(fMixAOmega2[index]); snprintf(key,buffersize,"<KEY>dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixB Pi0(A<0.8)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixBOmega2[index]=(TH2F*)fhEtalon->Clone(key) ; fMixBOmega2[index]->SetName(key) ; fMixBOmega2[index]->SetTitle(title); outputContainer->Add(fMixBOmega2[index]); snprintf(key,buffersize,"MixCToPi0Gamma2_Vz%dC%dRp%dPid%dDist%d",i,j,k,ipid,idist); snprintf(title,buffersize, "%s MixC Pi0(A<0.8)GammaIVM vz_%2.1f_ct_%2.1f_Rp_%2.1f_pid_%d_dist_%d",detectorName,fVtxZCut[i],fCent[j],fRp[k],ipid,idist); fMixCOmega2[index]=(TH2F*)fhEtalon->Clone(key) ; fMixCOmega2[index]->SetName(key) ; fMixCOmega2[index]->SetTitle(title); outputContainer->Add(fMixCOmega2[index]); } } } } } for(Int_t i=0;i<fNCentBin;i++){ snprintf(key,buffersize, "fhFakeOmega%d",i); snprintf(title,buffersize,"FakePi0(high pt cluster)+Gamma with Centrality%d",i); fhFakeOmega[i] = (TH2F*)fhEtalon->Clone(key); fhFakeOmega[i]->SetTitle(title); outputContainer->Add(fhFakeOmega[i]); } if(IsDataMC()){ snprintf(key,buffersize, "%sOmegaPri",detectorName); snprintf(title,buffersize,"primary #omega in %s",detectorName); fhOmegaPriPt=new TH1F(key, title,nptbins,ptmin,ptmax); fhOmegaPriPt->GetXaxis()->SetTitle("P_{T}"); fhOmegaPriPt->GetYaxis()->SetTitle("dN/P_{T}"); outputContainer->Add(fhOmegaPriPt); } delete fhEtalon; return outputContainer; } //_______________________________________________________________ /// Print some relevant parameters set in the analysis. //_______________________________________________________________ void AliAnaOmegaToPi0Gamma::Print(const Option_t * /*opt*/) const { printf("**** Print %s %s ****\n", GetName(), GetTitle() ) ; AliAnaCaloTrackCorrBaseClass::Print(" "); printf("Omega->pi0+gamma->3gamma\n"); printf("Cuts at event level: \n"); printf("Bins of vertex Z: %d \n", fNVtxZBin); printf("Bins of centrality: %d \n",fNCentBin); printf("Bins of Reaction plane: %d\n",fNRpBin); printf("Cuts at AOD particle level:\n"); printf("Number of PID: %d \n", fNpid); printf("Number of DistToBadChannel cuts: %d\n", fNBadChDistBin); } //______________________________________________________ /// Do analysis, fill histograms. //______________________________________________________ void AliAnaOmegaToPi0Gamma::MakeAnalysisFillHistograms() { // Fill the MC AOD if needed first. //----------- //need to be further implemented AliStack * stack = 0x0; // TParticle * primary = 0x0; TClonesArray * mcparticles0 = 0x0; //TClonesArray * mcparticles1 = 0x0; AliAODMCParticle * aodprimary = 0x0; Int_t pdg=0; Double_t pt=0; Double_t eta=0; if(IsDataMC()) { if(GetReader()->ReadStack()) { stack = GetMCStack() ; if(!stack){ printf("AliAnaAcceptance::MakeAnalysisFillHistograms() - There is no stack!\n"); } else{ for(Int_t i=0 ; i<stack->GetNtrack(); i++){ TParticle * prim = stack->Particle(i) ; pdg = prim->GetPdgCode() ; eta=prim->Eta(); pt=prim->Pt(); if(TMath::Abs(eta)<0.5) { if(pdg==223) fhOmegaPriPt->Fill(pt, GetEventWeight()); } } } } else if(GetReader()->ReadAODMCParticles()){ //Get the list of MC particles mcparticles0 = GetReader()->GetAODMCParticles(); if(!mcparticles0 ) { if(GetDebug() > 0) printf("AliAnaAcceptance::MakeAnalysisFillHistograms() - Standard MCParticles not available!\n"); } else { for(Int_t i=0;i<mcparticles0->GetEntries();i++) { aodprimary =(AliAODMCParticle*)mcparticles0->At(i); pdg = aodprimary->GetPdgCode() ; eta=aodprimary->Eta(); pt=aodprimary->Pt(); if(TMath::Abs(eta)<0.5) { if(pdg==223) fhOmegaPriPt->Fill(pt, GetEventWeight()); } } }//mcparticles0 exists }//AOD MC Particles }// is data and MC //process event from AOD brach //extract pi0, eta and omega analysis Int_t iRun=(GetReader()->GetInputEvent())->GetRunNumber() ; if(IsBadRun(iRun)) return ; //vertex z Double_t vert[]={0,0,0} ; GetVertex(vert); Int_t curEventBin =0; Int_t ivtxzbin=(Int_t)TMath::Abs(vert[2])/10; if(ivtxzbin>=fNVtxZBin)return; //centrality Int_t currentCentrality = GetEventCentrality(); if(currentCentrality == -1) return; Int_t optCent = GetReader()->GetCentralityOpt(); Int_t icentbin=currentCentrality/(optCent/fNCentBin) ; //GetEventCentrality(); printf("-------------- %d %d %d ",currentCentrality, optCent, icentbin); //reaction plane Int_t irpbin=0; if(ivtxzbin==-1) return; curEventBin = ivtxzbin*fNCentBin*fNRpBin + icentbin*fNRpBin + irpbin; TClonesArray *aodGamma = (TClonesArray*) GetAODBranch(fInputAODGammaName); //photon array // TClonesArray *aodGamma = (TClonesArray *) GetReader()->GetOutputEvent()->FindListObject(fInputAODGammaName); //photon array Int_t nphotons =0; if(aodGamma) nphotons= aodGamma->GetEntries(); else return; fInputAODPi0 = (TClonesArray*)GetInputAODBranch(); //pi0 array Int_t npi0s = 0; if(fInputAODPi0) npi0s= fInputAODPi0 ->GetEntries(); else return; if(nphotons<3 || npi0s<1)return; //for pi0, eta and omega->pi0+gamma->3gamma reconstruction //reconstruction of omega(782)->pi0+gamma->3gamma //loop for pi0 and photon if(GetDebug() > 0) printf("omega->pi0+gamma->3gamma invariant mass analysis ! This event have %d photons and %d pi0 \n", nphotons, npi0s); for(Int_t i=0;i<npi0s;i++){ AliAODPWG4Particle * pi0 = (AliAODPWG4Particle*) (fInputAODPi0->At(i)) ; //pi0 TLorentzVector vpi0(pi0->Px(),pi0->Py(),pi0->Pz(),pi0->E()); Int_t lab1=pi0->GetCaloLabel(0); // photon1 from pi0 decay Int_t lab2=pi0->GetCaloLabel(1); // photon2 from pi0 decay //for omega->pi0+gamma, it needs at least three photons per event //Get the two decay photons from pi0 AliAODPWG4Particle * photon1 =0; AliAODPWG4Particle * photon2 =0; for(Int_t d1=0;d1<nphotons;d1++){ for(Int_t d2=0;d2<nphotons;d2++){ AliAODPWG4Particle * dp1 = (AliAODPWG4Particle*) (aodGamma->At(d1)); AliAODPWG4Particle * dp2 = (AliAODPWG4Particle*) (aodGamma->At(d2)); Int_t dlab1=dp1->GetCaloLabel(0); Int_t dlab2=dp2->GetCaloLabel(0); if(dlab1==lab1 && dlab2==lab2){ photon1=dp1; photon2=dp2; } else continue; } } //caculate the asy and dist of the two photon from pi0 decay TLorentzVector dph1(photon1->Px(),photon1->Py(),photon1->Pz(),photon1->E()); TLorentzVector dph2(photon2->Px(),photon2->Py(),photon2->Pz(),photon2->E()); Double_t pi0asy= TMath::Abs(dph1.E()-dph2.E())/(dph1.E()+dph2.E()); // Double_t phi1=dph1.Phi(); // Double_t phi2=dph2.Phi(); // Double_t eta1=dph1.Eta(); // Double_t eta2=dph2.Eta(); // Double_t pi0dist=TMath::Sqrt((phi1-phi2)*(phi1-phi2)+(eta1-eta2)*(eta1-eta2)); if(pi0->GetIdentifiedParticleType()==111 && nphotons>2 && npi0s && TMath::Abs(vpi0.M()-fPi0Mass)<fPi0MassWindow) { //pi0 candidates //avoid the double counting Int_t * dc1= new Int_t[nphotons]; Int_t * dc2= new Int_t[nphotons]; Int_t index1=0; Int_t index2=0; for(Int_t k=0;k<i;k++){ AliAODPWG4Particle * p3=(AliAODPWG4Particle*)(fInputAODPi0->At(k)); Int_t lab4=p3->GetCaloLabel(0); Int_t lab5=p3->GetCaloLabel(1); if(lab1==lab4){ dc1[index1]=lab5; index1++; } if(lab2==lab5){ dc2[index2]=lab4; index2++; } } //loop the pi0 with third gamma for(Int_t j=0;j<nphotons;j++){ AliAODPWG4Particle *photon3 = (AliAODPWG4Particle*) (aodGamma->At(j)); TLorentzVector dph3(photon3->Px(),photon3->Py(),photon3->Pz(),photon3->E()); Int_t lab3=photon3->GetCaloLabel(0); Double_t pi0gammapt=(vpi0+dph3).Pt(); Double_t pi0gammamass=(vpi0+dph3).M(); Double_t pi0OverOmegaPtRatio =vpi0.Pt()/pi0gammapt; Double_t gammaOverOmegaPtRatio= dph3.Pt()/pi0gammapt; //pi0, gamma pt cut if(pi0OverOmegaPtRatio>fPi0OverOmegaPtCut || gammaOverOmegaPtRatio<fGammaOverOmegaPtCut) continue; for(Int_t l=0;l<index1;l++) if(lab3==dc1[l]) lab3=-1; for(Int_t l=0;l<index2;l++) if(lab3==dc2[l]) lab3=-1; if(lab3>0 && lab3!=lab1 && lab3!=lab2){ for(Int_t ipid=0;ipid<fNpid;ipid++){ for(Int_t idist=0;idist<fNBadChDistBin;idist++){ Int_t index=curEventBin*fNpid*fNBadChDistBin+ipid*fNBadChDistBin+idist; if(photon1->IsPIDOK(ipid,AliCaloPID::kPhoton) && photon2->IsPIDOK(ipid,AliCaloPID::kPhoton) && photon3->IsPIDOK(ipid,AliCaloPID::kPhoton) && photon1->DistToBad()>=idist && photon2->DistToBad()>=idist && photon3->DistToBad()>=idist ){ //fill the histograms if(GetDebug() > 2) printf("Real: index %d pt %2.3f mass %2.3f \n", index, pi0gammapt, pi0gammamass); fRealOmega0[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.7) fRealOmega1[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.8) fRealOmega2[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); } } } } } delete []dc1; delete []dc2; if(GetDebug() > 0) printf("MixA: (r1_event1+r2_event1)+r3_event2 \n"); //------------------------- //background analysis //three background // --A (r1_event1+r2_event1)+r3_event2 Int_t nMixed = fEventsList[curEventBin]->GetSize(); for(Int_t im=0;im<nMixed;im++){ TClonesArray* ev2= (TClonesArray*) (fEventsList[curEventBin]->At(im)); for(Int_t mix1=0;mix1<ev2->GetEntries();mix1++){ AliAODPWG4Particle *mix1ph = (AliAODPWG4Particle*) (ev2->At(mix1)); TLorentzVector vmixph(mix1ph->Px(),mix1ph->Py(),mix1ph->Pz(),mix1ph->E()); Double_t pi0gammapt=(vpi0+vmixph).Pt(); Double_t pi0gammamass=(vpi0+vmixph).M(); Double_t pi0OverOmegaPtRatio =vpi0.Pt()/pi0gammapt; Double_t gammaOverOmegaPtRatio= vmixph.Pt()/pi0gammapt; //pi0, gamma pt cut if(pi0OverOmegaPtRatio>fPi0OverOmegaPtCut || gammaOverOmegaPtRatio<fGammaOverOmegaPtCut) continue; for(Int_t ipid=0;ipid<fNpid;ipid++){ for(Int_t idist=0;idist<fNBadChDistBin;idist++){ Int_t index=curEventBin*fNpid*fNBadChDistBin+ipid*fNBadChDistBin+idist; if(photon1->IsPIDOK(ipid,AliCaloPID::kPhoton)&& photon2->IsPIDOK(ipid,AliCaloPID::kPhoton)&& mix1ph->IsPIDOK(ipid,AliCaloPID::kPhoton) && photon1->DistToBad()>=idist && photon2->DistToBad()>=idist && mix1ph->DistToBad()>=idist ){ if(GetDebug() > 2) printf("MixA: index %d pt %2.3f mass %2.3f \n",index, pi0gammapt, pi0gammamass); //fill the histograms fMixAOmega0[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.7)fMixAOmega1[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.8)fMixAOmega2[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); //printf("mix A %d %2.2f \n", index, pi0gammamass); } } } } } } } // // --B (r1_event1+r2_event2)+r3_event2 // if(GetDebug() >0)printf("MixB: (r1_event1+r2_event2)+r3_event2 \n"); for(Int_t i=0;i<nphotons;i++){ AliAODPWG4Particle *ph1 = (AliAODPWG4Particle*) (aodGamma->At(i)); TLorentzVector vph1(ph1->Px(),ph1->Py(),ph1->Pz(),ph1->E()); //interrupt here................... //especially for EMCAL //we suppose the high pt clusters are overlapped pi0 for(Int_t j=i+1;j<nphotons;j++){ AliAODPWG4Particle *ph2 = (AliAODPWG4Particle*) (aodGamma->At(j)); TLorentzVector fakePi0, fakeOmega, vph; if(ph1->E() > fEOverlapCluster && ph1->E() > ph2->E()) { fakePi0.SetPxPyPzE(ph1->Px(),ph1->Py(),ph1->Pz(),TMath::Sqrt(ph1->Px()*ph1->Px()+ph1->Py()*ph1->Py()+ph1->Pz()*ph1->Pz()+0.135*0.135)); vph.SetPxPyPzE(ph2->Px(),ph2->Py(),ph2->Pz(),ph2->E()); } else if(ph2->E() > fEOverlapCluster && ph2->E() > ph1->E()) { fakePi0.SetPxPyPzE(ph2->Px(),ph2->Py(),ph2->Pz(),TMath::Sqrt(ph2->Px()*ph2->Px()+ph2->Py()*ph2->Py()+ph2->Pz()*ph2->Pz()+0.135*0.135)); vph.SetPxPyPzE(ph1->Px(), ph1->Py(),ph1->Pz(),ph1->E()); } else continue; fakeOmega=fakePi0+vph; for(Int_t ii=0;ii<fNCentBin;ii++){ fhFakeOmega[icentbin]->Fill(fakeOmega.Pt(), fakeOmega.M(), GetEventWeight()); } }//j //continue ................ Int_t nMixed = fEventsList[curEventBin]->GetSize(); for(Int_t ie=0;ie<nMixed;ie++){ TClonesArray* ev2= (TClonesArray*) (fEventsList[curEventBin]->At(ie)); for(Int_t mix1=0;mix1<ev2->GetEntries();mix1++){ AliAODPWG4Particle *ph2 = (AliAODPWG4Particle*) (ev2->At(mix1)); TLorentzVector vph2(ph2->Px(),ph2->Py(),ph2->Pz(),ph2->E()); Double_t pi0asy = TMath::Abs(vph1.E()-vph2.E())/(vph1.E()+vph2.E()); Double_t pi0mass=(vph1+vph2).M(); if(TMath::Abs(pi0mass-fPi0Mass)<fPi0MassWindow){//for pi0 selection for(Int_t mix2=(mix1+1);mix2<ev2->GetEntries();mix2++){ AliAODPWG4Particle *ph3 = (AliAODPWG4Particle*) (ev2->At(mix2)); TLorentzVector vph3(ph3->Px(),ph3->Py(),ph3->Pz(),ph3->E()); Double_t pi0gammapt=(vph1+vph2+vph3).Pt(); Double_t pi0gammamass=(vph1+vph2+vph3).M(); Double_t pi0OverOmegaPtRatio =(vph1+vph2).Pt()/pi0gammapt; Double_t gammaOverOmegaPtRatio= vph3.Pt()/pi0gammapt; //pi0, gamma pt cut if(pi0OverOmegaPtRatio>fPi0OverOmegaPtCut || gammaOverOmegaPtRatio<fGammaOverOmegaPtCut) continue; for(Int_t ipid=0;ipid<fNpid;ipid++){ for(Int_t idist=0;idist<fNBadChDistBin;idist++){ Int_t index=curEventBin*fNpid*fNBadChDistBin+ipid*fNBadChDistBin+idist; if(ph1->IsPIDOK(ipid,AliCaloPID::kPhoton) && ph2->IsPIDOK(ipid,AliCaloPID::kPhoton) && ph3->IsPIDOK(ipid,AliCaloPID::kPhoton) && ph1->DistToBad()>=idist && ph2->DistToBad()>=idist && ph3->DistToBad()>=idist ){ if(GetDebug() > 2) printf("MixB: index %d pt %2.3f mass %2.3f \n", index, pi0gammapt, pi0gammamass); //fill histograms fMixBOmega0[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.7) fMixBOmega1[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.8) fMixBOmega2[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); //printf("mix B %d %2.2f \n", index, pi0gammamass); } } } } // // --C (r1_event1+r2_event2)+r3_event3 // if(GetDebug() >0)printf("MixC: (r1_event1+r2_event2)+r3_event3\n"); for(Int_t je=(ie+1);je<nMixed;je++){ TClonesArray* ev3= (TClonesArray*) (fEventsList[curEventBin]->At(je)); for(Int_t mix3=0;mix3<ev3->GetEntries();mix3++){ AliAODPWG4Particle *ph3 = (AliAODPWG4Particle*) (ev3->At(mix3)); TLorentzVector vph3(ph3->Px(),ph3->Py(),ph3->Pz(),ph3->E()); Double_t pi0gammapt=(vph1+vph2+vph3).Pt(); Double_t pi0gammamass=(vph1+vph2+vph3).M(); Double_t pi0OverOmegaPtRatio =(vph1+vph2).Pt()/pi0gammapt; Double_t gammaOverOmegaPtRatio= vph3.Pt()/pi0gammapt; //pi0, gamma pt cut if(pi0OverOmegaPtRatio>fPi0OverOmegaPtCut || gammaOverOmegaPtRatio<fGammaOverOmegaPtCut) continue; for(Int_t ipid=0;ipid<fNpid;ipid++){ for(Int_t idist=0;idist<fNBadChDistBin;idist++){ Int_t index=curEventBin*fNpid*fNBadChDistBin+ipid*fNBadChDistBin+idist; if(ph1->IsPIDOK(ipid,AliCaloPID::kPhoton) && ph2->IsPIDOK(ipid,AliCaloPID::kPhoton) && ph3->IsPIDOK(ipid,AliCaloPID::kPhoton) && ph1->DistToBad()>=idist && ph2->DistToBad()>=idist && ph3->DistToBad()>=idist ){ if(GetDebug() > 2) printf("MixC: index %d pt %2.3f mass %2.3f \n", index, pi0gammapt, pi0gammamass); //fill histograms fMixCOmega0[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.7) fMixCOmega1[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); if(pi0asy<0.8) fMixCOmega2[index]->Fill(pi0gammapt, pi0gammamass, GetEventWeight()); //printf("mix C %d %2.2f \n", index, pi0gammamass); } } } } } } //for pi0 selecton } } } //event buffer TClonesArray *currentEvent = new TClonesArray(*aodGamma); if(currentEvent->GetEntriesFast()>0){ fEventsList[curEventBin]->AddFirst(currentEvent) ; currentEvent=0 ; if(fEventsList[curEventBin]->GetSize()>=GetNMaxEvMix()) { TClonesArray * tmp = (TClonesArray*) (fEventsList[curEventBin]->Last()) ; fEventsList[curEventBin]->RemoveLast() ; delete tmp ; } } else { delete currentEvent ; currentEvent=0 ; } } //____________________________________________________________ /// Read the histograms. /// For the finalization of the terminate analysis. //____________________________________________________________ void AliAnaOmegaToPi0Gamma::ReadHistograms(TList * outputList) { Int_t index = outputList->IndexOf(outputList->FindObject(GetAddedHistogramsStringToName()+"RealToPi0Gamma_Vz0C0Rp0Pid0Dist0")); Int_t ndim=fNVtxZBin*fNCentBin*fNRpBin*fNBadChDistBin*fNpid; if(!fRealOmega0) fRealOmega0 =new TH2F*[ndim]; if(!fMixAOmega0) fMixAOmega0 =new TH2F*[ndim]; if(!fMixBOmega0) fMixBOmega0 =new TH2F*[ndim]; if(!fMixCOmega0) fMixCOmega0 =new TH2F*[ndim]; if(!fRealOmega1) fRealOmega1 =new TH2F*[ndim]; if(!fMixAOmega1) fMixAOmega1 =new TH2F*[ndim]; if(!fMixBOmega1) fMixBOmega1 =new TH2F*[ndim]; if(!fMixCOmega1) fMixCOmega1 =new TH2F*[ndim]; if(!fRealOmega2) fRealOmega2 =new TH2F*[ndim]; if(!fMixAOmega2) fMixAOmega2 =new TH2F*[ndim]; if(!fMixBOmega2) fMixBOmega2 =new TH2F*[ndim]; if(!fMixCOmega2) fMixCOmega2 =new TH2F*[ndim]; for(Int_t i=0;i<fNVtxZBin;i++) { for(Int_t j=0;j<fNCentBin;j++) { for(Int_t k=0;k<fNRpBin;k++) { //at event level Int_t idim=i*fNCentBin*fNRpBin+j*fNRpBin+k; for(Int_t ipid=0;ipid<fNpid;ipid++) { for(Int_t idist=0;idist<fNBadChDistBin;idist++) { //at particle Int_t ind=idim*fNpid*fNBadChDistBin+ipid*fNBadChDistBin+idist; fRealOmega0[ind]= (TH2F*) outputList->At(index++); fMixAOmega0[ind]= (TH2F*) outputList->At(index++); fMixBOmega0[ind]= (TH2F*) outputList->At(index++); fMixCOmega0[ind]= (TH2F*) outputList->At(index++); fRealOmega1[ind]= (TH2F*) outputList->At(index++); fMixAOmega1[ind]= (TH2F*) outputList->At(index++); fMixBOmega1[ind]= (TH2F*) outputList->At(index++); fMixCOmega1[ind]= (TH2F*) outputList->At(index++); fRealOmega2[ind]= (TH2F*) outputList->At(index++); fMixAOmega2[ind]= (TH2F*) outputList->At(index++); fMixBOmega2[ind]= (TH2F*) outputList->At(index++); fMixCOmega2[ind]= (TH2F*) outputList->At(index++); } } } } } if(IsDataMC()) { fhOmegaPriPt = (TH1F*) outputList->At(index++); } } //_______________________________________________________ /// Do some calculations and plots from the final histograms. //_______________________________________________________ void AliAnaOmegaToPi0Gamma::Terminate(TList * outputList) { if(GetDebug() >= 0) printf("AliAnaOmegaToPi0Gamma::Terminate() \n"); ReadHistograms(outputList); const Int_t buffersize = 255; char cvs1[buffersize]; snprintf(cvs1, buffersize, "Neutral_%s_IVM",fInputAODGammaName.Data()); TCanvas * cvsIVM = new TCanvas(cvs1, cvs1, 400, 10, 600, 700) ; cvsIVM->Divide(2, 2); cvsIVM->cd(1); char dec[buffersize]; snprintf(dec,buffersize,"h2Real_%s",fInputAODGammaName.Data()); TH2F * h2Real= (TH2F*)fRealOmega0[0]->Clone(dec); h2Real->GetXaxis()->SetRangeUser(4,6); TH1F * hRealOmega = (TH1F*) h2Real->ProjectionY(); hRealOmega->SetTitle("RealPi0Gamma 4<pt<6"); hRealOmega->SetLineColor(2); hRealOmega->Draw(); cvsIVM->cd(2); snprintf(dec,buffersize,"hMixA_%s",fInputAODGammaName.Data()); TH2F *h2MixA= (TH2F*)fMixAOmega0[0]->Clone(dec); h2MixA->GetXaxis()->SetRangeUser(4,6); TH1F * hMixAOmega = (TH1F*) h2MixA->ProjectionY(); hMixAOmega->SetTitle("MixA 4<pt<6"); hMixAOmega->SetLineColor(2); hMixAOmega->Draw(); cvsIVM->cd(3); snprintf(dec,buffersize,"hMixB_%s",fInputAODGammaName.Data()); TH2F * h2MixB= (TH2F*)fMixBOmega0[0]->Clone(dec); h2MixB->GetXaxis()->SetRangeUser(4,6); TH1F * hMixBOmega = (TH1F*) h2MixB->ProjectionY(); hMixBOmega->SetTitle("MixB 4<pt<6"); hMixBOmega->SetLineColor(2); hMixBOmega->Draw(); cvsIVM->cd(4); snprintf(dec,buffersize,"hMixC_%s",fInputAODGammaName.Data()); TH2F *h2MixC= (TH2F*)fMixCOmega0[0]->Clone(dec); h2MixC->GetXaxis()->SetRangeUser(4,6); TH1F * hMixCOmega = (TH1F*) h2MixC->ProjectionY(); hMixCOmega->SetTitle("MixC 4<pt<6"); hMixCOmega->SetLineColor(2); hMixCOmega->Draw(); char eps[buffersize]; snprintf(eps,buffersize,"CVS_%s_IVM.eps",fInputAODGammaName.Data()); cvsIVM->Print(eps); cvsIVM->Modified(); }
DarrenPaulWright/hord
bench/Schema/parse/checkTypeDef.bench.js
<reponame>DarrenPaulWright/hord import { benchSettings } from 'karma-webpack-bundle'; import checkSchemaType from '../../../src/Schema/parse/checkTypeDef.js'; suite('checkSchemaType', () => { let sandbox = 0; benchmark('string', () => { sandbox = checkSchemaType(String, false); }, benchSettings); benchmark('array empty', () => { sandbox = checkSchemaType([], false); }, benchSettings); benchmark('array two items', () => { sandbox = checkSchemaType([String, null], false); }, benchSettings); benchmark('object', () => { sandbox = checkSchemaType({ type: [String, null] }, true); }, benchSettings); benchmark('object, enforce', () => { sandbox = checkSchemaType({ enforce: () => { } }, true); }, benchSettings); });
ScalablyTyped/SlinkyTyped
a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/ec2Mod/SpotCapacityRebalance.scala
package typingsSlinky.awsSdk.ec2Mod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait SpotCapacityRebalance extends StObject { /** * The replacement strategy to use. Only available for fleets of type maintain. You must specify a value, otherwise you get an error. To allow Spot Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for a Spot Instance in the fleet, specify launch. When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for all instances while they are running. */ var ReplacementStrategy: js.UndefOr[typingsSlinky.awsSdk.ec2Mod.ReplacementStrategy] = js.native } object SpotCapacityRebalance { @scala.inline def apply(): SpotCapacityRebalance = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[SpotCapacityRebalance] } @scala.inline implicit class SpotCapacityRebalanceMutableBuilder[Self <: SpotCapacityRebalance] (val x: Self) extends AnyVal { @scala.inline def setReplacementStrategy(value: ReplacementStrategy): Self = StObject.set(x, "ReplacementStrategy", value.asInstanceOf[js.Any]) @scala.inline def setReplacementStrategyUndefined: Self = StObject.set(x, "ReplacementStrategy", js.undefined) } }
naskya/testcase-generator
verify/checker/abc219/f.py
<reponame>naskya/testcase-generator<gh_stars>1-10 def main() -> None: S = input() K = int(input()) assert all(S_i in ('L', 'R', 'U', 'D') for S_i in S) assert 1 <= len(S) <= 100 assert 1 <= K <= 10**12 if __name__ == '__main__': main()
GoldSubmarine/submarine-admin
src/main/java/com/htnova/system/tool/mapper/QuartzLogMapper.java
package com.htnova.system.tool.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.htnova.system.tool.dto.QuartzLogDto; import com.htnova.system.tool.entity.QuartzLog; import java.util.List; import org.apache.ibatis.annotations.Param; public interface QuartzLogMapper extends BaseMapper<QuartzLog> { IPage<QuartzLog> findPage(IPage<Void> xPage, @Param("quartzLogDto") QuartzLogDto quartzLogDto); List<QuartzLog> findList(@Param("quartzLogDto") QuartzLogDto quartzLogDto); }
Splyse/nos-client
src/renderer/account/actions/balanceWithPricesActions.js
<gh_stars>100-1000 import { createActions } from 'spunky'; import { reduce } from 'lodash'; import CoinGecko from 'coingecko-api'; import getBalances from 'shared/util/getBalances'; const coinGeckoClient = new CoinGecko(); function mapPrices(tickers) { return reduce( tickers, (mapping, ticker) => ({ ...mapping, [ticker.symbol.toUpperCase()]: ticker.current_price }), {} ); } async function getBalanceWithPrices({ currency, net, address }) { const balances = await getBalances({ net, address }); const coinListResult = await coinGeckoClient.coins.list(); if (!coinListResult.success) { throw new Error(coinListResult.message); } const balancesArray = Object.keys(balances).map((key) => balances[key]); const ids = coinListResult.data.reduce((accum, coin) => { if (balancesArray.find((balance) => balance.name.toLowerCase() === coin.name.toLowerCase())) { accum.push(coin.id); } return accum; }, []); const coinPricesResult = await coinGeckoClient.coins.markets({ vs_currency: currency.toLowerCase(), ids }); if (!coinPricesResult.success) { throw new Error(coinPricesResult.message); } const prices = mapPrices(coinPricesResult.data); return { balances, prices }; } export const ID = 'balacewithprices'; export default createActions(ID, ({ currency, net, address }) => { return () => getBalanceWithPrices({ currency, net, address }); });
AsenLins/tinymce5-ice-plugin
src/lib/tinymce/js/tinymce/classes/Shortcuts.js
<filename>src/lib/tinymce/js/tinymce/classes/Shortcuts.js /** * Shortcuts.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Contains all logic for handling of keyboard shortcuts. */ define("tinymce/Shortcuts", [ "tinymce/util/Tools", "tinymce/Env" ], function(Tools, Env) { var each = Tools.each, explode = Tools.explode; var keyCodeLookup = { "f9": 120, "f10": 121, "f11": 122 }; return function(editor) { var self = this, shortcuts = {}; editor.on('keyup keypress keydown', function(e) { if (e.altKey || e.ctrlKey || e.metaKey) { each(shortcuts, function(shortcut) { var ctrlState = Env.isMac ? e.metaKey : e.ctrlKey; if (shortcut.ctrl != ctrlState || shortcut.alt != e.altKey || shortcut.shift != e.shiftKey) { return; } if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) { e.preventDefault(); if (e.type == "keydown") { shortcut.func.call(shortcut.scope); } return true; } }); } }); /** * Adds a keyboard shortcut for some command or function. * * @method addShortcut * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. * @param {String} desc Text description for the command. * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. * @param {Object} sc Optional scope to execute the function in. * @return {Boolean} true/false state if the shortcut was added or not. */ self.add = function(pattern, desc, cmdFunc, scope) { var cmd; cmd = cmdFunc; if (typeof(cmdFunc) === 'string') { cmdFunc = function() { editor.execCommand(cmd, false, null); }; } else if (cmdFunc.length) { cmdFunc = function() { editor.execCommand(cmd[0], cmd[1], cmd[2]); }; } each(explode(pattern.toLowerCase()), function(pattern) { var shortcut = { func: cmdFunc, scope: scope || editor, desc: editor.translate(desc), alt: false, ctrl: false, shift: false }; each(explode(pattern, '+'), function(value) { switch (value) { case 'alt': case 'ctrl': case 'shift': shortcut[value] = true; break; default: shortcut.charCode = value.charCodeAt(0); shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0); } }); shortcuts[ (shortcut.ctrl ? 'ctrl' : '') + ',' + (shortcut.alt ? 'alt' : '') + ',' + (shortcut.shift ? 'shift' : '') + ',' + shortcut.keyCode ] = shortcut; }); return true; }; }; });
ksoichiro/spring-boot-practice
contents/20160821-querydsl-join/src/main/java/com/example/spring/service/EmployeeService.java
package com.example.spring.service; import com.example.spring.domain.Employee; import com.example.spring.domain.QEmployee; import com.mysema.query.jpa.JPQLQuery; import com.mysema.query.jpa.impl.JPAQuery; import com.mysema.query.types.Path; import com.mysema.query.types.Predicate; import com.mysema.query.types.path.PathBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.support.Querydsl; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import java.util.Collections; import java.util.List; @Service @Slf4j public class EmployeeService { @Autowired private EntityManager entityManager; public Page<Employee> findAll(Pageable pageable) { Predicate predicate = QEmployee.employee.name.startsWith("e"); PathBuilder<Employee> builder = new PathBuilder<>(Employee.class, QEmployee.employee.getMetadata()); Querydsl querydsl = new Querydsl(entityManager, builder); JPQLQuery countQuery = createQuery(predicate); JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate)); Path<Employee> path = QEmployee.employee; Long total = countQuery.count(); List<Employee> content = total > pageable.getOffset() ? query.list(path) : Collections.<Employee>emptyList(); return new PageImpl<>(content, pageable, total); } private JPAQuery createQuery(Predicate predicate) { return new JPAQuery(entityManager) .from(QEmployee.employee) .leftJoin(QEmployee.employee.department) .where(predicate); } }
deepcloudlabs/dcl202-2021-mar-01
core-banking/src/com/example/banking/questions/q1/moon/E.java
<gh_stars>0 package com.example.banking.questions.q1.moon; import com.example.banking.questions.q1.earth.A; public class E { public void f(A a) { // a.m_private = 1; // a.m_protected = 2; // a.m_default = 3; a.m_public = 4; } }
perfectsense/gyro-azure-provider
src/main/java/gyro/azure/dns/PtrRecordSetResource.java
/* * Copyright 2019, Perfect Sense, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gyro.azure.dns; import gyro.azure.AzureResource; import gyro.azure.Copyable; import gyro.core.GyroUI; import gyro.core.resource.Id; import gyro.core.resource.Output; import gyro.core.resource.Resource; import gyro.core.Type; import gyro.core.resource.Updatable; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.dns.DnsRecordSet; import com.microsoft.azure.management.dns.DnsZone; import com.microsoft.azure.management.dns.PtrRecordSet; import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.PtrRecordSetBlank; import com.microsoft.azure.management.dns.DnsRecordSet.UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable; import gyro.core.scope.State; import gyro.core.validation.Required; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Creates an PTR Record Set. * * Example * ------- * * .. code-block:: gyro * * azure::ptr-record-set * name: "ptrrecexample" * target-domain-names: ["domain1.com", "domain2.com"] * ttl: 3 * dns-zone: $(azure::dns-zone dns-zone-example-zones) * end */ @Type("ptr-record-set") public class PtrRecordSetResource extends AzureResource implements Copyable<PtrRecordSet> { private DnsZoneResource dnsZone; private Map<String, String> metadata; private String name; private Set<String> targetDomainNames; private Long ttl; private String id; /** * The DNS Zone where the Ptr Record Set resides. */ @Required public DnsZoneResource getDnsZone() { return dnsZone; } public void setDnsZone(DnsZoneResource dnsZone) { this.dnsZone = dnsZone; } /** * The metadata for the Ptr Record Set. */ @Updatable public Map<String, String> getMetadata() { if (metadata == null) { metadata = new HashMap<>(); } return metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } /** * The name of the Ptr Record Set. */ @Required public String getName() { return name; } public void setName(String name) { this.name = name; } /** * The domain names associated with the Ptr Record Set. */ @Required @Updatable public Set<String> getTargetDomainNames() { if (targetDomainNames == null) { targetDomainNames = new HashSet<>(); } return targetDomainNames; } public void setTargetDomainNames(Set<String> targetDomainNames) { this.targetDomainNames = targetDomainNames; } /** * The Time To Live in Seconds for the Ptr Record Set in the set. */ @Required @Updatable public Long getTtl() { return ttl; } public void setTtl(Long ttl) { this.ttl = ttl; } /** * The ID of the Ptr Record Set. */ @Id @Output public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public void copyFrom(PtrRecordSet ptrRecordSet) { setMetadata(ptrRecordSet.metadata()); setName(ptrRecordSet.name()); setTargetDomainNames(new HashSet<>(ptrRecordSet.targetDomainNames())); setTtl(ptrRecordSet.timeToLive()); setDnsZone(findById(DnsZoneResource.class, ptrRecordSet.parent().id())); setId(ptrRecordSet.id()); } @Override public boolean refresh() { Azure client = createClient(); PtrRecordSet ptrRecordSet = client.dnsZones().getById(getDnsZone().getId()).ptrRecordSets().getByName(getName()); if (ptrRecordSet == null) { return false; } copyFrom(ptrRecordSet); return true; } public void create(GyroUI ui, State state) { Azure client = createClient(); PtrRecordSetBlank<DnsZone.Update> definePtrRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().definePtrRecordSet(getName()); WithPtrRecordTargetDomainNameOrAttachable<DnsZone.Update> createPtrRecordSet = null; for (String targetDomainName : getTargetDomainNames()) { createPtrRecordSet = definePtrRecordSet.withTargetDomainName(targetDomainName); } if (getTtl() != null) { createPtrRecordSet.withTimeToLive(getTtl()); } for (Map.Entry<String,String> e : getMetadata().entrySet()) { createPtrRecordSet.withMetadata(e.getKey(), e.getValue()); } DnsZone.Update attach = createPtrRecordSet.attach(); DnsZone dnsZone = attach.apply(); copyFrom(dnsZone.ptrRecordSets().getByName(getName())); } @Override public void update(GyroUI ui, State state, Resource current, Set<String> changedProperties) { Azure client = createClient(); DnsRecordSet.UpdatePtrRecordSet updatePtrRecordSet = client.dnsZones().getById(getDnsZone().getId()).update().updatePtrRecordSet(getName()); if (getTtl() != null) { updatePtrRecordSet.withTimeToLive(getTtl()); } PtrRecordSetResource oldRecord = (PtrRecordSetResource) current; List<String> addNames = new ArrayList<>(getTargetDomainNames()); addNames.removeAll(oldRecord.getTargetDomainNames()); List<String> removeNames = new ArrayList<>(oldRecord.getTargetDomainNames()); removeNames.removeAll(getTargetDomainNames()); for (String addDomain : addNames) { updatePtrRecordSet.withTargetDomainName(addDomain); } for (String remDomain : removeNames) { updatePtrRecordSet.withoutTargetDomainName(remDomain); } Map<String, String> pendingMetaData = getMetadata(); Map<String, String> currentMetaData = oldRecord.getMetadata(); MapDifference<String, String> diff = Maps.difference(currentMetaData, pendingMetaData); //add new metadata diff.entriesOnlyOnRight().forEach(updatePtrRecordSet::withMetadata); //delete removed metadata diff.entriesOnlyOnLeft().keySet().forEach(updatePtrRecordSet::withoutMetadata); //update changed keys for (Map.Entry<String, MapDifference.ValueDifference<String>> ele : diff.entriesDiffering().entrySet()) { MapDifference.ValueDifference<String> disc = ele.getValue(); updatePtrRecordSet.withoutMetadata(ele.getKey()); updatePtrRecordSet.withMetadata(ele.getKey(), disc.rightValue()); } DnsZone.Update parent = updatePtrRecordSet.parent(); DnsZone dnsZone = parent.apply(); copyFrom(dnsZone.ptrRecordSets().getByName(getName())); } @Override public void delete(GyroUI ui, State state) { Azure client = createClient(); client.dnsZones().getById(getDnsZone().getId()).update().withoutPtrRecordSet(getName()).apply(); } }
jeroen-dhollander/python-paginator
more_or_less/buffered_input.py
<filename>more_or_less/buffered_input.py from .input import Input import queue class BufferedInput(Input): ''' Input object that allows you to put back characters (which are then returned by the next call to 'get_character') ''' def __init__(self, input): self._buffered_characters = queue.Queue() self._input = input def prompt(self, message): return self._input.prompt(message) def get_character(self, message): if not self._buffered_characters.empty(): return self._buffered_characters.get() return self._input.get_character(message) def put_back(self, character): self._buffered_characters.put(character)
AdityaSrikanth/core
server/app/model/composite-blueprints/composite-blueprints.js
<gh_stars>1-10 /* Copyright [2016] [Relevance Lab] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var mongoose = require('mongoose'); var util = require('util'); var Schema = mongoose.Schema; var mongoosePaginate = require('mongoose-paginate'); var logger = require('_pr/logger')(module); //@TODO Unique validation for name to be added //@TODO Get methods to be consolidated var CompositeBlueprintSchema = new Schema({ name: { type: String, required: true, trim: true }, organizationId: { type: String, required: true, trim: false }, businessGroupId: { type: String, required: true, trim: false }, projectId: { type: String, required: true, trim: false }, cloudProviderType:{ type: String, required: false, trim: false }, blueprints: [{ type: Schema.Types.Mixed, _id: false }], isDeleted: { type: Boolean, required: true, default: false } }); CompositeBlueprintSchema.plugin(mongoosePaginate); CompositeBlueprintSchema.statics.createNew = function createNew(data, callback) { var self = this; var compositeBlueprint = new self(data); compositeBlueprint.save(function (err, data) { if (err) { return callback(err); } else { return callback(null, compositeBlueprint); } }); }; CompositeBlueprintSchema.statics.getById = function getById(compositeBlueprintId, callback) { this.find( {'_id': compositeBlueprintId, 'isDeleted': false }, function(err, compositeBlueprints) { if (err) { return callback(err, null); } else if(compositeBlueprints && compositeBlueprints.length > 0) { return callback(null, compositeBlueprints[0]); } else { return callback(null, null); } } ); }; CompositeBlueprintSchema.statics.countByQuery = function countByQuery(query, callback) { query.isDeleted = false; this.count( query, function(err, resultCount) { if (err) { return callback(err, null); } else { return callback(null, resultCount); } } ); }; CompositeBlueprintSchema.statics.getAll = function getAll(filter, callback) { filter.queryObj.isDeleted = false; this.paginate(filter.queryObj, filter.options, function(err, compositeBlueprints) { if (err) { logger.error(err); return callback(err); } else { return callback(null, compositeBlueprints); } } ); }; CompositeBlueprintSchema.statics.deleteById = function deleteById(compositeBlueprintId, callback) { this.update( {'_id': compositeBlueprintId}, { $set: {isDeleted: true} }, function(err, compositeBlueprint) { if(err) { logger.error(err); return callback(err, null); } else { return callback(null, true); } } ) }; CompositeBlueprintSchema.statics.deleteAll = function deleteAll(compositeBlueprintIds, callback) { this.update( {'_id': {$in: compositeBlueprintIds}}, { $set: {isDeleted: true}}, {multi: true}, function(err, compositeBlueprintIds) { if(err) { logger.error(err); return callback(err, null); } else { return callback(null, true); } } ) }; CompositeBlueprintSchema.statics.updateById = function updateById(compositeBlueprintId, fields, callback) { this.update( {_id: compositeBlueprintId}, fields, function(err, result) { if (err) { return callback(err, null); } else if(result.ok == 1 && result.n == 1) { return callback(null, true); } } ); }; CompositeBlueprintSchema.statics.getCompositeBlueprintByOrgBgProject = function getCompositeBlueprintByOrgBgProject(query, callback) { query.queryObj.isDeleted = false; this.paginate(query.queryObj, query.options, function(err, compositeBlueprints) { if (err) { logger.error("Failed to getCompositeBlueprintByOrgBgProject", err); callback(err, null); return; } callback(null, compositeBlueprints); }); }; var CompositeBlueprints = mongoose.model('compositeBlueprints', CompositeBlueprintSchema); module.exports = CompositeBlueprints;
Ebury/chameleon-components
src/components/ec-phone-number-input/ec-phone-number-input.spec.js
import { mount, createLocalVue } from '@vue/test-utils'; import EcPhoneNumberInput from './ec-phone-number-input.vue'; import { withMockedConsole } from '../../../tests/utils/console'; jest.mock('svg-country-flags/png100px/gb.png', () => '/my-path/gb.png'); jest.mock('svg-country-flags/png100px/jm.png', () => '/my-path/jm.png'); jest.mock('svg-country-flags/png100px/es.png', () => '/my-path/es.png'); const countries = [ { areaCode: '+44', text: 'United Kingdom', countryCode: 'GB' }, { areaCode: '+1 658', text: 'Jamaica', countryCode: 'JM' }, { areaCode: '+34', text: 'Spain', countryCode: 'ES' }, { areaCode: '+204', text: 'New Country', countryCode: 'XX' }, { areaCode: '+204', text: 'New Country', countryCode: null }, ]; describe('EcPhoneNumberInput', () => { function mountPhoneNumberInput(props) { return mount(EcPhoneNumberInput, { propsData: { countries, value: {}, ...props, }, }); } function mountPhoneNumberInputAsTemplate(template, props, wrapperComponentOpts, mountOpts) { const localVue = createLocalVue(); const Component = localVue.extend({ components: { EcPhoneNumberInput }, template, ...wrapperComponentOpts, }); return mount(Component, { localVue, propsData: { ...props }, ...mountOpts, }); } it('should render properly', () => { const wrapper = mountPhoneNumberInput(); expect(wrapper.element).toMatchSnapshot(); }); describe(':props', () => { it('should render with a label', () => { const wrapper = mountPhoneNumberInput({ label: 'Phone number input label' }); expect(wrapper.element).toMatchSnapshot(); }); it('should render with a note', () => { const wrapper = mountPhoneNumberInput({ note: 'Phone number input note' }); expect(wrapper.element).toMatchSnapshot(); }); it('should render with a bottom note', () => { const wrapper = mountPhoneNumberInput({ bottomNote: 'Phone number input bottom note' }); expect(wrapper.findByDataTest('ec-phone-number-input__bottom-note').element).toMatchSnapshot(); }); it('should render with a warning', () => { const wrapper = mountPhoneNumberInput({ bottomNote: 'Phone number input bottom note', isWarning: true, }); expect(wrapper.findByDataTest('ec-phone-number-input__bottom-note').element).toMatchSnapshot(); }); it('should render with a warning tooltip', () => { const warningTooltipMessage = 'Warning tooltip message'; const wrapper = mountPhoneNumberInput({ bottomNote: 'Phone number input bottom note', isWarning: true, warningTooltipMessage, }); expect(wrapper.findByDataTest('ec-phone-number-input__bottom-note').element).toMatchSnapshot(); expect(wrapper.findByDataTest('ec-phone-number-input__warning-tooltip').attributes('data-ec-tooltip-mock-content')).toBe(warningTooltipMessage); }); it('should render with an error message', () => { const wrapper = mountPhoneNumberInput({ bottomNote: 'Phone number input bottom note', errorMessage: 'Random error message', }); expect(wrapper.findByDataTest('ec-phone-number-input__bottom-note').exists()).toBeFalsy(); expect(wrapper.findByDataTest('ec-phone-number-input__error-text').exists()).toBeTruthy(); expect(wrapper.element).toMatchSnapshot(); }); it('should render with an error tooltip', () => { const errorTooltipMessage = 'Error tooltip message'; const wrapper = mountPhoneNumberInput({ bottomNote: 'Phone number input bottom note', errorMessage: 'Random error message', errorTooltipMessage, }); expect(wrapper.findByDataTest('ec-phone-number-input__bottom-note').element).toMatchSnapshot(); expect(wrapper.findByDataTest('ec-phone-number-input__error-tooltip').attributes('data-ec-tooltip-mock-content')).toBe(errorTooltipMessage); }); it('should render in a loading state', () => { const wrapper = mountPhoneNumberInput({ areCountriesLoading: true }); expect(wrapper.findByDataTest('ec-popover-dropdown-search').element).toMatchSnapshot(); }); it('should render in a disabled state', () => { const wrapper = mountPhoneNumberInput({ isDisabled: true }); expect(wrapper.element).toMatchSnapshot(); }); it('should render with a disabled tooltip message', () => { const disabledTooltipMessage = 'Disabled tooltip message'; const wrapper = mountPhoneNumberInput({ isDisabled: true, disabledTooltipMessage, }); expect(wrapper.element).toMatchSnapshot(); expect(wrapper.findByDataTest('ec-phone-number-input__input-group').attributes('data-ec-tooltip-mock-content')).toBe(disabledTooltipMessage); }); it('should render with a sensitive class when isSensitive prop is set to true', () => { const wrapper = mountPhoneNumberInput({ isSensitive: true }); expect(wrapper.element).toMatchSnapshot(); }); it('should render with a country placeholder', () => { const countryPlaceholder = '+44'; const wrapper = mountPhoneNumberInput({ countryPlaceholder }); expect(wrapper.findByDataTest('ec-phone-number-input__countries').attributes('placeholder')).toBe(countryPlaceholder); }); it('should render with a number placeholder', () => { const phoneNumberPlaceholder = 'Phone Number'; const wrapper = mountPhoneNumberInput({ phoneNumberPlaceholder }); expect(wrapper.findByDataTest('ec-phone-number-input__number').attributes('placeholder')).toBe(phoneNumberPlaceholder); }); it('should render with a search field', async () => { const wrapper = mountPhoneNumberInput({ isSearchEnabled: true }); await wrapper.findByDataTest('ec-phone-number-input__countries').trigger('mousedown'); expect(wrapper.findByDataTest('ec-dropdown-search__search-input').element).toMatchSnapshot(); }); it('should accept a custom search field text', async () => { const wrapper = mountPhoneNumberInput({ isSearchEnabled: true, searchCountryPlaceholder: 'Search calling code', }); await wrapper.findByDataTest('ec-phone-number-input__countries').trigger('mousedown'); expect(wrapper.findByDataTest('ec-dropdown-search__search-input').element).toMatchSnapshot(); }); it('should accept a custom "no countries" search result text', async () => { const wrapper = mountPhoneNumberInput({ isSearchEnabled: true, searchCountryPlaceholder: 'Search calling code', noCountriesText: 'No country found', }); await wrapper.findByDataTest('ec-phone-number-input__countries').trigger('mousedown'); await wrapper.findByDataTest('ec-dropdown-search__search-input').setValue('Norway'); expect(wrapper.findByDataTest('ec-dropdown-search__item-list').element).toMatchSnapshot(); }); it.each([ ['modal', false], ['tooltip', false], ['notification', false], ['level-1', false], ['level-2', false], ['level-3', false], ['random', true], ])('should validate if the level prop("%s") is on the allowed array of strings', (str, error) => { if (error) { withMockedConsole((errorSpy) => { mountPhoneNumberInput({ level: str }); expect(errorSpy).toHaveBeenCalledTimes(3); // this is the test for the phone number input field expect(errorSpy.mock.calls[0][0]).toContain('Invalid prop: custom validator check failed for prop "level"'); // this is the test for the dropdown expect(errorSpy.mock.calls[1][0]).toContain('Invalid prop: custom validator check failed for prop "level"'); // this is the test for the dropdownsearch expect(errorSpy.mock.calls[2][0]).toContain('Invalid prop: custom validator check failed for prop "level"'); }); } else { const wrapper = mountPhoneNumberInput({ level: str }); expect(wrapper.findByDataTest('ec-popover-dropdown-search').attributes('level')).toBe(str); } }); }); describe('@events', () => { it('should emit change events when an item is selected', async () => { const wrapper = mountPhoneNumberInput(); await selectItem(wrapper, 1); expect(wrapper.emitted('change').length).toEqual(1); expect(wrapper.emitted('focus').length).toEqual(1); expect(wrapper.emitted('value-change').length).toEqual(1); expect(wrapper.emitted('country-change').length).toEqual(1); await selectItem(wrapper, 2); expect(wrapper.emitted('change').length).toEqual(2); expect(wrapper.emitted('focus').length).toEqual(2); expect(wrapper.emitted('value-change').length).toEqual(2); expect(wrapper.emitted('country-change').length).toEqual(2); }); it('should emit value-change event when number is set', async () => { const wrapper = mountPhoneNumberInput(); await wrapper.findByDataTest('ec-phone-number-input__number').setValue('11'); await wrapper.findByDataTest('ec-phone-number-input__number').trigger('change'); expect(wrapper.emitted('change').length).toEqual(1); expect(wrapper.emitted('phone-number-change').length).toEqual(1); expect(wrapper.emitted('value-change').length).toEqual(1); await wrapper.findByDataTest('ec-phone-number-input__number').setValue('111'); await wrapper.findByDataTest('ec-phone-number-input__number').trigger('change'); expect(wrapper.emitted('change').length).toEqual(2); expect(wrapper.emitted('phone-number-change').length).toEqual(2); expect(wrapper.emitted('value-change').length).toEqual(2); }); }); describe('v-model', () => { it('should use the v-model with the country and emit the changes', async () => { const wrapper = mountPhoneNumberInputAsTemplate( '<ec-phone-number-input :countries="countries" v-model="value" />', {}, { data() { return { countries, value: { country: {}, phoneNumber: '', }, }; }, }, ); await selectItem(wrapper, 0); expect(wrapper.vm.value.country).toEqual(countries[0]); await selectItem(wrapper, 1); expect(wrapper.vm.value.country).toEqual(countries[1]); }); it('should preselect the country item in the dropdown and the number in the input from the v-model', () => { const wrapper = mountPhoneNumberInputAsTemplate( '<ec-phone-number-input :countries="countries" v-model="value" />', {}, { data() { return { countries, value: { country: countries[0], phoneNumber: '123456789', }, }; }, }, ); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected-area-code').text()).toBe(countries[0].areaCode); expect(wrapper.findByDataTest('ec-phone-number-input__number').element.value).toBe('123456789'); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected').element).toMatchSnapshot(); }); it('should preselect a country item from the v-model and do not show the image if does not exist', () => { const wrapper = mountPhoneNumberInputAsTemplate( '<ec-phone-number-input :countries="countries" v-model="value" />', {}, { data() { return { countries, value: { country: countries[3], phoneNumber: '123456789', }, }; }, }, ); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected-area-code').text()).toBe(countries[3].areaCode); expect(wrapper.findByDataTest('ec-phone-number-input__number').element.value).toBe('123456789'); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected').element).toMatchSnapshot(); }); it('should preselect a country item from the v-model and do not show the image if country code is not set', () => { const wrapper = mountPhoneNumberInputAsTemplate( '<ec-phone-number-input :countries="countries" v-model="value" />', {}, { data() { return { countries, value: { country: countries[4], phoneNumber: '123456789', }, }; }, }, ); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected-area-code').text()).toBe(countries[4].areaCode); expect(wrapper.findByDataTest('ec-phone-number-input__number').element.value).toBe('123456789'); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected').element).toMatchSnapshot(); }); it('should preselect the country item in the dropdown and the number in the input from the v-model AND mask them when "is-masked" prop is true', () => { const wrapper = mountPhoneNumberInputAsTemplate( '<ec-phone-number-input :is-masked="true" :countries="countries" v-model="value" />', {}, { data() { return { countries, value: { country: countries[1], phoneNumber: '123456789', }, }; }, }, ); expect(wrapper.findByDataTest('ec-phone-number-input__countries-selected-area-code').text()).toBe(countries[1].areaCode); expect(wrapper.findByDataTest('ec-phone-number-input__number').element.value).toBe('*******89'); }); it('should use the v-model with the phone number and emit the changes', async () => { const wrapper = mountPhoneNumberInputAsTemplate( '<ec-phone-number-input :countries="countries" v-model="value" />', {}, { data() { return { countries, value: { phoneNumber: 0 } }; }, }, ); await wrapper.findByDataTest('ec-phone-number-input__number').setValue('11'); expect(wrapper.vm.value.phoneNumber).toEqual('11'); }); }); }); async function selectItem(wrapper, index) { wrapper.findByDataTest('ec-phone-number-input__countries').trigger('mousedown'); wrapper.findByDataTest('ec-phone-number-input__countries').trigger('focus'); wrapper.findByDataTest(`ec-dropdown-search__item--${index}`).trigger('click'); await wrapper.vm.$nextTick(); }
lebeerman/gatsby-netlify-tut
src/pages/Footer.js
import React from 'react' import Link from 'gatsby-link' import SpotifyPlayer from 'react-spotify-player'; import * as FaIconPack from 'react-icons/lib/fa'; // size may also be a plain string using the presets 'large' or 'compact' const size = { width: '100%', height: 300, }; const view = 'list'; // or 'coverart' const theme = 'black'; // or 'white' class Footer extends React.Component { render() { return <div className="Footer" href="#CONTACT"> <div className="footer-1"> <h3> <SpotifyPlayer uri="spotify:user:dewanderer:playlist:601WLbJ3Vj91XIugGUJNUe" size={size} view={view} theme={theme} /> </h3> </div> <div className="footer-2"> <h3>Social</h3> <p> <a href="mailto:<EMAIL>?Subject=Hello%20there!" target="_top"> <FaIconPack.FaPaperPlane size={20} className="fas i-hov" aria-hidden="true" /> <EMAIL> </a> </p> <p> <a href="https://www.linkedin.com/in/daniel-beerman/" target="_blank" rel="noopener noreferrer" className="footer-link"> <FaIconPack.FaLinkedinSquare size={20} className="fas i-hov" aria-hidden="true" /> Linkedin </a> </p> <p> <a href="https://github.com/lebeerman" target="_blank" rel="noopener noreferrer"> <FaIconPack.FaGithubSquare size={20} className="fas i-hov" aria-hidden="true" /> Github </a> </p> <p> <a href="https://twitter.com/toBDaniel" target="_blank" rel="noopener noreferrer"> <FaIconPack.FaTwitterSquare size={20} className="fas i-hov" aria-hidden="true" /> Twitter </a> </p> <p> <a href="https://www.instagram.com/dbeerman/" target="_blank" rel="noopener noreferrer"> <FaIconPack.FaInstagram size={20} className="fas i-hov" aria-hidden="true" /> Instagram </a> </p> </div> <div className="footer-full"> <p> ©2018. <strong><NAME></strong> using <strong> <a href="https://github.com/AustinGreen/gatsby-starter-netlify-cms"> React + Gatsby + Netlify </a> </strong>, JSX, CSS, and other cool tools. </p> <p> Check out the repo on <strong> <a href="https://github.com/lebeerman/portfolio" target="_blank" rel="noopener noreferrer"> github </a> </strong>.{' '} </p> </div> </div> } } export default Footer
souza-joao/cursoemvideo-python3
041.py
<gh_stars>0 from datetime import date idade = int(input('Digite o ano em que você nasceu: ')) x = date.today().year - idade print('O atleta tem ou fará {} anos.'.format(x)) if x < 9: print('Ele participará da categoria MIRIM.') elif 9 < x < 14: print('Ele participará da categoria INFANTIL.') elif 14 < x < 19: print('Ele participará da categoria JUNIOR.') elif 19 < x < 25: print('Ele participará da categoria SENIOR.') elif x > 25: print('Ele participará da categoria MASTER.')
Bu11etmagnet/GWToolboxpp
GWToolboxdll/GWToolbox/Widgets/PartyDamage.h
#pragma once #include <Defines.h> #include <GWCA/Constants/Constants.h> #include <GWCA/Packets/StoC.h> #include "ToolboxWidget.h" #include "Timer.h" #include "Color.h" class PartyDamage : public ToolboxWidget { static const int MAX_PLAYERS = 12; struct PlayerDamage { uint32_t damage = 0; uint32_t recent_damage = 0; clock_t last_damage = 0; uint32_t agent_id = 0; std::wstring name; GW::Constants::Profession primary = GW::Constants::Profession::None; GW::Constants::Profession secondary = GW::Constants::Profession::None; void Reset() { damage = 0; recent_damage = 0; agent_id = 0; name = L""; primary = GW::Constants::Profession::None; secondary = GW::Constants::Profession::None; } }; PartyDamage() {}; public: static PartyDamage& Instance() { static PartyDamage instance; return instance; } const char* Name() const override { return "Damage"; } void Initialize() override; void Terminate() override; // Draw user interface. Will be called every frame if the element is visible void Draw(IDirect3DDevice9* pDevice) override; void Update(float delta) override; void LoadSettings(CSimpleIni* ini) override; void SaveSettings(CSimpleIni* ini) override; void DrawSettingInternal() override; void WritePartyDamage(); void WriteDamageOf(size_t index, uint32_t rank = 0); // party index from 0 to 12 void WriteOwnDamage(); void ResetDamage(); bool is_resizable = false; private: void DamagePacketCallback(GW::HookStatus *, GW::Packet::StoC::GenericModifier *packet); void MapLoadedCallback(GW::HookStatus *, GW::Packet::StoC::MapLoaded *packet); void CreatePartyIndexMap(); float GetPartOfTotal(uint32_t dmg) const; inline float GetPercentageOfTotal(uint32_t dmg) const { return GetPartOfTotal(dmg) * 100.0f; }; // damage values uint32_t total = 0; PlayerDamage damage[MAX_PLAYERS]; std::map<DWORD, uint32_t> hp_map; std::map<DWORD, size_t> party_index; size_t player_index = 0; // main routine variables bool in_explorable = false; clock_t send_timer = 0; std::queue<std::wstring> send_queue; // ini CSimpleIni* inifile = nullptr; Color color_background = 0; Color color_damage = 0; Color color_recent = 0; float width = 0.f; bool bars_left = false; int recent_max_time = 0; int row_height = 0; bool hide_in_outpost = false; GW::HookEntry GenericModifier_Entry; GW::HookEntry MapLoaded_Entry; };
mrxbox98/ParticleNativeAPI
ParticleNativeAPI-api/src/main/java/com/github/fierioziy/particlenativeapi/api/types/ParticleTypeColorable.java
package com.github.fierioziy.particlenativeapi.api.types; import com.github.fierioziy.particlenativeapi.api.utils.ParticleException; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.util.Vector; /** * <p>Class used to represent particle type that can construct * colored particle packet.</p> * * <p>It provides a non-reflective <code>packetColored</code> * and <code>packet</code> method overloads * to construct particle packet with desired parameters.</p> * * <p>All <code>packetColored</code> and <code>packet</code> methods does not validate parameters in any way.</p> * * @see ParticleType */ public class ParticleTypeColorable extends ParticleType { /** * <p>Construct particle packet that will * spawn 1 colored particle at specified position.</p> * * <p>Parameters are not validated in any way.</p> * * <p>It is wise to check, if particle is supported by current Spigot version * using <code>isValid</code> method.</p> * * @param far if true, packets will be rendered much further * than 16 blocks (flag is ignored prior to MC 1.8 versions). * @param loc a <code>Location</code> containing position. * @param color a <code>Color</code> object with color parameters. * * @return a valid NMS <code>Packet</code> object. * * @throws ParticleException when requested particle type * is not supported by this server version. */ public Object packetColored(boolean far, Location loc, Color color) { return packet(far, loc.getX(), loc.getY(), loc.getZ(), color.getRed() / 255D, color.getGreen() / 255D, color.getBlue() / 255D, 1D, 0); } /** * <p>Construct particle packet that will * spawn 1 colored particle at specified position.</p> * * <p>Parameters are not validated in any way.</p> * * <p>It is wise to check, if particle is supported by current Spigot version * using <code>isValid</code> method.</p> * * @param far if true, packets will be rendered much further * than 16 blocks (flag is ignored prior to MC 1.8 versions). * @param loc a <code>Vector</code> containing position. * @param color a <code>Color</code> object with color parameters. * * @return a valid NMS <code>Packet</code> object. * * @throws ParticleException when requested particle type * is not supported by this server version. */ public Object packetColored(boolean far, Vector loc, Color color) { return packet(far, loc.getX(), loc.getY(), loc.getZ(), color.getRed() / 255D, color.getGreen() / 255D, color.getBlue() / 255D, 1D, 0); } /** * <p>Construct particle packet that will * spawn 1 colored particle at specified position.</p> * * <p>Parameters are not validated in any way.</p> * * <p>It is wise to check, if particle is supported by current Spigot version * using <code>isValid</code> method.</p> * * @param far if true, packets will be rendered much further * than 16 blocks (flag is ignored prior to MC 1.8 versions). * @param x component of a position. * @param y component of a position. * @param z component of a position. * @param color a <code>Color</code> object with color parameters. * * @return a valid NMS <code>Packet</code> object. * * @throws ParticleException when requested particle type * is not supported by this server version. */ public Object packetColored(boolean far, double x, double y, double z, Color color) { return packet(far, x, y, z, color.getRed() / 255D, color.getGreen() / 255D, color.getBlue() / 255D, 1D, 0); } /** * <p>Construct particle packet that will * spawn 1 colored particle at specified position.</p> * * <p>Parameters are not validated in any way.</p> * * <p>It is wise to check, if particle is supported by current Spigot version * using <code>isValid</code> method.</p> * * @param far if true, packets will be rendered much further * than 16 blocks (flag is ignored prior to MC 1.8 versions). * @param loc a <code>Location</code> containing position. * @param r red color value that should be between 0 and 255. * @param g green color value that should be between 0 and 255. * @param b blue color value that should be between 0 and 255. * * @return a valid NMS <code>Packet</code> object. * * @throws ParticleException when requested particle type * is not supported by this server version. */ public Object packetColored(boolean far, Location loc, int r, int g, int b) { return packet(far, loc.getX(), loc.getY(), loc.getZ(), r / 255D, g / 255D, b / 255D, 1D, 0); } /** * <p>Construct particle packet that will * spawn 1 colored particle at specified position.</p> * * <p>Parameters are not validated in any way.</p> * * <p>It is wise to check, if particle is supported by current Spigot version * using <code>isValid</code> method.</p> * * @param far if true, packets will be rendered much further * than 16 blocks (flag is ignored prior to MC 1.8 versions). * @param loc a <code>Vector</code> containing position. * @param r red color value that should be between 0 and 255. * @param g green color value that should be between 0 and 255. * @param b blue color value that should be between 0 and 255. * * @return a valid NMS <code>Packet</code> object. * * @throws ParticleException when requested particle type * is not supported by this server version. */ public Object packetColored(boolean far, Vector loc, int r, int g, int b) { return packet(far, loc.getX(), loc.getY(), loc.getZ(), r / 255D, g / 255D, b / 255D, 1D, 0); } /** * <p>Construct particle packet that will * spawn 1 colored particle at specified position.</p> * * <p>Parameters are not validated in any way.</p> * * <p>It is wise to check, if particle is supported by current Spigot version * using <code>isValid</code> method.</p> * * @param far if true, packets will be rendered much further * than 16 blocks (flag is ignored prior to MC 1.8 versions). * @param x component of a position. * @param y component of a position. * @param z component of a position. * @param r red color value that should be between 0 and 255. * @param g green color value that should be between 0 and 255. * @param b blue color value that should be between 0 and 255. * * @return a valid NMS <code>Packet</code> object. * * @throws ParticleException when requested particle type * is not supported by this server version. */ public Object packetColored(boolean far, double x, double y, double z, int r, int g, int b) { return packet(far, x, y, z, r / 255D, g / 255D, b / 255D, 1D, 0); } }
morozig/muzero
MuZero/MuCoach.py
<filename>MuZero/MuCoach.py """ Implements the abstract Coach class for defining the data sampling procedures for MuZero neural network training. Notes: - Base implementation done. - Documentation 15/11/2020 """ import typing from datetime import datetime import numpy as np import tensorflow as tf from Coach import Coach from Agents import DefaultMuZeroPlayer from MuZero.MuMCTS import MuZeroMCTS from utils import DotDict from utils.selfplay_utils import GameHistory, sample_batch class MuZeroCoach(Coach): """ Implement base Coach class to define proper data-batch sampling procedures and logging objects. """ def __init__(self, game, neural_net, args: DotDict, run_name: typing.Optional[str] = None) -> None: """ Initialize the class for self-play. This inherited method initializes tensorboard logging and defines helper variables for data batch sampling. The super class is initialized with the proper search engine and agent-interface. (MuZeroMCTS, MuZeroPlayer) :param game: Game Implementation of Game class for environment logic. :param neural_net: MuNeuralNet Implementation of MuNeuralNet class for inference. :param args: DotDict Data structure containing parameters for self-play. :param run_name: str Optionally provide a run-name for the TensorBoard log-files. Default is current datetime. """ super().__init__(game, neural_net, args, MuZeroMCTS, DefaultMuZeroPlayer) # Initialize tensorboard logging. if run_name is None: run_name = datetime.now().strftime("%Y%m%d-%H%M%S") self.log_dir = f"out/logs/MuZero/{self.neural_net.architecture}/" + run_name self.file_writer = tf.summary.create_file_writer(self.log_dir + "/metrics") self.file_writer.set_as_default() # Define helper variables. self.return_forward_observations = (neural_net.net_args.dynamics_penalty > 0 or args.latent_decoder) self.observation_stack_length = neural_net.net_args.observation_length def buildHypotheticalSteps(self, history: GameHistory, t: int, k: int) -> \ typing.Tuple[np.ndarray, typing.Tuple[np.ndarray, np.ndarray, np.ndarray], np.ndarray]: """ Sample/ extrapolate a sequence of targets for unrolling/ fitting the MuZero neural network. This sequence consists of the actions performed at time t until t + k - 1. These are used for unrolling the dynamics model. For extrapolating beyond terminal states we adopt an uniform policy over the entire action space to ensure that the model learns to generalize over the actions when encountering terminal states. The move-probabilities, value, and reward predictions are sampled from t until t + k. Note that the reward at the first index is not used for weight optimization as the initial call to the model does not predict rewards. For extrapolating beyond terminal states we repeat a zero vector for the move-probabilities and zeros for the reward and value targets seeing as a terminated environment does not provide rewards. The zero vector for the move-probabilities is used to define an improper probability distribution. The loss function can then infer that the episode ended, and distribute gradient accordingly. Empirically we observed that extrapolating an uniform move-policy for the move-probability vector results in slower and more unstable learning as we're feeding wrong data to the neural networks. We found that not distributing any gradient at all to these extrapolated steps resulted in the best learning. :param history: GameHistory Sampled data structure containing all statistics/ observations of a finished game. :param t: int The sampled index to generate the targets at. :param k: int The number of unrolling steps to perform/ length of the dynamics model target sequence. :return: Tuple of (actions, targets, future_inputs) that the neural network needs for optimization """ # One hot encode actions. actions = history.actions[t:t+k] a_truncation = k - len(actions) if a_truncation > 0: # Uniform policy when unrolling beyond terminal states. actions += np.random.randint(self.game.getActionSize(), size=a_truncation).tolist() enc_actions = np.zeros([k, self.game.getActionSize()]) enc_actions[np.arange(len(actions)), actions] = 1 # Value targets. pis = history.probabilities[t:t+k+1] vs = history.observed_returns[t:t+k+1] rewards = history.rewards[t:t+k+1] # Handle truncations > 0 due to terminal states. Treat last state as absorbing state t_truncation = (k + 1) - len(pis) # Target truncation due to terminal state if t_truncation > 0: pis += [np.zeros_like(pis[-1])] * t_truncation # Zero vector rewards += [0] * t_truncation # = 0 vs += [0] * t_truncation # = 0 # If specified, also sample/ extrapolate future observations. Otherwise return an empty array. obs_trajectory = [] if self.return_forward_observations: obs_trajectory = [history.stackObservations(self.observation_stack_length, t=t+i+1) for i in range(k)] # (Actions, Targets, Observations) return enc_actions, (np.asarray(vs), np.asarray(rewards), np.asarray(pis)), obs_trajectory def sampleBatch(self, histories: typing.List[GameHistory]) -> typing.List: """ Construct a batch of data-targets for gradient optimization of the MuZero neural network. The procedure samples a list of game and inside-game coordinates of length 'batch_size'. This is done either uniformly or with prioritized sampling. Using this list of coordinates, we sample the according games, and the according points of times within the game to generate neural network inputs, targets, and sample weights. :param histories: List of GameHistory objects. Contains all game-trajectories in the replay-buffer. :return: List of training examples: (observations, actions, targets, forward_observations, sample_weights) """ # Generate coordinates within the replay buffer to sample from. Also generate the loss scale of said samples. sample_coordinates, sample_weight = sample_batch( list_of_histories=histories, n=self.neural_net.net_args.batch_size, prioritize=self.args.prioritize, alpha=self.args.prioritize_alpha, beta=self.args.prioritize_beta) # Collect training examples for MuZero: (input, action, (targets), forward_observations, loss_scale) examples = [( histories[h_i].stackObservations(self.observation_stack_length, t=i), *self.buildHypotheticalSteps(histories[h_i], t=i, k=self.args.K), loss_scale ) for (h_i, i), loss_scale in zip(sample_coordinates, sample_weight) ] return examples
Programming-TRIGON/RobotCode2022
src/main/java/frc/robot/subsystems/MovableSubsystem.java
package frc.robot.subsystems; import edu.wpi.first.wpilibj2.command.Subsystem; /** * This is interface for all of our moving subsystems with motors. * For example every moving SS will have to move and stop. * It is also used for dependency injection with commands that works the same way, * for multiple subsystems. */ public interface MovableSubsystem extends Subsystem { void move(double power); default void stopMoving() { move(0); } }
sbwfk2/HearthSim
src/main/java/com/hearthsim/card/classic/minion/common/AmaniBerserker.java
package com.hearthsim.card.classic.minion.common; import com.hearthsim.card.minion.MinionWithEnrage; public class AmaniBerserker extends MinionWithEnrage { public AmaniBerserker() { super(); } @Override public void enrage() { attack_ = (byte)(attack_ + 3); } @Override public void pacify() { attack_ = (byte)(attack_ - 3); } }
dandroos/project-corner-website
src/pages/cursos.js
import React, { useEffect } from "react" import { connect } from "react-redux" import { setCurrentPage } from "../state" import { Link, useStaticQuery, graphql } from "gatsby" import { Toolbar, Box, Container, Typography, Link as MLink, List, ListSubheader, ListItem, ListItemText, Button, useTheme, } from "@material-ui/core" import { Information } from "mdi-material-ui" import Seo from "../components/seo" const CursosPage = ({ dispatch, isMobile }) => { const theme = useTheme() const data = useStaticQuery(graphql` { allSheetsCoursesCourses { edges { node { price ref studyLevel time days age } } } } `) var cleanCourses = [] const courses = data.allSheetsCoursesCourses.edges .map(i => { const { days, time, age, studyLevel, price, ref } = i.node return { days, time, age, studyLevel, price, ref, } }) .sort((a, b) => { return a.age < b.age ? -1 : a.age > b.age ? 1 : 0 }) courses.forEach((i, ind) => { if (ind === 0 || courses[ind].studyLevel !== courses[ind - 1].studyLevel) { cleanCourses.push({ label: i.studyLevel, age: i.age, classes: [i], }) } else { cleanCourses = cleanCourses.map(j => { if (j.label === i.studyLevel) { const replacement = { label: j.label, age: j.age, classes: [...j.classes, i], } return replacement } else { return j } }) } }) cleanCourses = cleanCourses.map(i => { i.classes.sort((a, b) => { const sortStringA = `${a.days} ${a.time}` const sortStringB = `${b.days} ${b.time}` return sortStringA < sortStringB ? -1 : sortStringA > sortStringB ? 1 : 0 }) return i }) useEffect(() => { dispatch(setCurrentPage("cursos")) //eslint-disable-next-line }, []) return ( <> <Seo title="Cursos" /> <Toolbar /> <Box mb={3} align={isMobile ? "center" : "left"}> <Container maxWidth="md"> <Typography variant="h2">Cursos</Typography> <Box> <Typography paragraph> ¿Quieres saber tu nivel actual de inglés?{` `} <MLink href="https://www.cambridgeenglish.org/test-your-english/" target="_blank" > Haz una prueba de nivel gratis aquí </MLink> . </Typography> <Typography variant="h4" paragraph> Clases programadas para niños </Typography> <Typography paragraph> Todos los cursos tienen 2 clases por semana durante el período escolar. El precio es de 45€ al mes salvo que se indique lo contrario. Hay una tasa de inscripción de 15€ y un costo de 30€ por libros y materiales. </Typography> <Typography variant="h5" align="center" paragraph> Calendario 2020/2021 </Typography> <List dense disablePadding> {cleanCourses.map((i, indA) => ( <React.Fragment key={indA}> <ListSubheader key={indA} color="primary" style={{ fontSize: "1.25rem" }} > {i.label} <span style={{ fontSize: ".75rem" }}>{` (${i.age})`}</span> </ListSubheader> {i.classes.map((j, indB) => ( <ListItem key={indB} divider> <ListItemText primary={j.days} secondary={j.time} primaryTypographyProps={{ style: { display: "inline" }, }} secondaryTypographyProps={{ style: { color: theme.palette.text.primary, display: "inline", float: "right", }, }} /> </ListItem> ))} </React.Fragment> ))} </List> </Box> <Box my={2}> <Typography variant="h4" paragraph> Clases privadas para todas las edades </Typography> <List> <ListItem divider> <ListItemText primary="1 hora" secondary="15.00€" primaryTypographyProps={{ style: { display: "inline" }, }} secondaryTypographyProps={{ style: { color: theme.palette.text.primary, fontSize: "1rem", display: "inline", float: "right", }, }} /> </ListItem> </List> <Typography paragraph> Ya sea que desee prepararse para un examen de inglés, usted (o su hijo) necesite apoyo con su trabajo escolar o simplemente quiera practicar sus habilidades de conversación, proporcionamos clases individuales en persona y también por Skype. Podemos ofrecer clases privadas por la mañana o por la tarde. </Typography> </Box> <Box align="center"> <Button color="primary" variant="contained" startIcon={<Information />} component={Link} to="/contacto" fullWidth={isMobile} > Contáctenos para más información </Button> </Box> </Container> </Box> </> ) } const mapStateToProps = state => ({ isMobile: state.isMobile, }) export default connect(mapStateToProps)(CursosPage)
y2ghost/study
c/algorithm/include/set.h
#ifndef SET_H #define SET_H #include <list.h> typedef list_t set_t; void set_init(set_t *set, int (*match)(const void *key1, const void *key2), void (*destroy)(void *data)); int set_insert(set_t *set, const void *data); int set_remove(set_t *set, void **data); int set_union(set_t *setu, const set_t *set1, const set_t *set2); int set_intersection(set_t *seti, const set_t *set1, const set_t *set2); int set_difference(set_t *setd, const set_t *set1, const set_t *set2); int set_is_member(const set_t *set, const void *data); int set_is_subset(const set_t *set1, const set_t *set2); int set_is_equal(const set_t *set1, const set_t *set2); #define set_size(set) ((set)->size) #define set_destroy list_destroy #endif /* SET_H */
designerasun/myLearning
myJavascript/backend/myNodeJs/netNinja/lists.js
<reponame>designerasun/myLearning<filename>myJavascript/backend/myNodeJs/netNinja/lists.js const people = ['elly', 'brian', 'paul'] const pets = ['cat', 'dog'] module.exports = { people : people, pets : pets }
zealoussnow/chromium
third_party/shell-encryption/glog/logging.h
<reponame>zealoussnow/chromium<filename>third_party/shell-encryption/glog/logging.h // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #ifndef SHELL_ENCRYPTION_GLOG_H_ #define SHELL_ENCRYPTION_GLOG_H_ #include"base/logging.h" #endif // SHELL_ENCRYPTION_GLOG_H_
jingyuyao/tactical-adventure
core/src/com/jingyuyao/tactical/model/state/Battling.java
<filename>core/src/com/jingyuyao/tactical/model/state/Battling.java package com.jingyuyao.tactical.model.state; import com.google.inject.assistedinject.Assisted; import com.jingyuyao.tactical.model.ModelBus; import com.jingyuyao.tactical.model.battle.Battle; import com.jingyuyao.tactical.model.world.Cell; import java.util.Arrays; import java.util.List; import javax.inject.Inject; public class Battling extends ControllingState { private final StateFactory stateFactory; private final BattleSequence battleSequence; private final Battle battle; @Inject Battling( ModelBus modelBus, WorldState worldState, StateFactory stateFactory, BattleSequence battleSequence, @Assisted Cell cell, @Assisted Battle battle) { super(modelBus, worldState, stateFactory, cell); this.stateFactory = stateFactory; this.battleSequence = battleSequence; this.battle = battle; } @Override public void select(Cell cell) { if (battle.getTarget().canTarget(cell)) { attack(); } } @Override public List<Action> getActions() { return Arrays.asList(new AttackAction(this), new BackAction(this)); } public Battle getBattle() { return battle; } void attack() { branchTo(stateFactory.createTransition()); battleSequence.start(battle, new Runnable() { @Override public void run() { finish(); } }); } }
openharmony-gitee-mirror/developtools_profiler
host/ohosprofiler/src/main/java/ohos/devtools/views/trace/metrics/strategy/MemAggStrategy.java
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ohos.devtools.views.trace.metrics.strategy; import ohos.devtools.views.trace.metrics.MetricsDb; import ohos.devtools.views.trace.metrics.MetricsSql; import ohos.devtools.views.trace.metrics.bean.MemAgg; import java.util.ArrayList; import java.util.List; /** * Memory unagg Strategy */ public class MemAggStrategy implements Strategy { /** * Query Memory Result * * @param sql sql * @return string string */ @Override public String getQueryResult(MetricsSql sql) { List<MemAgg> list = new ArrayList<>() { }; MetricsDb.getInstance().query(sql, list); return handleMemoryInfo(list); } private String handleMemoryInfo(List<MemAgg> result) { StringBuilder builder = new StringBuilder(); builder.append("trace_mem_unagg: {").append(System.lineSeparator()); for (MemAgg item : result) { builder.append(" process_values: {").append(System.lineSeparator()); builder.append(" process_name: ").append(item.getProcessName()).append(System.lineSeparator()); String[] names = item.getName().split(","); String[] values = item.getValue().split(","); String[] times = item.getTime().split(","); long anonTs = 0L; int anonValue = 0; int swapValue = 0; int oomScoreValue = getOomScoreValue(names, values); for (int index = 0; index < names.length; index++) { if ("mem.rss.anon".equals(names[index])) { builder.append(" anon_rss: {").append(System.lineSeparator()); anonTs = Long.parseLong(times[index]); anonValue = Integer.parseInt(values[index]); builder.append(" ts: ").append(anonTs).append(System.lineSeparator()); builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); builder.append(" value: ").append(anonValue).append(System.lineSeparator()); builder.append(" }").append(System.lineSeparator()); } if ("mem.swap".equals(names[index])) { swapValue = Integer.parseInt(values[index]); builder.append(" swap: {").append(System.lineSeparator()); builder.append(" ts: ").append(times[index]).append(System.lineSeparator()); builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); builder.append(" value: ").append(swapValue).append(System.lineSeparator()); builder.append(" }").append(System.lineSeparator()); } if ("mem.rss.file".equals(names[index])) { builder.append(" file_rss: { ").append(System.lineSeparator()); builder.append(" ts: ").append(times[index]).append(System.lineSeparator()); builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); builder.append(" value: ").append(values[index]).append(System.lineSeparator()); builder.append(" }").append(System.lineSeparator()); } if ("oom_score_adj".equals(names[index])) { builder.append(" anon_and_swap: { ").append(System.lineSeparator()); builder.append(" ts: ").append(anonTs).append(System.lineSeparator()); builder.append(" oom_score: ").append(oomScoreValue).append(System.lineSeparator()); builder.append(" value: ").append(anonValue + swapValue).append(System.lineSeparator()); builder.append(" }").append(System.lineSeparator()); } } builder.append(" }").append(System.lineSeparator()); } builder.append("}").append(System.lineSeparator()); return builder.toString(); } private int getOomScoreValue(String[] names, String[] values) { int oomScoreValue = 0; for (int index = 0; index < names.length; index++) { if ("oom_score_adj".equals(names[index])) { oomScoreValue = Integer.parseInt(values[index]); break; } } return oomScoreValue; } }
dram/metasfresh
backend/de.metas.ui.web.base/src/main/java/de/metas/ui/web/view/InvoiceCandidateViewHeaderPropertiesProvider.java
<reponame>dram/metasfresh<filename>backend/de.metas.ui.web.base/src/main/java/de/metas/ui/web/view/InvoiceCandidateViewHeaderPropertiesProvider.java<gh_stars>1000+ /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2020 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.ui.web.view; import java.util.List; import java.util.Set; import org.springframework.stereotype.Component; import com.google.common.collect.ImmutableList; import de.metas.handlingunits.invoicecandidate.ui.spi.impl.HUInvoiceCandidatesSelectionSummaryInfo; import de.metas.i18n.IMsgBL; import de.metas.invoicecandidate.api.IInvoiceCandBL; import de.metas.invoicecandidate.api.impl.InvoiceCandidatesAmtSelectionSummary; import de.metas.invoicecandidate.model.I_C_Invoice_Candidate; import de.metas.ui.web.view.descriptor.SqlAndParams; import de.metas.ui.web.view.descriptor.SqlViewRowsWhereClause; import de.metas.ui.web.window.datatypes.DocumentId; import de.metas.ui.web.window.datatypes.DocumentIdsSelection; import de.metas.ui.web.window.model.sql.SqlOptions; import de.metas.util.Services; import lombok.NonNull; @Component public class InvoiceCandidateViewHeaderPropertiesProvider implements ViewHeaderPropertiesProvider { private final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); private final IMsgBL msgBL = Services.get(IMsgBL.class); @Override public String getAppliesOnlyToTableName() { return I_C_Invoice_Candidate.Table_Name; } @Override public @NonNull ViewHeaderProperties computeHeaderProperties(@NonNull final IView view) { return ViewHeaderProperties.builder() .groups(computeRealData(view)) .build(); } private List<ViewHeaderPropertiesGroup> computeRealData(final @NonNull IView view) { /* * IMPORTANT! * Implementation detail * The `view.size()` call is needed because the rows in table `T_WEBUI_ViewSelection` are lazily inserted, on the first view usage. * If this call is not done, querying from the view will return 0 rows. */ final long rowsToDisplay = view.size(); if (rowsToDisplay == 0) { return ImmutableList.of(); } final SqlViewRowsWhereClause sqlWhereClause = view.getSqlWhereClause(DocumentIdsSelection.ALL, SqlOptions.usingTableName(I_C_Invoice_Candidate.Table_Name)); final SqlAndParams sqlAndParams = SqlAndParams.of(sqlWhereClause.toSqlString()); final InvoiceCandidatesAmtSelectionSummary summary = invoiceCandBL.calculateAmtSelectionSummary(sqlAndParams.getSql()); return toViewHeaderProperties(summary); } /** * Keep in sync with {@link HUInvoiceCandidatesSelectionSummaryInfo#getSummaryMessage()} */ private List<ViewHeaderPropertiesGroup> toViewHeaderProperties(final InvoiceCandidatesAmtSelectionSummary summary) { final ImmutableList.Builder<ViewHeaderPropertiesGroup> result = ImmutableList.<ViewHeaderPropertiesGroup> builder() .add(ViewHeaderPropertiesGroup.builder() .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("NetIsApprovedForInvoicing")) .value(summary.getTotalNetAmtApprovedAsTranslatableString()) .build()) .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("isTradingUnit")) .value(summary.getHUNetAmtApprovedAsTranslatableString()) .build()) .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("IsGoods")) .value(summary.getCUNetAmtApprovedAsTranslatableString()) .build()) .build()) .add(ViewHeaderPropertiesGroup.builder() .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("NetIsNotApprovedForInvoicing")) .value(summary.getTotalNetAmtNotApprovedAsTranslatableString()) .build()) .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("isTradingUnit")) .value(summary.getHUNetAmtNotApprovedAsTranslatableString()) .build()) .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("IsGoods")) .value(summary.getCUNetAmtNotApprovedAsTranslatableString()) .build()) .build()); if (summary.getCountTotalToRecompute() > 0) { result.add(ViewHeaderPropertiesGroup.builder() .entry(ViewHeaderProperty.builder() .caption(msgBL.translatable("IsToRecompute")) .value(summary.getCountTotalToRecompute()) .build()) .build()); } return result.build(); } @Override public ViewHeaderPropertiesIncrementalResult computeIncrementallyOnRowsChanged( @NonNull final ViewHeaderProperties currentHeaderProperties, @NonNull final IView view, @NonNull final Set<DocumentId> changedRowIds, final boolean watchedByFrontend) { return ViewHeaderPropertiesIncrementalResult.fullRecomputeRequired(); } }
icahoon/vocal
sip/gua/LookupTable.cxx
#include "LookupTable.hxx" #include <stdio.h> #include "cpLog.h" LookupTable* LookupTable::myInstance = 0; LookupTable::LookupTable(const char* filename) { // read from a file parseFile(filename); } void LookupTable::parseFile(const char* filename) { char line [256]; FILE* fd = fopen (filename , "r"); if (fd) { while(fgets(line, 256, fd)) { // do something to the line. separate on comma Data name; Data wav; int c = 0; int state = 0; line[255] = '\0'; while (c < 256 && line[c] != '\0') { if (line[c] == '\r' || line[c] == '\n') { } else if (line[c] == '#') { // ignore the rest of the line state = 3; } else if (line[c] == ',') { state++; } else if(state == 0) { name += line[c]; } else if (state == 1) { wav += line[c]; } c++; } // cpLog(LOG_DEBUG, "state: %d, got name: %s", name.logData()); if(state >= 1 && name != "") { cpLog(LOG_DEBUG, "got name: %s", name.logData()); LookupTableItem item; item.wav = wav; myMap[name] = item; } } fclose (fd); } else { cpLog (LOG_ERR, "Cannot open file: %s", filename); } } LookupTable* LookupTable::instance(const char* filename) { if(LookupTable::myInstance == 0) { myInstance = new LookupTable(filename); } return myInstance; } bool LookupTable::lookup(Data name, LookupTableItem& item) { map<Data,LookupTableItem>::iterator i; i = myMap.find(name); if(i != myMap.end()) { item = i->second; return true; } else { return false; } }
ggreen/pcf-scdf-retail-showcase
pivot-market-int-tests/src/main/java/io/pivotal/gemfire/functions/FunctionInvoker.java
package io.pivotal.gemfire.functions; import org.apache.geode.cache.Region; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.execute.ResultCollector; public class FunctionInvoker { //ClientCache cache; public FunctionInvoker() { } public static void exportToGpdb(Region<?, ?> region) { ResultCollector<?, ?> rc = FunctionService.onRegion(region).execute("ExportToGpdbFunction"); Object result = rc.getResult(); System.out.println(result.toString()); } public static boolean executeClearRegionRemoveAll(Region<?, ?> region) { ResultCollector<?, ?> rc = FunctionService.onRegion(region).execute("ClearRegionRemoveAllFunction"); Object result = rc.getResult(); // Array size seems to be server node count. //System.out.println("executeClearRegionRemoveAll.result: " + result); String str[] =result.toString().split(","); for (int i=0; i<str.length; i++) { if ("false".equals(str[i])) { return false; } } return true; } public static void executeMakeArray(Region<?, ?> region) { ResultCollector<?, ?> rc = FunctionService.onRegion(region).execute("MakeArrayFunction"); Object result = rc.getResult(); // Array size seems to be node count. System.out.println("executeMakeArray.result: " + result); } public static void executeGetMasterRegionData(Region<?, ?> region) { ResultCollector<?, ?> rc = FunctionService.onRegion(region).execute("GetMasterRegionDataFunction"); Object result = rc.getResult(); // Array size seems to be node count. System.out.println("executeGetMasterRegionData.result: " + result); } }
hascode/ArchUnit
archunit-example/example-plain/src/main/java/com/tngtech/archunit/example/cycle/constructorcycle/slice2/SliceTwoCallingConstructorInSliceOne.java
package com.tngtech.archunit.example.cycle.constructorcycle.slice2; import com.tngtech.archunit.example.cycle.constructorcycle.slice1.SomeClassWithCalledConstructor; public class SliceTwoCallingConstructorInSliceOne { void callSliceOne() { new SomeClassWithCalledConstructor(); } void doSomethingInSliceTwo() { } }
namin/pycket
meta-interp-pycket.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from rpython.jit.metainterp.test.support import LLJitMixin from pycket.racket_entry import dev_mode_metainterp_fasl_zo, dev_mode_dynamic_metainterp from pycket.env import w_global_config as glob from pycket.config import get_testing_config # 1 glob.set_pycketconfig(get_testing_config()) LLJitMixin().meta_interp(dev_mode_dynamic_metainterp, [], listcomp=True, listops=True, backendopt=True) # 2 # from pycket.entry_point import make_entry_point, target # from rpython.translator.driver import TranslationDriver # from rpython.config.translationoption import get_combined_translation_config # # pypy targetpycket.py --linklets --verbose 2 -I racket/kernel/init -e "1" # entry_flags_1 = ['--linklets', '--verbose', '2', '-I', 'racket/kernel/init', '-e', '1'] # def interp_w_1(): # make_entry_point(get_dummy_config())(entry_flags_1) ## LLJitMixin().meta_interp(interp_w_1, [], listcomp=True, listops=True, backendopt=True) # 3 # pypy targetpycket.py --linklets --dev # entry_flags_2 = ['--linklets', '--dev'] # def interp_w_2(): # make_entry_point(get_dummy_config())(entry_flags_2) # ## LLJitMixin().meta_interp(interp_w_2, [], listcomp=True, listops=True, backendopt=True) # # 4 - META-INTERP OLD PYCKET # from pycket.expand import JsonLoader, expand # from pycket.interpreter import interpret_one # from pycket.test.jit import TestLLtype # TestLLtype().run_file("use-fasl.rkt", run_untranslated=False)
shachindrasingh/apiman
manager/api/core/src/main/java/io/apiman/manager/api/core/catalog/JsonApiCatalog.java
<filename>manager/api/core/src/main/java/io/apiman/manager/api/core/catalog/JsonApiCatalog.java /* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.manager.api.core.catalog; import io.apiman.manager.api.beans.summary.ApiCatalogBean; import io.apiman.manager.api.beans.summary.ApiNamespaceBean; import io.apiman.manager.api.beans.summary.AvailableApiBean; import io.apiman.manager.api.core.IApiCatalog; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; /** * An API catalog that gets its data from a simple JSON file. * * @author <EMAIL> */ public class JsonApiCatalog implements IApiCatalog { private static final ObjectMapper mapper = new ObjectMapper(); private URI catalogUri; private List<AvailableApiBean> apis; /** * Constructor. * @param config */ public JsonApiCatalog(Map<String, String> config) { String cu = config.get("catalog-url"); //$NON-NLS-1$ try { cu = cu.trim(); if (cu.startsWith("file:")) { //$NON-NLS-1$ cu = cu.replace('\\', '/'); } catalogUri = new URI(cu); } catch (Exception e) { throw new RuntimeException("Error configuring the JSON API catalog from a URI: " + cu, e); //$NON-NLS-1$ } } /** * @see io.apiman.manager.api.core.IApiCatalog#search(java.lang.String, java.lang.String) */ @Override public List<AvailableApiBean> search(String keyword, String namespace) { if (apis == null) { apis = loadAPIs(catalogUri); } ArrayList<AvailableApiBean> rval = new ArrayList<>(); for (AvailableApiBean api : apis) { if ("*".equals(keyword) || api.getName().toLowerCase().contains(keyword.toLowerCase())) { //$NON-NLS-1$ rval.add(api); } } return rval; } /** * @see io.apiman.manager.api.core.IApiCatalog#getNamespaces(java.lang.String) */ @Override public List<ApiNamespaceBean> getNamespaces(String currentUser) { return Collections.EMPTY_LIST; } /** * @param uri the URL to load the catalog from * @return Loads APIs from the catalog URL */ private static List<AvailableApiBean> loadAPIs(URI uri) { try { ApiCatalogBean catalog = (ApiCatalogBean) mapper.reader(ApiCatalogBean.class).readValue(uri.toURL()); return catalog.getApis(); } catch (Exception e) { throw new RuntimeException("Error loading APIs from a URL: " + uri, e); //$NON-NLS-1$ } } }
kshatriya-abhay/leetcode-solutions
cpp-solutions/easy/pascals-triangle.cpp
<reponame>kshatriya-abhay/leetcode-solutions<filename>cpp-solutions/easy/pascals-triangle.cpp<gh_stars>0 class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> ans; if(numRows < 1) return ans; vector<int> init; init.push_back(1); ans.push_back(init); if(numRows == 1) return ans; for(int i=1; i<numRows; i++){ vector<int> curr; curr.push_back(1); for(int j=1; j < i; j++){ curr.push_back(ans[i-1][j-1] + ans[i-1][j]); } curr.push_back(1); ans.push_back(curr); } return ans; } };
mirajgodha/cdap
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/deploy/DefaultConfigResponse.java
<filename>cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/deploy/DefaultConfigResponse.java /* * Copyright © 2014-2018 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.internal.app.deploy; import co.cask.cdap.app.deploy.ConfigResponse; import javax.annotation.Nullable; /** * This is implementation of {@link ConfigResponse}. * <p> * Immutable class that hold exit code and stream of input. * </p> */ public final class DefaultConfigResponse implements ConfigResponse { private final int exit; private final String response; /** * Constructor. * * @param exit code returned from processing a command. * @param response the response generated by the configuration process */ public DefaultConfigResponse(int exit, @Nullable String response) { this.exit = exit; this.response = exit == 0 ? response : null; } @Nullable @Override public String getResponse() { return response; } /** * @return Exit code of command that was executed. */ @Override public int getExitCode() { return exit; } }
ananyahjha93/libself
ssl_framework/models/heads/mlp.py
import math import torch import torch.nn as nn from ssl_framework.config.default import cfg class MLP(nn.Module): def __init__(self, dims, dropout, dropout_probs, in_channels=0): """ length of dropout and dropout_probs should be 2 less than length of dims """ super(MLP, self).__init__() self.eval_mode = cfg.MODEL.FEATURE_EVAL_MODE self.in_channels = in_channels self.pool_type = cfg.MODEL.HEAD.POOL self.batchnorm = cfg.MODEL.HEAD.APPLY_BATCHNORM self.bn_eps = cfg.MODEL.HEAD.BATCHNORM_EPS self.bn_momentum = cfg.MODEL.HEAD.BATCHNORM_MOMENTUM self.dims = dims self.dropout = dropout self.dropout_probs = dropout_probs assert len(dims) - 2 == len(dropout) and len(dims) - 2 == len(dropout_probs),\ "length of dropout/dropout_probs should be 2 less than length of dims" if self.eval_mode: assert self.in_channels != 0,\ "in_channels should not be 0 in eval mode" resize_to = int(math.sqrt(self.dims[0] // self.in_channels)) if self.pool_type == 'avg': self.pool = nn.AdaptiveAvgPool2d((resize_to, resize_to)) elif self.pool_type == 'max': self.pool = nn.AdaptiveMaxPool2d((resize_to, resize_to)) if self.batchnorm: self.spatial_bn = nn.BatchNorm2d(self.in_channels, eps=self.bn_eps, momentum=self.bn_momentum) self.clf = self.create_mlp() def create_mlp(self): layers = [] last_dim = self.dims[0] dropout_idx = 0 for dim in self.dims[1:-1]: layers.append(nn.Linear(last_dim, dim)) if self.batchnorm: layers.append( nn.BatchNorm1d( dim, eps=self.bn_eps, momentum=self.bn_momentum, ) ) layers.append(nn.ReLU(inplace=True)) if self.dropout[dropout_idx]: layers.append(nn.Dropout(p=self.dropout_probs[dropout_idx])) dropout_idx += 1 last_dim = dim layers.append(nn.Linear(last_dim, self.dims[-1])) return nn.Sequential(*layers) def forward(self, x): if self.eval_mode: x = self.pool(x) if self.batchnorm: x = self.spatial_bn(x) if len(x.size()) != 2: x = x.view(x.size(0), -1) x = self.clf(x) return x
chenshun131/PaySystem
pay-banklink/pay-facade-banklink/src/main/java/wusc/edu/pay/facade/banklink/netpay/vo/NotifyResult.java
<reponame>chenshun131/PaySystem package wusc.edu.pay.facade.banklink.netpay.vo; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import wusc.edu.pay.facade.banklink.netpay.enums.BankCardTypeEnum; import wusc.edu.pay.facade.banklink.netpay.enums.BankTradeStatusEnum; /** * 支付完成后验证vo * * @author Administrator * */ public class NotifyResult implements Serializable { /** * */ private static final long serialVersionUID = 3929565355870158716L; /** 支付接口(非空) */ private String payInterface; /** * 是否验签通过 */ private boolean isVerify; /** 银行订单号 */ private String bankOrderNo; /** 支付金额 */ private BigDecimal payAmount; /** 支付状态(如果不能确定是否为已付或未付则为其它,已付确认需谨慎) */ private BankTradeStatusEnum status; /** 银行支付状态(银行原始支付状态) */ private String bankStatus; /** 银行成功时间(如果不能确定银行成功时间则放空) */ private Date bankSuccessTime; /** 银行返回交易流水号 **/ private String bankTrxNo; /** 银行返回用户支付卡种 **/ private BankCardTypeEnum cardType; /** 成功后回写字符串 **/ private String responseStr; public String getPayInterface() { return payInterface; } public void setPayInterface(String payInterface) { this.payInterface = payInterface; } public boolean isVerify() { return isVerify; } public void setVerify(boolean isVerify) { this.isVerify = isVerify; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo; } public BigDecimal getPayAmount() { return payAmount; } public void setPayAmount(BigDecimal payAmount) { this.payAmount = payAmount; } public BankTradeStatusEnum getStatus() { return status; } public void setStatus(BankTradeStatusEnum status) { this.status = status; } public String getBankStatus() { return bankStatus; } public void setBankStatus(String bankStatus) { this.bankStatus = bankStatus; } public Date getBankSuccessTime() { return bankSuccessTime; } public void setBankSuccessTime(Date bankSuccessTime) { this.bankSuccessTime = bankSuccessTime; } public String getBankTrxNo() { return bankTrxNo; } public void setBankTrxNo(String bankTrxNo) { this.bankTrxNo = bankTrxNo; } public BankCardTypeEnum getCardType() { return cardType; } public void setCardType(BankCardTypeEnum cardType) { this.cardType = cardType; } public String getResponseStr() { return responseStr; } public void setResponseStr(String responseStr) { this.responseStr = responseStr; } }
kravitz/transims4
SysLib/Include/Toll_Data.hpp
//********************************************************* // Toll_Data.hpp - network toll data //********************************************************* #ifndef TOLL_DATA_HPP #define TOLL_DATA_HPP #include "Class_Index.hpp" #include "Class_Array.hpp" //--------------------------------------------------------- // Toll_Data class definition //--------------------------------------------------------- class Toll_Data : public Class_Index { public: Toll_Data (int link_dir = 0); virtual ~Toll_Data (void) {} int Link_Dir (void) { return (ID ()); } int Link (void) { return ((ID () >> 1)); } int Dir (void) { return ((ID () & 1)); } int Start (void) { return (start); } int End (void) { return (end); } int Use (void) { return (use); } int Toll (void) { return (toll); } int TOD_List (void) { return (list); } void Link_Dir (int value) { ID (value); } void Link (int value) { ID ((value << 1) + Dir ()); } void Dir (int value) { ID ((Link () << 1) + value); } void Start (int value) { start = value; } void End (int value) { end = value; } void Use (int value) { use = (unsigned short) value; } void Toll (int value) { toll = (unsigned short) value; } void TOD_List (int value) { list = value; } private: int start; //---- rounded ---- int end; //---- rounded ---- unsigned short use; unsigned short toll; //---- cents ---- int list; }; //--------------------------------------------------------- // Toll_Array class definition //--------------------------------------------------------- class Toll_Array : public Class_Array { public: Toll_Array (int max_records = 0); bool Add (Toll_Data *data = NULL) { return (Class_Array::Add (data)); } Toll_Data * New_Record (bool clear = false, int number = 1) { return ((Toll_Data *) Class_Array::New_Record (clear, number)); } Toll_Data * Record (int index) { return ((Toll_Data *) Class_Array::Record (index)); } Toll_Data * Record (void) { return ((Toll_Data *) Class_Array::Record ()); } Toll_Data * Get (int link) { return ((Toll_Data *) Class_Array::Get (link)); } Toll_Data * Get_GE (int link) { return ((Toll_Data *) Class_Array::Get_GE (link)); } Toll_Data * Get_LE (int link) { return ((Toll_Data *) Class_Array::Get_LE (link)); } Toll_Data * First (void) { return ((Toll_Data *) Class_Array::First ()); } Toll_Data * Next (void) { return ((Toll_Data *) Class_Array::Next ()); } Toll_Data * Last (void) { return ((Toll_Data *) Class_Array::Last ()); } Toll_Data * Previous (void) { return ((Toll_Data *) Class_Array::Previous ()); } Toll_Data * First_Key (void) { return ((Toll_Data *) Class_Array::First_Key ()); } Toll_Data * Next_Key (void) { return ((Toll_Data *) Class_Array::Next_Key ()); } Toll_Data * operator[] (int index) { return (Record (index)); } }; #endif
sola-da/LambdaTester
experiments/every/everyGen/test686.js
var callbackArguments = []; var argument1 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) base_0[7] = "" return a-b*c }; var argument2 = {"157":"","783":0,"1.6387309732655129e+308":1.0334437466942613e+308,"":705,"9.553967314964856e+307":-100,"4.0176776835119257e+307":8.643476709719733e+307,"1.2469857714477715e+308":"yS,","1.0495403030958161e+308":"o","1.775206595900278e+308":"<","1.7920735092160647e+308":"[=_"}; var argument3 = false; var argument4 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) argument5[1] = ["LAqIfQz","+"] return a*b+c }; var argument5 = {"4.255294604624472e+307":-100,"1.5690116573747888e+308":7.499105561396426e+307,"":"942O]erm"}; var argument6 = true; var argument7 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) argument8[4] = 1.518653309817878e+308 base_2[0][6] = {"843":"*"} return a-b+c }; var argument8 = false; var argument9 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) base_3[1][5] = 1.7976931348623157e+308 argument10[4.960033715165713e+307] = 8.544899600130169e+307 argument9[2] = {"{":"","":595,"7.771442629080406e+307":"","0b)":")|d","-100":""} return a*b-c }; var argument10 = "g_"; var argument11 = "`?"; var base_0 = [607,893,595,893] var r_0= undefined try { r_0 = base_0.every(argument1,argument2,argument3) } catch(e) { r_0= "Error" } var base_1 = [607,893,595,893] var r_1= undefined try { r_1 = base_1.every(argument4,argument5,argument6) } catch(e) { r_1= "Error" } var base_2 = [607,893,595,893] var r_2= undefined try { r_2 = base_2.every(argument7,argument8) } catch(e) { r_2= "Error" } var base_3 = [607,893,595,893] var r_3= undefined try { r_3 = base_3.every(argument9,argument10,argument11) } catch(e) { r_3= "Error" } function serialize(array){ return array.map(function(a){ if (a === null || a == undefined) return a; var name = a.constructor.name; if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String') return JSON.stringify(a); return name; }); } setTimeout(function(){ require("fs").writeFileSync("./experiments/every/everyGen/test686.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments})) },300)
LindsayBradford/StopWatchUtility
src/main/java/blacksmyth/stopwatch/view/swing/StopWatchCommand.java
<filename>src/main/java/blacksmyth/stopwatch/view/swing/StopWatchCommand.java /** * Copyright (c) 2016, <NAME> and other Contributors. * All rights reserved. * * This program and the accompanying materials are made available * under the terms of the BSD 3-Clause licence which accompanies * this distribution, and is available at * http://opensource.org/licenses/BSD-3-Clause */ package blacksmyth.stopwatch.view.swing; /** * An interface that all stop watch commands are expected to implement. Based on {@link Runnable}, * the implemented command is expected to contain all refernces to other objects its needs to successfully * trigger one or more {@link StopWatchViewEvent}s. */ interface StopWatchCommand extends Runnable {}
lauracristinaes/aula-java
Aula-2709/src/Heranca/Colaborador.java
<filename>Aula-2709/src/Heranca/Colaborador.java package Heranca; import Pessoa.Pessoa; public class Colaborador extends Pessoa { private String carteiraTrabalho; private String cargo; private double salario; }
canuc/meow-engine
events/camera_following_event.cpp
#include "events/camera_following_event.h" int CameraFollowingEvent::processEvent(lua_State* L) { lua_pushnil(L); while(lua_next(L, -2) != 0) { const char *eventType = lua_tostring(L, -2); if (strncmp(eventType, ANIMATION_OFFSET_KEY, strlen(ANIMATION_OFFSET_KEY)) == 0 && lua_istable(L, -1)) { cameraOffset = lua_getvec3(L); } lua_pop(L, 1); } lua_pushinteger(L, getEventId()); return 1; } CameraState * CameraFollowingEvent::createAnimationState(Actor * character) const { return new FollowingState(character,cameraOffset); }
hpgit/HumanFoot
PyCommon/externalLibs/BaseLib/math/nr/cpp/recipes/laguer.cpp
#include <cmath> #include <complex> #include <limits> #include "nr.h" using namespace std; void NR::laguer(Vec_I_CPLX_DP &a, complex<DP> &x, int &its) { const int MR=8,MT=10,MAXIT=MT*MR; const DP EPS=numeric_limits<DP>::epsilon(); static const DP frac[MR+1]= {0.0,0.5,0.25,0.75,0.13,0.38,0.62,0.88,1.0}; int iter,j; DP abx,abp,abm,err; complex<DP> dx,x1,b,d,f,g,h,sq,gp,gm,g2; int m=a.size()-1; for (iter=1;iter<=MAXIT;iter++) { its=iter; b=a[m]; err=abs(b); d=f=0.0; abx=abs(x); for (j=m-1;j>=0;j--) { f=x*f+d; d=x*d+b; b=x*b+a[j]; err=abs(b)+abx*err; } err *= EPS; if (abs(b) <= err) return; g=d/b; g2=g*g; h=g2-2.0*f/b; sq=sqrt(DP(m-1)*(DP(m)*h-g2)); gp=g+sq; gm=g-sq; abp=abs(gp); abm=abs(gm); if (abp < abm) gp=gm; dx=MAX(abp,abm) > 0.0 ? DP(m)/gp : polar(1+abx,DP(iter)); x1=x-dx; if (x == x1) return; if (iter % MT != 0) x=x1; else x -= frac[iter/MT]*dx; } nrerror("too many iterations in laguer"); return; }
121arijit/jeneratedata
src/com/googlecode/jeneratedata/dates/DateGenerator.java
<gh_stars>0 package com.googlecode.jeneratedata.dates; import java.util.Calendar; import java.util.Date; import java.util.Random; import com.googlecode.jeneratedata.core.Generator; /** * Generates {@link Date} instances between two given dates. * * @author <NAME> <<EMAIL>> */ public class DateGenerator implements Generator<Date> { /** * {@link Random} instance to generate values within the given period. */ private Random random; /** * The start of the period (as returned by {@link Date#getTime()} that * contains the generated data items. */ private Long startTime; /** * The end of the period (as returned by {@link Date#getTime()} that * contains the generated data items. */ private Long endTime; /** * Constructor. * * @param start The start of the period that contains the generated data * items. * @param end The start of the period that contains the generated data * items. */ public DateGenerator(Date start, Date end) { super(); this.startTime = start.getTime(); this.endTime = end.getTime(); random = new Random(); } /** * Constructor. * * @param start The start of the period that contains the generated data * items. * @param end The start of the period that contains the generated data * items. */ public DateGenerator(Calendar start, Calendar end) { this(start.getTime(), end.getTime()); } /* (non-Javadoc) * @see com.googlecode.jeneratedata.core.Generator#generate() */ @Override public Date generate() { return new Date(startTime + ((Double) ((endTime - startTime) * random.nextDouble())).longValue()); } }
TomasHofman/infinispan
core/src/main/java/org/infinispan/conflict/impl/InternalConflictManager.java
package org.infinispan.conflict.impl; import org.infinispan.conflict.ConflictManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.topology.CacheTopology; /** * @author <NAME> * @since 9.1 */ @Scope(Scopes.NAMED_CACHE) public interface InternalConflictManager<K, V> extends ConflictManager<K, V> { void onTopologyUpdate(LocalizedCacheTopology cacheTopology); void cancelVersionRequests(); void restartVersionRequests(); void resolveConflicts(CacheTopology cacheTopology); }
f4deb/cen-electronic
robot/strategy/gameStrategyOutsidePathHandler.h
#ifndef GAME_STRATEGY_OUTSIDE_PATH_HANDLER #define GAME_STRATEGY_OUTSIDE_PATH_HANDLER #include "gameStrategyHandler.h" /** * Creates a new "route" for the robot which is not on a classical Path ! */ void gameStrategyCreateOutsideTemporaryPaths(GameStrategyContext* gameStrategyContext); /** * Do the cleanup when the robot is back to the Track. */ void gameStrategyClearOusideTemporaryPathsAndLocations(GameStrategyContext* gameStrategyContext); #endif
jnthn/intellij-community
python/testData/refactoring/extractmethod/GlobalVarAssignment.after.py
x = 0 def foo(): global x bar() def bar(): global x x = 1
mmonrealv/inversion-engine
inversion-jdbc/src/test/java/io/inversion/jdbc/postgres/PostgresRqlIntegTest.java
/* * Copyright (c) 2015-2020 Rocket Partners, LLC * https://github.com/inversion-api * * 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 io.inversion.jdbc.postgres; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; @TestInstance(Lifecycle.PER_CLASS) public class PostgresRqlIntegTest extends PostgresRqlUnitTest { public PostgresRqlIntegTest() throws Exception { super(); withExpectedResult("manyTManyNotExistsNe", "SELECT \"employees\".* FROM \"employees\" WHERE NOT EXISTS (SELECT 1 FROM \"order_details\" \"~~relTbl_order_details\", \"employeeorderdetails\" \"~~lnkTbl_employeeorderdetails\" WHERE \"employees\".\"EmployeeID\" = \"~~lnkTbl_employeeorderdetails\".\"EmployeeID\" AND \"~~lnkTbl_employeeorderdetails\".\"OrderID\" = \"~~relTbl_order_details\".\"OrderID\" AND \"~~lnkTbl_employeeorderdetails\".\"ProductID\" = \"~~relTbl_order_details\".\"ProductID\" AND \"~~relTbl_order_details\".\"Quantity\" = ?) ORDER BY \"employees\".\"EmployeeID\" ASC LIMIT 100 OFFSET 0 args=[12]"); } }
sirineFruition/angular-project-mon-terroir
app/appuser/app-user.js
<gh_stars>0 System.register([], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var User; return { setters:[], execute: function() { User = (function () { function User(username, terroirs) { } return User; }()); exports_1("User", User); } } }); //# sourceMappingURL=app-user.js.map
billforward/bf-python
billforward/models/flat_pricing_component.py
<reponame>billforward/bf-python<filename>billforward/models/flat_pricing_component.py # coding: utf-8 """ BillForward REST API OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git 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. """ from pprint import pformat from six import iteritems import re class FlatPricingComponent(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, created=None, changed_by=None, updated=None, type=None, version_id=None, crm_id=None, id=None, product_rate_plan_id=None, unit_of_measure_id=None, organization_id=None, name=None, public_name=None, description=None, charge_type=None, invoicing_type=None, charge_model=None, upgrade_mode=None, downgrade_mode=None, default_quantity=None, min_quantity=None, max_quantity=None, valid_from=None, valid_till=None, tiers=None, unit_of_measure=None): """ FlatPricingComponent - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'created': 'datetime', 'changed_by': 'str', 'updated': 'datetime', 'type': 'str', 'version_id': 'str', 'crm_id': 'str', 'id': 'str', 'product_rate_plan_id': 'str', 'unit_of_measure_id': 'str', 'organization_id': 'str', 'name': 'str', 'public_name': 'str', 'description': 'str', 'charge_type': 'str', 'invoicing_type': 'str', 'charge_model': 'str', 'upgrade_mode': 'str', 'downgrade_mode': 'str', 'default_quantity': 'int', 'min_quantity': 'int', 'max_quantity': 'int', 'valid_from': 'datetime', 'valid_till': 'datetime', 'tiers': 'list[PricingComponentTier]', 'unit_of_measure': 'UnitOfMeasure' } self.attribute_map = { 'created': 'created', 'changed_by': 'changedBy', 'updated': 'updated', 'type': '@type', 'version_id': 'versionID', 'crm_id': 'crmID', 'id': 'id', 'product_rate_plan_id': 'productRatePlanID', 'unit_of_measure_id': 'unitOfMeasureID', 'organization_id': 'organizationID', 'name': 'name', 'public_name': 'publicName', 'description': 'description', 'charge_type': 'chargeType', 'invoicing_type': 'invoicingType', 'charge_model': 'chargeModel', 'upgrade_mode': 'upgradeMode', 'downgrade_mode': 'downgradeMode', 'default_quantity': 'defaultQuantity', 'min_quantity': 'minQuantity', 'max_quantity': 'maxQuantity', 'valid_from': 'validFrom', 'valid_till': 'validTill', 'tiers': 'tiers', 'unit_of_measure': 'unitOfMeasure' } self._created = created self._changed_by = changed_by self._updated = updated self._type = type self._version_id = version_id self._crm_id = crm_id self._id = id self._product_rate_plan_id = product_rate_plan_id self._unit_of_measure_id = unit_of_measure_id self._organization_id = organization_id self._name = name self._public_name = public_name self._description = description self._charge_type = charge_type self._invoicing_type = invoicing_type self._charge_model = charge_model self._upgrade_mode = upgrade_mode self._downgrade_mode = downgrade_mode self._default_quantity = default_quantity self._min_quantity = min_quantity self._max_quantity = max_quantity self._valid_from = valid_from self._valid_till = valid_till self._tiers = tiers self._unit_of_measure = unit_of_measure @property def created(self): """ Gets the created of this FlatPricingComponent. { \"description\" : \"The UTC DateTime when the object was created.\", \"verbs\":[] } :return: The created of this FlatPricingComponent. :rtype: datetime """ return self._created @created.setter def created(self, created): """ Sets the created of this FlatPricingComponent. { \"description\" : \"The UTC DateTime when the object was created.\", \"verbs\":[] } :param created: The created of this FlatPricingComponent. :type: datetime """ self._created = created @property def changed_by(self): """ Gets the changed_by of this FlatPricingComponent. { \"description\" : \"ID of the user who last updated the entity.\", \"verbs\":[] } :return: The changed_by of this FlatPricingComponent. :rtype: str """ return self._changed_by @changed_by.setter def changed_by(self, changed_by): """ Sets the changed_by of this FlatPricingComponent. { \"description\" : \"ID of the user who last updated the entity.\", \"verbs\":[] } :param changed_by: The changed_by of this FlatPricingComponent. :type: str """ self._changed_by = changed_by @property def updated(self): """ Gets the updated of this FlatPricingComponent. { \"description\" : \"The UTC DateTime when the object was last updated.\", \"verbs\":[] } :return: The updated of this FlatPricingComponent. :rtype: datetime """ return self._updated @updated.setter def updated(self, updated): """ Sets the updated of this FlatPricingComponent. { \"description\" : \"The UTC DateTime when the object was last updated.\", \"verbs\":[] } :param updated: The updated of this FlatPricingComponent. :type: datetime """ self._updated = updated @property def type(self): """ Gets the type of this FlatPricingComponent. { \"description\" : \"\", \"default\" : \"\", \"verbs\":[\"POST\",\"GET\"] } :return: The type of this FlatPricingComponent. :rtype: str """ return self._type @type.setter def type(self, type): """ Sets the type of this FlatPricingComponent. { \"description\" : \"\", \"default\" : \"\", \"verbs\":[\"POST\",\"GET\"] } :param type: The type of this FlatPricingComponent. :type: str """ allowed_values = ["tieredPricingComponent", "flatPricingComponent", "tieredVolumePricingComponent"] if type not in allowed_values: raise ValueError( "Invalid value for `type` ({0}), must be one of {1}" .format(type, allowed_values) ) self._type = type @property def version_id(self): """ Gets the version_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"GET\"] } :return: The version_id of this FlatPricingComponent. :rtype: str """ return self._version_id @version_id.setter def version_id(self, version_id): """ Sets the version_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"GET\"] } :param version_id: The version_id of this FlatPricingComponent. :type: str """ self._version_id = version_id @property def crm_id(self): """ Gets the crm_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The crm_id of this FlatPricingComponent. :rtype: str """ return self._crm_id @crm_id.setter def crm_id(self, crm_id): """ Sets the crm_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param crm_id: The crm_id of this FlatPricingComponent. :type: str """ self._crm_id = crm_id @property def id(self): """ Gets the id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"GET\"] } When associating a pricing component with a product rate plan, this ID should be used. :return: The id of this FlatPricingComponent. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"GET\"] } When associating a pricing component with a product rate plan, this ID should be used. :param id: The id of this FlatPricingComponent. :type: str """ self._id = id @property def product_rate_plan_id(self): """ Gets the product_rate_plan_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The product_rate_plan_id of this FlatPricingComponent. :rtype: str """ return self._product_rate_plan_id @product_rate_plan_id.setter def product_rate_plan_id(self, product_rate_plan_id): """ Sets the product_rate_plan_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param product_rate_plan_id: The product_rate_plan_id of this FlatPricingComponent. :type: str """ self._product_rate_plan_id = product_rate_plan_id @property def unit_of_measure_id(self): """ Gets the unit_of_measure_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The unit_of_measure_id of this FlatPricingComponent. :rtype: str """ return self._unit_of_measure_id @unit_of_measure_id.setter def unit_of_measure_id(self, unit_of_measure_id): """ Sets the unit_of_measure_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param unit_of_measure_id: The unit_of_measure_id of this FlatPricingComponent. :type: str """ self._unit_of_measure_id = unit_of_measure_id @property def organization_id(self): """ Gets the organization_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[] } :return: The organization_id of this FlatPricingComponent. :rtype: str """ return self._organization_id @organization_id.setter def organization_id(self, organization_id): """ Sets the organization_id of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[] } :param organization_id: The organization_id of this FlatPricingComponent. :type: str """ self._organization_id = organization_id @property def name(self): """ Gets the name of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The name of this FlatPricingComponent. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param name: The name of this FlatPricingComponent. :type: str """ self._name = name @property def public_name(self): """ Gets the public_name of this FlatPricingComponent. {\"description\":\"A friendly non-unique name used to identify this pricing-component\",\"verbs\":[\"POST\",\"PUT\",\"GET\"]} :return: The public_name of this FlatPricingComponent. :rtype: str """ return self._public_name @public_name.setter def public_name(self, public_name): """ Sets the public_name of this FlatPricingComponent. {\"description\":\"A friendly non-unique name used to identify this pricing-component\",\"verbs\":[\"POST\",\"PUT\",\"GET\"]} :param public_name: The public_name of this FlatPricingComponent. :type: str """ self._public_name = public_name @property def description(self): """ Gets the description of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The description of this FlatPricingComponent. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this FlatPricingComponent. { \"description\" : \"\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param description: The description of this FlatPricingComponent. :type: str """ self._description = description @property def charge_type(self): """ Gets the charge_type of this FlatPricingComponent. { \"description\" : \"The charge type of the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The charge_type of this FlatPricingComponent. :rtype: str """ return self._charge_type @charge_type.setter def charge_type(self, charge_type): """ Sets the charge_type of this FlatPricingComponent. { \"description\" : \"The charge type of the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param charge_type: The charge_type of this FlatPricingComponent. :type: str """ allowed_values = ["setup", "subscription", "arrears", "usage"] if charge_type not in allowed_values: raise ValueError( "Invalid value for `charge_type` ({0}), must be one of {1}" .format(charge_type, allowed_values) ) self._charge_type = charge_type @property def invoicing_type(self): """ Gets the invoicing_type of this FlatPricingComponent. { \"default\" : \"Aggregated\", \"description\" : \"For <span class=\\\"label label-default\\\">setup</span> pricing components <span class=\\\"label label-default\\\">Immediate</span> invoicing will result in an invoice being issued on subscription being set to the AwaitingPayment state, irrespective of the subscription start date. <span class=\\\"label label-default\\\">Aggregated</span> invoicing will add a charge to the first invoice of the subscription.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The invoicing_type of this FlatPricingComponent. :rtype: str """ return self._invoicing_type @invoicing_type.setter def invoicing_type(self, invoicing_type): """ Sets the invoicing_type of this FlatPricingComponent. { \"default\" : \"Aggregated\", \"description\" : \"For <span class=\\\"label label-default\\\">setup</span> pricing components <span class=\\\"label label-default\\\">Immediate</span> invoicing will result in an invoice being issued on subscription being set to the AwaitingPayment state, irrespective of the subscription start date. <span class=\\\"label label-default\\\">Aggregated</span> invoicing will add a charge to the first invoice of the subscription.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param invoicing_type: The invoicing_type of this FlatPricingComponent. :type: str """ allowed_values = ["Immediate", "Aggregated"] if invoicing_type not in allowed_values: raise ValueError( "Invalid value for `invoicing_type` ({0}), must be one of {1}" .format(invoicing_type, allowed_values) ) self._invoicing_type = invoicing_type @property def charge_model(self): """ Gets the charge_model of this FlatPricingComponent. { \"description\" : \"The charge model of the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The charge_model of this FlatPricingComponent. :rtype: str """ return self._charge_model @charge_model.setter def charge_model(self, charge_model): """ Sets the charge_model of this FlatPricingComponent. { \"description\" : \"The charge model of the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param charge_model: The charge_model of this FlatPricingComponent. :type: str """ allowed_values = ["flat", "tiered", "tiered_volume"] if charge_model not in allowed_values: raise ValueError( "Invalid value for `charge_model` ({0}), must be one of {1}" .format(charge_model, allowed_values) ) self._charge_model = charge_model @property def upgrade_mode(self): """ Gets the upgrade_mode of this FlatPricingComponent. {\"default\":\"<span class=\\\"label label-default\\\">immediate</span>\",\"description\":\"Default behaviour when a value is upgraded using this pricing component, this behaviour can be overridden when changing the value.<br><span class=\\\"label label-default\\\">immediate</span> &mdash; Upgrade will apply at the time the request is made.<br><span class=\\\"label label-default\\\">delayed</span> &mdash; Upgrade will apply at the end of the current billing cycle.\",\"verbs\":[\"POST\",\"GET\"]} :return: The upgrade_mode of this FlatPricingComponent. :rtype: str """ return self._upgrade_mode @upgrade_mode.setter def upgrade_mode(self, upgrade_mode): """ Sets the upgrade_mode of this FlatPricingComponent. {\"default\":\"<span class=\\\"label label-default\\\">immediate</span>\",\"description\":\"Default behaviour when a value is upgraded using this pricing component, this behaviour can be overridden when changing the value.<br><span class=\\\"label label-default\\\">immediate</span> &mdash; Upgrade will apply at the time the request is made.<br><span class=\\\"label label-default\\\">delayed</span> &mdash; Upgrade will apply at the end of the current billing cycle.\",\"verbs\":[\"POST\",\"GET\"]} :param upgrade_mode: The upgrade_mode of this FlatPricingComponent. :type: str """ allowed_values = ["immediate", "delayed"] if upgrade_mode not in allowed_values: raise ValueError( "Invalid value for `upgrade_mode` ({0}), must be one of {1}" .format(upgrade_mode, allowed_values) ) self._upgrade_mode = upgrade_mode @property def downgrade_mode(self): """ Gets the downgrade_mode of this FlatPricingComponent. {\"default\":\"<span class=\\\"label label-default\\\">delayed</span>\",\"description\":\"Default behaviour when a value is downgraded using this pricing component, this behaviour can be overridden when changing the value.<br><span class=\\\"label label-default\\\">immediate</span> &mdash; Downgrade will apply at the time the request is made.<br><span class=\\\"label label-default\\\">delayed</span> &mdash; Downgrade will apply at the end of the current billing cycle.\",\"verbs\":[\"POST\",\"GET\"]} :return: The downgrade_mode of this FlatPricingComponent. :rtype: str """ return self._downgrade_mode @downgrade_mode.setter def downgrade_mode(self, downgrade_mode): """ Sets the downgrade_mode of this FlatPricingComponent. {\"default\":\"<span class=\\\"label label-default\\\">delayed</span>\",\"description\":\"Default behaviour when a value is downgraded using this pricing component, this behaviour can be overridden when changing the value.<br><span class=\\\"label label-default\\\">immediate</span> &mdash; Downgrade will apply at the time the request is made.<br><span class=\\\"label label-default\\\">delayed</span> &mdash; Downgrade will apply at the end of the current billing cycle.\",\"verbs\":[\"POST\",\"GET\"]} :param downgrade_mode: The downgrade_mode of this FlatPricingComponent. :type: str """ allowed_values = ["immediate", "delayed"] if downgrade_mode not in allowed_values: raise ValueError( "Invalid value for `downgrade_mode` ({0}), must be one of {1}" .format(downgrade_mode, allowed_values) ) self._downgrade_mode = downgrade_mode @property def default_quantity(self): """ Gets the default_quantity of this FlatPricingComponent. { \"description\" : \"The default quantity of the pricing-component. If no value is supplied on a subscription this value will be used. This is useful for setting an expected purchase level of for introducing new pricing components to existing subscriptions and not having to back-fill values\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The default_quantity of this FlatPricingComponent. :rtype: int """ return self._default_quantity @default_quantity.setter def default_quantity(self, default_quantity): """ Sets the default_quantity of this FlatPricingComponent. { \"description\" : \"The default quantity of the pricing-component. If no value is supplied on a subscription this value will be used. This is useful for setting an expected purchase level of for introducing new pricing components to existing subscriptions and not having to back-fill values\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param default_quantity: The default_quantity of this FlatPricingComponent. :type: int """ self._default_quantity = default_quantity @property def min_quantity(self): """ Gets the min_quantity of this FlatPricingComponent. { \"default\" : \"0\", \"description\" : \"The minimum quantity of the pricing-component.\", \"verbs\":[] } :return: The min_quantity of this FlatPricingComponent. :rtype: int """ return self._min_quantity @min_quantity.setter def min_quantity(self, min_quantity): """ Sets the min_quantity of this FlatPricingComponent. { \"default\" : \"0\", \"description\" : \"The minimum quantity of the pricing-component.\", \"verbs\":[] } :param min_quantity: The min_quantity of this FlatPricingComponent. :type: int """ self._min_quantity = min_quantity @property def max_quantity(self): """ Gets the max_quantity of this FlatPricingComponent. { \"description\" : \"The maximum quantity of the pricing-component.\", \"verbs\":[] } :return: The max_quantity of this FlatPricingComponent. :rtype: int """ return self._max_quantity @max_quantity.setter def max_quantity(self, max_quantity): """ Sets the max_quantity of this FlatPricingComponent. { \"description\" : \"The maximum quantity of the pricing-component.\", \"verbs\":[] } :param max_quantity: The max_quantity of this FlatPricingComponent. :type: int """ self._max_quantity = max_quantity @property def valid_from(self): """ Gets the valid_from of this FlatPricingComponent. { \"default\" : \"current time\", \"description\" : \"The DateTime specifying when the pricing-component is valid from.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The valid_from of this FlatPricingComponent. :rtype: datetime """ return self._valid_from @valid_from.setter def valid_from(self, valid_from): """ Sets the valid_from of this FlatPricingComponent. { \"default\" : \"current time\", \"description\" : \"The DateTime specifying when the pricing-component is valid from.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param valid_from: The valid_from of this FlatPricingComponent. :type: datetime """ self._valid_from = valid_from @property def valid_till(self): """ Gets the valid_till of this FlatPricingComponent. { \"default\" : \"null\", \"description\" : \"The UTC DateTime specifying when the pricing-component is valid till.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The valid_till of this FlatPricingComponent. :rtype: datetime """ return self._valid_till @valid_till.setter def valid_till(self, valid_till): """ Sets the valid_till of this FlatPricingComponent. { \"default\" : \"null\", \"description\" : \"The UTC DateTime specifying when the pricing-component is valid till.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param valid_till: The valid_till of this FlatPricingComponent. :type: datetime """ self._valid_till = valid_till @property def tiers(self): """ Gets the tiers of this FlatPricingComponent. { \"default\" : \"[]\", \"description\" : \"The pricing-component-tiers associated with the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The tiers of this FlatPricingComponent. :rtype: list[PricingComponentTier] """ return self._tiers @tiers.setter def tiers(self, tiers): """ Sets the tiers of this FlatPricingComponent. { \"default\" : \"[]\", \"description\" : \"The pricing-component-tiers associated with the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param tiers: The tiers of this FlatPricingComponent. :type: list[PricingComponentTier] """ self._tiers = tiers @property def unit_of_measure(self): """ Gets the unit_of_measure of this FlatPricingComponent. { \"description\" : \"The unit-of-measure associated with the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :return: The unit_of_measure of this FlatPricingComponent. :rtype: UnitOfMeasure """ return self._unit_of_measure @unit_of_measure.setter def unit_of_measure(self, unit_of_measure): """ Sets the unit_of_measure of this FlatPricingComponent. { \"description\" : \"The unit-of-measure associated with the pricing-component.\", \"verbs\":[\"POST\",\"PUT\",\"GET\"] } :param unit_of_measure: The unit_of_measure of this FlatPricingComponent. :type: UnitOfMeasure """ self._unit_of_measure = unit_of_measure def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
CodeNow/palantiri
lib/external/docker.js
<filename>lib/external/docker.js /** * Docker API requests * @module lib/external/docker */ 'use strict' require('loadenv')() const async = require('async') const DockerClient = require('@runnable/loki').Docker const DockerUtils = require('@runnable/loki').Utils const Promise = require('bluebird') const logger = require('./logger')() Promise.promisifyAll(async) module.exports = class Docker extends DockerClient { /** * creates docker class * @param {String} host docker host format: [https://]hostname:hostport * @return {Docker} Docker instance */ constructor (host) { const dockerHost = DockerUtils.toDockerUrl(host) super({ host: dockerHost, log: logger }) this.logger = logger.child({ dockerHost: this.dockerHost }) } /** * Returns list of all images * @return {Promise} * @resolves {DockerImages[]} all images on dockerhost * DockerImages: { * Id: 'sha256:e50427e890a7c83beacf646a2bb283379989f04e1de0beac9448546a0b51b429', * ParentId: '', * RepoTags: [ 'weaveworks/weave:1.4.6' ], * RepoDigests: null, * Created: 1458754743, * Size: 19295936, * VirtualSize: 19295936, * Labels: { 'works.weave.role': 'system' } * } */ listImages () { const log = this.logger.child({ method: 'listImages' }) log.info('listImages called') return this.listImagesAsync({ all: true }) } /** * Deletes a volume by its name * @param {String} volumeName */ removeVolume (volumeName) { const log = this.logger.child({ volumeName, method: 'removeVolume' }) log.info('called') // Workaround to give docker time to release volume to be deleted return Promise.fromCallback((cb) => { this.client.getVolume(volumeName).remove(cb) }) } /** * Lists volumes that aren't associated with any running container * @resolves {DockerVolumes[]} */ listDanglingVolumes () { const log = this.logger.child({ method: 'listDanglingVolumes' }) log.info('called') return this.listVolumesAsync({ dangling: true }) } /** * pushes docker image to registry. Resolves when push complete * @param {string} imageId id of image to push to registry * format: registry.runnable.com/123/456:<tag> * @return {Promise} Resolves when push complete */ pushImage (imageTag) { const log = this.logger.child({ imageTag: imageTag, method: 'Docker.pushImage' }) log.info('pushImage called') var tag = imageTag.split(':')[1] return Promise.fromCallback((cb) => { this.client.getImage(imageTag).push({ tag: tag }, (err, stream) => { if (err) { return cb(err) } // followProgress will return with an argument if error this.client.modem.followProgress(stream, cb) }) }) } /** * remove docker image * pushes docker image to registry. Resolves when push complete * @param {string} imageTag id of image to push to registry * format: registry.runnable.com/123/456:<tag> * @return {Promise} Resolves when push complete */ removeImage (imageTag) { const log = this.logger.child({ imageTag: imageTag, method: 'Docker removeImage' }) log.info('removeImage called') return Promise.fromCallback((cb) => { this.client.getImage(imageTag).remove(cb) }) } }
SelvorWhim/competitive
ACM-ICPC/icpc_7272.cpp
// problem 1/2 - which employees always appear in the first A/B of a topological sort? // problem 3 - which employees always appear after the first B in a topological sort? // Can I check all options in the topological? //// no way, that could be like E! I could maybe count them in less but this requires seeing which employees are where in the orderings... // ok so an employee is certainly not promoted if they have too many people above them (traisitively) (B). //// If there are fewer, because transitivity those people have fewer above them and can all be promoted and then the employee can be promoted, so that's a sufficient // similarly certainly promoted if everybody else is below, or enough people below that the rest are less than A/B. So at least E-A/B people below //// and if there are fewer below, that means there's at least A/B above or "to the side" and they can be promoted before you since you're not above them, so you're not guaranteed // need to search in reverse for problem 3 so gotta be adjacency matrix // based on accepted and unaccepted answer, looks like multiple inputs are a thing and outputs should just follow one another with no extra lines #include <iostream> #include <algorithm> //#include <sstream> #include <string> #include <set> #include <vector> //#include <map> //#include <cmath> using namespace std; #define MAX_N 5001 vector<vector<int> > adj; // adjacency list vector<vector<int> > rev_adj; // reverse graph adjacency list set<int> succ; // successors // DFS // input: an adjacency list describing an undirected/directed graph (g) // visible indicates which vertices where already seen // modified to work on either adj, save set instead of printing, for easy counting void dfs(vector<vector<int> >& adjl, int s) { //cout<<s<<endl; succ.insert(s); int n = adjl[s].size(); for(int i=0; i<n; i++) // removed auto thing for c++ 11..? { int x = adjl[s][i]; if(succ.find(x) != succ.end()) continue; dfs(adjl, x); } } int main() { // read - based on 4287 int A, B, E, P; while(cin >> A >> B >> E >> P) { adj = vector<vector<int> >(E, vector<int>()); rev_adj = vector<vector<int> >(E, vector<int>()); for (int i = 0; i < P; i++){ int s1, s2; cin >> s1 >> s2; adj[s1].push_back(s2); rev_adj[s2].push_back(s1); } int certain_A = 0; // certain if A are promoted int certain_B = 0; // certain if B are promoted int nochance_B = 0; // haha nope! How many definitely won't be promoted. for (int s = 0; s < E; s++){ succ.clear(); dfs(adj, s); if(succ.size() > E-B){ // succ.size()-1 = all but the node itself certain_B++; if(succ.size() > E-A){ certain_A++; } } succ.clear(); dfs(rev_adj, s); if(succ.size() > B){ nochance_B++; // boo hoo } } cout << certain_A << "\n" << certain_B << "\n" << nochance_B << "\n"; } return 0; }
sumeshmn/Visionlib
setup.py
<reponame>sumeshmn/Visionlib import setuptools with open("README.md", "r") as rd: long_description = rd.read() setuptools.setup( name="visionlib", version="1.4.5", author="<NAME>", author_email="<EMAIL>", url="https://github.com/ashwinvin/Visionlib", download_url="https://github.com/ashwinvin/Visionlib/archive/v1.4.5.tar.gz", description="A simple, easy to use and customizeble cv library ", long_description=long_description, long_description_content_type="text/markdown", keywords=["Deep learning", "Vision", "cv"], packages=setuptools.find_packages(), include_package_data=True, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ "mtcnn", "opencv-python", " dlib", "wget", 'numpy', "pafy", 'youtube-dl' ], python_requires=">=3.6", )
ShineXxx/zhengwu
common/src/main/java/com/shine/common/exceptions/BaseXmlInfo.java
<filename>common/src/main/java/com/shine/common/exceptions/BaseXmlInfo.java package com.shine.common.exceptions; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.shine.common.constant.XmlErrorInfo; /** * Created with IntelliJ IDEA. * * @author Berry_Cooper. * @date 2019/8/29 11:55 * fileName:BaseXmlInfo * Use: */ @JacksonXmlRootElement(localName = "ERROR") public class BaseXmlInfo implements XmlErrorInfo { @JacksonXmlProperty(localName = "Code") private String code = "400"; @JacksonXmlProperty(localName = "Message") private String message = "操作失败"; public BaseXmlInfo() { } public BaseXmlInfo(String code, String message) { this.code = code; this.message = message; } @Override public String getCode() { return this.code; } @Override public String getMessage() { return this.message; } }
ictk-solution-dev/amazon-freertos-zrg3m-
vendors/ictkholdings/sdk/driver/chip/inc/hal_pwm.h
<gh_stars>0 /* Copyright Statement: * * (C) 2005-2016 MediaTek Inc. All rights reserved. * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. ("MediaTek") and/or its licensors. * Without the prior written permission of MediaTek and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * You may only use, reproduce, modify, or distribute (as applicable) MediaTek Software * if you have agreed to and been bound by the applicable license agreement with * MediaTek ("License Agreement") and been granted explicit permission to do so within * the License Agreement ("Permitted User"). If you are not a Permitted User, * please cease any access or use of MediaTek Software immediately. * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT MEDIATEK SOFTWARE RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES * ARE PROVIDED TO RECEIVER ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. */ #ifndef __HAL_PWM_H__ #define __HAL_PWM_H__ #include "hal_platform.h" #ifdef HAL_PWM_MODULE_ENABLED /** * @addtogroup HAL * @{ * @addtogroup PWM * @{ * This section introduces the Pulse-Width Modulation(PWM) APIs including terms and acronyms, * supported features, software architecture, details on how to use this driver, PWM function groups, enums, structures and functions. * @section HAL_PWM_Terms_Chapter Terms and acronyms * * |Terms |Details | * |------------------------------|------------------------------------------------------------------------| * |\b PWM | Pulse-Width Modulation. PWM is a modulation technique used to encode a message into a pulsing signal. For more information, please refer to <a href="https://en.wikipedia.org/wiki/Pulse-width_modulation"> PWM in Wikipedia </a>.| * @section HAL_PWM_Features_Chapter Supported features * * - \b Support \b polling \b mode. \n * The PWM generates the fixed waveform at the specified frequency and duty. The application can query current frequency and * duty of the polling mode. The PWM does not support interrupt mode. * \n * @section HAL_PWM_Architechture_Chapter Software architecture of PWM * * * -# PWM polling mode architecture.\n * Call hal_pwm_init() function to initialize the PWM source clock, then call hal_pwm_set_frequency() function to set the PWM frequency and get the total counter of the hardware. Total counter is PWM counter internal value at specified frequency. The duty cycle is calculated as the product of application's duty ratio and total counter. * Duty ratio is the ratio of duty counter over the total counter.\n * Call hal_pwm_set_duty_cycle() function to set the PWM duty cycle. Call hal_pwm_start() function to trigger PWM execution.\n * Call hal_pwm_get_frequency() and hal_pwm_get_duty_cycle() functions if the current frequency and duty cycle need to be retrieved.\n * Call hal_pwm_get_running_status() function to get the PWM status, either busy or idle. Call hal_pwm_stop() function to stop the PWM execution.\n * Polling mode architecture is similar to the polling mode architecture in HAL overview. See @ref HAL_Overview_3_Chapter for polling mode architecture.\n * * * @section HAL_PWM_Driver_Usage_Chapter How to use this driver * * @} * @} */ #ifdef HAL_PWM_FEATURE_ADVANCED_CONFIG /** * @addtogroup HAL * @{ * @addtogroup PWM * @{ * - Using PWM in polling mode. \n * Calculate the PWM frequency and duty cycle at fixed source clock. Assuming the source clock is 32kHz * and the applicaton needs a waveform at 200Hz frequency and 50% duty ratio.The calculations of division clock, * total count and duty cycle are based on the formuals as shown below. * 1. division_clock = source_clock/division * 2. total_count = division_clock/frequency * 3. duty_cycle = (total_count*duty_ratio)/100 * 4. Set count to PWM_COUNT register * 5. Set duty_cycle to PWM_THRES register * . * - Step1: Call hal_gpio_init() to init the pin.\n * - Step2: Call hal_pinmux_set_function() to set the pwm pinmux if the EPT is not in use. * - Step3: Call hal_pwm_init() to initialize the PWM source clock. * - Step4: Call hal_pwm_set_advanced_config() to select clock division, this is set as default and the configuration is optional. * - Step5: Call hal_pwm_set_frequency() to set frequency and get total count of the PWM hardware at the specific frequency. * - Step6: Call hal_pwm_set_duty_cycle() to set duty cycle according to total count and application's duty ratio. * - Step7: Call hal_pwm_start() to trigger PWM at a specified frequency and duty count values. * - Step8: Call hal_pwm_get_frequency() to get the current frenquency. * - Step9: Call hal_pwm_get_duty_cycle() to get the current duty_cycle. * - Step10: Call hal_pwm_stop()to stop the PWM. * - Step11: Call hal_pwm_deinit() to deinitialize the PWM. * - Sample code: * @code * hal_pwm_advanced_config_t division = HAL_PWM_CLOCK_DIVISION_2; * uint32_t duty_ratio = 50; //The range from 0 to 100. * uint32_t frequency = 200; * hal_pwm_source_clock_t source_clock = HAL_PWM_CLOCK_32KHZ; * * hal_gpio_init(HAL_GPIO_35); * //function index = HAL_GPIO_35_PWM5; for more information about pinmux please refernence hal_pinmux_define.h * hal_pinmux_set_function(HAL_GPIO_35, function_index);//Set the GPIO pinmux. * //Initialize the PWM source clock. * if(HAL_PWM_STATUS_OK != hal_pwm_init(HAL_PWM_5, source_clock)) { * //error handle * } * if(HAL_PWM_STATUS_OK != hal_pwm_set_advanced_config(HAL_PWM_5, division);) { * //error handle * } * //Set the frequency and get total count of the PWM hardware at the specific frequency. * if(HAL_PWM_STATUS_OK != hal_pwm_set_frequency(HAL_PWM_5, frequency, &total_count)) { * //error handle * } * duty_cycle = (total_count * duty_ratio)/100; //duty_cycle is calcauted as a product of application's duty_ratio and hardware's total_count. * //Enable PWM to start the timer. * if(HAL_PWM_STATUS_OK != hal_pwm_set_duty_cycle(HAL_PWM_5, duty_cycle)) { * //error handle * } * hal_pwm_start(HAL_PWM_5); //Trigger PWM execution. * //... * hal_pwm_get_frequency(HAL_PWM_5, &frequency); * hal_pwm_get_duty_cycle(HAL_PWM_5, &duty_cycle); * //... * hal_pwm_stop(HAL_PWM_5); //Stop the PWM. * hal_pwm_deinit(HAL_PWM_5); //Deinitialize the PWM. * * @endcode * @} * @} */ #else /** * @addtogroup HAL * @{ * @addtogroup PWM * @{ * - Use PWM with polling mode. \n * How to calculate PWM frequency and duty cycle at fixed souce clock. Assuming the crystal(XTAL) oscillator runs at 40MHz. * and the applicaton needs a waveform at 2kHz frequency and 50% duty ratio.The calculations of division clock, * total count and duty cycle are based on the formuals as shown below. * 1. total_count = source_clock/frequency * 2. duty_ cycle = (total_count*duty_ratio)/100 * 3. PWM_ON duration = duty_cycle * 4. PWM_OFF duration = total_count-PWM_ON duration * 5. Set PWM_ON duration to PWM_PARAM register 0~15 bit * 6. Set PWM_OFF duration to PWM_PARAM register 16~31 bit * . * - Step1: Call hal_gpio_init() to init the pin.\n * - Step2: Call hal_pinmux_set_function() to set the pwm pinmux if the EPT is not in use. * - Step3: Call hal_pwm_init() to initialize the PWM source clock. * - Step4: Call hal_pwm_set_frequency() to set frequency and get total count of the PWM hardware at the specific frequency. * - Step5: Call hal_pwm_set_duty_cycle() to set duty cycle according to total count and application's duty ratio. * - Step6: Call hal_pwm_start() to trigger PWM at a specified frequency and duty count values. * - Step7: Call hal_pwm_get_frequency() to get the current frenquency. * - Step8: Call hal_pwm_get_duty_cycle() to get the current duty_cycle. * - Step9: Call hal_pwm_stop()to stop the PWM. * - Step10: Call hal_pwm_deinit() to deinitialize the PWM. * - Sample code: * @code * uint32_t duty_ratio = 50; //The range from 0 to 100. * hal_pwm_source_clock_t source_clock = HAL_PWM_CLOCK_40MHZ; * uint32_t frequency = 2000; * * hal_gpio_init(HAL_GPIO_0); * //function index = HAL_GPIO_0_PWM0; for more information about pinmux please refernence hal_pinmux_define.h * hal_pinmux_set_function(HAL_GPIO_0, function_index);//Set the GPIO pinmux. * //Initialize the PWM source clock. * if(HAL_PWM_STATUS_OK != hal_pwm_init(source_clock)) { * //error handle * * } * //Sets frequency and gets total count of the PWM hardware at the specific frequency. * if(HAL_PWM_STATUS_OK != hal_pwm_set_frequency(HAL_PWM_0, frequency, &total_count)) { * //error handle * } * duty_cycle = (total_count * duty_ratio)/100; //duty_cycle is calcauted as a product of application's duty_ratio and hardware's total_count. * //Enable PWM to start the timer. * if(HAL_PWM_STATUS_OK != hal_pwm_set_duty_cycle(HAL_PWM_0, duty_cycle)) { * //error handle * } * hal_pwm_start(HAL_PWM_0); //Trigger PWM execution. * //... * hal_pwm_get_frequency(HAL_PWM_0, &frequency); * hal_pwm_get_duty_cycle(HAL_PWM_0, &duty_cycle); * //... * hal_pwm_stop(HAL_PWM_0); //Stop the PWM. * hal_pwm_deinit(); //Deinitialize the PWM. * * @endcode * @} * @} */ #endif /** * @addtogroup HAL * @{ * @addtogroup PWM * @{ */ #ifdef __cplusplus extern "C" { #endif /** @defgroup hal_pwm_enum Enum * @{ */ /** @brief This enum defines the API return type. */ typedef enum { HAL_PWM_STATUS_ERROR = -4, /**< An error occurred during the function call. */ HAL_PWM_STATUS_ERROR_CHANNEL = -3, /**< A wrong PWM channel is given. */ HAL_PWM_STATUS_INVALID_PARAMETER = -2, /**< A wrong parameter is given. */ HAL_PWM_STATUS_INVALID_FREQUENCY = -1, /**< A smaller frequency is given.*/ HAL_PWM_STATUS_OK = 0 /**< No error during the function call. */ } hal_pwm_status_t; /** @brief This enum defines the PWM running status. */ typedef enum { HAL_PWM_IDLE = 0, /**<The PWM status is idle. */ HAL_PWM_BUSY = 1 /**< The PWM status is busy. */ } hal_pwm_running_status_t; /** * @} */ #ifdef HAL_PWM_FEATURE_ADVANCED_CONFIG /** @defgroup hal_pwm_enum Enum * @{ */ /** @brief This enum defines PWM clock division advanced configuration */ typedef enum { HAL_PWM_CLOCK_DIVISION_1 = 0, /**< Specify the PWM source clock 1 division. */ HAL_PWM_CLOCK_DIVISION_2 = 1, /**< Specify the PWM source clock 2 division. */ HAL_PWM_CLOCK_DIVISION_4 = 2, /**< Specify the PWM source clock 4 division. */ HAL_PWM_CLOCK_DIVISION_8 = 3, /**< Specify the PWM source clock 8 division. */ HAL_PWM_CLOCK_DIVISION_MAX, /**< MAX number of source clock division. */ } hal_pwm_advanced_config_t; /** * @} */ #endif #ifdef HAL_PWM_FEATURE_SINGLE_SOURCE_CLOCK /** * @brief This function initializes the PWM hardware source clock. * @param[in] source_clock is the PWM source clock. For more details about the parameter, please refer to #hal_pwm_source_clock_t. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @note There are some limitations about the minimum frequency that we can set if we choose the related * source clock list in hal_pwm_source_clock_t, and the caculation formula is as follows:\n * \b The \b minimum \b frequency \b = \b \b ( \b the \b chosen \b source \b clock\b ) \b / \b 0XFFFF \n * For example:\n if we choose the clock of HAL_PWM_CLOCK_32KHZ, the minimum frequency that we can set is 0.5 Hz;\n * if we choose the clock of HAL_PWM_CLOCK_2MHZ, the minimum frequency that we can set is 30 Hz;\n * if we choose the clock of HAL_PWM_CLOCK_40MHZ, the minimum frequency that we can set is 610 Hz; * @warning For this chip, all the PWM channel is using the same clock once this function has been called. * @sa hal_pwm_deinit() */ hal_pwm_status_t hal_pwm_init(hal_pwm_source_clock_t source_clock); /** * @brief This function deinitializes the PWM hardware. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_init() */ hal_pwm_status_t hal_pwm_deinit(void); #else /** * @brief This function initializes the PWM hardware source clock. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[in] source_clock is the PWM source clock. For more details about the parameter, please refer to #hal_pwm_source_clock_t. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @note There are some limitations about the minimum frequency that we can set if we choose the related * source clock list in hal_pwm_source_clock_t, and the caculation formula is as follows:\n * \b The \b minimum \b frequency \b = \b \b ( \b the \b chosen \b source \b clock\b ) \b / \b ( \b 0X1FFF \b * \b advanced_config \b ) \n * For example:\n * if we choose the clock of HAL_PWM_CLOCK_32KHZ, the minimum frequency that we can set is 0.5 Hz;\n * if we choose the clock of HAL_PWM_CLOCK_13MHZ, the minimum frequency that we can set is 199 Hz;\n * @warning For this chip, we can config the PWM channel and the related clock, which means different PWM channels can use the different clock. * @sa hal_pwm_deinit() */ hal_pwm_status_t hal_pwm_init(hal_pwm_channel_t pwm_channel, hal_pwm_source_clock_t source_clock); /** * @brief This function deinitializes the PWM hardware. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_init() */ hal_pwm_status_t hal_pwm_deinit(hal_pwm_channel_t pwm_channel); #endif /** * @brief This function sets the PWM frequency and retrieves total count of the PWM hardware at the specified frequency. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[in] frequency is the PWM output frequency. * @param[out] total_count is PWM hardware total count, the value of this parameter varies based on the given PWM frequency. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. */ hal_pwm_status_t hal_pwm_set_frequency(hal_pwm_channel_t pwm_channel, uint32_t frequency, uint32_t *total_count); /** * @brief This function sets the PWM duty cycle. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[in] duty_cycle is the PWM hardware duty cycle, which is calculated as a product of application's duty ratio and hardware 's total count. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_get_duty_cycle() */ hal_pwm_status_t hal_pwm_set_duty_cycle(hal_pwm_channel_t pwm_channel, uint32_t duty_cycle); /** * @brief This function starts the PWM execution. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_stop() */ hal_pwm_status_t hal_pwm_start(hal_pwm_channel_t pwm_channel); /** * @brief This function stops the PWM execution. * @param[in] pwm_channel is PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_start() */ hal_pwm_status_t hal_pwm_stop(hal_pwm_channel_t pwm_channel); /** * @brief This function gets current frequency of the PWM, the unit of frequency is Hz. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[out] frequency is PWM output frequency. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_set_frequency() */ hal_pwm_status_t hal_pwm_get_frequency(hal_pwm_channel_t pwm_channel, uint32_t *frequency); /** * @brief This function gets the current duty cycle of the PWM. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[out] *duty_cycle is PWM hardware duty cycle, which is calculated as a product of application's duty ratio and hardware 's total count. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. * @sa hal_pwm_set_duty_cycle() */ hal_pwm_status_t hal_pwm_get_duty_cycle(hal_pwm_channel_t pwm_channel, uint32_t *duty_cycle); /** * @brief This function gets the current status of PWM. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[out] running_status is PWM busy or idle status, For details about this parameter, please refer to #hal_pwm_running_status_t . * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. */ hal_pwm_status_t hal_pwm_get_running_status(hal_pwm_channel_t pwm_channel, hal_pwm_running_status_t *running_status); #ifdef HAL_PWM_FEATURE_ADVANCED_CONFIG /** * @brief This function sets the PWM advanced configuration. * @param[in] pwm_channel is the PWM channel number. For more details about the parameter, please refer to #hal_pwm_channel_t. * @param[in] advanced_config is PWM source clock division value, For more details about this parameter, please refer to #hal_pwm_advanced_config_t. * @return To indicate whether this function call is successful or not. * If the return value is #HAL_PWM_STATUS_OK, the operation completed successfully. * If the return value is #HAL_PWM_STATUS_INVALID_PARAMETER, a wrong parameter is given. The parameter needs to be verified. * @par Example * For a sample code, please refer to @ref HAL_PWM_Driver_Usage_Chapter. */ hal_pwm_status_t hal_pwm_set_advanced_config(hal_pwm_channel_t pwm_channel, hal_pwm_advanced_config_t advanced_config); #else #endif #ifdef __cplusplus } #endif /** * @} * @} */ #endif /*HAL_PWM_MODULE_ENABLED*/ #endif /* __HAL_PWM_H__ */
kermox/schronisko-krakow
shelter/migrations/0006_auto_20200718_1407.py
# Generated by Django 3.0.5 on 2020-07-18 14:07 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shelter', '0005_animal_date_of_registration'), ] operations = [ migrations.AlterField( model_name='animal', name='age', field=models.PositiveIntegerField(help_text='Wprowadź przybliżony wiek', validators=[django.core.validators.MinValueValidator(0, 'Wiek nie może być <= 0'), django.core.validators.MaxValueValidator(40, 'Wiek nie może być większy od 30')], verbose_name='przybliżony wiek'), ), ]
lnceballosz/inventaire
server/models/validations/common.js
// SPDX-FileCopyrightText: 2014 <NAME>, <NAME> // SPDX-License-Identifier: AGPL-3.0-only const _ = require('builders/utils') const error_ = require('lib/error/error') const validations = module.exports = { couchUuid: _.isCouchUuid, 'doc _id': _.isCouchUuid, userId: _.isUserId, itemId: _.isItemId, transactionId: _.isTransactionId, groupId: _.isGroupId, username: _.isUsername, email: _.isEmail, entityUri: _.isEntityUri, lang: _.isLang, localImg: _.isLocalImg, userImg: image => { // Allow a user to delete their picture by passing a null value if (image === null) return true else return _.isUserImg(image) }, boolean: _.isBoolean, attribute: _.isString, shelves: shelves => _.isArray(shelves) && _.every(shelves, _.isCouchUuid), position: latLng => { // Allow a user or a group to delete their position by passing a null value if (latLng === null) return true else return _.isArray(latLng) && (latLng.length === 2) && _.every(latLng, _.isNumber) }, patchId: _.isPatchId } validations.boundedString = (str, minLength, maxLength) => { return _.isString(str) && (minLength <= str.length && str.length <= maxLength) } validations.BoundedString = (minLength, maxLength) => str => { return validations.boundedString(str, minLength, maxLength) } validations.imgUrl = url => validations.localImg(url) || _.isUrl(url) || _.isImageHash(url) validations.valid = function (attribute, value, option) { let test = this[attribute] // if no test are set at this attribute for this context // default to common validations if (test == null) test = validations[attribute] if (test == null) throw error_.new('missing validation function', 500, { attribute, context: this }) return test(value, option) } validations.pass = function (attribute, value, option) { if (!validations.valid.call(this, attribute, value, option)) { if (_.isObject(value)) value = JSON.stringify(value) throw error_.newInvalid(attribute, value) } }
solstag/red
doc/html/mod_2group_8php.js
<gh_stars>0 var mod_2group_8php = [ [ "group_content", "mod_2group_8php.html#a07a64f6c65b0080d8190b3d9728a7a83", null ], [ "group_post", "mod_2group_8php.html#aed1f009b1221348021bb34761160ef35", null ] ];