repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
kefirzhang/algorithms
leetcode/python/easy/p687_longestUnivaluePath.py
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.max_length = 0 def longestUnivaluePath(self, root: TreeNode) -> int: def maxSameNode(node, value): if not node: return 0 if node.val != value: return 0 return maxSameNode(node.left, value) + 1 + maxSameNode(node.right, value) def dfs(node): if not node: return self.max_length = max(maxSameNode(node, node.val), self.max_length) dfs(node.left) dfs(node.right) dfs(root) return self.max_length - 1 if self.max_length > 0 else 0 tree = TreeNode(1) tree.right = TreeNode(1) tree.right.right = TreeNode(1) tree.right.left = TreeNode(1) slu = Solution() print(slu.longestUnivaluePath(tree))
manu88/RenderKit
RenderKit/Modest/include/myfont/vhea.h
<filename>RenderKit/Modest/include/myfont/vhea.h<gh_stars>1-10 /* Copyright (C) 2016-2017 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Author: <EMAIL> (<NAME>) */ #ifndef MyFONT_VHEA_H #define MyFONT_VHEA_H #pragma once #include <myfont/myosi.h> #ifdef __cplusplus extern "C" { #endif // table vhea struct myfont_table_vhea { uint32_t version; int16_t Ascender; int16_t Descender; int16_t LineGap; int16_t advanceHeightMax; int16_t minTopSideBearing; int16_t minBottomSideBearing; int16_t yMaxExtent; int16_t caretSlopeRise; int16_t caretSlopeRun; int16_t caretOffset; int16_t reserved1; int16_t reserved2; int16_t reserved3; int16_t reserved4; int16_t metricDataFormat; uint16_t numOfLongVerMetrics; } typedef myfont_table_vhea_t; #include <myfont/myfont.h> struct myfont_font; mystatus_t myfont_load_table_vhea(myfont_font_t* mf, uint8_t* data, size_t data_size); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* MyFONT_VHEA_H */
Sgitario/jcloud-unit
jester-core/src/main/java/io/jester/api/RunOnKubernetes.java
<filename>jester-core/src/main/java/io/jester/api/RunOnKubernetes.java package io.jester.api; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface RunOnKubernetes { /** * Print pods, events and status when there are test failures. Fallback property * `ts.kubernetes.print.info.on.error`. */ boolean printInfoOnError() default true; /** * Delete namespace after running all the tests. Fallback property `ts.kubernetes.delete.namespace.after.all`. */ boolean deleteNamespaceAfterAll() default true; /** * Run the tests on Kubernetes in an ephemeral namespace that will be deleted afterwards. Fallback property * `ts.kubernetes.ephemeral.namespaces.enabled`. */ boolean ephemeralNamespaceEnabled() default true; /** * Load the additional resources before running all the tests. Fallback property * `ts.kubernetes.additional-resources`. */ String[] additionalResources() default {}; }
MatiasComercio/ati
src/main/java/ar/edu/itba/ati/idp/function/noise/ExponentialNoise.java
package ar.edu.itba.ati.idp.function.noise; import java.util.function.DoubleUnaryOperator; import org.apache.commons.math3.distribution.ExponentialDistribution; public class ExponentialNoise implements DoubleUnaryOperator { private final ExponentialDistribution exponentialDist; public ExponentialNoise(final double mean) { this.exponentialDist = new ExponentialDistribution(mean); } @Override public double applyAsDouble(final double pixel) { return pixel * exponentialDist.sample(); } }
elementechemlyn/node-careconnect-server-core
src/Extensions/tests/ExtensionCareConnectValueApproximation1.test.js
// This code was autogenerated from BuildExtensions.py const ExtensionCareConnectValueApproximation1 = require('../../../src/Extensions/ExtensionCareConnectValueApproximation1.js') describe('Care Connect Extension ExtensionCareConnectValueApproximation1', function () { describe('Object constructor', function () { it('Can create object', function () { let ext = new ExtensionCareConnectValueApproximation1() expect(ext).toBeInstanceOf(ExtensionCareConnectValueApproximation1) expect(ext.url).toBe('https://fhir.hl7.org.uk/STU3/StructureDefinition/Extension-CareConnect-ValueApproximation-1') }) }) describe('Object getters and setters', function () { it('Get/Set Boolean', function () { let ext = new ExtensionCareConnectValueApproximation1() ext.boolean = true let bl = ext.boolean expect(bl).toBe(true) }) }) })
liubang/laboratory
cpp/leetcode/494.target-sum.cc
<filename>cpp/leetcode/494.target-sum.cc #include <gtest/gtest.h> #include <vector> namespace { class Solution { public: int findTargetSumWays(const std::vector<int>& nums, int target) { int sum = 0; std::for_each(nums.begin(), nums.end(), [&sum](int num) { sum += num; }); if (sum < target || ((sum + target) & 1) == 1) { return 0; } int w = (sum + target) / 2; std::vector<int> dp(w + 1); dp[0] = 1; for (int num : nums) { for (int j = w; j >= num; --j) { dp[j] += dp[j - num]; } } return dp[w]; } }; } // namespace TEST(Leetcode, target_sum) { Solution s; EXPECT_EQ(5, s.findTargetSumWays({1, 1, 1, 1, 1}, 3)); EXPECT_EQ(1, s.findTargetSumWays({1}, 1)); }
purm/IvmpDotNet
IvmpDotNet.Proxy/SDK/ModuleNatives/CheckpointNatives.h
//============== IV: Multiplayer - http://code.iv-multiplayer.com ============== // // File: CheckpointNatives.h // Project: Server.Core // Author(s): MaVe // License: See LICENSE in root directory // //============================================================================== #pragma once #include "ModuleNatives.h" namespace Modules { class CCheckpointModuleNatives : public ICCheckpointModuleNatives { public: EntityId Create(int iType, CVector3 vecPosition, CVector3 vecTargetPosition, float fRadius); bool Delete(EntityId checkpointId); bool ShowForPlayer(EntityId checkpointId, EntityId playerId); bool HideForPlayer(EntityId checkpointId, EntityId playerId); bool ShowForAll(EntityId checkpointId); bool HideForAll(EntityId checkpointId); bool SetType(EntityId checkpointId, int iType); int GetType(EntityId checkpointId); bool SetPosition(EntityId checkpointId, CVector3 vecPosition); CVector3 GetPosition(EntityId checkpointId); bool SetTargetPosition(EntityId checkpointId, CVector3 vecTargetPosition); CVector3 GetTargetPosition(EntityId checkpointId); bool SetRadius(EntityId checkpointId, float fRadius); float GetRadius(EntityId checkpointId); bool SetDimension(EntityId checkpointId, unsigned char dimensionId); int GetDimension(EntityId checkpointId); }; }
juleshwa/hacktiv8
phase0/week3/exercise-9.js
// Exercise 9 - Looking for Mean // <NAME> - Hacktiv8 Batch 34 - Humble Fox // Create function to calculate mean of an array number function cariMean (arr) { let sum = 0 let mean = 0 let arrayLength = arr.length for (let i = 0; i < arrayLength; i++) { sum += arr[i] } mean = Math.round(sum / arrayLength) return mean } // TEST CASES console.log(cariMean([1, 2, 3, 4, 5])) // 3 console.log(cariMean([3, 5, 7, 5, 3])) // 5 console.log(cariMean([6, 5, 4, 7, 3])) // 5 console.log(cariMean([1, 3, 3])) // 2 console.log(cariMean([7, 7, 7, 7, 7])) // 7
yuchengs/viennacl-dev
viennacl/device_specific/lazy_program_compiler.hpp
#ifndef VIENNACL_DEVICE_SPECIFIC_LAZY_PROGRAM_COMPILER_HPP #define VIENNACL_DEVICE_SPECIFIC_LAZY_PROGRAM_COMPILER_HPP /* ========================================================================= Copyright (c) 2010-2016, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. Portions of this software are copyright by UChicago Argonne, LLC. ----------------- ViennaCL - The Vienna Computing Library ----------------- Project Head: <NAME> <EMAIL> (A list of authors and contributors can be found in the manual) License: MIT (X11), see file LICENSE in the base directory ============================================================================= */ /** @file viennacl/device_specific/lazy_program_compiler.hpp @brief Helper for compiling a program lazily */ #include <map> #include "viennacl/ocl/context.hpp" namespace viennacl { namespace device_specific { class lazy_program_compiler { public: lazy_program_compiler(viennacl::ocl::context * ctx, std::string const & name, std::string const & src, bool force_recompilation) : ctx_(ctx), name_(name), src_(src), force_recompilation_(force_recompilation){ } lazy_program_compiler(viennacl::ocl::context * ctx, std::string const & name, bool force_recompilation) : ctx_(ctx), name_(name), force_recompilation_(force_recompilation){ } void add(std::string const & src) { src_+=src; } std::string const & src() const { return src_; } viennacl::ocl::program & program() { if (force_recompilation_ && ctx_->has_program(name_)) ctx_->delete_program(name_); if (!ctx_->has_program(name_)) { #ifdef VIENNACL_BUILD_INFO std::cerr << "Creating program " << program_name << std::endl; #endif ctx_->add_program(src_, name_); #ifdef VIENNACL_BUILD_INFO std::cerr << "Done creating program " << program_name << std::endl; #endif } return ctx_->get_program(name_); } private: viennacl::ocl::context * ctx_; std::string name_; std::string src_; bool force_recompilation_; }; } } #endif
tobireinhard/cbmc
src/util/xml.cpp
<gh_stars>100-1000 /*******************************************************************\ Module: Author: <NAME>, <EMAIL> \*******************************************************************/ #include "xml.h" #include <ostream> #include "exception_utils.h" #include "string2int.h" #include "structured_data.h" void xmlt::clear() { data.clear(); name.clear(); attributes.clear(); elements.clear(); } void xmlt::swap(xmlt &xml) { xml.data.swap(data); xml.attributes.swap(attributes); xml.elements.swap(elements); xml.name.swap(name); } void xmlt::output(std::ostream &out, unsigned indent) const { // 'name' needs to be set, or we produce mal-formed // XML. PRECONDITION(!name.empty()); do_indent(out, indent); out << '<' << name; for(const auto &attribute : attributes) { // it.first needs to be non-empty if(attribute.first.empty()) continue; out << ' ' << attribute.first << '=' << '"'; escape_attribute(attribute.second, out); out << '"'; } if(elements.empty() && data.empty()) { out << "/>" << "\n"; return; } out << '>'; if(elements.empty()) escape(data, out); else { out << "\n"; for(const auto &element : elements) element.output(out, indent+2); do_indent(out, indent); } out << '<' << '/' << name << '>' << "\n"; } /// escaping for XML elements void xmlt::escape(const std::string &s, std::ostream &out) { for(const auto ch : s) { switch(ch) { case '&': out << "&amp;"; break; case '<': out << "&lt;"; break; case '>': out << "&gt;"; break; case '\r': break; // drop! case '\n': out << '\n'; break; case 0x9: // TAB case 0x7F: // DEL out << "&#" << std::to_string((unsigned char)ch) << ';'; break; default: DATA_INVARIANT( ch >= ' ', "XML does not support escaping non-printable character " + std::to_string((unsigned char)ch)); out << ch; } } } /// escaping for XML attributes, assuming that double quotes " are used /// consistently, not single quotes void xmlt::escape_attribute(const std::string &s, std::ostream &out) { for(const auto ch : s) { switch(ch) { case '&': out << "&amp;"; break; case '<': out << "&lt;"; break; case '>': out << "&gt;"; break; case '"': out << "&quot;"; break; case 0x9: // TAB case 0xA: // LF case 0xD: // CR case 0x7F: // DEL out << "&#" << std::to_string((unsigned char)ch) << ';'; break; default: DATA_INVARIANT( ch >= ' ', "XML does not support escaping non-printable character " + std::to_string((unsigned char)ch)); out << ch; } } } bool xmlt::is_printable_xml(const std::string &s) { for(const auto ch : s) { if(ch < 0x20 && ch != 0x9 && ch != 0xA && ch != 0xD) return false; } return true; } void xmlt::do_indent(std::ostream &out, unsigned indent) { out << std::string(indent, ' '); } xmlt::elementst::const_iterator xmlt::find(const std::string &key) const { for(elementst::const_iterator it=elements.begin(); it!=elements.end(); it++) if(it->name == key) return it; return elements.end(); } xmlt::elementst::iterator xmlt::find(const std::string &key) { for(elementst::iterator it=elements.begin(); it!=elements.end(); it++) if(it->name == key) return it; return elements.end(); } void xmlt::set_attribute( const std::string &attribute, unsigned value) { set_attribute(attribute, std::to_string(value)); } void xmlt::set_attribute( const std::string &attribute, unsigned long value) { set_attribute(attribute, std::to_string(value)); } void xmlt::set_attribute( const std::string &attribute, unsigned long long value) { set_attribute(attribute, std::to_string(value)); } void xmlt::set_attribute( const std::string &attribute, const std::string &value) { if((value[0]=='\"' && value[value.size()-1]=='\"') || (value[0]=='\'' && value[value.size()-1]=='\'')) { attributes[attribute]=value.substr(1, value.size()-2); } else { attributes[attribute]=value; } } /// takes a string and unescapes any xml style escaped symbols /// \par parameters: a string /// \return the unescaped string std::string xmlt::unescape(const std::string &str) { std::string result; result.reserve(str.size()); for(std::string::const_iterator it=str.begin(); it!=str.end(); it++) { if(*it=='&') { std::string tmp; it++; while(it!=str.end() && *it!=';') tmp+=*it++; if(tmp=="gt") result+='>'; else if(tmp=="lt") result+='<'; else if(tmp=="amp") result+='&'; else if(tmp[0]=='#' && tmp[1]!='x') { char c=unsafe_string2int(tmp.substr(1, tmp.size()-1)); result+=c; } else throw deserialization_exceptiont("unknown XML escape code: " + tmp); } else result+=*it; } return result; } bool operator==(const xmlt &a, const xmlt &b) { return a.name == b.name && a.data == b.data && a.elements == b.elements && a.attributes == b.attributes; } bool operator!=(const xmlt &a, const xmlt &b) { return !(a == b); } xmlt xml_node(const std::pair<labelt, structured_data_entryt> &entry) { const labelt &label = entry.first; const structured_data_entryt &data = entry.second; xmlt output_data{label.kebab_case()}; if(data.is_leaf()) { output_data.data = data.leaf_data(); } else { const auto &children = data.children(); output_data.elements = make_range(children).map(xml_node).collect<std::list<xmlt>>(); } return output_data; } xmlt to_xml(const structured_datat &data) { if(data.data().size() == 0) return xmlt{}; if(data.data().size() == 1) { return xml_node(*data.data().begin()); } else { xmlt root{"root"}; root.elements = make_range(data.data()).map(xml_node).collect<std::list<xmlt>>(); return root; } }
DeraTechDesign/diode_client
util/helper_test.go
// Diode Network Client // Copyright 2021 Diode // Licensed under the Diode License, Version 1.1 package util import ( "bytes" "math" "testing" ) type PaddingBytesTest struct { Src []byte Pad uint8 Length int Res []byte } type IntBytesTest struct { Src int Bytes []byte } type IntBigTest struct { Src int AddedOne int Bytes []byte } type EmptyBytesTest struct { Length int Bytes []byte } type StringsContainTest struct { Pivot string Res bool } var ( paddingBytesSuffixTests = []PaddingBytesTest{ { Src: []byte{1}, Pad: 0, Length: 5, Res: []byte{1, 0, 0, 0, 0}, }, { Src: []byte{1}, Pad: 1, Length: 6, Res: []byte{1, 1, 1, 1, 1, 1}, }, { Src: []byte{1}, Pad: 1, Length: 0, Res: []byte{1}, }, { Src: []byte{1, 2, 3, 4}, Pad: 0, Length: 10, Res: []byte{1, 2, 3, 4, 0, 0, 0, 0, 0, 0}, }, } paddingBytesPrefixTests = []PaddingBytesTest{ { Src: []byte{1}, Pad: 0, Length: 5, Res: []byte{0, 0, 0, 0, 1}, }, { Src: []byte{1}, Pad: 1, Length: 6, Res: []byte{1, 1, 1, 1, 1, 1}, }, { Src: []byte{1}, Pad: 1, Length: 0, Res: []byte{1}, }, { Src: []byte{1, 2, 3, 4}, Pad: 0, Length: 8, Res: []byte{0, 0, 0, 0, 1, 2, 3, 4}, }, } intBytesTests = []IntBytesTest{ { Src: 1, Bytes: []byte{1}, }, { Src: 100, Bytes: []byte{100}, }, { Src: 256, Bytes: []byte{1, 0}, }, { Src: 512, Bytes: []byte{2, 0}, }, } intBigTests = []IntBigTest{ { Src: 1, AddedOne: 2, Bytes: []byte{1}, }, { Src: 100, AddedOne: 101, Bytes: []byte{100}, }, { Src: 256, AddedOne: 257, Bytes: []byte{1, 0}, }, { Src: 512, AddedOne: 513, Bytes: []byte{2, 0}, }, } emptyBytesTests = []EmptyBytesTest{ { Length: -1, Bytes: []byte{}, }, { Length: 0, Bytes: []byte{}, }, { Length: math.MaxInt64, Bytes: []byte{}, }, { Length: 10, Bytes: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }, { Length: 3, Bytes: []byte{0, 0, 0}, }, } stringsContainSrc = []string{"Lorem ipsum dolor sit amet", "consectetur adipiscing elit", "Cras pulvinar urna quam", "sit amet maximus nulla finibus id", "Vestibulum sit amet ante a lorem lobortis ullamcorper"} stringsContainTests = []StringsContainTest{ { Pivot: "hello", Res: false, }, { Pivot: "world", Res: false, }, { Pivot: "Lorem ipsum dolor sit amet", Res: true, }, { Pivot: "consectetur adipiscing elit", Res: true, }, } ) func TestPaddingBytesSuffix(t *testing.T) { for _, v := range paddingBytesSuffixTests { if !bytes.Equal(v.Res, PaddingBytesSuffix(v.Src, v.Pad, v.Length)) { t.Errorf("Cannot padding bytes suffix with givin pad") } } } func TestPaddingBytesPrefix(t *testing.T) { for _, v := range paddingBytesPrefixTests { if !bytes.Equal(v.Res, PaddingBytesPrefix(v.Src, v.Pad, v.Length)) { t.Errorf("Cannot padding bytes prefix with givin pad") } } } func TestIntToBytes(t *testing.T) { for _, v := range intBytesTests { if !bytes.Equal(v.Bytes, IntToBytes(v.Src)) { t.Errorf("Cannot convert int to bytes") } } } func TestBytesToInt(t *testing.T) { for _, v := range intBytesTests { if v.Src != BytesToInt(v.Bytes) { t.Errorf("Cannot convert bytes to int") } } } func TestInt64ToBytes(t *testing.T) { for _, v := range intBytesTests { if !bytes.Equal(v.Bytes, Int64ToBytes(int64(v.Src))) { t.Errorf("Cannot convert int64 to bytes") } } } func TestBytesToInt64(t *testing.T) { for _, v := range intBytesTests { if int64(v.Src) != BytesToInt64(v.Bytes) { t.Errorf("Cannot convert bytes to int64") } } } func TestBytesToBigInt(t *testing.T) { for _, v := range intBigTests { if int64(v.Src) != BytesToBigInt(v.Bytes).Int64() { t.Errorf("Cannot convert bytes to big.Int") } } } func TestBytesAddOne(t *testing.T) { for _, v := range intBigTests { if int64(v.AddedOne) != BytesToBigInt(BytesAddOne(v.Bytes)).Int64() { t.Errorf("Cannot call BytesAddOne") } } } func TestEmptyBytes(t *testing.T) { for _, v := range emptyBytesTests { if !bytes.Equal(v.Bytes, EmptyBytes(v.Length)) { t.Errorf("Cannot create empty bytes") } } } func TestStringsContain(t *testing.T) { for _, v := range stringsContainTests { if v.Res != StringsContain(stringsContainSrc, v.Pivot) { t.Errorf("Cannot find the string") } } }
zpsean/go4api
lib/pairwise/pairwise.go
/* * go4api - an api testing tool written in Go * Created by: <NAME> 2018 * * 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. * */ package pairwise import ( "fmt" "sort" "reflect" combins "go4api/lib/combination" ) // ------------------------------------------------------------------------- // Note: for pairewise, there are two kinds of algorithm: // --> algorithm 1. use the pairWises to build the test case data (test case) // --> algorithm 2. get the full combination first, the filter (remove) them based on the pairWises if repeated // ------------------------------------------------------------------------- // The algorithm 1: is rewitten the code for AllPairs (python) using Golang // refer to: https://github.com/thombashi/allpairspy // // key steps of this algorithm is: // 1. get the value value_matrix (combs), and maxUniquePairsExpected, workingItemMatrix, // 2. try the next item to be add, with computing and comparing existing pairs, some weights, like most new pairs, in, out, etc. // 3. sort the items in one vetor of the workingItemMatrix (workingItemMatrix(m)) // 4. add the highly recommended item of the sort items (step 3) // 5. add the item to existing pairs // 6. repeat Step 2 ~ Step 5 // ------------------------------------------------------------------------- // here is the entry for pairwise algorithm 1 func GetPairWise(c chan []interface{} ,combins [][]interface{}, PwLength int) { // init the PairsStorage var pairs PairsStorage pairs.PwLength = PwLength pwNodes := map[string]Node{} pairs.PwNodes = pwNodes for i := 0; i < PwLength; i++ { pairs.PwCombsArr = append(pairs.PwCombsArr, [][]interface{}{}) } // init the AllPairs var allPairs AllPairs allPairs.PwLength = PwLength allPairs.Pairs = pairs allPairs.MaxPairWiseCombinationNumber = GetMaxPairWiseCombinationNumber(combins, PwLength) allPairs.WorkingItemMatrix = GetWorkingItemMatrix(combins) // to get the data // for debug loop loopDepth := 0 for { returnedTestCaseData := allPairs.NextPairWiseTestCaseData() if len(returnedTestCaseData) == 0 { break } else { c <- returnedTestCaseData // fmt.Println(returnedTestCaseData) } if loopDepth == 30 { fmt.Println("loopDepth: ", loopDepth) break } } // fmt.Println("touch here ????? => yes") // allPairs.NextPairWiseTestCaseData() // allPairs.NextPairWiseTestCaseData() } // to define the item for each element type AllPairs struct { PwLength int Pairs PairsStorage MaxPairWiseCombinationNumber int WorkingItemMatrix [][]Item // [][]Item PairWiseTestCaseData [][]interface{} // [][]Item.Value } type Item struct { Id string Value interface{} Weights []int } // func (item Item) Append(weight int) { item.Weights = append(item.Weights, weight) } // Note: in Python, key_cache (KeyCache) is dict, with tuple(items) as key, tuple(ids) is value // { // (<allpairspy.allpairs.Item object at 0x1015dd2e8>,): ('a0v0',), // (<allpairspy.allpairs.Item object at 0x1015dd358>,): ('a0v1',), // (<allpairspy.allpairs.Item object at 0x1015dd3c8>,): ('a0v2',) // } type KeyCache struct { PairItems [][]interface{} // [][]Item ->for Item PairIds [][]interface{} // [][]string -> for id } var keyCache KeyCache // items -> []Item, return []string -> []Id func GetPairIdsBk(items []interface{}) []interface{} { // Note: in Python, items is tuple(item, item, ...) // (<allpairspy.allpairs.Item object at 0x1015dd3c8>,) for ind, cacheItems := range keyCache.PairItems { totalFound := 0 fmt.Println("keyCache, items: ", keyCache, "::", items) for i, _ := range cacheItems { // to compare Item, need special method, use the reflect.DeepEqual // if cacheItems[i] == items[i] { if reflect.DeepEqual(cacheItems[i], items[i]) { totalFound = totalFound + 1 if totalFound == len(items) { return keyCache.PairIds[ind] } } } } var keyIds []interface{} for _, item := range items { keyIds = append(keyIds, item.(Item).Id) } // set keyCache keyCache.PairItems = append(keyCache.PairItems, items) keyCache.PairIds = append(keyCache.PairIds, keyIds) // Note: in Python, key_value (keyIds) is tuple(id, id, ...) // ('a0v2',) return keyIds } func GetPairIds(items []interface{}) []interface{} { // Note: in Python, items is tuple(item, item, ...) // (<allpairspy.allpairs.Item object at 0x1015dd3c8>,) var keyIds []interface{} for _, item := range items { keyIds = append(keyIds, item.(Item).Id) } // Note: in Python, key_value (keyIds) is tuple(id, id, ...) // ('a0v2',) // in golang, keyIds = ['id', ...] return keyIds } /// // for the element already added / arranged type Node struct { Id string Counter int InIds []string // ensure no duplicate OutIds []string // ensure no duplicate } // for the elements already added / arranged type PairsStorage struct { PwLength int PwNodes map[string]Node // Note: in Python, this is dict -> {'id': Node, ...} PwCombsArr [][][]interface{} // ensure no duplicate //[ [[1-comb id], [1-combid], [...]], [[2-comb ids], [2-combids], [...]], ...] // Note: in Python PWCombsArr is array for set(id), like, [set(id), set(id), ...]: // [ {('a0v0',), ..., ('a3v1',), ('a1v0',)}, // {('a1v1', 'a2v3'), ..., ('a0v1', 'a2v0')} ] } func (pairs PairsStorage) GetNodeInfo (item interface{}) Node { var node Node node.Id = item.(Item).Id node.Counter = 0 for _, node_i := range pairs.PwNodes { if node_i.Id == item.(Item).Id { node = node_i break } } return node } func (pairs PairsStorage) GetCombs() [][][]interface{} { return pairs.PwCombsArr } func (pairs PairsStorage) Length() int { if len(pairs.PwCombsArr) > 0 { return len(pairs.PwCombsArr[len(pairs.PwCombsArr) - 1]) } else { return 0 } } // sequence -> [PwLength]item, which has been choseen for the next test data (case) func (pairs PairsStorage) AddSequence(sequence []interface{}) { for i := 0; i < pairs.PwLength; i++ { for combination := range combins.CombinationsInterface(sequence, i + 1) { pairs.AddCombination(combination) } } } // combination -> [1]item, ..., [PwLength]item func (pairs PairsStorage) AddCombination(combination []interface{}) { // fmt.Println("combination: ", combination) n := len(combination) if n > 0 { ids := GetPairIds(combination) // Note: not duplicate: check if pairs.PwCombsArr[n - 1] has ids first, if not, then add if len(pairs.PwCombsArr[n - 1]) > 0 { var ifExists bool ifExists = false for _, set := range pairs.PwCombsArr[n - 1] { if compareSlice(set, ids) { ifExists = true break } } if ifExists == false { pairs.PwCombsArr[n - 1] = append(pairs.PwCombsArr[n - 1], ids) } } else { pairs.PwCombsArr[n - 1] = append(pairs.PwCombsArr[n - 1], ids) } // if n == 1 and combination[0].id not in self.__nodes: if n == 1 { var ifExists bool ifExists = false // to check if combination[0].(Item).Id already exists in keys of PwNodes (map[id]Node) for key, _ := range pairs.PwNodes { if combination[0].(Item).Id == key { ifExists = true break } } if ifExists == false { var node Node node.Id = combination[0].(Item).Id node.Counter = 0 // fmt.Println("AddCombination: ", combination, combination[0].(Item).Id) pairs.PwNodes[combination[0].(Item).Id] = node return } } for i, id := range ids { // fmt.Println("ids: ", ids) var node Node node.Id = id.(string) curr := pairs.PwNodes[id.(string)] // curr is Node type // fmt.Println("curr -- 0: ", ids, curr) node.Counter = curr.Counter + 1 tempInIds := curr.InIds for _, id_i := range ids[:i] { // ensure tempInIds has no duplicate elements var ifExists bool ifExists = false for _, id_ii := range tempInIds { if id_ii == id_i.(string) { ifExists = true break } } if ifExists == false { tempInIds = append(tempInIds, id_i.(string)) } } node.InIds = tempInIds tempOutIds := curr.OutIds for _, id_i := range ids[i + 1:] { // ensure tempOutIds has no duplicate elements var ifExists bool ifExists = false for _, id_ii := range tempInIds { if id_ii == id_i.(string) { ifExists = true break } } if ifExists == false { tempOutIds = append(tempOutIds, id_i.(string)) } } node.OutIds = tempOutIds // fmt.Println("curr -- 1: ", ids, curr, node) pairs.PwNodes[id.(string)] = node } } } // to get the total number of pairwise combinations func GetMaxPairWiseCombinationNumber(combs [][]interface{}, PwLength int) int { // init ----------------- var indexSlice []int for i := 0; i < len(combs); i++ { indexSlice = append(indexSlice, i) } // to get the combinations like [1 1][1 2][1 3] ... var pwLen int if PwLength > len(combs) { pwLen = len(combs) } else { pwLen = PwLength } indexCombs := combins.CombinationsInt(indexSlice, pwLen) // totalNumber := 0 // for indexPair := range indexCombs { var combins_pw_index_slice [][]interface{} for _, ind_value := range indexPair { var indexSlice []interface{} for i, _ := range combs[ind_value] { indexSlice = append(indexSlice, i) } combins_pw_index_slice = append(combins_pw_index_slice, indexSlice) } // c := make(chan []interface{}) go func(c chan []interface{}) { defer close(c) combins.CombinsSliceInterface(c, []interface{}{}, combins_pw_index_slice) }(c) // can not use len(c) to get the channel length, as len(c) is always 0 here, why? cLenght := 0 for range c{ cLenght = cLenght + 1 } // fmt.Println("c: ", cLenght, len(c)) totalNumber = totalNumber + cLenght } // fmt.Println("MaxPairWiseCombinationNumber: ", totalNumber) return totalNumber } // to get the item matrix with type Item func GetWorkingItemMatrix(combs [][]interface{}) [][]Item { var workingItemMatrix [][]Item for i, combsSlice := range combs { var itemSlice []Item for j, value := range combsSlice { var strId string strId = "a" + fmt.Sprint(i) + "v" + fmt.Sprint(j) var item Item item.Id = strId item.Value = value // init the item.Weights, otherwise, will receive 'can not assign ...' error to change the weight later // var weights []int // item.Weights = weights itemSlice = append(itemSlice, item) } workingItemMatrix = append(workingItemMatrix, itemSlice) } // fmt.Println("workingItemMatrix: ", workingItemMatrix) return workingItemMatrix } // ------------------------------------------------------------------------- func (allPairs AllPairs) NextPairWiseTestCaseData() []interface{} { maxUniquePairsExpected := allPairs.MaxPairWiseCombinationNumber if allPairs.Pairs.Length() > maxUniquePairsExpected { fmt.Println("!! Error, added pairs more than maxUniquePairsExpected: ", allPairs.Pairs.Length(), maxUniquePairsExpected) return []interface {}{} } if allPairs.Pairs.Length() == maxUniquePairsExpected { fmt.Println("all pairs have been added: ", maxUniquePairsExpected) return []interface {}{} } workingItemMatrix := allPairs.WorkingItemMatrix previousUniquePairsCount := allPairs.Pairs.Length() chosenValuesArr := make([]interface{}, len(workingItemMatrix)) indexes := make([]int, len(workingItemMatrix)) direction := 1 i := 0 for { // to break the for if ... if i <= -1 || i >= len(workingItemMatrix) { break } // if direction == 1 { // move forward allPairs.resortWorkingArray(chosenValuesArr[:i], i) indexes[i] = 0 } else if direction == 0 || direction == -1 { // scan current array or go back indexes[i] += 1 if indexes[i] >= len(workingItemMatrix[i]) { direction = -1 if i == 0 { fmt.Println("stop and return") return []interface {}{} } i += direction continue } direction = 0 } else { fmt.Println("next(): unknown 'direction' code '{}'", direction) } chosenValuesArr[i] = workingItemMatrix[i][indexes[i]] if true { if direction <= -1 { return []interface {}{} } direction = 1 } else { direction = 0 } i += direction // // fmt.Println("indexes: ", i, indexes, chosenValuesArr) } if len(workingItemMatrix) != len(chosenValuesArr) { fmt.Println("stop and return") return []interface {}{} } allPairs.Pairs.AddSequence(chosenValuesArr) // fmt.Println("allPairs.Pairs.Length() vs. maxUniquePairsExpected: ", allPairs.Pairs.Length(), maxUniquePairsExpected) if allPairs.Pairs.Length() == previousUniquePairsCount { // could not find new unique pairs - stop fmt.Println("could not find new unique pairs - stop: ", previousUniquePairsCount) return []interface {}{} } // replace returned array elements with real values and return it var chosenValues []interface{} for _, item := range chosenValuesArr { chosenValues = append(chosenValues, item.(Item).Value) } // fmt.Println("-----> chosenValues: ", chosenValuesArr, chosenValues) return chosenValues } func (allPairs AllPairs) resortWorkingArray (chosenValuesArr []interface{}, num int) { for ii, item := range allPairs.WorkingItemMatrix[num] { dataNode := allPairs.Pairs.GetNodeInfo(item) // numbers of new combinations to be created if this item is // appended to array var newCombs [][][]interface{} // newCombs -> [][][]interface{} //[ [[1-comb id], [1-combid], [...]], [[2-comb ids], [2-combids], [...]], ...] for i := 0; i < allPairs.PwLength; i++ { var tempChosen []interface{} // copy(tempChosen, chosenValuesArr) => not sure why copy does not work here tempChosen = append(tempChosen, chosenValuesArr[0:]...) tempChosen = append(tempChosen, item) // fmt.Println("---> tempChosen : ", chosenValuesArr, item, tempChosen) var setPairIds [][]interface{} for z := range combins.CombinationsInterface(tempChosen, i + 1) { var idss []interface{} for _, item := range z { idss = append(idss, item.(Item).Id) } if allPairs.Pairs.Length() > 0 { var ifHas bool ifHas = false for _, comb := range allPairs.Pairs.GetCombs()[i] { if compareSlice(idss, comb) { ifHas = true break } } if ifHas == false { setPairIds = append(setPairIds, idss) } } else { setPairIds = append(setPairIds, idss) } } newCombs = append(newCombs, setPairIds) } // reset the item.Weights weights := []int{} item.Weights = weights // (1). weighting the node // node that creates most of new pairs is the best item.Weights = append(item.Weights, -len(newCombs[len(newCombs) - 1])) // (2). less used outbound connections most likely to produce more new // pairs while search continues item.Weights = append(item.Weights, len(dataNode.OutIds)) // (3). reverse the newCombs except the last [] as it is used in (1) var reversedNewCombs [][][]interface{} for i := len(newCombs) - 2; i >= 0; i-- { reversedNewCombs = append(reversedNewCombs, newCombs[i]) } for _, x := range reversedNewCombs { item.Weights = append(item.Weights, len(x)) } // (4). less used node is better item.Weights = append(item.Weights, -dataNode.Counter) // (5). otherwise we will prefer node with most of free inbound // connections; somehow it works out better ;) item.Weights = append(item.Weights, -len(dataNode.InIds)) // re-assign the item.Weights to the allPairs allPairs.WorkingItemMatrix[num][ii].Weights = item.Weights } // workingItemMatrix[num].sort(key=cmp_to_key(cmp_item)) // Sort: Ascending order // sort.Sort(allPairs.WorkingItemMatrix[num]) var items Items items = allPairs.WorkingItemMatrix[num] // fmt.Println("items--before sort: ", items) sort.Stable(items) // fmt.Println("items--after sort: ", items, "\n") // fmt.Println("items--after sort : allPairs - PwNodes", allPairs.Pairs.PwNodes) // fmt.Println("items--after sort : allPairs - PwCombsArr", allPairs.Pairs.PwCombsArr, "\n\n") } func compareSlice(sliceA []interface{}, sliceB []interface{}) bool { var ifMatched bool ifMatched = true for i, valueA := range sliceA { // if valueA != sliceB[i] { if !reflect.DeepEqual(valueA, sliceB[i]) { ifMatched = false break } } return ifMatched } // Implements the Interface in sort package, used for Item sort // type Interface interface { // Len() int // Less(i, j int) bool // Swap(i, j int) // } type Items []Item func (items Items) Len() int { return len(items) } func (items Items) Less(i, j int) bool { // lenI := len(items[i].Weights) // lenJ := len(items[j].Weights) var ifLess bool // if lenI < lenJ { // for ii, itemI := range items[i].Weights { // if itemI > items[j].Weights[ii] { // ifLess = false // break // } // } // } else if lenI >= lenJ { // for jj, itemJ := range items[j].Weights { // if items[i].Weights[jj] > itemJ { // ifLess = false // break // } // } // } for ii, itemI := range items[i].Weights { if itemI < items[j].Weights[ii] { ifLess = true break } else if itemI > items[j].Weights[ii] { ifLess = false break } } return ifLess } func (items Items) Swap(i, j int) { items[i], items[j] = items[j], items[i] }
aizatazhar/tp
src/main/java/seedu/zookeep/storage/JsonAdaptedMedicalCondition.java
<reponame>aizatazhar/tp package seedu.zookeep.storage; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import seedu.zookeep.commons.exceptions.IllegalValueException; import seedu.zookeep.model.medicalcondition.MedicalCondition; /** * Jackson-friendly version of {@link MedicalCondition}. */ class JsonAdaptedMedicalCondition { private final String medicalConditionName; /** * Constructs a {@code JsonAdaptedMedicalCondition} with the given {@code medicalConditionName}. */ @JsonCreator public JsonAdaptedMedicalCondition(String medicalConditionName) { this.medicalConditionName = medicalConditionName; } /** * Converts a given {@code MedicalCondition} into this class for Jackson use. */ public JsonAdaptedMedicalCondition(MedicalCondition source) { medicalConditionName = source.medicalConditionName; } @JsonValue public String getMedicalConditionName() { return medicalConditionName; } /** * Converts this Jackson-friendly adapted medicalCondition object into the model's {@code MedicalCondition} object. * * @throws IllegalValueException if there were any data constraints violated in the adapted medicalCondition. */ public MedicalCondition toModelType() throws IllegalValueException { if (!MedicalCondition.isValidMedicalConditionName(medicalConditionName)) { throw new IllegalValueException(MedicalCondition.MESSAGE_CONSTRAINTS); } return new MedicalCondition(medicalConditionName); } }
lkkuma/AutoPlug-Client
src/main/java/com/osiris/autoplug/client/utils/tasks/MyDate.java
<reponame>lkkuma/AutoPlug-Client /* * Copyright (c) 2022 Osiris-Team. * All rights reserved. * * This software is copyrighted work, licensed under the terms * of the MIT-License. Consult the "LICENSE" file for details. */ package com.osiris.autoplug.client.utils.tasks; import com.osiris.betterthread.BThread; import com.osiris.betterthread.BThreadManager; import com.osiris.betterthread.BThreadPrinter; import com.osiris.betterthread.modules.Date; import org.fusesource.jansi.Ansi; import java.time.LocalDateTime; import static org.fusesource.jansi.Ansi.ansi; public class MyDate extends Date { @Override public void append(BThreadManager manager, BThreadPrinter printer, BThread thread, StringBuilder line) { line.append(ansi().bg(Ansi.Color.WHITE).fgBlack().a("[" + dateFormatter.format(LocalDateTime.now()) + "]") .reset()); } }
sirmarcel/cmlk
tests/test_engine_configparse.py
from unittest import TestCase from cmlkit.engine import is_config, parse_config class TestConfigparseBasics(TestCase): def test_is_config_valid(self): valid = {"a": {"b": 3}} self.assertTrue(is_config(valid)) def test_is_config_invalid(self): invalid = {3: {"b": 3}} self.assertFalse(is_config(invalid)) invalid = {3: {"b": 3}, "b": 3} self.assertFalse(is_config(invalid)) invalid = [3, {"b": 3}] self.assertFalse(is_config(invalid)) invalid = {"b": 3} self.assertFalse(is_config(invalid)) def test_parse_valid_config(self): valid = {"a": {"b": 3}} kind, config = parse_config(valid) self.assertEqual(kind, "a") self.assertEqual(config, {"b": 3}) def test_parse_valid_config_with_shortcut_ok(self): valid = "test" kind, config = parse_config(valid, shortcut_ok=True) self.assertEqual(kind, "test") self.assertEqual(config, {}) def test_parse_invalid_config(self): with self.assertRaises(ValueError): invalid = {3: {"b": 3}, "b": 3} parse_config(invalid) def test_parse_invalid_config_with_shortcut_ok(self): with self.assertRaises(ValueError): invalid = {3: {"b": 3}, "b": 3} parse_config(invalid, shortcut_ok=True)
tzhanl/azure-sdk-for-python
sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/models/deploy_configuration_parameters_py3.py
<reponame>tzhanl/azure-sdk-for-python # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class DeployConfigurationParameters(Model): """Deploy Tenant Configuration Contract. All required parameters must be populated in order to send to Azure. :param branch: Required. The name of the Git branch from which the configuration is to be deployed to the configuration database. :type branch: str :param force: The value enforcing deleting subscriptions to products that are deleted in this update. :type force: bool """ _validation = { 'branch': {'required': True}, } _attribute_map = { 'branch': {'key': 'properties.branch', 'type': 'str'}, 'force': {'key': 'properties.force', 'type': 'bool'}, } def __init__(self, *, branch: str, force: bool=None, **kwargs) -> None: super(DeployConfigurationParameters, self).__init__(**kwargs) self.branch = branch self.force = force
kagaramag/ke-be-dep
src/helpers/factory/userNormal.js
<filename>src/helpers/factory/userNormal.js // eslint-disable-next-line import/no-extraneous-dependencies import { Factory } from 'rosie'; import Chance from 'chance'; const chance = new Chance(); export default Factory.define('user') .sequence('id') .attr('firstName', chance.first()) .attr('lastName', chance.last()) .attr('username', chance.word({ length: 5 })) .attr('email', chance.email({ domain: 'nivelo.me' })) .attr('password', '<PASSWORD>!@#') .attr( 'permissions', JSON.stringify({ articles: ['read', 'create', 'delete', 'edit'], comments: ['read', 'create', 'delete', 'edit'], tags: ['read', 'create', 'delete'], users: ['read', 'create', 'edit', 'delete'] }) );
pr0d1r2/gentoo_converge
cookbooks/shell_aliases/recipes/default.rb
directory '/root/projects' execute 'update-ca-certificates' git '/root/projects/shell_aliases_compiler' do repository 'https://github.com/pr0d1r2/shell_aliases_compiler.git' revision 'master' action :sync end template '/root/projects/shell_aliases_compiler/.config.sh' do source 'config.sh.erb' variables node[:shell_aliases] end execute 'cd /root/projects/shell_aliases_compiler && git checkout master' execute '/root/projects/shell_aliases_compiler/setup.sh' execute 'cp /root/.compiled_shell_aliases.sh /etc/profile.d/compiled_shell_aliases.sh'
logicred/Euler-Project
Problem 4/problem4.py
#Answer = 906609 993 913 #cost = 0.291 import time start = time.time() def palindrome(a, b): #print(1) summary = a * b num = str(summary) i = 0 j = len(num) - 1 while i < j: if num[i] != num[j]: return False i += 1 j -= 1 return True maxnum = 0 m1 = 0 m2 = 0 for i in range(999, 99, -1): #print(0) j = i while j >= 100: temp = i * j if temp % 11 == 0 and palindrome(i, j) == True and temp > maxnum: maxnum = temp m1 = i m2 = j j -= 1 print(maxnum, m1, m2) end = time.time() print(end - start)
pitchpoint-solutions/sfs
sfs-server/src/main/java/org/sfs/rx/HttpClientKeepAliveResponseBodyBuffer.java
/* * Copyright 2016 The Simple File Server Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.sfs.rx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClientResponse; import rx.Observable; import rx.functions.Func1; import static com.google.common.base.Charsets.UTF_8; import static io.vertx.core.buffer.Buffer.buffer; import static rx.Observable.just; public class HttpClientKeepAliveResponseBodyBuffer implements Func1<HttpClientResponse, Observable<Buffer>> { @Override public Observable<Buffer> call(HttpClientResponse httpClientResponse) { return just(httpClientResponse) .flatMap(new HttpClientResponseBodyBuffer()) .map(buffer -> buffer(buffer.toString(UTF_8.toString()).trim(), UTF_8.toString())); } }
jxg01713/zstack
header/src/main/java/org/zstack/header/network/l3/APIListL3NetworkMsg.java
<reponame>jxg01713/zstack package org.zstack.header.network.l3; import org.zstack.header.message.APIListMessage; import java.util.List; public class APIListL3NetworkMsg extends APIListMessage { public APIListL3NetworkMsg() { } public APIListL3NetworkMsg(List<String> uuids) { super(uuids); } }
Flexberry/olingo-jpa-processor-v4
jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TypedQueryImpl.java
package com.sap.olingo.jpa.processor.cb.impl; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; import javax.persistence.LockTimeoutException; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; import javax.persistence.Parameter; import javax.persistence.PersistenceException; import javax.persistence.PessimisticLockException; import javax.persistence.Query; import javax.persistence.QueryTimeoutException; import javax.persistence.TemporalType; import javax.persistence.TransactionRequiredException; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; import com.sap.olingo.jpa.processor.cb.ProcessorSelection; import com.sap.olingo.jpa.processor.cb.impl.ExpressionImpl.ParameterExpression; class TypedQueryImpl<T> implements TypedQuery<T> { private final CriteriaQueryImpl<T> parent; private final Query q; private final ProcessorSelection<T> selection; TypedQueryImpl(final CriteriaQuery<T> criteriaQuery, final EntityManager em, final ParameterBuffer parameterBuffer) { final StringBuilder sql = new StringBuilder(); this.parent = (CriteriaQueryImpl<T>) criteriaQuery; this.parent.getResultType(); this.selection = (ProcessorSelection<T>) parent.getSelection(); this.q = em.createNativeQuery(parent.asSQL(sql).toString()); copyParameter(parameterBuffer.getParameter()); } @Override public int executeUpdate() { return q.executeUpdate(); } @Override public int getFirstResult() { return q.getFirstResult(); } @Override public FlushModeType getFlushMode() { return q.getFlushMode(); } @Override public Map<String, Object> getHints() { return q.getHints(); } @Override public LockModeType getLockMode() { return q.getLockMode(); } @Override public int getMaxResults() { return q.getMaxResults(); } @Override public Parameter<?> getParameter(final int position) { return q.getParameter(position); } @Override public <X> Parameter<X> getParameter(final int position, final Class<X> type) { return q.getParameter(position, type); } @Override public Parameter<?> getParameter(final String name) { return q.getParameter(name); } @Override public <X> Parameter<X> getParameter(final String name, final Class<X> type) { return q.getParameter(name, type); } @Override public Set<Parameter<?>> getParameters() { return q.getParameters(); } @Override public Object getParameterValue(final int position) { return q.getParameterValue(position); } @Override public <X> X getParameterValue(final Parameter<X> param) { return q.getParameterValue(param); } @Override public Object getParameterValue(final String name) { return q.getParameterValue(name); } /** * Execute a SELECT query and return the query results as a typed List. * @return a list of the results * @throws IllegalStateException if called for a Java * Persistence query language UPDATE or DELETE statement * @throws QueryTimeoutException if the query execution exceeds * the query timeout value set and only the statement is * rolled back * @throws TransactionRequiredException if a lock mode other than * <code>NONE</code> has been set and there is no transaction * or the persistence context has not been joined to the * transaction * @throws PessimisticLockException if pessimistic locking * fails and the transaction is rolled back * @throws LockTimeoutException if pessimistic locking * fails and only the statement is rolled back * @throws PersistenceException if the query execution exceeds * the query timeout value set and the transaction * is rolled back */ @SuppressWarnings("unchecked") @Override public List<T> getResultList() { final List<?> result = q.getResultList(); if (parent.getResultType().isAssignableFrom(Tuple.class)) { if (result.isEmpty()) return Collections.emptyList(); final List<Entry<String, JPAPath>> selPath = buildSelection(); final Map<String, Integer> index = buildSelectionIndex(selPath); final List<Entry<String, JPAAttribute>> selAttributes = toAttributeList(selPath); if (result.get(0).getClass().isArray()) { return (List<T>) ((List<Object[]>) result).stream() .map(r -> new TupleImpl(r, selAttributes, index)) .collect(Collectors.toList()); } return (List<T>) ((List<Object>) result).stream() .map(r -> new TupleImpl(r, selAttributes, index)) .collect(Collectors.toList()); } return (List<T>) result; } /** * Execute a SELECT query that returns a single untyped result. * @return the result * @throws NoResultException if there is no result * @throws NonUniqueResultException if more than one result * @throws IllegalStateException if called for a Java Persistence query language UPDATE or DELETE statement * @throws QueryTimeoutException if the query execution exceeds * the query timeout value set and only the statement is rolled back * @throws TransactionRequiredException if a lock mode other than * <code>NONE</code> has been set and there is no transaction * or the persistence context has not been joined to the transaction * @throws PessimisticLockException if pessimistic locking * fails and the transaction is rolled back * @throws LockTimeoutException if pessimistic locking * fails and only the statement is rolled back * @throws PersistenceException if the query execution exceeds * the query timeout value set and the transaction * is rolled back */ @Override public T getSingleResult() { final List<T> results = getResultList(); if (results.isEmpty()) throw new NoResultException(); if (results.size() > 1) throw new NonUniqueResultException(); return results.get(0); } @Override public boolean isBound(final Parameter<?> param) { return q.isBound(param); } @Override public TypedQuery<T> setFirstResult(final int startPosition) { q.setFirstResult(startPosition); return this; } @Override public TypedQuery<T> setFlushMode(final FlushModeType flushMode) { q.setFlushMode(flushMode); return this; } @Override public TypedQuery<T> setHint(final String hintName, final Object value) { q.setHint(hintName, value); return this; } @Override public TypedQuery<T> setLockMode(final LockModeType lockMode) { q.setLockMode(lockMode); return this; } @Override public TypedQuery<T> setMaxResults(final int maxResult) { q.setMaxResults(maxResult); return this; } @Override public TypedQuery<T> setParameter(final int position, final Calendar value, final TemporalType temporalType) { q.setParameter(position, value, temporalType); return this; } @Override public TypedQuery<T> setParameter(final int position, final Date value, final TemporalType temporalType) { q.setParameter(position, value, temporalType); return this; } @Override public TypedQuery<T> setParameter(final int position, final Object value) { q.setParameter(position, value); return this; } @Override public TypedQuery<T> setParameter(final Parameter<Calendar> param, final Calendar value, final TemporalType temporalType) { q.setParameter(param, value, temporalType); return this; } @Override public TypedQuery<T> setParameter(final Parameter<Date> param, final Date value, final TemporalType temporalType) { q.setParameter(param, value, temporalType); return this; } @Override public <X> TypedQuery<T> setParameter(final Parameter<X> param, final X value) { q.setParameter(param, value); return this; } @Override public TypedQuery<T> setParameter(final String name, final Calendar value, final TemporalType temporalType) { q.setParameter(name, value, temporalType); return this; } @Override public TypedQuery<T> setParameter(final String name, final Date value, final TemporalType temporalType) { q.setParameter(name, value, temporalType); return this; } @Override public TypedQuery<T> setParameter(final String name, final Object value) { q.setParameter(name, value); return this; } @Override public <X> X unwrap(final Class<X> cls) { return q.unwrap(cls); } private List<Entry<String, JPAPath>> buildSelection() { return selection.getResolvedSelection(); } private Map<String, Integer> buildSelectionIndex(final List<Entry<String, JPAPath>> selPath) { final int[] count = { 0 }; return selPath.stream() .collect(Collectors.toMap(Entry::getKey, p -> count[0]++)); } private void copyParameter(final Map<Integer, ParameterExpression<?, ?>> map) { map.entrySet().stream().forEach(e -> this.q.setParameter(e.getKey(), e.getValue().getValue())); } private List<Entry<String, JPAAttribute>> toAttributeList(final List<Entry<String, JPAPath>> selPath) { final List<Entry<String, JPAAttribute>> result = new ArrayList<>(selPath.size()); for (final Entry<String, JPAPath> entity : selPath) { result.add(new ProcessorSelection.SelectionAttribute(entity.getKey(), entity.getValue().getLeaf())); } return result; } }
wokalski/Distraction-Free-Xcode-plugin
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESpriteKitParticleEditor/SKInspectorVector2Property.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "IDEInspectorProperty.h" @class DVTStepperTextField, IDEInspectorKeyPath, NSString, NSTextField; @interface SKInspectorVector2Property : IDEInspectorProperty { DVTStepperTextField *xLabel; DVTStepperTextField *yLabel; NSTextField *xTextField; NSTextField *yTextField; IDEInspectorKeyPath *_valueKeyPath; IDEInspectorKeyPath *_xValueKeyPath; IDEInspectorKeyPath *_yValueKeyPath; NSString *_nilPlaceholder; } - (void).cxx_destruct; - (void)setupRefreshTriggersAndConfigure; - (void)refresh; - (void)userDidChangeValue:(id)arg1; - (void)applyUserSizeFromSender:(id)arg1 byMappingValues:(CDUnknownBlockType)arg2; - (double)baseline; @end
Zz1ven/voovan
Network/src/main/java/org/voovan/network/udp/UdpSocket.java
package org.voovan.network.udp; import org.voovan.Global; import org.voovan.network.ConnectModel; import org.voovan.network.SocketContext; import org.voovan.network.exception.ReadMessageException; import org.voovan.network.exception.RestartException; import org.voovan.network.exception.SendMessageException; import org.voovan.tools.log.Logger; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketOption; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; /** * UdpSocket 连接 * * @author helyho * * Voovan Framework. * WebSite: https://github.com/helyho/Voovan * Licence: Apache v2 License */ public class UdpSocket extends SocketContext { private SelectorProvider provider; private Selector selector; private DatagramChannel datagramChannel; private UdpSession session; /** * socket 连接 * 默认不会出发空闲事件, 默认发超时时间: 1s * @param host 监听地址 * @param port 监听端口 * @param readTimeout 超时时间, 单位: 毫秒 * @throws IOException IO异常 */ public UdpSocket(String host, int port, int readTimeout) throws IOException{ super(host, port, readTimeout); init(); } /** * socket 连接 * 默认发超时时间: 1s * @param host 监听地址 * @param port 监听端口 * @param idleInterval 空闲事件触发时间, 单位: 秒 * @param readTimeout 超时时间, 单位: 毫秒 * @throws IOException IO异常 */ public UdpSocket(String host, int port, int readTimeout, int idleInterval) throws IOException{ super(host, port, readTimeout, idleInterval); init(); } /** * socket 连接 * @param host 监听地址 * @param port 监听端口 * @param idleInterval 空闲事件触发时间, 单位: 秒 * @param readTimeout 超时时间, 单位: 毫秒 * @param sendTimeout 发超时时间, 单位: 毫秒 * @throws IOException IO异常 */ public UdpSocket(String host, int port, int readTimeout, int sendTimeout, int idleInterval) throws IOException{ super(host, port, readTimeout, sendTimeout, idleInterval); init(); } private void init() throws IOException { provider = SelectorProvider.provider(); datagramChannel = provider.openDatagramChannel(); datagramChannel.socket().setSoTimeout(this.readTimeout); InetSocketAddress address = new InetSocketAddress(this.host, this.port); session = new UdpSession(this,address); datagramChannel.configureBlocking(false); connectModel = ConnectModel.CLIENT; } /** * 构造函数 * @param parentSocketContext 父 SocketChannel 对象 * @param socketAddress SocketAddress 对象 */ protected UdpSocket(SocketContext parentSocketContext, DatagramChannel datagramChannel, InetSocketAddress socketAddress){ try { provider = SelectorProvider.provider(); this.datagramChannel = datagramChannel; this.copyFrom(parentSocketContext); session = new UdpSession(this, socketAddress); connectModel = ConnectModel.SERVER; } catch (Exception e) { Logger.error("Create socket channel failed",e); } } @Override public void setIdleInterval(int idleInterval) { this.idleInterval = idleInterval; } /** * 设置 Socket 的 Option 选项 * * @param name SocketOption类型的枚举, 参照:DatagramChannel.setOption的说明 * @param value SocketOption参数 * @throws IOException IO异常 */ public <T> void setOption(SocketOption<T> name, T value) throws IOException { datagramChannel.setOption(name, value); } /** * 初始化函数 */ private void registerSelector() { try{ selector = provider.openSelector(); datagramChannel.register(selector, SelectionKey.OP_READ); }catch(IOException e){ Logger.error("init SocketChannel failed by openSelector",e); } } /** * 获取 Session 对象 * @return Session 对象 */ public UdpSession getSession(){ return session; } public DatagramChannel datagramChannel(){ return this.datagramChannel; } @Override public void start() throws IOException { InetSocketAddress address = new InetSocketAddress(this.host, this.port); datagramChannel.connect(address); registerSelector(); if(datagramChannel!=null && datagramChannel.isOpen()){ UdpSelector udpSelector = new UdpSelector(selector,this); udpSelector.eventChose(); } } /** * 启动同步的上下文连接,同步读写时使用 */ public void syncStart(){ Global.getThreadPool().execute(new Runnable(){ public void run() { try { start(); } catch (IOException e) { e.printStackTrace(); } } }); } @Override protected void acceptStart() throws IOException { throw new RuntimeException("Unsupport method"); } /** * 重连当前连接 * @return UdpSocket对象 * @throws IOException IO 异常 * @throws RestartException 重新启动的异常 */ public UdpSocket restart() throws IOException, RestartException { if(this.connectModel == ConnectModel.CLIENT) { init(); this.start(); return this; }else{ throw new RestartException("Can't invoke reStart method in server mode"); } } /** * 重连当前连接 * 同步模式 * @return UdpSocket对象 * @throws IOException IO 异常 * @throws RestartException 重新启动的异常 */ public UdpSocket syncRestart() throws IOException, RestartException { if(this.connectModel == ConnectModel.CLIENT) { init(); this.syncStart(); return this; }else{ throw new RestartException("Can't invoke reStart method in server mode"); } } /** * 同步读取消息 * @return 读取出的对象 * @throws ReadMessageException 读取消息异常 */ public Object synchronouRead() throws ReadMessageException { return session.syncRead(); } /** * 同步发送消息 * @param obj 要发送的对象 * @throws SendMessageException 消息发送异常 */ public void synchronouSend(Object obj) throws SendMessageException { session.syncSend(obj); } @Override public boolean isOpen() { if(datagramChannel!=null){ return datagramChannel.isOpen(); }else{ return false; } } @Override public boolean isConnected() { if(datagramChannel!=null){ return datagramChannel.isConnected(); }else{ return false; } } @Override public boolean close() { if(datagramChannel!=null){ try{ datagramChannel.close(); //如果有未读数据等待数据处理完成 //session.wait(this.getReadTimeout()); session.getByteBufferChannel().release(); return true; } catch(IOException e){ Logger.error("Close SocketChannel failed",e); return false; } }else{ return true; } } }
wotchin/openGauss-server
src/include/utils/rowstore.h
<filename>src/include/utils/rowstore.h<gh_stars>1-10 /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * --------------------------------------------------------------------------------------- * * rowstore.h * Generalized routines for buffer row storage rotine * * Description: Generalized data row store routines. * * What is row store? * ------------------- * Quite like tuple store, row store is for storing the row data(serialized * tuple recieved from dn) and providing the disk swap ability. If the tuple * size stored in RowStore exceeds the max memory allowed (work_mem), the * following coming data will be written into disk. * * You might ask why don't we use tuple/batch store instead? * (1) for performance. The tuple/batch store will de-serialize data when store * the row data. That cause un-needed CPU overhead. That's why we have row store * which have the ability to put the row data in its original format. * (2) the tuple/batch store cannot store the nodeid of a row. * * * The design of row store * ------------------------ * row store coming with the features such as * (1) FIFO: which perserved data order. * (2) DiskOnDemand: the comming data will be written to disk only when the * memory is full. and unlike tuple/batch store all data(including the data * in the memory) is written to disk, the rowstore only write those data * who cannot fit into memory. * (3) O(1) for read and write. The data row is directly read/write from/to the * node's bank. Because we allocate a bank for each node. * * * The internal of row store * ------------------------ * The data structure for the row store is as follows: * * [row store] * bank[1]---->[m][m][m].....[m][d][d][d]......[d] * bank[2]---->[m][m][m].....[m][d][d][d]......[d] * bank[3]---->[m][m][m].....[m][d][d][d]......[d] * bank[N]---->[m][m][m].....[m][d][d][d]......[d] * *----in mem----*------in disk-----* * * The row store has many banks(NumDataNodes), each datanode has its own bank. * Each bank contains many cells. The input data row is directed to its own * bank based on the msgid, and append to the bank's cell list. If the bank * has enough memory to hold the cell, the cell will be appeded to the in mem * list, otherwise will be append to the in disk list. The cell will be compressed * to save both memory and diskspace. * * Relation of structs * ------------------------- * RowStoreManager: holds all meta-data for a row store and have one bank for each datanode * Bank: holds all cells of a given datanode * RowStoreCell: each datarow convert to a cell and stored in bank * * introduce to the APIs * ------------------------- * First of all, have to invoke RowStoreAlloc() to initialize a RowStoreManager * And then you can use RowStoreInsert() to insert DataRow into the RowStore. * If the row store contains any data, you can use RowStoreFetch() to get the data * in the row store. * Finally, you have to invoke RowStoreDestory() to do the clean up work. * * IDENTIFICATION * src/include/utils/rowstore.h * * --------------------------------------------------------------------------------------- */ #ifndef ROWSTORE_H #define ROWSTORE_H #include "storage/buffile.h" #include "utils/memprot.h" #include "utils/memutils.h" #include "pgxc/pgxcnode.h" #ifdef USE_ASSERT_CHECKING #define CHECK_MEM(rs) MemoryContextCheck(rs->context, rs->context->session_id > 0) #else #define CHECK_MEM(rs) #endif #define ROW_STORE_MAX_MEM \ (u_sess->attr.attr_memory.work_mem * 1024L) /* use u_sess->attr.attr_memory.work_mem, default 64MB */ /* * bank holds all cell of a given datanode */ typedef struct Bank { List* mem; /* in memory list */ BufFile* file; /* in disk list */ size_t max_size; /* max memory allowed by this bank */ size_t current_size; /* current memory allocated for this bank */ int write_fileno; /* disk file no for write */ off_t write_offset; /* file no offset for write */ int read_fileno; /* disk file no for read */ off_t read_offset; /* file no offset for read */ int length; /* how many tuples stored in this bank */ } Bank; /* * each row convert to a cell and stored in the bank */ typedef struct RowStoreCellData { char* msg; /* data row msg, might be compressed */ int msglen; /* length of the data row message */ int msgnode; /* node number of the data row message */ int clen; /* compressed length of the msg */ } RowStoreCellData; typedef RowStoreCellData* RowStoreCell; /* * row store manager holds all meta-data for a row store. */ typedef struct RowStoreManagerData { Bank** banks; /* each datanode has its own bank */ MemoryContext context; /* memory context for the RowStore */ int bank_num; /* total number of banks, should equal to NumDataNodes */ } RowStoreManagerData; typedef RowStoreManagerData* RowStoreManager; /*===============API================*/ /* initialize a row store */ extern RowStoreManager RowStoreAlloc(MemoryContext context, size_t max_size); /* insert a value into row store */ extern void RowStoreInsert(RowStoreManager rs, RemoteDataRow data); /* fetch data row based on node id */ extern bool RowStoreFetch(RowStoreManager rs, Oid nodeid, RemoteDataRow datarow); /* fetch data row */ extern bool RowStoreFetch(RowStoreManager rs, RemoteDataRow datarow); /* get the length of row store */ extern int RowStoreLen(RowStoreManager rs); /* distory a row store */ extern void RowStoreDestory(RowStoreManager rs); #endif
h03147/Algorithm-bro
leetcodetest/src/part_1/medium/dp/dicesSum_swordOffer60.java
package part_1.medium.dp; import java.util.*; public class dicesSum_swordOffer60 { public List<Map.Entry<Integer, Double>> dicesSum(int n) { final int face = 6; final int pointNum = face * n; long[][] dp = new long[n + 1][pointNum + 1]; for(int i = 1; i <= face; ++i) { dp[1][i] = 1; } for(int i = 2; i <= n; ++i) { // i 个骰子最小点数和为i个1 for(int j = i; j <= pointNum; ++j) { for(int k = 1; k <= face && k <= j ; ++k) { dp[i][j] += dp[i - 1][j - k]; } } } final double totalNum = Math.pow(6, n); List<Map.Entry<Integer, Double>> ret = new ArrayList<>(); for(int i = n; i <= pointNum; ++i) { ret.add(new AbstractMap.SimpleEntry<>(i, dp[n][i] / totalNum)); } return ret; } }
Drakandes/Portfolio_NicolasPaulBonneau
Code en C++ de Mage War Online/IncludeAllArmors.h
<gh_stars>0 #pragma once #include "A_ArmorOfTheWandering.h" #include "A_BeginnerArmor.h" #include "A_BrokenArmor.h" #include "A_RobeOfTheAcclaimed.h" #include "A_RobeOfTheAcclaimedPlus.h" #include "A_RobeOfTheAncient.h" #include "A_RobeOfTheAncientElite.h" #include "A_RobeOfTheApprentice.h" #include "A_RobeOfTheApprenticePlus.h" #include "A_RobeOfTheChief.h" #include "A_RobeOfTheChiefPlus.h" #include "A_RobeOfTheCommander.h" #include "A_RobeOfTheCommanderPlus.h" #include "A_RobeOfTheDevotee.h" #include "A_RobeOfTheDevoteePlus.h" #include "A_RobeOfTheExpert.h" #include "A_RobeOfTheExpertPlus.h" #include "A_RobeOfTheFabled.h" #include "A_RobeOfTheFabledElite.h" #include "A_RobeOfTheGuardian.h" #include "A_RobeOfTheHunter.h" #include "A_RobeOfTheMaster.h" #include "A_RobeOfTheMasterElite.h" #include "A_RobeOfTheNovice.h" #include "A_RobeOfTheNovicePlus.h" #include "A_RobeOfTheScout.h" #include "A_RobeOfTheScoutElite.h" #include "A_RobeOfTheSpecialist.h" #include "A_RobeOfTheSpecialistElite.h" #include "A_RobeOfTheWarrior.h" #include "A_RobeOfTheWarriorPlus.h" #include "A_RobeOfTheWizard.h" #include "A_RobeOfTheWizardElite.h"
pmcollins/keybasket
app/controllers/managers_controller.rb
class ManagersController < ApplicationController before_filter :coordinator_authorized?, :except => [:show] before_filter :manager_authorized?, :only => [:show] before_filter :find_company def new @manager = Manager.new end def show @manager = @company.managers.find(params[:id]) @manager_properties = @manager.manager_properties @login = @manager.login @contact = @manager.contact @phones = @contact.phones @purchase_orders = @manager.purchase_orders @is_coordinator = session[:coordinator_id] ? true : false end def create a = Address.create(params[:address]) contact = Contact.new(params[:contact]) contact.address = a contact.save login = Login.create(params[:login]) Manager.create( :contact_id => contact.id, :login_id => login.id, :company_id => @company.id ) redirect_to m([@company]) end end
ali-sharif/avm
org.aion.avm.rt/src/i/EarlyAbortException.java
package i; /** * Error that indicates the DApp need to abort early. */ public class EarlyAbortException extends AvmException { private static final long serialVersionUID = 1L; }
nataren/mono
mono/mini/tramp-hppa.c
/* * tramp-hppa.c: JIT trampoline code for hppa * * Copyright (c) 2007 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include <config.h> #include <glib.h> #include <mono/arch/hppa/hppa-codegen.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/marshal.h> #include <mono/metadata/tabledefs.h> #include "mini.h" #include "mini-hppa.h" /* sizeof (MonoLMF) == 320 + HPPA_STACK_LMF_OFFSET + linkage area (64 bytes) * leave some room to spare */ #define TRAMP_STACK_SIZE 512 /* Method-specific trampoline code fragment size */ #define METHOD_TRAMPOLINE_SIZE 128 /* Jump-specific trampoline code fragment size */ #define JUMP_TRAMPOLINE_SIZE 64 /* * mono_arch_get_unbox_trampoline: * @gsctx: the generic sharing context * @m: method pointer * @addr: pointer to native code for @m * * when value type methods are called through the vtable we need to unbox the * this argument. This method returns a pointer to a trampoline which does * unboxing before calling the method */ gpointer mono_arch_get_unbox_trampoline (MonoGenericSharingContext *gsctx, MonoMethod *m, gpointer addr) { guint8 *code, *start; int this_pos = hppa_r26; MonoDomain *domain = mono_domain_get (); if (MONO_TYPE_ISSTRUCT (mono_method_signature (m)->ret)) this_pos = hppa_r25; start = code = mono_domain_code_reserve (domain, 20); hppa_set (code, addr, hppa_r1); hppa_ldo (code, sizeof (MonoObject), this_pos, this_pos); hppa_bv (code, hppa_r0, hppa_r1); hppa_nop (code); mono_arch_flush_icache (start, code - start); g_assert ((code - start) <= 20); return start; } void mono_arch_patch_callsite (guint8 *method_start, guint8 *p, guint8 *addr) { guint32 *code = (void *)p; /* Search for and patch the calling sequence * * Possibilities are: * * CEE_CALL outputs the following sequence: * * ldil L'<addr>, r1 * ldo R'<addr>, r1 * bb,>=,n r1, 30, .+16 * depwi 0, 31, 2, r1 * ldw 4(r1), r19 * ldw 0(r1), r1 * ble 0(sr4,r1) * copy r31, rp * XXXXXXXXXXXXXXXX <- code points here */ /* Go back to the branching insn */ code -= 2; /* We can patch the code only if it is a direct call. In some cases * we can reach here via a reg-indirect call. In that case we can't * patch the callsite */ if ((code[0] >> 26) == 0x39 && /* ble */ (code[-4] >> 26) == 0x31 && /* bb */ (code[-6] >> 26) == 0x08) /* ldil */ { hppa_patch (&code[-6], addr); mono_arch_flush_icache (&code[-6], 8); } else { printf("Can't patch callsite!\n"); } } void mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr) { g_assert_not_reached (); } void mono_arch_nullify_class_init_trampoline (guint8 *code8, mgreg_t *regs) { guint32 *buf = (guint32 *)((unsigned long)code8 & ~3); guint32 *code = buf; code -= 2; if (code[0] == 0x08000240) /* nop - already nullified */ return; g_assert ((code[0] >> 26) == 0x39); /* ble */ hppa_nop (code); hppa_nop (code); mono_arch_flush_icache (buf, 8); } void mono_arch_nullify_plt_entry (guint8 *code, mgreg_t *regs) { g_assert_not_reached (); } #define ALIGN_TO(val,align) (((val) + ((align) - 1)) & ~((align) - 1)) /* * Stack frame description when the generic trampoline is called. * caller frame * -------------------- * MonoLMF * ------------------- * incoming argument registers * ------------------- * linkage area * ------------------- */ guchar* mono_arch_create_trampoline_code (MonoTrampolineType tramp_type) { guint8 *buf, *code = NULL; int i, offset; code = buf = mono_global_codeman_reserve (1024); /* Trampoline is called with "method" in r20 */ hppa_stw (buf, hppa_r2, -20, hppa_sp); hppa_copy (buf, hppa_sp, hppa_r1); hppa_ldo (buf, TRAMP_STACK_SIZE, hppa_sp, hppa_sp); /* Save the MonoLMF structure on the stack */ offset = HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, regs); for (i = 0; i < 32; i++) { if (HPPA_IS_SAVED_GREG (i)) { hppa_stw (buf, i, offset, hppa_r1); offset += sizeof(ulong); } } hppa_copy (buf, hppa_r1, hppa_r3); hppa_set (buf, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, fregs), hppa_r1); for (i = 0; i < 32; i++) { if (HPPA_IS_SAVED_FREG (i)) { hppa_fstdx (buf, i, hppa_r1, hppa_r3); hppa_ldo (buf, sizeof(double), hppa_r1, hppa_r1); } } /* Save the method info stored in r20 */ hppa_stw (buf, hppa_r20, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, method), hppa_r3); hppa_stw (buf, hppa_r3, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, ebp), hppa_sp); if (tramp_type == MONO_TRAMPOLINE_JUMP) { hppa_stw (buf, hppa_r0, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, eip), hppa_r3); } else { hppa_stw (buf, hppa_r2, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, eip), hppa_r3); } /* Save the incoming arguments too, before they can trashed by the * call to the magic trampoline */ offset = HPPA_STACK_LMF_OFFSET + sizeof (MonoLMF); for (i = hppa_r23; i <= hppa_r26; i++) { hppa_stw (buf, i, offset, hppa_r3); offset += sizeof(ulong); } hppa_stw (buf, hppa_r28, offset, hppa_r3); offset += sizeof(ulong); offset = ALIGN_TO (offset, sizeof(double)); hppa_ldo (buf, offset, hppa_r3, hppa_r1); for (i = hppa_fr4; i <= hppa_fr7; i++) { hppa_fstds (buf, i, 0, hppa_r1); hppa_ldo (buf, sizeof(double), hppa_r1, hppa_r1); } /* Call mono_get_lmf_addr */ hppa_set (buf, mono_get_lmf_addr, hppa_r1); hppa_depi (buf, 0, 31, 2, hppa_r1); hppa_ldw (buf, 0, hppa_r1, hppa_r1); hppa_ble (buf, 0, hppa_r1); hppa_copy (buf, hppa_r31, hppa_r2); /* r28 now points at the (MonoLMF **) for the current thread. */ /* new_lmf->lmf_addr = lmf_addr */ hppa_stw (buf, hppa_r28, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, lmf_addr), hppa_r3); /* new_lmf->previous_lmf = *lmf_addr */ hppa_ldw (buf, 0, hppa_r28, hppa_r1); hppa_stw (buf, hppa_r1, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, previous_lmf), hppa_r3); /* *lmf_addr = new_lmf */ hppa_ldo (buf, HPPA_STACK_LMF_OFFSET, hppa_r3, hppa_r1); hppa_stw (buf, hppa_r1, 0, hppa_r28); /* Call mono_magic_trampoline (mgreg_t *regs, guint8 *code, MonoMethod *m, guint8* tramp) */ hppa_ldo (buf, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, regs), hppa_r3, hppa_r26); hppa_ldw (buf, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, method), hppa_r3, hppa_r24); if (tramp_type == MONO_TRAMPOLINE_JUMP) hppa_copy (buf, hppa_r0, hppa_r25); else { hppa_ldw (buf, -20, hppa_r3, hppa_r25); /* clear the lower two (privilege) bits */ hppa_depi (buf, 0, 31, 2, hppa_r25); } hppa_copy (buf, hppa_r0, hppa_r23); if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT) hppa_set (buf, mono_class_init_trampoline, hppa_r1); else hppa_set (buf, mono_magic_trampoline, hppa_r1); hppa_depi (buf, 0, 31, 2, hppa_r1); hppa_ldw (buf, 0, hppa_r1, hppa_r1); hppa_ble (buf, 0, hppa_r1); hppa_copy (buf, hppa_r31, hppa_r2); /* Code address is now in r28 */ /* Unwind LMF */ hppa_ldw (buf, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, previous_lmf), hppa_r3, hppa_r20); hppa_ldw (buf, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, lmf_addr), hppa_r3, hppa_r21); hppa_stw (buf, hppa_r20, 0, hppa_r21); hppa_copy (buf, hppa_r28, hppa_r20); /* Restore arguments */ offset = HPPA_STACK_LMF_OFFSET + sizeof (MonoLMF); for (i = hppa_r23; i <= hppa_r26; i++) { hppa_ldw (buf, offset, hppa_r3, i); offset += sizeof(ulong); } hppa_ldw (buf, offset, hppa_r3, hppa_r28); offset += sizeof(ulong); offset = ALIGN_TO (offset, sizeof(double)); hppa_ldo (buf, offset, hppa_r3, hppa_r1); for (i = hppa_fr4; i <= hppa_fr7; i++) { hppa_fldds (buf, 0, hppa_r1, i); hppa_ldo (buf, sizeof(double), hppa_r1, hppa_r1); } /* Restore registers */ hppa_set (buf, HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, fregs), hppa_r1); for (i = 0; i < 32; i++) { if (HPPA_IS_SAVED_FREG (i)) { hppa_flddx (buf, hppa_r1, hppa_r3, i); hppa_ldo (buf, sizeof(double), hppa_r1, hppa_r1); } } hppa_copy (buf, hppa_r3, hppa_r1); offset = HPPA_STACK_LMF_OFFSET + G_STRUCT_OFFSET (MonoLMF, regs); for (i = 0; i < 32; i++) { if (HPPA_IS_SAVED_GREG (i)) { hppa_ldw (buf, offset, hppa_r1, i); offset += sizeof(ulong); } } /* Jump to the compiled code in hppa_r28 */ hppa_ldw (buf, -20, hppa_r1, hppa_r2); hppa_bv (buf, hppa_r0, hppa_r20); hppa_ldo (buf, -TRAMP_STACK_SIZE, hppa_sp, hppa_sp); g_assert ((buf - code) <= 1024); return code; } /** * mono_arch_create_class_init_trampoline: * @vtable: the type to initialize * * Creates a trampoline function to run a type initializer. * If the trampoline is called, it calls mono_runtime_class_init with the * given vtable, then patches the caller code so it does not get called any * more. * * Returns: a pointer to the newly created code */ gpointer mono_arch_create_class_init_trampoline (MonoVTable *vtable) { guint8 *code, *buf, *tramp; tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT); /* This is the method-specific part of the trampoline. Its purpose is to provide the generic part with the MonoMethod *method pointer. */ code = buf = mono_domain_code_reserve (vtable->domain, METHOD_TRAMPOLINE_SIZE); hppa_stw (buf, hppa_r2, -20, hppa_sp); hppa_copy (buf, hppa_r3, hppa_r1); hppa_copy (buf, hppa_sp, hppa_r3); hppa_stwm (buf, hppa_r1, 64, hppa_sp); /* mono_class_init_trampoline (regs, code, vtable, tramp) */ hppa_copy (buf, hppa_r0, hppa_r26); hppa_copy (buf, hppa_r2, hppa_r25); hppa_set (buf, vtable, hppa_r24); hppa_copy (buf, hppa_r0, hppa_r23); hppa_set (buf, mono_class_init_trampoline, hppa_r1); hppa_depi (buf, 0, 31, 2, hppa_r1); hppa_ldw (buf, 0, hppa_r1, hppa_r1); hppa_ble (buf, 0, hppa_r1); hppa_copy (buf, hppa_r31, hppa_r2); hppa_ldw (buf, -20, hppa_r3, hppa_r2); hppa_ldo (buf, 64, hppa_r3, hppa_sp); hppa_bv (buf, hppa_r0, hppa_r2); hppa_ldwm (buf, -64, hppa_sp, hppa_r3); /* Flush instruction cache, since we've generated code */ mono_arch_flush_icache (code, buf - code); /* Sanity check */ g_assert ((buf - code) <= METHOD_TRAMPOLINE_SIZE); return code; } static MonoJitInfo* create_specific_tramp (MonoMethod *method, guint8* tramp, MonoDomain *domain) { guint8 *code, *buf; MonoJitInfo *ji; code = buf = mono_domain_code_reserve (domain, 20); /* Call trampoline, with the "method" pointer in r20 */ hppa_set (buf, tramp, hppa_r1); hppa_ldil (buf, hppa_lsel (method), hppa_r20); hppa_bv (buf, hppa_r0, hppa_r1); hppa_ldo (buf, hppa_rsel (method), hppa_r20, hppa_r20); /* Flush instruction cache, since we've generated code */ mono_arch_flush_icache (code, buf - code); g_assert ((buf - code) <= 20); ji = g_new0 (MonoJitInfo, 1); ji->method = method; ji->code_start = code; ji->code_size = buf - code; return ji; } MonoJitInfo* mono_arch_create_jump_trampoline (MonoMethod *method) { guint8 *tramp; MonoDomain* domain = mono_domain_get (); tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_JUMP); return create_specific_tramp (method, tramp, domain); } /** * arch_create_jit_trampoline: * @method: pointer to the method info * * Creates a trampoline function for virtual methods. If the created * code is called it first starts JIT compilation of method, * and then calls the newly created method. It also replaces the * corresponding vtable entry (see mono_magic_trampoline). * * A trampoline consists of two parts: a main fragment, shared by all method * trampolines, and some code specific to each method, which hard-codes a * reference to that method and then calls the main fragment. * * The main fragment contains a call to 'arm_magic_trampoline', which performs * call to the JIT compiler and substitutes the method-specific fragment with * some code that directly calls the JIT-compiled method. * * Returns: a pointer to the newly created code */ gpointer mono_arch_create_jit_trampoline (MonoMethod *method) { guint8 *tramp; MonoJitInfo *ji; MonoDomain* domain = mono_domain_get (); gpointer code_start; tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_JIT); ji = create_specific_tramp (method, tramp, domain); code_start = ji->code_start; g_free (ji); return code_start; } gpointer mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 encoded_offset) { /* FIXME: implement! */ g_assert_not_reached (); return NULL; }
jianglei-tianma/knows
hadoop_demo/src/main/java/com/lagou/hdfs/hadoop/demo/mr/WordcountReducer.java
<reponame>jianglei-tianma/knows package com.lagou.hdfs.hadoop.demo.mr; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; //继承的Reduce类有四个泛型参数,2对kv //第一对kv:类型要与mapper输出类型一致:Text, IntWritable //第二队kv:自己设计决定输出的结果数据是什么类型:Text, IntWritable public class WordcountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { //1 重写reduce方法 //Text key, :map方法输出的key,本案例中就是单词 // Iterable<IntWritable> values:一组key相同的kv的value组成的集合 /* * 假设map方法:hello1;hello 1;hello 1 * reduce的key和value是什么 * key:hello * values:<1,1,1> * 假设map方法输出:hello 1;hello 1; hello 1,hadoop 1, mapreduce 1,hadoop 1 * reduce的key和value是什么? * reduce方法何时调用:一组key相同的kv中的value组成集合然后调用一次reduce方法 * 第一次:key:hello,values:<1,1,1> 第二次:key:hadoop, values:<1,1> 第三次:key:mapreduce,values<1> * */ IntWritable total = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { //2、遍历key对应的values,然后累加结果 int sum = 0; for (IntWritable value : values) { int i = value.get(); sum += i; } //3、直接输出当前key对应的sum值,结果就是单词出现的踪次数 total.set(sum); context.write(key, total); } }
Fsero/maiao
pkg/github/github.go
package gh import ( "context" "fmt" "net/url" "github.com/google/go-github/v40/github" "github.com/sirupsen/logrus" "golang.org/x/oauth2" ) // NewClient instanciates a new github client depending on the domain name // // When requesting a client for a different host than github.com, // a client for github enterprise is considered // // Credentials are even taken from GITHUB_TOKEN environment variable or // from your ~/.netrc file func NewClient(domain string) (*github.Client, error) { logger := Logger.WithFields(logrus.Fields{ "context": "initializing GitHub client", }) if domain == "github.com" { domain = "api.github.com" } token, err := getGithubToken(domain) if err != nil { logger.Errorf("unable to find token for %s: %s", domain, err.Error()) return nil, fmt.Errorf("unable to find token for %s: %s", domain, err.Error()) } ctx := context.Background() ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(ctx, ts) c := github.NewClient(tc) if domain != "api.github.com" { GitHubURL := url.URL{ Scheme: "https", Host: domain, Path: "/api/v3/", } GitHubUploadURL := GitHubURL GitHubUploadURL.Path = "/api/v3/upload/" c.BaseURL = &GitHubURL // TODO: confirm from https://github.com/goreleaser/goreleaser/issues/365#issuecomment-331655225 c.UploadURL = &GitHubUploadURL } return c, nil } func getGithubToken(domain string) (string, error) { creds, err := DefaultCredentialGetter.CredentialForHost(domain) if err != nil { return "", err } token := findFirstNonEmptyString(creds.Password, creds.Username) if token != "" { Logger.WithFields(logrus.Fields{ "context": "initializing GitHub client", }).Debugf("using github token from credentials store") return token, nil } return "", fmt.Errorf("unable to find a token for domain %s", domain) } func findFirstNonEmptyString(ss ...string) string { for _, s := range ss { if s != "" { return s } } return "" }
IlfirinPL/robotframework-testmanagement
src/TestManagementLibrary/user.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Lingaro from .query import ( Operator, DisplayNameParameter ) class UserManager(object): """ We assumes that this class will be mixed with RallyConnectionManager to provide the _get_rally_connection method. """ def _get_user(self, query, **kwargs): """ Calls Rally Rest API with given query and fetch build object :param query: RallyQuery object :return: Build object """ return self._execute_rally_query(u'User', query, fetch=True, **kwargs) def _get_user_by_name(self, name): return self._get_object_by_id(u'User', DisplayNameParameter(name, Operator.EQUAL))
arayi/colobus
src/functions/flatten.js
const flatten = (arr) => { const newArray = [] if (Array.isArray(arr) || typeof arr === "string") { for (let i of arr) { if (!Array.isArray(i) ) { newArray.push(i) } else { for (let j of i) { newArray.push(j) } } } return newArray } return [] } export default flatten
AmirAlahmedy/Node.js-nandbox-Help-Bot
src/data/Gif.js
<filename>src/data/Gif.js const Thumbnail = require("../data/Thumbnail"); /** * This class represents incoming Message used to get Gif Message . * * @author <NAME> @Amir * */ module.exports = class Gif { constructor(obj) { this.id = obj.id; this.width = Number(obj.width); this.height = Number(obj.height); this.size = Number(obj.size); this.thumbnail = obj.thumbnail ? new Thumbnail(obj.thumbnail) : null; } toJsonObject(){ let obj = {}; if (this.id) obj.id = this.id; if (this.width) obj.width = this.width; if (this.height) obj.height = this.height; if (this.size) obj.size = this.size; if (this.thumbnail) obj.thumbnail = this.thumbnail; return obj; } }
glossina/ldetool
internal/ast/action_pass_heading_characters.go
<gh_stars>100-1000 package ast import ( "fmt" ) var _ Action = PassHeadingCharacters('1') type PassHeadingCharacters string func (a PassHeadingCharacters) String() string { return fmt.Sprintf("pass all '%s' characters in the head of rest", string(a)) } func (a PassHeadingCharacters) Accept(d ActionDispatcher) error { return d.DispatchPassHeadingCharacters(a) } func (a PassHeadingCharacters) neverCallMe() {}
MrRleft/QFLowServer
src/main/java/com/qflow/server/controller/dto/UserPost.java
<filename>src/main/java/com/qflow/server/controller/dto/UserPost.java package com.qflow.server.controller.dto; public class UserPost { private String username; private String password; private String email; private String nameLastName; public String getUsername() { return username; } public String getPassword() { return password; } public String getEmail() { return email; } public String getNameLastName() { return nameLastName; } public static final class UserPostBuilder { private String userName; private String password; private String email; private String nameLastName; private UserPostBuilder() { } public static UserPostBuilder anUserPost() { return new UserPostBuilder(); } public UserPostBuilder withUserName(String userName) { this.userName = userName; return this; } public UserPostBuilder withPassword(String password) { this.password = password; return this; } public UserPostBuilder withEmail(String email) { this.email = email; return this; } public UserPostBuilder withNameLastName(String nameLastName) { this.nameLastName = nameLastName; return this; } public UserPost build() { UserPost userPost = new UserPost(); userPost.email = this.email; userPost.nameLastName = this.nameLastName; userPost.username = this.userName; userPost.password = <PASSWORD>; return userPost; } } }
tianruoliu/deep-in-java
stage-2/lesson1/src/main/java/com/ajin/deep/in/java/modular/ModuleReflectionDemo.java
package com.ajin.deep.in.java.modular; import java.lang.module.ModuleDescriptor; import java.util.logging.Logger; /** * 模块化反射Demo * * @author ajin */ public class ModuleReflectionDemo { public static void main(String[] args) { Class<Logger> loggerClass = Logger.class; Module module = loggerClass.getModule(); String moduleName = module.getName(); System.out.printf("%s 类存在于模块%s 中\n", loggerClass.getName(), moduleName); ModuleDescriptor moduleDescriptor = module.getDescriptor(); moduleDescriptor.requires().forEach(require -> System.out.println(require.modifiers()) ); } }
researchgate/nodejs-simple-downloader
nsd/nodejs/arch_darwin_arm64.go
<filename>nsd/nodejs/arch_darwin_arm64.go package nodejs // CurrentArch and CurrentURL describe how the URL of the nodejs download will look like const ( CurrentArch string = "darwin-x64" //until nodejs provides a specific image for arm64 we'll use x64 CurrentURL DownloadURL = Stable CurrentExtension FileExtension = TarXz )
drking445/Spotify
node_modules/react-component-metadata/lib/createClass-visitor.js
<filename>node_modules/react-component-metadata/lib/createClass-visitor.js 'use strict'; var _babelTypes = require('babel-types'); var t = _interopRequireWildcard(_babelTypes); var _componentBodyVisitor = require('./component-body-visitor'); var _componentBodyVisitor2 = _interopRequireDefault(_componentBodyVisitor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var _require = require('./parseProps'), parsePropTypes = _require.parsePropTypes, parseDefaultProps = _require.parseDefaultProps, resolveToValue = require('./util/resolveToValue'), resolveToName = require('./util/resolveToName'), isReactClass = require('./util/isReactCreateClass'), find = require('lodash/collection/find'), uuid = require('lodash/utility/uniqueId'), doc = require('./util/comments'); var isResolvable = resolveToValue.isResolvable; function getCreatClassName(spec, visitor, scope, comment) { var parent = visitor.parentPath.node, displayName = find(spec || [], function (node) { return t.isProperty(node) && node.key.name === 'displayName'; }), literal = displayName && resolveToValue(displayName.value, scope), doclets = doc.getDoclets(comment); if (doclets.alias || doclets.name) return doclets.alias || doclets.name;else if (literal) return literal.value;else if (t.isVariableDeclarator(parent)) return parent.id.name;else if (t.isProperty(parent)) return parent.key.name; return uuid('AnonymousComponent'); } module.exports = function (state, opts) { var json = state.result, components = state.seen; return { enter: function enter(path) { var node = path.node, scope = path.scope; if (isReactClass(node.callee, scope)) { var spec = resolveToValue(node.arguments[0], scope).properties, comment = doc.parseCommentBlock(doc.findLeadingCommentNode(path)), component = getCreatClassName(spec, path, scope, comment), propTypes = find(spec, function (node) { return t.isProperty(node) && node.key.name === 'propTypes'; }), getDefaultProps = find(spec, function (node) { return (t.isProperty(node) || t.isObjectMethod(node)) && node.key.name === 'getDefaultProps'; }); components.push(component); json[component] = { props: {}, composes: [], methods: (0, _componentBodyVisitor2.default)(spec), desc: comment || '' }; if (opts.mixins) { var mixins = find(spec, function (node) { return t.isProperty(node) && node.key.name === 'mixins'; }); if (mixins) { json[component].mixins = []; parseMixins(mixins.value.elements, scope, json[component].mixins); } } propTypes && parsePropTypes(resolveToValue(propTypes.value, scope), json[component], scope); if (getDefaultProps) { var body = (t.isProperty(getDefaultProps) ? getDefaultProps.value.body : getDefaultProps.body).body; var defaultProps = find(body, function (node) { return t.isReturnStatement(node) && (isResolvable(node.argument) || t.isIdentifier(node.argument)); }); if (defaultProps) parseDefaultProps(resolveToValue(defaultProps.argument, scope), json[component], state.file, scope); } } } }; }; function parseMixins() { var mixins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var scope = arguments[1]; var composes = arguments[2]; mixins.forEach(function (mixin) { var name = resolveToName(mixin, scope); if (name && composes.indexOf(name) === -1) composes.push(name); }); }
Mysticpasta1/DimDoors
src/main/java/org/dimdev/dimdoors/shared/world/ModDimensions.java
package org.dimdev.dimdoors.shared.world; import lombok.Getter; import net.minecraft.world.DimensionType; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import org.dimdev.dimdoors.shared.ModConfig; import org.dimdev.dimdoors.shared.world.limbo.WorldProviderLimbo; import org.dimdev.dimdoors.shared.world.pocketdimension.WorldProviderDungeonPocket; import org.dimdev.dimdoors.shared.world.pocketdimension.WorldProviderPersonalPocket; import org.dimdev.dimdoors.shared.world.pocketdimension.WorldProviderPublicPocket; public final class ModDimensions { // These are ok to register on class load, the DimensionType.register method only adds an enum value to DimensionTypes // Lowercase names because all minecraft dimensions are lowercase, _pockets suffix to make it clear what the world is public static final DimensionType LIMBO = DimensionType.register("limbo", "_limbo", 684, WorldProviderLimbo.class, false); public static final DimensionType PRIVATE = DimensionType.register("private_pockets", "_private", 685, WorldProviderPersonalPocket.class, false); public static final DimensionType PUBLIC = DimensionType.register("public_pockets", "_public", 686, WorldProviderPublicPocket.class, false); public static final DimensionType DUNGEON = DimensionType.register("dungeon_pockets", "_dungeon", 687, WorldProviderDungeonPocket.class, false); @Getter private static int limboDim; @Getter private static int privateDim; @Getter private static int publicDim; @Getter private static int dungeonDim; @Getter private static int dungeonMakingDim; @SuppressWarnings("UnusedAssignment") public static void registerDimensions() { // TODO: more than 1 dimension/dimension type int dim = ModConfig.general.baseDimensionID; limboDim = dim++; privateDim = dim++; publicDim = dim++; dungeonDim = dim++; dungeonMakingDim = dim++; DimensionManager.registerDimension(limboDim, LIMBO); DimensionManager.registerDimension(privateDim, PRIVATE); DimensionManager.registerDimension(publicDim, PUBLIC); DimensionManager.registerDimension(dungeonDim, DUNGEON); DimensionManager.registerDimension(dungeonMakingDim, DUNGEON); } public static boolean isDimDoorsPocketDimension(int id) { return id == privateDim || id == publicDim || id == dungeonDim; } public static boolean isDimDoorsPocketDimension(World world) { return world.provider instanceof WorldProviderPublicPocket || world.provider instanceof WorldProviderPersonalPocket || world.provider instanceof WorldProviderDungeonPocket; } }
YanXs/nighthawk
nightawk-jdbc/src/main/java/com/github/nightawk/jdbc/support/DB2URLParser.java
package com.github.nightawk.jdbc.support; import java.net.URI; /** * jdbc:db2://192.168.0.2:50000/test * * @author Xs. */ public class DB2URLParser implements URLParser { @Override public DatabaseURL parse(String url) { DatabaseURL databaseUrl = DatabaseURL.DATABASE_URLS.get(url); if (databaseUrl == null) { URI uri = URI.create(url.substring(5)); // strip "jdbc:" String host = uri.getHost(); int port = uri.getPort(); String dataBase = uri.getPath().substring(1); // path "/test" databaseUrl = new DatabaseURL(host, port, dataBase); DatabaseURL.DATABASE_URLS.putIfAbsent(url, databaseUrl); } return databaseUrl; } }
aliahsan07/safe-development
tests/test262/15.4/15.4.4/15.4.4.7/S15.4.4.7_A5_T1.js
Object.prototype[1] = - 1; Object.prototype.length = 1; Object.prototype.push = Array.prototype.push; var x = { 0 : 0 }; var push = x.push(1); { var __result1 = push !== 2; var __expect1 = false; } { var __result2 = x.length !== 2; var __expect2 = false; } { var __result3 = x[1] !== 1; var __expect3 = false; } delete x[1]; { var __result4 = x[1] !== - 1; var __expect4 = false; } delete x.length; { var __result5 = x.length !== 1; var __expect5 = false; }
egriswol/astr-119-section-assignments
hello-world-Kyle-D.py
<gh_stars>1-10 #!/usr/bin/env python3 print("Hello from <NAME>!")
jambolo/jambolo.github.io
docs/Vkx/html/search/classes_8.js
<filename>docs/Vkx/html/search/classes_8.js var searchData= [ ['material',['Material',['../class_vkx_1_1_material.html',1,'Vkx']]] ];
fergy/aplit_linux-5
mm/frontswap.c
/* * Frontswap frontend * * This code provides the generic "frontend" layer to call a matching * "backend" driver implementation of frontswap. See * Documentation/vm/frontswap.rst for more information. * * Copyright (C) 2009-2012 Oracle Corp. All rights reserved. * Author: <NAME> * * This work is licensed under the terms of the GNU GPL, version 2. */ #include <linux/mman.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/security.h> #include <linux/module.h> #include <linux/debugfs.h> #include <linux/frontswap.h> #include <linux/swapfile.h> DEFINE_STATIC_KEY_FALSE(frontswap_enabled_key); /* * frontswap_ops are added by frontswap_register_ops, and provide the * frontswap "backend" implementation functions. Multiple implementations * may be registered, but implementations can never deregister. This * is a simple singly-linked list of all registered implementations. */ static struct frontswap_ops *frontswap_ops __read_mostly; #define for_each_frontswap_ops(ops) \ for ((ops) = frontswap_ops; (ops); (ops) = (ops)->next) /* * If enabled, frontswap_store will return failure even on success. As * a result, the swap subsystem will always write the page to swap, in * effect converting frontswap into a writethrough cache. In this mode, * there is no direct reduction in swap writes, but a frontswap backend * can unilaterally "reclaim" any pages in use with no data loss, thus * providing increases control over maximum memory usage due to frontswap. */ static bool frontswap_writethrough_enabled __read_mostly; /* * If enabled, the underlying tmem implementation is capable of doing * exclusive gets, so frontswap_load, on a successful tmem_get must * mark the page as no longer in frontswap AND mark it dirty. */ static bool frontswap_tmem_exclusive_gets_enabled __read_mostly; #ifdef CONFIG_DEBUG_FS /* * Counters available via /sys/kernel/debug/frontswap (if debugfs is * properly configured). These are for information only so are not protected * against increment races. */ static u64 frontswap_loads; static u64 frontswap_succ_stores; static u64 frontswap_failed_stores; static u64 frontswap_invalidates; static inline void inc_frontswap_loads(void) { frontswap_loads++; } static inline void inc_frontswap_succ_stores(void) { frontswap_succ_stores++; } static inline void inc_frontswap_failed_stores(void) { frontswap_failed_stores++; } static inline void inc_frontswap_invalidates(void) { frontswap_invalidates++; } #else static inline void inc_frontswap_loads(void) { } static inline void inc_frontswap_succ_stores(void) { } static inline void inc_frontswap_failed_stores(void) { } static inline void inc_frontswap_invalidates(void) { } #endif /* * Due to the asynchronous nature of the backends loading potentially * _after_ the swap system has been activated, we have chokepoints * on all frontswap functions to not call the backend until the backend * has registered. * * This would not guards us against the user deciding to call swapoff right as * we are calling the backend to initialize (so swapon is in action). * Fortunatly for us, the swapon_mutex has been taked by the callee so we are * OK. The other scenario where calls to frontswap_store (called via * swap_writepage) is racing with frontswap_invalidate_area (called via * swapoff) is again guarded by the swap subsystem. * * While no backend is registered all calls to frontswap_[store|load| * invalidate_area|invalidate_page] are ignored or fail. * * The time between the backend being registered and the swap file system * calling the backend (via the frontswap_* functions) is indeterminate as * frontswap_ops is not atomic_t (or a value guarded by a spinlock). * That is OK as we are comfortable missing some of these calls to the newly * registered backend. * * Obviously the opposite (unloading the backend) must be done after all * the frontswap_[store|load|invalidate_area|invalidate_page] start * ignoring or failing the requests. However, there is currently no way * to unload a backend once it is registered. */ /* * Register operations for frontswap */ void frontswap_register_ops(struct frontswap_ops *ops) { DECLARE_BITMAP(a, MAX_SWAPFILES); DECLARE_BITMAP(b, MAX_SWAPFILES); struct swap_info_struct *si; unsigned int i; bitmap_zero(a, MAX_SWAPFILES); bitmap_zero(b, MAX_SWAPFILES); spin_lock(&swap_lock); plist_for_each_entry(si, &swap_active_head, list) { if (!WARN_ON(!si->frontswap_map)) set_bit(si->type, a); } spin_unlock(&swap_lock); /* the new ops needs to know the currently active swap devices */ for_each_set_bit(i, a, MAX_SWAPFILES) ops->init(i); /* * Setting frontswap_ops must happen after the ops->init() calls * above; cmpxchg implies smp_mb() which will ensure the init is * complete at this point. */ do { ops->next = frontswap_ops; } while (cmpxchg(&frontswap_ops, ops->next, ops) != ops->next); static_branch_inc(&frontswap_enabled_key); spin_lock(&swap_lock); plist_for_each_entry(si, &swap_active_head, list) { if (si->frontswap_map) set_bit(si->type, b); } spin_unlock(&swap_lock); /* * On the very unlikely chance that a swap device was added or * removed between setting the "a" list bits and the ops init * calls, we re-check and do init or invalidate for any changed * bits. */ if (unlikely(!bitmap_equal(a, b, MAX_SWAPFILES))) { for (i = 0; i < MAX_SWAPFILES; i++) { if (!test_bit(i, a) && test_bit(i, b)) ops->init(i); else if (test_bit(i, a) && !test_bit(i, b)) ops->invalidate_area(i); } } } EXPORT_SYMBOL(frontswap_register_ops); /* * Enable/disable frontswap writethrough (see above). */ void frontswap_writethrough(bool enable) { frontswap_writethrough_enabled = enable; } EXPORT_SYMBOL(frontswap_writethrough); /* * Enable/disable frontswap exclusive gets (see above). */ void frontswap_tmem_exclusive_gets(bool enable) { frontswap_tmem_exclusive_gets_enabled = enable; } EXPORT_SYMBOL(frontswap_tmem_exclusive_gets); /* * Called when a swap device is swapon'd. */ void __frontswap_init(unsigned type, unsigned long *map) { struct swap_info_struct *sis = swap_info[type]; struct frontswap_ops *ops; VM_BUG_ON(sis == NULL); /* * p->frontswap is a bitmap that we MUST have to figure out which page * has gone in frontswap. Without it there is no point of continuing. */ if (WARN_ON(!map)) return; /* * Irregardless of whether the frontswap backend has been loaded * before this function or it will be later, we _MUST_ have the * p->frontswap set to something valid to work properly. */ frontswap_map_set(sis, map); for_each_frontswap_ops(ops) ops->init(type); } EXPORT_SYMBOL(__frontswap_init); bool __frontswap_test(struct swap_info_struct *sis, pgoff_t offset) { if (sis->frontswap_map) return test_bit(offset, sis->frontswap_map); return false; } EXPORT_SYMBOL(__frontswap_test); static inline void __frontswap_set(struct swap_info_struct *sis, pgoff_t offset) { set_bit(offset, sis->frontswap_map); atomic_inc(&sis->frontswap_pages); } static inline void __frontswap_clear(struct swap_info_struct *sis, pgoff_t offset) { clear_bit(offset, sis->frontswap_map); atomic_dec(&sis->frontswap_pages); } /* * "Store" data from a page to frontswap and associate it with the page's * swaptype and offset. Page must be locked and in the swap cache. * If frontswap already contains a page with matching swaptype and * offset, the frontswap implementation may either overwrite the data and * return success or invalidate the page from frontswap and return failure. */ int __frontswap_store(struct page *page) { int ret = -1; swp_entry_t entry = { .val = page_private(page), }; int type = swp_type(entry); struct swap_info_struct *sis = swap_info[type]; pgoff_t offset = swp_offset(entry); struct frontswap_ops *ops; VM_BUG_ON(!frontswap_ops); VM_BUG_ON(!PageLocked(page)); VM_BUG_ON(sis == NULL); /* * If a dup, we must remove the old page first; we can't leave the * old page no matter if the store of the new page succeeds or fails, * and we can't rely on the new page replacing the old page as we may * not store to the same implementation that contains the old page. */ if (__frontswap_test(sis, offset)) { __frontswap_clear(sis, offset); for_each_frontswap_ops(ops) ops->invalidate_page(type, offset); } /* Try to store in each implementation, until one succeeds. */ for_each_frontswap_ops(ops) { ret = ops->store(type, offset, page); if (!ret) /* successful store */ break; } if (ret == 0) { __frontswap_set(sis, offset); inc_frontswap_succ_stores(); } else { inc_frontswap_failed_stores(); } if (frontswap_writethrough_enabled) /* report failure so swap also writes to swap device */ ret = -1; return ret; } EXPORT_SYMBOL(__frontswap_store); /* * "Get" data from frontswap associated with swaptype and offset that were * specified when the data was put to frontswap and use it to fill the * specified page with data. Page must be locked and in the swap cache. */ int __frontswap_load(struct page *page) { int ret = -1; swp_entry_t entry = { .val = page_private(page), }; int type = swp_type(entry); struct swap_info_struct *sis = swap_info[type]; pgoff_t offset = swp_offset(entry); struct frontswap_ops *ops; VM_BUG_ON(!frontswap_ops); VM_BUG_ON(!PageLocked(page)); VM_BUG_ON(sis == NULL); if (!__frontswap_test(sis, offset)) return -1; /* Try loading from each implementation, until one succeeds. */ for_each_frontswap_ops(ops) { ret = ops->load(type, offset, page); if (!ret) /* successful load */ break; } if (ret == 0) { inc_frontswap_loads(); if (frontswap_tmem_exclusive_gets_enabled) { SetPageDirty(page); __frontswap_clear(sis, offset); } } return ret; } EXPORT_SYMBOL(__frontswap_load); /* * Invalidate any data from frontswap associated with the specified swaptype * and offset so that a subsequent "get" will fail. */ void __frontswap_invalidate_page(unsigned type, pgoff_t offset) { struct swap_info_struct *sis = swap_info[type]; struct frontswap_ops *ops; VM_BUG_ON(!frontswap_ops); VM_BUG_ON(sis == NULL); if (!__frontswap_test(sis, offset)) return; for_each_frontswap_ops(ops) ops->invalidate_page(type, offset); __frontswap_clear(sis, offset); inc_frontswap_invalidates(); } EXPORT_SYMBOL(__frontswap_invalidate_page); /* * Invalidate all data from frontswap associated with all offsets for the * specified swaptype. */ void __frontswap_invalidate_area(unsigned type) { struct swap_info_struct *sis = swap_info[type]; struct frontswap_ops *ops; VM_BUG_ON(!frontswap_ops); VM_BUG_ON(sis == NULL); if (sis->frontswap_map == NULL) return; for_each_frontswap_ops(ops) ops->invalidate_area(type); atomic_set(&sis->frontswap_pages, 0); bitmap_zero(sis->frontswap_map, sis->max); } EXPORT_SYMBOL(__frontswap_invalidate_area); static unsigned long __frontswap_curr_pages(void) { unsigned long totalpages = 0; struct swap_info_struct *si = NULL; assert_spin_locked(&swap_lock); plist_for_each_entry(si, &swap_active_head, list) totalpages += atomic_read(&si->frontswap_pages); return totalpages; } static int __frontswap_unuse_pages(unsigned long total, unsigned long *unused, int *swapid) { int ret = -EINVAL; struct swap_info_struct *si = NULL; int si_frontswap_pages; unsigned long total_pages_to_unuse = total; unsigned long pages = 0, pages_to_unuse = 0; assert_spin_locked(&swap_lock); plist_for_each_entry(si, &swap_active_head, list) { si_frontswap_pages = atomic_read(&si->frontswap_pages); if (total_pages_to_unuse < si_frontswap_pages) { pages = pages_to_unuse = total_pages_to_unuse; } else { pages = si_frontswap_pages; pages_to_unuse = 0; /* unuse all */ } /* ensure there is enough RAM to fetch pages from frontswap */ if (security_vm_enough_memory_mm(current->mm, pages)) { ret = -ENOMEM; continue; } vm_unacct_memory(pages); *unused = pages_to_unuse; *swapid = si->type; ret = 0; break; } return ret; } /* * Used to check if it's necessory and feasible to unuse pages. * Return 1 when nothing to do, 0 when need to shink pages, * error code when there is an error. */ static int __frontswap_shrink(unsigned long target_pages, unsigned long *pages_to_unuse, int *type) { unsigned long total_pages = 0, total_pages_to_unuse; assert_spin_locked(&swap_lock); total_pages = __frontswap_curr_pages(); if (total_pages <= target_pages) { /* Nothing to do */ *pages_to_unuse = 0; return 1; } total_pages_to_unuse = total_pages - target_pages; return __frontswap_unuse_pages(total_pages_to_unuse, pages_to_unuse, type); } /* * Frontswap, like a true swap device, may unnecessarily retain pages * under certain circumstances; "shrink" frontswap is essentially a * "partial swapoff" and works by calling try_to_unuse to attempt to * unuse enough frontswap pages to attempt to -- subject to memory * constraints -- reduce the number of pages in frontswap to the * number given in the parameter target_pages. */ void frontswap_shrink(unsigned long target_pages) { unsigned long pages_to_unuse = 0; int uninitialized_var(type), ret; /* * we don't want to hold swap_lock while doing a very * lengthy try_to_unuse, but swap_list may change * so restart scan from swap_active_head each time */ spin_lock(&swap_lock); ret = __frontswap_shrink(target_pages, &pages_to_unuse, &type); spin_unlock(&swap_lock); if (ret == 0) try_to_unuse(type, true, pages_to_unuse); return; } EXPORT_SYMBOL(frontswap_shrink); /* * Count and return the number of frontswap pages across all * swap devices. This is exported so that backend drivers can * determine current usage without reading debugfs. */ unsigned long frontswap_curr_pages(void) { unsigned long totalpages = 0; spin_lock(&swap_lock); totalpages = __frontswap_curr_pages(); spin_unlock(&swap_lock); return totalpages; } EXPORT_SYMBOL(frontswap_curr_pages); static int __init init_frontswap(void) { #ifdef CONFIG_DEBUG_FS struct dentry *root = debugfs_create_dir("frontswap", NULL); if (root == NULL) return -ENXIO; debugfs_create_u64("loads", 0444, root, &frontswap_loads); debugfs_create_u64("succ_stores", 0444, root, &frontswap_succ_stores); debugfs_create_u64("failed_stores", 0444, root, &frontswap_failed_stores); debugfs_create_u64("invalidates", 0444, root, &frontswap_invalidates); #endif return 0; } module_init(init_frontswap);
yassine/spring-boot-sample
src/main/java/org/github/yassine/samples/domain/repository/PersonRepository.java
package org.github.yassine.samples.domain.repository; import org.github.yassine.samples.domain.model.company.Person; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository public interface PersonRepository extends PagingAndSortingRepository<Person, Long>, DomainRepository<Person> { }
jmosro/trazactivo
src/main/java/com/ipec/trazactivo/model/ActivoObservacion.java
package com.ipec.trazactivo.model; import java.io.Serializable; import javax.persistence.*; import javax.validation.Valid; import lombok.Data; @Entity @Data @Table(name="activo_observacion") public class ActivoObservacion implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_activo_observacion") private int idActivoObservacion; @Embedded private @Valid ActivoPK activoPK; private Integer tomo; private Integer folio; private Integer asiento; // @Column(name = "id_tipo_anotacion") @JoinColumn(name="id_tipo_anotacion", referencedColumnName = "id_tipo_anotacion") @ManyToOne private TipoAnotacion tipoAnotacion; @Column(name = "otro_detalle") private String otroDetalle; @ManyToOne @JoinColumns({ @JoinColumn( name = "numero_activo", referencedColumnName = "numero_activo", insertable = false, updatable = false), @JoinColumn( name = "numero_junta", referencedColumnName = "numero_junta", insertable = false, updatable = false) }) private Activo activo; }
ratiotile/StardustDevEnvironment
3rdparty/openbw/bwapi/bwapi/BWScriptEmulator/Guard.cpp
<filename>3rdparty/openbw/bwapi/bwapi/BWScriptEmulator/Guard.cpp #include "UnitInfo.h" void UnitWrap::RunGuard() { SetOrderTimer( rand()%16 ); // 0-15 if ( GetControlType() == ControlTypes::Guard ) SetVirtualUnitOrder(Orders::Enum::GuardPost); else SetVirtualUnitOrder(Orders::Enum::ComputerAI); } void UnitWrap::RunGuardPost() { if ( GetOrderTimer() != 0 ) return; SetOrderTimer(15); if ( TaskSpellcaster(false) ) return; if ( TaskAggression() ) return; if ( pUnit->getType() == UnitTypes::Protoss_Observer ) return; if ( GetControlType() == ControlTypes::Guard && pUnit->getPosition() != GetGuardReturnPosition() ) { if ( pUnit->getType() == UnitTypes::Terran_Siege_Tank_Siege_Mode ) pUnit->unsiege(); SetVirtualUnitOrder(Orders::Enum::ComputerReturn, GetGuardReturnPosition() ); } else { SetVirtualUnitOrder(Orders::Enum::ComputerAI); } }
aaltamar12/solidus_graphql_api
lib/solidus_graphql_api/queries/product/option_types_query.rb
# frozen_string_literal: true module SolidusGraphqlApi module Queries module Product class OptionTypesQuery attr_reader :product def initialize(product:) @product = product end def call SolidusGraphqlApi::BatchLoader.for(product, :option_types) end end end end end
Nizernizer/DongTai-agent-java
iast-core/src/main/java/com/secnium/iast/core/util/LazyGet.java
package com.secnium.iast.core.util; /** * 懒加载 * * @param <T> 懒加载类型 * @author <EMAIL> * @since {@code sandbox-api:1.2.2} */ public abstract class LazyGet<T> { private volatile boolean isInit = false; private volatile T object; abstract protected T initialValue() throws Throwable; public T get() { if (isInit) { return object; } // lazy get try { object = initialValue(); isInit = true; return object; } catch (Throwable throwable) { throw new LazyGetUnCaughtException(throwable); } } private static class LazyGetUnCaughtException extends RuntimeException { LazyGetUnCaughtException(Throwable cause) { super(cause); } } }
lukewagner/wasmint
libwasmint/interpreter/heap/Heap.cpp
<reponame>lukewagner/wasmint /* * Copyright 2015 WebAssembly Community Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Heap.h" namespace wasmint { void Heap::serialize(ByteOutputStream& stream) const { stream.writeBytes(data_); } void Heap::setState(ByteInputStream& stream) { data_ = stream.getBytes(); } bool Heap::operator==(const Heap& other) const { if (other.size() != size()) return false; if (size() == 0) return true; return memcmp(other.data_.data(), data_.data(), size()) == 0; } }
shadansari/onos-cu-cp
openair2/UTIL/LFDS/liblfds7.0.0/test/src/test_lfds700_hash_addonly_random_adds_overwrite.c
/***** includes *****/ #include "internal.h" /***** structs *****/ struct test_element { struct lfds700_hash_a_element hae; lfds700_pal_uint_t key; }; struct test_state { lfds700_pal_uint_t number_elements_per_thread, overwrite_count; struct lfds700_hash_a_state *has; struct test_element *element_array; }; /***** private prototypes *****/ static test_pal_thread_return_t TEST_PAL_CALLING_CONVENTION thread_adding( void *util_thread_starter_thread_state ); static int key_compare_function( void const *new_key, void const *existing_key ); static void key_hash_function( void const *key, lfds700_pal_uint_t *hash ); static int qsort_and_bsearch_key_compare_function( void const *e1, void const *e2 ); /****************************************************************************/ void test_lfds700_hash_a_random_adds_overwrite_on_existing( struct lfds700_list_asu_state *list_of_logical_processors, lfds700_pal_uint_t memory_in_megabytes ) { enum lfds700_misc_validity dvs = LFDS700_MISC_VALIDITY_VALID; int rv; lfds700_pal_uint_t actual_sum_overwrite_existing_count, expected_sum_overwrite_existing_count, *key_count_array, loop, number_elements_per_thread, number_elements_total, number_logical_processors, random_value; struct lfds700_hash_a_iterate hai; struct lfds700_hash_a_element *hae; struct lfds700_hash_a_state has; struct lfds700_list_asu_element *lasue = NULL; struct lfds700_btree_au_state *baus; struct lfds700_misc_prng_state ps; struct lfds700_misc_validation_info vi; struct test_pal_logical_processor *lp; struct util_thread_starter_state *tts; struct test_element *element_array; struct test_state *ts; test_pal_thread_state_t *thread_handles; void *key_pointer, *key; assert( list_of_logical_processors != NULL ); // TRD : memory_in_megabytes can be any value in its range /* TRD : we create a single hash_a we generate n elements per thread each element contains a key value, which is set to a random value (we don't use value, so it's just set to 0) the threads then run, putting the threads count their number of overwrite hits once the threads are done, then we count the number of each key from this we figure out the min/max element for hash_a validation, so we call validation we check the sum of overwrites for each thread is what it should be then using the hash_a get() we check all the elements we expect are present and then we iterate over the hash_a checking we see each key once */ internal_display_test_name( "Random adds, get and iterate (overwrite on existing key)" ); lfds700_misc_prng_init( &ps ); lfds700_list_asu_query( list_of_logical_processors, LFDS700_LIST_ASU_QUERY_GET_POTENTIALLY_INACCURATE_COUNT, NULL, (void **) &number_logical_processors ); baus = util_aligned_malloc( sizeof(struct lfds700_btree_au_state) * 1000, LFDS700_PAL_ATOMIC_ISOLATION_IN_BYTES ); lfds700_hash_a_init_valid_on_current_logical_core( &has, baus, 1000, key_compare_function, key_hash_function, LFDS700_HASH_A_EXISTING_KEY_OVERWRITE, NULL ); // TRD : we divide by 2 beccause we have to allocate a second array of this size later number_elements_per_thread = ( memory_in_megabytes * ONE_MEGABYTE_IN_BYTES ) / ( sizeof(struct test_element) * number_logical_processors ) / 2; number_elements_total = number_elements_per_thread * number_logical_processors; // TRD : created an ordered list of unique numbers element_array = util_aligned_malloc( sizeof(struct test_element) * number_elements_total, LFDS700_PAL_ATOMIC_ISOLATION_IN_BYTES ); for( loop = 0 ; loop < number_elements_total ; loop++ ) { random_value = LFDS700_MISC_PRNG_GENERATE( &ps ); (element_array+loop)->key = (lfds700_pal_uint_t) floor( (number_elements_total/2) * ((double) random_value / (double) LFDS700_MISC_PRNG_MAX) ); } ts = util_malloc_wrapper( sizeof(struct test_state) * number_logical_processors ); for( loop = 0 ; loop < number_logical_processors ; loop++ ) { (ts+loop)->has = &has; (ts+loop)->element_array = element_array + number_elements_per_thread*loop; (ts+loop)->overwrite_count = 0; (ts+loop)->number_elements_per_thread = number_elements_per_thread; } thread_handles = util_malloc_wrapper( sizeof(test_pal_thread_state_t) * number_logical_processors ); util_thread_starter_new( &tts, number_logical_processors ); LFDS700_MISC_BARRIER_STORE; lfds700_misc_force_store(); loop = 0; while( LFDS700_LIST_ASU_GET_START_AND_THEN_NEXT(*list_of_logical_processors, lasue) ) { lp = LFDS700_LIST_ASU_GET_VALUE_FROM_ELEMENT( *lasue ); util_thread_starter_start( tts, &thread_handles[loop], loop, lp, thread_adding, ts+loop ); loop++; } util_thread_starter_run( tts ); for( loop = 0 ; loop < number_logical_processors ; loop++ ) test_pal_thread_wait( thread_handles[loop] ); util_thread_starter_delete( tts ); free( thread_handles ); LFDS700_MISC_BARRIER_LOAD; // TRD : now for validation key_count_array = util_malloc_wrapper( sizeof(lfds700_pal_uint_t) * number_elements_total ); for( loop = 0 ; loop < number_elements_total ; loop++ ) *(key_count_array+loop) = 0; for( loop = 0 ; loop < number_elements_total ; loop++ ) ( *(key_count_array + (element_array+loop)->key) )++; vi.min_elements = number_elements_total; for( loop = 0 ; loop < number_elements_total ; loop++ ) if( *(key_count_array+loop) == 0 ) vi.min_elements--; vi.max_elements = vi.min_elements; lfds700_hash_a_query( &has, LFDS700_HASH_A_QUERY_SINGLETHREADED_VALIDATE, (void *) &vi, (void *) &dvs ); expected_sum_overwrite_existing_count = 0; for( loop = 0 ; loop < number_elements_total ; loop++ ) if( *(key_count_array+loop) != 0 ) expected_sum_overwrite_existing_count += *(key_count_array+loop) - 1; actual_sum_overwrite_existing_count = 0; for( loop = 0 ; loop < number_logical_processors ; loop++ ) actual_sum_overwrite_existing_count += (ts+loop)->overwrite_count; if( expected_sum_overwrite_existing_count != actual_sum_overwrite_existing_count ) dvs = LFDS700_MISC_VALIDITY_INVALID_TEST_DATA; // TRD : now loop over the expected array and check we can get() every element for( loop = 0 ; loop < number_elements_total ; loop++ ) if( *(key_count_array+loop) > 0 ) { rv = lfds700_hash_a_get_by_key( &has, (void *) loop, &hae ); if( rv != 1 ) dvs = LFDS700_MISC_VALIDITY_INVALID_TEST_DATA; } /* TRD : now iterate, checking we find every element and no others to do this in a timely manner, we need to qsort() the key values and use bsearch() to check for items in the array */ for( loop = 0 ; loop < number_elements_total ; loop++ ) if( *(key_count_array+loop) != 0 ) *(key_count_array+loop) = loop; else *(key_count_array+loop) = 0; qsort( key_count_array, number_elements_total, sizeof(lfds700_pal_uint_t), qsort_and_bsearch_key_compare_function ); lfds700_hash_a_iterate_init( &has, &hai ); while( dvs == LFDS700_MISC_VALIDITY_VALID and lfds700_hash_a_iterate(&hai, &hae) ) { key = LFDS700_HASH_A_GET_KEY_FROM_ELEMENT( *hae ); key_pointer = bsearch( &key, key_count_array, number_elements_total, sizeof(lfds700_pal_uint_t), qsort_and_bsearch_key_compare_function ); if( key_pointer == NULL ) dvs = LFDS700_MISC_VALIDITY_INVALID_TEST_DATA; } // TRD : cleanup lfds700_hash_a_cleanup( &has, NULL ); util_aligned_free( baus ); free( ts ); util_aligned_free( element_array ); free( key_count_array ); // TRD : print the test result internal_display_test_result( 1, "hash_a", dvs ); return; } /****************************************************************************/ static test_pal_thread_return_t TEST_PAL_CALLING_CONVENTION thread_adding( void *util_thread_starter_thread_state ) { enum lfds700_hash_a_insert_result apr; lfds700_pal_uint_t index = 0; struct test_state *ts; struct lfds700_misc_prng_state ps; struct util_thread_starter_thread_state *tsts; LFDS700_MISC_MAKE_VALID_ON_CURRENT_LOGICAL_CORE_INITS_COMPLETED_BEFORE_NOW_ON_ANY_OTHER_LOGICAL_CORE; assert( util_thread_starter_thread_state != NULL ); tsts = (struct util_thread_starter_thread_state *) util_thread_starter_thread_state; ts = (struct test_state *) tsts->thread_user_state; lfds700_misc_prng_init( &ps ); util_thread_starter_ready_and_wait( tsts ); while( index < ts->number_elements_per_thread ) { LFDS700_HASH_A_SET_KEY_IN_ELEMENT( (ts->element_array+index)->hae, (ts->element_array+index)->key ); LFDS700_HASH_A_SET_VALUE_IN_ELEMENT( (ts->element_array+index)->hae, 0 ); apr = lfds700_hash_a_insert( ts->has, &(ts->element_array+index)->hae, NULL, &ps ); if( apr == LFDS700_HASH_A_PUT_RESULT_SUCCESS_OVERWRITE ) ts->overwrite_count++; index++; } LFDS700_MISC_BARRIER_STORE; lfds700_misc_force_store(); return( (test_pal_thread_return_t) EXIT_SUCCESS ); } /****************************************************************************/ #pragma warning( disable : 4100 ) static int key_compare_function( void const *new_key, void const *existing_key ) { int cr = 0; // TRD : new_key can be NULL (i.e. 0) // TRD : existing_key can be NULL (i.e. 0) if( (lfds700_pal_uint_t) new_key < (lfds700_pal_uint_t) existing_key ) cr = -1; if( (lfds700_pal_uint_t) new_key > (lfds700_pal_uint_t) existing_key ) cr = 1; return( cr ); } #pragma warning( default : 4100 ) /****************************************************************************/ #pragma warning( disable : 4100 ) static void key_hash_function( void const *key, lfds700_pal_uint_t *hash ) { // TRD : key can be NULL assert( hash != NULL ); *hash = 0; /* TRD : this function iterates over the user data and we are using the void pointer *as* key data so here we need to pass in the addy of key */ LFDS700_HASH_A_32BIT_HASH_FUNCTION( (void *) &key, sizeof(lfds700_pal_uint_t), *hash ); return; } #pragma warning( default : 4100 ) /****************************************************************************/ static int qsort_and_bsearch_key_compare_function( void const *e1, void const *e2 ) { int cr = 0; lfds700_pal_uint_t s1, s2; s1 = *(lfds700_pal_uint_t *) e1; s2 = *(lfds700_pal_uint_t *) e2; if( s1 > s2 ) cr = 1; if( s1 < s2 ) cr = -1; return( cr ); }
mcodegeeks/OpenKODE-Framework
03_Tutorial/T07_XMOgre3D/Source/Sample/Fresnel.cpp
/* ------------------------------------------------------------------------------------ * * File Fresnel.cpp * Description This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * Author <NAME> * * ------------------------------------------------------------------------------------ * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * Contact Email: <EMAIL> * * ------------------------------------------------------------------------------------ * * Copyright (c) 2010-2012 Torus Knot Software Ltd. * * For the latest info, see http://www.ogre3d.org/ * * ------------------------------------------------------------------------------------ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ------------------------------------------------------------------------------------ */ #include "Precompiled.h" #include "Fresnel.h" Sample_Fresnel::Sample_Fresnel ( KDvoid ) : NUM_FISH ( 30 ) , NUM_FISH_WAYPOINTS ( 10 ) , FISH_PATH_LENGTH ( 200 ) , FISH_SCALE ( 2 ) { m_aInfo [ "Title" ] = "Fresnel"; m_aInfo [ "Description" ] = "Shows how to create reflections and refractions using render-to-texture and shaders."; m_aInfo [ "Thumbnail" ] = "thumb_fresnel.png"; m_aInfo [ "Category" ] = "Unsorted"; } StringVector Sample_Fresnel::getRequiredPlugins ( KDvoid ) { StringVector aNames; if ( !GpuProgramManager::getSingleton ( ).isSyntaxSupported ( "glsles" ) ) { aNames.push_back("Cg Program Manager"); } return aNames; } KDvoid Sample_Fresnel::testCapabilities ( const RenderSystemCapabilities* pCaps ) { if ( !pCaps->hasCapability ( RSC_VERTEX_PROGRAM ) || !pCaps->hasCapability ( RSC_FRAGMENT_PROGRAM ) ) { OGRE_EXCEPT ( Exception::ERR_NOT_IMPLEMENTED, "Your graphics card does not support vertex and fragment" " programs, so you cannot run this sample. Sorry!", "FresnelSample::testCapabilities" ); } if ( !GpuProgramManager::getSingleton ( ).isSyntaxSupported ( "arbfp1" ) && !GpuProgramManager::getSingleton ( ).isSyntaxSupported ( "ps_4_0" ) && !GpuProgramManager::getSingleton ( ).isSyntaxSupported ( "ps_2_0" ) && !GpuProgramManager::getSingleton ( ).isSyntaxSupported ( "ps_1_4" ) && !GpuProgramManager::getSingleton ( ).isSyntaxSupported ( "glsles" ) ) { OGRE_EXCEPT ( Exception::ERR_NOT_IMPLEMENTED, "Your graphics card does not support advanced fragment" " programs, so you cannot run this sample. Sorry!", "FresnelSample::testCapabilities" ); } } bool Sample_Fresnel::frameRenderingQueued ( const FrameEvent& tEvent ) { // update the fish spline path animations and loop as needed m_fFishAnimTime += tEvent.timeSinceLastFrame; while ( m_fFishAnimTime >= FISH_PATH_LENGTH ) { m_fFishAnimTime -= FISH_PATH_LENGTH; } for ( KDuint i = 0; i < NUM_FISH; i++ ) { m_aFishAnimStates[i]->addTime ( tEvent.timeSinceLastFrame * 2 ); // update fish swim animation // set the new position based on the spline path and set the direction based on displacement Vector3 tLastPos = m_aFishNodes[i]->getPosition ( ); m_aFishNodes[i]->setPosition ( m_aFishSplines[i].interpolate ( m_fFishAnimTime / FISH_PATH_LENGTH ) ); m_aFishNodes[i]->setDirection ( m_aFishNodes[i]->getPosition ( ) - tLastPos, Node::TS_PARENT, Vector3::NEGATIVE_UNIT_X ); m_aFishNodes[i]->setFixedYawAxis(true); } return SdkSample::frameRenderingQueued ( tEvent ); } KDvoid Sample_Fresnel::preRenderTargetUpdate ( const RenderTargetEvent& tEvent ) { m_pWater->setVisible ( false ); // hide the water if ( tEvent.source == m_pReflectionTarget) // for reflection, turn on camera reflection and hide submerged entities { m_pCamera->enableReflection ( m_tWaterPlane ); for ( std::vector<Entity*>::iterator it = m_aSubmergedEnts.begin ( ); it != m_aSubmergedEnts.end ( ); it++ ) { ( *it )->setVisible ( false ); } } else // for refraction, hide surface entities { for ( std::vector<Entity*>::iterator it = m_aSurfaceEnts.begin ( ); it != m_aSurfaceEnts.end ( ); it++ ) { ( *it )->setVisible ( false ); } } } KDvoid Sample_Fresnel::postRenderTargetUpdate ( const RenderTargetEvent& tEvent ) { m_pWater->setVisible ( true ); // unhide the water if ( tEvent.source == m_pReflectionTarget) // for reflection, turn off camera reflection and hide submerged entities { m_pCamera->disableReflection ( ); for ( std::vector<Entity*>::iterator it = m_aSubmergedEnts.begin ( ); it != m_aSubmergedEnts.end ( ); it++ ) { ( *it )->setVisible ( true ); } } else // for refraction, hide surface entities { for ( std::vector<Entity*>::iterator it = m_aSurfaceEnts.begin ( ); it != m_aSurfaceEnts.end ( ); it++ ) { ( *it )->setVisible ( true ); } } } KDvoid Sample_Fresnel::setupContent ( KDvoid ) { m_pCamera->setPosition ( -50, 125, 760 ); m_pCameraMan->setTopSpeed ( 280 ); m_pSceneMgr->setAmbientLight ( ColourValue ( 0.5, 0.5, 0.5 ) ); // set ambient light m_pSceneMgr->setSkyBox ( true, "Examples/CloudyNoonSkyBox" ); // set a skybox // make the scene's main light come from above Light* pLight = m_pSceneMgr->createLight ( ); pLight->setType ( Light::LT_DIRECTIONAL ); pLight->setDirection ( Vector3::NEGATIVE_UNIT_Y ); setupWater ( ); setupProps ( ); setupFish ( ); } KDvoid Sample_Fresnel::setupWater ( KDvoid ) { // create our reflection & refraction render textures, and setup their render targets for ( KDuint i = 0; i < 2; i++ ) { TexturePtr pTex = TextureManager::getSingleton ( ).createManual ( i == 0 ? "refraction" : "reflection", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET ); RenderTarget* pRtt = pTex->getBuffer ( )->getRenderTarget ( ); pRtt->addViewport ( m_pCamera )->setOverlaysEnabled ( false ); pRtt->addListener ( this ); if ( i == 0 ) { m_pRefractionTarget = pRtt; } else { m_pReflectionTarget = pRtt; } } // create our water plane mesh m_tWaterPlane = Plane ( Vector3::UNIT_Y, 0 ); MeshManager::getSingleton ( ).createPlane ( "water", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, m_tWaterPlane, 700, 1300, 10, 10, true, 1, 3, 5, Vector3::UNIT_Z ); // create a water entity using our mesh, give it the shader material, and attach it to the origin m_pWater = m_pSceneMgr->createEntity ( "Water", "water" ); m_pWater->setMaterialName ( "Examples/FresnelReflectionRefraction" ); m_pSceneMgr->getRootSceneNode ( )->attachObject ( m_pWater ); } KDvoid Sample_Fresnel::setupProps ( KDvoid ) { Entity* pEntity; // setting up props might take a while, so create a progress bar for visual feedback ProgressBar* pProgress = m_pTrayMgr->createProgressBar ( TL_CENTER, "FresnelBuildingBar", "Creating Props...", 280, 100 ); m_pTrayMgr->showBackdrop ( "SdkTrays/Shade" ); pProgress->setComment ( "Upper Bath" ); pEntity = m_pSceneMgr->createEntity ( "UpperBath", "RomanBathUpper.mesh" ); m_pSceneMgr->getRootSceneNode()->attachObject ( pEntity ); m_aSurfaceEnts.push_back ( pEntity ); pProgress->setProgress ( 0.4 ); pProgress->setComment("Columns"); pEntity = m_pSceneMgr->createEntity ( "Columns", "columns.mesh" ); m_pSceneMgr->getRootSceneNode ( )->attachObject ( pEntity ); m_aSurfaceEnts.push_back ( pEntity ); pProgress->setProgress ( 0.5 ); pProgress->setComment ( "Ogre Head" ); pEntity = m_pSceneMgr->createEntity ( "Head", "ogrehead.mesh" ); pEntity->setMaterialName ( "RomanBath/OgreStone" ); m_aSurfaceEnts.push_back ( pEntity ); pProgress->setProgress ( 0.6 ); SceneNode* pHeadNode = m_pSceneMgr->getRootSceneNode ( )->createChildSceneNode ( ); pHeadNode->setPosition ( -350, 55, 130 ); pHeadNode->yaw ( Degree ( 90 ) ); pHeadNode->attachObject ( pEntity ); pProgress->setComment ( "Lower Bath" ); pEntity = m_pSceneMgr->createEntity ( "LowerBath", "RomanBathLower.mesh" ); m_pSceneMgr->getRootSceneNode ( )->attachObject ( pEntity ); m_aSubmergedEnts.push_back( pEntity ); pProgress->setProgress ( 1 ); m_pTrayMgr->destroyWidget ( pProgress ); m_pTrayMgr->hideBackdrop ( ); } KDvoid Sample_Fresnel::setupFish ( KDvoid ) { m_aFishNodes .resize ( NUM_FISH ); m_aFishAnimStates.resize ( NUM_FISH ); m_aFishSplines .resize ( NUM_FISH ); for ( KDuint i = 0; i < NUM_FISH; i++ ) { // create fish entity Entity* pEntity = m_pSceneMgr->createEntity ( "Fish" + StringConverter::toString ( i + 1 ), "fish.mesh" ); m_aSubmergedEnts.push_back ( pEntity ); // create an appropriately scaled node and attach the entity m_aFishNodes[i] = m_pSceneMgr->getRootSceneNode ( )->createChildSceneNode ( ); m_aFishNodes[i]->setScale ( Vector3::UNIT_SCALE * FISH_SCALE ); m_aFishNodes[i]->attachObject ( pEntity ); // enable and save the swim animation state m_aFishAnimStates[i] = pEntity->getAnimationState ( "swim" ); m_aFishAnimStates[i]->setEnabled ( true ); m_aFishSplines[i].setAutoCalculate ( false ); // save the tangent calculation for when we are all done // generate random waypoints for the fish to swim through for ( KDuint j = 0; j < NUM_FISH_WAYPOINTS; j++ ) { Vector3 tPos ( Math::SymmetricRandom ( ) * 270, -10, Math::SymmetricRandom ( ) * 700 ); if ( j > 0 ) // make sure the waypoint isn't too far from the last, or our fish will be turbo-fish { const Vector3& tLastPos = m_aFishSplines[i].getPoint ( j - 1 ); Vector3 tDelta = tPos - tLastPos; if ( tDelta.length ( ) > 750) { tPos = tLastPos + tDelta.normalisedCopy ( ) * 750; } } m_aFishSplines[i].addPoint ( tPos ); } // close the spline and calculate all the tangents at once m_aFishSplines[i].addPoint ( m_aFishSplines[i].getPoint ( 0 ) ); m_aFishSplines[i].recalcTangents ( ); } m_fFishAnimTime = 0; } KDvoid Sample_Fresnel::cleanupContent ( KDvoid ) { m_aSurfaceEnts .clear ( ); m_aSubmergedEnts .clear ( ); m_aFishNodes .clear ( ); m_aFishAnimStates.clear ( ); m_aFishSplines .clear ( ); MeshManager::getSingleton ( ).remove ( "water" ); TextureManager::getSingleton ( ).remove ( "refraction" ); TextureManager::getSingleton ( ).remove ( "reflection" ); }
Uniandes-isis2603/s3_Animaciones_201910
s3_animaciones-back/src/main/java/co/edu/uniandes/csw/animaciones/ejb/ConcursoJuradoLogic.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.animaciones.ejb; import co.edu.uniandes.csw.animaciones.entities.ConcursoEntity; import co.edu.uniandes.csw.animaciones.entities.JuradoEntity; import co.edu.uniandes.csw.animaciones.persistence.ConcursoPersistence; import co.edu.uniandes.csw.animaciones.persistence.JuradoPersistence; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; /** * * @author df.perezc */ @Stateless public class ConcursoJuradoLogic { @Inject private ConcursoPersistence cp; @Inject private JuradoPersistence jp; public JuradoEntity addJurado(Long concursoId, Long juradoId) { ConcursoEntity ce = cp.find(concursoId); JuradoEntity je = jp.find(juradoId); ce.getJurados().add(je); return je; } public List<JuradoEntity> getJurados(Long concursoId) { return cp.find(concursoId).getJurados(); } public JuradoEntity getJurado(Long concursoId, Long juradoId) { List<JuradoEntity> list = getJurados(concursoId); JuradoEntity je = jp.find(juradoId); int i = list.indexOf(je); if(i >= 0){ return list.get(i); } return null; } }
UBICUA-JSSI/ssido.server
ssido.core/src/main/java/ssido/core/data/AuthenticatorSelectionCriteria.java
// Copyright (c) 2018, Yubico AB // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package ssido.core.data; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Optional; import javax.annotation.Nonnull; /** * This class may be used to specify requirements regarding authenticator attributes. * * @see <a href="https://www.w3.org/TR/webauthn/#dictdef-authenticatorselectioncriteria">§5.4.4. * Authenticator Selection Criteria (dictionary AuthenticatorSelectionCriteria) * </a> */ public final class AuthenticatorSelectionCriteria { /** * If present, eligible authenticators are filtered to only authenticators attached with the specified <a * href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration * (enum AuthenticatorAttachment)</a>. */ @Nonnull private final Optional<AuthenticatorAttachment> authenticatorAttachment; /** * Describes the Relying Party's requirements regarding resident credentials. If set to <code>true</code>, the * authenticator MUST create a <a href="https://www.w3.org/TR/webauthn/#client-side-resident-public-key-credential-source">client-side-resident * public key credential source</a> when creating a public key credential. */ private final boolean requireResidentKey; /** * Describes the Relying Party's requirements regarding <a href="https://www.w3.org/TR/webauthn/#user-verification">user * verification</a> for the * <code>navigator.credentials.create()</code> operation. Eligible authenticators are filtered to only those * capable of satisfying this requirement. */ @Nonnull private final UserVerificationRequirement userVerification; @JsonCreator private AuthenticatorSelectionCriteria(@JsonProperty("authenticatorAttachment") AuthenticatorAttachment authenticatorAttachment, @JsonProperty("requireResidentKey") boolean requireResidentKey, @Nonnull @JsonProperty("userVerification") UserVerificationRequirement userVerification) { this(Optional.ofNullable(authenticatorAttachment), requireResidentKey, userVerification); } public static class AuthenticatorSelectionCriteriaBuilder { private boolean requireResidentKey = false; private UserVerificationRequirement userVerification = UserVerificationRequirement.PREFERRED; @Nonnull private Optional<AuthenticatorAttachment> authenticatorAttachment = Optional.empty(); /** * If present, eligible authenticators are filtered to only authenticators attached with the specified <a * href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration * (enum AuthenticatorAttachment)</a>. * @param authenticatorAttachment * @return */ public AuthenticatorSelectionCriteriaBuilder authenticatorAttachment(@Nonnull Optional<AuthenticatorAttachment> authenticatorAttachment) { this.authenticatorAttachment = authenticatorAttachment; return this; } /** * If present, eligible authenticators are filtered to only authenticators attached with the specified <a * href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration * (enum AuthenticatorAttachment)</a>. * @param authenticatorAttachment * @return */ public AuthenticatorSelectionCriteriaBuilder authenticatorAttachment(@Nonnull AuthenticatorAttachment authenticatorAttachment) { return this.authenticatorAttachment(Optional.of(authenticatorAttachment)); } AuthenticatorSelectionCriteriaBuilder() { } /** * Describes the Relying Party's requirements regarding resident credentials. If set to <code>true</code>, the * authenticator MUST create a <a href="https://www.w3.org/TR/webauthn/#client-side-resident-public-key-credential-source">client-side-resident * public key credential source</a> when creating a public key credential. * @param requireResidentKey * @return */ public AuthenticatorSelectionCriteriaBuilder requireResidentKey(final boolean requireResidentKey) { this.requireResidentKey = requireResidentKey; return this; } /** * Describes the Relying Party's requirements regarding <a href="https://www.w3.org/TR/webauthn/#user-verification">user * verification</a> for the * <code>navigator.credentials.create()</code> operation. Eligible authenticators are filtered to only those * capable of satisfying this requirement. * @param userVerification * @return */ public AuthenticatorSelectionCriteriaBuilder userVerification(@Nonnull final UserVerificationRequirement userVerification) { this.userVerification = userVerification; return this; } public AuthenticatorSelectionCriteria build() { return new AuthenticatorSelectionCriteria(authenticatorAttachment, requireResidentKey, userVerification); } } public static AuthenticatorSelectionCriteriaBuilder builder() { return new AuthenticatorSelectionCriteriaBuilder(); } public AuthenticatorSelectionCriteriaBuilder toBuilder() { return new AuthenticatorSelectionCriteriaBuilder().authenticatorAttachment(this.authenticatorAttachment).requireResidentKey(this.requireResidentKey).userVerification(this.userVerification); } /** * If present, eligible authenticators are filtered to only authenticators attached with the specified <a * href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration * (enum AuthenticatorAttachment)</a>. * @return */ @Nonnull public Optional<AuthenticatorAttachment> getAuthenticatorAttachment() { return this.authenticatorAttachment; } /** * Describes the Relying Party's requirements regarding resident credentials. If set to <code>true</code>, the * authenticator MUST create a <a href="https://www.w3.org/TR/webauthn/#client-side-resident-public-key-credential-source">client-side-resident * public key credential source</a> when creating a public key credential. * @return */ public boolean isRequireResidentKey() { return this.requireResidentKey; } /** * Describes the Relying Party's requirements regarding <a href="https://www.w3.org/TR/webauthn/#user-verification">user * verification</a> for the * <code>navigator.credentials.create()</code> operation. Eligible authenticators are filtered to only those * capable of satisfying this requirement. * @return */ @Nonnull public UserVerificationRequirement getUserVerification() { return this.userVerification; } private AuthenticatorSelectionCriteria(@Nonnull final Optional<AuthenticatorAttachment> authenticatorAttachment, final boolean requireResidentKey, @Nonnull final UserVerificationRequirement userVerification) { this.authenticatorAttachment = authenticatorAttachment; this.requireResidentKey = requireResidentKey; this.userVerification = userVerification; } }
kurylo/openvino
src/common/transformations/src/transformations/op_conversions/softplus_decomposition.cpp
<reponame>kurylo/openvino // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/op_conversions/softplus_decomposition.hpp" #include <memory> #include <ngraph/opsets/opset4.hpp> #include <ngraph/pattern/op/wrap_type.hpp> #include <ngraph/rt_info.hpp> #include <vector> #include "itt.hpp" ngraph::pass::SoftPlusDecomposition::SoftPlusDecomposition() { MATCHER_SCOPE(SoftPlusDecomposition); // decomposes SoftPlus(x) operation into ln(exp(x) + 1.0) auto input = ngraph::pattern::any_input(); auto softplus = std::make_shared<ngraph::opset4::SoftPlus>(input); ngraph::matcher_pass_callback callback = [=](ngraph::pattern::Matcher& m) { auto& pattern_to_output = m.get_pattern_value_map(); auto softplus_input = pattern_to_output.at(input); auto softplus_node = pattern_to_output.at(softplus).get_node_shared_ptr(); if (transformation_callback(softplus_node)) { return false; } auto exp = std::make_shared<ngraph::opset4::Exp>(softplus_input); auto add = std::make_shared<ngraph::opset4::Add>( exp, opset4::Constant::create(softplus_input.get_element_type(), ngraph::Shape{1}, {1.0})); auto log = std::make_shared<ngraph::opset4::Log>(add); log->set_friendly_name(softplus_node->get_friendly_name()); ngraph::copy_runtime_info(softplus_node, {exp, add, log}); ngraph::replace_node(softplus_node, log); return true; }; auto m = std::make_shared<ngraph::pattern::Matcher>(softplus, matcher_name); register_matcher(m, callback); }
alv1n/pws
include/uspienv/logger.h
// // logger.h // // USPi - An USB driver for Raspberry Pi written in C // Copyright (C) 2014 <NAME> <<EMAIL>> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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/>. // #ifndef _uspienv_logger_h #define _uspienv_logger_h #include <uspienv/screen.h> #include <uspienv/timer.h> #include <uspienv/stdarg.h> #include <uspienv/types.h> #ifdef __cplusplus extern "C" { #endif typedef enum TLogSeverity { LogPanic, LogError, LogWarning, LogNotice, LogDebug } TLogSeverity; typedef struct TLogger { unsigned m_nLogLevel; TTimer *m_pTimer; TScreenDevice *m_pTarget; } TLogger; void Logger (TLogger *pThis, unsigned nLogLevel, TTimer *pTimer /* = 0 */); // time is not logged if pTimer is 0 void _Logger (TLogger *pThis); boolean LoggerInitialize (TLogger *pThis, TScreenDevice *pTarget); void LoggerWrite (TLogger *pThis, const char *pSource, TLogSeverity Severity, const char *pMessage, ...); void LoggerWriteV (TLogger *pThis, const char *pSource, TLogSeverity Severity, const char *pMessage, va_list Args); TLogger *LoggerGet (void); #ifdef __cplusplus } #endif #endif
novadwisaptanainseven/e-pekerja
src/views/pages/Admin/Mutasi/EditMutasi.js
import { CCard, CCardHeader, CButton, CInput, CLabel, CCol, CCardFooter, CFormGroup, CCardBody, CForm, } from "@coreui/react"; import React, { useState, useEffect } from "react"; import { useHistory } from "react-router-dom"; import LoadingSubmit from "src/reusable/LoadingSubmit"; import * as Yup from "yup"; import { Formik } from "formik"; import swal2 from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { getMutasiById } from "src/context/actions/Mutasi/getMutasiById"; import { editMutasi } from "src/context/actions/Mutasi/editMutasi"; import Loading from "src/reusable/Loading"; const MySwal = withReactContent(swal2); const EditMutasi = ({ match }) => { const params = match.params; const history = useHistory(); const [loading, setLoading] = useState(false); const [mutasi, setMutasi] = useState(""); const goBackToParent = () => { history.goBack(); }; // Get mutasi by id useEffect(() => { getMutasiById(params.id, setMutasi); }, [params]); // Inisialisasi state formik const initState = { id_pegawai: mutasi ? mutasi.id_pegawai : "", tgl_mutasi: mutasi ? mutasi.tgl_mutasi : "", keterangan: mutasi ? mutasi.keterangan : "", }; // Fungsi untuk menampilkan alert success tambah data const showAlertSuccess = () => { MySwal.fire({ icon: "success", title: "Edit Mutasi Berhasil", showConfirmButton: false, timer: 1500, }).then((res) => { history.push("/epekerja/admin/mutasi"); }); }; // Fungsi untuk menampilkan alert error tambah data const showAlertError = (message) => { let err_message = ""; for (const key in message) { err_message += `${message[key]}, `; } MySwal.fire({ icon: "error", title: "Edit Mutasi Gagal", text: err_message, }).then((result) => { setLoading(false); }); }; // Setting validasi form menggunakan YUP & FORMIK const validationSchema = Yup.object().shape({ id_pegawai: Yup.string().required("Pegawai harus diisi"), tgl_mutasi: Yup.string().required("Tanggal mutasi harus diisi"), keterangan: Yup.string().required("Keterangan / alasan mutasi harus diisi"), }); // Menangani value dari form submit const handleFormSubmit = (values) => { editMutasi(params.id, values, setLoading, showAlertSuccess, showAlertError); }; return ( <CCard> <CCardHeader className="d-flex justify-content-between"> <h3>Edit Data Mutasi</h3> <CButton type="button" color="warning" className="text-white" onClick={goBackToParent} > Kembali </CButton> </CCardHeader> {!mutasi ? ( <Loading /> ) : ( <Formik initialValues={initState} enableReinitialize={true} validationSchema={validationSchema} onSubmit={handleFormSubmit} > {({ values, errors, touched, handleChange, handleBlur, handleSubmit, }) => ( <CForm onSubmit={handleSubmit}> <CCardBody> <CFormGroup row> <CCol md="2"> <CLabel>Nama Pegawai</CLabel> </CCol> <CCol> <CInput type="text" name="nama" value={mutasi.nama} readOnly /> </CCol> </CFormGroup> <CFormGroup row> <CCol md="2"> <CLabel>Tgl. Mutasi</CLabel> </CCol> <CCol> <CInput type="date" name="tgl_mutasi" id="tgl_mutasi" onChange={handleChange} onBlur={handleBlur} value={values.tgl_mutasi || ""} placeholder="Masukkan tgl. mutasi" className={ errors.tgl_mutasi && touched.tgl_mutasi ? "is-invalid" : null } /> {errors.tgl_mutasi && touched.tgl_mutasi && ( <div className="invalid-feedback"> {errors.tgl_mutasi} </div> )} </CCol> </CFormGroup> <CFormGroup row> <CCol md="2"> <CLabel>Keterangan</CLabel> </CCol> <CCol> <CInput type="text" name="keterangan" id="keterangan" onChange={handleChange} onBlur={handleBlur} value={values.keterangan || ""} placeholder="Masukkan keterangan / alasan mutasi" className={ errors.keterangan && touched.keterangan ? "is-invalid" : null } /> {errors.keterangan && touched.keterangan && ( <div className="invalid-feedback"> {errors.keterangan} </div> )} </CCol> </CFormGroup> </CCardBody> <CCardFooter> <CButton color="primary" type="submit" className="mr-1" disabled={loading ? true : false} > {loading ? <LoadingSubmit /> : "Simpan"} </CButton> </CCardFooter> </CForm> )} </Formik> )} </CCard> ); }; export default EditMutasi;
vinjatovix/booking-flights-app
front/src/components/SearchFlight/ResponseHeader/filters.js
<reponame>vinjatovix/booking-flights-app<filename>front/src/components/SearchFlight/ResponseHeader/filters.js const formatDuration = (string) => { return +string.replace(/PT(\d+)H(\d+)M/, "$1.$2"); }; export const byPrice = (a, b) => +a.price.grandTotal < +b.price.grandTotal ? 1 : -1; export const byStops = (a, b) => { return a.itineraries[0].segments.length > b.itineraries[0].segments.length ? -1 : 1; }; export const byDuration = (a, b) => { const durA = formatDuration(a.itineraries[0].duration); const durB = formatDuration(b.itineraries[0].duration); return +durA - +durB; };
bpbpublications/Advance-Core-Python-Programming
Chapter 02/descriptiveQA.py
#1 class classLevel: def class1(self,string_a): print(string_a) def class2(self): print('There are 15 students in this class') cl = classLevel("Hello") cl.class1() cl.class2() ####################################### class Foo: @staticmethod def bar(): print('Static method bar()') @staticmethod def stat(): print("Static method stat()") def class1(self,string_a): print(string_a) # Calling static method bar() Foo.bar() # Calling static method stat() Foo.stat() #calling bounded method class1() f = Foo() f.class1('bounded method') ######################################33 #2 class Bank: def __init__(self, name, balance): self.name = name self.balance = balance b1 = Bank('customer1','10000') b2 = Bank('friend','10000') #print values of b1 and b2 print(b1) print(b2) #print values of b1 and b2 b1+b2 #################################3 class Bank: def __init__(self, name, balance): self.name = name self.balance = balance def __str__(self): str1 = 'name: '+self.name+' balance: '+self.balance+'.' return str1 def __add__(self, other): balance = int(self.balance) + int(other.balance) return balance b1 = Bank('customer1','10000') b2 = Bank('friend','10000') #print values of b1 and b2 print(b1) print(b2) #print values of b1 and b2 print(b1 + b2)
h1st-ai/h1st-contrib
h1st_contrib/iot_mgmt/maint_ops/migrations/0020_auto_20180420_1922.py
<reponame>h1st-ai/h1st-contrib # -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-04-21 02:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('IoT_DataMgmt', '0006_auto_20180410_1904'), ('IoT_MaintOps', '0019_auto_20180420_1522'), ] operations = [ migrations.CreateModel( name='EquipmentInstanceProblemDiagnosis', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('from_date', models.DateField(default=None)), ('to_date', models.DateField(default=None)), ('equipment_instance', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='equipment_problem_instances', related_query_name='equipment_problem_instance', to='IoT_DataMgmt.EquipmentInstance')), ], ), migrations.CreateModel( name='EquipmentProblemType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ], options={ 'ordering': ('name',), }, ), migrations.AddField( model_name='equipmentinstanceproblemdiagnosis', name='equipment_problem_types', field=models.ManyToManyField(blank=True, related_name='equipment_problem_instances', related_query_name='equipment_problem_instance', to='IoT_MaintOps.EquipmentProblemType'), ), ]
raybdzhou/PyChip-py-hcl
example/Blackbox.py
from pyhcl import * class BBox(BlackBox): io = IO( in1=Input(U.w(64)), in2=Input(U.w(64)), out=Output(U.w(64)), ) class M(Module): io = IO( i = Input(U.w(64)), o = Output(U.w(64)), ) bbox = BBox() bbox.io.in1 <<= io.i bbox.io.in2 <<= io.i io.o <<= bbox.io.out if __name__ == '__main__': Emitter.dumpVerilog(Emitter.dump(Emitter.emit(M()), "bbox.fir"))
onmyway133/Runtime-Headers
macOS/10.13/Foundation.framework/NSRangeSpecifier.h
<reponame>onmyway133/Runtime-Headers<gh_stars>10-100 /* Generated by RuntimeBrowser Image: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation */ @interface NSRangeSpecifier : NSScriptObjectSpecifier { NSScriptObjectSpecifier * _endSpec; NSScriptObjectSpecifier * _startSpec; } @property (atomic, readwrite, retain) NSScriptObjectSpecifier *endSpecifier; @property (atomic, readwrite, retain) NSScriptObjectSpecifier *startSpecifier; - (id)_initFromRecord:(id)arg1; - (BOOL)_putKeyFormAndDataInRecord:(id)arg1; - (id)_simpleDescription; - (id)_specifiedIndexesOfObjectsInContainer:(id)arg1; - (BOOL)_specifiesSingleIndexedObjectPerContainer; - (void)dealloc; - (void)encodeWithCoder:(id)arg1; - (id)endSpecifier; - (id)initWithCoder:(id)arg1; - (id)initWithContainerClassDescription:(id)arg1 containerSpecifier:(id)arg2 key:(id)arg3; - (id)initWithContainerClassDescription:(id)arg1 containerSpecifier:(id)arg2 key:(id)arg3 startSpecifier:(id)arg4 endSpecifier:(id)arg5; - (void)setEndSpecifier:(id)arg1; - (void)setStartSpecifier:(id)arg1; - (id)startSpecifier; @end
imuntil/React
utils/back-after-blur.js
<gh_stars>0 let flag; let timer; const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); let pos = { top: 0, left: 0 }; let scrollingElementName = ''; const reports = () => { if (scrollingElementName) { const { scrollLeft, scrollTop } = document[scrollingElementName]; pos = { top: scrollTop, left: scrollLeft }; return; } scrollingElementName = ['scrollingElement', 'documentElement', 'body'].find(name => { const { scrollTop, scrollLeft } = document[name]; if (scrollLeft || scrollTop) { pos = { top: scrollTop, left: scrollLeft }; return true; } return false; }); }; if (isIOS) { document.body.addEventListener('focusin', e => { if (e.target.getAttribute('bab') !== 'true') return; reports(); flag = true; clearTimeout(timer); }); document.body.addEventListener('focusout', e => { if (e.target.getAttribute('bab') !== 'true') return; flag = false; if (!flag) { timer = setTimeout(() => { // 当键盘收起的时候让页面回到原始位置 window.scrollTo({ ...pos, behavior: 'smooth' }); pos = { top: 0, left: 0 }; }, 100); } }); }
tmexcept/android-lite-http
litehttp/src/main/java/com/litesuits/http/annotation/HttpCacheMode.java
package com.litesuits.http.annotation; import com.litesuits.http.request.param.CacheMode; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author MaTianyu * @date 2015-04-26 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface HttpCacheMode { CacheMode value(); }
djknit/timeclock
client/src/utilities/jobData/wage.js
function areWagesEquivalent(wage_1, wage_2) { // expect wages already processed for output, but NOT processed for earnings calc if (!wage_1 && !wage_2) return true; if (!wage_1 || !wage_2) return false; if ( _hasDiff(w => w.currency) || _hasDiff(w => w.rate.raw) || _hasDiff(w => !!w.overtime) ) return false; if (!wage_1.overtime) return true; if ( _hasDiff(w => w.overtime.cutoff.durationInMsec) || _hasDiff(w => w.overtime.useMultiplier) || _hasDiff(w => w.overtime.useMultiplier ? w.overtime.rateMultiplier : w.overtime.rate.raw) ) return false; return true; function _hasDiff(_evaluator) { return _evaluator(wage_1) !== _evaluator(wage_2); } } export { areWagesEquivalent };
farukonfly/java-examples
javase/jdk6/src/main/java/examples/jdk6/gui/InterruptableLongRunningTask.java
<filename>javase/jdk6/src/main/java/examples/jdk6/gui/InterruptableLongRunningTask.java<gh_stars>0 package examples.jdk6.gui; //: gui/InterruptableLongRunningTask.java // Long-running tasks in threads. import javax.swing.*; import static examples.jdk6.net.mindview.util.SwingConsole.*; import java.awt.*; import java.awt.event.*; import java.util.concurrent.*; class Task implements Runnable { private static int counter = 0; private final int id = counter++; public void run() { System.out.println(this + " started"); try { TimeUnit.SECONDS.sleep(3); } catch(InterruptedException e) { System.out.println(this + " interrupted"); return; } System.out.println(this + " completed"); } public String toString() { return "Task " + id; } public long id() { return id; } }; public class InterruptableLongRunningTask extends JFrame { private JButton b1 = new JButton("Start Long Running Task"), b2 = new JButton("End Long Running Task"); ExecutorService executor = Executors.newSingleThreadExecutor(); public InterruptableLongRunningTask() { b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Task task = new Task(); executor.execute(task); System.out.println(task + " added to the queue"); } }); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { executor.shutdownNow(); // Heavy-handed } }); setLayout(new FlowLayout()); add(b1); add(b2); } public static void main(String[] args) { run(new InterruptableLongRunningTask(), 200, 150); } } ///:~
sargunv/better-than-wolves-mod
Src/FCBlockSnowLooseSlab.java
// FCMOD package net.minecraft.src; import java.util.Random; public class FCBlockSnowLooseSlab extends FCBlockSlabFalling { public FCBlockSnowLooseSlab( int iBlockID ) { super( iBlockID, Material.craftedSnow ); setHardness( FCBlockSnowLoose.m_fHardness ); SetShovelsEffectiveOn(); SetBuoyant(); setStepSound( soundSnowFootstep ); setUnlocalizedName( "fcBlockSnowLooseSlab" ); setTickRandomly( true ); setLightOpacity( 2 ); Block.useNeighborBrightness[iBlockID] = true; setCreativeTab( CreativeTabs.tabBlock ); } @Override public int idDropped( int iMetadata, Random rand, int iFortuneModifier ) { return Item.snowball.itemID; } public int quantityDropped( Random rand ) { return 4; } @Override public void OnBlockDestroyedWithImproperTool( World world, EntityPlayer player, int i, int j, int k, int iMetadata ) { dropBlockAsItem( world, i, j, k, iMetadata, 0 ); } @Override public void onBlockAdded( World world, int i, int j, int k ) { if ( world.provider.isHellWorld ) { // melt instantly in the nether world.setBlockToAir( i, j, k ); world.playSoundEffect( (double)i + 0.5D, (double)j + 0.5D, (double)k + 0.5D, "random.fizz", 0.5F, 2.6F + ( world.rand.nextFloat() - world.rand.nextFloat() ) * 0.8F ); for ( int iTempCount = 0; iTempCount < 8; iTempCount++ ) { world.spawnParticle( "largesmoke", (double)i + Math.random(), (double)j + Math.random(), (double)k + Math.random(), 0D, 0D, 0D ); } } else { ScheduleCheckForFall( world, i, j, k ); } } @Override public int GetCombinedBlockID( int iMetadata ) { return FCBetterThanWolves.fcBlockSnowLoose.blockID; } @Override public void updateTick( World world, int i, int j, int k, Random rand ) { if ( !HasStickySnowNeighborInContact( world, i, j, k ) || ( GetIsUpsideDown( world, i, j, k ) && HasFallingBlockRestingOn( world, i, j, k ) ) ) { if ( !CheckForFall( world, i, j, k ) ) { if ( GetIsUpsideDown( world, i, j, k ) ) { SetIsUpsideDown( world, i, j, k, false ); } } } } @Override public void RandomUpdateTick( World world, int i, int j, int k, Random rand ) { if ( FCUtilsMisc.IsIKInColdBiome( world, i, k ) ) { if ( rand.nextInt( FCBlockSnowLoose.m_iChanceOfHardeningIncrement ) == 0 ) { int iHardeningLevel = GetHardeningLevel( world, i, j, k ); if ( iHardeningLevel < 7 ) { SetHardeningLevel( world, i, j, k, iHardeningLevel + 1 ); } else { ConvertToSolidSnow( world, i, j, k ); } } } else { if ( rand.nextInt( FCBlockSnowLoose.m_iChanceOfMeltingIncrement ) == 0 ) { int iHardeningLevel = GetHardeningLevel( world, i, j, k ); if ( iHardeningLevel > 0 ) { SetHardeningLevel( world, i, j, k, iHardeningLevel - 1 ); } else { Melt( world, i, j, k ); } } } } @Override public boolean CanBePlacedUpsideDownAtLocation( World world, int i, int j, int k ) { return HasStickySnowNeighborInContact( world, i, j, k, true ); } @Override public void OnPlayerWalksOnBlock( World world, int i, int j, int k, EntityPlayer player ) { if ( !CheckForFall( world, i, j, k ) ) { if ( GetIsUpsideDown( world, i, j, k ) ) { SetIsUpsideDown( world, i, j, k, false ); } } } @Override public float GetMovementModifier( World world, int i, int j, int k ) { return 0.8F; } @Override public boolean GetCanBeSetOnFireDirectly( IBlockAccess blockAccess, int i, int j, int k ) { return true; } @Override public boolean GetCanBeSetOnFireDirectlyByItem( IBlockAccess blockAccess, int i, int j, int k ) { return false; } @Override public boolean SetOnFireDirectly( World world, int i, int j, int k ) { Melt( world, i, j, k ); return true; } @Override public int GetChanceOfFireSpreadingDirectlyTo( IBlockAccess blockAccess, int i, int j, int k ) { return 60; // same chance as leaves and other highly flammable objects } @Override protected boolean canSilkHarvest() { return true; } @Override protected ItemStack createStackedBlock( int iMetadata ) { return new ItemStack( blockID, 1, 0 ); } @Override public boolean CanBePistonShoveled( World world, int i, int j, int k ) { return true; } //------------- Class Specific Methods ------------// public int GetHardeningLevel( IBlockAccess blockAccess, int i, int j, int k ) { return GetHardeningLevel( blockAccess.getBlockMetadata( i, j, k ) ); } public int GetHardeningLevel( int iMetadata ) { return ( iMetadata & 14 ) >> 1; } public void SetHardeningLevel( World world, int i, int j, int k, int iLevel ) { int iMetadata = SetHardeningLevel( world.getBlockMetadata( i, j, k ), iLevel ); world.setBlockMetadataWithNotify( i, j, k, iMetadata ); } public int SetHardeningLevel( int iMetadata, int iLevel ) { iMetadata &= ~14; return iMetadata | ( iLevel << 1 ); } private void ConvertToSolidSnow( World world, int i, int j, int k ) { int iNewMetadata = FCBetterThanWolves.fcBlockSnowSolidSlab.SetIsUpsideDown( 0, GetIsUpsideDown( world, i, j, k ) ); world.setBlockAndMetadataWithNotify( i, j, k, FCBetterThanWolves.fcBlockSnowSolidSlab.blockID, iNewMetadata ); } private void Melt( World world, int i, int j, int k ) { FCUtilsMisc.PlaceNonPersistantWaterMinorSpread( world, i, j, k ); } //----------- Client Side Functionality -----------// private Icon[] m_iconsHardening; @Override public void registerIcons( IconRegister register ) { super.registerIcons( register ); m_iconsHardening = new Icon[8]; for ( int iTempIndex = 0; iTempIndex < 8; iTempIndex++ ) { m_iconsHardening[iTempIndex] = register.registerIcon( "fcOverlaySnowLoose_" + iTempIndex ); } } @Override public void RenderBlockSecondPass( RenderBlocks renderBlocks, int i, int j, int k, boolean bFirstPassResult ) { if ( bFirstPassResult ) { int iHardeningLevel = GetHardeningLevel( renderBlocks.blockAccess, i, j, k ); if ( iHardeningLevel >= 0 && iHardeningLevel <= 7 ) { RenderBlockWithTexture( renderBlocks, i, j, k, m_iconsHardening[iHardeningLevel] ); } } } @Override public void RenderBlockAsItem( RenderBlocks renderBlocks, int iItemDamage, float fBrightness ) { renderBlocks.renderBlockAsItemVanilla( this, iItemDamage, fBrightness ); FCClientUtilsRender.RenderInvBlockWithTexture( renderBlocks, this, -0.5F, -0.5F, -0.5F, m_iconsHardening[0] ); } @Override public void RenderFallingBlock( RenderBlocks renderBlocks, int i, int j, int k, int iMetadata ) { renderBlocks.SetRenderAllFaces( true ); renderBlocks.setRenderBounds( GetBlockBoundsFromPoolFromMetadata( iMetadata ) ); renderBlocks.renderStandardBlock( this, i, j, k ); FCClientUtilsRender.RenderStandardBlockWithTexture( renderBlocks, this, i, j, k, m_iconsHardening[GetHardeningLevel( iMetadata )] ); renderBlocks.SetRenderAllFaces( false ); } @Override public void randomDisplayTick( World world, int i, int j, int k, Random rand ) { EmitHardeningParticles( world, (double)i + 0.5D, (double)j + 0.5D, (double)k + 0.5D, rand ); } private void EmitHardeningParticles( World world, double dCenterX, double dCenterY, double dCenterZ, Random rand ) { for ( int iTempCount = 0; iTempCount < 1; ++iTempCount ) { double xPos = dCenterX - 0.60D + rand.nextDouble() * 1.2D; double yPos = dCenterY - 0.60D + rand.nextDouble() * 1.2D; double zPos = dCenterZ - 0.60D + rand.nextDouble() * 1.2D; world.spawnParticle( "fcwhitecloud", xPos, yPos, zPos, 0D, 0D, 0D ); } } }
ianemcallister/team-29kettle
public/scripts/directives/list-of-channels.directive.js
<reponame>ianemcallister/team-29kettle ckc.directive('listOfChannels', listOfChannels); /* @ngInject */ function listOfChannels() { //define the directive var directive = { restrict: "AECM", templateUrl: 'assets/views/directives/list-of-channels.htm', replace: true, scope: { channels: "=" }, link: linkFunc, controller: listOfChannelsController, controllerAs: 'vm', bindToController: true }; /* @ngInject */ function linkFunc(scope, el, attr, ctrl) { scope.$watch('vm.channels', function loadChannelsData(newVal, oldVal) { }); } listOfChannelsController.$inject = ['$scope']; /* @ngInject */ function listOfChannelsController($scope) { // DEFINE LOCAL VARIABLES var vm = this; // DEFINE VIEW MODEL VARIABLES vm.sortBy = 'name'; vm.sortedChannels = [] // DEFINE LOCAL METHODS // DEFINE VIEW MODEL METHODS console.log('in the list of channels directive', $scope); }; return directive; };
AkshayBhanawala/MERN-HackerPolls
Client/src/App.js
import React, { Component } from 'react'; import { Container } from 'reactstrap'; import { Switch, Route } from "react-router-dom"; import Config from './helpers/Config'; import Header from './components/Header.component'; import Login from './components/Login.component'; import User from './components/User/User.component'; import Admin from './components/Admin/Admin.component'; import UsersList from './components/UsersList.component'; import Redirectors from './components/_Custom/Redirectors'; import HelperMethods from './helpers/HelperMethods'; import RoutesForClient from './helpers/RoutesForClient'; import EditUser from './components/EditUser.component'; export default class App extends Component { static displayName = 'App'; _isMounted = false; constructor(props) { super(props); this.state = { user: undefined, updateUsersList: false }; this.logInCallback = this.logInCallback.bind(this); this.logOutCallBack = this.logOutCallBack.bind(this); this.redirectToAdminHome = Redirectors.redirectToAdminHome.bind(this); this.redirectToUserHome = Redirectors.redirectToUserHome.bind(this); this.isUserLoggedIn_Local = HelperMethods.isUserLoggedIn_Local.bind(this); } componentDidMount() { this._isMounted = true; if (Config.isDebug) console.log("App", "Mounted"); // Code to run when component is loaded this.isUserLoggedIn_Local(); } componentWillUnmount() { this._isMounted = false; if (Config.isDebug) console.log("App", "Unmounted"); localStorage.removeItem(Config.LSNames.usersList) } logInCallback() { this.doHeaderUpdate(); } logOutCallBack() { this.setState({ updateUsersList: true }); } render() { if (Config.isDebug) console.log("App", "render", this.state); return ( <React.Fragment> <Header setUpdate={(updateFN) => { this.doHeaderUpdate = updateFN; }} logOutCallBack={this.logOutCallBack} ThemeChangeButton={this.props.ThemeChangeButton} /> {this.redirectToAdminHome()} {this.redirectToUserHome()} <Container className="MainContainer"> <Switch> <Route path={RoutesForClient.Home} exact component={() => (!this.state.user || this.state.updateUsersList) ? <UsersList /> : <React.Fragment />} /> <Route path={RoutesForClient.Login} exact component={() => <Login logInCallback={this.logInCallback} />} /> </Switch> <Switch> <Route path={RoutesForClient.Admin.Home} component={Admin} /> </Switch > <Switch> <Route path={RoutesForClient.User.Home} component={User} /> </Switch> <Switch> <Route path={RoutesForClient.Edit} component={EditUser} /> </Switch > </Container> </React.Fragment> ); }; }
nibblesnbits/slingshot-sagas
src/reducers/appReducer.spec.js
import { expect } from 'chai'; import appReducer from './appReducer'; import * as actions from '../actions/appActions'; describe('App Reducer', () => { it ('should add message on showMessage()', () => { const initialState = { messages: [] }; const action = actions.showMessage('test', 'test', 'success'); const newState = appReducer(initialState, action); expect(newState.messages.length).to.equal(1); }); it ('should delete message on removeMessage()', () => { const initialState = { messages: [{ title: 'test', text: 'test', className: 'info', hidden: false, id: 0 }] }; const action = actions.removeMessage(0); const newState = appReducer(initialState, action); expect(newState.messages.length).to.equal(0); }); it ('should hide all messages on clearMesages()', () => { const initialState = { messages: [{ title: 'test', text: 'test', className: 'info', hidden: false, id: 0 }] }; const action = actions.clearMessages(); const newState = appReducer(initialState, action); expect(newState.messages.length).to.equal(0); }); it ('should set hidden to "true" for a message on fadeMessage()', () => { const initialState = { messages: [{ title: 'test', text: 'test', className: 'info', hidden: false, id: 0 }] }; const action = actions.fadeMessage(0); const newState = appReducer(initialState, action); expect(newState.messages[0].hidden).to.be.true; expect(newState.messages.length).to.be.equal(1); }); it ('messages remain in original order on fadeMessage()', () => { const initialState = { messages: [{ title: 'test1', text: 'test1', className: 'test1', hidden: false, id: 'test1', order: 0 }, { title: 'test2', text: 'test2', className: 'test2', hidden: false, id: 'test2', order: 1 }] }; const action = actions.fadeMessage('test1'); const newState = appReducer(initialState, action); expect(newState.messages[0].order).to.equal(0); }); it ('messages remain in original order on showMessage()', () => { const initialState = { messages: [{ title: 'test0', text: 'test0', className: 'test0', hidden: true, id: 'test0', order: 0 }, { title: 'test2', text: 'test2', className: 'test2', hidden: true, id: 'test2', order: 2 }] }; const action = actions.showMessage('test1', 'test1', 'test1'); const newState = appReducer(initialState, action); expect(newState.messages[2].order).to.equal(2); }); it ('messages remain in original order on removeMessage()', () => { const initialState = { messages: [{ title: 'test0', text: 'test0', className: 'test0', hidden: false, id: 'test0', order: 0 }, { title: 'test1', text: 'test1', className: 'test1', hidden: true, id: 'test1', order: 1 }, { title: 'test2', text: 'test2', className: 'test2', hidden: true, id: 'test2', order: 2 }] }; const action = actions.removeMessage('test1'); const newState = appReducer(initialState, action); expect(newState.messages[1].order).to.equal(1); }); });
yongjhih/hivemq-community-edition
src/main/java/com/hivemq/extensions/client/parameter/ServerInformationImpl.java
/* * Copyright 2019 dc-square GmbH * * 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.hivemq.extensions.client.parameter; import com.hivemq.annotations.NotNull; import com.hivemq.bootstrap.ioc.lazysingleton.LazySingleton; import com.hivemq.configuration.info.SystemInformation; import com.hivemq.extension.sdk.api.client.parameter.ServerInformation; import javax.inject.Inject; import java.io.File; /** * @author <NAME> * @since 4.0.0 */ @LazySingleton public class ServerInformationImpl implements ServerInformation { @NotNull private final SystemInformation systemInformation; @Inject public ServerInformationImpl(@NotNull final SystemInformation systemInformation) { this.systemInformation = systemInformation; } @NotNull @Override public String getVersion() { return systemInformation.getHiveMQVersion(); } @NotNull @Override public File getHomeFolder() { return systemInformation.getHiveMQHomeFolder(); } @NotNull @Override public File getDataFolder() { return systemInformation.getDataFolder(); } @NotNull @Override public File getLogFolder() { return systemInformation.getLogFolder(); } @NotNull @Override public File getExtensionsFolder() { return systemInformation.getExtensionsFolder(); } }
junrrein/ic2017
guia3/borroso.cpp
<reponame>junrrein/ic2017 #include <armadillo> #include <gnuplot-iostream.h> #include <memory> using namespace arma; using namespace std; class Conjunto { public: virtual double membresia(double x) const = 0; virtual void graficar(Gnuplot& gp, double escala = 1) const = 0; virtual double centroide_x() const = 0; virtual double area(double altura) const = 0; }; class ConjuntoTrapezoidal : public Conjunto { public: ConjuntoTrapezoidal(vec puntos); double membresia(double x) const override; void graficar(Gnuplot& gp, double escala = 1) const override; double centroide_x() const override; double area(double altura) const override; const double a, b, c, d; }; class ConjuntoGaussiano : public Conjunto { public: ConjuntoGaussiano(double t_media, double t_sigma); double membresia(double x) const override; void graficar(Gnuplot& gp, double escala = 1) const override; double centroide_x() const override; double area(double altura) const override; const double media, sigma; }; enum class tipoConjunto { trapezoidal, gaussiano }; class SistemaBorroso { public: SistemaBorroso(const mat& matrizEntrada, tipoConjunto tipoEntrada); SistemaBorroso(const mat& matrizEntrada, tipoConjunto tipoEntrada, const mat& matrizSalida, tipoConjunto tipoSalida, const uvec& t_reglasMapeo = {}); vec activacionesEntrada(double x) const; vec mapeoEntradaSalida(const vec& activacionesEntrada) const; double defuzzyficarSalida(vec activaciones) const; double salidaSistema(double entrada) const; const vector<unique_ptr<Conjunto>>& conjuntosEntrada() const { return m_conjuntosEntrada; }; const vector<unique_ptr<Conjunto>>& conjuntosSalida() const { return m_conjuntosSalida; }; private: vector<unique_ptr<Conjunto>> m_conjuntosEntrada; vector<unique_ptr<Conjunto>> m_conjuntosSalida; const uvec m_reglasMapeo; }; ConjuntoTrapezoidal::ConjuntoTrapezoidal(vec puntos) : a{puntos(0)} , b{puntos(1)} , c{puntos(2)} , d{puntos(3)} { // chequear orden de puntos if (!puntos.is_sorted()) throw runtime_error("los puntos no estan ordenados"); if (puntos.n_elem != 4) throw runtime_error("no se tienen cuatro puntos"); } double ConjuntoTrapezoidal::membresia(double x) const { if (x < a or x > d) return 0; else if (a <= x and x < b) return (x - a) / (b - a); else if (b <= x and x <= c) return 1; else if (c < x and x <= d) return 1 - (x - c) / (d - c); else throw runtime_error("Nunca se debería llegar acá (en ConjuntoTrapezoidal::membresia)"); } void ConjuntoTrapezoidal::graficar(Gnuplot& gp, double escala) const { const mat puntos = {{a, 0}, {b, 1 * escala}, {c, 1 * escala}, {d, 0}}; gp << gp.file1d(puntos) << "with lines"; } double ConjuntoTrapezoidal::centroide_x() const { // Ver http://www.efunda.com/math/areas/Trapezoid.cfm const double A = c - b; const double B = d - a; const double C = b - a; const double numerador = 2 * A * C + A * A + C * B + A * B + B * B; const double denominador = 3 * (A + B); const double result = numerador / denominador; // El resultado está como si el trapezoide tuviera el punto // a en (0, 0). // Para corregir esto, hace falta sumarle a. return result + a; } double ConjuntoTrapezoidal::area(double altura) const { return ((d - a) + (c - b)) * altura / 2; } ConjuntoGaussiano::ConjuntoGaussiano(double t_media, double t_sigma) : media{t_media} , sigma{t_sigma} { if (t_sigma <= 0) throw runtime_error("el sigma debe ser mayor o igual a cero"); } double ConjuntoGaussiano::membresia(double x) const { return exp(-0.5 * (pow((x - media) / sigma, 2))); } void ConjuntoGaussiano::graficar(Gnuplot& gp, double escala) const { const string exponencial = to_string(escala) + " * exp(-0.5 * ((x - " + to_string(media) + ") / " + to_string(sigma) + ") ** 2)"; gp << exponencial << "with lines"; } double ConjuntoGaussiano::centroide_x() const { return media; } double ConjuntoGaussiano::area(double altura) const { // PREGUNTAR: // ¿Se puede escalar el área original de la gaussiana // por el grado de activación y obtener el área correcta? return sigma * sqrt(2 * datum::pi) * altura; } vector<unique_ptr<Conjunto>> parsearTrapecios(const mat& matrizConjuntos) { vector<unique_ptr<Conjunto>> result; for (unsigned int i = 0; i < matrizConjuntos.n_rows; ++i) { result.push_back(unique_ptr<Conjunto>{new ConjuntoTrapezoidal{matrizConjuntos.row(i).t()}}); } return result; } vector<unique_ptr<Conjunto>> parsearGaussianas(const mat& matrizConjuntos) { if (matrizConjuntos.n_cols != 2) throw runtime_error("La matriz debe tener dos columnas"); vector<unique_ptr<Conjunto>> result; for (unsigned int i = 0; i < matrizConjuntos.n_rows; ++i) { result.push_back(unique_ptr<Conjunto>{ new ConjuntoGaussiano{matrizConjuntos(i, 0), matrizConjuntos(i, 1)}}); } return result; } // NOTA // Después de usar esta función hace falta cerrar el ploteo // ya sea ploteando algo más, o ploteando "NaN notitle". void graficarConjuntos(const vector<unique_ptr<Conjunto>>& conjuntos, Gnuplot& gp, vec escalas = {}) { if (escalas.empty()) escalas = ones(conjuntos.size()); gp << "plot "; for (unsigned int i = 0; i < conjuntos.size(); ++i) { conjuntos[i]->graficar(gp, escalas(i)); gp << " title 'Conjunto " << (i + 1) << "', "; } } SistemaBorroso::SistemaBorroso(const mat& matrizEntrada, tipoConjunto tipoEntrada) { switch (tipoEntrada) { case tipoConjunto::trapezoidal: m_conjuntosEntrada = parsearTrapecios(matrizEntrada); break; case tipoConjunto::gaussiano: m_conjuntosEntrada = parsearGaussianas(matrizEntrada); break; } } SistemaBorroso::SistemaBorroso(const mat& matrizEntrada, tipoConjunto tipoEntrada, const mat& matrizSalida, tipoConjunto tipoSalida, const uvec& t_reglasMapeo) : m_reglasMapeo{t_reglasMapeo} { switch (tipoEntrada) { case tipoConjunto::trapezoidal: m_conjuntosEntrada = parsearTrapecios(matrizEntrada); break; case tipoConjunto::gaussiano: m_conjuntosEntrada = parsearGaussianas(matrizEntrada); break; } switch (tipoSalida) { case tipoConjunto::trapezoidal: m_conjuntosSalida = parsearTrapecios(matrizSalida); break; case tipoConjunto::gaussiano: m_conjuntosSalida = parsearGaussianas(matrizSalida); break; } if (!t_reglasMapeo.empty()) { if (t_reglasMapeo.n_elem != m_conjuntosEntrada.size()) throw runtime_error( "La cantidad de reglas tiene que ser la misma " "que la cantidad de conjuntos de entrada"); if (unique(t_reglasMapeo).eval().n_elem != t_reglasMapeo.n_elem) throw runtime_error( "No puede haber reglas que mapeen al mismo " "conjunto de salida"); if (max(t_reglasMapeo) != m_conjuntosSalida.size() || min(t_reglasMapeo != 1)) throw runtime_error( "Los valores de las reglas están fuera de rango"); } } vec SistemaBorroso::activacionesEntrada(double x) const { vec result(m_conjuntosEntrada.size()); for (unsigned int i = 0; i < m_conjuntosEntrada.size(); ++i) { result(i) = m_conjuntosEntrada[i]->membresia(x); } return result; } vec SistemaBorroso::mapeoEntradaSalida(const vec& activacionesEntrada) const { if (m_reglasMapeo.empty()) throw runtime_error("No se tienen reglas de mapeo"); vec activacionesSalida(m_conjuntosSalida.size()); for (unsigned int i = 0; i < m_reglasMapeo.n_elem; ++i) { // El "- 1" es para pasar el vector de reglas de mapeo de base 1 a base 0 activacionesSalida(m_reglasMapeo(i) - 1) = activacionesEntrada(i); } return activacionesSalida; } double SistemaBorroso::defuzzyficarSalida(vec activaciones) const { if (activaciones.size() != m_conjuntosSalida.size()) throw runtime_error( "La cantidad de activaciones y la cantidad " "de conjuntos de salida no coinciden"); double numerador = 0, denominador = 0; for (unsigned int i = 0; i < m_conjuntosSalida.size(); ++i) { numerador += m_conjuntosSalida[i]->centroide_x() * m_conjuntosSalida[i]->area(activaciones(i)); denominador += m_conjuntosSalida[i]->area(activaciones(i)); } return numerador / denominador; } double SistemaBorroso::salidaSistema(double entrada) const { const vec actEntrada = activacionesEntrada(entrada); const vec actSalida = mapeoEntradaSalida(actEntrada); const double salida = defuzzyficarSalida(actSalida); return salida; }
onap/aai-aai-common
aai-core/src/main/java/org/onap/aai/dbmap/AAIGraph.java
<gh_stars>1-10 /** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2018 IBM. * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.aai.dbmap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.io.IoCore; import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphFactory; import org.janusgraph.core.schema.JanusGraphManagement; import org.onap.aai.config.SpringContextAware; import org.onap.aai.dbgen.SchemaGenerator; import org.onap.aai.dbgen.SchemaGenerator4Hist; import org.onap.aai.exceptions.AAIException; import org.onap.aai.util.AAIConstants; import java.io.FileNotFoundException; import java.util.Properties; /** * Database Mapping class which acts as the middle man between the REST * interface objects and JanusGraph DB objects. This class provides methods to commit * the objects received on the REST interface into the JanusGraph graph database as * vertices and edges. Transactions are also managed here by using a JanusGraph * object to load, commit/rollback and shutdown for each request. The data model * rules such as keys/required properties are handled by calling DBMeth methods * which are driven by a specification file in json. * * */ public class AAIGraph { private static final Logger logger = LoggerFactory.getLogger(AAIGraph.class); private static final String IN_MEMORY = "inmemory"; protected JanusGraph graph; private static boolean isInit = false; /** * Instantiates a new AAI graph. */ private AAIGraph() { try { String serviceName = System.getProperty("aai.service.name", "NA"); String rtConfig = System.getProperty("realtime.db.config"); if (rtConfig == null) { rtConfig = AAIConstants.REALTIME_DB_CONFIG; } this.loadGraph(rtConfig, serviceName); } catch (Exception e) { throw new RuntimeException("Failed to instantiate graphs", e); } } private static class Helper { private static final AAIGraph INSTANCE = new AAIGraph(); private Helper() { } } /** * Gets the single instance of AAIGraph. * * @return single instance of AAIGraph */ public static AAIGraph getInstance() { isInit = true; return Helper.INSTANCE; } public static boolean isInit() { return isInit; } private void loadGraph(String configPath, String serviceName) throws Exception { // Graph being opened by JanusGraphFactory is being placed in hashmap to be used later // These graphs shouldn't be closed until the application shutdown try { PropertiesConfiguration propertiesConfiguration = new AAIGraphConfig.Builder(configPath) .forService(serviceName).withGraphType("realtime").buildConfiguration(); graph = JanusGraphFactory.open(propertiesConfiguration); Properties graphProps = new Properties(); propertiesConfiguration.getKeys() .forEachRemaining(k -> graphProps.setProperty(k, propertiesConfiguration.getString(k))); if (IN_MEMORY.equals(graphProps.get("storage.backend"))) { // Load the propertyKeys, indexes and edge-Labels into the DB loadSchema(graph); loadSnapShotToInMemoryGraph(graph, graphProps); } if (graph == null) { throw new AAIException("AAI_5102"); } } catch (FileNotFoundException e) { throw new AAIException("AAI_4001", e); } } private void loadSnapShotToInMemoryGraph(JanusGraph graph, Properties graphProps) { if (logger.isDebugEnabled()) { logger.debug("Load Snapshot to InMemory Graph"); } if (graphProps.containsKey("load.snapshot.file")) { String value = graphProps.getProperty("load.snapshot.file"); if ("true".equals(value)) { try (Graph transaction = graph.newTransaction()) { String location = System.getProperty("snapshot.location"); logger.info("Loading snapshot to inmemory graph."); transaction.io(IoCore.graphson()).readGraph(location); transaction.tx().commit(); logger.info("Snapshot loaded to inmemory graph."); } catch (Exception e) { logger.info(String.format("ERROR: Could not load datasnapshot to in memory graph. %n%s", ExceptionUtils.getFullStackTrace(e))); throw new RuntimeException(e); } } } } private void loadSchema(JanusGraph graph) { // Load the propertyKeys, indexes and edge-Labels into the DB JanusGraphManagement graphMgt = graph.openManagement(); logger.info("-- loading schema into JanusGraph"); if ("true".equals(SpringContextAware.getApplicationContext().getEnvironment().getProperty("history.enabled", "false"))) { SchemaGenerator4Hist.loadSchemaIntoJanusGraph(graphMgt, IN_MEMORY); } else { SchemaGenerator.loadSchemaIntoJanusGraph(graphMgt, IN_MEMORY); } } /** * Close all of the graph connections made in the instance. */ public void graphShutdown() { if (graph != null && graph.isOpen()) { graph.close(); } } /** * Gets the graph. * * @return the graph */ public JanusGraph getGraph() { return graph; } }
zero-deps/protobuf-scala-macros
proto/src/main/scala-3/Common.scala
package proto import com.google.protobuf.{CodedOutputStream, CodedInputStream} import scala.quoted.* import scala.collection.immutable.ArraySeq import scala.annotation.* trait Common: implicit val qctx: Quotes import qctx.reflect.{*, given} import qctx.reflect.defn.* import report.* extension (x: TypeRepr) private[proto] def matchable: TypeRepr & Matchable = x.asInstanceOf[TypeRepr & Matchable] private[proto] case class FieldInfo( name: String , num: Int , sym: Symbol , tpe: TypeRepr & Matchable , getter: Term => Term , sizeSym: Symbol , prepareSym: Symbol , prepareOptionSym: Symbol = Symbol.noSymbol , prepareArraySym: Symbol = Symbol.noSymbol , defaultValue: Option[Term] , isCaseObject: Boolean = false , nonPacked: Boolean = false ): def tag: Int = if nonPacked && tpe.isRepeated && tpe.repeatedArgument.matchable.isCommonType then num << 3 | wireType(tpe.repeatedArgument.matchable) else num << 3 | wireType(tpe) def wireType(t: TypeRepr & Matchable): Int = if t.isInt || t.isLong || t.isBoolean then 0 else if t.isDouble then 1 else if t.isFloat then 5 else if t.isOption then wireType(t.optionArgument.matchable) else if t.isString || t.isArrayByte || t.isArraySeqByte || t.isCaseType || t.isSealedTrait || t.isRepeated then 2 else 2 def writeFun(os: Expr[CodedOutputStream], t: TypeRepr & Matchable, getterTerm: Term)(using Quotes): Expr[Unit] = if t.isInt then '{ ${os}.writeInt32NoTag(${getterTerm.asExprOf[Int]}) } else if t.isLong then '{ ${os}.writeInt64NoTag(${getterTerm.asExprOf[Long]}) } else if t.isBoolean then '{ ${os}.writeBoolNoTag(${getterTerm.asExprOf[Boolean]}) } else if t.isDouble then '{ ${os}.writeDoubleNoTag(${getterTerm.asExprOf[Double]}) } else if t.isFloat then '{ ${os}.writeFloatNoTag(${getterTerm.asExprOf[Float]}) } else if t.isString then '{ ${os}.writeStringNoTag(${getterTerm.asExprOf[String]}) } else if t.isArrayByte then '{ ${os}.writeByteArrayNoTag(${getterTerm.asExprOf[Array[Byte]]}) } else if t.isArraySeqByte then '{ ${os}.writeByteArrayNoTag(${getterTerm.asExprOf[ArraySeq[Byte]]}.toArray[Byte]) } else errorAndAbort(s"Unsupported common type: ${t.typeSymbol.name}") def sizeFun(t: TypeRepr & Matchable, getterTerm: Term): Expr[Int] = if t.isInt then '{ CodedOutputStream.computeInt32SizeNoTag(${getterTerm.asExprOf[Int]}) } else if t.isLong then '{ CodedOutputStream.computeInt64SizeNoTag(${getterTerm.asExprOf[Long]}) } else if t.isBoolean then Expr(1) else if t.isDouble then Expr(8) else if t.isFloat then Expr(4) else if t.isString then '{ CodedOutputStream.computeStringSizeNoTag(${getterTerm.asExprOf[String]}) } else if t.isArrayByte then '{ CodedOutputStream.computeByteArraySizeNoTag(${getterTerm.asExprOf[Array[Byte]]}) } else if t.isArraySeqByte then '{ CodedOutputStream.computeByteArraySizeNoTag(${getterTerm.asExprOf[ArraySeq[Byte]]}.toArray[Byte]) } else errorAndAbort(s"Unsupported common type: ${t.typeSymbol.name}") def readFun(t: TypeRepr & Matchable, is: Expr[CodedInputStream])(using Quotes): Term = if t.isInt then '{ ${is}.readInt32 }.asTerm else if t.isLong then '{ ${is}.readInt64 }.asTerm else if t.isBoolean then '{ ${is}.readBool }.asTerm else if t.isDouble then '{ ${is}.readDouble }.asTerm else if t.isFloat then '{ ${is}.readFloat }.asTerm else if t.isString then '{ ${is}.readString.nn }.asTerm else if t.isArrayByte then '{ ${is}.readByteArray.nn }.asTerm else if t.isArraySeqByte then '{ ArraySeq.unsafeWrapArray(${is}.readByteArray.nn) }.asTerm else errorAndAbort(s"Unsupported common type: ${t.typeSymbol.name}") val ArrayByteType: TypeRepr = TypeRepr.of[Array[Byte]] val ArraySeqByteType: TypeRepr = TypeRepr.of[ArraySeq[Byte]] val NTpe: TypeRepr = TypeRepr.of[N] val RestrictedNType: TypeRepr = TypeRepr.of[RestrictedN] val ItetableType: TypeRepr = TypeRepr.of[scala.collection.Iterable[?]] val ArrayType: TypeRepr = TypeRepr.of[Array[?]] val PrepareType: TypeRepr = TypeRepr.of[Prepare] val CodedInputStreamType: TypeRepr = TypeRepr.of[CodedInputStream] extension (s: Symbol) def constructorParams: List[Symbol] = s.primaryConstructor.paramSymss.find(_.headOption.fold(false)( _.isTerm)).getOrElse(Nil) def tpe: TypeRepr = s.tree match case x: ClassDef => x.constructor.returnTpt.tpe case ValDef(_,tpt,_) => tpt.tpe case Bind(_, pattern: Term) => pattern.tpe def unitLiteral: Literal = Literal(UnitConstant()) def defaultMethodName(i: Int): String = s"$$lessinit$$greater$$default$$${i+1}" def unitExpr: Expr[Unit] = unitLiteral.asExprOf[Unit] def builderType: TypeRepr = TypeRepr.of[scala.collection.mutable.Builder] def OptionType: TypeRepr = TypeRepr.of[Option] def Some_Apply(tpe: TypeRepr, value: Term): Term = Select.unique(Ref(SomeModule.companionModule), "apply") .appliedToType(tpe) .appliedTo(value) val commonTypes: List[TypeRepr] = TypeRepr.of[String] :: TypeRepr.of[Int] :: TypeRepr.of[Long] :: TypeRepr.of[Boolean] :: TypeRepr.of[Double] :: TypeRepr.of[Float] :: ArrayByteType :: ArraySeqByteType :: Nil extension (t: TypeRepr) def isNType: Boolean = t =:= NTpe def isCaseClass: Boolean = t.typeSymbol.flags.is(Flags.Case) def isCaseObject: Boolean = t.termSymbol.flags.is(Flags.Case) def isCaseType: Boolean = t.isCaseClass || t.isCaseObject def isSealedTrait: Boolean = t.typeSymbol.flags.is(Flags.Sealed) && t.typeSymbol.flags.is(Flags.Trait) def isIterable: Boolean = t <:< ItetableType && !t.isArraySeqByte def isArray: Boolean = t <:< ArrayType && !t.isArrayByte def isRepeated: Boolean = t.isIterable || t.isArray def isString: Boolean = t =:= TypeRepr.of[String] def isInt: Boolean = t =:= TypeRepr.of[Int] def isLong: Boolean = t =:= TypeRepr.of[Long] def isBoolean: Boolean = t =:= TypeRepr.of[Boolean] def isDouble: Boolean = t =:= TypeRepr.of[Double] def isFloat: Boolean = t =:= TypeRepr.of[Float] def isArrayByte: Boolean = t =:= ArrayByteType def isArraySeqByte: Boolean = t =:= ArraySeqByteType def isCommonType: Boolean = commonTypes.exists(_ =:= t) def typeArgsToReplace: Map[String, TypeRepr] = t.typeSymbol.primaryConstructor.paramSymss .find(_.headOption.fold(false)( _.isType)) .map(_.map(_.name).zip(t.typeArgs)).getOrElse(Nil) .toMap def replaceTypeArgs(map: Map[String, TypeRepr]): TypeRepr = t.matchable match case AppliedType(t1, args) => t1.appliedTo(args.map(_.matchable.replaceTypeArgs(map))) case _ => map.getOrElse(t.typeSymbol.name, t) def isOption: Boolean = t.matchable match case AppliedType(t1, _) if t1.typeSymbol == OptionClass => true case _ => false def typeArgs: List[TypeRepr] = t.dealias.matchable match case AppliedType(t1, args) => args case _ => Nil def optionArgument: TypeRepr = t.matchable match case AppliedType(t1, args) if t1.typeSymbol == OptionClass => args.head case _ => errorAndAbort(s"It isn't Option type: ${t.typeSymbol.name}") def iterableArgument: TypeRepr = t.baseType(ItetableType.typeSymbol).matchable match case AppliedType(_, args) if t.isIterable => args.head case _ => errorAndAbort(s"It isn't Iterable (argument) type: ${t.typeSymbol.name}") def arrayArgument: TypeRepr = t.dealias.matchable match case AppliedType(_, args) if t.isArray => args.head case _ => errorAndAbort(s"It isn't Array (base) type: ${t.typeSymbol.name}") def repeatedArgument: TypeRepr = if t.isIterable then t.iterableArgument else if t.isArray then t.arrayArgument else errorAndAbort(s"It isn't Iterable or Array type: ${t.typeSymbol.name}") def repeatedBaseType: TypeRepr = t.dealias.matchable match case AppliedType(t1, _) if t.isRepeated => t1 case _ => errorAndAbort(s"It isn't Iterable or Array type: ${t.typeSymbol.name}") def restrictedNums: List[Int] = val aName = RestrictedNType.typeSymbol.name val tName = t.typeSymbol.fullName t.typeSymbol.annotations.collect{ case Apply(Select(New(tpt),_), List(Typed(Repeated(args,_),_))) if tpt.tpe =:= RestrictedNType => args } match case List(Nil) => errorAndAbort(s"empty annotation ${aName} for `${tName}`") case List(xs) => val nums = xs.collect{ case Literal(IntConstant(n)) => n case x => errorAndAbort(s"wrong annotation ${aName} for `${tName}` $x") } if nums.size != nums.distinct.size then errorAndAbort(s"nums not unique in annotation ${aName} for `${tName}`") nums case Nil => Nil case _ => errorAndAbort(s"multiple ${aName} annotations applied for `${tName}`") def knownFinalSubclasses: List[Symbol] = @tailrec def loop(q: List[Symbol], acc: List[Symbol]): List[Symbol] = q match case Nil => acc case x :: xs if x.tpe.isSealedTrait => loop(x.tpe.typeSymbol.children ++ xs, acc) case x :: xs => loop(xs, x :: acc) loop(t.typeSymbol.children, Nil) def mkIfStatement(branches: List[(Term, Term)], elseBranch: Term): Term = branches match case (cond, thenp) :: xs => If(cond, thenp, mkIfStatement(xs, elseBranch)) case Nil => elseBranch def findCodec(t: TypeRepr): Term = val tpe = TypeRepr.of[MessageCodec].appliedTo(t) Implicits.search(tpe) match case x: ImplicitSearchSuccess => x.tree case x: ImplicitSearchFailure => errorAndAbort(x.explanation) def findImplicit(tpe: TypeRepr): Term = Implicits.search(tpe) match case x: ImplicitSearchSuccess => x.tree case x: ImplicitSearchFailure => errorAndAbort(x.explanation) extension (array_term: Term) private[proto] def wrapArrayOps(array_tpe: TypeRepr): Term = Select.unique(Ref(PredefModule), "genericArrayOps").appliedToType(array_tpe.arrayArgument).appliedTo(array_term) end Common
brndkfr/xmppbot
xmppbot-core/src/main/java/de/raion/xmppbot/filter/MessageBodyContainsFilter.java
package de.raion.xmppbot.filter; /* * #%L * XmppBot Core * %% * Copyright (C) 2012 - 2013 <NAME> <<EMAIL>> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.jivesoftware.smack.packet.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simple Filter checking Body content containing a specific string * */ public class MessageBodyContainsFilter extends AbstractMessageFilter { private static Logger log = LoggerFactory.getLogger(MessageBodyContainsFilter.class); private String containing; private boolean ignoreCase; /** * Constructor with containing = null and ignoreCase = false * @see #getContaining() * @see #isIgnoreCase() */ public MessageBodyContainsFilter() { containing = null; ignoreCase = false; } /** * @param token reference token the message body has to contain for acceptance * @param ignoreCase shall ignore Cases */ public MessageBodyContainsFilter(String token, boolean ignoreCase) { this.ignoreCase = ignoreCase; if (ignoreCase) { this.containing = token.toLowerCase(); } else { this.containing = token; } } @Override public boolean accept(Message aMessage) { log.debug(aMessage.toXML()); if(containing == null) { return false; } String body = aMessage.getBody(); if (body == null || body.equals("")) { return false; } if (ignoreCase) { return body.toLowerCase().contains(this.containing); } return body.contains(this.containing); } /** * containing getter method. * * @return the containing */ public String getContaining() { return containing; } /** * sets the phrase which should be contained in the message body * @param phrase the phrase which should be contained in the message body */ public void setContaining(String phrase) { this.containing = phrase; } /** * ignoreCase getter method. * * @return the ignoreCase */ public boolean isIgnoreCase() { return ignoreCase; } /** * @param ignoreCase */ public void setIgnoreCase(boolean ignoreCase) { this.ignoreCase = ignoreCase; } }
lechium/iOS1351Headers
usr/libexec/companionappd/SPError.h
<reponame>lechium/iOS1351Headers // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @interface SPError : NSObject { } + (_Bool)isValidationErrorCode:(long long)arg1; // IMP=0x000000010002bf88 + (id)errorWithCode:(long long)arg1 additionalDescription:(id)arg2; // IMP=0x000000010002be60 + (id)errorWithCode:(long long)arg1; // IMP=0x000000010002bc0c @end
teerapongt/marketplace-sample-apps
Freshworks-Samples/App-Development-Features/Advanced-Features/oauth2/shopify_oauth_app/app/app.js
$(document).ready(function() { app.initialized().then(function(client) { window.client = client; client.events.on('app.activated', function() { client.request.get('https://<%= oauth_iparams.subdomain %>.myshopify.com/admin/products.json', { isOAuth: true, headers: { 'X-Shopify-Access-Token': '<%= access_token %>' } }) .then(function(data) { let html = ''; const products = JSON.parse(data.response).products; if (products.length == 0) { $('#products').find('#products').append('No products'); } else { products.map(function(product) { html += `<li>${product.title}</li>`; }); $('#products').append(`<ul>${html}</ul>`); } }, function(err) { $('#products').append('Error displaying products'); }); }) }); });
AK391/mindspore
mindspore/ccsrc/plugin/device/cpu/kernel/eigen/matrix_inverse_cpu_kernel.cc
/** * Copyright 2021-2022 Huawei Technologies 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. */ #include "plugin/device/cpu/kernel/eigen/matrix_inverse_cpu_kernel.h" #include "plugin/device/cpu/kernel/eigen/eigen_common_utils.h" #include "Eigen/Dense" namespace mindspore { namespace kernel { namespace { constexpr size_t kMatrixInverseInputsNum = 1; constexpr size_t kMatrixInverseOutputsNum = 1; constexpr size_t kMatrixInverseInIndex = 0; constexpr size_t kMatrixInverseOutIndex = 0; } // namespace template <typename T> void MatrixInverseCpuKernelMod<T>::InitKernel(const CNodePtr &kernel_node) { MS_EXCEPTION_IF_NULL(kernel_node); kernel_name_ = AnfAlgo::GetCNodeName(kernel_node); size_t input_num = AnfAlgo::GetInputTensorNum(kernel_node); CHECK_KERNEL_INPUTS_NUM(input_num, kMatrixInverseInputsNum, kernel_name_); size_t output_num = AnfAlgo::GetOutputTensorNum(kernel_node); CHECK_KERNEL_OUTPUTS_NUM(output_num, kMatrixInverseOutputsNum, kernel_name_); auto input_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, kMatrixInverseInIndex); if (input_shape.size() < 2) { MS_LOG(EXCEPTION) << "The dim entered needs to be greater than 2, but " << input_shape.size() << " was taken"; } size_t last_index = input_shape.size() - 1; if (input_shape[last_index] != input_shape[last_index - 1]) { MS_LOG(EXCEPTION) << "The last two dimensions of the input matrix should be equal!"; } size_ = input_shape[last_index]; for (size_t i = 0; i < last_index - 1; i++) { batch_size_ *= input_shape[i]; } adjoint_ = AnfAlgo::GetNodeAttr<bool>(kernel_node, ADJOINT); } template <typename T> bool MatrixInverseCpuKernelMod<T>::Launch(const std::vector<kernel::AddressPtr> &inputs, const std::vector<kernel::AddressPtr> &, const std::vector<kernel::AddressPtr> &outputs) { auto input_addr = reinterpret_cast<T *>(inputs[kMatrixInverseInIndex]->addr); auto output_addr = reinterpret_cast<T *>(outputs[kMatrixInverseOutIndex]->addr); for (size_t i = 0; i < batch_size_; i++) { size_t offset = i * size_ * size_; Map<Matrix<T, RowMajor>> input(input_addr + offset, size_, size_); Map<Matrix<T, RowMajor>> output(output_addr + offset, size_, size_); output = input.inverse(); if (output.RowsAtCompileTime == 0 || output.ColsAtCompileTime == 0) { MS_LOG_EXCEPTION << kernel_name_ << " output shape is invalid."; } } return true; } } // namespace kernel } // namespace mindspore
mikandi/apptentive-android
apptentive/src/com/apptentive/android/sdk/model/ExtendedData.java
<filename>apptentive/src/com/apptentive/android/sdk/model/ExtendedData.java<gh_stars>0 /* * Copyright (c) 2014, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.sdk.model; import com.apptentive.android.sdk.Log; import org.json.JSONException; import org.json.JSONObject; /** * @author <NAME> */ public abstract class ExtendedData extends JSONObject { private static final String KEY_VERSION = "version"; private Type type = Type.unknown; protected ExtendedData() { init(); } protected ExtendedData(String json) throws JSONException { super(json); init(); } public String getTypeName() { return type.name(); } protected void setType(Type type) { this.type = type; } protected void setVersion(int version) { try { put(KEY_VERSION, version); } catch (JSONException e) { Log.w("Error adding %s to ExtendedData.", KEY_VERSION, e); } return; } protected abstract void init(); public enum Type { time, location, commerce, unknown; public static Type parse(String type) { try { return Type.valueOf(type); } catch (IllegalArgumentException e) { Log.v("Error parsing unknown ExtendedData.BaseType: " + type); } return unknown; } } }
macndev/Stntuple
geom/geom/THexCrystalMap.hh
#ifndef Stntuple_base_THexCrystalMap_hh #define Stntuple_base_THexCrystalMap_hh #include "Stntuple/geom/TDiskIndex.hh" #include "Stntuple/geom/TDiskCrystalMap.hh" class THexCrystalMap : public TDiskCrystalMap { protected: // hexagon vertices static TDiskIndex fgPos[6]; public: THexCrystalMap(double Size, double RMin, double RMax); THexCrystalMap(); ~THexCrystalMap(); virtual int GetFirst(int Ir) const { if (Ir == 0) return 0; else { printf(" THexCrystalMap::GetFirst ERROR: not implemented yet\n"); return -1; } } // total number of crystals per ring (including ones outside the disk) virtual int GetNCrystalsPerRing(int I) const { if (I == 0) return 1; else return 6*I; } virtual int GetNTotal() const { return 3*fNRings*(fNRings-1)+1 ; } virtual int GetRing(int I); virtual int GetRing(TDiskIndex* Index); virtual void GetPosition(int I, TVector2* Pos); virtual void GetPosition(TDiskIndex* Index, TVector2* Pos); virtual double GetRadius(TDiskIndex* Index); virtual double GetRadius(int I); virtual TDiskIndex& Pos(int I) { return fgPos[I]; } virtual int InsideCode(TDiskIndex* Index, double* Fraction); }; #endif
RanerL/analyzer
tests/juliet/testcases/CWE191_Integer_Underflow/s03/CWE191_Integer_Underflow__short_rand_sub_52b.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__short_rand_sub_52b.c Label Definition File: CWE191_Integer_Underflow.label.xml Template File: sources-sinks-52b.tmpl.c */ /* * @description * CWE: 191 Integer Underflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: sub * GoodSink: Ensure there will not be an underflow before subtracting 1 from data * BadSink : Subtract 1 from data, which can cause an Underflow * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef OMITBAD /* bad function declaration */ void CWE191_Integer_Underflow__short_rand_sub_52c_badSink(short data); void CWE191_Integer_Underflow__short_rand_sub_52b_badSink(short data) { CWE191_Integer_Underflow__short_rand_sub_52c_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE191_Integer_Underflow__short_rand_sub_52c_goodG2BSink(short data); void CWE191_Integer_Underflow__short_rand_sub_52b_goodG2BSink(short data) { CWE191_Integer_Underflow__short_rand_sub_52c_goodG2BSink(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE191_Integer_Underflow__short_rand_sub_52c_goodB2GSink(short data); void CWE191_Integer_Underflow__short_rand_sub_52b_goodB2GSink(short data) { CWE191_Integer_Underflow__short_rand_sub_52c_goodB2GSink(data); } #endif /* OMITGOOD */
musasesay/tesseract-ocr.github.io
3.x/a00844.js
<filename>3.x/a00844.js var a00844 = [ [ "MAX_MSG", "a00844.html#aa24597a54a085c6c2c33b64138f09eff", null ], [ "BADERRACTION", "a00844.html#a7e1ef09aa091c698c9fe7e38cae89a1c", null ] ];
RunCoding/runcoding.github.io
develop/back_end/java/base-java/src/main/java/com/runcoding/learn/proxy/ProxyFactory.java
<reponame>RunCoding/runcoding.github.io<filename>develop/back_end/java/base-java/src/main/java/com/runcoding/learn/proxy/ProxyFactory.java package com.runcoding.learn.proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory implements InvocationHandler { private static Logger logger = LoggerFactory.getLogger(ProxyFactory.class); private Object object; public ProxyFactory() { } public Object createProxy(Object object){ this.object = object; return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { object = method.invoke(object, args); return object; } }
Yamakaja/irc-client
client/src/main/java/me/yamakaja/irc/client/network/event/channel/TopicEvent.java
<gh_stars>0 package me.yamakaja.irc.client.network.event.channel; import me.yamakaja.irc.client.chat.ChatChannel; import net.lahwran.fevents.Event; import java.util.Date; /** * Created by Yamakaja on 04.02.17. */ public class TopicEvent extends Event { private ChatChannel channel; public TopicEvent(ChatChannel channel) { this.channel = channel; } public ChatChannel getChannel() { return channel; } public String getTopic() { return channel.getTopic(); } public Date getSetTime() { return channel.getTopicTime(); } public String getTopicSetter() { return channel.getTopicSetter(); } }
ikaushikpal/DS-450-python
LinkedList/Reorder List.py
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param A : head node of linked list # @return the head node in the linked list # Time Complexity : O(n) # Space Complexity : O(n) def reorderList(self, root): if not root or not root.next: return root linkedListAddresses = [] ptr = root while ptr: linkedListAddresses.append(ptr) ptr = ptr.next i, j = 0, len(linkedListAddresses)-1 main_head = main_tail= None while i<=j: leftNode, rightNode = linkedListAddresses[i], linkedListAddresses[j] if main_head == None: main_head = leftNode main_head.next = rightNode main_tail = rightNode else: main_tail.next = leftNode main_tail = leftNode main_tail.next = rightNode main_tail = rightNode i += 1 j -= 1 if main_tail: main_tail.next = None return main_head # Efficient Solution: # 1) Find the middle point using tortoise and hare method. # 2) Split the linked list into two halves using found middle point in step 1. # 3) Reverse the second half. # 4) Do alternate merge of first and second halves. # Time Complexity : O(n) # Space Complexity : O(1) def reverseLL(self, root): prevNode = currentNode = None nextNode = root while nextNode: prevNode = currentNode currentNode = nextNode nextNode = nextNode.next currentNode.next = prevNode return currentNode def splitLL(self, root): if root is None: return None, None slow = root fast = root.next prev = None while fast: prev = slow slow = slow.next fast = fast.next if fast: fast = fast.next head1 = root prev.next = None head2 = slow return head1, head2 def reorderList(self, root): if not root or not root.next: return root leftHead, rightHead = self.splitLL(root) rightHead = self.reverseLL(rightHead) leftPtr, rightPtr = leftHead, rightHead main_head = main_tail = None while leftPtr and rightPtr: if main_head == None: main_head = main_tail = leftPtr else: main_tail.next = leftPtr main_tail = leftPtr leftPtr = leftPtr.next main_tail.next = rightPtr main_tail = rightPtr rightPtr = rightPtr.next if rightPtr: #if odd no of nodes then main_tail.next = rightPtr main_tail = rightPtr if main_tail: main_tail.next = None return main_head # both approach took same time , lol root = ListNode(10) root.next = ListNode(20) root.next.next = ListNode(30) root.next.next.next = ListNode(40) x = Solution().reorderList(root) while x: print(x.val, end=' ') x = x.next
columbus9963/kubernetes
test/e2e/framework/deployment/logging.go
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 deployment import ( appsv1 "k8s.io/api/apps/v1" clientset "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/test/e2e/framework" testutils "k8s.io/kubernetes/test/utils" ) func logReplicaSetsOfDeployment(deployment *appsv1.Deployment, allOldRSs []*appsv1.ReplicaSet, newRS *appsv1.ReplicaSet) { testutils.LogReplicaSetsOfDeployment(deployment, allOldRSs, newRS, framework.Logf) } func logPodsOfDeployment(c clientset.Interface, deployment *appsv1.Deployment, rsList []*appsv1.ReplicaSet) { testutils.LogPodsOfDeployment(c, deployment, rsList, framework.Logf) }
Neon-FN/Neon-Client
Neon Client/SDK/FN_LobbyGadgetButton_classes.hpp
<gh_stars>0 #pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass LobbyGadgetButton.LobbyGadgetButton_C // 0x0059 (0x0291 - 0x0238) class ULobbyGadgetButton_C : public UCommonUserWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0238(0x0008) (Transient, DuplicateTransient) class UPanelButton_C* Button; // 0x0240(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* EmptySlot; // 0x0248(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UFortMultiSizeItemCard* Item; // 0x0250(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) TArray<class UFortWorldItemDefinition*> DesignTestItemDefinitions; // 0x0258(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class UFortWorldItem* GadgetItem; // 0x0268(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FScriptMulticastDelegate OnButtonClicked; // 0x0270(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable) struct FScriptMulticastDelegate OnButtonHovered; // 0x0280(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable) bool bLocked; // 0x0290(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass LobbyGadgetButton.LobbyGadgetButton_C"); return ptr; } void GetLocked(bool* bLocked); void SetLocked(bool bLocked); void GetGadgetItem(class UFortWorldItem** GadgetItem); void Refresh(class UFortWorldItem* WorldItem); void PreConstruct(bool* IsDesignTime); void BndEvt__Button_K2Node_ComponentBoundEvent_81_CommonButtonClicked__DelegateSignature(class UCommonButton* Button); void BndEvt__Button_K2Node_ComponentBoundEvent_96_CommonButtonClicked__DelegateSignature(class UCommonButton* Button); void ExecuteUbergraph_LobbyGadgetButton(int EntryPoint); void OnButtonHovered__DelegateSignature(class ULobbyGadgetButton_C* GadgetButton); void OnButtonClicked__DelegateSignature(class ULobbyGadgetButton_C* GadgetButton); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
cohadar/hackerrank
contests/WeekOfCode-18/Rhombographs/backup1.java
<reponame>cohadar/hackerrank import java.util.*; import java.io.*; /* <NAME> */ public class Rhombographs { static void firstCombination(int[] A, int y, int r) { int count = r; int x = 0; while (count > 0) { if (x == y) { A[x++] = -1; } else{ A[x++] = 1; count--; } } while (x < A.length) { if (x == y) { A[x++] = -1; } else { A[x++] = 0; } } } static boolean nextCombination(int[] A, int y, int r) { int erased = 0; int x = A.length - 1; while (x >= 0 && A[x] != 0) { if (x != y) { A[x] = 0; erased++; } x--; } int z = x; x--; while (x >= 0) { if (x != y) { if (A[x] == 1) { A[x] = 0; A[z] = 1; x = z + 1; while (erased > 0) { if (x != y) { A[x] = 1; erased--; } x++; } return true; } } x--; } return false; } static boolean generate(int n, int r) { assert r < n; int[][] G = new int[n][n]; for (int y = 0; y < n; y++) { firstCombination(G[y], y, r); } if (isUndirected(G) && isRhomboGraph(G)) { int m = n * r / 2; int z = n * n - 2 * m; debug(n, r, m, z); debug(G); return true; } int c = 0; while (true) { c = 0; for (int y = 0; y < n; y++) { if (nextCombination(G[y], y, r)) { break; } else { firstCombination(G[y], y, r); c++; } } if (c == n) { break; } if (isUndirected(G) && isRhomboGraph(G)) { int m = n * r / 2; int z = n * n - 2 * m; debug(n, r, m, z); debug(G); return true; } } return false; } static boolean isUndirected(int[][] G) { int n = G.length; for (int a = 0; a < n; a++) { for (int b = 0; b < n; b++) { if (G[a][b] != G[b][a]) { return false; } } } return true; } static boolean isRhomboGraph(int[][] G) { int n = G.length; for (int a = 0; a < n - 1; a++) { ok: for (int b = a + 1; b < n; b++) { if (G[a][b] == 0) { for (int c = 0; c < n - 1; c++) { for (int d = c + 1; d < n; d++) { if (c != a && d != a && c != b && d != b) { if (G[a][c] == 1 && G[c][b] == 1 && G[a][d] == 1 && G[d][b] == 1) { continue ok; } } } } return false; } } } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); for (int n = 2; n < 10; n++) { for (int r = n - 1; r > 0; r--) { if ((n * r) % 2 != 0) { continue; } int m = n * r / 2; int z = n * n - 2 * m; if (z % n != 0) { continue; } if (generate(n, r) == false) { assert z / n > r; debug(String.format("formula is bad for: n=%d, r=%d, m=%d, z=%d", n, r, m, z)); } else { assert z / n <= r; } } } } static boolean DEBUG = true; static void debug(Object...os) { if (!DEBUG) { return; } System.err.printf("%.65536s\n", Arrays.deepToString(os)); } static void debug(int[][] M) { if (!DEBUG) { return; } for (int y = 0; y < M.length; y++) { for (int x = 0; x < M[0].length; x++) { System.err.printf("%-2d", (M[y][x] == -1) ? 0 : M[y][x]); } System.err.println(); } System.err.println(); } }
hadryansalles/ray-tracing-from-the-ground-up
source/Utilities/Vector3D.hpp
#pragma once #include <math.h> #include "Matrix.hpp" class Normal; class Point3D; class Vector3D { public: double x, y, z; public: Vector3D(); // default constructor Vector3D(double a); // constructor Vector3D(double _x, double _y, double _z); // constructor Vector3D(const Vector3D& v); // copy constructor Vector3D(const Normal& n); // constructs a vector from a Normal Vector3D(const Point3D& p); // constructs a vector from a point ~Vector3D (void); // destructor Vector3D& operator= (const Vector3D& rhs); // assignment operator Vector3D& operator= (const Normal& rhs); // assign a Normal to a vector Vector3D& operator= (const Point3D& rhs); // assign a Point3D to a vector Vector3D operator- (void) const; // unary minus double length(void); // length double len_squared(void); // square of the length Vector3D operator* (const double a) const; // multiplication by a double on the right Vector3D operator/ (const double a) const; // division by a double Vector3D operator+ (const Vector3D& v) const; // addition Vector3D& operator+= (const Vector3D& v); // compound addition Vector3D operator- (const Vector3D& v) const; // subtraction double operator* (const Vector3D& b) const; // dot product Vector3D operator^ (const Vector3D& v) const; // cross product void normalize(void); // convert vector to a unit vector Vector3D& hat(void); // return a unit vector, and normalize the vector }; Vector3D operator* (const double a, const Vector3D& v); Vector3D operator* (const Matrix& mat, const Vector3D& v);
uk-gov-mirror/hmrc.view-external-guidance-frontend
app/core/models/ocelot/stanzas/Stanza.scala
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package core.models.ocelot.stanzas import play.api.libs.json._ import core.models.ocelot.{Labels, Label, Page} trait Stanza { val visual: Boolean = false val next: Seq[String] = Nil val links: List[String] = Nil val labels: List[Label] = Nil val labelRefs: List[String] = Nil } trait VisualStanza extends Stanza { val stack: Boolean override val visual: Boolean = true } trait Populated trait Evaluate { def eval(labels: Labels): (String, Labels) } trait DataInput { def eval(value: String, page: Page, labels: Labels): (Option[String], Labels) def validInput(value: String): Option[String] } case object EndStanza extends Stanza object Stanza { implicit val reads: Reads[Stanza] = (js: JsValue) => { (js \ "type").validate[String] match { case err @ JsError(_) => err case JsSuccess(typ, _) => typ match { case "QuestionStanza" => js.validate[QuestionStanza] case "InstructionStanza" => js.validate[InstructionStanza] case "CalloutStanza" => js.validate[CalloutStanza] case "PageStanza" => js.validate[PageStanza] case "ValueStanza" => js.validate[ValueStanza] case "CalculationStanza" => js.validate[CalculationStanza] case "SequenceStanza" => js.validate[SequenceStanza] case "ChoiceStanza" => js.validate[ChoiceStanza] case "InputStanza" => js.validate[InputStanza] case "RowStanza" => js.validate[RowStanza] case "Choice" => js.validate[Choice] case "Calculation" => js.validate[Calculation] case "EndStanza" => JsSuccess(EndStanza) case typeName => JsError(JsonValidationError(Seq("Stanza"), typeName)) } } } implicit val writes: Writes[Stanza] = { case q: QuestionStanza => Json.obj("type" -> "QuestionStanza") ++ Json.toJsObject[QuestionStanza](q) case i: InstructionStanza => Json.obj("type" -> "InstructionStanza") ++ Json.toJsObject[InstructionStanza](i) case c: CalloutStanza => Json.obj("type" -> "CalloutStanza") ++ Json.toJsObject[CalloutStanza](c) case p: PageStanza => Json.obj("type" -> "PageStanza") ++ Json.toJsObject[PageStanza](p) case v: ValueStanza => Json.obj("type" -> "ValueStanza") ++ Json.toJsObject[ValueStanza](v) case c: CalculationStanza => Json.obj( "type" -> "CalculationStanza") ++ Json.toJsObject[CalculationStanza](c) case s: SequenceStanza => Json.obj( "type" -> "SequenceStanza") ++ Json.toJsObject[SequenceStanza](s) case c: ChoiceStanza => Json.obj("type" -> "ChoiceStanza") ++ Json.toJsObject[ChoiceStanza](c) case i: InputStanza => Json.obj("type" -> "InputStanza") ++ Json.toJsObject[InputStanza](i) case r: RowStanza => Json.obj( "type" -> "RowStanza") ++ Json.toJsObject[RowStanza](r) case c: Choice => Json.obj("type" -> "Choice") ++ Json.toJsObject[Choice](c) case c: Calculation => Json.obj( "type" -> "Calculation") ++ Json.toJsObject[Calculation](c) case EndStanza => Json.obj("type" -> "EndStanza") case s => Json.toJson("") } }
ael-noblegas/pychron
pychron/processing/analyses/view/magnitude_editor.py
<reponame>ael-noblegas/pychron # =============================================================================== # Copyright 2014 <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. # =============================================================================== # ============= enthought library imports ======================= from __future__ import absolute_import from pyface.qt import QtCore, QtGui # ============= standard library imports ======================== # ============= local library imports ========================== from traitsui.qt4.table_editor import TableDelegate from traitsui.table_column import ObjectColumn # class Bar(QtGui.QFrame): # bar_width = 10 # # def paintEvent(self, evt): # qp = QtGui.QPainter() # qp.begin(self) # # qp.setBrush(QtGui.QColor(*self.value)) # qp.drawRect(0, 0, self.bar_width, 20) # qp.end() # # class _MagnitudeEditor(Editor): # def init(self, parent): # self.control = Bar() # # def update_editor(self): # if self.control: # self.control.bar_width = self.value # # # class MagnitudeEditor(BasicEditorFactory): # klass = _MagnitudeEditor class MagnitudeRenderer(TableDelegate): bar_width = 50 def editorEvent(self, event, model, option, index): pass def paint(self, painter, option, index): # column = index.model()._editor.columns[index.column()] obj = index.data(QtCore.Qt.UserRole) # v = column.get_raw_value(obj) v = obj.get_percent_value() painter.save() # painter.begin(self) # qp.setBrush(QtGui.QColor(*self.value)) brush = QtGui.QBrush(QtCore.Qt.SolidPattern) brush.setColor(QtGui.QColor(255, 0, 0)) rect = option.rect w = rect.width() rect.setWidth(w * min(1.0, v)) painter.fillRect(rect, brush) painter.restore() class MagnitudeColumn(ObjectColumn): def __init__(self, **traits): """ Initializes the object. """ super(MagnitudeColumn, self).__init__(**traits) # force the renderer to be a magnitude renderer self.renderer = MagnitudeRenderer() # ============= EOF =============================================
Mr-Devin/GraphicAlgorithm
003_Stochastic Light Culling/ShadowmapPass.cpp
#include "ShadowmapPass.h" #include "Interface.h" #include "Common.h" #include "Utils.h" #include "Sponza.h" #include "Shader.h" #include <GL/glew.h> #include <GLM/gtc/matrix_transform.hpp> #include <GLM/gtc/type_ptr.hpp> CShadowmapPass::CShadowmapPass(const std::string& vPassName, int vExcutionOrder) : IRenderPass(vPassName, vExcutionOrder) { } CShadowmapPass::~CShadowmapPass() { } void CShadowmapPass::initV() { m_pShader = std::make_shared<CShader>("Shadowmap_VS.glsl", "Shadowmap_FS.glsl"); m_pSponza = std::dynamic_pointer_cast<CSponza>(ElayGraphics::ResourceManager::getGameObjectByName("Sponza")); auto TextureConfig4Color = std::make_shared<ElayGraphics::STexture>(); auto TextureConfig4Depth = std::make_shared<ElayGraphics::STexture>(); genTexture(TextureConfig4Color); TextureConfig4Depth->InternalFormat = GL_DEPTH_COMPONENT32F; TextureConfig4Depth->ExternalFormat = GL_DEPTH_COMPONENT; TextureConfig4Depth->DataType = GL_FLOAT; TextureConfig4Depth->Type4MinFilter = GL_LINEAR; TextureConfig4Depth->Type4MagFilter = GL_LINEAR; TextureConfig4Depth->Width = TextureConfig4Depth->Height = m_ShadowmapResolution; TextureConfig4Depth->Type4WrapS = TextureConfig4Depth->Type4WrapT = GL_CLAMP_TO_BORDER; TextureConfig4Depth->BorderColor = { 0,0,0,0 }; TextureConfig4Depth->TextureAttachmentType = ElayGraphics::STexture::ETextureAttachmentType::DepthTexture; genTexture(TextureConfig4Depth); m_FBO = genFBO({ TextureConfig4Color, TextureConfig4Depth }); ElayGraphics::ResourceManager::registerSharedData("LightDepthTexture", TextureConfig4Depth); m_pShader->activeShader(); m_pShader->setMat4UniformValue("u_ModelMatrix", glm::value_ptr(m_pSponza->getModelMatrix())); glm::mat4 LightProjectionMatrix = ElayGraphics::ResourceManager::getSharedDataByName<glm::mat4>("LightProjectionMatrix"); glm::mat4 LightViewMatrix = ElayGraphics::ResourceManager::getSharedDataByName<glm::mat4>("LightViewMatrix"); m_pShader->setMat4UniformValue("u_LightVPMatrix", glm::value_ptr(LightProjectionMatrix * LightViewMatrix)); m_pSponza->initModel(*m_pShader); } void CShadowmapPass::updateV() { glBindFramebuffer(GL_FRAMEBUFFER, m_FBO); glClear(GL_DEPTH_BUFFER_BIT); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glViewport(0, 0, m_ShadowmapResolution, m_ShadowmapResolution); m_pShader->activeShader(); #ifdef _DEBUG glm::mat4 LightProjectionMatrix = ElayGraphics::ResourceManager::getSharedDataByName<glm::mat4>("LightProjectionMatrix"); glm::mat4 LightViewMatrix = ElayGraphics::ResourceManager::getSharedDataByName<glm::mat4>("LightViewMatrix"); m_pShader->setMat4UniformValue("u_LightVPMatrix", glm::value_ptr(LightProjectionMatrix * LightViewMatrix)); #endif m_pSponza->updateModel(*m_pShader); glViewport(0, 0, ElayGraphics::WINDOW_KEYWORD::getWindowWidth(), ElayGraphics::WINDOW_KEYWORD::getWindowHeight()); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glBindFramebuffer(GL_FRAMEBUFFER, 0); }
Benn-Co/refactored-broccoli
rebro/src/java/org/netlib/lapack/Dlazq3.java
package org.netlib.lapack; import org.netlib.util.*; public final class Dlazq3 { public static void dlazq3(int i, intW intw, double ad[], int j, int k, doubleW doublew, doubleW doublew1, doubleW doublew2, doubleW doublew3, intW intw1, intW intw2, intW intw3, boolean flag, intW intw4, doubleW doublew4, doubleW doublew5, doubleW doublew6, doubleW doublew7, doubleW doublew8, doubleW doublew9) { int j1 = 0; double d = 0.0; doubleW doublew10 = new doubleW(0.0); double d4 = 0.0; double d5 = 0.0; double d8 = 0.0; double d9 = 0.0; j1 = intw.val; d = Dlamch.dlamch("Precision"); d4 = Dlamch.dlamch("Safe minimum"); d8 = d * 100.0; d9 = Math.pow(d8, 2.0); doublew10.val = 0.0; label0: do { int k1; label1: { label2: { if(intw.val < i) return; if(intw.val != i) { k1 = 4 * intw.val + k; if(intw.val == i + 1) break label1; if((ad[(k1 - 5 - 1) + j] > d9 * (doublew1.val + ad[(k1 - 3 - 1) + j])) && (ad[(k1 - 2 * k - 4 - 1) + j] > d9 * ad[(k1 - 7 - 1) + j])) break label2; } ad[(4 * intw.val - 3 - 1) + j] = ad[((4 * intw.val + k) - 3 - 1) + j] + doublew1.val; intw.val = intw.val - 1; continue; } if((ad[(k1 - 9 - 1) + j] > d9 * doublew1.val) && (ad[(k1 - 2 * k - 8 - 1) + j] > d9 * ad[(k1 - 11 - 1) + j])) break label0; } if(ad[(k1 - 3 - 1) + j] > ad[(k1 - 7 - 1) + j]) { double d2 = ad[(k1 - 3 - 1) + j]; ad[(k1 - 3 - 1) + j] = ad[(k1 - 7 - 1) + j]; ad[(k1 - 7 - 1) + j] = d2; } if(ad[(k1 - 5 - 1) + j] > ad[(k1 - 3 - 1) + j] * d9) { d5 = 0.5 * ((ad[(k1 - 7 - 1) + j] - ad[(k1 - 3 - 1) + j]) + ad[(k1 - 5 - 1) + j]); double d3 = ad[(k1 - 3 - 1) + j] * (ad[(k1 - 5 - 1) + j] / d5); if(d3 <= d5) d3 = ad[(k1 - 3 - 1) + j] * (ad[(k1 - 5 - 1) + j] / (d5 * (1.0 + Math.sqrt(1.0 + d3 / d5)))); else d3 = ad[(k1 - 3 - 1) + j] * (ad[(k1 - 5 - 1) + j] / (d5 + Math.sqrt(d5) * Math.sqrt(d5 + d3))); d5 = ad[(k1 - 7 - 1) + j] + (d3 + ad[(k1 - 5 - 1) + j]); ad[(k1 - 3 - 1) + j] = ad[(k1 - 3 - 1) + j] * (ad[(k1 - 7 - 1) + j] / d5); ad[(k1 - 7 - 1) + j] = d5; } ad[(4 * intw.val - 7 - 1) + j] = ad[(k1 - 7 - 1) + j] + doublew1.val; ad[(4 * intw.val - 3 - 1) + j] = ad[(k1 - 3 - 1) + j] + doublew1.val; intw.val = intw.val - 2; } while(true); label3: { if(((doublew.val <= 0.0) || (intw.val < j1)) && (1.5 * ad[((4 * i + k) - 3 - 1) + j] < ad[((4 * intw.val + k) - 3 - 1) + j])) { int l = 4 * (i + intw.val); int i1 = 4 * i; for(int l1 = ((2 * ((i + intw.val) - 1) - 4 * i) + 4) / 4; l1 > 0; l1--) { double d7 = ad[(i1 - 3 - 1) + j]; ad[(i1 - 3 - 1) + j] = ad[(l - i1 - 3 - 1) + j]; ad[(l - i1 - 3 - 1) + j] = d7; d7 = ad[(i1 - 2 - 1) + j]; ad[(i1 - 2 - 1) + j] = ad[(l - i1 - 2 - 1) + j]; ad[(l - i1 - 2 - 1) + j] = d7; d7 = ad[(i1 - 1 - 1) + j]; ad[(i1 - 1 - 1) + j] = ad[(l - i1 - 5 - 1) + j]; ad[(l - i1 - 5 - 1) + j] = d7; d7 = ad[(i1 - 1) + j]; ad[(i1 - 1) + j] = ad[(l - i1 - 4 - 1) + j]; ad[(l - i1 - 4 - 1) + j] = d7; i1 += 4; } if(intw.val - i <= 4) { ad[((4 * intw.val + k) - 1 - 1) + j] = ad[((4 * i + k) - 1 - 1) + j]; ad[(4 * intw.val - k - 1) + j] = ad[(4 * i - k - 1) + j]; } doublew5.val = Math.min(doublew5.val, ad[((4 * intw.val + k) - 1 - 1) + j]); ad[((4 * intw.val + k) - 1 - 1) + j] = Util.min(ad[((4 * intw.val + k) - 1 - 1) + j], ad[((4 * i + k) - 1 - 1) + j], ad[((4 * i + k + 3) - 1) + j]); ad[(4 * intw.val - k - 1) + j] = Util.min(ad[(4 * intw.val - k - 1) + j], ad[(4 * i - k - 1) + j], ad[(((4 * i - k) + 4) - 1) + j]); doublew3.val = Util.max(doublew3.val, ad[((4 * i + k) - 3 - 1) + j], ad[((4 * i + k + 1) - 1) + j]); doublew.val = 0.0; } if((doublew.val < 0.0) || (d4 * doublew3.val < Util.min(ad[((4 * intw.val + k) - 1 - 1) + j], ad[((4 * intw.val + k) - 9 - 1) + j], doublew5.val + ad[(4 * intw.val - k - 1) + j]))) { Dlazq4.dlazq4(i, intw.val, ad, j, k, j1, doublew.val, doublew4.val, doublew5.val, doublew6.val, doublew7.val, doublew8.val, doublew9, intw4, doublew10); do { Dlasq5.dlasq5(i, intw.val, ad, j, k, doublew9.val, doublew, doublew4, doublew5, doublew6, doublew7, doublew8, flag); intw3.val = intw3.val + ((intw.val - i) + 2); intw2.val = intw2.val + 1; if((doublew.val >= 0.0) && (doublew4.val > 0.0)) break label3; if((((doublew.val < 0.0) && (doublew4.val > 0.0)) && (ad[(4 * (intw.val - 1) - k - 1) + j] < d8 * (doublew1.val + doublew7.val))) && (Math.abs(doublew6.val) < d8 * doublew1.val)) { ad[(((4 * (intw.val - 1) - k) + 2) - 1) + j] = 0.0; doublew.val = 0.0; break label3; } if(doublew.val < 0.0) { intw1.val = intw1.val + 1; if(intw4.val < -22) doublew9.val = 0.0; else if(doublew4.val > 0.0) { doublew9.val = (doublew9.val + doublew.val) * (1.0 - 2.0 * d); intw4.val = intw4.val - 11; } else { doublew9.val = 0.25 * doublew9.val; intw4.val = intw4.val - 12; } continue; } if(doublew.val == doublew.val) break; doublew9.val = 0.0; } while(true); } Dlasq6.dlasq6(i, intw.val, ad, j, k, doublew, doublew4, doublew5, doublew6, doublew7, doublew8); intw3.val = intw3.val + ((intw.val - i) + 2); intw2.val = intw2.val + 1; doublew9.val = 0.0; } if(doublew9.val < doublew1.val) { doublew2.val = doublew2.val + doublew9.val; d5 = doublew1.val + doublew2.val; doublew2.val = doublew2.val - (d5 - doublew1.val); } else { d5 = doublew1.val + doublew9.val; doublew2.val = (doublew1.val - (d5 - doublew9.val)) + doublew2.val; } doublew1.val = d5; } }
gordon-elliott/glod
src/a_tuin/unittests/metadata/test_args_field_group.py
__copyright__ = 'Copyright(c) <NAME> 2017' """ """ from unittest import TestCase from a_tuin.metadata.field import StringField, IntField from a_tuin.metadata.field_group import DictFieldGroup from a_tuin.metadata.mapping import Mapping from a_tuin.metadata.object_field_group_meta import ObjectFieldGroupBase class Fixture(ObjectFieldGroupBase): public_interface = ( IntField('id', is_mutable=False), StringField('purpose'), StringField('name'), StringField('account_no'), StringField('IBAN', use_custom_properties=True), ) def __init__(self, *args, named=None, **kwargs): self._named = named @property def IBAN(self): return self._IBAN @IBAN.setter def IBAN(self, value): self._IBAN = 'IBAN:' + value class TestArgsFieldGroup(TestCase): def test_all_args_passed(self): named = 'named parameter' identity = 2002 purpose = 'purpose' name = 'name' account_no = '303820G' fixture = Fixture(identity, purpose, named=named, name=name, account_no=account_no) self.assertEqual(name, fixture.name) self.assertEqual(named, fixture._named) self.assertEqual(identity, fixture._id) self.assertEqual(purpose, fixture._purpose) self.assertEqual(name, fixture._name) self.assertEqual(account_no, fixture._account_no) def test_cast_from(self): csv_fields = DictFieldGroup(Fixture.public_interface) csv_to_constructor = Mapping(csv_fields, Fixture.constructor_parameters) named = 'named parameter' identity = 83993 purpose = 'purpose' name = 'name' acc_no = '38387RR' iban = 'IBAN 30383093 30 30 03' cast_values = csv_to_constructor.cast_from({ 'id': identity, 'purpose': purpose, 'name': name, 'account_no': acc_no, 'IBAN': iban, }) from_csv = Fixture(named=named, **cast_values) self.assertEqual(named, from_csv._named) self.assertEqual(identity, from_csv._id) self.assertEqual(purpose, from_csv._purpose) self.assertEqual(iban, from_csv._IBAN) def test_update_from_dict(self): named = 'named parameter' identity = 83993 purpose = 'purpose' name = 'name' acc_no = '38387RR' iban = '3038 3093 3030 03' initial_values = { 'id': identity, 'purpose': purpose, 'name': name, } fixture = Fixture(named=named, **initial_values) self.assertEqual(named, fixture._named) self.assertEqual(identity, fixture._id) self.assertEqual(purpose, fixture._purpose) self.assertEqual(None, fixture._IBAN) self.assertEqual(None, fixture._account_no) new_name = 'updated' update_values = { 'id': 88888, # this update is ignored 'name': new_name, 'account_no': acc_no, 'IBAN': iban, } fixture.update_from(update_values) self.assertEqual(named, fixture._named) self.assertEqual(identity, fixture.id) # id is unchanged self.assertEqual(new_name, fixture.name) self.assertEqual(purpose, fixture.purpose) self.assertEqual(acc_no, fixture.account_no) self.assertEqual('IBAN:' + iban, fixture.IBAN)
RusDavies/indigo
indigo_mac_drivers/ccd_ica/indigo_ica_ptp_canon.h
<filename>indigo_mac_drivers/ccd_ica/indigo_ica_ptp_canon.h // // indigo_ica_canon.h // IndigoApps // // Created by <NAME> on 11/07/2017. // Copyright © 2017 CloudMakers, s. r. o. All rights reserved. // #import <Foundation/Foundation.h> #import "indigo_ica_ptp.h" enum PTPCanonOperationCodeEnum { PTPRequestCodeCanonGetStorageIDs = 0x9101, PTPRequestCodeCanonGetStorageInfo = 0x9102, PTPRequestCodeCanonGetObjectInfo = 0x9103, PTPRequestCodeCanonGetObject = 0x9104, PTPRequestCodeCanonDeleteObject = 0x9105, PTPRequestCodeCanonFormatStore = 0x9106, PTPRequestCodeCanonGetPartialObject = 0x9107, PTPRequestCodeCanonGetDeviceInfoEx = 0x9108, PTPRequestCodeCanonGetObjectInfoEx = 0x9109, PTPRequestCodeCanonGetThumbEx = 0x910A, PTPRequestCodeCanonSendPartialObject = 0x910B, PTPRequestCodeCanonSetObjectAttributes = 0x910C, PTPRequestCodeCanonGetObjectTime = 0x910D, PTPRequestCodeCanonSetObjectTime = 0x910E, PTPRequestCodeCanonRemoteRelease = 0x910F, PTPRequestCodeCanonSetDevicePropValueEx = 0x9110, PTPRequestCodeCanonGetRemoteMode = 0x9113, PTPRequestCodeCanonSetRemoteMode = 0x9114, PTPRequestCodeCanonSetEventMode = 0x9115, PTPRequestCodeCanonGetEvent = 0x9116, PTPRequestCodeCanonTransferComplete = 0x9117, PTPRequestCodeCanonCancelTransfer = 0x9118, PTPRequestCodeCanonResetTransfer = 0x9119, PTPRequestCodeCanonPCHDDCapacity = 0x911A, PTPRequestCodeCanonSetUILock = 0x911B, PTPRequestCodeCanonResetUILock = 0x911C, PTPRequestCodeCanonKeepDeviceOn = 0x911D, PTPRequestCodeCanonSetNullPacketMode = 0x911E, PTPRequestCodeCanonUpdateFirmware = 0x911F, PTPRequestCodeCanonTransferCompleteDT = 0x9120, PTPRequestCodeCanonCancelTransferDT = 0x9121, PTPRequestCodeCanonSetWftProfile = 0x9122, PTPRequestCodeCanonGetWftProfile = 0x9123, PTPRequestCodeCanonSetProfileToWft = 0x9124, PTPRequestCodeCanonBulbStart = 0x9125, PTPRequestCodeCanonBulbEnd = 0x9126, PTPRequestCodeCanonRequestDevicePropValue = 0x9127, PTPRequestCodeCanonRemoteReleaseOn = 0x9128, PTPRequestCodeCanonRemoteReleaseOff = 0x9129, PTPRequestCodeCanonRegistBackgroundImage = 0x912A, PTPRequestCodeCanonChangePhotoStudioMode = 0x912B, PTPRequestCodeCanonGetPartialObjectEx = 0x912C, PTPRequestCodeCanonResetMirrorLockupState = 0x9130, PTPRequestCodeCanonPopupBuiltinFlash = 0x9131, PTPRequestCodeCanonEndGetPartialObjectEx = 0x9132, PTPRequestCodeCanonMovieSelectSWOn = 0x9133, PTPRequestCodeCanonMovieSelectSWOff = 0x9134, PTPRequestCodeCanonGetCTGInfo = 0x9135, PTPRequestCodeCanonGetLensAdjust = 0x9136, PTPRequestCodeCanonSetLensAdjust = 0x9137, PTPRequestCodeCanonGetMusicInfo = 0x9138, PTPRequestCodeCanonCreateHandle = 0x9139, PTPRequestCodeCanonSendPartialObjectEx = 0x913A, PTPRequestCodeCanonEndSendPartialObjectEx = 0x913B, PTPRequestCodeCanonSetCTGInfo = 0x913C, PTPRequestCodeCanonSetRequestOLCInfoGroup = 0x913D, PTPRequestCodeCanonSetRequestRollingPitchingLevel = 0x913E, PTPRequestCodeCanonGetCameraSupport = 0x913F, PTPRequestCodeCanonSetRating = 0x9140, PTPRequestCodeCanonRequestInnerDevelopStart = 0x9141, PTPRequestCodeCanonRequestInnerDevelopParamChange = 0x9142, PTPRequestCodeCanonRequestInnerDevelopEnd = 0x9143, PTPRequestCodeCanonGpsLoggingDataMode = 0x9144, PTPRequestCodeCanonGetGpsLogCurrentHandle = 0x9145, PTPRequestCodeCanonInitiateViewfinder = 0x9151, PTPRequestCodeCanonTerminateViewfinder = 0x9152, PTPRequestCodeCanonGetViewFinderData = 0x9153, PTPRequestCodeCanonDoAf = 0x9154, PTPRequestCodeCanonDriveLens = 0x9155, PTPRequestCodeCanonDepthOfFieldPreview = 0x9156, PTPRequestCodeCanonClickWB = 0x9157, PTPRequestCodeCanonZoom = 0x9158, PTPRequestCodeCanonZoomPosition = 0x9159, PTPRequestCodeCanonSetLiveAfFrame = 0x915A, PTPRequestCodeCanonTouchAfPosition = 0x915B, PTPRequestCodeCanonSetLvPcFlavoreditMode = 0x915C, PTPRequestCodeCanonSetLvPcFlavoreditParam = 0x915D, PTPRequestCodeCanonAfCancel = 0x9160, PTPRequestCodeCanonSetDefaultCameraSetting = 0x91BE, PTPRequestCodeCanonGetAEData = 0x91BF, PTPRequestCodeCanonNotifyNetworkError = 0x91E8, PTPRequestCodeCanonAdapterTransferProgress = 0x91E9, PTPRequestCodeCanonTransferComplete2 = 0x91F0, PTPRequestCodeCanonCancelTransfer2 = 0x91F1, PTPRequestCodeCanonFAPIMessageTX = 0x91FE, PTPRequestCodeCanonFAPIMessageRX = 0x91FF }; enum PTPCanonResponseCodeEnum { PTPResponseCodeCanonUnknownCommand = 0xA001, PTPResponseCodeCanonOperationRefused = 0xA005, PTPResponseCodeCanonLensCover = 0xA006, PTPResponseCodeCanonBatteryLow = 0xA101, PTPResponseCodeCanonNotReady = 0xA102 }; enum PTPCanonEventCodeEnum { PTPEventCodeCanonRequestGetEvent = 0xC101, PTPEventCodeCanonObjectAddedEx = 0xC181, PTPEventCodeCanonObjectRemoved = 0xC182, PTPEventCodeCanonRequestGetObjectInfoEx = 0xC183, PTPEventCodeCanonStorageStatusChanged = 0xC184, PTPEventCodeCanonStorageInfoChanged = 0xC185, PTPEventCodeCanonRequestObjectTransfer = 0xC186, PTPEventCodeCanonObjectInfoChangedEx = 0xC187, PTPEventCodeCanonObjectContentChanged = 0xC188, PTPEventCodeCanonPropValueChanged = 0xC189, PTPEventCodeCanonAvailListChanged = 0xC18A, PTPEventCodeCanonCameraStatusChanged = 0xC18B, PTPEventCodeCanonWillSoonShutdown = 0xC18D, PTPEventCodeCanonShutdownTimerUpdated = 0xC18E, PTPEventCodeCanonRequestCancelTransfer = 0xC18F, PTPEventCodeCanonRequestObjectTransferDT = 0xC190, PTPEventCodeCanonRequestCancelTransferDT = 0xC191, PTPEventCodeCanonStoreAdded = 0xC192, PTPEventCodeCanonStoreRemoved = 0xC193, PTPEventCodeCanonBulbExposureTime = 0xC194, PTPEventCodeCanonRecordingTime = 0xC195, PTPEventCodeCanonRequestObjectTransferTS = 0xC1A2, PTPEventCodeCanonAfResult = 0xC1A3, PTPEventCodeCanonCTGInfoCheckComplete = 0xC1A4, PTPEventCodeCanonOLCInfoChanged = 0xC1A5, PTPEventCodeCanonObjectAddedEx2 = 0xC1A7, PTPEventCodeCanonRequestObjectTransferFTP = 0xC1F1 }; enum PTPCanonPropertyCode { PTPPropertyCodeCanonAperture = 0xD101, PTPPropertyCodeCanonShutterSpeed = 0xD102, PTPPropertyCodeCanonISOSpeed = 0xD103, PTPPropertyCodeCanonExpCompensation = 0xD104, PTPPropertyCodeCanonAutoExposureMode = 0xD105, PTPPropertyCodeCanonDriveMode = 0xD106, PTPPropertyCodeCanonMeteringMode = 0xD107, PTPPropertyCodeCanonFocusMode = 0xD108, PTPPropertyCodeCanonWhiteBalance = 0xD109, PTPPropertyCodeCanonColorTemperature = 0xD10A, PTPPropertyCodeCanonWhiteBalanceAdjustA = 0xD10B, PTPPropertyCodeCanonWhiteBalanceAdjustB = 0xD10C, PTPPropertyCodeCanonWhiteBalanceXA = 0xD10D, PTPPropertyCodeCanonWhiteBalanceXB = 0xD10E, PTPPropertyCodeCanonColorSpace = 0xD10F, PTPPropertyCodeCanonPictureStyle = 0xD110, PTPPropertyCodeCanonBatteryPower = 0xD111, PTPPropertyCodeCanonBatterySelect = 0xD112, PTPPropertyCodeCanonCameraTime = 0xD113, PTPPropertyCodeCanonAutoPowerOff = 0xD114, PTPPropertyCodeCanonOwner = 0xD115, PTPPropertyCodeCanonModelID = 0xD116, PTPPropertyCodeCanonPTPExtensionVersion = 0xD119, PTPPropertyCodeCanonDPOFVersion = 0xD11A, PTPPropertyCodeCanonAvailableShots = 0xD11B, PTPPropertyCodeCanonCaptureDestination = 0xD11C, PTPPropertyCodeCanonBracketMode = 0xD11D, PTPPropertyCodeCanonCurrentStorage = 0xD11E, PTPPropertyCodeCanonCurrentFolder = 0xD11F, PTPPropertyCodeCanonImageFormat = 0xD120 , PTPPropertyCodeCanonImageFormatCF = 0xD121 , PTPPropertyCodeCanonImageFormatSD = 0xD122 , PTPPropertyCodeCanonImageFormatExtHD = 0xD123 , PTPPropertyCodeCanonCompressionS = 0xD130, PTPPropertyCodeCanonCompressionM1 = 0xD131, PTPPropertyCodeCanonCompressionM2 = 0xD132, PTPPropertyCodeCanonCompressionL = 0xD133, PTPPropertyCodeCanonAEModeDial = 0xD138, PTPPropertyCodeCanonAEModeCustom = 0xD139, PTPPropertyCodeCanonMirrorUpSetting = 0xD13A, PTPPropertyCodeCanonHighlightTonePriority = 0xD13B, PTPPropertyCodeCanonAFSelectFocusArea = 0xD13C, PTPPropertyCodeCanonHDRSetting = 0xD13D, PTPPropertyCodeCanonPCWhiteBalance1 = 0xD140, PTPPropertyCodeCanonPCWhiteBalance2 = 0xD141, PTPPropertyCodeCanonPCWhiteBalance3 = 0xD142, PTPPropertyCodeCanonPCWhiteBalance4 = 0xD143, PTPPropertyCodeCanonPCWhiteBalance5 = 0xD144, PTPPropertyCodeCanonMWhiteBalance = 0xD145, PTPPropertyCodeCanonMWhiteBalanceEx = 0xD146, PTPPropertyCodeCanonUnknownPropD14D = 0xD14D , PTPPropertyCodeCanonPictureStyleStandard = 0xD150, PTPPropertyCodeCanonPictureStylePortrait = 0xD151, PTPPropertyCodeCanonPictureStyleLandscape = 0xD152, PTPPropertyCodeCanonPictureStyleNeutral = 0xD153, PTPPropertyCodeCanonPictureStyleFaithful = 0xD154, PTPPropertyCodeCanonPictureStyleBlackWhite = 0xD155, PTPPropertyCodeCanonPictureStyleAuto = 0xD156, PTPPropertyCodeCanonPictureStyleUserSet1 = 0xD160, PTPPropertyCodeCanonPictureStyleUserSet2 = 0xD161, PTPPropertyCodeCanonPictureStyleUserSet3 = 0xD162, PTPPropertyCodeCanonPictureStyleParam1 = 0xD170, PTPPropertyCodeCanonPictureStyleParam2 = 0xD171, PTPPropertyCodeCanonPictureStyleParam3 = 0xD172, PTPPropertyCodeCanonHighISOSettingNoiseReduction = 0xD178, PTPPropertyCodeCanonMovieServoAF = 0xD179, PTPPropertyCodeCanonContinuousAFValid = 0xD17A, PTPPropertyCodeCanonAttenuator = 0xD17B, PTPPropertyCodeCanonUTCTime = 0xD17C, PTPPropertyCodeCanonTimezone = 0xD17D, PTPPropertyCodeCanonSummertime = 0xD17E, PTPPropertyCodeCanonFlavorLUTParams = 0xD17F, PTPPropertyCodeCanonCustomFunc1 = 0xD180, PTPPropertyCodeCanonCustomFunc2 = 0xD181, PTPPropertyCodeCanonCustomFunc3 = 0xD182, PTPPropertyCodeCanonCustomFunc4 = 0xD183, PTPPropertyCodeCanonCustomFunc5 = 0xD184, PTPPropertyCodeCanonCustomFunc6 = 0xD185, PTPPropertyCodeCanonCustomFunc7 = 0xD186, PTPPropertyCodeCanonCustomFunc8 = 0xD187, PTPPropertyCodeCanonCustomFunc9 = 0xD188, PTPPropertyCodeCanonCustomFunc10 = 0xD189, PTPPropertyCodeCanonCustomFunc11 = 0xD18a, PTPPropertyCodeCanonCustomFunc12 = 0xD18b, PTPPropertyCodeCanonCustomFunc13 = 0xD18c, PTPPropertyCodeCanonCustomFunc14 = 0xD18d, PTPPropertyCodeCanonCustomFunc15 = 0xD18e, PTPPropertyCodeCanonCustomFunc16 = 0xD18f, PTPPropertyCodeCanonCustomFunc17 = 0xD190, PTPPropertyCodeCanonCustomFunc18 = 0xD191, PTPPropertyCodeCanonCustomFunc19 = 0xD192, PTPPropertyCodeCanonInnerDevelop = 0xD193, PTPPropertyCodeCanonMultiAspect = 0xD194, PTPPropertyCodeCanonMovieSoundRecord = 0xD195, PTPPropertyCodeCanonMovieRecordVolume = 0xD196, PTPPropertyCodeCanonWindCut = 0xD197, PTPPropertyCodeCanonExtenderType = 0xD198, PTPPropertyCodeCanonOLCInfoVersion = 0xD199, PTPPropertyCodeCanonUnknownPropD19A = 0xD19A , PTPPropertyCodeCanonUnknownPropD19C = 0xD19C , PTPPropertyCodeCanonUnknownPropD19D = 0xD19D , PTPPropertyCodeCanonCustomFuncEx = 0xD1a0, PTPPropertyCodeCanonMyMenu = 0xD1a1, PTPPropertyCodeCanonMyMenuList = 0xD1a2, PTPPropertyCodeCanonWftStatus = 0xD1a3, PTPPropertyCodeCanonWftInputTransmission = 0xD1a4, PTPPropertyCodeCanonHDDirectoryStructure = 0xD1a5, PTPPropertyCodeCanonBatteryInfo = 0xD1a6, PTPPropertyCodeCanonAdapterInfo = 0xD1a7, PTPPropertyCodeCanonLensStatus = 0xD1a8, PTPPropertyCodeCanonQuickReviewTime = 0xD1a9, PTPPropertyCodeCanonCardExtension = 0xD1aa, PTPPropertyCodeCanonTempStatus = 0xD1ab, PTPPropertyCodeCanonShutterCounter = 0xD1ac, PTPPropertyCodeCanonSpecialOption = 0xD1ad, PTPPropertyCodeCanonPhotoStudioMode = 0xD1ae, PTPPropertyCodeCanonSerialNumber = 0xD1af, PTPPropertyCodeCanonEVFOutputDevice = 0xD1b0, PTPPropertyCodeCanonEVFMode = 0xD1b1, PTPPropertyCodeCanonDepthOfFieldPreview = 0xD1b2, PTPPropertyCodeCanonEVFSharpness = 0xD1b3, PTPPropertyCodeCanonEVFWBMode = 0xD1b4, PTPPropertyCodeCanonEVFClickWBCoeffs = 0xD1b5, PTPPropertyCodeCanonEVFColorTemp = 0xD1b6, PTPPropertyCodeCanonExposureSimMode = 0xD1b7, PTPPropertyCodeCanonEVFRecordStatus = 0xD1b8, PTPPropertyCodeCanonLvAfSystem = 0xD1ba, PTPPropertyCodeCanonMovSize = 0xD1bb, PTPPropertyCodeCanonLvViewTypeSelect = 0xD1bc, PTPPropertyCodeCanonMirrorDownStatus = 0xD1bd, PTPPropertyCodeCanonMovieParam = 0xD1be, PTPPropertyCodeCanonMirrorLockupState = 0xD1bf, PTPPropertyCodeCanonFlashChargingState = 0xD1C0, PTPPropertyCodeCanonAloMode = 0xD1C1, PTPPropertyCodeCanonFixedMovie = 0xD1C2, PTPPropertyCodeCanonOneShotRawOn = 0xD1C3, PTPPropertyCodeCanonErrorForDisplay = 0xD1C4, PTPPropertyCodeCanonAEModeMovie = 0xD1C5, PTPPropertyCodeCanonBuiltinStroboMode = 0xD1C6, PTPPropertyCodeCanonStroboDispState = 0xD1C7, PTPPropertyCodeCanonStroboETTL2Metering = 0xD1C8, PTPPropertyCodeCanonContinousAFMode = 0xD1C9, PTPPropertyCodeCanonMovieParam2 = 0xD1CA, PTPPropertyCodeCanonStroboSettingExpComposition = 0xD1CB, PTPPropertyCodeCanonMovieParam3 = 0xD1CC, PTPPropertyCodeCanonLVMedicalRotate = 0xD1CF, PTPPropertyCodeCanonArtist = 0xD1d0, PTPPropertyCodeCanonCopyright = 0xD1d1, PTPPropertyCodeCanonBracketValue = 0xD1d2, PTPPropertyCodeCanonFocusInfoEx = 0xD1d3, PTPPropertyCodeCanonDepthOfField = 0xD1d4, PTPPropertyCodeCanonBrightness = 0xD1d5, PTPPropertyCodeCanonLensAdjustParams = 0xD1d6, PTPPropertyCodeCanonEFComp = 0xD1d7, PTPPropertyCodeCanonLensName = 0xD1d8, PTPPropertyCodeCanonAEB = 0xD1d9, PTPPropertyCodeCanonStroboSetting = 0xD1da, PTPPropertyCodeCanonStroboWirelessSetting = 0xD1db, PTPPropertyCodeCanonStroboFiring = 0xD1dc, PTPPropertyCodeCanonLensID = 0xD1dd, PTPPropertyCodeCanonLCDBrightness = 0xD1de, PTPPropertyCodeCanonCADarkBright = 0xD1df, PTPPropertyCodeCanonExExposureLevelIncrements = 0x8101, PTPPropertyCodeCanonExISOExpansion = 0x8103, PTPPropertyCodeCanonExFlasgSyncSpeedInAvMode = 0x810F, PTPPropertyCodeCanonExLongExposureNoiseReduction = 0x8201, PTPPropertyCodeCanonExHighISONoiseReduction = 0x8202, PTPPropertyCodeCanonExHHighlightTonePriority = 0x8203, PTPPropertyCodeCanonExAutoLightingOptimizer = 0x8204, PTPPropertyCodeCanonExAFAssistBeamFiring = 0x850E, PTPPropertyCodeCanonExAFDuringLiveView = 0x8511, PTPPropertyCodeCanonExMirrorLockup = 0x860f, PTPPropertyCodeCanonExShutterAELockButton = 0x8701, PTPPropertyCodeCanonExSetButtonWhenShooting = 0x8704, PTPPropertyCodeCanonExLCDDisplayWhenPowerOn = 0x8811, PTPPropertyCodeCanonExAddOriginalDecisionData = 0x880F, }; @interface PTPCanonRequest : PTPRequest +(NSString *)operationCodeName:(PTPRequestCode)operationCode; @end @interface PTPCanonResponse : PTPResponse +(NSString *)responseCodeName:(PTPResponseCode)responseCode; @end @interface PTPCanonEvent : PTPEvent +(NSString *)eventCodeName:(PTPEventCode)eventCode; @end @interface PTPCanonProperty : PTPProperty +(NSString *)propertyCodeName:(PTPPropertyCode)propertyCode; @end @interface PTPCanonDeviceInfo : PTPDeviceInfo @end @interface PTPCanonCamera : PTPCamera @end
semihshn/RentaCar-Desktop
src/application/dataAccess/concretes/HibernateColorDao.java
package application.dataAccess.concretes; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import application.dataAccess.abstracts.ColorDao; import application.entities.concretes.Color; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class HibernateColorDao implements ColorDao{ Connection connection=null; PreparedStatement query=null; ResultSet result=null; String sql; public HibernateColorDao() { // TODO Auto-generated constructor stub connection=Context.Connect(); } @Override public void add(Color color) { // TODO Auto-generated method stub sql="insert into colors (Name) values (?)"; try { query=connection.prepareStatement(sql); query.setString(1, color.getName()); query.executeUpdate(); } catch (Exception e) { // TODO: handle exception new Exception(e); } } @Override public void update(Color color) { // TODO Auto-generated method stub sql="update colors set Name=? where Id=?"; try { query=connection.prepareStatement(sql); query.setString(1, color.getName()); query.setInt(2, color.getId()); query.executeUpdate(); } catch (Exception e) { // TODO: handle exception new Exception(e); } } @Override public void delete(Color color) { // TODO Auto-generated method stub sql="delete from colors where id=?"; try { query=connection.prepareStatement(sql); query.setInt(1, color.getId()); query.executeUpdate(); } catch (Exception e) { // TODO: handle exception new Exception(e); } } @Override public Color get(int id) { // TODO Auto-generated method stub try { sql="select * from colors where id=?"; query=connection.prepareStatement(sql); query.setInt(1, id); ResultSet result=query.executeQuery(); result.next(); Color color=new Color(result.getInt("Id"),result.getString("Name")); return color; } catch (Exception e) { // TODO: handle exception new Exception(e.getMessage()); } return null; } @Override public ObservableList<Color> getAll() { // TODO Auto-generated method stub sql="select * from colors"; ObservableList<Color> color=FXCollections.observableArrayList(); try { query=connection.prepareStatement(sql); ResultSet result=query.executeQuery(); while (result.next()) { color.add(new Color(result.getInt("Id"),result.getString("Name"))); } return color; } catch (Exception e) { // TODO: handle exception new Exception(e.getMessage()); } return null; } }
mariorojas/MorphoMSO
app/src/main/java/com/morpho/demo/helper/INEFingerVerification.java
<gh_stars>1-10 package com.morpho.demo.helper; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.morpho.demo.constant.Constants; import com.morpho.demo.constant.Customer; import com.morpho.demo.constant.MorphoFormApp; import com.morpho.demo.tools.Base64; import com.morpho.demo.tools.IOUtil; import com.morpho.demo.tools.Util; import com.morpho.wsdl.wsclient.ClientWS; import com.morpho.wsdl.wsclient.ConsumeResponse; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; /** * Creada por <NAME> el 26/04/2017. * * Clase para gestionar el envío de huellas dactilares hacia servidores del INE */ public class INEFingerVerification extends AsyncTask<Void, Void, Void> implements ConsumeResponse { private Customer customer; private Context context; private ConsumeResponse consumeResponse; public INEFingerVerification(Customer customer, Context context, ConsumeResponse consumeResponse) { this.customer = customer; this.context = context; this.consumeResponse = consumeResponse; } @Override protected Void doInBackground(Void... params) { if (customer != null) { HashMap<String, Object> data = new HashMap<>(); fillData(data); ClientWS clientWS = new ClientWS(Util.getSettingWSURI(context),Util.getSettingWSHost(context),this); JSONObject jsonObject = new JSONObject(data); try { clientWS.postCon("/api/customer/verifyMinutia",jsonObject.toString(),Util.getSettingWSPort(context)); } catch (Exception e) { e.printStackTrace(); if (consumeResponse != null) consumeResponse.consumeResponde(500, e.getMessage()); } } return null; } /** * Asignación de huellas digitales al objeto que se enviará vía POST * @param data */ private void fillData(HashMap<String, Object> data) { byte[] dataByte = null; try { if (data != null) { if (MorphoFormApp.getSingleton().getCustomer().ID != null) { data.put(Constants.CUSTOMER_ID, MorphoFormApp.getSingleton().getCustomer().ID); } if (MorphoFormApp.getSingleton().getCustomer().indexLeftBuff != null) { data.put(Constants.CUSTOMER_LEFT_I, Base64.encode(MorphoFormApp.getSingleton().getCustomer().indexLeftBuff)); } if (MorphoFormApp.getSingleton().getCustomer().indexRightBuff != null) { data.put(Constants.CUSTOMER_RIGHT_I, Base64.encode(MorphoFormApp.getSingleton().getCustomer().indexRightBuff)); } customer.isFake = true; data.put("isFake", customer.isFake); Log.d(this.getClass().getName(), "isFake finger flag: " + data.get("isFake")); dataByte = IOUtil.serialize(data); } } catch (IOException e) { e.printStackTrace(); } } @Override public void consumeResponde(int statusCode, String response) { Log.d(this.getClass().getName(), "response: " + response); if(consumeResponse != null){ consumeResponse.consumeResponde(statusCode,response); } } }
wilco/bunq-client
spec/bunq/bunqme_tab_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Bunq::BunqmeTab do let(:client) { Bunq.client } let(:user_id) { '1' } let(:user) { client.user(user_id) } let(:user_url) { "#{client.configuration.base_url}/v1/user/#{user_id}" } let(:account_id) { '2' } let(:monetary_account) { user.monetary_account(account_id) } let(:account_url) { "#{user_url}/monetary-account/#{account_id}" } let(:bunqme_tab_id) { '10' } let(:bunqme_tab) { monetary_account.bunqme_tab(bunqme_tab_id) } let(:bunqme_tab_url) { "#{account_url}/bunqme-tab/#{bunqme_tab_id}" } describe '#show', :requires_session do before do stub_request(:get, bunqme_tab_url) .to_return( { status: status_code, body: response, }, ) end context 'given a known id' do let(:status_code) { 200 } let(:response) { IO.read('spec/bunq/fixtures/bunqme_tab.get.json') } it 'returns a specific bunqme tab' do expect(bunqme_tab.show) .to include_json [{"BunqMeTab": {"id": 10}}] end end context 'given an unknown id' do let(:status_code) { 404 } let(:response) { IO.read('spec/bunq/fixtures/not-found.json') } it 'raises a ResourceNotFound error' do expect { bunqme_tab.show } .to raise_error(Bunq::ResourceNotFound) end end end describe '#update', :requires_session do let(:response) { IO.read('spec/bunq/fixtures/bunqme_tab.put.json') } let(:attributes) do { "bunqme_tab_entry": { "amount_inquired": { "value": 'string', "currency": 'string', }, "description": 'string', "redirect_url": 'string', "alias": { "avatar": { "uuid": 'string', }, "label_user": { "uuid": 'string', "display_name": 'string', "country": 'string', "avatar": { "uuid": 'string', }, }, "bunq_me": { "type": 'string', "value": 'string', "name": 'string', }, }, }, "status": 'string', } end before do stub_request(:put, bunqme_tab_url) .with(body: attributes) .to_return( { status: 200, body: response, }, ) end it 'updates and returns the bunqme tab id' do result = bunqme_tab.update(attributes) expect(result).to include_json [{"Id": {"id": 10}}] end end end