repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
oakesville/mdw
mdw-common/src/com/centurylink/mdw/util/CodeUtil.java
<filename>mdw-common/src/com/centurylink/mdw/util/CodeUtil.java package com.centurylink.mdw.util; import java.io.File; import java.io.IOException; import com.centurylink.mdw.util.file.FileHelper; public class CodeUtil { public static final String HEADER_COMMENT = ""; /** * @param args h c:/workspaces/mdw (for adding standard header comments to *.java) */ public static void main(String[] args) { if (args.length < 2) { System.err.println("arguments: h fileSystemRoot"); } else { String rootPath = args[1]; File rootDir = new File(rootPath); if (!rootDir.exists() || !rootDir.isDirectory()) { System.err.println("Cannot find root directory: " + rootDir); } else { try { CodeUtil codeUtil = new CodeUtil(); codeUtil.count = 0; if ("h".equals(args[0])) { System.out.println("Replacing Headers Comments..."); codeUtil.addHeaderComments(rootDir); System.out.println("Replaced Header Comment in " + codeUtil.count + " files"); } else if ("a".equals(args[0])) { System.out.println("Removing Author Tags..."); codeUtil.removeAuthorTags(rootDir); System.out.println("Removed Author Tags in " + codeUtil.count + " files"); } } catch (Exception ex) { ex.printStackTrace(); } } } } private int count; public void addHeaderComments(File rootDir) throws IOException { for (File file : rootDir.listFiles()) { if (file.isDirectory()) { addHeaderComments(file); } else if (file.getName().endsWith(".java")) { String contents = FileHelper.readFromFile(file.getAbsolutePath()); if (!contents.startsWith(HEADER_COMMENT + "\npackage ") && !contents.startsWith(HEADER_COMMENT + "\r\npackage ")) { int idx = contents.startsWith("package ") ? 0 : contents.indexOf("\npackage "); if (idx >= 0) { contents = HEADER_COMMENT + contents.substring(idx == 0 ? 0 : idx+1); FileHelper.writeToFile(file.getAbsolutePath(), contents, false); System.out.println(file); count++; } } } } } public void removeAuthorTags(File rootDir) throws IOException { for (File file : rootDir.listFiles()) { if (file.isDirectory()) { removeAuthorTags(file); } else if (file.getName().endsWith(".java")) { String contents = FileHelper.readFromFile(file.getAbsolutePath()); int idx = contents.indexOf("\r\n * @author "); if (idx > 0) { int lineEnd = contents.indexOf("\n", idx + 2); contents = contents.substring(0, idx + 2) + contents.substring(lineEnd + 1); FileHelper.writeToFile(file.getAbsolutePath(), contents, false); System.out.println(file); count++; } } } } }
rubylibs/textutils
textutils/lib/textutils/parser/name_parser.rb
# encoding: utf-8 # fix: move into TextUtils namespace/module!! ?? class NameParser include LogUtils::Logging def parse( chunks ) ## todo/fix: (re)use nameparser - for now "simple" inline version ## fix!!! - note: for now lang gets ignored ## fix: add hanlde ## Leuven[nl]|Louvain[fr] Löwen[de] ## Antwerpen[nl]|Anvers[fr] [Antwerp] ## Brussel[nl]•Bruxelles[fr] -> official bi-lingual name ## etc. ## values - split into names (name n lang pairs) ## note: assumes (default) lang from more_attribs unless otherwise marked e.g. [] assume en etc. ## split chunks into values values = [] chunks.each do |chunk| next if chunk.nil? || chunk.blank? ## skip nil or empty/blank chunks parts = chunk.split( '|' ) # 1) split | parts.each do |part| s = StringScanner.new( part ) s.skip( /[ \t]+/) # skip whitespaces while s.eos? == false if s.check( /\[/ ) ## scan everything until the end of bracket (e.g.]) ## fix!!! - note: for now lang gets ignored value = s.scan( /\[[^\]]+\]/) value = value[1...-1] # strip enclosing [] e.g. [Bavaria] => Bavaria else ## scan everything until the begin of bracket (e.g.[) value = s.scan( /[^\[]+/) value = value.strip end values << value s.skip( /[ \t]+/) # skip whitespaces logger.debug( "[NameParser] eos?: #{s.eos?}, rest: >#{s.rest}<" ) end end end logger.debug( "[NameParser] values=#{values.inspect}") names = [] values.each do |value| name = value ## todo: split by bullet ? (official multilang name) e.g. Brussel • Bruxelles ## todo: process variants w/ () e.g. Krems (a. d. Donau) etc. ?? names << name end logger.debug( "[NameParser] names=#{names.inspect}") names end # method parse end # class NameParser
tibers/rio
vendor/github.com/solo-io/solo-kit/pkg/api/v1/resources/common/kubernetes/job.sk.go
<reponame>tibers/rio // Code generated by solo-kit. DO NOT EDIT. package kubernetes import ( "sort" github_com_solo_io_solo_kit_api_external_kubernetes_job "github.com/solo-io/solo-kit/api/external/kubernetes/job" "github.com/solo-io/go-utils/hashutils" "github.com/solo-io/solo-kit/pkg/api/v1/resources" "github.com/solo-io/solo-kit/pkg/api/v1/resources/core" "github.com/solo-io/solo-kit/pkg/errors" "k8s.io/apimachinery/pkg/runtime/schema" ) func NewJob(namespace, name string) *Job { job := &Job{} job.Job.SetMetadata(core.Metadata{ Name: name, Namespace: namespace, }) return job } // require custom resource to implement Clone() as well as resources.Resource interface type CloneableJob interface { resources.Resource Clone() *github_com_solo_io_solo_kit_api_external_kubernetes_job.Job } var _ CloneableJob = &github_com_solo_io_solo_kit_api_external_kubernetes_job.Job{} type Job struct { github_com_solo_io_solo_kit_api_external_kubernetes_job.Job } func (r *Job) Clone() resources.Resource { return &Job{Job: *r.Job.Clone()} } func (r *Job) Hash() uint64 { clone := r.Job.Clone() resources.UpdateMetadata(clone, func(meta *core.Metadata) { meta.ResourceVersion = "" }) return hashutils.HashAll(clone) } func (r *Job) GroupVersionKind() schema.GroupVersionKind { return JobGVK } type JobList []*Job // namespace is optional, if left empty, names can collide if the list contains more than one with the same name func (list JobList) Find(namespace, name string) (*Job, error) { for _, job := range list { if job.GetMetadata().Name == name { if namespace == "" || job.GetMetadata().Namespace == namespace { return job, nil } } } return nil, errors.Errorf("list did not find job %v.%v", namespace, name) } func (list JobList) AsResources() resources.ResourceList { var ress resources.ResourceList for _, job := range list { ress = append(ress, job) } return ress } func (list JobList) Names() []string { var names []string for _, job := range list { names = append(names, job.GetMetadata().Name) } return names } func (list JobList) NamespacesDotNames() []string { var names []string for _, job := range list { names = append(names, job.GetMetadata().Namespace+"."+job.GetMetadata().Name) } return names } func (list JobList) Sort() JobList { sort.SliceStable(list, func(i, j int) bool { return list[i].GetMetadata().Less(list[j].GetMetadata()) }) return list } func (list JobList) Clone() JobList { var jobList JobList for _, job := range list { jobList = append(jobList, resources.Clone(job).(*Job)) } return jobList } func (list JobList) Each(f func(element *Job)) { for _, job := range list { f(job) } } func (list JobList) EachResource(f func(element resources.Resource)) { for _, job := range list { f(job) } } func (list JobList) AsInterfaces() []interface{} { var asInterfaces []interface{} list.Each(func(element *Job) { asInterfaces = append(asInterfaces, element) }) return asInterfaces } var ( JobGVK = schema.GroupVersionKind{ Version: "kubernetes", Group: "kubernetes.solo.io", Kind: "Job", } )
wyan/ack
mach/proto/mcg/pass_phigroups.c
<gh_stars>100-1000 #include "mcg.h" static PMAPOF(struct vreg, struct vreg) phimap; static void make_phimap(void) { int i, j; phimap.count = 0; for (i=0; i<cfg.preorder.count; i++) { struct basicblock* bb = cfg.preorder.item[i]; /* Registers imported through a phi can come from multiple locations. */ for (j=0; j<bb->phis.count; j++) { struct vreg* vreg = bb->phis.item[j].left; struct phi* phi = bb->phis.item[j].right; struct vreg* prevvreg = phi->ir->result; pmap_add(&phimap, vreg, prevvreg); } } } static void recursively_associate_group(struct phicongruence* c, struct vreg* vreg) { int i; vreg->congruence = c; array_appendu(&c->vregs, vreg); tracef('V', "V: %%%d is a member of congruence group %d\n", vreg->id, c->id); if (vreg->defined) { struct constraint* constraint = pmap_findleft(&vreg->defined->constraints, vreg); if (c->type == 0) c->type = vreg->type; if (c->type != vreg->type) fatal("tried to add register %%%d of type 0x%x to a phi congruence group of type 0x%x", vreg->id, vreg->type, c->type); array_appendu(&c->definitions, vreg->defined); } for (;;) { struct vreg* child = pmap_findleft(&phimap, vreg); if (!child) break; pmap_remove(&phimap, vreg, child); recursively_associate_group(c, child); } for (;;) { struct vreg* child = pmap_findright(&phimap, vreg); if (!child) break; pmap_remove(&phimap, child, vreg); recursively_associate_group(c, child); } } static void update_vreg_types(struct phicongruence* c) { int i; for (i=0; i<c->vregs.count; i++) { struct vreg* vreg = c->vregs.item[i]; if (vreg->type == 0) vreg->type = c->type; assert(vreg->type == c->type); assert(vreg->type != 0); } } static void associate_groups(void) { static int number = 0; while (phimap.count > 0) { struct phicongruence* c = calloc(1, sizeof(*c)); c->id = number++; recursively_associate_group(c, phimap.item[0].left); update_vreg_types(c); } } void pass_find_phi_congruence_groups(void) { make_phimap(); associate_groups(); } /* vim: set sw=4 ts=4 expandtab : */
chuntaojun/pole
server/auth/auth_plugin.go
<gh_stars>0 // Copyright (c) 2020, Conf-Group. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package auth import ( "context" "errors" "fmt" "regexp" "strings" "sync" "time" "github.com/Conf-Group/pole/constants" "github.com/Conf-Group/pole/utils" ) type OperationType int var ( AdminName = "admin" ReadOnly OperationType = 0 WriteOnly OperationType = 1 ReadAndWrite OperationType = 2 ErrorTokenNotExist = errors.New("token does not exist") ErrorTokenExpire = errors.New("this token already expire") ErrorResourceNotFound = errors.New("resource not found") ErrorForbid = errors.New("forbid access this resource") ErrorOperateNotSupport = errors.New("this ops not support") ) type User struct { id int64 username string password string role string } func (u User) GetID() int64 { return u.id } func (u User) GetUsername() string { return u.username } func (u User) GetPassword() string { return u.password } func (u User) GetRole() string { return u.role } type Role struct { id int64 roleName string permissions Permission } type Permission struct { resource string operation OperationType } type Token struct { id int64 role string token string } type SecurityCenter struct { ctx context.Context rL sync.RWMutex tL sync.RWMutex roleMap map[string]Role tokenMap map[string]Role } func CreateSecurityCenter(ctx context.Context) *SecurityCenter { return &SecurityCenter{ ctx: ctx, roleMap: make(map[string]Role), tokenMap: make(map[string]Role), } } func (s *SecurityCenter) startRoleRefresh() { utils.DoTickerSchedule(s.ctx, func() { }, time.Duration(30)*time.Second) } func (s *SecurityCenter) startTokenRefresh() { utils.DoTickerSchedule(s.ctx, func() { }, time.Duration(30)*time.Second) } func (s *SecurityCenter) HasPermission(metadata map[string]string, op OperationType) (bool, error) { token := metadata[constants.TokenKey] resource := s.buildResource(metadata) // Judge whether token exists if role, exist := s.tokenMap[token]; exist { return s.authFilter(resource, role, op) } return false, ErrorTokenNotExist } func (s *SecurityCenter) authFilter(resource string, role Role, op OperationType) (bool, error) { defer func() { s.tL.RUnlock() }() s.tL.RLock() if strings.Compare(AdminName, role.roleName) == 0 { return true, nil } // what permissions do I have to find this resource p := role.permissions reg := strings.ReplaceAll(p.resource, "*", ".*") isOk, err := regexp.Match(reg, []byte(resource)) if err != nil { return false, err } if !isOk { return false, ErrorForbid } if op == p.operation { return true, nil } return false, fmt.Errorf("forbid %s this resource, it just allow %s", parseOperationName(op), parseOperationName(p.operation)) } func parseOperationName(ops OperationType) string { switch ops { case ReadOnly: return "read" case WriteOnly: return "write" case ReadAndWrite: return "read and write" default: panic(ErrorOperateNotSupport) } } // {namespace}:{group} func (s *SecurityCenter) buildResource(header map[string]string) string { namespaceID := header[constants.NamespaceID] group := header[constants.Group] resource := "" if namespaceID != "" { resource += namespaceID } resource += ":" if group == "" { resource += "*" } else { resource += group } return resource }
huangxinping/o2oa
o2server/servers/webServer/x_component_Note/lp/zh-cn.js
<filename>o2server/servers/webServer/x_component_Note/lp/zh-cn.js<gh_stars>1-10 MWF.xApplication.Note.LP = { "title": "便签", "deleteNoteTitle": "删除便签确认", "deleteNote": "您确定要删除当前便签吗?" };
mkesmetzis/starter-kit-spring-maven
src/main/java/com/client/core/base/model/jpa/JpaEntity.java
<gh_stars>10-100 package com.client.core.base.model.jpa; import com.client.core.base.model.Entity; import java.util.Date; public interface JpaEntity<ID> extends Entity<ID>{ /** * Returns the primary key of this entity * * @return */ @Override ID getId(); void setId(ID id); /** * Returns the date of when the record was added * * @return the dateAdded */ Date getDateAdded(); void setDateAdded(Date dateAdded); /** * Returns the date when the record was last updated * * @return the dateUpdated */ Date getDateUpdated(); /** * Does not actually set the dateUpdated, here so that form binding will not fail. To update the dateUpdate use overrideDateUpdate * * @param dateUpdated */ void setDateUpdated(Date dateUpdated); }
Apache-HB/managarm
kernel/thor/arch/arm/thor-internal/arch/timer.hpp
<gh_stars>1-10 #pragma once namespace thor { void initializeTimers(); } // namespace thor
RalfBarkow/semweb4j
org.semweb4j.rdf2go.api/src/main/java/org/ontoware/rdf2go/model/node/impl/URIImpl.java
/** * LICENSE INFORMATION * * Copyright 2005-2008 by FZI (http://www.fzi.de). Licensed under a BSD license * (http://www.opensource.org/licenses/bsd-license.php) <OWNER> = <NAME> * <ORGANIZATION> = FZI Forschungszentrum Informatik Karlsruhe, Karlsruhe, * Germany <YEAR> = 2010 * * Further project information at http://semanticweb.org/wiki/RDF2Go */ package org.ontoware.rdf2go.model.node.impl; import java.net.URISyntaxException; import org.ontoware.rdf2go.exception.ModelRuntimeException; import org.ontoware.rdf2go.model.node.BlankNode; import org.ontoware.rdf2go.model.node.Node; import org.ontoware.rdf2go.model.node.URI; public class URIImpl extends ResourceImpl implements URI { private static final long serialVersionUID = -73757322163415742L; private String uriString; /** * Checks uri for validity and creates * * @param uriString should be in valid URI syntax and not null * @throws IllegalArgumentException if the uri is not valid and * createURIWithChecking is true */ public URIImpl(String uriString) { this(uriString, true); } /** * @param uriString should be in valid URI syntax and not null * @param createURIWithChecking if true, checks for valid uri * @throws IllegalArgumentException if the uri is not valid and * createURIWithChecking is true */ public URIImpl(String uriString, boolean createURIWithChecking) { if(createURIWithChecking) { try { @SuppressWarnings("unused") java.net.URI u = new java.net.URI(uriString); } catch(URISyntaxException e) { throw new IllegalArgumentException(e); } } this.uriString = uriString; } /** * This method is deprecated. Just use new URIImpl(uriString) instead. * * @deprecated use the constructors instead * @param uriString should be in valid URI syntax and not null * @return a URI */ @Deprecated public static URI create(String uriString) { return new URIImpl(uriString); } /** * This method is deprecated. Just use new URIImpl(uriString,false) instead. * * @deprecated use the constructors instead * @param uriString should be in valid URI syntax and not null * @return a URI */ @Deprecated public static URI createURIWithoutChecking(String uriString) { return new URIImpl(uriString, false); } @Override public String toString() { return this.uriString; } @Override public URI asURI() throws ClassCastException { return this; } @Override public BlankNode asBlankNode() throws ClassCastException { throw new ClassCastException("Cannot cast a URI to a BlankNode"); } @Override public boolean equals(Object other) { if(other == null) return false; if(other instanceof URI) { boolean equal = this == other || ((URI)other).toString().equals(this.toString()); return equal; } else return false; } public java.net.URI toJavaURI() throws URISyntaxException { return new java.net.URI(this.uriString); } @Override public int hashCode() { return this.uriString.hashCode(); } @Override public int compareTo(Node other) { if(other instanceof URI) { return this.uriString.compareTo(((URI)other).toString()); } else { // sort by type return NodeUtils.compareByType(this, other); } } @Override public String toSPARQL() { return "<" + this.uriString + ">"; } @Override public java.net.URI asJavaURI() { try { return new java.net.URI(toString()); } catch(URISyntaxException e) { throw new ModelRuntimeException(e); } } }
IvanLu1024/LeetCode
src/tree/Solution105.java
<filename>src/tree/Solution105.java package tree; /** * 根据一棵树的前序遍历与中序遍历构造二叉树。 * * 注意: * 你可以假设树中没有重复的元素。 * * 例如,给出 * * 前序遍历 preorder = [3,9,20,15,7] * 中序遍历 inorder = [9,3,15,20,7] * 返回如下的二叉树: * * 3 * / \ * 9 20 * / \ * 15 7 * */ public class Solution105 { public TreeNode buildTree(int[] preorder, int[] inorder) { return buildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1); } private TreeNode buildTree(int[] preorder,int[] inorder,int preStart,int preEnd,int inStart,int inEnd){ if (preStart>preEnd||inStart>inEnd){ return null; } int val = preorder[preStart]; TreeNode root = new TreeNode(val); //根节点的下标 int index=0; for (int i = inStart; i <= inEnd; i++) { if (val==inorder[i]){ index=i; break; } } //左子树,preorder[preStart+1,preStart+(index-inStart)],inorder[inStart,index-1] // (index-inStart):左子树的结点数量 root.left=buildTree(preorder,inorder,preStart+1,preStart+(index-inStart),inStart,index-1); //右子树, root.right=buildTree(preorder,inorder,preStart+(index-inStart)+1,preEnd,index+1,inEnd); return root; } }
mkp1104/localEclipseWorkspaceJava
try_catch_0/src/com/lara/N.java
<gh_stars>0 package com.lara; class W { static void test() throws ClassNotFoundException { System.out.println(1); // int i=10/0; Class.forName(""); System.out.println(2); } } public class N { public static void main(String[] args) { System.out.println(3); W w1=new W(); try { System.out.println(3); w1.test(); System.out.println(5); } catch(ClassNotFoundException ex) { System.out.println(6); } System.out.println(7); } }
jsptest/jsptest
jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/compiler/java/Java6Compiler.java
<reponame>jsptest/jsptest<gh_stars>1-10 package net.sf.jsptest.compiler.java; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import net.sf.jsptest.utils.IO; public class Java6Compiler extends CommandLineJavac { private static final String TMPDIR = System.getProperty("java.io.tmpdir"); protected boolean execute(String[] arguments) throws IOException, InterruptedException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { return executeWithReflection(arguments, output) == 0; } finally { File logFile = new File(TMPDIR, getClass().getName() + ".log"); IO.append(output.toString(), logFile); } } private int executeWithReflection(String[] arguments, ByteArrayOutputStream output) { try { Object systemJavaCompiler = acquireCompilerImplementation(); Method[] methods = systemJavaCompiler.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals("run")) { Object returnValue = methods[i].invoke(systemJavaCompiler, new Object[] { new ByteArrayInputStream(new byte[0]), output, output, arguments }); return Integer.parseInt(String.valueOf(returnValue)); } } return -1; } catch (Exception e) { throw new RuntimeException(e); } } protected String[] buildCommandLine(String pathToJavaSource, String outputDirectory, String classpathString) { return new String[] { "-verbose", "-classpath", classpathString, "-d", outputDirectory, pathToJavaSource }; } public boolean isAvailable() { return acquireCompilerImplementation() != null; } private Object acquireCompilerImplementation() { try { Class factory = Class.forName("javax.tools.ToolProvider"); Method method = factory.getMethod("getSystemJavaCompiler", null); return method.invoke(null, null); } catch (Exception e) { return null; } } }
LeoBaro/astro
astro/misc/time_conversion.py
import itertools from astropy.time import Time times = ['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00', '2019-01-01T12:00:00', '2019-01-01T12:30:00'] t = Time(times, format='isot', scale='utc') m = Time([51544.5, 51544.511574], format='mjd') print("t: ", t) print("m: ", m) for i in itertools.chain(t, m): print("time: %23s, ISO: %23s, JD: %.5f, MJD: %.5f" % (i, i.iso, i.jd, i.mjd))
AeonGames/AeonEngine
engine/core/ResourceCache.cpp
<filename>engine/core/ResourceCache.cpp /* Copyright (C) 2018 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <unordered_map> #include "aeongames/ResourceCache.h" #include "aeongames/ResourceFactory.h" #include "aeongames/ResourceId.h" namespace AeonGames { static std::unordered_map<uint32_t, UniqueAnyPtr> gResourceStore{}; void ClearAllResources() { gResourceStore.clear(); } void EnumerateResources ( const std::function<bool ( uint32_t, const UniqueAnyPtr& ) >& aEnumerator ) { for ( auto& i : gResourceStore ) { if ( !aEnumerator ( i.first, i.second ) ) { return; } } } const UniqueAnyPtr& StoreResource ( uint32_t aKey, UniqueAnyPtr&& pointer ) { static const UniqueAnyPtr unique_nullptr{nullptr}; // Don't store nullptrs if ( pointer.GetRaw() ) { gResourceStore.emplace ( std::make_pair<> ( aKey, std::move ( pointer ) ) ); return gResourceStore[aKey]; } return unique_nullptr; } UniqueAnyPtr DisposeResource ( uint32_t aKey ) { UniqueAnyPtr result{}; auto i = gResourceStore.find ( aKey ); if ( i != gResourceStore.end() ) { result.Swap ( ( *i ).second ); gResourceStore.erase ( i ); } return result; } const UniqueAnyPtr& GetResource ( uint32_t aKey ) { static const UniqueAnyPtr unique_nullptr{nullptr}; auto i = gResourceStore.find ( aKey ); if ( i != gResourceStore.end() ) { return ( *i ).second; } return unique_nullptr; } const UniqueAnyPtr& GetResource ( const ResourceId& aResourceId ) { auto i = gResourceStore.find ( aResourceId.GetPath() ); if ( i != gResourceStore.end() ) { return ( *i ).second; } return GetDefaultResource ( aResourceId.GetType() ); } }
Evil1991/bitrixdock
www/html/bitrix/modules/currency/install/js/currency/core_currency.js
<reponame>Evil1991/bitrixdock ;(function(window) { BX.namespace('BX.Currency'); if (BX.Currency.defaultFormat) { return; } BX.mergeEx(BX.Currency, { currencyList: [], defaultFormat: { 'FORMAT_STRING': '#', 'DEC_POINT': '.', 'THOUSANDS_SEP': ' ', 'DECIMALS': 2, 'HIDE_ZERO': 'N' }, setCurrencyFormat: function(currency, format, replace) { var index = this.getCurrencyIndex(currency), currencyFormat = BX.clone(this.defaultFormat, true), i; replace = !!replace; if (index > -1 && !replace) { return; } if (index === -1) { index = this.currencyList.length; } for (i in currencyFormat) { if (currencyFormat.hasOwnProperty(i) && typeof format[i] !== 'undefined') { currencyFormat[i] = format[i]; } } this.currencyList[index] = { 'currency': currency, 'format': BX.clone(currencyFormat, true) }; }, setCurrencies: function(currencies, replace) { var i; if (!!currencies && BX.type.isArray(currencies)) { for (i = 0; i < currencies.length; i++) { if (!!currencies[i].CURRENCY && !!currencies[i].FORMAT) { this.setCurrencyFormat(currencies[i].CURRENCY, currencies[i].FORMAT, replace); } } } }, getCurrencyFormat: function(currency) { var index = this.getCurrencyIndex(currency); return (index > -1 ? this.currencyList[index].format : false); }, getCurrencyIndex: function(currency) { var i, index = -1; if (this.currencyList.length === 0) { return index; } for (i = 0; i < this.currencyList.length; i++) { if (this.currencyList[i].currency === currency) { index = i; break; } } return index; }, clearCurrency: function(currency) { var index = this.getCurrencyIndex(currency); if (index > -1) this.currencyList = BX.util.deleteFromArray(this.currencyList, index); }, clean: function() { this.currencyList = []; }, currencyFormat: function (price, currency, useTemplate) { var result = '', format; useTemplate = !!useTemplate; format = this.getCurrencyFormat(currency); if (!!format && typeof format === 'object') { format.CURRENT_DECIMALS = format.DECIMALS; if (format.HIDE_ZERO === 'Y' && price == parseInt(price, 10)) format.CURRENT_DECIMALS = 0; result = BX.util.number_format(price, format.CURRENT_DECIMALS, format.DEC_POINT, format.THOUSANDS_SEP); if (useTemplate) result = format.FORMAT_STRING.replace(/(^|[^&])#/, '$1' + result); } return result; }, loadCurrencyFormat: function (currency) { return new Promise(function (resolve, reject) { var index = this.getCurrencyIndex(currency); if(index > -1) { resolve(this.currencyList[index].format); } else { BX.ajax.runAction("currency.format.get", {data: {currencyId: currency}}).then( function(response) { var format = response.data; this.setCurrencyFormat(currency, format); resolve(format); }.bind(this) ).catch(function(response) { reject(response.errors); }) } }.bind(this)) } }); })(window);
som-dev/Algorithms
Graph/Matrix.hpp
#pragma once template <typename T> class Matrix { public: Matrix(std::initializer_list<std::initializer_list<T>> rows) { for (auto& row : rows) { std::vector<T> newrow; for (auto& item : row) newrow.push_back(item); m_rows.push_back(newrow); } } Matrix(size_t rows, size_t cols, const T& initial_value) { for (size_t i = 0; i < rows; ++i) { std::vector<T> newrow; for (size_t j = 0; j < rows; ++j) newrow.push_back(initial_value); m_rows.push_back(newrow); } } const std::vector<T>& operator[](size_t n) const { return m_rows[n]; } std::vector<T>& operator[](size_t n) { return m_rows[n]; } size_t rows() const { return m_rows.size(); } size_t cols() const { return m_rows[0].size(); } private: std::vector<std::vector<T>> m_rows; };
fluorumlabs/disconnect-project
disconnect-classlib/src/main/java/js/web/webspeech/SpeechSynthesisErrorEvent.java
package js.web.webspeech; import org.teavm.jso.JSBody; import org.teavm.jso.JSProperty; public interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent { @JSBody(script = "return SpeechSynthesisErrorEvent.prototype") static SpeechSynthesisErrorEvent prototype() { throw new UnsupportedOperationException("Available only in JavaScript"); } @JSBody(script = "return new SpeechSynthesisErrorEvent()") static SpeechSynthesisErrorEvent create() { throw new UnsupportedOperationException("Available only in JavaScript"); } @JSProperty SpeechSynthesisErrorCode getError(); }
jpabb7/p2pScrapper
BitTorrent-5.2.2/BTL/profile.py
<reponame>jpabb7/p2pScrapper # extensions for lsprof/cProfile # # usage: # # from BTL.profile import Profiler, Stats # # prof = Profiler() # prof.enable() # # your_code() # # prof.disable() # stats = Stats(prof.getstats()) # stats.sort("inlinetime") # stats.pprint() # # by <NAME> from __future__ import division import sys from BTL.ebencode import ebencode from lsprof import Profiler, _fn2mod from lsprof import Stats as lsprof_Stats def label(code): if isinstance(code, str): return code try: mname = _fn2mod[code.co_filename] except KeyError: for k, v in sys.modules.items(): if v is None: continue if not hasattr(v, '__file__'): continue if not isinstance(v.__file__, str): continue if v.__file__.startswith(code.co_filename): mname = _fn2mod[code.co_filename] = k break else: mname = _fn2mod[code.co_filename] = '<%s>'%code.co_filename return '%s (%s:%d)' % (code.co_name, mname, code.co_firstlineno) class Stats(lsprof_Stats): def dump(self, file, top=None): d = self.data if top is not None: d = d[:top] root = [] for e in d: n = {} root.append(n) n['l'] = (e.inlinetime, e.callcount, e.totaltime, label(e.code)) n['c'] = [] for se in e.calls or []: n['c'].append((se.inlinetime, se.callcount, se.totaltime, label(se.code))) file.write(ebencode(root)) def list_stats(self, top=None): l = [] d = self.data if top is not None: d = d[:top] l.append(("CallCount", "Inline(sec)", "Per call(sec)", "Total(sec)", "Per call(sec)", "function (module:lineno)")) def make_set(d, child=False): if child: fmt = "+%s" else: fmt = "%s" return (fmt % d.callcount, '%.3f' % d.inlinetime, '%.3f' % (d.inlinetime / e.callcount), '%.3f' % d.totaltime, '%.3f' % (d.totaltime / e.callcount), fmt % label(d.code)) for e in d: l.append(make_set(e)) if e.calls: for se in e.calls: l.append(make_set(se, child=True)) return l
UniqueDong/zero-design-patterns
src/main/java/com/zero/headfirst/observer/Observer.java
package com.zero.headfirst.observer; public interface Observer { /** * 接收主题发布的更新通知 */ void notice(Newspaper data); }
chanshiyucx/moemall
moemall-mbg/src/main/java/com/chanshiyu/moemall/mbg/mapper/SmsCouponProductRelationMapper.java
package com.chanshiyu.moemall.mbg.mapper; import com.chanshiyu.moemall.mbg.model.SmsCouponProductRelation; import tk.mybatis.mapper.MyMapper; public interface SmsCouponProductRelationMapper extends MyMapper<SmsCouponProductRelation> { }
KingMikeXS/dl
adv/cassandra.py
import adv.adv_test from core.advbase import * from slot.a import * def module(): return Cassandra class Cassandra(Adv): comment = 'no counter damage; s2 drops combo' a1 = ('prep_charge','5%') a3 = ('ro', 0.15) conf = {} conf['slots.a'] = Candy_Couriers()+The_Plaguebringer() conf['acl'] = """ `s1 `s2, seq=5 `s3 """ conf['afflict_res.poison'] = 0 def prerun(this): this.hp = 80 if this.condition('reflect 500 damage on every s2'): this.s2reflect = 500 else: this.s2reflect = 0 def s1_proc(this, e): this.afflics.poison('s1',120,0.582) def s2_proc(this, e): this.dmg_make('o_s2_reflect', this.s2reflect * 11, fixed=True) with CrisisModifier('s2', 1, this.hp): this.dmg_make('s2',9.72) if __name__ == '__main__': conf = {} adv.adv_test.test(module(), conf)
TeamvisionCorp/GAT-CODE
GATCore/src/main/java/com/gateside/autotesting/Gat/manager/WebUIStepsCaseManager.java
<filename>GATCore/src/main/java/com/gateside/autotesting/Gat/manager/WebUIStepsCaseManager.java package com.gateside.autotesting.Gat.manager; import com.gateside.autotesting.Gat.manager.StepsCaseManager; import java.util.ArrayList; import java.util.List; import org.dom4j.Element; import com.gateside.autotesting.Gat.dataobject.testcase.InterfaceStepsCase; import com.gateside.autotesting.Gat.dataobject.testcase.StepsCase; import com.gateside.autotesting.Gat.dataobject.testcase.TestStep; import com.gateside.autotesting.Gat.dataobject.testcase.WebUIStepsCase; import com.gateside.autotesting.Gat.dataobject.testcase.WebUITestStep; import com.gateside.autotesting.Gat.util.GlobalConfig; import com.gateside.autotesting.Lib.xmlService.XMLParser; import com.gateside.autotesting.Lib.xmlService.XMLSerializer; public class WebUIStepsCaseManager extends StepsCaseManager { @Override public WebUIStepsCase geTestCase(String caseID) throws Exception { WebUIStepsCase caseResult=new WebUIStepsCase(); String filePath=GlobalConfig.getTestCaseFilePath(); String testCaseXPth="AllTestCases/TestCase"; String caseXMLString=this.getTestObjectXML(caseID, filePath, testCaseXPth,"ID"); caseResult=(WebUIStepsCase)XMLSerializer.XMLToObject(caseResult,caseXMLString); caseResult=formatTestCase(caseResult, filePath); return caseResult; } @Override public List<StepsCase> getAllTestCase(String filePath) throws Exception { List<StepsCase> result=new ArrayList<StepsCase>(); String testCaseXPth="AllTestCases/TestCase"; List<Element> caseXMLElement=this.getTestObjectXMLs(filePath, testCaseXPth); for(Element item:caseXMLElement) { WebUIStepsCase caseResult=new WebUIStepsCase(); caseResult=(WebUIStepsCase)XMLSerializer.XMLToObject(caseResult,item.asXML()); caseResult=formatTestCase(caseResult, filePath); result.add(caseResult); } return result; } private WebUIStepsCase formatTestCase(WebUIStepsCase testCase,String filePath) { resetAssembly(testCase,filePath); resetGroup(testCase,filePath); resetParametersFilePath(testCase,filePath); resetUIElementsFilePath(testCase, filePath); resetTestCaseModuleID(testCase, filePath); return testCase; } private void resetAssembly(WebUIStepsCase testCase,String filePath) { String assemblyXpath="AllTestCases/StepAssembly"; if(testCase.StepAssembly==null || testCase.StepGroup=="") { testCase.StepAssembly=XMLParser.getElementsByXPath(filePath, assemblyXpath).get(0).getTextTrim(); } for(WebUITestStep step: testCase.Steps) { if(step.StepAssembly==null || step.StepAssembly=="") { step.StepAssembly=XMLParser.getElementsByXPath(filePath, assemblyXpath).get(0).getTextTrim(); } } } private void resetGroup(WebUIStepsCase testCase,String filePath) { String groupXpath="AllTestCases/StepGroup"; if(testCase.StepGroup==null || testCase.StepGroup=="") { testCase.StepGroup=XMLParser.getElementsByXPath(filePath, groupXpath).get(0).getTextTrim(); } for(WebUITestStep step: testCase.Steps) { if(step.StepGroup==null || step.StepGroup=="") { step.StepGroup=XMLParser.getElementsByXPath(filePath, groupXpath).get(0).getTextTrim(); } } } private void resetParametersFilePath(WebUIStepsCase testCase,String filePath) { String parameterFilePath="AllTestCases/StepParametersFilePath"; for(WebUITestStep step: testCase.Steps) { if(step.StepParametersFilePath==null || step.StepParametersFilePath=="") { if(testCase.StepParametersFilePath!=null) { step.StepParametersFilePath=testCase.StepParametersFilePath; } else { step.StepParametersFilePath=XMLParser.getElementsByXPath(filePath, parameterFilePath).get(0).getTextTrim(); } } this.transforSpecialChar(step); } } private void resetUIElementsFilePath(WebUIStepsCase testCase,String filePath) { String elementsFilePath="AllTestCases/UIElementsFilePath"; for(WebUITestStep step: testCase.Steps) { if(step.UIElementsFilePath==null || step.UIElementsFilePath=="") { if(testCase.UIElementsFilePath!=null) { step.UIElementsFilePath=testCase.UIElementsFilePath; } else { step.UIElementsFilePath=XMLParser.getElementsByXPath(filePath, elementsFilePath).get(0).getTextTrim(); } } } } }
trombonehero/Footlights
Client/Core/src/main/scala/me/footlights/core/data/store/filesystem.scala
/* * Copyright 2011 <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. */ import java.io.IOException import java.net.URI import java.nio.ByteBuffer import java.nio.channels.Channels import scala.collection.JavaConversions._ import me.footlights.api import me.footlights.api.support.Either._ import me.footlights.core.{Footlights,HasBytes,IO} import me.footlights.core.crypto.{Fingerprint,Link,MutableKeychain} import me.footlights.core.data import me.footlights.core.data.{Directory,File} package me.footlights.core.data.store { /** * Provides the basics of a filesystem (opening and saving files), assuming that we have a * {@link Store} (for storing and retrieving data blocks) and a {@link Keychain} (for decrypting * encrypted data). */ trait Filesystem extends Footlights { protected def io:IO protected def keychain:MutableKeychain protected def prefs:api.ModifiablePreferences protected def store:Store override def open(link:Link):Either[Exception,File] = store fetch link match { case Some(x) => Right(x) case None => Left(new IOException("'%s' not found in block store" format link)) } /** Open a file, named by its content, e.g. "urn:sha-256:0123456789abcdef01234...". */ override def open(name:URI):Either[Exception,api.File] = { log fine { "open('%s')" format name } Option(name) map Fingerprint.decode flatMap keychain.getLink map open getOrElse Left(new IOException("Unable to open '%s' (unknown reason, sorry)" format name)) } /** Open a {@link Directory} whose key is stored in our {@link Keychain}. */ override def openDirectory(name:URI):Either[Exception,Directory] = Some(name) map Fingerprint.decode flatMap keychain.getLink map openDirectory getOrElse { Left(new NoSuchElementException("Key for '%s' not known" format name)) } override def openDirectory(link:Link):Either[Exception,Directory] = store fetchDirectory link /** We cannot meaningfully create a {@link MutableDirectory} without a persistent name. */ override def openDirectory(name:String) = rootDirectory flatMap { _.openDirectory(name) } /** Open a directory relative to a specified base. */ override def openDirectory(names:Iterable[String], base:data.Directory) = { // Walk down through the directory hierarchy. var dir:Either[Exception,data.Directory] = Right(base) for (name <- names if !name.isEmpty) { dir = dir flatMap { _(name) filter { _.isDir } map Right.apply getOrElse { val path = names reduce { _ + "/" + _ } Left(new Exception("'%s' not a directory (in path '%s'" format (name, path))) } } map { _.link } flatMap store.fetchDirectory } dir } /** Open a file using a hierarchical name that recurses through directories. */ override def open(name:String):Either[Exception,api.File] = { val names = name split "/" // The name must be of the form "urn:base-name/path/relative/to/base-name". openDirectory(URI create names.head) flatMap { base => openat(names.tail, base) } } /** Open a file using a hierarchical name relative to a base directory. */ override def openat(names:Iterable[String], base:api.Directory) = base match { case d:data.MutableDirectory => openat(names, d.dir) } override def openat(names:Iterable[String], base:data.Directory) = { var dir = openDirectory(names.init, base) // Retrieve the file from the final directory. dir flatMap { _(names.last) filter { _.isFile } map { _.link } flatMap store.fetch map Right.apply getOrElse { val path = names reduce { _ + "/" + _ } Left(new java.io.FileNotFoundException("No such file '%s'" format path)) } } } /** Save a buffer of data to a {@link File}, whose name will be derived from the content. */ override def save(data:ByteBuffer):Either[Exception,api.File] = save { File.newBuilder.setContent(data).freeze } /** Save a {@link File} that has already been generated to the {@link Store}. */ def save(file:File) = { store store file.toSave log fine { "saved '%s'" format file } Right(file) } /** Save an immutable {@link Directory} to the {@link Store}. */ def save(dir:Directory) = { store store dir.encrypted log fine { "saved dir '%s'" format dir } Right(dir) } /** * Save data to a local {@link java.io.File}. * * We do what we can to make this as atomic an operation as possible: we write to a temporary * file which is on the same filesystem as the target filename, then rename it to the target. */ override def saveLocal(f:File, filename:java.io.File) = try { val tmp = java.io.File.createTempFile("tmp-", "", filename.getParentFile) val out = io writer tmp out transferFrom (Channels newChannel f.getInputStream, 0, f.stat.length) out force true out close tmp renameTo filename Right(f) } catch { case ex:Exception => Left(ex) } /** List some of the files in the filesystem (not exhaustive!). */ override def listFiles = store.listBlocks override protected def subsystemRoot(name:String) = { rootDirectory flatMap { _ openDirectory name } leftFlatMap { ex => rootDirectory flatMap { _ mkdir name } } map { case d:data.MutableDirectory => d } getOrElse { ex => new Error("Failed to open subsystem root '%s'" format name, ex) } } /** The root of our filesystem. */ private lazy val rootDirectory = prefs.synchronized { prefs getString RootPrefKey map URI.create map openDirectory getOrElse { Right(data.Directory()) } map { new data.MutableDirectory(_, this, setNewRoot) } } /** Set a new root directory. */ private def setNewRoot(dir:data.Directory) = prefs.synchronized { log info "Updated root: %s".format(dir) save(dir) map { _.link } tee keychain.store map { _.fingerprint.encode } foreach { prefs set (RootPrefKey, _) } } /** The key used to identify the global preference with the root name. */ private val RootPrefKey = "root" private val log = java.util.logging.Logger getLogger classOf[Filesystem].getCanonicalName } class Stat(val name: Fingerprint, val length: Long) { override val toString = "File '%s' (%d B)" format (name, length) } object Stat { def apply(f:java.io.File) = new Stat(Fingerprint.decode(f.getName), f.length()) def apply(name:Fingerprint, length:Long) = new Stat(name, length) } }
allenai/tango
examples/euler/complex_arithmetic.py
<reponame>allenai/tango<filename>examples/euler/complex_arithmetic.py<gh_stars>10-100 import cmath from typing import Tuple, Union from tango import Step ComplexOrTuple = Union[complex, Tuple[float, float]] def make_complex(x: ComplexOrTuple) -> complex: if isinstance(x, complex): return x elif isinstance(x, (int, float)): return complex(x) else: return complex(*x) @Step.register("cadd") class AdditionStep(Step): def run(self, a: ComplexOrTuple, b: ComplexOrTuple) -> complex: # type: ignore return make_complex(a) + make_complex(b) @Step.register("csub") class SubtractionStep(Step): def run(self, a: ComplexOrTuple, b: ComplexOrTuple) -> complex: # type: ignore return make_complex(a) - make_complex(b) @Step.register("cexp") class ExponentiateStep(Step): def run(self, x: ComplexOrTuple, base: ComplexOrTuple = cmath.e) -> complex: # type: ignore return make_complex(base) ** make_complex(x) @Step.register("cmul") class MultiplyStep(Step): def run(self, a: ComplexOrTuple, b: ComplexOrTuple) -> complex: # type: ignore return make_complex(a) * make_complex(b) @Step.register("csin") class SineStep(Step): def run(self, x: ComplexOrTuple) -> complex: # type: ignore return cmath.sin(make_complex(x)) @Step.register("ccos") class CosineStep(Step): def run(self, x: ComplexOrTuple) -> complex: # type: ignore return cmath.cos(make_complex(x))
BadLiveware/trident
storage_drivers/ontap/api/rest/models/cifs_service_options.go
<filename>storage_drivers/ontap/api/rest/models/cifs_service_options.go<gh_stars>100-1000 // Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "encoding/json" "strconv" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // CifsServiceOptions cifs service options // // swagger:model cifs_service_options type CifsServiceOptions struct { // Specifies whether or not Administrator can be mapped to the UNIX user "root". // AdminToRootMapping *bool `json:"admin_to_root_mapping,omitempty"` // Specifies whether or not the CIFS server supports the advanced sparse file capabilities. This allows // CIFS clients to query the allocated ranges of a file and to write zeroes or free data blocks for ranges // of a file. // AdvancedSparseFile *bool `json:"advanced_sparse_file,omitempty"` // Specifies whether or not to enable the Copy Offload feature. This feature enables direct // data transfers within or between compatible storage devices without transferring the data // through the host computer.<br/> // Note that this will also enable/disable the direct copy feature accordingly. // CopyOffload *bool `json:"copy_offload,omitempty"` // Specifies whether or not fake open support is enabled. This parameter allows you to optimize the // open and close requests coming from SMB 2 clients. // FakeOpen *bool `json:"fake_open,omitempty"` // Specifies whether or not the trim requests (FSCTL_FILE_LEVEL_TRIM) are supported on the CIFS server. // FsctlTrim *bool `json:"fsctl_trim,omitempty"` // Specifies whether or not the reparse point support is enabled. When enabled the CIFS server // exposes junction points to Windows clients as reparse points. This parameter is only active // if the client has negotiated use of the SMB 2 or SMB 3 protocol. This parameter is not supported // for SVMs with Infinite Volume. // JunctionReparse *bool `json:"junction_reparse,omitempty"` // Specifies whether or not SMB clients can send reads up to 1 MB in size. LargeMtu *bool `json:"large_mtu,omitempty"` // Specifies whether or not the CIFS server supports Multichannel. Multichannel *bool `json:"multichannel,omitempty"` // Specifies a Windows User or Group name that should be mapped in case of a NULL user // value. // NullUserWindowsName string `json:"null_user_windows_name,omitempty"` // Specifies whether or not the path component cache is enabled on the CIFS server. PathComponentCache *bool `json:"path_component_cache,omitempty"` // Specifies whether or not to refer clients to more optimal LIFs. When enabled, it automatically // refers clients to a data LIF local to the node which hosts the root of the requested share. // Referral *bool `json:"referral,omitempty"` // Specifies the maximum number of outstanding requests on a CIFS connection. // Example: 128 // Maximum: 8192 // Minimum: 2 SmbCredits int64 `json:"smb_credits,omitempty"` // Specifies the CIFS protocol versions for which the widelink is reported as reparse point. // // Example: ["smb1"] WidelinkReparseVersions []string `json:"widelink_reparse_versions,omitempty"` } // Validate validates this cifs service options func (m *CifsServiceOptions) Validate(formats strfmt.Registry) error { var res []error if err := m.validateSmbCredits(formats); err != nil { res = append(res, err) } if err := m.validateWidelinkReparseVersions(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *CifsServiceOptions) validateSmbCredits(formats strfmt.Registry) error { if swag.IsZero(m.SmbCredits) { // not required return nil } if err := validate.MinimumInt("smb_credits", "body", m.SmbCredits, 2, false); err != nil { return err } if err := validate.MaximumInt("smb_credits", "body", m.SmbCredits, 8192, false); err != nil { return err } return nil } var cifsServiceOptionsWidelinkReparseVersionsItemsEnum []interface{} func init() { var res []string if err := json.Unmarshal([]byte(`["smb1","smb2","smb2_1","smb3","smb3_1"]`), &res); err != nil { panic(err) } for _, v := range res { cifsServiceOptionsWidelinkReparseVersionsItemsEnum = append(cifsServiceOptionsWidelinkReparseVersionsItemsEnum, v) } } func (m *CifsServiceOptions) validateWidelinkReparseVersionsItemsEnum(path, location string, value string) error { if err := validate.EnumCase(path, location, value, cifsServiceOptionsWidelinkReparseVersionsItemsEnum, true); err != nil { return err } return nil } func (m *CifsServiceOptions) validateWidelinkReparseVersions(formats strfmt.Registry) error { if swag.IsZero(m.WidelinkReparseVersions) { // not required return nil } for i := 0; i < len(m.WidelinkReparseVersions); i++ { // value enum if err := m.validateWidelinkReparseVersionsItemsEnum("widelink_reparse_versions"+"."+strconv.Itoa(i), "body", m.WidelinkReparseVersions[i]); err != nil { return err } } return nil } // ContextValidate validates this cifs service options based on context it is used func (m *CifsServiceOptions) ContextValidate(ctx context.Context, formats strfmt.Registry) error { return nil } // MarshalBinary interface implementation func (m *CifsServiceOptions) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *CifsServiceOptions) UnmarshalBinary(b []byte) error { var res CifsServiceOptions if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
WololoBrothers/moodlemobile2
www/core/components/courses/controllers/list.js
<gh_stars>1-10 // (C) Copyright 2015 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. angular.module('mm.core.courses') /** * Controller to handle the courses list. * * @module mm.core.courses * @ngdoc controller * @name mmCoursesListCtrl */ .controller('mmCoursesListCtrl', function($scope, $mmCourses, $mmCoursesDelegate, $mmUtil, $mmEvents, $mmSite, $q, mmCoursesEventMyCoursesUpdated, mmCoreEventSiteUpdated, $mmCourseHelper) { var updateSiteObserver, myCoursesObserver, prefetchIconInitialized = false; $scope.searchEnabled = $mmCourses.isSearchCoursesAvailable() && !$mmCourses.isSearchCoursesDisabledInSite(); $scope.filter = {}; $scope.prefetchCoursesData = {}; $scope.showFilter = false; // Convenience function to fetch courses. function fetchCourses(refresh) { return $mmCourses.getUserCourses().then(function(courses) { $scope.filter.filterText = ''; // Filter value MUST be set after courses are shown. var courseIds = courses.map(function(course) { return course.id; }); return $mmCourses.getCoursesOptions(courseIds).then(function(options) { angular.forEach(courses, function(course) { course.progress = isNaN(parseInt(course.progress, 10)) ? false : parseInt(course.progress, 10); course.navOptions = options.navOptions[course.id]; course.admOptions = options.admOptions[course.id]; }); $scope.courses = courses; initPrefetchCoursesIcon(); }); }, function(error) { $mmUtil.showErrorModalDefault(error, 'mm.courses.errorloadcourses', true); }); } // Initialize the prefetch icon for the list of courses. function initPrefetchCoursesIcon() { if (prefetchIconInitialized) { // Already initialized. return; } prefetchIconInitialized = true; if (!$scope.courses || $scope.courses.length < 2) { // Not enough courses. $scope.prefetchCoursesData.icon = ''; return; } $mmCourseHelper.determineCoursesStatus($scope.courses).then(function(status) { var icon = $mmCourseHelper.getCourseStatusIconFromStatus(status); if (icon == 'spinner') { // It seems all courses are being downloaded, show a download button instead. icon = 'ion-ios-cloud-download-outline'; } $scope.prefetchCoursesData.icon = icon; }); } fetchCourses().finally(function() { $scope.coursesLoaded = true; }); $scope.refreshCourses = function() { var promises = []; promises.push($mmCourses.invalidateUserCourses()); promises.push($mmCoursesDelegate.clearAndInvalidateCoursesOptions()); $q.all(promises).finally(function() { prefetchIconInitialized = false; fetchCourses(true).finally(function() { $scope.$broadcast('scroll.refreshComplete'); }); }); }; $scope.switchFilter = function() { $scope.filter.filterText = ''; $scope.showFilter = !$scope.showFilter; }; // Download all the courses. $scope.downloadCourses = function() { var initialIcon = $scope.prefetchCoursesData.icon; $scope.prefetchCoursesData.icon = 'spinner'; $scope.prefetchCoursesData.badge = ''; return $mmCourseHelper.confirmAndPrefetchCourses($scope.courses).then(function(downloaded) { $scope.prefetchCoursesData.icon = downloaded ? 'ion-android-refresh' : initialIcon; }, function(error) { if (!$scope.$$destroyed) { $mmUtil.showErrorModalDefault(error, 'mm.course.errordownloadingcourse', true); $scope.prefetchCoursesData.icon = initialIcon; } }, function(progress) { $scope.prefetchCoursesData.badge = progress.count + ' / ' + progress.total; }).finally(function() { $scope.prefetchCoursesData.badge = ''; }); }; myCoursesObserver = $mmEvents.on(mmCoursesEventMyCoursesUpdated, function(siteid) { if (siteid == $mmSite.getId()) { fetchCourses(); } }); updateSiteObserver = $mmEvents.on(mmCoreEventSiteUpdated, function(siteId) { if ($mmSite.getId() === siteId) { $scope.searchEnabled = $mmCourses.isSearchCoursesAvailable() && !$mmCourses.isSearchCoursesDisabledInSite(); } }); $scope.$on('$destroy', function() { myCoursesObserver && myCoursesObserver.off && myCoursesObserver.off(); updateSiteObserver && updateSiteObserver.off && updateSiteObserver.off(); }); });
shijunLee/helmops
api/v1alpha1/zz_generated.deepcopy.go
// +build !ignore_autogenerated /* Copyright 2021 <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. */ // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Condition) DeepCopyInto(out *Condition) { *out = *in if in.LastTransitionTime != nil { in, out := &in.LastTransitionTime, &out.LastTransitionTime *out = (*in).DeepCopy() } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Condition. func (in *Condition) DeepCopy() *Condition { if in == nil { return nil } out := new(Condition) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Create) DeepCopyInto(out *Create) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Create. func (in *Create) DeepCopy() *Create { if in == nil { return nil } out := new(Create) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmOperation) DeepCopyInto(out *HelmOperation) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmOperation. func (in *HelmOperation) DeepCopy() *HelmOperation { if in == nil { return nil } out := new(HelmOperation) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HelmOperation) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmOperationList) DeepCopyInto(out *HelmOperationList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]HelmOperation, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmOperationList. func (in *HelmOperationList) DeepCopy() *HelmOperationList { if in == nil { return nil } out := new(HelmOperationList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HelmOperationList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmOperationSpec) DeepCopyInto(out *HelmOperationSpec) { *out = *in in.Values.DeepCopyInto(&out.Values) out.Create = in.Create out.Upgrade = in.Upgrade out.Uninstall = in.Uninstall } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmOperationSpec. func (in *HelmOperationSpec) DeepCopy() *HelmOperationSpec { if in == nil { return nil } out := new(HelmOperationSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmOperationStatus) DeepCopyInto(out *HelmOperationStatus) { *out = *in if in.LastUpdateTime != nil { in, out := &in.LastUpdateTime, &out.LastUpdateTime *out = (*in).DeepCopy() } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmOperationStatus. func (in *HelmOperationStatus) DeepCopy() *HelmOperationStatus { if in == nil { return nil } out := new(HelmOperationStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmRepo) DeepCopyInto(out *HelmRepo) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmRepo. func (in *HelmRepo) DeepCopy() *HelmRepo { if in == nil { return nil } out := new(HelmRepo) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HelmRepo) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmRepoList) DeepCopyInto(out *HelmRepoList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]HelmRepo, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmRepoList. func (in *HelmRepoList) DeepCopy() *HelmRepoList { if in == nil { return nil } out := new(HelmRepoList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *HelmRepoList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmRepoSpec) DeepCopyInto(out *HelmRepoSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmRepoSpec. func (in *HelmRepoSpec) DeepCopy() *HelmRepoSpec { if in == nil { return nil } out := new(HelmRepoSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HelmRepoStatus) DeepCopyInto(out *HelmRepoStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmRepoStatus. func (in *HelmRepoStatus) DeepCopy() *HelmRepoStatus { if in == nil { return nil } out := new(HelmRepoStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Uninstall) DeepCopyInto(out *Uninstall) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Uninstall. func (in *Uninstall) DeepCopy() *Uninstall { if in == nil { return nil } out := new(Uninstall) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Upgrade) DeepCopyInto(out *Upgrade) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Upgrade. func (in *Upgrade) DeepCopy() *Upgrade { if in == nil { return nil } out := new(Upgrade) in.DeepCopyInto(out) return out }
bTspm/stock-track
app/models/address.rb
class Address < ApplicationRecord validates_presence_of :country, :line_1 end
annelindeandersen/bachelor_project
node_modules/sweetalert-react/lib/utils/__mocks__/isDOMEquals.js
<reponame>annelindeandersen/bachelor_project 'use strict'; var isDOMEquals = jest.genMockFromModule('../isDOMEquals'); module.exports = isDOMEquals;
musasesay/tesseract-ocr.github.io
3.x/a00097.js
var a00097 = [ [ "base", "a00097.html#a15179a66cf30d663c37a4451e6f96fe5", null ], [ "FunctionSignature", "a00097.html#a2ef64a08dc3a3c67c96c9c74047714e3", null ], [ "_TessFunctionResultCallback_0_5", "a00097.html#a4ee4a1dc2dda788a0cccdc30d595540b", null ], [ "Run", "a00097.html#a9557f93b5f8e70ee9f55d4c150da62f6", null ] ];
egraba/vbox_openbsd
VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/selector/UIVMDesktop.h
/* $Id: UIVMDesktop.h $ */ /** @file * * VBox frontends: Qt GUI ("VirtualBox"): * UIVMDesktop class declarations */ /* * Copyright (C) 2010-2013 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifndef __UIVMDesktop_h__ #define __UIVMDesktop_h__ /* Qt includes: */ #include <QWidget> /* GUI includes: */ #include "QIWithRetranslateUI.h" /* Forward declarations: */ class CMachine; class UIVMDesktopPrivate; class UITexturedSegmentedButton; class UIVMItem; class VBoxSnapshotsWgt; class UIToolBar; class QStackedLayout; /* Class representing widget which contains three panes: * 1. Information pane reflecting base information about VirtualBox, * 2. Inaccessible machine pane reflecting information about * currently chosen inaccessible VM and allowing to operate over it, * 3. Snapshot pane allowing to operate over the snapshots. */ class UIVMDesktop: public QIWithRetranslateUI<QWidget> { Q_OBJECT; signals: /* Notifier: Current widget stuff: */ void sigCurrentChanged(int iWidgetIndex); public: /* Constructor: */ UIVMDesktop(UIToolBar *pToolBar, QAction *pRefreshAction, QWidget *pParent); /* API: Current pane index: */ int widgetIndex() const; /* Helpers: Update stuff: */ void updateDetailsText(const QString &strText); void updateDetailsError(const QString &strError); void updateSnapshots(UIVMItem *pVMItem, const CMachine& machine); void lockSnapshots(); private slots: /** Initialization handler. */ void sltInit(); private: /* Helper: Translate stuff: */ void retranslateUi(); /* Variables: */ QStackedLayout *m_pStackedLayout; UITexturedSegmentedButton *m_pHeaderBtn; UIVMDesktopPrivate *m_pDesktopPrivate; VBoxSnapshotsWgt *m_pSnapshotsPane; }; #endif /* !__UIVMDesktop_h__ */
Amarnathpg123/grokking_coding_patterns
grooking_patterns_cpp/dp_probs/count_ways_dies.cpp
#include<bits/stdc++.h> using namespace std; long findWays(int f, int d, int s) { vector<vector<long>> mem(d+1, vector<long>(s+1, 0)); mem[0][0] = 1; for (int i = 1; i <= d; i++) { for (int j = i; j <= s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when "j-f-1> = 0" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]; if (j - f - 1 >= 0) mem[i][j] -= mem[i - 1][j - f - 1]; } } return mem[d][s]; } int main(void) { cout << findWays(4, 2, 1) << endl; cout << findWays(2, 2, 3) << endl; cout << findWays(6, 3, 8) << endl; cout << findWays(4, 2, 5) << endl; cout << findWays(4, 3, 5) << endl; return 0; }
ghsecuritylab/tomato_egg
release/src/router/samba3/source/librpc/gen_ndr/svcctl.h
/* header auto-generated by pidl */ #ifndef _HEADER_svcctl #define _HEADER_svcctl #define SERVICE_TYPE_KERNEL_DRIVER ( 0x01 ) #define SERVICE_TYPE_FS_DRIVER ( 0x02 ) #define SERVICE_TYPE_ADAPTER ( 0x04 ) #define SERVICE_TYPE_RECOGNIZER_DRIVER ( 0x08 ) #define SERVICE_TYPE_DRIVER ( SERVICE_TYPE_KERNEL_DRIVER|SERVICE_TYPE_FS_DRIVER|SERVICE_TYPE_RECOGNIZER_DRIVER ) #define SERVICE_TYPE_WIN32_OWN_PROCESS ( 0x10 ) #define SERVICE_TYPE_WIN32_SHARE_PROCESS ( 0x20 ) #define SERVICE_TYPE_WIN32 ( SERVICE_TYPE_WIN32_OWN_PROCESS|SERVICE_TYPE_WIN32_SHARE_PROCESS ) #define SERVICE_STATE_ACTIVE ( 0x01 ) #define SERVICE_STATE_INACTIVE ( 0x02 ) #define SERVICE_STATE_ALL ( 0x03 ) #define SV_TYPE_ALL ( 0xFFFFFFFF ) struct SERVICE_LOCK_STATUS { uint32_t is_locked; const char *lock_owner;/* [unique,charset(UTF16)] */ uint32_t lock_duration; }; struct SERVICE_STATUS { uint32_t type; uint32_t state; uint32_t controls_accepted; uint32_t win32_exit_code; uint32_t service_exit_code; uint32_t check_point; uint32_t wait_hint; }; struct ENUM_SERVICE_STATUS { const char * service_name;/* [relative,flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ const char * display_name;/* [relative,flag(LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM)] */ struct SERVICE_STATUS status; }; /* bitmap svcctl_ServerType */ #define SV_TYPE_WORKSTATION ( 0x00000001 ) #define SV_TYPE_SERVER ( 0x00000002 ) #define SV_TYPE_SQLSERVER ( 0x00000004 ) #define SV_TYPE_DOMAIN_CTRL ( 0x00000008 ) #define SV_TYPE_DOMAIN_BAKCTRL ( 0x00000010 ) #define SV_TYPE_TIME_SOURCE ( 0x00000020 ) #define SV_TYPE_AFP ( 0x00000040 ) #define SV_TYPE_NOVELL ( 0x00000080 ) #define SV_TYPE_DOMAIN_MEMBER ( 0x00000100 ) #define SV_TYPE_PRINTQ_SERVER ( 0x00000200 ) #define SV_TYPE_DIALIN_SERVER ( 0x00000400 ) #define SV_TYPE_SERVER_UNIX ( 0x00000800 ) #define SV_TYPE_NT ( 0x00001000 ) #define SV_TYPE_WFW ( 0x00002000 ) #define SV_TYPE_SERVER_MFPN ( 0x00004000 ) #define SV_TYPE_SERVER_NT ( 0x00008000 ) #define SV_TYPE_POTENTIAL_BROWSER ( 0x00010000 ) #define SV_TYPE_BACKUP_BROWSER ( 0x00020000 ) #define SV_TYPE_MASTER_BROWSER ( 0x00040000 ) #define SV_TYPE_DOMAIN_MASTER ( 0x00080000 ) #define SV_TYPE_SERVER_OSF ( 0x00100000 ) #define SV_TYPE_SERVER_VMS ( 0x00200000 ) #define SV_TYPE_WIN95_PLUS ( 0x00400000 ) #define SV_TYPE_DFS_SERVER ( 0x00800000 ) #define SV_TYPE_ALTERNATE_XPORT ( 0x20000000 ) #define SV_TYPE_LOCAL_LIST_ONLY ( 0x40000000 ) #define SV_TYPE_DOMAIN_ENUM ( 0x80000000 ) enum SERVICE_CONTROL { FIXME=1 }; struct svcctl_CloseServiceHandle { struct { struct policy_handle *handle;/* [ref] */ } in; struct { struct policy_handle *handle;/* [ref] */ WERROR result; } out; }; struct svcctl_ControlService { struct { struct policy_handle *handle;/* [ref] */ uint32_t control; } in; struct { struct SERVICE_STATUS *status;/* [ref] */ WERROR result; } out; }; struct svcctl_DeleteService { struct { struct policy_handle *handle;/* [ref] */ } in; struct { WERROR result; } out; }; struct svcctl_LockServiceDatabase { struct { struct policy_handle *handle;/* [ref] */ } in; struct { struct policy_handle *lock;/* [ref] */ WERROR result; } out; }; struct svcctl_QueryServiceObjectSecurity { struct { WERROR result; } out; }; struct svcctl_SetServiceObjectSecurity { struct { WERROR result; } out; }; struct svcctl_QueryServiceStatus { struct { struct policy_handle *handle;/* [ref] */ } in; struct { struct SERVICE_STATUS *status;/* [ref] */ WERROR result; } out; }; struct svcctl_SetServiceStatus { struct { WERROR result; } out; }; struct svcctl_UnlockServiceDatabase { struct { struct policy_handle *lock;/* [ref] */ } in; struct { struct policy_handle *lock;/* [ref] */ WERROR result; } out; }; struct svcctl_NotifyBootConfigStatus { struct { WERROR result; } out; }; struct svcctl_SCSetServiceBitsW { struct { struct policy_handle *handle;/* [ref] */ uint32_t bits; uint32_t bitson; uint32_t immediate; } in; struct { WERROR result; } out; }; struct svcctl_ChangeServiceConfigW { struct { struct policy_handle *handle;/* [ref] */ uint32_t type; uint32_t start; uint32_t error; const char *binary_path;/* [unique,charset(UTF16)] */ const char *load_order_group;/* [unique,charset(UTF16)] */ const char *dependencies;/* [unique,charset(UTF16)] */ const char *service_start_name;/* [unique,charset(UTF16)] */ const char *password;/* [unique,charset(UTF16)] */ const char *display_name;/* [unique,charset(UTF16)] */ } in; struct { uint32_t *tag_id;/* [ref] */ WERROR result; } out; }; struct svcctl_CreateServiceW { struct { struct policy_handle *scmanager_handle;/* [ref] */ const char *ServiceName;/* [charset(UTF16)] */ const char *DisplayName;/* [unique,charset(UTF16)] */ uint32_t desired_access; uint32_t type; uint32_t start_type; uint32_t error_control; const char *binary_path;/* [charset(UTF16)] */ const char *LoadOrderGroupKey;/* [unique,charset(UTF16)] */ uint32_t *TagId;/* [unique] */ uint8_t *dependencies;/* [unique,size_is(dependencies_size)] */ uint32_t dependencies_size; const char *service_start_name;/* [unique,charset(UTF16)] */ uint8_t *password;/* [unique,size_is(password_size)] */ uint32_t password_size; } in; struct { uint32_t *TagId;/* [unique] */ struct policy_handle *handle;/* [ref] */ WERROR result; } out; }; struct svcctl_EnumDependentServicesW { struct { struct policy_handle *service;/* [ref] */ uint32_t state; uint32_t buf_size; } in; struct { struct ENUM_SERVICE_STATUS *status;/* [unique] */ uint32_t *bytes_needed;/* [ref] */ uint32_t *services_returned;/* [ref] */ WERROR result; } out; }; struct svcctl_EnumServicesStatusW { struct { struct policy_handle *handle;/* [ref] */ uint32_t type; uint32_t state; uint32_t buf_size; uint32_t *resume_handle;/* [unique] */ } in; struct { uint8_t *service;/* [size_is(buf_size)] */ uint32_t *bytes_needed;/* [ref] */ uint32_t *services_returned;/* [ref] */ uint32_t *resume_handle;/* [unique] */ WERROR result; } out; }; struct svcctl_OpenSCManagerW { struct { const char *MachineName;/* [unique,charset(UTF16)] */ const char *DatabaseName;/* [unique,charset(UTF16)] */ uint32_t access_mask; } in; struct { struct policy_handle *handle;/* [ref] */ WERROR result; } out; }; struct svcctl_OpenServiceW { struct { struct policy_handle *scmanager_handle;/* [ref] */ const char *ServiceName;/* [charset(UTF16)] */ uint32_t access_mask; } in; struct { struct policy_handle *handle;/* [ref] */ WERROR result; } out; }; struct svcctl_QueryServiceConfigW { struct { struct policy_handle *handle;/* [ref] */ uint32_t buf_size; } in; struct { uint8_t *query; uint32_t *bytes_needed;/* [ref] */ WERROR result; } out; }; struct svcctl_QueryServiceLockStatusW { struct { struct policy_handle *handle;/* [ref] */ uint32_t buf_size; } in; struct { struct SERVICE_LOCK_STATUS *status;/* [ref] */ uint32_t *required_buf_size;/* [ref] */ WERROR result; } out; }; struct svcctl_StartServiceW { struct { struct policy_handle *handle;/* [ref] */ uint32_t NumArgs; const char *Arguments;/* [unique,charset(UTF16),length_is(NumArgs)] */ } in; struct { WERROR result; } out; }; struct svcctl_GetServiceDisplayNameW { struct { struct policy_handle *handle;/* [ref] */ const char *service_name;/* [unique,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ } in; struct { const char **display_name;/* [ref,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ WERROR result; } out; }; struct svcctl_GetServiceKeyNameW { struct { struct policy_handle *handle;/* [ref] */ const char *service_name;/* [unique,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ } in; struct { const char **key_name;/* [ref,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ WERROR result; } out; }; struct svcctl_SCSetServiceBitsA { struct { struct policy_handle *handle;/* [ref] */ uint32_t bits; uint32_t bitson; uint32_t immediate; } in; struct { WERROR result; } out; }; struct svcctl_ChangeServiceConfigA { struct { struct policy_handle *handle;/* [ref] */ uint32_t type; uint32_t start; uint32_t error; const char *binary_path;/* [unique,charset(UTF16)] */ const char *load_order_group;/* [unique,charset(UTF16)] */ const char *dependencies;/* [unique,charset(UTF16)] */ const char *service_start_name;/* [unique,charset(UTF16)] */ const char *password;/* [unique,charset(UTF16)] */ const char *display_name;/* [unique,charset(UTF16)] */ } in; struct { uint32_t *tag_id;/* [ref] */ WERROR result; } out; }; struct svcctl_CreateServiceA { struct { struct policy_handle *handle;/* [ref] */ const char *ServiceName;/* [unique,charset(UTF16)] */ const char *DisplayName;/* [unique,charset(UTF16)] */ uint32_t desired_access; uint32_t type; uint32_t start_type; uint32_t error_control; const char *binary_path;/* [unique,charset(UTF16)] */ const char *LoadOrderGroupKey;/* [unique,charset(UTF16)] */ const char *dependencies;/* [unique,charset(UTF16)] */ const char *service_start_name;/* [unique,charset(UTF16)] */ const char *password;/* [unique,charset(UTF16)] */ } in; struct { uint32_t *TagId;/* [unique] */ WERROR result; } out; }; struct svcctl_EnumDependentServicesA { struct { struct policy_handle *service;/* [ref] */ uint32_t state; uint32_t buf_size; } in; struct { struct ENUM_SERVICE_STATUS *status;/* [unique] */ uint32_t *bytes_needed;/* [ref] */ uint32_t *services_returned;/* [ref] */ WERROR result; } out; }; struct svcctl_EnumServicesStatusA { struct { struct policy_handle *handle;/* [ref] */ uint32_t type; uint32_t state; uint32_t buf_size; uint32_t *resume_handle;/* [unique] */ } in; struct { uint8_t *service;/* [size_is(buf_size)] */ uint32_t *bytes_needed;/* [ref] */ uint32_t *services_returned;/* [ref] */ uint32_t *resume_handle;/* [unique] */ WERROR result; } out; }; struct svcctl_OpenSCManagerA { struct { const char *MachineName;/* [unique,charset(UTF16)] */ const char *DatabaseName;/* [unique,charset(UTF16)] */ uint32_t access_mask; } in; struct { struct policy_handle *handle;/* [ref] */ WERROR result; } out; }; struct svcctl_OpenServiceA { struct { struct policy_handle *scmanager_handle;/* [ref] */ const char *ServiceName;/* [unique,charset(UTF16)] */ uint32_t access_mask; } in; struct { WERROR result; } out; }; struct svcctl_QueryServiceConfigA { struct { struct policy_handle *handle;/* [ref] */ uint32_t buf_size; } in; struct { uint8_t *query; uint32_t *bytes_needed;/* [ref] */ WERROR result; } out; }; struct svcctl_QueryServiceLockStatusA { struct { struct policy_handle *handle;/* [ref] */ uint32_t buf_size; } in; struct { struct SERVICE_LOCK_STATUS *status;/* [ref] */ uint32_t *required_buf_size;/* [ref] */ WERROR result; } out; }; struct svcctl_StartServiceA { struct { struct policy_handle *handle;/* [ref] */ uint32_t NumArgs; const char *Arguments;/* [unique,charset(UTF16),length_is(NumArgs)] */ } in; struct { WERROR result; } out; }; struct svcctl_GetServiceDisplayNameA { struct { struct policy_handle *handle;/* [ref] */ const char *service_name;/* [unique,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ } in; struct { const char **display_name;/* [ref,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ WERROR result; } out; }; struct svcctl_GetServiceKeyNameA { struct { struct policy_handle *handle;/* [ref] */ const char *service_name;/* [unique,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ } in; struct { const char **key_name;/* [ref,charset(UTF16)] */ uint32_t *display_name_length;/* [unique] */ WERROR result; } out; }; struct svcctl_GetCurrentGroupeStateW { struct { WERROR result; } out; }; struct svcctl_EnumServiceGroupW { struct { WERROR result; } out; }; struct svcctl_ChangeServiceConfig2A { struct { struct policy_handle *handle;/* [ref] */ uint32_t info_level; uint8_t *info;/* [unique] */ } in; struct { WERROR result; } out; }; struct svcctl_ChangeServiceConfig2W { struct { struct policy_handle *handle;/* [ref] */ uint32_t info_level; uint8_t *info;/* [unique] */ } in; struct { WERROR result; } out; }; struct svcctl_QueryServiceConfig2A { struct { struct policy_handle *handle;/* [ref] */ uint32_t info_level; uint32_t buf_size; } in; struct { uint8_t *buffer; uint32_t *bytes_needed;/* [ref] */ WERROR result; } out; }; struct svcctl_QueryServiceConfig2W { struct { struct policy_handle *handle;/* [ref] */ uint32_t info_level; uint32_t buf_size; } in; struct { uint8_t *buffer; uint32_t *bytes_needed;/* [ref] */ WERROR result; } out; }; struct svcctl_QueryServiceStatusEx { struct { struct policy_handle *handle;/* [ref] */ uint32_t info_level; uint32_t buf_size; } in; struct { uint8_t *buffer; uint32_t *bytes_needed;/* [ref] */ WERROR result; } out; }; struct EnumServicesStatusExA { struct { struct policy_handle *scmanager;/* [ref] */ uint32_t info_level; uint32_t type; uint32_t state; uint32_t buf_size; uint32_t *resume_handle;/* [unique] */ } in; struct { uint8_t *services; uint32_t *bytes_needed;/* [ref] */ uint32_t *service_returned;/* [ref] */ uint32_t *resume_handle;/* [unique] */ const char **group_name;/* [ref,charset(UTF16)] */ WERROR result; } out; }; struct EnumServicesStatusExW { struct { struct policy_handle *scmanager;/* [ref] */ uint32_t info_level; uint32_t type; uint32_t state; uint32_t buf_size; uint32_t *resume_handle;/* [unique] */ } in; struct { uint8_t *services; uint32_t *bytes_needed;/* [ref] */ uint32_t *service_returned;/* [ref] */ uint32_t *resume_handle;/* [unique] */ const char **group_name;/* [ref,charset(UTF16)] */ WERROR result; } out; }; struct svcctl_SCSendTSMessage { struct { WERROR result; } out; }; #endif /* _HEADER_svcctl */
TobiasRasbold/pywrangler
src/pywrangler/wranglers.py
"""This module contains computation engine independent wrangler interfaces and corresponding descriptions. """ from typing import Any from pywrangler.base import BaseWrangler from pywrangler.util import sanitizer from pywrangler.util.types import TYPE_ASCENDING, TYPE_COLUMNS NONEVALUE = object() class IntervalIdentifier(BaseWrangler): """Defines the reference interface for the interval identification wrangler. An interval is defined as a range of values beginning with an opening marker and ending with a closing marker (e.g. the interval daylight may be defined as all events/values occurring between sunrise and sunset). Start and end marker may be identical. The interval identification wrangler assigns ids to values such that values belonging to the same interval share the same interval id. For example, all values of the first daylight interval are assigned with id 1. All values of the second daylight interval will be assigned with id 2 and so on. By default, values which do not belong to any valid interval, are assigned the value 0 by definition (please refer to `result_type` for different result types). If start and end marker are identical or the end marker is not provided, invalid values are only possible before the first start marker is encountered. Due to messy data, start and end marker may occur multiple times in sequence until its counterpart is reached. Therefore, intervals may have different spans based on different task requirements. For example, the very first start or very last start marker may define the correct start of an interval. Accordingly, four intervals can be selected by setting `marker_start_use_first` and `marker_end_use_first`. The resulting intervals are as follows: - first start / first end - first start / last end (longest interval) - last start / first end (shortest interval) - last start / last end Opening and closing markers are included in their corresponding interval. Parameters ---------- marker_column: str Name of column which contains the opening and closing markers. marker_start: Any A value defining the start of an interval. marker_end: Any, optional A value defining the end of an interval. This value is optional. If not given, the end marker equals the start marker. marker_start_use_first: bool Identifies if the first occurring `marker_start` of an interval is used. Otherwise the last occurring `marker_start` is used. Default is False. marker_end_use_first: bool Identifies if the first occurring `marker_end` of an interval is used. Otherwise the last occurring `marker_end` is used. Default is True. orderby_columns: str, Iterable[str], optional Column names which define the order of the data (e.g. a timestamp column). Sort order can be defined with the parameter `ascending`. groupby_columns: str, Iterable[str], optional Column names which define how the data should be grouped/split into separate entities. For distributed computation engines, groupby columns should ideally reference partition keys to avoid data shuffling. ascending: bool, Iterable[bool], optional Sort ascending vs. descending. Specify list for multiple sort orders. If a list is specified, length of the list must equal length of `order_columns`. Default is True. result_type: str, optional Defines the content of the returned result. If 'raw', interval ids will be in arbitrary order with no distinction made between valid and invalid intervals. Intervals are distinguishable by interval id but the interval id may not provide any more information. If 'valid', the result is the same as 'raw' but all invalid intervals are set to 0. If 'enumerated', the result is the same as 'valid' but interval ids increase in ascending order (as defined by order) in steps of one. target_column_name: str, optional Name of the resulting target column. """ def __init__(self, marker_column: str, marker_start: Any, marker_end: Any = NONEVALUE, marker_start_use_first: bool = False, marker_end_use_first: bool = True, orderby_columns: TYPE_COLUMNS = None, groupby_columns: TYPE_COLUMNS = None, ascending: TYPE_ASCENDING = None, result_type: str = "enumerated", target_column_name: str = "iids"): self.marker_column = marker_column self.marker_start = marker_start self.marker_end = marker_end self.marker_start_use_first = marker_start_use_first self.marker_end_use_first = marker_end_use_first self.orderby_columns = sanitizer.ensure_iterable(orderby_columns) self.groupby_columns = sanitizer.ensure_iterable(groupby_columns) self.ascending = sanitizer.ensure_iterable(ascending) self.result_type = result_type self.target_column_name = target_column_name # check correct result type valid_result_types = {"raw", "valid", "enumerated"} if result_type not in valid_result_types: raise ValueError("Parameter `result_type` is invalid with: {}. " "Allowed arguments are: {}" .format(result_type, valid_result_types)) # check for identical start and end values self._identical_start_end_markers = ((marker_end == NONEVALUE) or (marker_start == marker_end)) # sanity checks for sort order if self.ascending: # check for equal number of items of order and sort columns if len(self.orderby_columns) != len(self.ascending): raise ValueError('`order_columns` and `ascending` must have ' 'equal number of items.') # check for correct sorting keywords if not all([isinstance(x, bool) for x in self.ascending]): raise ValueError('Only `True` and `False` are ' 'allowed arguments for `ascending`') # set default sort order if None is given elif self.orderby_columns: self.ascending = [True] * len(self.orderby_columns) @property def preserves_sample_size(self) -> bool: return True
nesticat/engine
common/util.go
/* * Copyright 2018 It-chain * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package common import ( "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "math/big" "os" "os/user" "path" "path/filepath" "sort" "strings" "github.com/it-chain/engine/common/command" "github.com/rs/xid" ) func CreateDirIfMissing(dirPath string) error { if !strings.HasSuffix(dirPath, "/") { dirPath = dirPath + "/" } //logger.Debugf("CreateDirIfMissing [%s]", dirPath) err := os.MkdirAll(path.Dir(dirPath), 0755) if err != nil { return err } return nil } // DirEmpty returns true if the dir at dirPath is empty func DirEmpty(dirPath string) (bool, error) { f, err := os.Open(dirPath) if err != nil { return false, err } defer f.Close() _, err = f.Readdir(1) if err == io.EOF { return true, nil } return false, err } func ComputeSHA256(data []string) string { sort.Strings(data) arg := strings.Join(data, ",") hash := sha256.New() hash.Write([]byte(arg)) return hex.EncodeToString(hash.Sum(nil)) } /** gob encoder로 인코딩했을 때 문제점 1. empty slice(make 로 생성한거) 가 디코딩하면 nil 로 디코딩 됨. ㄴ json marshal로 바꾸면서 해결 2. time.Time 값들은 뒤에 monotonic 파트가 없어짐. 2번은 문제가 안 될수도 있는데 테스트 실패의 원인.. */ // encoding/json 패키지에 대한 설명 // json data를 json으로 인코딩 하기 위한 encoding/json 패키지의 Marshal() 을 사용한다. // json.Marshal(_struct_) 을 하면 (json 인코딩 바이트배열, 에러객체) 를 리턴한다. // decode를 위해서는 json.Unmarshal(_jsonBytes_, 받을 구조체 포인터) 를 사용한다. func Serialize(object interface{}) ([]byte, error) { //모든 stuct 받기 위해 interface{} 타입의 입력으로 선언 data, err := json.Marshal(object) if err != nil { panic(fmt.Sprintf("Error encoding : %s", err)) } return data, nil } func Deserialize(serializedBytes []byte, object interface{}) error { if len(serializedBytes) == 0 { return nil } err := json.Unmarshal(serializedBytes, object) if err != nil { panic(fmt.Sprintf("Error decoding : %s", err)) } return err } func CryptoRandomGeneration(min int64, max int64) int64 { n, _ := rand.Int(rand.Reader, big.NewInt(max+1-min)) ret := n.Int64() + min return ret } // absolute path로 변경하기 // TODO: rename func // TODO: Refactoring func RelativeToAbsolutePath(rpath string) (string, error) { if rpath == "" { return rpath, nil } absolutePath := "" // 1. ./ ../ 경우 if strings.Contains(rpath, "./") { abs, err := filepath.Abs(rpath) if err != nil { return rpath, err } return abs, nil } // 2. ~/ 홈폴더 경우 if strings.Contains(rpath, "~") { i := strings.Index(rpath, "~") // 처음 나온 ~만 반환 if i > -1 { pathRemain := rpath[i+1:] // user home 얻기 usr, err := user.Current() if err != nil { return rpath, err } return path.Join(usr.HomeDir, pathRemain), nil } else { return rpath, nil } } if string(rpath[0]) == "/" { return rpath, nil } if string(rpath[0]) != "." && string(rpath[0]) != "/" { currentPath, err := filepath.Abs(".") if err != nil { return rpath, err } return path.Join(currentPath, rpath), nil } return absolutePath, nil } func FindEarliestString(list []string) string { largerOne := list[0] for _, v := range list { if strings.Compare(largerOne, v) > 0 { largerOne = v } } return largerOne } func CreateGrpcDeliverCommand(protocol string, body interface{}) (command.DeliverGrpc, error) { data, err := Serialize(body) if err != nil { return command.DeliverGrpc{}, err } return command.DeliverGrpc{ MessageId: xid.New().String(), RecipientList: make([]string, 0), Body: data, Protocol: protocol, }, err }
Thendont/lwjgl
modules/lwjgl/opengl/src/generated/java/org/lwjgl/opengl/EXTTextureCompressionS3TC.java
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; /** * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_compression_s3tc.txt">EXT_texture_compression_s3tc</a> extension. * * <p>This extension provides additional texture compression functionality specific to S3's S3TC format (called DXTC in Microsoft's DirectX API), subject to * all the requirements and limitations described by the extension {@link ARBTextureCompression ARB_texture_compression}.</p> * * <p>This extension supports DXT1, DXT3, and DXT5 texture compression formats. For the DXT1 image format, this specification supports an RGB-only mode and a * special RGBA mode with single-bit "transparent" alpha.</p> * * <p>Requires {@link ARBTextureCompression ARB_texture_compression}.</p> */ public final class EXTTextureCompressionS3TC { /** * Accepted by the {@code internalformat} parameter of TexImage2D, CopyTexImage2D, and CompressedTexImage2D and the {@code format} parameter of * CompressedTexSubImage2D. */ public static final int GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3; private EXTTextureCompressionS3TC() {} }
angellee1988/design-pattern
src/main/java/com/javapatterns/builder/extended/Builder.java
package com.javapatterns.builder.extended; abstract public class Builder { public abstract void buildPart1(); public abstract void buildPart2(); public abstract Product retrieveResult(); }
npocmaka/Windows-Server-2003
net/mmc/mprsnap/ifadmin.cpp
<reponame>npocmaka/Windows-Server-2003 /**********************************************************************/ /** Microsoft Windows/NT **/ /** Copyright(c) Microsoft Corporation, 1997 - 1999 **/ /**********************************************************************/ /* IFadmin Interface node information FILE HISTORY: */ #include "stdafx.h" #include "ifadmin.h" #include "iface.h" // to get InterfaceNodeHandler class #include "rtrstrm.h" // for RouterAdminConfigStream #include "rtrlib.h" // ContainerColumnInfo #include "coldlg.h" // ColumnDlg #include "column.h" // ComponentConfigStream #include "refresh.h" // IRouterRefresh #include "refrate.h" // CRefRate dialog #include "machine.h" #include "dmvcomp.h" #include "rtrerr.h" // FormatRasError #include "ports.h" // for PortsDataEntry extern "C" { #define _NOUIUTIL_H_ #include "dtl.h" #include "pbuser.h" }; /*!-------------------------------------------------------------------------- AddStaticRoute -- Collapse this later into common module This function ASSUMES that the route is NOT in the block. Author: KennT ---------------------------------------------------------------------------*/ HRESULT AddStaticRoute(MIB_IPFORWARDROW * pNewForwardRow, IInfoBase *pInfoBase, InfoBlock *pBlock, DWORD dwCount) { MIB_IPFORWARDROW IPRow; HRESULT hr = hrOK; if (pBlock == NULL) { // // No IP_ROUTE_INFO block was found; we create a new block // with the new route, and add that block to the interface-info // CORg( pInfoBase->AddBlock(IP_ROUTE_INFO, sizeof(MIB_IPFORWARDROW), (LPBYTE) pNewForwardRow, dwCount, 0) ); } else { // Either the route is completely new, or it is a route // which was moved from one interface to another. // Set a new block as the IP_ROUTE_INFO, // and include the re-configured route in the new block. MIB_IPFORWARDROW* prdTable; prdTable = new MIB_IPFORWARDROW[pBlock->dwCount + 1]; Assert(prdTable); // Copy the original table of routes ::memcpy(prdTable, pBlock->pData, pBlock->dwCount * sizeof(MIB_IPFORWARDROW)); // Append the new route prdTable[pBlock->dwCount] = *pNewForwardRow; // Replace the old route-table with the new one CORg( pInfoBase->SetData(IP_ROUTE_INFO, sizeof(MIB_IPFORWARDROW), (LPBYTE) prdTable, pBlock->dwCount + 1, 0) ); } Error: return hr; } IfAdminNodeData::IfAdminNodeData() { #ifdef DEBUG StrCpyA(m_szDebug, "IfAdminNodeData"); #endif } IfAdminNodeData::~IfAdminNodeData() { } /*!-------------------------------------------------------------------------- IfAdminNodeData::InitAdminNodeData - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeData::InitAdminNodeData(ITFSNode *pNode, RouterAdminConfigStream *pConfigStream) { HRESULT hr = hrOK; IfAdminNodeData * pData = NULL; pData = new IfAdminNodeData; SET_IFADMINNODEDATA(pNode, pData); return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeData::FreeAdminNodeData - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeData::FreeAdminNodeData(ITFSNode *pNode) { IfAdminNodeData * pData = GET_IFADMINNODEDATA(pNode); delete pData; SET_IFADMINNODEDATA(pNode, NULL); return hrOK; } STDMETHODIMP IfAdminNodeHandler::QueryInterface(REFIID riid, LPVOID *ppv) { // Is the pointer bad? if (ppv == NULL) return E_INVALIDARG; // Place NULL in *ppv in case of failure *ppv = NULL; // This is the non-delegating IUnknown implementation if (riid == IID_IUnknown) *ppv = (LPVOID) this; else if (riid == IID_IRtrAdviseSink) *ppv = &m_IRtrAdviseSink; else return CHandler::QueryInterface(riid, ppv); // If we're going to return an interface, AddRef it first if (*ppv) { ((LPUNKNOWN) *ppv)->AddRef(); return hrOK; } else return E_NOINTERFACE; } /*--------------------------------------------------------------------------- NodeHandler implementation ---------------------------------------------------------------------------*/ extern const ContainerColumnInfo s_rgIfAdminColumnInfo[]; const ContainerColumnInfo s_rgIfAdminColumnInfo[] = { { IDS_COL_INTERFACES, CON_SORT_BY_STRING, TRUE, COL_IF_NAME }, { IDS_COL_TYPE, CON_SORT_BY_STRING, TRUE, COL_STRING }, { IDS_COL_STATUS, CON_SORT_BY_STRING, TRUE, COL_STATUS }, { IDS_COL_CONNECTION_STATE, CON_SORT_BY_STRING, TRUE, COL_STRING}, { IDS_COL_DEVICE_NAME, CON_SORT_BY_STRING, TRUE, COL_IF_DEVICE}, }; IfAdminNodeHandler::IfAdminNodeHandler(ITFSComponentData *pCompData) : BaseContainerHandler(pCompData, DM_COLUMNS_IFADMIN, s_rgIfAdminColumnInfo), m_bExpanded(FALSE), m_hInstRasDlg(NULL), m_pfnRouterEntryDlg(NULL), m_pConfigStream(NULL), m_ulConnId(0), m_ulRefreshConnId(0) { // Setup the verb states for this node m_rgButtonState[MMC_VERB_REFRESH_INDEX] = ENABLED; m_bState[MMC_VERB_REFRESH_INDEX] = TRUE; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::Init - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::Init(IRouterInfo *pRouterInfo, RouterAdminConfigStream *pConfigStream) { HRESULT hr = hrOK; HKEY hkeyMachine; DWORD dwErr; // If we don't have a router info then we probably failed to load // or failed to connect. Bail out of this. if (!pRouterInfo) CORg( E_FAIL ); m_spRouterInfo.Set(pRouterInfo); // Also need to register for change notifications m_spRouterInfo->RtrAdvise(&m_IRtrAdviseSink, &m_ulConnId, 0); if (m_hInstRasDlg == NULL) m_hInstRasDlg = LoadLibrary(_T("rasdlg.dll")); if (m_hInstRasDlg) { m_pfnRouterEntryDlg= (PROUTERENTRYDLG)::GetProcAddress(m_hInstRasDlg, SZROUTERENTRYDLG); if (m_pfnRouterEntryDlg == NULL) { Trace0("MPRSNAP - Could not find function: RouterEntryDlg\n"); } } else { dwErr = GetLastError(); Trace0("MPRSNAP - failed to load rasdlg.dll\n"); } m_pConfigStream = pConfigStream; Error: return hrOK; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::DestroyHandler Implementation of ITFSNodeHandler::DestroyHandler Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::DestroyHandler(ITFSNode *pNode) { IfAdminNodeData::FreeAdminNodeData(pNode); m_spDataObject.Release(); if (m_hInstRasDlg) { FreeLibrary(m_hInstRasDlg); m_hInstRasDlg = NULL; } if (m_ulRefreshConnId) { SPIRouterRefresh spRefresh; if (m_spRouterInfo) m_spRouterInfo->GetRefreshObject(&spRefresh); if (spRefresh) spRefresh->UnadviseRefresh(m_ulRefreshConnId); } m_ulRefreshConnId = 0; if (m_spRouterInfo) { m_spRouterInfo->RtrUnadvise(m_ulConnId); m_spRouterInfo.Release(); } return hrOK; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::HasPropertyPages Implementation of ITFSNodeHandler::HasPropertyPages Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::HasPropertyPages ( ITFSNode * pNode, LPDATAOBJECT pDataObject, DATA_OBJECT_TYPES type, DWORD dwType ) { return hrOK; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnAddMenuItems Implementation of ITFSNodeHandler::OnAddMenuItems Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::OnAddMenuItems( ITFSNode *pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long *pInsertionAllowed) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = S_OK; CString stMenuItem; DWORD dwWiz; ULONG ulFlags; SPIRouterRefresh spRefresh; RouterVersionInfo routerVer; BOOL fNt4; COM_PROTECT_TRY { m_spRouterInfo->GetRouterVersionInfo(&routerVer); fNt4 = (routerVer.dwRouterVersion == 4); if ((type == CCT_SCOPE) || (dwType == TFS_COMPDATA_CHILD_CONTEXTMENU)) { long lMenuText; // // If any more menus are added to this section, then the // code for the InterfaceNodeHandler needs to be updated also. // // Add these menus at the top of the context menu if (!fNt4) { if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { lMenuText = IDS_MENU_NEW_DEMAND_DIAL_INTERFACE; stMenuItem.LoadString( lMenuText ); hr = LoadAndAddMenuItem( pContextMenuCallback, stMenuItem, lMenuText, CCM_INSERTIONPOINTID_PRIMARY_TOP, EnableAddInterface() ? 0 : MF_GRAYED); #ifdef KSL_IPINIP lMenuText = IDS_MENU_ADD_TUNNEL; stMenuItem.LoadString( lMenuText ); hr = LoadAndAddMenuItem( pContextMenuCallback, stMenuItem, lMenuText, CCM_INSERTIONPOINTID_PRIMARY_TOP, EnableAddInterface() ? 0 : MF_GRAYED); #endif //KSL_IPINIP } } // For NT4, we add the option to disable the wizard // interface. // -------------------------------------------------------- if (fNt4) { if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { lMenuText = IDS_MENU_ADD_INTERFACE; stMenuItem.LoadString(lMenuText); hr = LoadAndAddMenuItem( pContextMenuCallback, stMenuItem, lMenuText, CCM_INSERTIONPOINTID_PRIMARY_TOP, EnableAddInterface() ? 0 : MF_GRAYED); } hr = GetDemandDialWizardRegKey(OLE2CT(m_spRouterInfo->GetMachineName()), &dwWiz); if (!FHrSucceeded(hr)) dwWiz = TRUE; ulFlags = dwWiz ? MF_CHECKED : MF_UNCHECKED; if (!FHrSucceeded(hr)) ulFlags |= MF_GRAYED; if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { lMenuText = IDS_MENU_USE_DEMANDDIALWIZARD; stMenuItem.LoadString(lMenuText); hr = LoadAndAddMenuItem( pContextMenuCallback, stMenuItem, lMenuText, CCM_INSERTIONPOINTID_PRIMARY_TOP, ulFlags ); ASSERT( SUCCEEDED(hr) ); } } } } COM_PROTECT_CATCH; return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnCommand Implementation of ITFSNodeHandler::OnCommand Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::OnCommand(ITFSNode *pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = S_OK; COM_PROTECT_TRY { switch (nCommandId) { case IDS_MENU_NEW_DEMAND_DIAL_INTERFACE: case IDS_MENU_ADD_INTERFACE: OnAddInterface(); break; #ifdef KSL_IPINIP case IDS_MENU_ADD_TUNNEL: OnNewTunnel(); break; #endif //KSL_IPINIP case IDS_MENU_USE_DEMANDDIALWIZARD: OnUseDemandDialWizard(); break; case IDS_MENU_REFRESH: SynchronizeNodeData(pNode); break; default: break; } } COM_PROTECT_CATCH; return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::GetString Implementation of ITFSNodeHandler::GetString Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP_(LPCTSTR) IfAdminNodeHandler::GetString(ITFSNode *pNode, int nCol) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; COM_PROTECT_TRY { if (m_stTitle.IsEmpty()) m_stTitle.LoadString(IDS_ROUTING_INTERFACES); } COM_PROTECT_CATCH; return m_stTitle; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnCreateDataObject Implementation of ITFSNodeHandler::OnCreateDataObject Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::OnCreateDataObject(MMC_COOKIE cookie, DATA_OBJECT_TYPES type, IDataObject **ppDataObject) { HRESULT hr = hrOK; COM_PROTECT_TRY { if (!m_spDataObject) { CORg( CreateDataObjectFromRouterInfo(m_spRouterInfo, m_spRouterInfo->GetMachineName(), type, cookie, m_spTFSCompData, &m_spDataObject, NULL, FALSE) ); Assert(m_spDataObject); } *ppDataObject = m_spDataObject; (*ppDataObject)->AddRef(); COM_PROTECT_ERROR_LABEL; } COM_PROTECT_CATCH; return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnExpand - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::OnExpand(ITFSNode *pNode, LPDATAOBJECT pDataObject, DWORD dwType, LPARAM arg, LPARAM lParam) { HRESULT hr = hrOK; SPIEnumInterfaceInfo spEnumIf; SPIInterfaceInfo spIf; // If we don't have a router object, then we don't have any info, don't // try to expand. if (!m_spRouterInfo) return hrOK; // Windows NT Bug: 288427 // This flag may also get set inside of the OnChange() call. // The OnChange() will enumerate and all interfaces. // They may have been added as the result of an OnChange() // because they were added before the OnExpand() was called. // // WARNING! Be careful about adding anything to this function, // since the m_bExpanded can be set in another function. // ---------------------------------------------------------------- if (m_bExpanded) { return hrOK; } COM_PROTECT_TRY { CORg( m_spRouterInfo->EnumInterface(&spEnumIf) ); while (spEnumIf->Next(1, &spIf, NULL) == hrOK) { AddInterfaceNode(pNode, spIf); spIf.Release(); } m_bExpanded = TRUE; // Now that we have all of the nodes, update the data for // all of the nodes SynchronizeNodeData(pNode); COM_PROTECT_ERROR_LABEL; } COM_PROTECT_CATCH; return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnResultShow - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::OnResultShow(ITFSComponent *pTFSComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { BOOL bSelect = (BOOL) arg; HRESULT hr = hrOK; SPIRouterRefresh spRefresh; SPITFSNode spNode; BaseContainerHandler::OnResultShow(pTFSComponent, cookie, arg, lParam); if (bSelect) { // Call synchronize on this node m_spNodeMgr->FindNode(cookie, &spNode); if (spNode) SynchronizeNodeData(spNode); } // Un/Register for refresh advises if (m_spRouterInfo) m_spRouterInfo->GetRefreshObject(&spRefresh); if (spRefresh) { if (bSelect) { if (m_ulRefreshConnId == 0) spRefresh->AdviseRefresh(&m_IRtrAdviseSink, &m_ulRefreshConnId, 0); } else { if (m_ulRefreshConnId) spRefresh->UnadviseRefresh(m_ulRefreshConnId); m_ulRefreshConnId = 0; } } return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::ConstructNode Initializes the Domain node (sets it up). Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::ConstructNode(ITFSNode *pNode) { HRESULT hr = hrOK; IfAdminNodeData * pNodeData; if (pNode == NULL) return hrOK; COM_PROTECT_TRY { // Need to initialize the data for the Domain node pNode->SetData(TFS_DATA_IMAGEINDEX, IMAGE_IDX_INTERFACES); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, IMAGE_IDX_INTERFACES); pNode->SetData(TFS_DATA_SCOPEID, 0); // This is a leaf node in the scope pane pNode->SetData(TFS_DATA_SCOPE_LEAF_NODE, TRUE); m_cookie = reinterpret_cast<LONG_PTR>(pNode); pNode->SetData(TFS_DATA_COOKIE, m_cookie); pNode->SetNodeType(&GUID_RouterIfAdminNodeType); IfAdminNodeData::InitAdminNodeData(pNode, m_pConfigStream); pNodeData = GET_IFADMINNODEDATA(pNode); Assert(pNodeData); // Copy over this data so that the Interface node can access // this and use this to configure its interface. pNodeData->m_hInstRasDlg = m_hInstRasDlg; pNodeData->m_pfnRouterEntryDlg = m_pfnRouterEntryDlg; } COM_PROTECT_CATCH return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnAddInterface - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::OnAddInterface() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; CString stPhoneBook; CString stRouter; DWORD dwErr = NO_ERROR; SPIConsole spConsole; SPIInterfaceInfo spIfInfo; BOOL bStatus; MachineNodeData *pData; SPITFSNode spNode, spParent; DWORD dwRouterType; CString stServiceDesc; RouterVersionInfo routerVersion; if (!EnableAddInterface()) { AddHighLevelErrorStringId(IDS_ERR_TEMPNOADD); CORg( E_FAIL ); } m_spNodeMgr->FindNode(m_cookie, &spNode); spNode->GetParent(&spParent); pData = GET_MACHINENODEDATA(spParent); // Get the router type, if WAN routing is not-enabled // then we don't need to create demand-dial interfaces. // ---------------------------------------------------------------- Assert(m_spRouterInfo); dwRouterType = m_spRouterInfo->GetRouterType(); Trace1("Routertype is %d\n", dwRouterType); if ((dwRouterType & ROUTER_TYPE_WAN) == 0) { // //Show warning message box. This is not an error anymore // AfxMessageBox ( IDS_ERR_NEEDS_WAN, MB_OK|MB_ICONINFORMATION ); hr = E_FAIL; return hr; /* AddHighLevelErrorStringId(IDS_ERR_NEEDS_WAN); CORg( E_FAIL ); */ } // Get the version info. Needed later on. // ---------------------------------------------------------------- m_spRouterInfo->GetRouterVersionInfo(&routerVersion); // Check to see if the router service is running, before // continuing on. // ---------------------------------------------------------------- hr = IsRouterServiceRunning(m_spRouterInfo->GetMachineName(), NULL); if (hr == hrFalse) { // Ask the user if they want to start the service // ------------------------------------------------------------ if (AfxMessageBox(IDS_PROMPT_SERVICESTART, MB_YESNO) != IDYES) CWRg( ERROR_CANCELLED ); // Else start the service // ------------------------------------------------------------ stServiceDesc.LoadString(IDS_RRAS_SERVICE_DESC); dwErr = TFSStartService(m_spRouterInfo->GetMachineName(), c_szRemoteAccess, stServiceDesc); if (dwErr != NO_ERROR) { AddHighLevelErrorStringId(IDS_ERR_IFASERVICESTOPPED); CWRg( dwErr ); } //$todo: what to do about forcing a refresh through? // ForceGlobalRefresh(); } // Now we need to check to see if there are any routing-enabled ports // (Here we can assume that rasman is running). We can make this // check only for >= NT5, since this is when we got Rao's API. // ---------------------------------------------------------------- if ((routerVersion.dwRouterVersion >= 5) && !FLookForRoutingEnabledPorts(m_spRouterInfo->GetMachineName())) { AfxMessageBox(IDS_ERR_NO_ROUTING_ENABLED_PORTS); CWRg( ERROR_CANCELLED ); } m_spTFSCompData->GetConsole(&spConsole); // First create the phone book entry. RASENTRYDLG info; HWND hwnd; ZeroMemory( &info, sizeof(info) ); info.dwSize = sizeof(info); hwnd = NULL; spConsole->GetMainWindow(&hwnd); info.hwndOwner = hwnd; //info.hwndOwner = IFGetApp()->m_hWndHost; info.dwFlags |= RASEDFLAG_NewEntry; TRACE0("RouterEntryDlg\n"); ASSERT(m_pfnRouterEntryDlg); stRouter = m_spRouterInfo->GetMachineName(); GetPhoneBookPath(stRouter, &stPhoneBook); if (stRouter.GetLength() == 0) { stRouter = CString(_T("\\\\")) + GetLocalMachineName(); } bStatus = m_pfnRouterEntryDlg( (LPTSTR)(LPCTSTR)stRouter, (LPTSTR)(LPCTSTR)stPhoneBook, NULL, &info); Trace2("RouterEntryDlg=%f,e=%d\n", bStatus, info.dwError); if (!bStatus) { if (info.dwError != NO_ERROR) { AddHighLevelErrorStringId(IDS_ERR_UNABLETOCONFIGPBK); CWRg( info.dwError ); } CWRg( ERROR_CANCELLED ); } // CORg( CreateInterfaceInfo(&spIfInfo, info.szEntry, ROUTER_IF_TYPE_FULL_ROUTER) ); CORg( spIfInfo->SetTitle(spIfInfo->GetId()) ); CORg( spIfInfo->SetMachineName(m_spRouterInfo->GetMachineName()) ); CORg( m_spRouterInfo->AddInterface(spIfInfo) ); // Ok, we've added the interfaces, we now need to add in // the appropriate defaults for the router managers if (info.reserved2 & RASNP_Ip) { CORg( AddRouterManagerToInterface(spIfInfo, m_spRouterInfo, PID_IP) ); } if (info.reserved2 & RASNP_Ipx) { CORg( AddRouterManagerToInterface(spIfInfo, m_spRouterInfo, PID_IPX) ); } HANDLE hMachine = INVALID_HANDLE_VALUE; dwErr = ::MprConfigServerConnect((LPWSTR)m_spRouterInfo->GetMachineName(), &hMachine); if(dwErr != NOERROR || hMachine == INVALID_HANDLE_VALUE) goto Error; // //Add static routes here if any // SROUTEINFOLIST * pSRouteList = (SROUTEINFOLIST * )info.reserved; while ( pSRouteList ) { MIB_IPFORWARDROW route; SPIInfoBase spInfoBase; SPIRtrMgrInterfaceInfo spRmIf; InfoBlock * pBlock; SROUTEINFOLIST * pTemp; ZeroMemory(&route, sizeof(route) ); route.dwForwardDest = INET_ADDR(pSRouteList->RouteInfo.pszDestIP); route.dwForwardMask = INET_ADDR(pSRouteList->RouteInfo.pszNetworkMask); route.dwForwardMetric1 = _ttol(pSRouteList->RouteInfo.pszMetric ); route.dwForwardMetric5 = RTM_VIEW_MASK_UCAST | RTM_VIEW_MASK_MCAST; route.dwForwardNextHop = 0; if (routerVersion.dwRouterVersion < 5) route.dwForwardProto = PROTO_IP_LOCAL; else route.dwForwardProto = PROTO_IP_NT_STATIC; CORg( spIfInfo->FindRtrMgrInterface(PID_IP, &spRmIf) ); CORg( spRmIf->GetInfoBase( hMachine, NULL, NULL, &spInfoBase)); // Ok, go ahead and add the route // Get the IP_ROUTE_INFO block from the interface spInfoBase->GetBlock(IP_ROUTE_INFO, &pBlock, 0); CORg( AddStaticRoute(&route, spInfoBase, pBlock, 1) ); // Update the interface information CORg( spRmIf->Save(m_spRouterInfo->GetMachineName(), hMachine, NULL, NULL, spInfoBase, 0)); //Free all the entry items pTemp = pSRouteList->pNext; GlobalFree(pSRouteList->RouteInfo.pszDestIP); GlobalFree(pSRouteList->RouteInfo.pszNetworkMask); GlobalFree(pSRouteList->RouteInfo.pszMetric); GlobalFree(pSRouteList); pSRouteList = pTemp; } // disconnect it if(hMachine != INVALID_HANDLE_VALUE) { ::MprAdminServerDisconnect(hMachine); } Error: if (!FHrSucceeded(hr) && (hr != HRESULT_FROM_WIN32(ERROR_CANCELLED))) { TCHAR szErr[2048] = _T(" "); if (hr != E_FAIL) // E_FAIL doesn't give user any information { FormatRasError(hr, szErr, DimensionOf(szErr)); } AddLowLevelErrorString(szErr); // If there is no high level error string, add a // generic error string. This will be used if no other // high level error string is set. SetDefaultHighLevelErrorStringId(IDS_ERR_GENERIC_ERROR); DisplayTFSErrorMessage(NULL); } return hr; } #ifdef KSL_IPINIP /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnNewTunnel - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::OnNewTunnel() { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; SPIConsole spConsole; SPIInterfaceInfo spIfInfo; int idsErr = 0; RouterVersionInfo routerVersion; TunnelDialog tunnel; GUID guidNew; TCHAR szGuid[128]; if (!EnableAddInterface()) { idsErr = IDS_ERR_TEMPNOADD; CORg( E_FAIL ); } // Get the version info. Needed later on. // ---------------------------------------------------------------- m_spRouterInfo->GetRouterVersionInfo(&routerVersion); m_spTFSCompData->GetConsole(&spConsole); // For now, popup a dialog asking for the tunnel information // ---------------------------------------------------------------- if (tunnel.DoModal() == IDOK) { // We need to create a GUID for this tunnel. // ------------------------------------------------------------ CORg( CoCreateGuid(&guidNew) ); // Convert the GUID into a string // ------------------------------------------------------------ Verify( StringFromGUID2(guidNew, szGuid, DimensionOf(szGuid)) ); CORg( CreateInterfaceInfo(&spIfInfo, szGuid, ROUTER_IF_TYPE_TUNNEL1) ); CORg( spIfInfo->SetTitle(tunnel.m_stName) ); CORg( spIfInfo->SetMachineName(m_spRouterInfo->GetMachineName()) ); CORg( m_spRouterInfo->AddInterface(spIfInfo) ); // Need to add the IP Specific data ForceGlobalRefresh(m_spRouterInfo); } Error: if (!FHrSucceeded(hr) && (hr != HRESULT_FROM_WIN32(ERROR_CANCELLED))) { TCHAR szErr[2048]; if (idsErr) AddHighLevelErrorStringId(idsErr); FormatRasError(hr, szErr, DimensionOf(szErr)); AddLowLevelErrorString(szErr); DisplayTFSErrorMessage(NULL); } return hr; } #endif //KSL_IPINIP /*!-------------------------------------------------------------------------- IfAdminNodeHandler::AddRouterManagerToInterface - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::AddRouterManagerToInterface(IInterfaceInfo *pIf, IRouterInfo *pRouter, DWORD dwTransportId) { HRESULT hr = hrOK; SPIRtrMgrInfo spRm; SPIRtrMgrInterfaceInfo spRmIf; SPIInfoBase spInfoBase; // Get the router manager hr = pRouter->FindRtrMgr(dwTransportId, &spRm); // If this cannot find the RtrMgr, then just exit out. if (!FHrOK(hr)) goto Error; // Construct a new CRmInterfaceInfo object CORg( CreateRtrMgrInterfaceInfo(&spRmIf, spRm->GetId(), spRm->GetTransportId(), pIf->GetId(), pIf->GetInterfaceType()) ); CORg( spRmIf->SetTitle(pIf->GetTitle()) ); CORg( spRmIf->SetMachineName(pRouter->GetMachineName()) ); // Add this interface to the router-manager CORg( pIf->AddRtrMgrInterface(spRmIf, NULL) ); // get/create the infobase for this interface CORg( spRmIf->Load(pIf->GetMachineName(), NULL, NULL, NULL) ); CORg( spRmIf->GetInfoBase(NULL, NULL, NULL, &spInfoBase) ); if (!spInfoBase) CORg( CreateInfoBase(&spInfoBase) ); if (dwTransportId == PID_IP) CORg( AddIpPerInterfaceBlocks(pIf, spInfoBase) ); else { Assert(dwTransportId == PID_IPX); CORg( AddIpxPerInterfaceBlocks(pIf, spInfoBase) ); } // Save the infobase CORg( spRmIf->Save(pIf->GetMachineName(), NULL, NULL, NULL, spInfoBase, 0) ); // Mark this interface (it can now be synced with the router) spRmIf->SetFlags( spRmIf->GetFlags() | RouterSnapin_InSyncWithRouter ); // Notify RM of a new interface spRm->RtrNotify(ROUTER_CHILD_ADD, ROUTER_OBJ_RmIf, 0); Error: if (!FHrSucceeded(hr)) { // Cleanup pIf->DeleteRtrMgrInterface(dwTransportId, TRUE); } return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::OnUseDemandDialWizard - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::OnUseDemandDialWizard() { HRESULT hr = hrOK; DWORD dwWiz; hr = GetDemandDialWizardRegKey(OLE2CT(m_spRouterInfo->GetMachineName()), &dwWiz); if (FHrSucceeded(hr)) { // Ok, now toggle the switch SetDemandDialWizardRegKey(OLE2CT(m_spRouterInfo->GetMachineName()), !dwWiz); } return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::SynchronizeNodeData - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::SynchronizeNodeData(ITFSNode *pThisNode) { Assert(pThisNode); SPITFSNodeEnum spEnum; SPITFSNode spNode; DWORD dwStatus; DWORD dwConnState; DWORD dwUnReachabilityReason; int i; HRESULT hr = hrOK; InterfaceNodeData *pData; SPMprAdminBuffer spIf0Table; SPMprServerHandle sphMprServer; MPR_INTERFACE_0 * if0Table = NULL; DWORD if0Count = 0; DWORD dwTotal; DWORD dwErr; // Get the status data from the running router dwErr = ConnectRouter(m_spRouterInfo->GetMachineName(), &sphMprServer); if (dwErr == NO_ERROR) { ::MprAdminInterfaceEnum(sphMprServer, 0, (BYTE **) &spIf0Table, (DWORD) -1, &if0Count, &dwTotal, NULL); if0Table = (MPR_INTERFACE_0 *) (BYTE *) spIf0Table; } pThisNode->GetEnum(&spEnum); spEnum->Reset(); while (spEnum->Next(1, &spNode, NULL) == hrOK) { pData = GET_INTERFACENODEDATA(spNode); Assert(pData); // default status/connection states dwConnState = ROUTER_IF_STATE_UNREACHABLE; dwUnReachabilityReason = MPR_INTERFACE_NOT_LOADED; pData->dwLastError = 0; // Match the status we find to the actual status for (i=0; i<(int) if0Count; i++) { // There could be a client interface with the same name // as a router interface, so filter the client interfaces if ((if0Table[i].dwIfType != ROUTER_IF_TYPE_CLIENT) && !StriCmpW(pData->spIf->GetId(), if0Table[i].wszInterfaceName)) { break; } } // If we found an entry in the table, pull the data out if (i < (int) if0Count) { dwConnState = if0Table[i].dwConnectionState; dwUnReachabilityReason = if0Table[i].fUnReachabilityReasons; if (dwUnReachabilityReason & MPR_INTERFACE_CONNECTION_FAILURE) pData->dwLastError = if0Table[i].dwLastError; } dwStatus = pData->spIf->IsInterfaceEnabled(); // Place the data into the per-node data area pData->m_rgData[IFADMIN_SUBITEM_TITLE].m_stData = pData->spIf->GetTitle(); pData->m_rgData[IFADMIN_SUBITEM_DEVICE_NAME].m_stData = pData->spIf->GetDeviceName(); pData->m_rgData[IFADMIN_SUBITEM_TYPE].m_stData = InterfaceTypeToCString(pData->spIf->GetInterfaceType()); pData->m_rgData[IFADMIN_SUBITEM_STATUS].m_stData = StatusToCString(dwStatus); pData->m_rgData[IFADMIN_SUBITEM_CONNECTION_STATE].m_stData = ConnectionStateToCString(dwConnState); pData->dwUnReachabilityReason = dwUnReachabilityReason; pData->dwConnectionState = dwConnState; pData->fIsRunning = ::MprAdminIsServiceRunning((LPWSTR) pData->spIf->GetMachineName()); // Force MMC to redraw the nodes spNode->ChangeNode(RESULT_PANE_CHANGE_ITEM_DATA); // Cleanup spNode.Release(); } return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::EnableAddInterface - Author: KennT ---------------------------------------------------------------------------*/ BOOL IfAdminNodeHandler::EnableAddInterface() { return m_hInstRasDlg != 0; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::GetPhoneBookPath - Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::GetPhoneBookPath(LPCTSTR pszMachine, CString *pstPath) { CString str = _T(""), stPath; CString stRouter = pszMachine; if (pszMachine && StrLen(pszMachine)) { // add on the two slashes to the beginning of the machine name if (stRouter.Left(2) != _T("\\\\")) { stRouter = _T("\\\\"); stRouter += pszMachine; } // If this is not the local machine, use this string if (stRouter.GetLength() && StriCmp(stRouter, CString(_T("\\\\")) + GetLocalMachineName())) str = stRouter; } Verify( FHrSucceeded(::GetRouterPhonebookPath(str, &stPath)) ); *pstPath = stPath; return hrOK; } ImplementEmbeddedUnknown(IfAdminNodeHandler, IRtrAdviseSink) STDMETHODIMP IfAdminNodeHandler::EIRtrAdviseSink::OnChange(LONG_PTR ulConn, DWORD dwChangeType, DWORD dwObjectType, LPARAM lUserParam, LPARAM lParam) { InitPThis(IfAdminNodeHandler, IRtrAdviseSink); SPIEnumInterfaceInfo spEnumIf; SPIInterfaceInfo spIf; SPITFSNode spThisNode; SPITFSNode spNode; SPITFSNodeEnum spEnumNode; InterfaceNodeData * pNodeData; BOOL fFound, fAdded; HRESULT hr = hrOK; pThis->m_spNodeMgr->FindNode(pThis->m_cookie, &spThisNode); if (dwObjectType == ROUTER_OBJ_If) { // Force a data refresh of the current result pane if (dwChangeType == ROUTER_CHILD_DELETE) { // Go through the list of nodes, if we cannot find this // node in the list of interfaces, delete the node spThisNode->GetEnum(&spEnumNode); spEnumNode->Reset(); while (spEnumNode->Next(1, &spNode, NULL) == hrOK) { // Get the node data, look for the interface pNodeData = GET_INTERFACENODEDATA(spNode); pThis->m_spRouterInfo->FindInterface(pNodeData->spIf->GetId(), &spIf); if (spIf == NULL) { // cannot find the interface, release this node! spThisNode->RemoveChild(spNode); spNode->Destroy(); } spNode.Release(); spIf.Release(); } } else if (dwChangeType == ROUTER_CHILD_ADD) { // Enumerate through the list of interfaces // if we cannot find this interface in our current // set of nodes, then add it. spThisNode->GetEnum(&spEnumNode); CORg( pThis->m_spRouterInfo->EnumInterface(&spEnumIf) ); fAdded = FALSE; spEnumIf->Reset(); while (spEnumIf->Next(1, &spIf, NULL) == hrOK) { // Look for this interface in our list of nodes fFound = FALSE; spEnumNode->Reset(); while (spEnumNode->Next(1, &spNode, NULL) == hrOK) { pNodeData = GET_INTERFACENODEDATA(spNode); Assert(pNodeData); if (StriCmpW(pNodeData->spIf->GetId(),spIf->GetId()) == 0) { fFound = TRUE; break; } spNode.Release(); } // // If the interface was not found in the list of nodes, // then we should add the interface to the UI. // if (!fFound) { pThis->AddInterfaceNode(spThisNode, spIf); fAdded = TRUE; } spNode.Release(); spIf.Release(); } // Now that we have all of the nodes, update the data for // all of the nodes if (fAdded) pThis->SynchronizeNodeData(spThisNode); // Windows NT Bug : 288247 // Set this here, so that we can avoid the nodes being // added in the OnExpand(). pThis->m_bExpanded = TRUE; } // Determine what nodes were deleted, changed, or added // and do the appropriate action } else if (dwChangeType == ROUTER_REFRESH) { // Ok, just call the synchronize on this node pThis->SynchronizeNodeData(spThisNode); } Error: return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::CompareItems Implementation of ITFSResultHandler::CompareItems Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) IfAdminNodeHandler::CompareItems( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol) { // Get the strings from the nodes and use that as a basis for // comparison. SPITFSNode spNode; SPITFSResultHandler spResult; m_spNodeMgr->FindNode(cookieA, &spNode); spNode->GetResultHandler(&spResult); return spResult->CompareItems(pComponent, cookieA, cookieB, nCol); } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::AddMenuItems Implementation of ITFSResultHandler::AddMenuItems Use this to add commands to the context menu of the blank areas of the result pane. Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::AddMenuItems(ITFSComponent *pComponent, MMC_COOKIE cookie, LPDATAOBJECT pDataObject, LPCONTEXTMENUCALLBACK pCallback, long *pInsertionAllowed) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); SPITFSNode spNode; CString stMenu; LONG lMenuText; HRESULT hr = hrOK; m_spNodeMgr->FindNode(cookie, &spNode); hr = OnAddMenuItems(spNode, pCallback, pDataObject, CCT_RESULT, TFS_COMPDATA_CHILD_CONTEXTMENU, pInsertionAllowed); CORg( hr ); Error: return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::Command - Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP IfAdminNodeHandler::Command(ITFSComponent *pComponent, MMC_COOKIE cookie, int nCommandID, LPDATAOBJECT pDataObject) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); SPITFSNode spNode; HRESULT hr = hrOK; m_spNodeMgr->FindNode(cookie, &spNode); hr = OnCommand(spNode, nCommandID, CCT_RESULT, pDataObject, TFS_COMPDATA_CHILD_CONTEXTMENU); return hr; } typedef DWORD (APIENTRY* PRASRPCCONNECTSERVER)(LPTSTR, HANDLE *); typedef DWORD (APIENTRY* PRASRPCDISCONNECTSERVER)(HANDLE); typedef DWORD (APIENTRY* PRASRPCREMOTEGETUSERPREFERENCES)(HANDLE, PBUSER *, DWORD); typedef DWORD (APIENTRY* PRASRPCREMOTESETUSERPREFERENCES)(HANDLE, PBUSER *, DWORD); /*!-------------------------------------------------------------------------- GetDemandDialWizardRegKey - Author: KennT ---------------------------------------------------------------------------*/ HRESULT GetDemandDialWizardRegKey(LPCTSTR szMachine, DWORD *pfWizard) { ASSERT(pfWizard); BOOL fUnload = FALSE; DWORD dwErr; PBUSER pbUser; PRASRPCCONNECTSERVER pRasRpcConnectServer; PRASRPCDISCONNECTSERVER pRasRpcDisconnectServer; PRASRPCREMOTEGETUSERPREFERENCES pRasRpcRemoteGetUserPreferences; PRASRPCREMOTESETUSERPREFERENCES pRasRpcRemoteSetUserPreferences; HINSTANCE hrpcdll = NULL; HANDLE hConnection = NULL; if (!(hrpcdll = LoadLibrary(TEXT("rasman.dll"))) || !(pRasRpcConnectServer = (PRASRPCCONNECTSERVER)GetProcAddress( hrpcdll, "RasRpcConnectServer" )) || !(pRasRpcDisconnectServer = (PRASRPCDISCONNECTSERVER)GetProcAddress( hrpcdll, "RasRpcDisconnectServer" )) || !(pRasRpcRemoteGetUserPreferences = (PRASRPCREMOTEGETUSERPREFERENCES)GetProcAddress( hrpcdll, "RasRpcRemoteGetUserPreferences" )) || !(pRasRpcRemoteSetUserPreferences = (PRASRPCREMOTESETUSERPREFERENCES)GetProcAddress( hrpcdll, "RasRpcRemoteSetUserPreferences" ))) { if (hrpcdll) { FreeLibrary(hrpcdll); } return HRESULT_FROM_WIN32(GetLastError()); } dwErr = pRasRpcConnectServer((LPTSTR) szMachine, &hConnection); if (dwErr) goto Error; fUnload = TRUE; dwErr = pRasRpcRemoteGetUserPreferences(hConnection, &pbUser, UPM_Router); if (dwErr) goto Error; *pfWizard = pbUser.fNewEntryWizard; // Ignore error codes for these calls, we can't do // anything about them if they fail. pRasRpcRemoteSetUserPreferences(hConnection, &pbUser, UPM_Router); DestroyUserPreferences((PBUSER *) &pbUser); Error: if (fUnload) pRasRpcDisconnectServer(hConnection); if (hrpcdll) FreeLibrary(hrpcdll); return HRESULT_FROM_WIN32(dwErr); } /*!-------------------------------------------------------------------------- SetDemandDialWizardRegistyKey This is a function that was added for Beta1 of Steelhead. We want to allow the user to use the wizard even though it was turned off. So we have added this hack for the beta where we set the registry key for the user/ Author: KennT ---------------------------------------------------------------------------*/ HRESULT SetDemandDialWizardRegKey(LPCTSTR szMachine, DWORD fEnableWizard) { DWORD dwErr; PBUSER pbUser; BOOL fUnload = FALSE; PRASRPCCONNECTSERVER pRasRpcConnectServer; PRASRPCDISCONNECTSERVER pRasRpcDisconnectServer; PRASRPCREMOTEGETUSERPREFERENCES pRasRpcRemoteGetUserPreferences; PRASRPCREMOTESETUSERPREFERENCES pRasRpcRemoteSetUserPreferences; HINSTANCE hrpcdll = NULL; HANDLE hConnection = NULL; if (!(hrpcdll = LoadLibrary(TEXT("rasman.dll"))) || !(pRasRpcConnectServer = (PRASRPCCONNECTSERVER)GetProcAddress( hrpcdll, "RasRpcConnectServer" )) || !(pRasRpcDisconnectServer = (PRASRPCDISCONNECTSERVER)GetProcAddress( hrpcdll, "RasRpcDisconnectServer" )) || !(pRasRpcRemoteGetUserPreferences = (PRASRPCREMOTEGETUSERPREFERENCES)GetProcAddress( hrpcdll, "RasRpcRemoteGetUserPreferences" )) || !(pRasRpcRemoteSetUserPreferences = (PRASRPCREMOTESETUSERPREFERENCES)GetProcAddress( hrpcdll, "RasRpcRemoteSetUserPreferences" ))) { if (hrpcdll) { FreeLibrary(hrpcdll); } return HRESULT_FROM_WIN32(GetLastError()); } dwErr = pRasRpcConnectServer((LPTSTR) szMachine, &hConnection); if (dwErr) goto Error; fUnload = TRUE; dwErr = pRasRpcRemoteGetUserPreferences(hConnection, &pbUser, UPM_Router); if (dwErr) goto Error; pbUser.fNewEntryWizard = fEnableWizard; pbUser.fDirty = TRUE; // Ignore error codes for these calls, we can't do // anything about them if they fail. pRasRpcRemoteSetUserPreferences(hConnection, &pbUser, UPM_Router); DestroyUserPreferences((PBUSER *) &pbUser); Error: if (fUnload) pRasRpcDisconnectServer(hConnection); if (hrpcdll) FreeLibrary(hrpcdll); return HRESULT_FROM_WIN32(dwErr); } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::AddInterfaceNode Adds an interface to the UI. This will create a new result item node for each interface. Author: KennT ---------------------------------------------------------------------------*/ HRESULT IfAdminNodeHandler::AddInterfaceNode(ITFSNode *pParent, IInterfaceInfo *pIf) { InterfaceNodeHandler * pHandler; SPITFSResultHandler spHandler; SPITFSNode spNode; HRESULT hr = hrOK; pHandler = new InterfaceNodeHandler(m_spTFSCompData); spHandler = pHandler; CORg( pHandler->Init(pIf, pParent) ); CORg( CreateLeafTFSNode(&spNode, NULL, static_cast<ITFSNodeHandler *>(pHandler), static_cast<ITFSResultHandler *>(pHandler), m_spNodeMgr) ); CORg( pHandler->ConstructNode(spNode, pIf) ); // Make the node immediately visible CORg( spNode->SetVisibilityState(TFS_VIS_SHOW) ); CORg( pParent->AddChild(spNode) ); Error: return hr; } /*!-------------------------------------------------------------------------- IfAdminNodeHandler::FLookForRoutingEnabledPorts Returns TRUE if we find at least on routing-enabled port. Author: KennT ---------------------------------------------------------------------------*/ BOOL IfAdminNodeHandler::FLookForRoutingEnabledPorts(LPCTSTR pszMachineName) { PortsDataEntry portsData; PortsDeviceList portsList; PortsDeviceEntry * pPorts = NULL; BOOL fReturn = FALSE; HRESULT hr = hrOK; POSITION pos; COM_PROTECT_TRY { CORg( portsData.Initialize(pszMachineName) ); CORg( portsData.LoadDevices(&portsList) ); // Now go through the list, looking for a routing-enabled port pos = portsList.GetHeadPosition(); while (pos) { pPorts = portsList.GetNext(pos); if ((pPorts->m_dwEnableRouting) || (pPorts->m_dwEnableOutboundRouting)) { fReturn = TRUE; break; } } COM_PROTECT_ERROR_LABEL; } COM_PROTECT_CATCH; while (!portsList.IsEmpty()) delete portsList.RemoveHead(); return fReturn; } #ifdef KSL_IPINIP /*--------------------------------------------------------------------------- TunnelDialog implementation ---------------------------------------------------------------------------*/ /*!-------------------------------------------------------------------------- TunnelDialog::TunnelDialog - Author: KennT ---------------------------------------------------------------------------*/ TunnelDialog::TunnelDialog() : CBaseDialog(TunnelDialog::IDD) { } /*!-------------------------------------------------------------------------- TunnelDialog::~TunnelDialog - Author: KennT ---------------------------------------------------------------------------*/ TunnelDialog::~TunnelDialog() { } BEGIN_MESSAGE_MAP(TunnelDialog, CBaseDialog) //{{AFX_MSG_MAP(TunnelDialog) //}}AFX_MSG_MAP END_MESSAGE_MAP() /*!-------------------------------------------------------------------------- RadiusServerDialog::DoDataExchange - Author: KennT ---------------------------------------------------------------------------*/ void TunnelDialog::DoDataExchange(CDataExchange* pDX) { CBaseDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(TunnelDialog) //}}AFX_DATA_MAP } /*!-------------------------------------------------------------------------- TunnelDialog::OnInitDialog - Author: KennT ---------------------------------------------------------------------------*/ BOOL TunnelDialog::OnInitDialog() { CBaseDialog::OnInitDialog(); return TRUE; } /*!-------------------------------------------------------------------------- TunnelDialog::OnOK - Author: KennT ---------------------------------------------------------------------------*/ void TunnelDialog::OnOK() { CString stLocal, stRemote; GetDlgItemText(IDC_TUNNEL_EDIT_NAME, m_stName); m_stName.TrimLeft(); m_stName.TrimRight(); if (m_stName.IsEmpty()) { AfxMessageBox(IDS_ERR_TUNNEL_NEEDS_A_NAME); GetDlgItem(IDC_TUNNEL_EDIT_NAME)->SetFocus(); goto Error; } // Truncate the interface ID to MAX_INTERFACE_NAME_LEN characters if (m_stName.GetLength() > MAX_INTERFACE_NAME_LEN) { m_stName.GetBufferSetLength(MAX_INTERFACE_NAME_LEN+1); m_stName.ReleaseBuffer(MAX_INTERFACE_NAME_LEN); } CBaseDialog::OnOK(); Error: return; } #endif //KSL_IPINIP
domesticmouse/SmallerC
v0100/tests/libf.c
/* Quick and dirty test to ensure that all functions are actually in the library. How to compile for DOS (all mode(l)s: tiny/.COM, small/.EXE, huge/.EXE, unreal/.EXE, 32-bit DPMI/.EXE): smlrcc -dost libf.c -o libfdt.com smlrcc -doss libf.c -o libfds.exe smlrcc -dosh libf.c -o libfdh.exe smlrcc -dosu libf.c -o libfdu.exe smlrcc -dosp libf.c -o libfdp.exe How to compile for Windows: smlrcc -win libf.c -o libfw.exe How to compile for Linux: smlrcc -linux libf.c -o libfl How to compile for MacOS: smlrcc -macos libf.c -o libfm */ #include <assert.h> #include <stdint.h> #include <ctype.h> #include <locale.h> #include <math.h> #include <setjmp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <fcntl.h> #include <unistd.h> #include <sys/lng.h> #ifdef _WINDOWS void __ExitProcess(); void ExitProcess(); char* __GetCommandLineA(); char* GetCommandLineA(); unsigned __GetStdHandle(); unsigned GetStdHandle(); unsigned __GetFileType(); unsigned GetFileType(); int __CloseHandle(); int CloseHandle(); unsigned __GetLastError(); unsigned GetLastError(); void __SetLastError(); void SetLastError(); unsigned __GetProcessHeap(); unsigned GetProcessHeap(); void* __HeapAlloc(); void* HeapAlloc(); int __HeapFree(); int HeapFree(); void* __HeapReAlloc(); void* HeapReAlloc(); unsigned __CreateFileA(); unsigned CreateFileA(); int __DeleteFileA(); int DeleteFileA(); int __MoveFileA(); int MoveFileA(); int __ReadFile(); int ReadFile(); int __WriteFile(); int WriteFile(); unsigned __SetFilePointer(); unsigned SetFilePointer(); unsigned __GetFileAttributesA(); unsigned GetFileAttributesA(); unsigned __GetEnvironmentVariableA(); unsigned GetEnvironmentVariableA(); unsigned __GetTickCount(); unsigned GetTickCount(); void __GetSystemTime(); void GetSystemTime(); int __SystemTimeToTzSpecificLocalTime(); int SystemTimeToTzSpecificLocalTime(); int __TzSpecificLocalTimeToSystemTime(); int TzSpecificLocalTimeToSystemTime(); int __CreateProcessA(); int CreateProcessA(); int __GetExitCodeProcess(); int GetExitCodeProcess(); unsigned __WaitForSingleObject(); unsigned WaitForSingleObject(); void* __SetUnhandledExceptionFilter(); void* SetUnhandledExceptionFilter(); void* __LoadLibraryExA(); void* LoadLibraryExA(); int __FreeLibrary(); int FreeLibrary(); void (*__GetProcAddress())(); void (*GetProcAddress())(); #endif uintptr_t must_be_present[] = { // <ctype.h> isalnum, isalpha, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper, // <locale.h> setlocale, localeconv, // <math.h> #ifdef __SMALLER_C_32__ frexp, frexpf, ldexp, ldexpf, modf, modff, fabs, fabsf, ceil, ceilf, floor, floorf, round, roundf, trunc, truncf, sqrt, sqrtf, hypot, hypotf, exp, expf, exp2, exp2f, expm1, expm1f, pow, powf, log, logf, log2, log2f, log10, log10f, sin, sinf, cos, cosf, tan, tanf, atan2, atan2f, atan, atanf, acos, acosf, asin, asinf, fmod, fmodf, cosh, coshf, sinh, sinhf, tanh, tanhf, #endif // <setjmp.h> setjmp, longjmp, // <signal.h> signal, raise, // <stdio.h> fopen, freopen, fflush, fclose, remove, rename, fread, fgetc, getc, getchar, fgets, gets, ungetc, fwrite, fputc, putc, putchar, fputs, puts, perror, #ifdef __SMALLER_C_32__ ftell, fseek, #endif __ftell, __fseek, rewind, fgetpos, fsetpos, clearerr, ferror, feof, setvbuf, setbuf, __fileno, fileno, tmpnam, tmpfile, vfprintf, fprintf, vprintf, printf, vsprintf, sprintf, vsnprintf, snprintf, vfscanf, fscanf, vscanf, scanf, vsscanf, sscanf, // <stdlib.h> abort, _Exit, exit, atexit, malloc, calloc, free, realloc, abs, #ifdef __SMALLER_C_32__ labs, #endif div, #ifdef __SMALLER_C_32__ ldiv, #endif atoi, #ifdef __SMALLER_C_32__ atol, strtol, strtoul, strtof, strtod, atof, #endif rand, srand, bsearch, qsort, getenv, system, // <string.h> memset, memcpy, memmove, memchr, memcmp, strcpy, strncpy, strxfrm, strcat, strncat, strlen, strchr, strrchr, strstr, strspn, strcspn, strpbrk, strtok, strcmp, strncmp, strcoll, strerror, // <time.h> #ifdef __SMALLER_C_32__ clock, time, gmtime, localtime, mktime, ctime, difftime, #endif asctime, strftime, // <fcntl.h> __creat, creat, __open, open, // <unistd.h> __close, close, #ifdef __SMALLER_C_32__ __lseek, lseek, #endif __lseekp, __read, read, __write, write, __unlink, unlink, __isatty, isatty, // <sys/lng.h> __lngFromUnsigned, __lngFromSigned, __lngToUnsigned, __lngToSigned, __lngAdd, __lngSub, __lngEq, __lngUnsignedLess, __lngSignedLess, __lngLessThan0, #ifdef _WINDOWS __ExitProcess, ExitProcess, __GetCommandLineA, GetCommandLineA, __GetStdHandle, GetStdHandle, __GetFileType, GetFileType, __CloseHandle, CloseHandle, __GetLastError, GetLastError, __SetLastError, SetLastError, __GetProcessHeap, GetProcessHeap, __HeapAlloc, HeapAlloc, __HeapFree, HeapFree, __HeapReAlloc, HeapReAlloc, __CreateFileA, CreateFileA, __DeleteFileA, DeleteFileA, __MoveFileA, MoveFileA, __ReadFile, ReadFile, __WriteFile, WriteFile, __SetFilePointer, SetFilePointer, __GetFileAttributesA, GetFileAttributesA, __GetEnvironmentVariableA, GetEnvironmentVariableA, __GetTickCount, GetTickCount, __GetSystemTime, GetSystemTime, __SystemTimeToTzSpecificLocalTime, SystemTimeToTzSpecificLocalTime, __TzSpecificLocalTimeToSystemTime, TzSpecificLocalTimeToSystemTime, __CreateProcessA, CreateProcessA, __GetExitCodeProcess, GetExitCodeProcess, __WaitForSingleObject, WaitForSingleObject, __SetUnhandledExceptionFilter, SetUnhandledExceptionFilter, __LoadLibraryExA, LoadLibraryExA, __FreeLibrary, FreeLibrary, __GetProcAddress, GetProcAddress, #endif }; uintptr_t aliases[][2] = { __fileno, fileno, __creat, creat, __open, open, __close, close, #ifdef __SMALLER_C_32__ __lseek, lseek, #endif __read, read, __write, write, __unlink, unlink, __isatty, isatty, #ifdef _WINDOWS __ExitProcess, ExitProcess, __GetCommandLineA, GetCommandLineA, __GetStdHandle, GetStdHandle, __GetFileType, GetFileType, __CloseHandle, CloseHandle, __GetLastError, GetLastError, __SetLastError, SetLastError, __GetProcessHeap, GetProcessHeap, __HeapAlloc, HeapAlloc, __HeapFree, HeapFree, __HeapReAlloc, HeapReAlloc, __CreateFileA, CreateFileA, __DeleteFileA, DeleteFileA, __MoveFileA, MoveFileA, __ReadFile, ReadFile, __WriteFile, WriteFile, __SetFilePointer, SetFilePointer, __GetFileAttributesA, GetFileAttributesA, __GetEnvironmentVariableA, GetEnvironmentVariableA, __GetTickCount, GetTickCount, __GetSystemTime, GetSystemTime, __SystemTimeToTzSpecificLocalTime, SystemTimeToTzSpecificLocalTime, __TzSpecificLocalTimeToSystemTime, TzSpecificLocalTimeToSystemTime, __CreateProcessA, CreateProcessA, __GetExitCodeProcess, GetExitCodeProcess, __WaitForSingleObject, WaitForSingleObject, __SetUnhandledExceptionFilter, SetUnhandledExceptionFilter, __LoadLibraryExA, LoadLibraryExA, __FreeLibrary, FreeLibrary, __GetProcAddress, GetProcAddress, #endif }; #ifdef __HUGE__ #define __HUGE_OR_UNREAL__ #endif #ifdef __UNREAL__ #define __HUGE_OR_UNREAL__ #endif int main(void) { unsigned i; #ifdef __SMALLER_C_16__ extern unsigned short __getCS(void); extern unsigned short __getSS(void); // In Small Model .EXE programs code and data/stack are in two // different segments and so instructions can't be accessed as data. if (__getCS() == __getSS()) // fallthrough #endif for (i = 0; i < sizeof aliases / sizeof aliases[0]; i++) { uintptr_t impl = aliases[i][0]; uintptr_t wrap = aliases[i][1]; uint8_t* p = wrap; uintptr_t target; #ifdef __HUGE_OR_UNREAL__ assert(*p == 0xEA); // jmp sel16:ofs16 memcpy(&target, p + 1, sizeof target); target = ((target >> 16) << 4) + (target & 0xFFFF); #else assert(*p == 0xE9); // jmp rel16/32 memcpy(&target, p + 1, sizeof target); p += target + 1 + sizeof target; target = p; #endif assert(target == impl); } puts("All functions present!"); return 0; }
zealoussnow/chromium
media/mojo/clients/mojo_renderer_factory.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_MOJO_CLIENTS_MOJO_RENDERER_FACTORY_H_ #define MEDIA_MOJO_CLIENTS_MOJO_RENDERER_FACTORY_H_ #include <memory> #include <string> #include "build/build_config.h" #include "media/base/renderer_factory.h" #include "media/mojo/buildflags.h" #include "media/mojo/mojom/interface_factory.mojom.h" #include "media/mojo/mojom/renderer.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" namespace media { class MojoRenderer; // The default factory class for creating MojoRenderer. // // The MojoRenderer should be thought of as a pure communication layer between // media::Pipeline and a media::Renderer in a different process. // // Implementors of new media::Renderer types are encouraged to create small // wrapper factories that use MRF, rather than creating derived MojoRenderer // types, or extending MRF. See DecryptingRendererFactory and // MediaPlayerRendererClientFactory for examples of small wrappers around MRF. class MojoRendererFactory final : public RendererFactory { public: explicit MojoRendererFactory( media::mojom::InterfaceFactory* interface_factory); MojoRendererFactory(const MojoRendererFactory&) = delete; MojoRendererFactory& operator=(const MojoRendererFactory&) = delete; ~MojoRendererFactory() final; std::unique_ptr<Renderer> CreateRenderer( const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner, const scoped_refptr<base::TaskRunner>& worker_task_runner, AudioRendererSink* audio_renderer_sink, VideoRendererSink* video_renderer_sink, RequestOverlayInfoCB request_overlay_info_cb, const gfx::ColorSpace& target_color_space) final; #if defined(OS_WIN) std::unique_ptr<MojoRenderer> CreateMediaFoundationRenderer( mojo::PendingRemote<mojom::MediaLog> media_log_remote, mojo::PendingReceiver<mojom::MediaFoundationRendererExtension> renderer_extension_receiver, const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner, VideoRendererSink* video_renderer_sink); #endif // defined (OS_WIN) #if BUILDFLAG(ENABLE_CAST_RENDERER) std::unique_ptr<MojoRenderer> CreateCastRenderer( const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner, VideoRendererSink* video_renderer_sink); #endif // BUILDFLAG(ENABLE_CAST_RENDERER) #if defined(OS_ANDROID) std::unique_ptr<MojoRenderer> CreateFlingingRenderer( const std::string& presentation_id, mojo::PendingRemote<mojom::FlingingRendererClientExtension> client_extenion_ptr, const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner, VideoRendererSink* video_renderer_sink); std::unique_ptr<MojoRenderer> CreateMediaPlayerRenderer( mojo::PendingReceiver<mojom::MediaPlayerRendererExtension> renderer_extension_receiver, mojo::PendingRemote<mojom::MediaPlayerRendererClientExtension> client_extension_remote, const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner, VideoRendererSink* video_renderer_sink); #endif // defined (OS_ANDROID) private: // InterfaceFactory or InterfaceProvider used to create or connect to remote // renderer. media::mojom::InterfaceFactory* interface_factory_ = nullptr; }; } // namespace media #endif // MEDIA_MOJO_CLIENTS_MOJO_RENDERER_FACTORY_H_
moazzamwaheed2017/carparkapi
CarParkArcGisApi/CarParkArcGisApi/env/Lib/site-packages/arcgis/gis/server/_service/_vectortile.py
""" .. module:: _vectortile.py :platform: Windows, Linux :synopsis: Represents functions/classes that represents a vector tile service. .. moduleauthor:: Esri """ from __future__ import absolute_import import tempfile from .._common._base import BaseServer ######################################################################## class VectorTile(BaseServer): """ The vector tile service resource represents a vector service published with ArcGIS Server. The resource provides information about the service such as the tile info, spatial reference, initial and full extents. """ _con = None _url = None _json = None _json_dict = None def __init__(self, url, connection=None, initialize=True): """class initializer""" super(VectorTile, self).__init__(url=url, connection=connection) self._url = url self._con = connection if initialize: self._init(connection) #---------------------------------------------------------------------- def tile_fonts(self, fontstack, stack_range, out_folder=None): """This resource returns glyphs in PBF format. The template url for this fonts resource is represented in Vector Tile Style resource.""" url = "{url}/resources/fonts/{fontstack}/{stack_range}.pbf".format( url=self._url, fontstack=fontstack, stack_range=stack_range) params = {} if out_folder is None: out_folder = tempfile.gettempdir() return self._con.get(path=url, params=params, out_folder=out_folder) #---------------------------------------------------------------------- def vector_tile(self, level, row, column, out_folder=None): """This resource represents a single vector tile for the map. The bytes for the tile at the specified level, row and column are returned in PBF format. If a tile is not found, an HTTP status code of 404 (Not found) is returned.""" url = "{url}/tile/{level}/{row}/{column}.pbf".format(url=self._url, level=level, row=row, column=column) params = {} if out_folder is None: out_folder = tempfile.gettempdir() return self._con.get(path=url, params=params, out_folder=out_folder, try_json=False) #---------------------------------------------------------------------- def tile_sprite(self, out_format="sprite.json", out_folder=None): """ This resource returns sprite image and metadata """ url = "{url}/resources/sprites/{f}".format(url=self._url, f=out_format) if out_folder is None: out_folder = tempfile.gettempdir() return self._con.get(path=url, params={}, out_folder=out_folder) #---------------------------------------------------------------------- @property def info(self): """This returns relative paths to a list of resource files""" url = "{url}/resources/info".format(url=self._url) params = {"f" : "json"} return self._con.get(path=url, params=params) #---------------------------------------------------------------------- @property def iteminfo(self): """returns the item information for the service""" url = "{url}/resources/info/iteminfo".format(url=self._url) params = {"f" : "json"} return self._con.get(path=url, params=params) #---------------------------------------------------------------------- @property def metadata(self): """returns the item's metadata for the service""" url = "{url}/resources/info/metedata".format(url=self._url) params = {"f" : "json"} return self._con.get(path=url, params=params) #---------------------------------------------------------------------- @property def thumbnail(self): """returns the item's thumbnail for the service""" url = "{url}/resources/info/thumbnail".format(url=self._url) params = {"f" : "json"} return self._con.get(path=url, params=params)
Miruken-ObjC/Miruken
Miruken/Cocoa/MKSlide3DTransition.h
// // MKSlide3DTransition.h // Miruken // // Created by <NAME> on 4/6/14. // Copyright (c) 2014 <NAME>. All rights reserved. // // Based on work by <NAME> on 7/3/13. // Copyright (c) 2013 CapTech. All rights reserved. // #import "MKAnimatedTransition.h" @interface MKSlide3DTransition : MKAnimatedTransition @property (assign, nonatomic) CGFloat perspective; @end
eid101/InjazErp
modules/org.openbravo.client.application/src/org/openbravo/client/application/process/DefaultsProcessActionHandler.java
/* ************************************************************************* * The contents of this file are subject to the Openbravo Public License * Version 1.1 (the "License"), being the Mozilla Public License * Version 1.1 with a permitted attribution clause; you may not use this * file except in compliance with the License. You may obtain a copy of * the License at http://www.openbravo.com/legal/license.html * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * The Original Code is Openbravo ERP. * The Initial Developer of the Original Code is Openbravo SLU * All portions are Copyright (C) 2012-2015 Openbravo SLU * All Rights Reserved. * Contributor(s): ______________________________________. ************************************************************************ */ package org.openbravo.client.application.process; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.openbravo.base.model.Entity; import org.openbravo.base.model.ModelProvider; import org.openbravo.base.model.Property; import org.openbravo.base.structure.BaseOBObject; import org.openbravo.client.application.Parameter; import org.openbravo.client.application.ParameterUtils; import org.openbravo.client.application.Process; import org.openbravo.client.kernel.KernelConstants; import org.openbravo.client.kernel.KernelUtils; import org.openbravo.dal.core.DalUtil; import org.openbravo.dal.core.OBContext; import org.openbravo.dal.service.OBDal; import org.openbravo.data.Sqlc; import org.openbravo.model.ad.ui.Field; import org.openbravo.model.ad.ui.Tab; import org.openbravo.model.ad.ui.Window; /** * This ActionHandler is invoked when opening a Process Definition window. It is in charge of * computing default values for the parameters in the window. * * @author alostale */ public class DefaultsProcessActionHandler extends BaseProcessActionHandler { private static final Logger log = Logger.getLogger(DefaultsProcessActionHandler.class); private static final String WINDOW_REFERENCE_ID = "FF80818132D8F0F30132D9BC395D0038"; @Override protected final JSONObject doExecute(Map<String, Object> parameters, String content) { try { OBContext.setAdminMode(true); final String processId = (String) parameters.get("processId"); final Process processDefinition = OBDal.getInstance().get(Process.class, processId); JSONObject context = null; if (StringUtils.isNotEmpty(content)) { try { context = new JSONObject(content); } catch (JSONException e) { log.error("Error getting context for process definition " + processDefinition, e); } } final Map<String, String> fixedParameters = fixRequestMap(parameters, context); JSONObject defaults = new JSONObject(); JSONObject filterExpressions = new JSONObject(); final List<Parameter> orderedParams = new ArrayList<Parameter>(); // Reorder params in a list in order to compute in order based on the dependencies of default // values final boolean paramsOrdered = reorderParams(processDefinition, orderedParams, context); if (paramsOrdered) { for (Parameter param : orderedParams) { if (param.getDefaultValue() != null) { Object defValue = ParameterUtils.getParameterDefaultValue(fixedParameters, param, (HttpSession) parameters.get(KernelConstants.HTTP_SESSION), context); defaults.put(param.getDBColumnName(), defValue); } if (WINDOW_REFERENCE_ID.equals(param.getReference().getId())) { if (param.getReferenceSearchKey().getOBUIAPPRefWindowList().size() > 0) { final Window window = param.getReferenceSearchKey().getOBUIAPPRefWindowList().get(0) .getWindow(); final Tab tab = window.getADTabList().get(0); final String entityName = tab.getTable().getName(); final Entity entity = ModelProvider.getInstance().getEntity(entityName); JSONObject gridJson = new JSONObject(); for (Field field : tab.getADFieldList()) { if (field.getObuiappDefaultExpression() != null) { String rawDefaultExpression = field.getObuiappDefaultExpression(); Object defaultExpression; fixedParameters.put("filterExpressionColumnName", field.getColumn() .getDBColumnName()); defaultExpression = ParameterUtils.getJSExpressionResult(fixedParameters, (HttpSession) parameters.get(KernelConstants.HTTP_SESSION), rawDefaultExpression); if (defaultExpression != null && !defaultExpression.equals("") && !defaultExpression.equals("''")) { Property property = null; if (field.getColumn() != null) { property = KernelUtils.getInstance().getPropertyFromColumn(field.getColumn()); } else if (field.getProperty() != null) { property = DalUtil.getPropertyFromPath(entity, field.getProperty()); } if (property != null && property.getTargetEntity() != null && !property.isOneToMany()) { final BaseOBObject bob = OBDal.getInstance().get( property.getTargetEntity().getName(), defaultExpression); defaultExpression = bob.getIdentifier(); } } if (defaultExpression != null && !defaultExpression.equals("") && !defaultExpression.equals("''")) { String fieldName = field.getProperty(); if (fieldName != null) { gridJson.put(fieldName.replace(DalUtil.DOT, DalUtil.FIELDSEPARATOR), defaultExpression); } else { gridJson.put( entity.getPropertyByColumnName(field.getColumn().getDBColumnName()) .getName().replace(DalUtil.DOT, DalUtil.FIELDSEPARATOR), defaultExpression); } } } } log.debug("Implicit Filters for process " + processDefinition + ", grid: " + param.getDBColumnName() + "\n" + gridJson.toString()); filterExpressions.put(param.getDBColumnName(), gridJson); } } } log.debug("Defaults for process " + processDefinition + "\n" + defaults.toString()); JSONObject results = new JSONObject(); results.put("defaults", defaults); results.put("filterExpressions", filterExpressions); return results; } else { return new JSONObject(); } } catch (Exception e) { log.error( "Error trying getting defaults and Filter Expressions for process: " + e.getMessage(), e); return new JSONObject(); } finally { OBContext.restorePreviousMode(); } } // Returns true if the value of the parameter default value matches "@*@" private boolean isSessionDefaultValue(String rawDefaultValue) { if ("@".equals(rawDefaultValue.substring(0, 1)) && "@".equals(rawDefaultValue.substring(rawDefaultValue.length() - 1)) && rawDefaultValue.length() > 2) { return true; } else { return false; } } // Returns true if it orders all the params in a list taking into account the dependencies of the // defaults. It returns false of is not able to order all the params because of dependencies in // circle private boolean reorderParams(Process processDefinition, List<Parameter> orderedParams, JSONObject context) { final List<String> paramsAddedToOrderList = new ArrayList<String>(); List<Parameter> paramsWithDefaultValue = new ArrayList<Parameter>(); String dependentDefaultValue = null; Parameter parameter = null; int i = 0; try { for (Parameter param : processDefinition.getOBUIAPPParameterList()) { if (param.getDefaultValue() != null) { paramsWithDefaultValue.add(param); } else { orderedParams.add(param); paramsAddedToOrderList.add(param.getDBColumnName()); } } while (!paramsWithDefaultValue.isEmpty()) { if (i == paramsWithDefaultValue.size()) { log.error("Error getting default values for process: " + processDefinition.getName() + ". Default values not properly defined, circle dependencies found"); return false; } parameter = paramsWithDefaultValue.get(i); if (!isSessionDefaultValue(parameter.getDefaultValue())) { orderedParams.add(parameter); paramsAddedToOrderList.add(parameter.getDBColumnName()); paramsWithDefaultValue.remove(i); i = 0; } else { dependentDefaultValue = getDependentDefaultValue(parameter.getDefaultValue()); String inpName = "inp" + Sqlc.TransformaNombreColumna(dependentDefaultValue); if (paramsAddedToOrderList.contains(dependentDefaultValue) || context.get(inpName) != null) { orderedParams.add(parameter); paramsAddedToOrderList.add(parameter.getDBColumnName()); paramsWithDefaultValue.remove(i); i = 0; } else { i++; } } } } catch (JSONException e) { log.error("Error getting defaults and Filter Expressions for process: " + e.getMessage(), e); return false; } return true; } /** * Removes the leading and preceding '@' from a default value * * @param rawDefaultValue * defaultValue surrounded by '@', i.e. '@AD_USER_ID@' * @return the rawDefaultValue, after removing the first and the last caracters */ private String getDependentDefaultValue(String rawDefaultValue) { return rawDefaultValue.substring(1, rawDefaultValue.length() - 1); } }
JellyBrother/live-android
im/src/main/java/com/yunbao/im/bean/SystemMessageBean.java
package com.yunbao.im.bean; /** * Created by cxf on 2018/11/24. */ public class SystemMessageBean { private String content; private String addtime; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAddtime() { return addtime; } public void setAddtime(String addtime) { this.addtime = addtime; } }
willitscale/simplejavawebsocket
java/src/uk/co/n3tw0rk/websocketregistration/structures/hixie76/HIXIE76_Request.java
package uk.co.n3tw0rk.websocketregistration.structures.hixie76; public class HIXIE76_Request { }
MobButcher/Charm
src/main/java/svenhjol/charm/module/bookcases/BookcasesClient.java
<reponame>MobButcher/Charm package svenhjol.charm.module.bookcases; import net.fabricmc.fabric.api.client.screenhandler.v1.ScreenRegistry; import svenhjol.charm.annotation.ClientModule; import svenhjol.charm.loader.CharmModule; @ClientModule(module = Bookcases.class) public class BookcasesClient extends CharmModule { @Override public void register() { ScreenRegistry.register(Bookcases.SCREEN_HANDLER, BookcaseScreen::new); } }
AsahiOS/gate
usr/src/uts/common/ktli/t_kgtstate.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * University Copyright- Copyright (c) 1982, 1986, 1988 * The Regents of the University of California * All Rights Reserved * * University Acknowledgment- Portions of this document are derived from * software developed by the University of California, Berkeley, and its * contributors. */ #pragma ident "%Z%%M% %I% %E% SMI" /* * Kernel TLI-like function to get the state of an * endpoint. * * Returns: * 0 on success and "state" is set to the current state, * or a positive error code. */ #include <sys/param.h> #include <sys/types.h> #include <sys/proc.h> #include <sys/file.h> #include <sys/user.h> #include <sys/vnode.h> #include <sys/errno.h> #include <sys/stream.h> #include <sys/ioctl.h> #include <sys/stropts.h> #include <sys/strsubr.h> #include <sys/tihdr.h> #include <sys/timod.h> #include <sys/tiuser.h> #include <sys/t_kuser.h> int t_kgetstate(TIUSER *tiptr, int *state) { struct T_info_ack inforeq; struct strioctl strioc; int retval; vnode_t *vp; file_t *fp; int error; error = 0; retval = 0; fp = tiptr->fp; vp = fp->f_vnode; if (state == NULL) return (EINVAL); inforeq.PRIM_type = T_INFO_REQ; strioc.ic_cmd = TI_GETINFO; strioc.ic_timout = 0; strioc.ic_dp = (char *)&inforeq; strioc.ic_len = (int)sizeof (struct T_info_req); error = strdoioctl(vp->v_stream, &strioc, FNATIVE, K_TO_K, CRED(), &retval); if (error) return (error); if (retval) { if ((retval & 0xff) == TSYSERR) error = (retval >> 8) & 0xff; else error = t_tlitosyserr(retval & 0xff); return (error); } if (strioc.ic_len != sizeof (struct T_info_ack)) return (EPROTO); switch (inforeq.CURRENT_state) { case TS_UNBND: *state = T_UNBND; break; case TS_IDLE: *state = T_IDLE; break; case TS_WRES_CIND: *state = T_INCON; break; case TS_WCON_CREQ: *state = T_OUTCON; break; case TS_DATA_XFER: *state = T_DATAXFER; break; case TS_WIND_ORDREL: *state = T_OUTREL; break; case TS_WREQ_ORDREL: *state = T_INREL; break; default: error = EPROTO; break; } return (error); }
kwadsten/RetroStoreCard
src/esp/main/io.h
<filename>src/esp/main/io.h #pragma once #include "esp_system.h" void init_io(); uint8_t read_byte(); void write_bytes(uint8_t* data, uint16_t len);
kpagacz/software-engineering
programowanie-podstawowe/book-excercises/8-9-1.c
#include<stdio.h> int multiply(int a, int* b) { if(a >= 1 && a <= 100) { *b = (*b)*a; return 1; } else { return 0; } } int main(void) { int numbers; scanf("%i", &numbers); int one = 1; int* res = &one; int single_number; int multplication_happened = 0; for(int i = 0; i < numbers; i++) { scanf("%i", &single_number); if(multiply(single_number, res)) { multplication_happened = 1; } } if(multplication_happened) { printf("%i\n", *res); } else { printf("There were no numbers from <1, 100>\n"); } return 0; }
ponyville/kilim
src/kilim/KilimClassLoader.java
<filename>src/kilim/KilimClassLoader.java package kilim; /** * Extends Classloader just to have access to the (protected) findLoadedClass method */ public class KilimClassLoader extends ClassLoader { public KilimClassLoader(ClassLoader cl) { super(cl); } public Class<?> getLoadedClass(String className) { return super.findLoadedClass(className); } public boolean isLoaded(String className) { return getLoadedClass(className) != null; } }
sunkun1210/cloud
imooc-c6-3-spring-dtx-jms-db/src/main/java/com/immoc/example/springtx/service/CustomerService.java
<gh_stars>1-10 package com.immoc.example.springtx.service; import com.immoc.example.springtx.dao.CustomerRepository; import com.immoc.example.springtx.domain.Customer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Created by mavlarn on 2018/1/24. */ @Service public class CustomerService { private static final Logger LOG = LoggerFactory.getLogger(CustomerService.class); @Autowired private CustomerRepository customerRepository; @Autowired private JmsTemplate jmsTemplate; @Transactional @JmsListener(destination = "customer:msg:new") public void handle(String msg) { LOG.info("Get msg1:{}", msg); Customer customer = new Customer(); customer.setUsername(msg); customer.setDeposit(100); customerRepository.save(customer); if (msg.contains("error1")) { throw new RuntimeException("Error1"); } jmsTemplate.convertAndSend("customer:msg:reply", msg + " created."); if (msg.contains("error2")) { throw new RuntimeException("Error2"); } } @Transactional public Customer create(Customer customer) { LOG.info("CustomerService In Annotation create customer:{}", customer.getUsername()); if (customer.getId() != null) { throw new RuntimeException("用户已经存在"); } customer.setUsername("Annotation:" + customer.getUsername()); customer = customerRepository.save(customer); if (customer.getUsername().contains("error1")) { throw new RuntimeException("Error1"); } jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername() + " created."); if (customer.getUsername().contains("error2")) { throw new RuntimeException("Error2"); } return customer; } }
TheKiddos/faith
code/src/main/java/org/thekiddos/faith/dtos/ProposalDto.java
package org.thekiddos.faith.dtos; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ProposalDto { private Long id; @NotNull @Min(1) private double amount; @NotNull private long projectId; @NotNull private long freelancerId; private String status; }
nkapinos/chorus
spec/models/events/note_spec.rb
<reponame>nkapinos/chorus<gh_stars>1-10 # encoding: utf-8 require "spec_helper" require_relative "helpers" describe Events::Note do extend EventHelpers let(:actor) { users(:not_a_member) } let(:gpdb_data_source) { data_sources(:default) } let(:hdfs_data_source) { hdfs_data_sources(:hadoop) } let(:gnip_data_source) { gnip_data_sources(:default) } let(:workspace) { workspaces(:public) } let(:workfile) { workfiles(:public) } let(:tableau_workfile) { workfiles(:tableau) } let(:dataset) { datasets(:table) } let(:hdfs_entry) do hdfs_data_source.hdfs_entries.create!(:path => '/data/test.csv', :modified_at => "2010-10-24 22:00:00") end describe "associations" do it { should belong_to(:promoted_by).class_name('User') } end it "requires an actor" do note = Events::Note.new note.should have_error_on(:actor_id) end describe ".insights" do let(:insight) { events(:insight_on_greenplum) } let(:normal) { events(:note_on_dataset) } it "should only include insights" do insights = described_class.insights insights.should include(insight) insights.should_not include(normal) end end describe "NoteOnDataSource" do subject do Events::NoteOnDataSource.create!({ :actor => actor, :data_source => gpdb_data_source, :body => "This is the body" }, :as => :create) end its(:data_source) { should == gpdb_data_source } its(:targets) { should == {:data_source => gpdb_data_source} } its(:additional_data) { should == {'body' => "This is the body"} } it_creates_activities_for { [actor, gpdb_data_source] } it_creates_a_global_activity end describe "NoteOnHdfsDataSource" do subject do Events::NoteOnHdfsDataSource.create!({ :actor => actor, :hdfs_data_source => hdfs_data_source, :body => "This is the body" }, :as => :create) end it "sets the data source set correctly" do subject.hdfs_data_source.should == hdfs_data_source end it "sets the data source as the target" do subject.targets.should == {:hdfs_data_source => hdfs_data_source} end it "sets the body" do subject.body.should == "This is the body" end it_creates_activities_for { [actor, hdfs_data_source] } it_creates_a_global_activity end describe "NoteOnHdfsFile" do subject do Events::NoteOnHdfsFile.create!({ :actor => actor, :hdfs_file => hdfs_entry, :body => "This is the text of the note" }, :as => :create) end its(:hdfs_file) { should == hdfs_entry } its(:targets) { should == {:hdfs_file => hdfs_entry} } its(:additional_data) { should == {'body' => "This is the text of the note"} } it_creates_activities_for { [actor, hdfs_entry] } it_creates_a_global_activity end describe "NoteOnWorkspace" do subject do Events::NoteOnWorkspace.new({ :actor => actor, :workspace => workspace, :body => "This is the text of the note on the workspace" }, :as => :create) end its(:workspace) { should == workspace } its(:targets) { should == {:workspace => workspace} } its(:additional_data) { should == {'body' => "This is the text of the note on the workspace"} } it_creates_activities_for { [actor, workspace] } it_does_not_create_a_global_activity it_behaves_like 'event associated with a workspace' it "can not be created on an archived workspace" do note = Events::NoteOnWorkspace.new(:workspace => workspaces(:archived), :actor => actor, :body => 'WOO!') note.should have_error_on(:workspace) end it "is valid if the workspace later becomes archived" do subject.save! workspace.archived = 'true' workspace.archiver = actor workspace.save! subject.reload subject.should be_valid end end describe "NoteOnWorkfile" do let(:workspace) { nil } subject do Events::NoteOnWorkfile.create!({ :actor => actor, :workfile => workfile, :workspace => workspace, :body => "This is the text’s of the note on the workfile" }, :as => :create) end its(:workfile) { should == workfile } its(:targets) { should == {:workfile => workfile} } its(:additional_data) { should == {'body' => "This is the text’s of the note on the workfile"} } it_creates_activities_for { [actor, workfile, workfile.workspace] } it_does_not_create_a_global_activity it "has an event on the workspace" do subject workfile.workspace.events.should include(subject) end it "can access associated workfiles when they are deleted" do subject workfile.destroy subject.reload.workfile.should == workfile subject.workfile.should be_deleted end describe "when a different workspace is passed" do let(:workspace) { workspaces(:private) } it "sets the workspace to the workspace of the workfile" do subject.workspace.should == workfile.workspace end end end describe "NoteOnDataset" do subject do Events::NoteOnDataset.create!({ :actor => actor, :dataset => dataset, :body => "<3 <3 <3" }, :as => :create) end its(:dataset) { should == dataset } its(:targets) { should == {:dataset => dataset} } its(:additional_data) { should == {'body' => "<3 <3 <3"} } it_creates_activities_for { [actor, dataset] } it_creates_a_global_activity end describe "NoteOnWorkspaceDataset" do subject do Events::NoteOnWorkspaceDataset.create({ :actor => actor, :dataset => dataset, :workspace => workspace, :body => "<3 <3 <3" }, :as => :create) end its(:dataset) { should == dataset } its(:targets) { should == {:dataset => dataset, :workspace => workspace} } its(:additional_data) { should == {'body' => "<3 <3 <3"} } context "when workspace is private" do let(:workspace) { workspaces(:private_with_no_collaborators) } it "is not valid if the actor is not a member of a private workspace" do subject.should have_error_on(:workspace).with_message(:not_a_member) end end it "is valid if the workspace is public" do workspace.should be_public subject.should be_valid end it_creates_activities_for { [actor, dataset, workspace] } it_does_not_create_a_global_activity end describe "NoteOnGnipDataSource" do subject do Events::NoteOnGnipDataSource.create!({ :actor => actor, :gnip_data_source => gnip_data_source, :body => "This is the body" }, :as => :create) end its(:gnip_data_source) { should == gnip_data_source } its(:targets) { should == {:gnip_data_source => gnip_data_source} } its(:additional_data) { should == {'body' => "This is the body"} } it_creates_activities_for { [actor, gnip_data_source] } it_creates_a_global_activity end describe "search" do it "indexes text fields" do Events::Note.should have_searchable_field :body end describe "with a target" do let(:workfile) { workfiles(:public) } let(:workspace) { workfile.workspace } let(:subclass1) do Class.new(Events::Note) { has_targets :workspace, :workfile } end let(:note) { subclass1.new({:workspace => workspace, :workfile => workfile}, :as => :create) } it "delegates grouping, type, and security fields to its first 'target'" do note.grouping_id.should == workspace.grouping_id note.grouping_id.should_not be_blank note.type_name.should == workspace.type_name note.type_name.should_not be_blank note.security_type_name.should == workspace.security_type_name end end end describe "#promote_to_insight" do let(:promoter) { users(:default) } let(:creator) { users(:owner) } let(:event) { FactoryGirl.create :note_on_data_source_event, :actor => creator } subject { event.promote_to_insight } before do set_current_user(promoter) end it { should be_true } it "saves the note" do expect { event.promote_to_insight }.to change(event, :updated_at) end describe "it saves a note after promoting it to an insight" do subject do event.promote_to_insight event.reload end it { should be_insight } its(:promoted_by) { should == promoter } its(:actor) { should == creator } its(:promotion_time) { should be_within(1.minute).of(Time.current) } end end describe "#demote_from_insight" do let(:demoter) { users(:default) } let(:promoter) { users(:owner) } let(:creator) { event.actor } let(:event) do Events::NoteOnWorkspace.last.tap do |note| set_current_user(promoter) note.promote_to_insight set_current_user(demoter) end end subject { event.demote_from_insight } it { should be_true } it "saves the note" do expect { event.demote_from_insight }.to change(event, :updated_at) end describe "it saves a note after demoting it from an insight" do subject do event.demote_from_insight event.reload end it { should_not be_insight } its(:promoted_by) { should == promoter } its(:actor) { should == creator } end end describe "demotable_by" do let(:promoter) { insight.promoted_by } let(:actor) { insight.actor } let(:workspace_owner) { insight.workspace.owner } let(:admin) { users(:admin) } let(:rando) { FactoryGirl.create(:user) } let(:insight) do Events::NoteOnWorkspace.last.tap do |note| set_current_user(users(:the_collaborator)) note.promote_to_insight end end it "returns true if the given user is the insight's promoter, workspace owner or admin" do insight.demotable_by(promoter).should == true insight.demotable_by(workspace_owner).should == true insight.demotable_by(admin).should == true insight.demotable_by(rando).should == false end context "when there is no workspace" do let(:insight) { events(:insight_on_greenplum) } it "returns true if the given user is the promoter or an admin" do insight.demotable_by(promoter).should == true insight.demotable_by(admin).should == true insight.demotable_by(rando).should == false end end end describe "#build_for(model, params)" do let(:user) { users(:owner) } before do set_current_user(user) end context "workspace is archived" do it "builds a note with errors" do workfile.workspace.archived = true workfile.workspace.archiver = user workfile.workspace.save! note = Events::Note.build_for(workfile, { :body => "More crazy content", :workspace_id => workspace.id }) note.should have_error_on(:workspace).with_message(:archived) end end it "builds a note on a greenplum data source" do gpdb_data_source = data_sources(:default) note = Events::Note.build_for(gpdb_data_source, { :body => "Some crazy content" }) note.save! note.should be_a(Events::NoteOnDataSource) note.data_source.should == gpdb_data_source note.body.should == "Some crazy content" note.actor.should == user end it "builds a note on a oracle data source" do data_source = data_sources(:oracle) note = Events::Note.build_for(data_source, { :body => "Some crazy content" }) note.save! note.should be_a(Events::NoteOnDataSource) note.data_source.should == data_source note.body.should == "Some crazy content" note.actor.should == user end it "builds a note on a hadoop data source" do hdfs_data_source = hdfs_data_sources(:hadoop) note = Events::Note.build_for(hdfs_data_source, { :body => "Some crazy content" }) note.save! note.hdfs_data_source.should == hdfs_data_source note.should be_a(Events::NoteOnHdfsDataSource) note.body.should == "Some crazy content" note.actor.should == user end it "builds a note on an hdfs file" do note = Events::Note.build_for(hdfs_entry, { :body => "Some crazy content" }) note.save! note.should be_a(Events::NoteOnHdfsFile) note.actor.should == user note.hdfs_file.hdfs_data_source.should == hdfs_data_source note.hdfs_file.path.should == "/data/test.csv" note.body.should == "Some crazy content" end it "builds a note on a Gnip Data Source" do note = Events::Note.build_for(gnip_data_source, { :body => "Some crazy content" }) note.save! note.gnip_data_source.should == gnip_data_source note.should be_a(Events::NoteOnGnipDataSource) note.body.should == "Some crazy content" note.actor.should == user end it "builds a note on a workfile" do note = Events::Note.build_for(workfile, { :body => "Workfile content" }) note.save! note.should be_a(Events::NoteOnWorkfile) note.actor.should == user note.workfile.should == workfile note.workspace.should == workfile.workspace note.body.should == "Workfile content" end it "builds a note on a tableau workfile" do note = Events::Note.build_for(tableau_workfile, { :body => "Workfile content" }) note.save! note.should be_a(Events::NoteOnWorkfile) note.actor.should == user note.workfile.should == tableau_workfile note.workspace.should == tableau_workfile.workspace note.body.should == "Workfile content" end it "builds a note on a dataset" do note = Events::Note.build_for(dataset, { :body => "Crazy dataset content" }) note.save! note.should be_a(Events::NoteOnDataset) note.actor.should == user note.dataset.should == dataset note.body.should == "Crazy dataset content" end it "builds a note on a dataset in a workspace" do note = Events::Note.build_for(dataset, { :body => "Crazy workspace dataset content", :workspace_id => workspace.id }) note.save! note.should be_a(Events::NoteOnWorkspaceDataset) note.actor.should == user note.dataset == dataset note.workspace == workspace note.body.should == "Crazy workspace dataset content" end it "doesn't always create insights" do note = Events::Note.build_for(dataset, { :body => "Crazy workspace dataset content", :workspace_id => workspace.id }) note.save! note.insight.should_not == true note.promoted_by.should == nil note.promotion_time.should == nil end it "builds an insight" do note = Events::Note.build_for(dataset, { :body => "Crazy workspace dataset content", :workspace_id => workspace.id, :is_insight => true }) note.save! note.insight.should == true note.promoted_by.should == user note.promotion_time.should_not == nil end it "uses the target workspace over the workspace_id" do note = Events::Note.build_for(workfile, { :body => "Workfile content", :workspace_id => workspaces(:empty_workspace).id }) note.save! note.workfile.should == workfile note.workspace.should == workfile.workspace note = Events::Note.build_for(workfile, { :body => "Workfile content", :workspace_id => workspaces(:empty_workspace).id }) note.save! note.workfile.should == workfile note.workspace.should == workfile.workspace end end end
guiles00/tbpmnio
node_modules/diagram-js/test/spec/features/tooltips/TooltipsSpec.js
<reponame>guiles00/tbpmnio<filename>node_modules/diagram-js/test/spec/features/tooltips/TooltipsSpec.js 'use strict'; /* global bootstrapDiagram, inject */ var forEach = require('lodash/collection/forEach'), assign = require('lodash/object/assign'), every = require('lodash/collection/every'), domify = require('min-dom/lib/domify'); var tooltipsModule = require('../../../../lib/features/tooltips'); function asMatrix(transformStr) { if (transformStr && transformStr !== 'none') { var m = transformStr.match(/[+-]?\d*[.]?\d+(?=,|\))/g); return { a: parseFloat(m[0]), b: parseFloat(m[1]), c: parseFloat(m[2]), d: parseFloat(m[3]), e: parseFloat(m[4]), f: parseFloat(m[5]) }; } } function isVisible(element) { return window.getComputedStyle(element).display !== 'none'; } function highlight(element) { assign(element.style, { background: 'fuchsia', minWidth: '10px', minHeight: '10px' }); return element; } function createOverlay() { var element = highlight(domify('<div>TEST<br/>TEST</div>')); assign(element.style, { width: 40, height: 40 }); return element; } function queryTooltip(id) { return document.querySelector('[data-tooltip-id=' + id + ']'); } describe('features/tooltips', function() { describe('bootstrap', function() { beforeEach(bootstrapDiagram({ modules: [ tooltipsModule ] })); it('should expose api', inject(function(tooltips) { expect(tooltips).to.exist; expect(tooltips.get).to.exist; expect(tooltips.add).to.exist; expect(tooltips.remove).to.exist; })); }); describe('#add', function() { beforeEach(bootstrapDiagram({ modules: [ tooltipsModule ] })); it('should add <div>', inject(function(tooltips, canvas) { // when var id = tooltips.add({ position: { x: 100, y: 200 }, html: '<div class="tooltip"></div>' }); // then expect(id).to.exist; expect(tooltips.get(id)).to.exist; expect(queryTooltip(id)).to.exist; })); it('should add Element', inject(function(tooltips, canvas) { // when var id = tooltips.add({ position: { x: 100, y: 200 }, html: highlight(domify('<div class="tooltip" />')) }); // then var tooltip = tooltips.get(id); expect(tooltip).to.exist; expect(isVisible(tooltips._tooltipRoot)).to.be.true; expect(isVisible(tooltip.html)).to.be.true; expect(queryTooltip(id)).to.exist; })); it('should add with timeout', function(done) { inject(function(tooltips, canvas) { // when var id = tooltips.add({ position: { x: 100, y: 200 }, timeout: 200, html: '<div class="tooltip" id="html-ov"></div>' }); // then expect(id).to.exist; expect(tooltips.get(id)).to.exist; // but when setTimeout(function() { expect(tooltips.get(id)).not.to.exist; done(); }, 300); })(); }); }); describe('#remove', function() { beforeEach(bootstrapDiagram({ modules: [ tooltipsModule ] })); it('should remove tooltip', inject(function(tooltips, canvas) { // given var id = tooltips.add({ position: { x: 100, y: 200 }, html: highlight(domify('<div class="tooltip" id="html-ov2"></div>')) }); // when tooltips.remove(id); // then expect(tooltips.get(id)).not.to.exist; expect(queryTooltip(id)).not.to.exist; })); it('should remove non-existing', inject(function(tooltips) { expect(function() { tooltips.remove('non-existing'); }).not.to.throw; })); }); describe('positioning', function() { beforeEach(bootstrapDiagram({ modules: [ tooltipsModule ] })); function position(tooltipHtml) { var parent = tooltipHtml.parentNode; var result = {}; forEach([ 'left', 'right', 'top', 'bottom' ], function(pos) { var p = parseInt(parent.style[pos]); if (!isNaN(p)) { result[pos] = p; } }); return result; } it('should position absolute', inject(function(tooltips) { var html = createOverlay(); // when tooltips.add({ position: { x: 100, y: 50 }, html: html }); // then expect(position(html)).to.eql({ left: 100, top: 50 }); })); }); describe('zoom behavior', function() { beforeEach(bootstrapDiagram({ modules: [ tooltipsModule ], canvas: { deferUpdate: false } })); function isVisible(element) { return element.parentNode.style.display !== 'none'; } it('should respect default min/max show rules', inject(function(tooltips, canvas) { // given var html = createOverlay(); tooltips.add({ position: { x: 20, y: 50 }, html: html }); // when zoom in visibility range canvas.zoom(0.7); // then expect(isVisible(html)).to.be.true; // when zoom below visibility range canvas.zoom(0.6); // then expect(isVisible(html)).to.be.false; // when zoom in visibility range canvas.zoom(3.0); // then expect(isVisible(html)).to.be.true; // when zoom above visibility range canvas.zoom(6.0); // then expect(isVisible(html)).to.be.false; })); it('should respect tooltip specific min/max rules', inject(function(tooltips, canvas) { // given var html = createOverlay(); tooltips.add({ position: { x: 20, y: 50 }, html: html, show: { minZoom: 0.3, maxZoom: 4 } }); // when zoom in visibility range canvas.zoom(0.6); // then expect(isVisible(html)).to.be.true; // when zoom on visibility range border canvas.zoom(0.3); // then expect(isVisible(html)).to.be.true; // when zoom below visibility range canvas.zoom(0.2); // then expect(isVisible(html)).to.be.false; // when zoom in visibility range canvas.zoom(3); // then expect(isVisible(html)).to.be.true; // when zoom on visibility range border canvas.zoom(4.0); // then expect(isVisible(html)).to.be.true; // when zoom above visibility range canvas.zoom(4.1); // then expect(isVisible(html)).to.be.false; })); }); describe('scroll/zoom behavior', function() { beforeEach(bootstrapDiagram({ modules: [ tooltipsModule ], canvas: { deferUpdate: false } })); function transformMatrix(element) { return asMatrix(element.style.transform); } function isMatrixEql(original, test) { return every(original, function(val, key) { if (key === 'e') { return val <= -500 || val > -520; } return val === test[key]; }); } it('should not be transformed initially', inject(function(tooltips, canvas) { // given // diagram got newly created // then expect(transformMatrix(tooltips._tooltipRoot)).to.not.exist; })); it('should transform tooltip container on scroll', inject(function(tooltips, canvas) { // when canvas.scroll({ dx: 100, dy: 50 }); // then expect(transformMatrix(tooltips._tooltipRoot)).to.eql({ a : 1, b : 0, c : 0, d : 1, e : 100, f : 50 }); })); it('should transform tooltip container on zoom', inject(function(tooltips, canvas) { // when canvas.zoom(2); var containerTransform = asMatrix(tooltips._tooltipRoot.style.transform); var result = { a : 2, b : 0, c : 0, d : 2, e : -501, f : -300 }; // then expect(isMatrixEql(containerTransform, result)).to.be.true; })); it('should transform tooltip container on zoom (with position)', inject(function(tooltips, canvas) { // when canvas.zoom(2, { x: 300, y: 300 }); // then expect(transformMatrix(tooltips._tooltipRoot)).to.eql({ a : 2, b : 0, c : 0, d : 2, e : -300, f : -300 }); })); }); });
solemnwarning/KatanaEngine
shared/shared_menu.h
/* Copyright (C) 2011-2016 OldTimes Software This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef SHARED_MENU_H #define SHARED_MENU_H typedef enum { MENU_IMAGE, MENU_MODEL, MENU_WINDOW, MENU_BUTTON, MENU_BUTTON_OK, MENU_BUTTON_CANCEL, MENU_BUTTON_YESNO, // Special types MENU_TYPE_HUD, MENU_TYPE_MENU } MenuType_t; // Different menu states. #define MENU_STATE_LOADING 1 // Display loading menu. #define MENU_STATE_HUD 2 // Display HUD. #define MENU_STATE_SCOREBOARD 4 // Display player score. #define MENU_STATE_MENU 8 // Display the menu. #define MENU_STATE_PAUSED 16 // Display pause menu. typedef struct Menu_s { char *cName, // The name of the menu element. *cResource, // If based on a model/image this is the path of the resource it needs. *cContent; // Content, meaning the text that could be inside the window. struct Menu_s *mParent; // The parent of the element. If an element has a parent and the parent moves then this will move with it. int iPosition[1]; // Position (X & Y) of the element. int iScale[1]; // Scale (width & height) of the element. MenuType_t mMenuType; // The type of element. bool bActive, // Is it active? bMoveable; // Can the element be moved? float fAlpha; } Menu_t; // Exported functions typedef struct { int iVersion; // Inteface version. void (*Initialize)(void); // Called when we initialize the module. void (*Draw)(void); // Called whenever we draw the menu. void (*Input)(int iKey); // Called whenever we press a key while in menu mode. void (*AddState)(int iState); // Add onto the current menu state. void (*RemoveState)(int iState); // Remove a state from the menus current state set. void (*SetState)(int iState); // Forcefully set a new state. void (*Shutdown)(void); // Called upon shutdown. int (*GetState)(void); // Get the menus current state so we can check it. } MenuExport_t; #define MENU_VERSION (sizeof(MenuExport_t)+sizeof(ModuleImport_t)) #endif
mehmet-biter/dexwebapp
src/redux/actions/WalletConnect.js
export const CONNECT_TO_WALLET_CONNECT = 'CONNECT_TO_WALLET_CONNECT'; export const CONNECT_TO_WALLET_CONNECT_COMPLETE = 'CONNECT_TO_WALLET_CONNECT_COMPLETE'; export function connectToWalletConnect(startConnecting) { return { type: CONNECT_TO_WALLET_CONNECT, payload: { startConnecting, }, }; } export function connectToWalletConnectComplete() { return { type: CONNECT_TO_WALLET_CONNECT_COMPLETE, payload: {}, }; }
qiagen/LogATE
src/CursATE/Curses/Field/Input.cpp
#include "CursATE/Curses/Field/Input.hpp" #include "CursATE/Curses/Field/detail/resizePadded.hpp" namespace CursATE::Curses::Field { FieldSize size(Input const& i) { const auto minimumReasonableInputFieldWidth = 3; return FieldSize{ i.label_.size(), minimumReasonableInputFieldWidth }; } void draw(Window& win, const ScreenPosition sp, const FieldSize fs, Input const& i, const bool selected) { const auto markAttr = A_REVERSE; const auto commonAttr = A_UNDERLINE; mvwprintw(win.get(), sp.row_.value_, sp.column_.value_, "%s ", detail::resizePadded(i.label_, fs.label_, 0).c_str() ); auto attr = commonAttr; if(selected) attr |= markAttr; wattr_on( win.get(), attr, nullptr ); wprintw(win.get(), "%s", detail::resizePadded(i.value_, fs.value_, i.cursorPosition_).c_str() ); wattr_off( win.get(), attr, nullptr ); } }
JackovAlltrades/solid-react-components
src/lib/components/FormModel/children/Form/UI/Heading/heading.test.js
import React from 'react'; import { render, cleanup } from '@testing-library/react'; import { getByText } from '@testing-library/dom'; import { Heading } from './heading.component'; import { UI } from '@constants'; import 'jest-dom/extend-expect'; afterAll(cleanup); test('Renders without crashing', () => { const data = {}; const { container } = render(<Heading data={data} />); expect(container).toBeTruthy(); }); test('Renders the heading', () => { const data = { [UI.CONTENTS]: 'heading' }; const { container } = render(<Heading data={data} />); expect(getByText(container, 'heading')).toBeTruthy(); });
yennanliu/Python_basics
leetcode_python/Dynamic_Programming/minimum-insertion-steps-to-make-a-string-palindrome.py
""" 1312. Minimum Insertion Steps to Make a String Palindrome Hard Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. Example 1: Input: s = "zzazz" Output: 0 Explanation: The string "zzazz" is already palindrome we don't need any insertions. Example 2: Input: s = "mbadm" Output: 2 Explanation: String can be "mbdadbm" or "mdbabdm". Example 3: Input: s = "leetcode" Output: 5 Explanation: Inserting 5 characters the string becomes "leetcodocteel". Constraints: 1 <= s.length <= 500 s consists of lowercase English letters. """ # V0 # V1 # IDEA : DP # https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/470706/JavaC%2B%2BPython-Longest-Common-Sequence # IDEA : # Intuition # Split the string s into to two parts, # and we try to make them symmetrical by adding letters. # # The more common symmetrical subsequence they have, # the less letters we need to add. # # Now we change the problem to find the length of longest common sequence. # This is a typical dynamic problem. # # # Explanation # Step1. # Initialize dp[n+1][n+1], # wheredp[i][j] means the length of longest common sequence between # i first letters in s1 and j first letters in s2. # # Step2. # Find the the longest common sequence between s1 and s2, # where s1 = s and s2 = reversed(s) # # Step3. # return n - dp[n][n] class Solution(object): def minInsertions(self, s): n = len(s) dp = [[0] * (n + 1) for i in range(n + 1)] for i in xrange(n): for j in range(n): dp[i + 1][j + 1] = dp[i][j] + 1 if s[i] == s[~j] else max(dp[i][j + 1], dp[i + 1][j]) return n - dp[n][n] # V1' # IDEA : DP # https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/476662/Python-Clean-DP class Solution(object): def minInsertions(self, s): n = len(s) dp = [[0] * n for _ in range(n)] for j in range(n): for i in range(j-1,-1,-1): dp[i][j] = dp[i+1][j-1] if s[i] == s[j] else min(dp[i+1][j], dp[i][j-1]) + 1 return dp[0][n-1] # V1'' # IDEA : DP # https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/1630626/Python-or-DP-or-Simplest-Solution class Solution: def minInsertions(self, s: str, lookup={}) -> int: if len(s) <= 1: return 0 if s not in lookup: if s[0] == s[-1]: lookup[s] = self.minInsertions(s[1:-1], lookup) else: lookup[s] = 1 + min(self.minInsertions(s[1:], lookup), self.minInsertions(s[:-1], lookup)) return lookup[s] # V1''' # IDEA : DP # https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/470733/Python-concise-dp-solution class Solution: def minInsertions(self, s: str) -> int: N=len(s) dp=[[0]*(N+1) for _ in range(N+1)] for gap in range(N): for left in range(N-gap): right=left+gap if s[left]==s[right]: dp[left][right]=dp[left+1][right-1] else: dp[left][right]=min(dp[left+1][right],dp[left][right-1])+1 return dp[0][N-1] # V2
Javiyack/zio-lambda
lambda-event/src/main/scala/zio/lambda/event/S3Event.scala
<filename>lambda-event/src/main/scala/zio/lambda/event/S3Event.scala<gh_stars>10-100 package zio.lambda.event import zio.json._ final case class S3Event() object S3Event { implicit val decoder: JsonDecoder[S3Event] = DeriveJsonDecoder.gen[S3Event] }
peterchaula/ClassicF1
andEngineMODPlayerExtension/src/main/jni/drivers/debug.c
/* Extended Module Player * Copyright (C) 1996-2010 <NAME> and <NAME> * * This file is part of the Extended Module Player and is distributed * under the terms of the GNU General Public License. See doc/COPYING * for more information. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <stdlib.h> #include "common.h" #include "driver.h" static int numvoices(struct xmp_context *, int); static void voicepos(int, int); static void echoback(struct xmp_context *, int); static void setpatch(int, int); static void setvol(int, int); static void setnote(int, int); static void setpan(int, int); static void setbend(int, int); static void seteffect(int, int, int); static void starttimer(void); static void stoptimer(void); static void resetvoices(void); static void bufdump(void); static void bufwipe(void); static void clearmem(void); static void seq_sync(double); static int writepatch(struct patch_info *); static int init(struct xmp_context *ctx); static int getmsg(void); static void shutdown(struct xmp_context *); struct xmp_drv_info drv_debug = { "debug", /* driver ID */ "Driver debugger", /* driver description */ NULL, /* help */ init, /* init */ shutdown, /* shutdown */ numvoices, /* numvoices */ voicepos, /* voicepos */ echoback, /* echoback */ setpatch, /* setpatch */ setvol, /* setvol */ setnote, /* setnote */ setpan, /* setpan */ setbend, /* setbend */ seteffect, /* seteffect */ starttimer, /* settimer */ stoptimer, /* stoptimer */ resetvoices, /* resetvoices */ bufdump, /* bufdump */ bufwipe, /* bufwipe */ clearmem, /* clearmem */ seq_sync, /* sync */ writepatch, /* writepatch */ getmsg, /* getmsg */ NULL }; static int numvoices(struct xmp_context *ctx, int num) { return 32; } static void voicepos(int ch, int pos) { } static void echoback(struct xmp_context *ctx, int msg) { } static void setpatch(int ch, int smp) { printf("[%02d] setpatch: %d\n", ch, smp); } static void setvol(int ch, int vol) { printf("[%02d] setvol: %d\n", ch, vol); } static void setnote(int ch, int note) { printf("[%02d] setvol: %d\n", ch, note); } static void seteffect(int ch, int type, int val) { printf("[%02d] seteffect: %d, %d\n", ch, type, val); } static void setpan(int ch, int pan) { printf("[%02d] setpan: %d\n", ch, pan); } static void setbend(int ch, int bend) { printf("[%02d] setbend: %d\n", ch, bend); } static void starttimer() { printf("** starttimer\n"); } static void stoptimer() { printf("** stoptimer\n"); } static void resetvoices() { printf("** resetvoices\n"); } static void bufwipe() { printf("** bufwipe\n"); } static void bufdump() { } static void clearmem() { printf("** clearmem\n"); } static void seq_sync(double next_time) { } static int writepatch(struct patch_info *patch) { if (!patch) { clearmem(); return 0; } printf("** writepatch: len = %d\n", patch->len); return 0; } static int getmsg() { return 0; } static int init(struct xmp_context *ctx) { return 0; } static void shutdown(struct xmp_context *ctx) { printf("** shutdown\n"); }
mulesoft/amf
amf-api-contract/shared/src/main/scala/amf/apicontract/internal/spec/oas/parser/domain/Oas30RequestParser.scala
<reponame>mulesoft/amf package amf.apicontract.internal.spec.oas.parser.domain import amf.apicontract.client.scala.model.domain.{Payload, Request} import amf.apicontract.internal.metamodel.domain.{RequestModel, ResponseModel} import amf.apicontract.internal.spec.common.WebApiDeclarations.ErrorRequest import amf.apicontract.internal.spec.common.parser.{SpecParserOps, WebApiShapeParserContextAdapter} import amf.apicontract.internal.spec.oas.parser.context.OasWebApiContext import amf.apicontract.internal.spec.spec.OasDefinitions import amf.apicontract.internal.validation.definitions.ParserSideValidations.RequestBodyContentRequired import amf.core.client.scala.model.domain.{AmfArray, AmfScalar} import amf.core.internal.parser.YMapOps import amf.core.internal.parser.domain.{Annotations, ScalarNode, SearchScope} import amf.core.internal.validation.CoreValidations import amf.shapes.internal.annotations.{BaseVirtualNode, ExternalReferenceUrl} import amf.shapes.internal.spec.common.parser.AnnotationParser import org.yaml.model.{YMap, YMapEntry} import scala.collection.mutable case class Oas30RequestParser(map: YMap, parentId: String, definitionEntry: YMapEntry)(implicit ctx: OasWebApiContext) extends SpecParserOps { private def adopt(request: Request) = { request .setWithoutId(RequestModel.Name, ScalarNode(definitionEntry.key).string(), Annotations(definitionEntry.key)) } def parse(): Request = { ctx.link(map) match { case Left(fullRef) => parseRef(fullRef) case Right(_) => val annotations = Annotations.virtual() += BaseVirtualNode(definitionEntry) val request = adopt(Request(annotations)) map.key("description", RequestModel.Description in request) map.key("required", RequestModel.Required in request) val payloads = mutable.ListBuffer[Payload]() map.key("content") match { case Some(entry) => payloads ++= OasContentsParser(entry, request.withPayload).parse() case None => ctx.eh.violation( RequestBodyContentRequired, request, s"Request body must have a 'content' field defined", map.location ) } request.setWithoutId(ResponseModel.Payloads, AmfArray(payloads, Annotations.virtual()), Annotations.inferred()) AnnotationParser(request, map)(WebApiShapeParserContextAdapter(ctx)).parse() ctx.closedShape(request, map, "request") request } } private def parseRef(fullRef: String): Request = { val name = OasDefinitions.stripOas3ComponentsPrefix(fullRef, "requestBodies") ctx.declarations .findRequestBody(name, SearchScope.Named) .map(req => adopt(req.link(AmfScalar(name), Annotations(map), Annotations.synthesized()))) .getOrElse { ctx.navigateToRemoteYNode(fullRef) match { case Some(navigation) => Oas30RequestParser(navigation.remoteNode.as[YMap], parentId, definitionEntry)(navigation.context) .parse() .add(ExternalReferenceUrl(fullRef)) case None => ctx.eh.violation( CoreValidations.UnresolvedReference, "", s"Cannot find requestBody reference $fullRef", map.location ) adopt(ErrorRequest(fullRef, map).link(name)) } } } }
fakeNetflix/twitter-repo-ios-twitter-network-layer
TNLExample/TNLXDummy.h
<gh_stars>1-10 // // TNLXDummy.h // TwitterNetworkLayer // // Created on 8/29/14. // Copyright (c) 2014 Twitter. All rights reserved. // @import UIKit; @interface DummyVC : UIViewController @end
pupper68k/arcusplatform
platform/arcus-subsystems/src/main/java/com/iris/common/subsystem/alarm/generic/InactiveState.java
<reponame>pupper68k/arcusplatform /* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package com.iris.common.subsystem.alarm.generic; import com.google.common.collect.ImmutableSet; import com.iris.common.subsystem.SubsystemContext; import com.iris.messages.address.Address; import com.iris.messages.capability.AlarmCapability; import com.iris.messages.model.serv.AlarmModel; import com.iris.messages.model.subs.SubsystemModel; /** * @author tweidlin * */ public class InactiveState extends AlarmState<SubsystemModel> { private static final InactiveState INSTANCE = new InactiveState(); public static InactiveState instance() { return INSTANCE; } protected InactiveState() { } @Override public String getName() { return AlarmCapability.ALERTSTATE_INACTIVE; } @Override public String onStarted(SubsystemContext<? extends SubsystemModel> context, String name) { return checkActive(context, name); } @Override public String onEnter(SubsystemContext<? extends SubsystemModel> context, String name) { clearTriggers(context, name); return super.onEnter(context, name); } @Override public String onActivated(SubsystemContext<? extends SubsystemModel> context, String name) { return checkActive(context, name); } @Override public String onSensorAdded(SubsystemContext<? extends SubsystemModel> context, String name, Address sensor) { context.logger().debug("New sensor added, attempting to enable [{}] alarm", name); return checkActive(context, name); } @Override public String onTriggered(SubsystemContext<? extends SubsystemModel> context, String name, Address triggeredBy, TriggerEvent trigger) { addTrigger(context, name, triggeredBy, trigger); return AlarmCapability.ALERTSTATE_ALERT; } protected String checkActive(SubsystemContext<? extends SubsystemModel> context, String name) { if(!isActive(context)) { context.logger().debug("AlarmSubsystem is suspended, setting [{}] inactive", name); return AlarmCapability.ALERTSTATE_INACTIVE; } if(AlarmModel.getDevices(name, context.model(), ImmutableSet.<String>of()).isEmpty()) { context.logger().debug("No active devices for alarm [{}], disabling alert", name); return AlarmCapability.ALERTSTATE_INACTIVE; } if(AlarmModel.getTriggeredDevices(name, context.model(), ImmutableSet.<String>of()).size() > 0) { context.logger().debug("Activated with triggered devices, marking alert as clearing"); return AlarmCapability.ALERTSTATE_CLEARING; } return AlarmCapability.ALERTSTATE_READY; } }
ScalablyTyped/SlinkyTyped
i/ipfs-http-server/src/main/scala/typingsSlinky/ipfsHttpServer/errorHandlerMod.scala
package typingsSlinky.ipfsHttpServer import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object errorHandlerMod { @JSImport("ipfs-http-server/dist/src/error-handler", JSImport.Namespace) @js.native def apply(server: js.Any): Unit = js.native }
OSADP/C2C-RI
C2CRIBuildDir/projects/C2C-RI/src/NTCIP2306v01_69/src/test/TemporaryMessageFile.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * The Class TemporaryMessageFile. * * @author TransCore ITS, LLC * Last Updated: 1/8/2014 */ public class TemporaryMessageFile { /** The file path. */ String filePath; /** The file stream. */ ResetOnCloseInputStream fileStream; /** * The main method. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @param args the arguments * @throws Exception the exception */ public static void main(String[] args) throws Exception { tmpTest(); System.gc(); tmpTest(); System.gc(); System.out.println("Exiting Now."); } /** * Tmp test. * * Pre-Conditions: N/A * Post-Conditions: N/A */ private static void tmpTest(){ String output = "This is the message."; ByteArrayInputStream bais = new ByteArrayInputStream(output.getBytes()); TemporaryMessageFile ttm = new TemporaryMessageFile(bais); String byteString = new String(ttm.toByteArray()); System.out.println("Byte Array: "+ byteString); System.out.println("String: "+ttm.toString()); } /** * Instantiates a new temporary message file. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @param inMessage the in message */ public TemporaryMessageFile(InputStream inMessage) { createMessageFile(inMessage); } /** * To byte array. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @return the byte[] */ public byte[] toByteArray() { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; try { while ((nRead = fileStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); fileStream.close(); } catch (Exception ex) { ex.printStackTrace(); } return buffer.toByteArray(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString(){ String result = new String(toByteArray()); return result; } /** * Creates the message file. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @param inMessage the in message */ private void createMessageFile(InputStream inMessage) { boolean fileNotFound = true; while (fileNotFound) { String testPath = generateFilename(); try { File tmpFile = new File (testPath); if (tmpFile.exists()){ fileNotFound = false; this.filePath = testPath; } } catch (Exception e) { // exception thrown by RandomAccessFile if // testPath doesn't exist (ie: it can't be read) this.filePath = testPath; fileNotFound = false; } } try { OutputStream f = new FileOutputStream( new File(this.filePath)); boolean keepReading = true; while (keepReading) { int inputByte = inMessage.read(); if (inputByte == -1) { keepReading = false; } else { f.write(inputByte); } } f.close(); System.out.println("Temp File is "+this.filePath); fileStream = new ResetOnCloseInputStream(new BufferedInputStream(new FileInputStream(new File(this.filePath)),2048)); } catch (Exception e) { e.printStackTrace(); } //now create your file with filePath } /* (non-Javadoc) * @see java.lang.Object#finalize() */ @Override public void finalize() throws Throwable { super.finalize(); System.out.println("Finalize was called"); if (filePath != null) { File tmpFile = new File(filePath); if (tmpFile.exists()) { System.out.println("Finalize is deleting the file " + filePath); tmpFile.delete(); } } } /** * Generate filename. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @return the string */ public String generateFilename() { String fileName = "NotGenerated.tmp"; try { File dirPath = new File(".\\"); fileName = File.createTempFile("Message", "tmp", dirPath).getAbsolutePath(); } catch (Exception ex) { ex.printStackTrace(); } return fileName; } /** * The Class ResetOnCloseInputStream. * * @author TransCore ITS, LLC * Last Updated: 1/8/2014 */ class ResetOnCloseInputStream extends InputStream { /** The decorated. */ private final InputStream decorated; /** * Instantiates a new reset on close input stream. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @param anInputStream the an input stream */ private ResetOnCloseInputStream(InputStream anInputStream) { if (!anInputStream.markSupported()) { throw new IllegalArgumentException("marking not supported"); } anInputStream.mark(Integer.MAX_VALUE); decorated = anInputStream; } /* (non-Javadoc) * @see java.io.InputStream#close() */ @Override public void close() throws IOException { decorated.reset(); } /* (non-Javadoc) * @see java.io.InputStream#read() */ @Override public int read() throws IOException { return decorated.read(); } /** * Release. * * Pre-Conditions: N/A * Post-Conditions: N/A * * @throws IOException Signals that an I/O exception has occurred. */ public void release() throws IOException { decorated.close(); } } }
kinglyjn/zdemo-parent
zdemo-core-java/src/main/java/concurrent/jmm_shared/basic/problem/low_concurrent_level/Demo01_LowConcurrentLevelProblem.java
package concurrent.jmm_shared.basic.problem.low_concurrent_level; import lombok.extern.slf4j.Slf4j; /** * 并发度低的问题 */ @Slf4j(topic = "c.concurrent.jmm_shared.basic.problem.low_concurrent_level.Demo01_LowConcurrentLevelProblem") public class Demo01_LowConcurrentLevelProblem { public static void main(String[] args) { // testLowConcurrentLevelProblem(); testSolveProblemByUsingMultiLocks(); } /** * 一间大屋子有两个功能:睡觉、学习,互不相干。 * 现在张三要学习,小娟要睡觉,但如果只用一间屋子(一个对象锁)的话,那么并发度很低 */ public static void testLowConcurrentLevelProblem() { class BigRoom { public void sleep() { synchronized (this) { log.debug("睡觉2s开始"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("睡觉2s结束"); } } public void study() { synchronized (this) { log.debug("学习1s开始"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("学习1s结束"); } } } BigRoom bigRoom = new BigRoom(); new Thread("张三"){ @Override public void run() { bigRoom.study(); } }.start(); new Thread("小娟"){ @Override public void run() { bigRoom.sleep(); } }.start(); } /** * 解决方法1: * 准备多个房间(多个对象锁) * * 好处:是可以增强并发度 * 坏处:如果一个线程需要同时获得多把锁,就容易发生死锁 */ public static void testSolveProblemByUsingMultiLocks() { class BigRoom { private Object studyRoom = new Object(); private Object bedRoom = new Object(); public void sleep() { synchronized (bedRoom) { log.debug("睡觉2s开始"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("睡觉2s结束"); } } public void study() { synchronized (studyRoom) { log.debug("学习1s开始"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("学习1s结束"); } } } BigRoom bigRoom = new BigRoom(); new Thread("张三"){ @Override public void run() { bigRoom.study(); } }.start(); new Thread("小娟"){ @Override public void run() { bigRoom.sleep(); } }.start(); } }
cristianlpereira/uri-judge-online-c
1015.c
<reponame>cristianlpereira/uri-judge-online-c #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> int main () { int x1, x2, y1, y2; float Distancia; scanf("%i %i", &x1, &y1); scanf("%i %i", &x2, &y2); Distancia = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); printf("%.4f\n", Distancia); return 0; }
PONSASIKALA/signal-interpreter-server
src/exercise/lesson3_exercise_5/test_is_hex.py
# pylint: disable=missing-function-docstring import pytest from lesson_3.exercise_5.is_hex import is_hex @pytest.mark.parametrize("item, expected_result", [ ("123", True), ("DEADBEEF", True), ("78AA", True), ("DUMMY", False), ("no hex", False), ]) def test_is_hex(item, expected_result): assert is_hex(item) == expected_result
cqtddt/AndroidPAD
src/com/shen/hso/listener/NotifyBaseInfoListener.java
package com.shen.hso.listener; import com.shen.hso.entity.TopoBaseData; public interface NotifyBaseInfoListener { public void notifyBaseInfoUpdateView(Object object); public void notifyReadBaseInfoUpdateView(Object object); public void notifyErrorUpdateView(Object object); }
student-t/Xnat
src/main/java/org/nrg/xnat/turbine/modules/screens/DefaultPipelineScreen.java
<filename>src/main/java/org/nrg/xnat/turbine/modules/screens/DefaultPipelineScreen.java /* * web: org.nrg.xnat.turbine.modules.screens.DefaultPipelineScreen * XNAT http://www.xnat.org * Copyright (c) 2005-2017, Washington University School of Medicine and Howard Hughes Medical Institute * All Rights Reserved * * Released under the Simplified BSD. */ package org.nrg.xnat.turbine.modules.screens; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.turbine.util.RunData; import org.apache.velocity.context.Context; import org.nrg.config.entities.Configuration; import org.nrg.framework.constants.Scope; import org.nrg.pipeline.PipelineRepositoryManager; import org.nrg.pipeline.xmlbeans.ParameterData; import org.nrg.pipeline.xmlbeans.ParameterData.Values; import org.nrg.pipeline.xmlbeans.ParametersDocument.Parameters; import org.nrg.xdat.XDAT; import org.nrg.xdat.base.BaseElement; import org.nrg.xdat.model.ArcPipelinedataI; import org.nrg.xdat.model.ArcPipelineparameterdataI; import org.nrg.xdat.model.ArcProjectDescendantPipelineI; import org.nrg.xdat.model.PipePipelinedetailsParameterI; import org.nrg.xdat.om.*; import org.nrg.xdat.om.base.BaseWrkWorkflowdata; import org.nrg.xdat.schema.SchemaElement; import org.nrg.xdat.turbine.modules.screens.SecureReport; import org.nrg.xdat.turbine.utils.TurbineUtils; import org.nrg.xft.ItemI; import org.nrg.xft.XFT; import org.nrg.xft.XFTItem; import org.nrg.xft.XFTTable; import org.nrg.xft.collections.ItemCollection; import org.nrg.xft.search.CriteriaCollection; import org.nrg.xft.search.ItemSearch; import org.nrg.xft.search.TableSearch; import org.nrg.xft.security.UserI; import org.nrg.xnat.exceptions.PipelineNotFoundException; import org.nrg.xnat.turbine.utils.ArcSpecManager; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @SuppressWarnings("unused") public abstract class DefaultPipelineScreen extends SecureReport { static Logger logger = Logger.getLogger(DefaultPipelineScreen.class); String message = null; ArrayList<WrkWorkflowdata> workflows; String project = null; protected HashMap<String, ArcPipelineparameterdata> projectParameters; String pipelinePath = null; public DefaultPipelineScreen() { workflows = Lists.newArrayList(); projectParameters = Maps.newHashMap(); } public abstract void finalProcessing(RunData data, Context context); protected void setHasDicomFiles(XnatImagesessiondata mr, String mprageScanType, Context context) { if (mr instanceof XnatMrsessiondata || mr instanceof XnatPetsessiondata) { boolean rtn = false; for (String type : mprageScanType.split(",")) { ArrayList<XnatImagescandata> scans = mr.getScansByType(type.trim()); if (scans != null && scans.size() > 0) { List<XnatAbstractresource> files = scans.get(0).getFile(); for (XnatAbstractresource absFile : files) { if (absFile instanceof XnatDicomseries) { rtn = true; } else if (absFile instanceof XnatResourcecatalog) { XnatResourcecatalog rsccat = (XnatResourcecatalog) absFile; if (rsccat.getContent().endsWith("RAW")) { if (rsccat.getFormat().equals("DICOM")) rtn = true; break; } } } } } context.put("isDicom", rtn ? "1" : "0"); } } protected void setHasFreesurfer(XnatMrsessiondata mr, Context context) { String project = mr.getProject(); int hasFreesurfer = 0; ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(project); final List<ArcProjectDescendantPipelineI> descPipelines = arcProject.getPipelinesForDescendant(XnatMrsessiondata.SCHEMA_ELEMENT_NAME); for (ArcProjectDescendantPipelineI aPipeline : descPipelines) { if (aPipeline.getLocation().endsWith(File.separator + "StdFreeSurferBuild.xml")) { hasFreesurfer = 1; break; } } context.put("freesurfer", hasFreesurfer); } protected void setWorkflows(RunData data, Context context) { String projectId = (String) context.get("project"); try { org.nrg.xft.search.CriteriaCollection cc = new CriteriaCollection("AND"); cc.addClause("wrk:workflowData.ID", item.getProperty("ID")); if (projectId != null) cc.addClause("wrk:workflowData.ExternalID", projectId); ItemCollection items = ItemSearch.GetItems(cc, TurbineUtils.getUser(data), false); //Sort by Launch Time ArrayList workitems = items.getItems("wrk:workflowData.launch_time", "DESC"); for (Object item : workitems) { workflows.add(new WrkWorkflowdata((XFTItem) item)); } context.put("workflows", workflows); } catch (Exception e) { logger.debug(e); } } public void preProcessing(RunData data, Context context) { } public void doBuildTemplate(RunData data, Context context) { // preserveVariables(data,context); logger.debug("BEGIN SECURE REPORT :" + this.getClass().getName()); preProcessing(data, context); item = TurbineUtils.getDataItem(data); if (item == null) { try { item = TurbineUtils.GetItemBySearch(data, preLoad()); } catch (IllegalAccessException e1) { logger.error(e1); data.setMessage(e1.getMessage()); noItemError(data, context); return; } catch (Exception e1) { logger.error(e1); data.setMessage(e1.getMessage()); data.setScreenTemplate("Error.vm"); noItemError(data, context); return; } } if (item == null) { data.setMessage("Error: No item found."); noItemError(data, context); } else { try { if (XFT.VERBOSE) System.out.println("Creating report: " + getClass()); context.put("item", item.getItem()); if (XFT.VERBOSE) System.out.println("Loaded item object (org.nrg.xft.ItemI) as context parameter 'item'."); context.put("element", SchemaElement.GetElement(item.getXSIType())); context.put("search_element", TurbineUtils.GetPassedParameter("search_element", data)); context.put("search_field", TurbineUtils.GetPassedParameter("search_field", data)); context.put("search_value", TurbineUtils.GetPassedParameter("search_value", data)); project = (String) TurbineUtils.GetPassedParameter("project", data); pipelinePath = (String) context.get("pipelinePath"); context.put("project", project); om = BaseElement.GetGeneratedItem(item); context.put("om", om); setWorkflows(data, context); setParameters(pipelinePath); if (message != null) data.setMessage(message); finalProcessing(data, context); } catch (Exception e) { data.setMessage(e.getMessage()); logger.error("", e); } } logger.debug("END SECURE REPORT :" + this.getClass().getName()); } protected boolean isAnyQueuedOrRunning(ArrayList<WrkWorkflowdata> workflows) { boolean rtn = false; try { for (WrkWorkflowdata wrkFlow : workflows) { if (wrkFlow.getStatus().toUpperCase().equals(BaseWrkWorkflowdata.QUEUED) || wrkFlow.getStatus().toUpperCase().equals(BaseWrkWorkflowdata.RUNNING)) { rtn = true; break; } } } catch (IndexOutOfBoundsException aoe) { logger.debug(aoe); } return rtn; } protected boolean hasBeenCompletedInThePast(String pipelinePath, ArrayList<WrkWorkflowdata> workflows) { boolean rtn = false; for (WrkWorkflowdata wrkFlow : workflows) { String matchPipelineName = wrkFlow.getPipelineName(); if (matchPipelineName.equals(pipelinePath) || pipelinePath.contains(matchPipelineName)) { if (wrkFlow.getStatus().equalsIgnoreCase(BaseWrkWorkflowdata.COMPLETE)) { rtn = true; message = "This pipeline has been completed in the past. Relaunching the pipeline may result in loss of data. Are you sure you want to proceed?"; break; } } } return rtn; } protected ArcPipelineparameterdata getProjectPipelineSetting(String parameterName) throws Exception { return projectParameters.get(parameterName); } protected ArcPipelineparameterdata getParameter(ArcProject arcProject, String parameterName) throws PipelineNotFoundException { ArcPipelineparameterdata rtn = null; ArcPipelinedataI pipelineData = arcProject.getPipelineByPath(pipelinePath); for (ArcPipelineparameterdataI aParam : pipelineData.getParameters_parameter()) { if (aParam.getName().equals(parameterName)) { rtn = (ArcPipelineparameterdata) aParam; break; } } return rtn; } protected void setParameters(String pipeline) throws PipelineNotFoundException { ArcProject arcProject = ArcSpecManager.GetFreshInstance().getProjectArc(project); ArcPipelinedataI pipelineData; if (arcProject == null) { //Project pipeline hasnt been set PipePipelinedetails pipelineDetails = PipelineRepositoryManager.GetInstance().getPipeline(pipeline); for (PipePipelinedetailsParameterI paramI : pipelineDetails.getParameters_parameter()) { ArcPipelineparameterdata aParam = PipelineRepositoryManager.GetInstance().convertToArcPipelineParameter((PipePipelinedetailsParameter) paramI); projectParameters.put(aParam.getName(), aParam); } } else { if (om.getXSIType().equals(XnatProjectdata.SCHEMA_ELEMENT_NAME)) { pipelineData = arcProject.getPipelineByPath(pipeline); } else { pipelineData = arcProject.getPipelineForDescendantByPath(om.getXSIType(), pipeline); } for (ArcPipelineparameterdataI aParamI : pipelineData.getParameters_parameter()) { projectParameters.put(aParamI.getName(), (ArcPipelineparameterdata) aParamI); } } } @SuppressWarnings("unchecked") protected void setParameters(ArcPipelinedataI arcPipeline, Context context) throws Exception { List<ArcPipelineparameterdataI> pipelineParameters = arcPipeline.getParameters_parameter(); Parameters parameters = Parameters.Factory.newInstance(); ParameterData param; for (ArcPipelineparameterdataI pipelineParam : pipelineParameters) { String schemaLink = pipelineParam.getSchemalink(); String paramCsv = pipelineParam.getCsvvalues(); if (schemaLink == null && paramCsv == null) { // param has no default value // Make default value empty string paramCsv = ""; } param = parameters.addNewParameter(); param.setName(pipelineParam.getName()); Values values = param.addNewValues(); if (schemaLink != null) { Object o = om.getItem().getProperty(schemaLink, true); if (o != null) { try { ArrayList<? extends Class> matches = (ArrayList<? extends Class>) o; if (matches.size() == 1) { values.setUnique("" + matches.get(0)); } else { for (Object match : matches) { values.addList("" + match); } } } catch (ClassCastException cce) { values.setUnique("" + o); } } } else { String[] paramArray = paramCsv.split(","); if (paramArray.length == 1) { values.setUnique(paramArray[0]); } else { values.setListArray(paramArray); } } } context.put("parameters", parameters); } public ArrayList<XnatImagescandata> getScansFromScantypeConfig(String toolName, String fileName) { Configuration config = XDAT.getConfigService().getConfig(toolName, fileName, Scope.Project, project); if (config != null && config.getContents() != null) { return ((XnatImagesessiondata) om).getScansByTypeCsv(config.getContents().trim()); } else { return Lists.newArrayList(); } } protected List<XnatImagesessiondata> getPreviousImagingSessions(final XnatImagesessiondata latestImagingSession) { if (latestImagingSession == null) { return null; } final String subjectId = latestImagingSession.getSubjectId(); if (StringUtils.isBlank(subjectId)) { logger.error("Image session " + latestImagingSession.getId() + " has no subject identifier."); return null; } final String projectId = latestImagingSession.getSubjectId(); if (StringUtils.isBlank(projectId)) { logger.error("Image session " + latestImagingSession.getId() + " has no project identifier."); return null; } final UserI userI = XDAT.getUserDetails(); if (userI == null) { logger.error("Bad user object returned from XDAT."); return null; } final String login = userI.getLogin(); final String query = "SELECT im.id FROM xnat_imagesessiondata im LEFT JOIN xnat_subjectAssessorData sad ON im.ID=sad.ID LEFT JOIN xnat_experimentData ed ON sad.ID=ed.ID WHERE subject_id='" + subjectId +"' and ed.project='" + projectId + "' and date < '" + latestImagingSession.getDate() +"' ORDER BY date DESC "; final List<XnatImagesessiondata> previousSessions = Lists.newArrayList(); XFTTable table; try { table = TableSearch.Execute(query, latestImagingSession.getDBName(), login); } catch (Exception e) { logger.error("There was a problem searching for previous imaging sessions.", e); return null; } if (table != null && table.size() > 0) { table.resetRowCursor(); while(table.hasMoreRows()) { final Object imageSessionId = table.nextRowHash().get("id"); if (imageSessionId != null) { ItemI itemI = null; try { itemI = ItemSearch.GetItem("xnat:imageSessionData.ID", imageSessionId, userI, false); } catch (Exception e) { logger.error("Could not find image session " + imageSessionId, e); } if (itemI != null) { previousSessions.add(new XnatImagesessiondata(itemI)); } } } } return previousSessions; } }
mdegirolami/stay
compiler/src/builtin_functions.cpp
#include <string.h> #include "builtin_functions.h" #include "ast_nodes.h" namespace SingNames { struct IFDesc { const char *name; const char *signature; }; static const char *GetSignatureByKey(IFDesc *map, const char *name); static IAstTypeNode *GetTypeFromSignature(const char type_id, const ExpressionAttributes *attr, bool *owning); static VarDeclaration *GetVarFromSignature(const char type_id, const ExpressionAttributes *attr); // signature: // optional prefix: M for muting. // first letter is return value // T = same type as implicit argument // i = int // v = void // b = bool // k = key type // e = value/element type // other are INPUT parms // x = index // s = size // f = compare function f(T, x, x) b // k = key type // e = value/element type // last letter is the implementation type: // s = sing::name(T); // c = (cast)name(T); // cast if not double // p = name(T); // plain // m = T.member() // S = std::name(T) // NOTE: functions on integers are all with 0 values and not muting (apply also to right values) // the two letters are the returned value and the implementation type. IFDesc g_integer_functs[] = {{"abs", "Ts"}, {"sqrt", "Tc"}, {"sgn", "is"}, {"", ""}}; IFDesc g_float_functs[] = { {"abs", "Ts"}, {"sqrt", "Tc"}, {"sgn", "is"}, {"sin", "Tc"}, {"cos", "Tc"}, {"tan", "Tc"}, {"asin", "Tc"}, {"acos", "Tc"}, {"atan", "Tc"}, {"log", "Tc"}, {"exp", "Tc"}, {"log10", "Tc"}, {"exp10", "Ts"}, {"log2", "Tc"}, {"exp2", "Tc"}, {"floor", "Tc"}, {"ceil", "Tc"}, {"round", "Tc"}, {"", ""} }; IFDesc g_complex_functs[] = { {"abs", "eS"}, {"arg", "eS"}, {"imag", "eS"}, {"real", "eS"}, {"norm", "eS"}, {"sqrt", "TS"}, {"sin", "TS"}, {"cos", "TS"}, {"tan", "TS"}, {"asin", "TS"}, {"acos", "TS"}, {"atan", "TS"}, {"log", "TS"}, {"exp", "TS"}, {"", ""} }; IFDesc g_array_functs[] = { {"size", "im"}, //{"sort", "Mvxsf"}, {"radix_sort", "Mvxsf"}, {"find", "ie"}, {"binary_search", "ie"}, {"upper_bound", "ie"}, {"lower_bound", "ie"}, {"", ""} }; IFDesc g_vector_functs[] = { {"reserve", "Mvsm"}, {"capacity", "im"}, {"shrink_to_fit", "Mvm"}, {"resize", "Mvsm"}, {"clear", "Mvm"}, {"size", "im"}, {"empty", "bm"}, {"push_back", "Mvem"}, {"pop_back", "Mvm"}, {"insert", "Mvxses"}, {"erase", "Mvxxs"}, {"insert_v", "MvxTs"}, {"append", "MvTs"}, //{"sort", "Mvxsf"}, {"radix_sort", "Mvxsf"}, {"find", "ie"}, {"binary_search", "ie"}, {"upper_bound", "ie"}, {"lower_bound", "ie"}, {"", ""} }; IFDesc g_map_functs[] = { {"reserve", "Mvsm"}, {"capacity", "im"}, {"shrink_to_fit", "Mvm"}, {"clear" ,"Mvm"}, {"size", "im"}, {"isempty", "bm"}, {"insert", "Mvkem"}, {"erase", "Mvkm"}, {"get", "ekm"}, {"get_safe", "ekem"}, {"has", "bkm"}, {"key_at", "kxm"}, {"value_at", "exm"}, //{"sort_by_key", "Mvxsf"}, {"radix_sort_by_key", "Mvxsf"}, {"sort_by_value", "Mvxsf"}, {"radix_sort_by_value", "Mvxsf"}, //{"find_value", "ie"}, {"binary_search_value", "ie"}, {"upper_bound_value", "ie"}, {"lower_bound_value", "ie"}, {"", ""} }; static const char *GetSignatureByKey(IFDesc *map, const char *name) { while (map->name[0] != 0) { if (strcmp(map->name, name) == 0) { return(map->signature); } ++map; } return(nullptr); } const char *GetFuncSignature(const char *name, const ExpressionAttributes *attr) { IFDesc *table = nullptr; if (attr->IsInteger()) { table = g_integer_functs; } else if (attr->IsFloat()) { table = g_float_functs; } else if (attr->IsComplex()) { table = g_complex_functs; } else if (attr->IsArray()) { if (((AstArrayType*)attr->GetTypeTree())->is_dynamic_) { table = g_vector_functs; } else { table = g_array_functs; } } else if (attr->IsMap()) { table = g_map_functs; } if (table == nullptr) { return(nullptr); } return(GetSignatureByKey(table, name)); } AstFuncType *GetFuncTypeFromSignature(const char *signature, const ExpressionAttributes *attr) { if (signature == nullptr) return(nullptr); if (signature[0] == 'M') ++signature; if (signature[0] == 0) return(nullptr); int numargs = strlen(signature) - 2; if (numargs < 0) { return(nullptr); } AstFuncType *retvalue = new AstFuncType(true); // note: all functions are pure ! if (retvalue == nullptr) return(nullptr); bool owning; retvalue->SetReturnType(GetTypeFromSignature(*signature++, attr, &owning)); retvalue->SetOwning(owning); for (int ii = 0; ii < numargs; ++ii) { retvalue->AddArgument(GetVarFromSignature(*signature++, attr)); } retvalue->SetIsMember(); // to prevent undue copying return(retvalue); } BInSynthMode GetBuiltinSynthMode(const char *signature) { switch (signature[strlen(signature) - 1]) { case 's': return(BInSynthMode::sing); case 'S': return(BInSynthMode::std); case 'c': return(BInSynthMode::cast); case 'm': return(BInSynthMode::member); case 'p': default: break; } return(BInSynthMode::plain); } char GetBuiltinArgType(const char *signature, int idx) { if (signature[0] == 'M') ++idx; ++idx; if (idx < strlen(signature) - 1) { return(signature[idx]); } return('s'); // default } void GetBuiltinNames(NamesList *names, const ExpressionAttributes *attr) { IFDesc *table = nullptr; if (attr->IsInteger()) { table = g_integer_functs; } else if (attr->IsFloat()) { table = g_float_functs; } else if (attr->IsComplex()) { table = g_complex_functs; } else if (attr->IsArray()) { if (((AstArrayType*)attr->GetTypeTree())->is_dynamic_) { table = g_vector_functs; } else { table = g_array_functs; } } else if (attr->IsMap()) { table = g_map_functs; } if (table != nullptr) { while (table->name[0] != 0) { names->AddName(table->name); ++table; } } } static IAstTypeNode *GetTypeFromSignature(const char type_id, const ExpressionAttributes *attr, bool *owning) { static AstBaseType int_type(TOKEN_INT32); static AstBaseType void_type(TOKEN_VOID); static AstBaseType bool_type(TOKEN_BOOL); static AstBaseType size_type(TOKEN_INT64); static AstBaseType float32_type(TOKEN_FLOAT32); static AstBaseType float64_type(TOKEN_FLOAT64); *owning = false; IAstTypeNode *the_type = nullptr; switch (type_id) { case 'T': the_type = attr->GetTypeTree(); if (the_type == nullptr) { Token base_type = attr->GetAutoBaseType(); if (base_type != TOKENS_COUNT) { *owning = true; the_type = new AstBaseType(base_type); } } break; case 'i': the_type = &int_type; break; case 'v': the_type = &void_type; break; case 'b': the_type = &bool_type; break; case 'k': the_type = attr->GetTypeTree(); if (the_type->GetType() == ANT_MAP_TYPE) { the_type = ((AstMapType*)the_type)->key_type_; } break; case 'e': the_type = attr->GetTypeTree(); switch (the_type->GetType()) { case ANT_MAP_TYPE: the_type = ((AstMapType*)the_type)->returned_type_; break; case ANT_ARRAY_TYPE: the_type = ((AstArrayType*)the_type)->element_type_; break; default: switch (attr->GetAutoBaseType()) { case TOKEN_COMPLEX64: the_type = &float32_type; break; case TOKEN_COMPLEX128: the_type = &float64_type; break; default: break; } break; } break; case 'x': case 's': the_type = &size_type; break; default: break; } return(the_type); } static VarDeclaration *GetVarFromSignature(const char type_id, const ExpressionAttributes *attr) { bool owning; IAstTypeNode *typedesc = GetTypeFromSignature(type_id, attr, &owning); if (typedesc == nullptr) return(nullptr); const char *name = ""; switch (type_id) { case 'k': name = "key"; break; case 'e': name = "element"; break; case 'x': name = "idx"; break; case 's': name = "size"; break; case 'i': case 'T': case 'v': case 'b': default: break; } VarDeclaration *the_var = new VarDeclaration(name); the_var->SetFlags(VF_ISARG | VF_READONLY); if (owning) { the_var->SetType(typedesc); } else { the_var->SetWeakType(typedesc); } return(the_var); } }
xiaozhu36/alibaba-cloud-sdk-go
services/cassandra/create_data_center.go
<reponame>xiaozhu36/alibaba-cloud-sdk-go<filename>services/cassandra/create_data_center.go package cassandra //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // CreateDataCenter invokes the cassandra.CreateDataCenter API synchronously // api document: https://help.aliyun.com/api/cassandra/createdatacenter.html func (client *Client) CreateDataCenter(request *CreateDataCenterRequest) (response *CreateDataCenterResponse, err error) { response = CreateCreateDataCenterResponse() err = client.DoAction(request, response) return } // CreateDataCenterWithChan invokes the cassandra.CreateDataCenter API asynchronously // api document: https://help.aliyun.com/api/cassandra/createdatacenter.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) CreateDataCenterWithChan(request *CreateDataCenterRequest) (<-chan *CreateDataCenterResponse, <-chan error) { responseChan := make(chan *CreateDataCenterResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.CreateDataCenter(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // CreateDataCenterWithCallback invokes the cassandra.CreateDataCenter API asynchronously // api document: https://help.aliyun.com/api/cassandra/createdatacenter.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) CreateDataCenterWithCallback(request *CreateDataCenterRequest, callback func(response *CreateDataCenterResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *CreateDataCenterResponse var err error defer close(result) response, err = client.CreateDataCenter(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // CreateDataCenterRequest is the request struct for api CreateDataCenter type CreateDataCenterRequest struct { *requests.RpcRequest ClientToken string `position:"Query" name:"ClientToken"` InstanceType string `position:"Query" name:"InstanceType"` AutoRenewPeriod requests.Integer `position:"Query" name:"AutoRenewPeriod"` Period requests.Integer `position:"Query" name:"Period"` DiskSize requests.Integer `position:"Query" name:"DiskSize"` ClusterId string `position:"Query" name:"ClusterId"` DiskType string `position:"Query" name:"DiskType"` VswitchId string `position:"Query" name:"VswitchId"` PeriodUnit string `position:"Query" name:"PeriodUnit"` AutoRenew requests.Boolean `position:"Query" name:"AutoRenew"` DataCenterName string `position:"Query" name:"DataCenterName"` NodeCount requests.Integer `position:"Query" name:"NodeCount"` VpcId string `position:"Query" name:"VpcId"` ZoneId string `position:"Query" name:"ZoneId"` PayType string `position:"Query" name:"PayType"` } // CreateDataCenterResponse is the response struct for api CreateDataCenter type CreateDataCenterResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` DataCenterId string `json:"DataCenterId" xml:"DataCenterId"` } // CreateCreateDataCenterRequest creates a request to invoke CreateDataCenter API func CreateCreateDataCenterRequest() (request *CreateDataCenterRequest) { request = &CreateDataCenterRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Cassandra", "2019-01-01", "CreateDataCenter", "Cassandra", "openAPI") request.Method = requests.POST return } // CreateCreateDataCenterResponse creates a response to parse from CreateDataCenter response func CreateCreateDataCenterResponse() (response *CreateDataCenterResponse) { response = &CreateDataCenterResponse{ BaseResponse: &responses.BaseResponse{}, } return }
userzrq/gulimall
gulimall-order/src/main/java/com/atguigu/gulimall/order/vo/ware/LockStockVo.java
<gh_stars>0 package com.atguigu.gulimall.order.vo.ware; import lombok.Data; import lombok.ToString; import java.util.List; /** * @author userzrq */ @Data @ToString public class LockStockVo { private List<SkuLock> locks; /** * 本次锁定的 最终结果 是成功了还是失败了,用于直接判断 */ private Boolean locked; /** * 如果有拆单的逻辑,订单里面有很多来源于不同仓库的商品 * 以仓库发货单位进行拆分 */ }
UlisesVelazquez208/hadoop-hdfs-trunk
src/test/hdfs/org/apache/hadoop/hdfs/server/namenode/TestComputeInvalidateWork.java
<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.server.common.GenerationStamp; import junit.framework.TestCase; /** * Test if FSNamesystem handles heartbeat right */ public class TestComputeInvalidateWork extends TestCase { /** * Test if {@link FSNamesystem#computeInvalidateWork(int)} * can schedule invalidate work correctly */ public void testCompInvalidate() throws Exception { final Configuration conf = new HdfsConfiguration(); final int NUM_OF_DATANODES = 3; final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_OF_DATANODES).build(); try { cluster.waitActive(); final FSNamesystem namesystem = cluster.getNamesystem(); DatanodeDescriptor[] nodes = namesystem.heartbeats.toArray(new DatanodeDescriptor[NUM_OF_DATANODES]); assertEquals(nodes.length, NUM_OF_DATANODES); namesystem.writeLock(); try { for (int i=0; i<nodes.length; i++) { for(int j=0; j<3*namesystem.blockInvalidateLimit+1; j++) { Block block = new Block(i*(namesystem.blockInvalidateLimit+1)+j, 0, GenerationStamp.FIRST_VALID_STAMP); namesystem.blockManager.addToInvalidates(block, nodes[i]); } } assertEquals(namesystem.blockInvalidateLimit*NUM_OF_DATANODES, namesystem.blockManager.computeInvalidateWork(NUM_OF_DATANODES+1)); assertEquals(namesystem.blockInvalidateLimit*NUM_OF_DATANODES, namesystem.blockManager.computeInvalidateWork(NUM_OF_DATANODES)); assertEquals(namesystem.blockInvalidateLimit*(NUM_OF_DATANODES-1), namesystem.blockManager.computeInvalidateWork(NUM_OF_DATANODES-1)); int workCount = namesystem.blockManager.computeInvalidateWork(1); if (workCount == 1) { assertEquals(namesystem.blockInvalidateLimit+1, namesystem.blockManager.computeInvalidateWork(2)); } else { assertEquals(workCount, namesystem.blockInvalidateLimit); assertEquals(2, namesystem.blockManager.computeInvalidateWork(2)); } } finally { namesystem.writeUnlock(); } } finally { cluster.shutdown(); } } }
xstefank/smallrye-fault-tolerance
testsuite/integration/src/test/java/io/smallrye/faulttolerance/vertx/AbstractVertxTest.java
<reponame>xstefank/smallrye-fault-tolerance package io.smallrye.faulttolerance.vertx; import static org.awaitility.Awaitility.await; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import io.smallrye.faulttolerance.util.FaultToleranceIntegrationTest; import io.vertx.core.Future; import io.vertx.core.Vertx; @FaultToleranceIntegrationTest public abstract class AbstractVertxTest { private Vertx vertx; @BeforeEach public final void createVertx() { vertx = Vertx.vertx(); } @AfterEach public final void destroyVertx() { Future<Void> future = vertx.close(); await().atMost(5, TimeUnit.SECONDS).until(future::isComplete); } protected final void runOnVertx(Runnable runnable) { vertx.runOnContext(ignored -> { runnable.run(); }); } }
MAYANK25402/city-scrapers
tests/test_chi_animal.py
<filename>tests/test_chi_animal.py<gh_stars>1-10 from datetime import datetime from os.path import dirname, join import pytest from city_scrapers_core.constants import ADVISORY_COMMITTEE, PASSED from city_scrapers_core.utils import file_response from city_scrapers.spiders.chi_animal import ChiAnimalSpider test_response = file_response( join(dirname(__file__), "files", "chi_animal.html"), url="https://chicago.gov/city/en/depts/cacc/supp_info/public_notice.html", ) spider = ChiAnimalSpider() parsed_items = [item for item in spider.parse(test_response)] def test_len(): assert len(parsed_items) == 3 def test_start(): assert parsed_items[0]["start"] == datetime(2017, 9, 21) def test_end(): assert parsed_items[0]["end"] == datetime(2017, 9, 21, 3) def test_time_notes(): assert parsed_items[0]["time_notes"] == "Estimated 3 hour duration" @pytest.mark.parametrize("item", parsed_items) def test_all_day(item): assert item["all_day"] is False @pytest.mark.parametrize("item", parsed_items) def test_class(item): assert item["classification"] == ADVISORY_COMMITTEE @pytest.mark.parametrize("item", parsed_items) def test_title(item): assert item["title"] == "Advisory Board" @pytest.mark.parametrize("item", parsed_items) def test_description(item): assert item["description"] == "" @pytest.mark.parametrize("item", parsed_items) def test_location(item): assert item["location"] == { "address": "2741 S. Western Ave, Chicago, IL 60608", "name": "<NAME> Animal Care Center", } @pytest.mark.parametrize("item", parsed_items) def test_status(item): assert item["status"] == PASSED @pytest.mark.parametrize("item", parsed_items) def test_sources(item): assert ( item["source"] == "https://chicago.gov/city/en/depts/cacc/supp_info/public_notice.html" ) @pytest.mark.parametrize("item", parsed_items) def test_links(item): assert len(item["links"]) == 0
jourquin/JFlowMap
src/org/piccolo2d/examples/StickyHandleLayerExample.java
/* * Copyright (c) 2008-2011, Piccolo2D project, http://piccolo2d.org * Copyright (c) 1998-2008, University of Maryland * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * None of the name of the University of Maryland, the name of the Piccolo2D project, or the names of its * contributors may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.piccolo2d.examples; import java.awt.Color; import java.util.Iterator; import org.piccolo2d.PCanvas; import org.piccolo2d.PNode; import org.piccolo2d.PRoot; import org.piccolo2d.activities.PActivity; import org.piccolo2d.extras.PFrame; import org.piccolo2d.extras.handles.PBoundsHandle; import org.piccolo2d.extras.handles.PHandle; import org.piccolo2d.extras.util.PBoundsLocator; import org.piccolo2d.nodes.PPath; /** * This example shows another way to create sticky handles. These handles are * not added as children to the object that they manipulate. Instead they are * added to the camera the views that objects. This means that they will not be * affected by the cameras view transform, and so will stay the same size when * the view is zoomed. They will also be drawn on top of all other objects, even * if those objects overlap the object that they manipulate. For this setup we * need to add and updateHandles activity that makes sure to relocate the handle * after any change. Another way to do this would be to add change listeners to * the camera and the node that they manipulate and only update them then. But * this method is easier and should be plenty efficient for normal use. * * @author jesse */ public class StickyHandleLayerExample extends PFrame { /** * */ private static final long serialVersionUID = 1L; public StickyHandleLayerExample() { this(null); } public StickyHandleLayerExample(final PCanvas aCanvas) { super("StickyHandleLayerExample", false, aCanvas); } public void initialize() { final PCanvas c = getCanvas(); final PActivity updateHandles = new PActivity(-1, 0) { protected void activityStep(final long elapsedTime) { super.activityStep(elapsedTime); final PRoot root = getActivityScheduler().getRoot(); if (root.getPaintInvalid() || root.getChildPaintInvalid()) { final Iterator i = getCanvas().getCamera().getChildrenIterator(); while (i.hasNext()) { final PNode each = (PNode) i.next(); if (each instanceof PHandle) { final PHandle handle = (PHandle) each; handle.relocateHandle(); } } } } }; final PPath rect = PPath.createRectangle(0, 0, 100, 100); rect.setPaint(Color.RED); c.getLayer().addChild(rect); c.getCamera().addChild(new PBoundsHandle(PBoundsLocator.createNorthEastLocator(rect))); c.getCamera().addChild(new PBoundsHandle(PBoundsLocator.createNorthWestLocator(rect))); c.getCamera().addChild(new PBoundsHandle(PBoundsLocator.createSouthEastLocator(rect))); c.getCamera().addChild(new PBoundsHandle(PBoundsLocator.createSouthWestLocator(rect))); c.getRoot().getActivityScheduler().addActivity(updateHandles, true); } public static void main(final String[] args) { new StickyHandleLayerExample(); } }
A-LiX/bit-com-sdk-go
pkg/model/account/get_user_deliveries_response.go
<gh_stars>1-10 package account import "github.com/bitcom-exchange/bitcom-go-api/pkg/model/base" type GetUserDeliveriesResponse struct { base.RestBaseResponse Paging base.OldPaging `json:"paging"` Data []DeliveryVo `json:"data"` } type DeliveryVo struct { Type string `json:"type" example:"delivery"` Timestamp int64 `json:"timestamp" example:"1585296000000"` InstrumentId string `json:"instrument_id" example:"BTC-27MAR20-9000-C"` Position string `json:"position" example:"0.7"` Exercise bool `json:"exercise"` DeliveryPrice string `json:"delivery_price" example:"8000"` DeliveryPnl string `json:"delivery_pnl" example:"0.07"` //MarkPrice string `json:"mark_price" example:"0.0035"` //SessionProfitLoss string `json:"session_profit_loss" example:"0.35"` //ProfitLoss string `json:"profit_loss" example:"0.07"` }
benmooo/necm-api
user_dj.go
package necmapi import ( "net/http" "regexp" "strconv" ) // 说明 : 登录后调用此接口 , 传入用户 id, 可以获取用户电台 // // required // 必选参数 : uid : 用户 id func (api *NeteaseAPI) UserDj(uid int, opts ...hm) (*APIResponse, error) { u := replaceAllRouteParams(APIRoutes["user_dj"], strconv.Itoa(uid)) data := hm{"limit": 30, "offset": 0}.Merge(opts...) resp, err := api.Req(http.MethodPost, u, data, nil) return resp, err } func replaceAllRouteParams(u, repl string) string { reg := regexp.MustCompile(`\${.*}`) return reg.ReplaceAllString(u, repl) }
spencec6/gatsby-twitter-feed
node_modules/webpack-validator/node_modules/joi/lib/string/rfc3986.js
'use strict'; // Load modules // Delcare internals const internals = { rfc3986: {} }; internals.generate = function () { /** * elements separated by forward slash ("/") are alternatives. */ const or = '|'; /** * DIGIT = %x30-39 ; 0-9 */ const digit = '0-9'; const digitOnly = '[' + digit + ']'; /** * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z */ const alpha = 'a-zA-Z'; const alphaOnly = '[' + alpha + ']'; /** * cidr = DIGIT ; 0-9 * / %x31-32 DIGIT ; 10-29 * / "3" %x30-32 ; 30-32 */ internals.rfc3986.cidr = digitOnly + or + '[1-2]' + digitOnly + or + '3' + '[0-2]'; /** * HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" */ const hexDigit = digit + 'A-Fa-f'; const hexDigitOnly = '[' + hexDigit + ']'; /** * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" */ const unreserved = alpha + digit + '-\\._~'; /** * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" */ const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; /** * pct-encoded = "%" HEXDIG HEXDIG */ const pctEncoded = '%' + hexDigit; /** * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" */ const pchar = unreserved + pctEncoded + subDelims + ':@'; const pcharOnly = '[' + pchar + ']'; /** * Rule to support zero-padded addresses. */ const zeroPad = '0?'; /** * dec-octet = DIGIT ; 0-9 * / %x31-39 DIGIT ; 10-99 * / "1" 2DIGIT ; 100-199 * / "2" %x30-34 DIGIT ; 200-249 * / "25" %x30-35 ; 250-255 */ const decOctect = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + digitOnly + digitOnly + or + '2' + '[0-4]' + digitOnly + or + '25' + '[0-5])'; /** * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet */ internals.rfc3986.IPv4address = '(?:' + decOctect + '\\.){3}' + decOctect; /** * h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal * ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address * IPv6address = 6( h16 ":" ) ls32 * / "::" 5( h16 ":" ) ls32 * / [ h16 ] "::" 4( h16 ":" ) ls32 * / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 * / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 * / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 * / [ *4( h16 ":" ) h16 ] "::" ls32 * / [ *5( h16 ":" ) h16 ] "::" h16 * / [ *6( h16 ":" ) h16 ] "::" */ const h16 = hexDigitOnly + '{1,4}'; const ls32 = '(?:' + h16 + ':' + h16 + '|' + internals.rfc3986.IPv4address + ')'; const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; internals.rfc3986.IPv6address = '(?:' + IPv6SixHex + or + IPv6FiveHex + or + IPv6FourHex + or + IPv6ThreeHex + or + IPv6TwoHex + or + IPv6OneHex + or + IPv6NoneHex + or + IPv6NoneHex2 + or + IPv6NoneHex3 + ')'; /** * IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) */ internals.rfc3986.IPvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; /** * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ internals.rfc3986.scheme = alphaOnly + '[' + alpha + digit + '+-\\.]*'; /** * userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) */ const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; /** * IP-literal = "[" ( IPv6address / IPvFuture ) "]" */ const IPLiteral = '\\[(?:' + internals.rfc3986.IPv6address + or + internals.rfc3986.IPvFuture + ')\\]'; /** * reg-name = *( unreserved / pct-encoded / sub-delims ) */ const regName = '[' + unreserved + pctEncoded + subDelims + ']{0,255}'; /** * host = IP-literal / IPv4address / reg-name */ const host = '(?:' + IPLiteral + or + internals.rfc3986.IPv4address + or + regName + ')'; /** * port = *DIGIT */ const port = digitOnly + '*'; /** * authority = [ userinfo "@" ] host [ ":" port ] */ const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; /** * segment = *pchar * segment-nz = 1*pchar * path = path-abempty ; begins with "/" or is empty * / path-absolute ; begins with "/" but not "//" * / path-noscheme ; begins with a non-colon segment * / path-rootless ; begins with a segment * / path-empty ; zero characters * path-abempty = *( "/" segment ) * path-absolute = "/" [ segment-nz *( "/" segment ) ] * path-rootless = segment-nz *( "/" segment ) */ const segment = pcharOnly + '*'; const segmentNz = pcharOnly + '+'; const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+'; const pathEmpty = ''; const pathAbEmpty = '(?:\\/' + segment + ')*'; const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; const pathRootless = segmentNz + pathAbEmpty; const pathNoScheme = segmentNzNc + pathAbEmpty; /** * hier-part = "//" authority path */ internals.rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathRootless + ')'; /** * relative-part = "//" authority path-abempty * / path-absolute * / path-noscheme * / path-empty */ internals.rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathNoScheme + or + pathEmpty + ')'; /** * query = *( pchar / "/" / "?" ) */ internals.rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line. /** * fragment = *( pchar / "/" / "?" ) */ internals.rfc3986.fragment = '[' + pchar + '\\/\\?]*'; }; internals.generate(); module.exports = internals.rfc3986;
Instagram-Clone-Coding/Instagram-Clone-Project
src/main/java/cloneproject/Instagram/domain/member/dto/JwtResponse.java
<filename>src/main/java/cloneproject/Instagram/domain/member/dto/JwtResponse.java package cloneproject.Instagram.domain.member.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @ApiModel("JWT 토큰 응답 데이터 모델") @Getter @NoArgsConstructor @AllArgsConstructor @Builder public class JwtResponse { @ApiModelProperty(value = "토큰 타입", example = "Bearer") private String type; @ApiModelProperty(value = "Access 토큰", example = "AAA.BBB.CCC") private String accessToken; }
SoftmedTanzania/opensrp-client-chw-hf
opensrp-chw-hf/src/main/java/org/smartregister/chw/hf/job/MarkPmtctAndHeiLtfServiceJob.java
<reponame>SoftmedTanzania/opensrp-client-chw-hf package org.smartregister.chw.hf.job; import android.content.Intent; import androidx.annotation.NonNull; import org.smartregister.AllConstants; import org.smartregister.chw.hf.sync.intent.MarkPmtctAndHeiLtfIntentService; import org.smartregister.job.BaseJob; /** * Created by cozej4 on 2022-03-24. * * @author cozej4 https://github.com/cozej4 */ public class MarkPmtctAndHeiLtfServiceJob extends BaseJob { public static final String TAG = "MarkPmtctAndHeiLtfServiceJob"; @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), MarkPmtctAndHeiLtfIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } }
tefra/xsdata-w3c-tests
output/models/nist_data/atomic/g_year_month/schema_instance/nistschema_sv_iv_atomic_g_year_month_max_exclusive_1_xsd/__init__.py
<gh_stars>1-10 from output.models.nist_data.atomic.g_year_month.schema_instance.nistschema_sv_iv_atomic_g_year_month_max_exclusive_1_xsd.nistschema_sv_iv_atomic_g_year_month_max_exclusive_1 import NistschemaSvIvAtomicGYearMonthMaxExclusive1 __all__ = [ "NistschemaSvIvAtomicGYearMonthMaxExclusive1", ]
ramok/Themis_ForHPSDR
c2000/C2000Ware_1_00_06_00/device_support/f2806x/examples/c28/bl_app/deprecated/usblib/usb_ids.h
//########################################################################### // // FILE: usb_ids.h // // TITLE: Definitions of VIDs and PIDs used by TI USB examples. // //########################################################################### // $TI Release: F2806x Support Library v2.04.00.00 $ // $Release Date: Thu Oct 18 15:47:20 CDT 2018 $ // $Copyright: Copyright (C) 2011-2015 Texas Instruments Incorporated - // http://www.ti.com/ ALL RIGHTS RESERVED $ //########################################################################### #ifndef __USBIDS_H__ #define __USBIDS_H__ //***************************************************************************** // // TI C2000 Vendor ID. // //***************************************************************************** #define USB_VID_C2000 0x1cbe //***************************************************************************** // // Product IDs. // //***************************************************************************** #define USB_PID_MOUSE 0x0000 #define USB_PID_KEYBOARD 0x0001 #define USB_PID_SERIAL 0x0002 #define USB_PID_BULK 0x0003 #define USB_PID_SCOPE 0x0004 #define USB_PID_MSC 0x0005 #define USB_PID_AUDIO 0x0006 #define USB_PID_COMP_SERIAL 0x0007 #define USB_PID_COMP_AUDIO_HID 0x0008 #define USB_PID_COMP_HID_SER 0x0009 #define USB_PID_COMP_HID_DFU 0x000A #define USB_PID_DATA_LOGGER 0x000B #define USB_PID_DFU 0x00FF #ifndef DEPRECATED //***************************************************************************** // // Deprecated definitions. // //***************************************************************************** #define USB_VID_TI USB_VID_C2000 #endif #endif /* __USBIDS_H__ */
valitydev/fraudbusters
src/main/java/dev/vality/fraudbusters/listener/payment/TemplateListener.java
package dev.vality.fraudbusters.listener.payment; import dev.vality.fraudo.FraudoPaymentParser; import dev.vality.damsel.fraudbusters.Command; import dev.vality.damsel.fraudbusters.CommandType; import dev.vality.damsel.fraudbusters.Template; import dev.vality.fraudbusters.fraud.FraudContextParser; import dev.vality.fraudbusters.fraud.payment.validator.PaymentTemplateValidator; import dev.vality.fraudbusters.listener.AbstractPoolCommandListenerExecutor; import dev.vality.fraudbusters.listener.CommandListener; import dev.vality.fraudbusters.pool.Pool; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.antlr.v4.runtime.ParserRuleContext; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.nio.charset.StandardCharsets; import java.util.List; @Slf4j @Component @RequiredArgsConstructor public class TemplateListener extends AbstractPoolCommandListenerExecutor implements CommandListener { private final FraudContextParser<FraudoPaymentParser.ParseContext> paymentContextParser; private final PaymentTemplateValidator paymentTemplateValidator; private final Pool<ParserRuleContext> templatePoolImpl; @Override @KafkaListener(topics = "${kafka.topic.template}", containerFactory = "templateListenerContainerFactory") public void listen(@Payload Command command) { log.info("TemplateListener command: {}", command); if (command != null && command.isSetCommandBody() && command.getCommandBody().isSetTemplate()) { Template template = command.getCommandBody().getTemplate(); String templateString = new String(template.getTemplate(), StandardCharsets.UTF_8); log.info("TemplateListener templateString: {}", templateString); if (CommandType.CREATE.equals(command.command_type)) { validateTemplate(template.getId(), templateString); } execCommand(command, template.getId(), templatePoolImpl, paymentContextParser::parse, templateString); } } private void validateTemplate(String id, String templateString) { List<String> validate = paymentTemplateValidator.validate(templateString); if (!CollectionUtils.isEmpty(validate)) { log.warn("TemplateListener templateId: {} validateError: {}", id, validate); } } }
digitalheir/java-cfg-parser
src/test/java/org/leibnizcenter/cfg/earleyparser/ExpressionWrapperTest.java
<filename>src/test/java/org/leibnizcenter/cfg/earleyparser/ExpressionWrapperTest.java package org.leibnizcenter.cfg.earleyparser; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created by maarten on 27-1-17. */ public class ExpressionWrapperTest { @Test public void getExpression() throws Exception { final ExpressionWrapper w = new ExpressionWrapper(new Atom(1)); assertEquals(new Atom(1), w.getExpression()); } @Test public void setExpression() throws Exception { final ExpressionWrapper w = new ExpressionWrapper(new Atom(1)); assertEquals(new Atom(1), w.getExpression()); w.setExpression(new Atom(3)); assertEquals(new Atom(3), w.getExpression()); } @Test(expected = IllegalStateException.class) public void setExpressionIllegal() throws Exception { final ExpressionWrapper w = new ExpressionWrapper(new Atom(1)); w.resolveFinal(); w.setExpression(null); } @Test public void resolve() throws Exception { assertTrue(1.0 == new ExpressionWrapper(new Atom(1)).resolveAndClean()); } }
yudong2015/openpitrix
pkg/models/attachment.go
<reponame>yudong2015/openpitrix<gh_stars>100-1000 // Copyright 2018 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. package models import ( "fmt" "time" "openpitrix.io/openpitrix/pkg/db" "openpitrix.io/openpitrix/pkg/pb" "openpitrix.io/openpitrix/pkg/util/idutil" "openpitrix.io/openpitrix/pkg/util/pbutil" ) const AttachmentIdPrefix = "att-" func NewAttachmentId() string { return fmt.Sprintf( "%s%s-%s", AttachmentIdPrefix, idutil.GetAttachmentPrefix(), idutil.GetUuid(""), ) } // "att-xxyyzzqqwweerrttyyaassddff-iooihogwe" => "xx/yy/zz/qq/" func getAttachmentObjectPrefix(attachmentId string) string { return fmt.Sprintf( "%s/%s/%s/%s/", attachmentId[4:6], attachmentId[6:8], attachmentId[8:10], attachmentId[10:12]) } type Attachment struct { AttachmentId string CreateTime time.Time } func (a Attachment) GetObjectName(filename string) string { return a.GetObjectPrefix() + filename } func (a Attachment) RemoveObjectName(filenameWithPrefix string) string { return filenameWithPrefix[len(a.GetObjectPrefix()):] } func (a Attachment) GetObjectPrefix() string { return getAttachmentObjectPrefix(a.AttachmentId) } var AttachmentColumns = db.GetColumnsFromStruct(&Attachment{}) func NewAttachment() *Attachment { return &Attachment{ AttachmentId: NewAttachmentId(), CreateTime: time.Now(), } } func AttachmentToPb(attachment *Attachment) *pb.Attachment { pbAttachment := pb.Attachment{} pbAttachment.AttachmentId = attachment.AttachmentId pbAttachment.CreateTime = pbutil.ToProtoTimestamp(attachment.CreateTime) return &pbAttachment } func AttachmentsToPbs(attachments []*Attachment) (pbAttachments []*pb.Attachment) { for _, attachment := range attachments { pbAttachments = append(pbAttachments, AttachmentToPb(attachment)) } return }
timfel/netbeans
javafx/javafx2.editor/src/org/netbeans/modules/javafx2/editor/completion/impl/IdReferenceCompleter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.javafx2.editor.completion.impl; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import org.netbeans.api.editor.mimelookup.MimeRegistration; import org.netbeans.modules.javafx2.editor.JavaFXEditorUtils; import org.netbeans.modules.javafx2.editor.completion.beans.FxBean; import org.netbeans.modules.javafx2.editor.completion.beans.FxProperty; import org.netbeans.modules.javafx2.editor.completion.model.FxInstance; import org.netbeans.spi.editor.completion.CompletionItem; /** * * @author sdedic */ @MimeRegistration(mimeType=JavaFXEditorUtils.FXML_MIME_TYPE, service=Completer.Factory.class) public class IdReferenceCompleter implements Completer, Completer.Factory { private static final String ICON_RESOURCE = "org/netbeans/modules/javafx2/editor/resources/variable_ref.png"; // NOI18N private CompletionContext ctx; public IdReferenceCompleter() { } IdReferenceCompleter(CompletionContext ctx) { this.ctx = ctx; } @Override public List<? extends CompletionItem> complete() { Set<String> names = ctx.getModel().getInstanceNames(); String prefix = ctx.getPrefix(); if (prefix.startsWith("$")) { prefix = prefix.substring(1); } FxProperty prop = ctx.getEnclosingProperty(); TypeMirror el = prop.getType().resolve(ctx.getCompilationInfo()); List<CompletionItem> items = new ArrayList<CompletionItem>(); for (String s : names) { if (!prefix.isEmpty() && !s.startsWith(prefix)) { continue; } FxInstance inst = ctx.getModel().getInstance(s); if (inst == null) { // ?? error in model ? throw new IllegalStateException(); } FxBean def = inst.getDefinition(); if (def == null) { continue; } // be conservative, allow unknown items in completion if (def.getJavaType() != null) { TypeElement clazz = def.getJavaType().resolve(ctx.getCompilationInfo()); if (clazz != null) { if (!ctx.getCompilationInfo().getTypes().isAssignable(el, clazz.asType())) { continue; } } } items.add(new ValueItem(ctx, s, "$", ICON_RESOURCE)); } return items; } @Override public boolean hasMoreItems() { return false; } @Override public Completer createCompleter(CompletionContext ctx) { switch (ctx.getType()) { case VARIABLE: case PROPERTY_VALUE: case PROPERTY_VALUE_CONTENT: break; default: return null; } FxProperty prop = ctx.getEnclosingProperty(); if (prop == null) { return null; } return new IdReferenceCompleter(ctx); } }
tdiprima/code
recipes/Python/580630_Saving_numpy_array_png_image_using_fitz__MuPDF/recipe-580630.py
#! /usr/bin/python # -*- coding: utf-8 -*- import numpy as np import fitz # this PyMuPDF #============================================================================== # Create any height*width*4 RGBA pixel area using numpy and then use fitz # to save it as a PNG image. # This is usually more than 10 times faster than pure python solutions # like pypng and more than 2 times faster than PIL / Pillow. #============================================================================== height = 108 # choose whatever width = 192 # you want here image = np.ndarray((height, width, 4), dtype=np.uint8) # data type uint8 is required! #============================================================================== # Fill the array. Each 4-byte-tuple represents a pixel with (R, B, G, A). # We have chosen A = 255 here (non transparent). #============================================================================== for i in range(height): for j in range(width): # just demoing - choose color components as you like them image[i, j] = np.array([i%256, j%256, 200, 255], dtype=np.uint8) #============================================================================== # create a string from the array and output the picture #============================================================================== samples = image.tostring() pix = fitz.Pixmap(fitz.csRGB, width, height, samples) pix.writePNG("test.png")
mdbloice/systemds
src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederatedResponse.java
<filename>src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederatedResponse.java<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysds.runtime.controlprogram.federated; import java.io.Serializable; import java.util.EnumMap; import java.util.Map; import java.util.concurrent.atomic.LongAdder; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.sysds.runtime.controlprogram.caching.CacheBlock; import org.apache.sysds.runtime.DMLRuntimeException; import org.apache.sysds.runtime.lineage.LineageItem; import org.apache.sysds.runtime.privacy.CheckedConstraintsLog; import org.apache.sysds.runtime.privacy.PrivacyConstraint.PrivacyLevel; public class FederatedResponse implements Serializable { private static final long serialVersionUID = 3142180026498695091L; public enum ResponseType { SUCCESS, SUCCESS_EMPTY, ERROR, } private ResponseType _status; private Object[] _data; private Map<PrivacyLevel,LongAdder> checkedConstraints; private transient LineageItem _linItem = null; // not included in serialized object public FederatedResponse(ResponseType status) { this(status, null, null); } public FederatedResponse(ResponseType status, Object[] data) { this(status, data, null); } public FederatedResponse(ResponseType status, Object[] data, LineageItem linItem) { _status = status; _data = data; if( _status == ResponseType.SUCCESS && data == null ) _status = ResponseType.SUCCESS_EMPTY; _linItem = linItem; } public FederatedResponse(FederatedResponse.ResponseType status, Object data) { this(status, data, null); } public FederatedResponse(FederatedResponse.ResponseType status, Object data, LineageItem linItem) { _status = status; _data = new Object[] {data}; if(_status == ResponseType.SUCCESS && data == null) _status = ResponseType.SUCCESS_EMPTY; _linItem = linItem; } public boolean isSuccessful() { return _status != ResponseType.ERROR; } public String getErrorMessage() { if (_data[0] instanceof Throwable ) return ExceptionUtils.getFullStackTrace( (Throwable) _data[0] ); else if (_data[0] instanceof String) return (String) _data[0]; else return "No readable error message"; } public Object[] getData() throws Exception { updateCheckedConstraintsLog(); if ( !isSuccessful() ) throwExceptionFromResponse(); return _data; } public long estimateSerializationBufferSize() { long minBufferSize = 312; // general offset for the FederatedResponse object if(_data != null) { for(Object obj : _data) { if(obj instanceof CacheBlock) minBufferSize += ((CacheBlock)obj).getExactSerializedSize(); } } return minBufferSize; } /** * Checks the data object array for exceptions that occurred in the federated worker * during handling of request. * @throws Exception the exception retrieved from the data object array * or DMLRuntimeException if no exception is provided by the federated worker. */ public void throwExceptionFromResponse() throws Exception { for ( Object potentialException : _data){ if (potentialException != null && (potentialException instanceof Exception) ){ throw (Exception) potentialException; } } String errorMessage = getErrorMessage(); if (getErrorMessage() != "No readable error message") throw new DMLRuntimeException(errorMessage); else throw new DMLRuntimeException("Unknown runtime exception in handling of federated request by federated worker."); } /** * Set checked privacy constraints in response if the provided map is not empty. * If the map is empty, it means that no privacy constraints were found. * @param checkedConstraints map of checked constraints from the PrivacyMonitor */ public void setCheckedConstraints(Map<PrivacyLevel,LongAdder> checkedConstraints){ if ( checkedConstraints != null && !checkedConstraints.isEmpty() ){ this.checkedConstraints = new EnumMap<>(PrivacyLevel.class); this.checkedConstraints.putAll(checkedConstraints); } } public void updateCheckedConstraintsLog(){ if ( checkedConstraints != null && !checkedConstraints.isEmpty() ) CheckedConstraintsLog.addCheckedConstraints(checkedConstraints); } public LineageItem getLineageItem() { return _linItem; } }
kusum007/kafka-connect-rest
kafka-connect-rest-plugin/src/test/java/com/tm/kafka/connect/rest/http/payload/templated/XPathResponseValueProviderTest.java
package com.tm.kafka.connect.rest.http.payload.templated; import com.tm.kafka.connect.rest.http.Request; import com.tm.kafka.connect.rest.http.Response; import org.junit.Before; import org.junit.Test; import java.util.Collections; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class XPathResponseValueProviderTest { Request request = mock(Request.class); Response response = mock(Response.class); XPathResponseValueProvider provider = new XPathResponseValueProvider(); @Before public void before() { provider.configure(Collections.emptyMap()); } @Test public void extractValuesTest_oneMatch() { provider.setExpressions(Collections.singletonMap("name", "/greeting/name")); when(response.getPayload()).thenReturn("<greeting><hail>Hello</hail><name>Big Ears</name></greeting>"); provider.extractValues(request, response); assertThat(provider.getParameters(), hasEntry("name", "Big Ears")); } @Test public void extractValuesTest_multipleMatches() { provider.setExpressions(Collections.singletonMap("name", "/greeting/name")); when(response.getPayload()).thenReturn("<greeting><hail>Hello</hail><name>Big Ears</name><name>Noddy</name></greeting>"); provider.extractValues(request, response); assertThat(provider.getParameters(), hasEntry("name", "Big Ears,Noddy")); } @Test public void extractValuesTest_noMatch() { provider.setExpressions(Collections.singletonMap("name", "/greeting/title")); when(response.getPayload()).thenReturn("<greeting><hail>Hello</hail><name>Big Ears</name></greeting>"); provider.extractValues(request, response); assertThat(provider.getParameters(), hasEntry("name", null)); } @Test public void extractValuesTest_illegalXPath() { provider.setExpressions(Collections.singletonMap("name", "/[/]title")); when(response.getPayload()).thenReturn("<greeting><hail>Hello</hail><name><NAME></name></greeting>"); provider.extractValues(request, response); assertThat(provider.getParameters(), not(hasKey(anything()))); } @Test public void extractValuesTest_illegalXML() { provider.setExpressions(Collections.singletonMap("name", "/greeting/title")); when(response.getPayload()).thenReturn("<greeting<hailHello><"); provider.extractValues(request, response); assertThat(provider.getParameters(), not(hasKey(anything()))); } @Test public void lookupValueTest_extracted() { provider.setExpressions(Collections.singletonMap("name", "/greeting/name")); when(response.getPayload()).thenReturn("<greeting><hail>Hello</hail><name><NAME></name></greeting>"); provider.extractValues(request, response); assertThat(provider.lookupValue("name"), equalTo("<NAME>")); } @Test public void lookupValueTest_fromEnvironment() { System.setProperty("test", "yeah"); assertThat(provider.lookupValue("test"), equalTo("yeah")); } @Test public void lookupValueTest_notDefined() { System.clearProperty("test"); assertThat(provider.lookupValue("test"), nullValue()); } }
alfazzafashion/image-js
node_modules/fast-png/lib-esm/index.js
import PngDecoder from './PngDecoder'; import PngEncoder from './PngEncoder'; export * from './types'; function decodePng(data, options) { const decoder = new PngDecoder(data, options); return decoder.decode(); } function encodePng(png, options) { const encoder = new PngEncoder(png, options); return encoder.encode(); } export { decodePng as decode, encodePng as encode }; //# sourceMappingURL=index.js.map
pupper68k/arcusplatform
platform/arcus-lib/src/main/java/com/iris/i18n/DBResourceBundleControl.java
/* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.iris.i18n; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; import com.google.inject.Inject; import com.iris.bootstrap.ServiceLocator; import com.iris.core.dao.ResourceBundleDAO; public class DBResourceBundleControl extends ResourceBundle.Control { private static final String DAO = "dao"; private final Supplier<ResourceBundleDAO> resourceBundleDaoProvider; public DBResourceBundleControl() { this.resourceBundleDaoProvider = () -> ServiceLocator.getInstance(ResourceBundleDAO.class); } @Inject public DBResourceBundleControl(ResourceBundleDAO resourceBundleDao) { this.resourceBundleDaoProvider = () -> resourceBundleDao; } @Override public List<String> getFormats(String baseName) { return Collections.<String>singletonList(DAO); } @Override public ResourceBundle newBundle( String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { Preconditions.checkArgument(!StringUtils.isBlank(baseName), "baseName must not be blank"); if(!DAO.equals(format)) { return null; } ResourceBundleDAO bundleDao = resourceBundleDaoProvider.get(); Map<String,String> bundle = bundleDao.loadBundle(baseName, locale); return new DBResourceBundle(bundle); } private class DBResourceBundle extends ResourceBundle { private final Map<String,String> bundle; private DBResourceBundle(Map<String,String> bundle) { this.bundle = Collections.unmodifiableMap(bundle); } @Override protected Object handleGetObject(String key) { Object value = bundle.get(key); if(value == null) { return parent != null ? parent.getObject(key) : null; } return value; } @Override public Enumeration<String> getKeys() { if(bundle.isEmpty()) { return parent != null ? parent.getKeys() : Collections.<String>emptyEnumeration(); } return Iterators.asEnumeration(bundle.keySet().iterator()); } } }
cloudawan/kubernetes_management_gui
controllers/inventory/service/edit.go
// Copyright 2015 CloudAwan LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 service import ( "github.com/astaxie/beego" "github.com/cloudawan/cloudone_gui/controllers/identity" "github.com/cloudawan/cloudone_gui/controllers/utility/guimessagedisplay" "github.com/cloudawan/cloudone_utility/restclient" "regexp" ) type EditController struct { beego.Controller } func (c *EditController) Get() { c.TplName = "inventory/service/edit.html" guimessage := guimessagedisplay.GetGUIMessage(c) // Authorization for web page display c.Data["layoutMenu"] = c.GetSession("layoutMenu") service := c.GetString("service") if service == "" { c.Data["actionButtonValue"] = "Create" c.Data["pageHeader"] = "Create Service" c.Data["serviceName"] = "" } else { c.Data["actionButtonValue"] = "Update" c.Data["pageHeader"] = "Update Service" c.Data["serviceName"] = service } guimessage.OutputMessage(c.Data) } func (c *EditController) Post() { guimessage := guimessagedisplay.GetGUIMessage(c) cloudoneProtocol := beego.AppConfig.String("cloudoneProtocol") cloudoneHost := beego.AppConfig.String("cloudoneHost") cloudonePort := beego.AppConfig.String("cloudonePort") namespace, _ := c.GetSession("namespace").(string) name := c.GetString("name") selectorName := c.GetString("selectorName") //labelName := c.GetString("labelName") //portName := c.GetString("portName") protocol := c.GetString("protocol") port, _ := c.GetInt("port") targetPort := c.GetString("targetPort") useNodePort := c.GetString("useNodePort") autoGeneratedNodePort := c.GetString("autoGeneratedNodePort") nodePort, _ := c.GetInt("nodePort") sessionAffinity := c.GetString("sessionAffinity") // Name need to be a DNS 952 label match, _ := regexp.MatchString("^[a-z]{1}[a-z0-9-]{1,23}$", name) if match == false { guimessage.AddDanger("The name need to be a DNS 952 label ^[a-z]{1}[a-z0-9-]{1,23}$") c.Ctx.Redirect(302, "/gui/inventory/service/list") guimessage.RedirectMessage(c) return } labelName := selectorName portName := selectorName if useNodePort == "on" { if autoGeneratedNodePort == "on" { nodePort = 0 } } else { nodePort = -1 } portSlice := make([]ServicePort, 0) portSlice = append(portSlice, ServicePort{portName, protocol, port, targetPort, nodePort, "", "", ""}) selectorMap := make(map[string]interface{}) selectorMap["name"] = selectorName labelMap := make(map[string]interface{}) labelMap["name"] = labelName service := Service{name, namespace, portSlice, selectorMap, "", labelMap, sessionAffinity, "", ""} url := cloudoneProtocol + "://" + cloudoneHost + ":" + cloudonePort + "/api/v1/services/" + namespace tokenHeaderMap, _ := c.GetSession("tokenHeaderMap").(map[string]string) _, err := restclient.RequestPostWithStructure(url, service, nil, tokenHeaderMap) if identity.IsTokenInvalidAndRedirect(c, c.Ctx, err) { return } if err != nil { // Error guimessage.AddDanger(guimessagedisplay.GetErrorMessage(err)) } else { guimessage.AddSuccess("Service " + name + " is edited") } c.Ctx.Redirect(302, "/gui/inventory/service/list") guimessage.RedirectMessage(c) }
lechium/tvOS10Headers
System/Library/PrivateFrameworks/AssistantUI.framework/AFUISpeechSynthesisElement.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:08:10 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/PrivateFrameworks/AssistantUI.framework/AssistantUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol AFUISpeechSynthesisElementDelegate; @class NSString, VSSpeechRequest, NSDictionary; @interface AFUISpeechSynthesisElement : NSObject { NSString* _text; BOOL _isPhonetic; BOOL _eligibleForSynthesis; BOOL _provisional; BOOL _preprationBlockCompleted; BOOL _durationHasElapsed; VSSpeechRequest* _speechRequest; long long _synthesisResult; id<AFUISpeechSynthesisElementDelegate> _delegate; NSString* _animationIdentifier; NSDictionary* _analyticsContext; /*^block*/id _completion; } @property (assign,setter=_setEligibleForSynthesis:,getter=isEligibleForSynthesis,nonatomic) BOOL eligibleForSynthesis; //@synthesize eligibleForSynthesis=_eligibleForSynthesis - In the implementation block @property (getter=_completion,nonatomic,readonly) id completion; //@synthesize completion=_completion - In the implementation block @property (setter=_setText:,nonatomic,copy) NSString * text; //@synthesize text=_text - In the implementation block @property (setter=_setPreparationBlockCompleted:) BOOL preprationBlockCompleted; //@synthesize preprationBlockCompleted=_preprationBlockCompleted - In the implementation block @property (setter=_setDurationHasElapsed:) BOOL durationHasElapsed; //@synthesize durationHasElapsed=_durationHasElapsed - In the implementation block @property (assign,nonatomic) BOOL isPhonetic; //@synthesize isPhonetic=_isPhonetic - In the implementation block @property (getter=isProvisional,nonatomic,readonly) BOOL provisional; //@synthesize provisional=_provisional - In the implementation block @property (nonatomic,retain) VSSpeechRequest * speechRequest; //@synthesize speechRequest=_speechRequest - In the implementation block @property (assign,nonatomic) long long synthesisResult; //@synthesize synthesisResult=_synthesisResult - In the implementation block @property (assign,nonatomic,__weak) id<AFUISpeechSynthesisElementDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block @property (nonatomic,readonly) NSString * animationIdentifier; //@synthesize animationIdentifier=_animationIdentifier - In the implementation block @property (nonatomic,readonly) NSDictionary * analyticsContext; //@synthesize analyticsContext=_analyticsContext - In the implementation block -(BOOL)isPhonetic; -(void)setDelegate:(id<AFUISpeechSynthesisElementDelegate>)arg1 ; -(id)init; -(id)description; -(id<AFUISpeechSynthesisElementDelegate>)delegate; -(NSString *)text; -(void)_setText:(id)arg1 ; -(/*^block*/id)_completion; -(void)_setDurationHasElapsed:(BOOL)arg1 ; -(void)_setPreparationBlockCompleted:(BOOL)arg1 ; -(BOOL)durationHasElapsed; -(BOOL)preprationBlockCompleted; -(void)_updateSynthesisEligibility; -(id)initWithText:(id)arg1 provisional:(BOOL)arg2 eligibleAfterDuration:(double)arg3 preparation:(/*^block*/id)arg4 completion:(/*^block*/id)arg5 animationIdentifier:(id)arg6 analyticsContext:(id)arg7 ; -(BOOL)isProvisional; -(BOOL)isEligibleForSynthesis; -(void)_setEligibleForSynthesis:(BOOL)arg1 ; -(void)executeCompletion; -(void)setIsPhonetic:(BOOL)arg1 ; -(VSSpeechRequest *)speechRequest; -(void)setSpeechRequest:(VSSpeechRequest *)arg1 ; -(long long)synthesisResult; -(void)setSynthesisResult:(long long)arg1 ; -(NSString *)animationIdentifier; -(NSDictionary *)analyticsContext; @end
qualitesys/openssl-1
docs/QcrReportFile01File493detailjsondata.js
<reponame>qualitesys/openssl-1 console.log('leListeStr main01 start json de data maDataBlocs'); var maDataBlocs = { "data00" : { "fic1" : "./qc/crypto/evp/legacy_sha.c.html" , "texte" : "File crypto/evp/legacy_sha.c 20 rule violations " , "fic2" : "./qc/crypto/evp/legacy_sha.c.xml" , "fic3" : "" } , "data01" : [ ] , "data02" : [ ] , "data03" : [ ] , "data04" : [ ] , "data05" : [ ] , "data06" : [ ] , "data07" : [ ] , "data08" : [ ] , "data11" : [ ] , "data14" : [ ] , "data13a" : [ { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000012" , "c3" : "The condition expression is invariable, always true or false" , "c4" : "16" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000018" , "c3" : "A suspicious bitwise expression is compared to a numerical expression" , "c4" : "3" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPP000014" , "c3" : "A pointer is defined but not initialized" , "c4" : "1" }} ] , "data13b" : [ { "ligne" : { "c1" : "01324" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1324" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01324] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "01329" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1329" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01329] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "01354" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1354" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01354] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01358" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1358" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[01358] Suspicious mix of Bitwise and Literal expressions in (__size|__n)&gt;=(((size_t )1)&lt;&lt;(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "01361" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1361" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01361] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01386" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1386" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01386] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01390" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1390" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[01390] Suspicious mix of Bitwise and Literal expressions in (__size|__n)&gt;=(((size_t )1)&lt;&lt;(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "01394" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1394" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01394] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01402" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#1402" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[01402] Suspicious mix of Bitwise and Literal expressions in (__size|__n)&lt;(((size_t )1)&lt;&lt;(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "03384" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3384" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[03384] The pointer __p is declared but not initialized" }} , { "ligne" : { "c1" : "03547" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3547" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03547] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03550" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3550" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03550] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03574" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3574" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03574] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03578" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3578" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03578] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03600" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3600" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03600] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03600" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3600" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03600] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03624" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3624" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03624] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03630" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3630" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03630] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03655" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3655" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03655] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "03659" , "c1link" : "./qc/crypto/evp/legacy_sha.c.html#3659" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[03659] The expression 2&gt;1 is invariable" }} ] }; console.log('leListeStr 99 main end');
cljnnn/v2
locale/locale.go
// Copyright 2018 <NAME>. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package locale // import "miniflux.app/locale" // AvailableLanguages returns the list of available languages. func AvailableLanguages() map[string]string { return map[string]string{ "en_US": "English", "es_ES": "Español", "fr_FR": "Français", "de_DE": "Deutsch", "pl_PL": "Polski", "pt_BR": "Português Brasileiro", "zh_CN": "简体中文", "nl_NL": "Nederlands", "ru_RU": "Русский", "it_IT": "Italiano", "ja_JP": "日本語", "tr_TR": "Türkçe", "el_EL": "Ελληνικά", } }
Kiransibi/Android-Activity-Tracker-for-Dynamics-CRM-Web-API
app/src/main/java/com/microsoft/activitytracker/classes/scopes/StorageScope.java
package com.microsoft.activitytracker.classes.scopes; import javax.inject.Scope; @Scope public @interface StorageScope { }
powernit/epicode
java/src/main/java/com/epi/PathSumBinaryTree.java
package com.epi; /* @slug path-sum-binary-tree @summary You are given a binary tree where each node is labeled with an integer. The path weight of a node in such a tree is the sum of the integers on the unique path from the root to that node. For the example shown in the figure, the path weight of E is 591. @problem Write a program which takes as input an integer and a binary tree with integer node weights, and checks if there exists a leaf whose path weight equals the given integer. */ import com.epi.BinaryTreePrototypeTemplate.BinaryTreeNode; public class PathSumBinaryTree { // @include public static boolean hasPathSum(BinaryTreeNode<Integer> tree, int targetSum) { return hasPathSumHelper(tree, 0, targetSum); } private static boolean hasPathSumHelper(BinaryTreeNode<Integer> node, int partialPathSum, int targetSum) { if (node == null) { return false; } partialPathSum += node.data; if (node.left == null && node.right == null) { // Leaf. return partialPathSum == targetSum; } // Non-leaf. return hasPathSumHelper(node.left, partialPathSum, targetSum) || hasPathSumHelper(node.right, partialPathSum, targetSum); } // @exclude public static void main(String[] args) { // 3 // 2 5 // 1 4 6 BinaryTreeNode<Integer> tree = new BinaryTreeNode<>(3); assert(hasPathSum(tree, 3)); tree.left = new BinaryTreeNode<>(2); assert(hasPathSum(tree, 5)); tree.left.left = new BinaryTreeNode<>(1); assert(hasPathSum(tree, 6)); tree.right = new BinaryTreeNode<>(5); assert(hasPathSum(tree, 8)); assert(!hasPathSum(tree, 7)); tree.right.left = new BinaryTreeNode<>(4); assert(hasPathSum(tree, 12)); assert(!hasPathSum(tree, 1)); assert(!hasPathSum(tree, 3)); assert(!hasPathSum(tree, 5)); tree.right.right = new BinaryTreeNode<>(6); assert(hasPathSum(tree, 6)); assert(!hasPathSum(tree, 7)); assert(hasPathSum(tree, 14)); assert(!hasPathSum(tree, -1)); assert(!hasPathSum(tree, Integer.MAX_VALUE)); assert(!hasPathSum(tree, Integer.MIN_VALUE)); } }