repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
INT2ECALL/capsule8
test/functional/container.go
<gh_stars>10-100 // Copyright 2017 Capsule8, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package functional import ( "os/exec" "strings" "testing" "golang.org/x/net/context" ) type Container struct { t *testing.T Path string ImageID string command *exec.Cmd } func (c *Container) dockerBuildArgs(quiet bool, buildargs []string) []string { args := []string{"build"} if quiet { args = append(args, "-q") } args = append(args, buildargs...) args = append(args, c.Path) return args } func (c *Container) Build(buildargs ...string) error { dockerArgs := c.dockerBuildArgs(false, buildargs) docker := exec.Command("docker", dockerArgs...) err := docker.Run() if err != nil { return err } dockerArgs = c.dockerBuildArgs(true, buildargs) docker = exec.Command("docker", dockerArgs...) dockerOutput, err := docker.Output() if err != nil { return err } trimmed := strings.TrimSpace(string(dockerOutput)) c.ImageID = strings.TrimPrefix(trimmed, "sha256:") return nil } func (c *Container) dockerRunArgs(runargs []string) []string { args := append([]string{"run", "--rm"}, runargs...) args = append(args, c.ImageID) return args } func (c *Container) Start(runargs ...string) error { dockerArgs := c.dockerRunArgs(runargs) c.command = exec.Command("docker", dockerArgs...) return c.command.Start() } func (c *Container) StartContext(ctx context.Context, runargs ...string) error { dockerArgs := c.dockerRunArgs(runargs) c.command = exec.CommandContext(ctx, "docker", dockerArgs...) return c.command.Start() } func (c *Container) Wait() error { return c.command.Wait() } func (c *Container) Run(runargs ...string) error { dockerArgs := c.dockerRunArgs(runargs) c.command = exec.Command("docker", dockerArgs...) return c.command.Run() } func (c *Container) RunContext(ctx context.Context, runargs ...string) error { dockerArgs := c.dockerRunArgs(runargs) c.command = exec.CommandContext(ctx, "docker", dockerArgs...) return c.command.Run() } func NewContainer(t *testing.T, path string) *Container { return &Container{ t: t, Path: path, } }
27crags/scaffolding_extensions
test_site/app/models/dm_officer.rb
class DmOfficer include DataMapper::Resource property :id, Serial property :name, String property :position_id, Integer storage_names[:default] = 'officers' belongs_to :position, :model => 'DmPosition', :child_key => [:position_id], :required => false has n, :groups, :model => 'DmGroup', :through => Resource @scaffold_name = 'officer' @scaffold_human_name = 'Officer' @scaffold_select_order = 'name' @scaffold_use_auto_complete = true @scaffold_browse_records_per_page = nil def self.scaffold_association_use_auto_complete(association) true end end
PaulBryden/ContextualTriggers
contextualtriggers/src/main/java/uk/ac/strath/contextualtriggers/conditions/GymNearbyCondition.java
package uk.ac.strath.contextualtriggers.conditions; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.model.PlaceLikelihood; import uk.ac.strath.contextualtriggers.data.PlacesData; import uk.ac.strath.contextualtriggers.managers.IDataManager; /** * A condition that checks for nearby gyms. */ public class GymNearbyCondition extends DataCondition<PlacesData> { public GymNearbyCondition(IDataManager<PlacesData> dataManager) { super(dataManager, 20); } @Override public boolean isSatisfied() { if (getData() == null) { return false; } boolean nearGym = false; for (PlaceLikelihood p : getData().places) { for (Place.Type type : p.getPlace().getTypes()) { if (type == Place.Type.GYM) { if (p.getLikelihood() < 0.5) { nearGym = true; } else { return false; } } } } return nearGym; } }
snpmyn/MyApplication
app/src/main/java/customview/point/PointActivity.java
package customview.point; import com.example.myapplication.R; import base.BaseActivity; /** * @decs: 点页 * @author: zsp * @date: 2020/7/3 10:24 */ public class PointActivity extends BaseActivity { /** * 布局资源 ID * * @return 布局资源 ID */ @Override protected int layoutResId() { return R.layout.activity_point; } /** * 初始控件 */ @Override protected void stepUi() { } /** * 初始配置 */ @Override protected void initConfiguration() { } /** * 设置监听 */ @Override protected void setListener() { } /** * 初始数据 */ @Override protected void initData() { } /** * 开始逻辑 */ @Override protected void startLogic() { } }
mcc-github/blockchain
common/flogging/logger.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package flogging type Logger interface { Critical(args ...interface{}) Criticalf(format string, args ...interface{}) Debug(args ...interface{}) Debugf(format string, args ...interface{}) Error(args ...interface{}) Errorf(format string, args ...interface{}) Fatal(args ...interface{}) Fatalf(format string, args ...interface{}) Info(args ...interface{}) Infof(format string, args ...interface{}) Notice(args ...interface{}) Noticef(format string, args ...interface{}) Panic(args ...interface{}) Panicf(format string, args ...interface{}) Warning(args ...interface{}) Warningf(format string, args ...interface{}) }
012huang/wormhole
rider/mad-server/src/main/scala/edp/mad/schedule/MadScheduler.scala
<gh_stars>0 /*- * << * wormhole * == * Copyright (C) 2016 - 2017 EDP * == * 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 edp.mad.schedule import akka.actor.{Actor, ActorRef, Props} import edp.mad.alert.StreamDiagnosis import edp.mad.elasticsearch.MadES._ import edp.mad.module._ import edp.mad.persistence.entities._ import edp.mad.util.OffsetUtils import edp.wormhole.common.util.DateUtils._ import edp.wormhole.common.util.DtFormat import edp.wormhole.common.util.JsonUtils import org.apache.log4j.Logger import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import scala.language.postfixOps object MadScheduler { private val logger = Logger.getLogger(this.getClass) val modules = ModuleObj.getModule def start: Unit = { val schedulerActor: ActorRef = modules.system.actorOf(Props[SchedulerActor]) modules.system.scheduler.schedule(30.seconds, 12.hours, schedulerActor, "maintenance") modules.system.scheduler.schedule(30.seconds, 10.minutes, schedulerActor, "analysisAndDiagnosis") modules.system.scheduler.schedule(30.seconds, 10.minutes, schedulerActor, "MapPersistence") modules.system.scheduler.schedule(30.seconds, 10.minutes, schedulerActor, "CacheRefresh") } class SchedulerActor extends Actor { def receive = { case "maintenance" => { createEsIndex deleteEsIndex logger.info(s" Scheduler maintenance task ${new java.util.Date().toString} start") } case "analysisAndDiagnosis" => { logger.info(s" Scheduler maintenance task ${new java.util.Date().toString} start") } case "MapPersistence" => { hashMapPersistence madES.indexMaintenance logger.info(s" Scheduler maintenance task ${new java.util.Date().toString} start") } case "CacheRefresh" => { logger.info(s" Scheduler maintenance task ${new java.util.Date().toString} start") cacheRefresh } case _ => {} logger.info(s"timer ${new java.util.Date().toString}") } } def hashMapPersistence ={ logger.info(s"--------- StreamFeedbackMap \n ") val curTs = yyyyMMddHHmmssToString(currentyyyyMMddHHmmss, DtFormat.TS_DASH_MILLISEC) modules.streamFeedbackMap.getMapHandle.foreach{e=> logger.info(s"--------- StreamFeedbackMap item ${e} \n") modules.cacheEffectDal.updateOrInsert(Seq(CacheEffectEntity(0,e._1, e._2, e._3,e._4,e._5))) logger.info(s"--------- \n") } val offsetList = modules.offsetMap.getMapHandle logger.info(s"--------- offsetList item ${offsetList} \n") val topicList = offsetList.groupBy(t => (t._1, t._2)).map{e=> (e._1._1,e._1._2, e._2.map(it => it._3 +":" +it._4).sorted.mkString(",")) } logger.info(s"--------- getOffsetCacheHandle item ${topicList} \n") topicList.foreach{et => //logger.info(s"--------- topicList ${et} \n") val partitionNum = OffsetUtils.getPartitionNumber(et._3) val offsetEntity = OffsetTableEntity(0, et._1,et._2, partitionNum, et._3, curTs ) logger.info(s"--------- offset Entity ${offsetEntity} \n") modules.offsetSavedDal.updateOrInsert(Seq( offsetEntity)) } //modules.offsetDal.insert() // if(modules.madMaintenance.cachePersistence == true && modules.madRedis.enable == false){ // modules.streamMap.getMapHandle.foreach{e=> // logger.info(s"--------- Stream Map item ${e} \n") // modules.streamCacheDal.updateOrInsert(Seq(StreamCacheEntity(0,e._1, e._2, "", JsonUtils.caseClass2json(e._3), JsonUtils.caseClass2json(e._4),curTs,curTs))) // logger.info(s"--------- \n") // } // // modules.applicationMap.getMapHandle.foreach{e=> // logger.info(s"--------- Application Map item ${e} \n") // modules.applicationCacheDal.updateOrInsert(Seq(ApplicationCacheEntity(0,e._1, e._2, curTs,curTs))) // logger.info(s"--------- \n") // } // // modules.namespaceMap.getMapHandle.foreach{e=> // logger.info(s"--------- Namespace Map item ${e} \n") // modules.namespaceCacheDal.updateOrInsert(Seq(NamespaceCacheEntity(0,e._1, e._2, curTs,curTs))) // logger.info(s"--------- \n") // } // } } def cacheRefresh={ // 1 refresh logger.info(s" --------- \n") modules.streamMap.refresh logger.info(s" --------- \n") modules.namespaceMap.refresh logger.info(s" --------- \n") modules.applicationMap.refresh logger.info(s" --------- \n") modules.streamMap.mapPrint StreamDiagnosis.streamStatusDiagnosis() logger.info(s" --------- \n") // 2 delete expire map if(modules.madRedis.enable == false){ // delete the streamMap settings on rider, but the status is not running // delete the appllicatoinMap which is not the wormhole stream } } def deleteEsIndex={ madES.deleteHistoryIndex } def createEsIndex={ madES.autoCreateIndexByPattern } }
SimpleGraduationProjects/MobileMallManagementSystem
src/com/java/controller/ClientController.java
<gh_stars>0 package com.java.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.java.model.*; import com.java.service.*; import com.java.utils.CommonUtils; import com.java.utils.PageList; import com.java.utils.ResponseUtil; @Controller @RequestMapping("/client") public class ClientController { private ClientService clientService; public ClientService getClientService() { return clientService; } @Autowired public void setClientService(ClientService clientService) { this.clientService = clientService; } @Autowired private HttpServletRequest request; @Autowired private HttpServletResponse response; @SuppressWarnings("finally") @RequestMapping("/reg") public String add() { return "reg"; } @SuppressWarnings("finally") @RequestMapping("/pwd") public String pwd() { Client c=(Client)request.getSession().getAttribute("client"); request.setAttribute("client", c); return "user/editpass"; } @SuppressWarnings("finally") @RequestMapping("/editform") public String EditForm() { Client c=(Client)request.getSession().getAttribute("client"); request.setAttribute("client", c); return "user/edit"; } @SuppressWarnings("finally") @RequestMapping("/client_add") public String Add(Client c) { Map<String,Object> map = new HashMap<String,Object>(); try { System.out.println(request.getParameter("login")); List<Map> list=clientService.GetMy(c); if(list!=null && list.size()>0){ map.put("mgf", "注册失败,用户名或者手机号重复!"); map.put("success", false); String result2 = new JSONObject(map).toString(); ResponseUtil.write(response, result2); return null; } int r = clientService.Add(c); if(r>0) { map.put("mgf", "注册成功"); map.put("success", true); } else { map.put("mgf", "注册失败"); map.put("success", false); } } catch (Exception e) { map.put("mgf", "错误:"+e.getMessage()); map.put("success", false); } String result = new JSONObject(map).toString(); ResponseUtil.write(response, result); return null; } @SuppressWarnings("finally") @RequestMapping("/edit") public String Edit() { Map<String,Object> map = new HashMap<String,Object>(); try { Client c=(Client)request.getSession().getAttribute("client"); System.out.println(request.getParameter("login")); c.setAddress(request.getParameter("address")); c.setMail(request.getParameter("mail")); c.setSex(request.getParameter("sex")); c.setTel(request.getParameter("tel")); int r=clientService.Edit(c); if(r>0) { map.put("mgf", "修改成功"); map.put("success", true); request.getSession().setAttribute("client", c); } else { map.put("mgf", "修改失败"); map.put("success", false); } } catch (Exception e) { map.put("mgf", "错误:"+e.getMessage()); map.put("success", false); } String result = new JSONObject(map).toString(); ResponseUtil.write(response, result); return null; } @SuppressWarnings("finally") @RequestMapping("/editpass") public String EditPass() { Map<String,Object> map = new HashMap<String,Object>(); try { Client c=(Client)request.getSession().getAttribute("client"); c.setPwd(request.getParameter("pwd")); int r=clientService.EditPass(c); if(r>0) { map.put("mgf", "密码修改成功,下次请用新密码登陆"); map.put("success", true); request.getSession().setAttribute("client", c); } else { map.put("mgf", "密码修改失败"); map.put("success", false); } } catch (Exception e) { map.put("mgf", "错误:"+e.getMessage()); map.put("success", false); } String result = new JSONObject(map).toString(); ResponseUtil.write(response, result); return null; } @RequestMapping("/client_list") public String Get(Client c) { //分页参数设置 Pages p=new Pages(); p.setPagesize(10);//每页显示数量 int startindex=request.getParameter("startindex")==null?0:Integer.parseInt(request.getParameter("startindex"));//起始页,默认从第1页开始读 p.setStartindex(startindex); c.setPage(p); try { List<Client> list = clientService.Get(c); System.out.println(list); request.setAttribute("list", list); //分页 request.setAttribute("pages", PageList.Page(request,"client/client_list.do", clientService.GetCount(c), p.getPagesize(), p.getStartindex(),request.getQueryString())); return "admin/client"; } catch (Exception e) { return null; } } @RequestMapping("/showmes") public String GetByID() { try { int id=Integer.parseInt(request.getParameter("id")); Client c = clientService.GetByID(id); request.setAttribute("client", c); return "reg"; } catch (Exception e) { return null; } } @RequestMapping("/login") public String Login(Client client) { Map<String,Object> map = new HashMap<String,Object>(); try { Client a = clientService.Login(client.getLogin()); if(a==null) { map.put("mgf", "用户不存在"); map.put("success", false); } else if(!a.getPwd().equals(client.getPwd())) { map.put("mgf", "密码错误"); map.put("success", false); } else { request.getSession().setAttribute("client", a); map.put("mgf", "登录成功!"); map.put("success", true); } } catch (Exception e) { map.put("mgf", "错误:"+e.getMessage()); map.put("success", false); } String result = new JSONObject(map).toString(); ResponseUtil.write(response, result); return null; } @SuppressWarnings("finally") @RequestMapping(value="/client_del", method = RequestMethod.POST) public String Del(@RequestParam(value = "id") int id) { Map<String,Object> map = new HashMap<String,Object>(); try { System.out.println("================================"); System.out.println(id); int r = clientService.Del(id); if(r>0) { map.put("mgf", "删除成功"); map.put("success", true); } else { map.put("mgf", "删除失败"); map.put("success", false); } } catch (Exception e) { map.put("mgf", "错误:"+e.getMessage()); map.put("success", false); } String result = new JSONObject(map).toString(); ResponseUtil.write(response, result); return null; } @RequestMapping("/exit") public String Exit() { Map<String,Object> map = new HashMap<String,Object>(); try { request.getSession().removeAttribute("client"); map.put("mgf", "已安全退出!"); map.put("success", true); } catch (Exception e) { map.put("mgf", "错误:"+e.getMessage()); map.put("success", false); } String result = new JSONObject(map).toString(); ResponseUtil.write(response, result); return null; } }
AJAkimana/ivugurura-ui
src/views/AdminSetting.js
import React, { useState, useEffect } from 'react'; import { AdminPageHeader } from '../components/common'; import { Row, Container, Col } from 'react-bootstrap'; import { Announcement } from '../components/models'; import { AdminCommuniques, MenuSetting, Page } from '../components'; import { useSelector } from 'react-redux'; export const AdminSetting = () => { const [show, setShow] = useState(false); const { communiqueAdded } = useSelector(({ communiqueAdd }) => communiqueAdd); useEffect(() => { if (communiqueAdded) { setShow(false); } }, [communiqueAdded]); return ( <Page title='Setting'> <Announcement show={show} onHide={() => setShow(false)} /> <AdminPageHeader name='Site setting' btnTitle='Add a new communication' btnAction={() => setShow(true)} /> <section className='tables'> <Container fluid> <Row> <Col sm={12} md={8}> <AdminCommuniques /> </Col> <Col sm={12} md={4}> <MenuSetting /> </Col> </Row> </Container> </section> </Page> ); }; export default AdminSetting;
DeepAQ/Autumn
autumn-http/autumn-http-common/src/main/java/cn/imaq/autumn/http/protocol/AutumnHttpRequest.java
<gh_stars>10-100 package cn.imaq.autumn.http.protocol; import lombok.Builder; import lombok.Data; import java.net.SocketAddress; import java.util.List; import java.util.Map; @Data @Builder public class AutumnHttpRequest { private String method; private String path; private String protocol; private Map<String, List<String>> headers; private byte[] body; private SocketAddress localAddress; private SocketAddress remoteAddress; public byte[] toHeaderBytes() { StringBuilder sb = new StringBuilder(); sb.append(method).append(' ').append(path).append(' ').append(protocol).append("\r\n"); if (headers != null) { for (Map.Entry<String, List<String>> header : headers.entrySet()) { for (String value : header.getValue()) { sb.append(header.getKey()).append(": ").append(value).append("\r\n"); } } } if (body != null) { sb.append("Content-Length: ").append(body.length).append("\r\n"); } sb.append("\r\n"); return sb.toString().getBytes(); } }
nablarch/nablarch-fw-jaxrs
src/test/java/nablarch/fw/jaxrs/integration/app/IntegrationTestResource.java
<reponame>nablarch/nablarch-fw-jaxrs<filename>src/test/java/nablarch/fw/jaxrs/integration/app/IntegrationTestResource.java package nablarch.fw.jaxrs.integration.app; import nablarch.core.db.connection.ConnectionFactory; import nablarch.core.db.connection.TransactionManagerConnection; import nablarch.core.db.statement.ResultSetIterator; import nablarch.core.db.statement.SqlPStatement; import nablarch.core.db.statement.SqlRow; import nablarch.core.repository.SystemRepository; import nablarch.core.repository.di.ComponentDefinitionLoader; import nablarch.core.repository.di.DiContainer; import nablarch.core.repository.di.config.xml.XmlComponentDefinitionLoader; import org.junit.rules.ExternalResource; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class IntegrationTestResource extends ExternalResource { private TransactionManagerConnection connection; public void truncatePersonTable() { SqlPStatement statement = connection.prepareStatement("truncate table person"); statement.execute(); statement.close(); connection.commit(); } @Override protected void before() throws Throwable { super.before(); loadRepository(); connection = getConnection(); createTestTable(); } private void createTestTable() { System.out.println("create person table"); SqlPStatement statement = connection.prepareStatement( "create table if not exists person (id IDENTITY , name varchar(100) not null, PRIMARY KEY (id))"); statement.execute(); statement.close(); connection.commit(); } private void loadRepository() { ComponentDefinitionLoader loader = new XmlComponentDefinitionLoader("integration/db.xml"); SystemRepository.clear(); SystemRepository.load(new DiContainer(loader)); } private TransactionManagerConnection getConnection() { ConnectionFactory connectionFactory = SystemRepository.get("connectionFactory"); return connectionFactory.getConnection("test-tran"); } @Override protected void after() { super.after(); closeConnection(); SystemRepository.clear(); } private void closeConnection() { try { connection.terminate(); } catch (Throwable ignore) { ignore.printStackTrace(); } } public Long insertPerson(String name) throws Exception { SqlPStatement statement = connection.prepareStatement("insert into person (name) values (?)", new int[] {1}); statement.setString(1, name); statement.executeUpdate(); ResultSet keys = statement.getGeneratedKeys(); Long id; if (keys.next()) { id = keys.getLong(1); } else { throw new RuntimeException("error"); } statement.close(); connection.commit(); return id; } public Person findPerson(Long id) { SqlPStatement statement = connection.prepareStatement("select name from person where id = ?"); statement.setLong(1, id); ResultSetIterator rows = statement.executeQuery(); if (rows.next()) { return new Person(id, rows.getString(1)); } else { return null; } } public List<Person> findAllPerson() { SqlPStatement statement = connection.prepareStatement("select id, name from person order by id"); ResultSetIterator rows = statement.executeQuery(); ArrayList<Person> persons = new ArrayList<Person>(); for (SqlRow row : rows) { persons.add(new Person(row.getLong("id"), row.getString("name"))); } return persons; } }
xakep666/konfig
loader/klconsul/consulloader.go
<filename>loader/klconsul/consulloader.go package klconsul import ( "bytes" "errors" "fmt" "os" "time" "github.com/hashicorp/consul/api" "github.com/lalamove/konfig" "github.com/lalamove/konfig/parser" "github.com/lalamove/konfig/watcher/kwpoll" "github.com/lalamove/nui/nlogger" "github.com/lalamove/nui/nstrings" ) var ( defaultTimeout = 5 * time.Second _ konfig.Loader = (*Loader)(nil) ) const ( defaultName = "consul" ) // Key is an Consul Key to load type Key struct { // Key is the consul key Key string // Parser is the parser for the key // If nil, the value is casted to a string before adding to the config.Store Parser parser.Parser // QueryOptions is the query options to pass when retrieving the key from consul QueryOptions *api.QueryOptions } // ConsulKV is an interface that consul client.KV implements. It is used to retrieve keys. type ConsulKV interface { Get(key string, q *api.QueryOptions) (*api.KVPair, *api.QueryMeta, error) } // Config is the structure representing the config of a Loader type Config struct { // Name is the name of the loader Name string // Client is the consul KV client Client *api.Client // StopOnFailure tells wether a load failure(after the retries) leads to closing the config and all registered closers StopOnFailure bool // Keys is the list of keys to fetch Keys []Key // Timeout is the timeout duration when fetching a key Timeout time.Duration // Prefix is a prefix to prepend keys when adding into the konfig.Store Prefix string // Replacer is a Replacer for the key before adding to the konfig.Store Replacer nstrings.Replacer // Watch tells if there should be a watcher with the loader Watch bool // Rater is the rater to pass to the poll watcher Rater kwpoll.Rater // MaxRetry is the maximum number of times we can retry to load if it fails MaxRetry int // RetryDelay is the time between each retry when a load fails RetryDelay time.Duration // Debug sets debug mode on the consulloader Debug bool // Logger is used across this package to produce logs Logger nlogger.Provider // StrictMode will raise error if key was not found // In false state, konfig will try to reload desired key(s) // up until they are not found StrictMode bool kvClient ConsulKV } // Loader is the structure of a loader type Loader struct { *kwpoll.PollWatcher cfg *Config } // New returns a new loader with the given config func New(cfg *Config) *Loader { if cfg.Timeout == 0 { cfg.Timeout = defaultTimeout } if cfg.Client == nil { panic(errors.New("no consul client was provided")) } if cfg.Logger == nil { cfg.Logger = defaultLogger() } if cfg.Name == "" { cfg.Name = defaultName } if cfg.kvClient == nil { cfg.kvClient = cfg.Client.KV() } var l = &Loader{ cfg: cfg, } if cfg.Watch { var v = konfig.Values{} // we don't want to kill the process if there is an error // in the config if err := l.Load(v); err != nil { cfg.Logger.Get().Error(fmt.Sprintf("Can't read provided config: %v", err)) } l.PollWatcher = kwpoll.New(&kwpoll.Config{ Loader: l, Rater: cfg.Rater, InitValue: v, Diff: true, Debug: cfg.Debug, }) } return l } // Name returns the name of the loader func (l *Loader) Name() string { return l.cfg.Name } // Load implements konfig.Loader, // it loads environment variables into the konfig.Store // based on config passed to the loader func (l *Loader) Load(s konfig.Values) error { for _, k := range l.cfg.Keys { kp, _, err := l.keyValue(k.Key) if err != nil { return err } if kp == nil && l.cfg.StrictMode { return fmt.Errorf("provided key \"%v\" was not found", k.Key) } else if kp == nil { l.cfg.Logger.Get().Warn(fmt.Sprintf("provided key \"%v\" was not found", k.Key)) return nil } var configKey = l.cfg.Prefix + string(kp.Key) if l.cfg.Replacer != nil { configKey = l.cfg.Replacer.Replace(configKey) } // if the key has a parser, we parse the key value using the provided Parser // else we just convert the value to a string if k.Parser != nil { if err := k.Parser.Parse(bytes.NewReader(kp.Value), s); err != nil { return err } } else { s.Set(configKey, string(kp.Value)) } } return nil } // MaxRetry is the maximum number of time to retry when a load fails func (l *Loader) MaxRetry() int { return l.cfg.MaxRetry } // RetryDelay is the delay between each retry func (l *Loader) RetryDelay() time.Duration { return l.cfg.RetryDelay } // StopOnFailure returns wether a load failure should stop the config and the registered closers func (l *Loader) StopOnFailure() bool { return l.cfg.StopOnFailure } // keyValue is a quick helper to load KVPair from // the consul server func (l *Loader) keyValue(k string) (pair *api.KVPair, qm *api.QueryMeta, err error) { return l.cfg.kvClient.Get(k, nil) } func defaultLogger() nlogger.Provider { return nlogger.NewProvider(nlogger.New(os.Stdout, "CONSULLOADER | ")) }
multitudes/Python_am_Freitag
files/screenshots/edx python screenshots/src6/weeks/1/overflow.py
# Integer overflow from time import sleep # Iteratively double i i = 1 while True: print(i) i *= 2 sleep(1)
specter01wj/LAB-Udemy
Backend/JAVA/Data Structure and Algorithms Analysis - Job Interview/DataStructureAndAlgorithms-master/src/com/graph/BFSGraph.java
package com.graph; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class BFSGraph { int size; adjList[] array; public BFSGraph(int size) { this.size=size; array= new adjList[ this.size]; for(int i=0;i<size;i++){ array[i]=new adjList(); array[i].head=null; } } public void add(int src, int dest){ Node n= new Node(dest, null); n.next= array[src].head; array[src].head=n; } public void BFSExplore( int StartVertex){ Boolean[] visited= new Boolean[size]; for(int i=0;i<size;i++) visited[i]=false; Queue<Integer> q= new LinkedList<Integer>(); q.add(StartVertex); while( !q.isEmpty()){ int n= q.poll(); System.out.println("Visted node: "+ n); visited[n]=true; Node head= array[n].head; while(head!=null){ if(visited[head.value]==false){ q.add(head.value); visited[head.value]=true; }else{ head=head.next; } } } } }
gisonyeung/myblog
server/app/backstage/js/blog.js
<filename>server/app/backstage/js/blog.js $(function() { var baseurl = 'http://' + window.location.host; var gb = GlobalModule(); gb.modal.tip.init(); gb.modal.loading.init(); loadBlogsByPage(); fetchAllPage(); /* 点击页码,换页 */ $('#paging1').on('click', '.jump-page', function() { var page = $(this).attr('data-target') || $(this).text(); // 请求内容 loadBlogsByPage(page); // 重新渲染页码 gb.pagination.reload('#paging1', page); }); /* 删除 */ var blogId = ''; var parentTr = {}; var deleteConfirm = gb.modal.confirm.init(function () { if ( !confirm('确定删除?删除后不可恢复') ) { return false; } $.ajax({ url: '/admin/deleteBlog', method: 'POST', data: { id: blogId, }, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { $(parentTr).remove(); } else { gb.modal.tip.show(data.reason, 'error'); }; }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); } }); }); $('#tbody').on('click', '.delete', function() { blogId = $(this).attr('data-target'); parentTr = $(this).parent().parent(); gb.modal.confirm.show(deleteConfirm, '是否确认删除该行博及其相应的评论?'); }); /* 获取页码 */ function fetchAllPage() { $.ajax({ url: '/admin/blogPage', method: 'POST', beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { gb.pagination.init('#paging1', 1, data.page); } else { gb.modal.tip.show(data.reason, 'error'); }; }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); } }); }; /* 获取指定页码的博客 */ function loadBlogsByPage(page) { var blog_tr_rpl = $('#blog_tr_rpl').html().trim(); var norecord_rpl = $('#norecord_rpl').html().trim(); page = page || 1; $.ajax({ url: '/admin/blogByPage', method: 'POST', data: { page: page, }, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { var _html = ''; $.each(data.blogs, function(index, blog) { var _tr = blog_tr_rpl .replace(/{{blogId}}/g, blog.blogId) .replace(/{{time_createAt}}/g, gb.dateFormat(blog.time.createAt, 'YYYY-MM-DD hh:mm:ss')) .replace(/{{time_updateAt}}/g, gb.dateFormat(blog.time.updateAt, 'YYYY-MM-DD hh:mm:ss')) .replace(/{{category}}/g, blog.category) .replace(/{{tags}}/g, blog.tags) .replace(/{{title}}/g, blog.title) .replace(/{{numbers_view}}/g, blog.numbers.view) .replace(/{{numbers_comment}}/g, blog.numbers.comment) .replace(/{{numbers_like}}/g, blog.numbers.like) .replace(/{{status}}/g, blog.isShow ? '公开' : '私密') .replace(/{{url}}/g, '/article/' + blog.blogId) .replace(/{{status_btn}}/g, blog.isShow ? '设为私密' : '设为公开') .replace(/{{_id}}/g, blog._id); _html += _tr; }); _html = _html ? _html : norecord_rpl; $('#tbody').empty(); $('#tbody').append($(_html)); _html = null; } else { gb.modal.tip.show(data.reason, 'error'); }; }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); }; /* 切换面板 */ $('.panel-btn').on('click', '.toggle-btn', function() { var selector = $(this).attr('data-target'); $(this).siblings('.toggle-btn').removeClass('active'); $(this).addClass('active'); $(selector).siblings('.panel').removeClass('open'); $(selector).addClass('open'); }); /* 点击修改,获取博文详情并切换面板 */ $('#tbody').on('click', '.edit', function() { var id = $(this).attr('data-target'); $.ajax({ url: '/admin/blogDetail', method: 'POST', data: { id: id, }, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if(data.result == "success") { console.log(data.blog); $('#edit-title').val(data.blog.title); $('#edit-category').val(data.blog.category); $('#edit-summation').val(data.blog.summary); $('#edit-tags').val(data.blog.tags); $('#edit-content').val(data.blog.markdown); resizeContentHeight('#edit-content'); Preview2.window.writeHTML('Preview2', data.blog.content); $('#edit-submit').attr('data-target', data.blog._id); var other = $('.edit-value'); other[0].innerText = data.blog.blogId; other[1].innerText = data.blog.numbers.view + '/' + data.blog.numbers.comment; other[2].innerText = data.blog.isShow ? '公开' : '私密'; other[3].innerText = dateFormat(data.blog.time.createAt, 'YYYY-MM-DD hh:mm:ss'); other[4].innerText = dateFormat(data.blog.time.updateAt, 'YYYY-MM-DD hh:mm:ss'); } else { gb.modal.tip.show("获取博文内容失败,原因: " + data.reason + "。\n请重试", 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); var btn = $($('.toggle-btn')[2]); btn.siblings('.toggle-btn').removeClass('active'); btn.addClass('active'); $('.panel').removeClass('open'); $('#panel3').addClass('open'); }); /* 修改博文提交 */ var edit_formData = {}; var editConfirm = gb.modal.confirm.init(function() { gb.modal.loading.show('正在提交中…'); $.ajax({ url: '/admin/editBlog', method: 'POST', data: edit_formData, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if(data.result == "success") { gb.modal.tip.show('修改成功', 'success'); setTimeout(function() { window.open( baseurl + data.url); }, 2000); } else { gb.modal.tip.show("修改失败,原因: " + data.reason + "。\n请重试", 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); }); $('#edit-submit').on('click', function(e) { var id = $(this).attr('data-target'); edit_formData = { id: id, title: $('#edit-title').val() || '', category: $('#edit-category').val() || '', summary: $('#edit-summation').val() || '', tags: $('#edit-tags').val() || '', content: converter.makeHtml($('#edit-content').val()) || '', markdown: $('#edit-content').val() || '', }; if ( !/\S/.test(edit_formData.id) ) { gb.modal.tip.show('请先选择要修改的博文', 'error'); return false; } else if ( !/\S/.test(edit_formData.title) ) { gb.modal.tip.show('博文标题不能为空', 'error'); return false; } else if ( !/\S/.test(edit_formData.category) ) { gb.modal.tip.show('博文分类不能为空', 'error'); return false; } else if ( !/\S/.test(edit_formData.summation) ) { gb.modal.tip.show('博文摘要不能为空', 'error'); return false; } else if ( !/\S/.test(edit_formData.markdown) ) { gb.modal.tip.show('博文内容不能为空', 'error'); return false; } gb.modal.confirm.show(editConfirm, '是否确认修改博文?'); // 阻断默认提交事件 e.preventDefault(); }); /* 发布博文 */ var add_formData = {}; var addConfirm = gb.modal.confirm.init(function() { gb.modal.loading.show('正在发布中…'); $.ajax({ url: '/admin/addBlog', method: 'POST', data: add_formData, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if(data.result == "success") { gb.modal.tip.show('发布成功', 'success'); // 清除localStorage setTimeout(function() { localStorage.setItem('ArticleCache', '{}'); location.reload(); window.open( baseurl + data.url ); }, 2000); } else { gb.modal.tip.show("发布失败,原因: " + data.reason + "。\n请重试", 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); }); $('#add-submit').on('click', function(e) { add_formData = { title: $('#blog-title').val() || '', category: $('#blog-category').val() || '', summary: $('#blog-summation').val() || '', tags: $('#blog-tags').val() || '', isNotice: $('#isNotice').val(), content: converter.makeHtml($('#blog-content').val()) || '', markdown: $('#blog-content').val() || '', }; if ( !/\S/.test(add_formData.title) ) { gb.modal.tip.show('博文标题不能为空', 'error'); return false; } else if ( !/\S/.test(add_formData.category) ) { gb.modal.tip.show('博文分类不能为空', 'error'); return false; } else if ( !/\S/.test(add_formData.summation) ) { gb.modal.tip.show('博文摘要不能为空', 'error'); return false; } else if ( !/\S/.test(add_formData.markdown) ) { gb.modal.tip.show('博文内容不能为空', 'error'); return false; } gb.modal.confirm.show(addConfirm, '是否确认发布博文?'); // 阻断默认提交事件 e.preventDefault(); }); /* 更新评论数 */ $('#tbody').on('click', '.update', function() { var id = $(this).attr('data-target'); var that = $(this).parent().parent(); $.ajax({ url: '/admin/updateblogComment', method: 'POST', data: { id: id, }, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { that.find('.numbers-comment').text(data.count); } else { gb.modal.tip.show('更新失败,原因:' + data.reason, 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); }); /* 修改状态 */ $('#tbody').on('click', '.status', function() { var id = $(this).attr('data-target'); var that = $(this).parent().parent(); $.ajax({ url: '/admin/changeBlogStatus', method: 'POST', data: { id: id, }, beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { that.find('.status').text( data.show ? '设为私密' : '设为公开' ); data.show = data.show ? '公开' : '私密'; that.find('.status-value').text(data.show); } else { gb.modal.tip.show('更新失败,原因:' + data.reason, 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); }); /* 显隐面板 */ $('.switch').on('click', function() { var panel = $(this).parent().find('.switch-panel'); $(panel).slideToggle(200); }); var converter = new showdown.Converter({ tasklists: true, tables: true, }); // var Preview = $('#Preview'); /* 输入内容,同步更新 */ $('#blog-content').on('keyup', function() { var value = $(this).val(); Preview.window.writeHTML('Preview', converter.makeHtml(value)); // 存草稿 saveDraft_repeat(); // 适应textarea高度 resizeContentHeight('#blog-content'); }); $('#edit-content').on('keyup', function() { var value = $(this).val(); Preview2.window.writeHTML('Preview2', converter.makeHtml(value)); // 适应textarea高度 resizeContentHeight('#edit-content'); }); function resizeContentHeight(selector) { var content = $(selector).val(); $('#calHeight').text(content); var height = $('#calHeight').height(); $(selector).css('min-height', (height + 250) + 'px' ); }; /* 获取图片url */ $('.upload-photo').on('click', function() { var editor = $(this).attr('data-target'); var fileId = $(this).attr('data-file'); $.ajaxFileUpload({ url: baseurl + '/admin/uploadPhoto', //用于文件上传的服务器端请求地址 type: 'POST', secureuri: false, //是否需要安全协议,一般设置为false fileElementId: fileId, //文件上传域的ID dataType: 'text', //返回值类型 一般设置为json success: function (data, status) { //服务器成功响应处理函数 var json; data.replace(/({.*})/, function(match, capture) { json = capture; return capture; }); gb.modal.loading.hide(); data = gb.parseJSON(json); if(data.result == "success") { $(editor).val( $(editor).val() + '![](' + data.url + ')'); } else { gb.modal.tip.show("上传失败,原因: " + data.reason + "。\n请重试", 'error'); } }, error: function (data, status, e) { //服务器响应失败处理函数 gb.modal.loading.hide(); gb.modal.tip.show('上传失败,服务器无响应,请稍后再试。', 'error'); } }); }); /* 获取分类列表 */ (function() { $.ajax({ url: '/categories', method: 'POST', beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { var _html = ''; var _li = '<li>{{cate_name}}</li>'; $.each(data.category, function(index, item) { _html += _li.replace(/{{cate_name}}/, item.cateName); }); $('.cate-list').empty().append( $(_html) ); } else { gb.modal.tip.show('获取分类列表失败,原因:' + data.reason, 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); })(); /* 分类列表显隐 */ $('.cate-input').on('focus', function() { $(this).next().slideDown(200); }); $('.cate-input').on('blur', function() { $(this).next().slideUp(200); }); /* 点击分类列表里的分类 */ $('.cate-list').on('click', 'li', function() { var container = $(this).parent().attr('data-target'); $(container).val( $(this).text() ); }); /* 获取标签列表 */ (function() { $.ajax({ url: '/tags', method: 'POST', beforeSend: function() { gb.modal.loading.show(); }, complete: function() { gb.modal.loading.hide(); }, success: function(data) { if ( data.result == 'success' ) { var _html = ''; var _li = '<li>{{tag_name}}</li>'; $.each(data.tags, function(index, item) { _html += _li.replace(/{{tag_name}}/, item.tagName); }); $('.tag-list').empty().append( $(_html) ); } else { gb.modal.tip.show('获取标签列表失败,原因:' + data.reason, 'error'); } }, error: function() { gb.modal.tip.show('与服务器连接无响应', 'error'); }, }); })(); /* 标签列表显隐 */ $('.tag-input').on('focus', function() { $(this).next().slideDown(200); }); $('.tag-input').on('blur', function() { $(this).next().slideUp(200); }); /* 点击标签列表里的标签 */ $('.tag-list').on('click', 'li', function() { var container = $(this).parent().attr('data-target'); var oldValue = $(container).val().replace(/,*$/, ''); var newValue = $(this).text(); var reg = new RegExp(newValue); // 输入框里已经含有新标签,则不继续添加 if ( reg.test(oldValue) ) { return false; } oldValue = oldValue ? oldValue + ',' : ''; $(container).val( oldValue + newValue ); }); /* 保存草稿 */ function saveDraft() { var formData = { title: $('#blog-title').val() || '', category: $('#blog-category').val() || '', summation: $('#blog-summation').val() || '', tags: $('#blog-tags').val() || '', isNotice: $('#isNotice').val(), content: $('#blog-content').val() || '', } var formStr = JSON.stringify(formData); localStorage.setItem('ArticleCache', formStr); saveSuccessTip(); }; var timeouting = false; function saveDraft_repeat() { var formData = { title: $('#blog-title').val() || '', category: $('#blog-category').val() || '', summation: $('#blog-summation').val() || '', tags: $('#blog-tags').val() || '', isNotice: $('#isNotice').val(), content: $('#blog-content').val() || '', }; var formStr = JSON.stringify(formData); // 定时器过期了,则执行保存,并且再次开启30s定时器 if ( !timeouting ) { timeouting = true; localStorage.setItem('ArticleCache', formStr); saveSuccessTip(); setTimeout(function() { timeouting = false; saveDraft_repeat(); }, 30000); } }; /* 保存草稿成功提示 */ function saveSuccessTip() { var time = dateFormat(Date.now(), 'YYYY-MM-DD hh:mm:ss'); $('.cache-time').text(time); $('.cache-tip').addClass('show'); }; // 手动保存草稿 $('#save-draft').on('click', function() { saveDraft(); }); function dateFormat(dateString, fmt) { var _Date = new Date(dateString); var o = { "M+": _Date.getMonth() + 1, //月份 "D+": _Date.getDate(), //日 "h+": _Date.getHours(), //小时 "m+": _Date.getMinutes(), //分 "s+": _Date.getSeconds(), //秒 "q+": Math.floor((_Date.getMonth() + 3) / 3), //季度 "S": _Date.getMilliseconds() //毫秒 }; if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (_Date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } /* 加载草稿的内容 */ function loadDraft() { var formStr = localStorage.getItem('ArticleCache'); if ( formStr ) { var formData = JSON.parse(formStr); $('#blog-title').val(formData.title); $('#blog-category').val(formData.category); $('#blog-summation').val(formData.summation); $('#blog-tags').val(formData.tags); $('#blog-content').val(formData.content); if ( formData.isNotice == 'false' ) { $('#isNotice option:eq(1)').prop('selected', 'selected'); } else { $('#isNotice option:eq(0)').prop('selected', 'selected'); } Preview.window.writeHTML('Preview', converter.makeHtml(formData.content)); resizeContentHeight('#blog-content'); } }; setTimeout(loadDraft, 2000); });
bugnolwy/bugnolwy-sys
bugnolwy-sys/sys-web/src/main/java/cn/bugnolwy/controller/SysMenuController.java
<filename>bugnolwy-sys/sys-web/src/main/java/cn/bugnolwy/controller/SysMenuController.java<gh_stars>1-10 package cn.bugnolwy.controller; import cn.bugnolwy.model.SysMenu; import cn.bugnolwy.service.SysMenuService; import cn.bugnolwy.vo.JsonResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * 菜单管理 * HandlerAdapter类 * * @author BugnoLwy * @email <EMAIL> * @gitee https://gitee.com/bugnolwy/bugnolwy-sys * @gitHub https://github.com/bugnolwy/bugnolwy-sys * @since 2020-9 */ @Api(tags = "菜单管理") @RestController @RequestMapping("/menu") public class SysMenuController { @Autowired private SysMenuService sysMenuService; @ApiOperation(value = "上级菜单呈现") @RequestMapping("/doFindZTreeMenuNodes") public JsonResult dofindztreemenunodes() { return JsonResult.ok(sysMenuService.findztreemenunodes()); } @ApiOperation(value = "查询菜单") @GetMapping("/doFindObjects") public JsonResult findObjects() { return JsonResult.ok(sysMenuService.findSysMenus()); } @ApiOperation(value = "删除菜单", notes = "根据接收的id参数进行删除菜单") @ApiImplicitParam(name = "id", value = "菜单id", dataType = "Integer", dataTypeClass = SysMenu.class) @DeleteMapping("/doDeleteObjects") public JsonResult doDeleteObjects(Integer id) { if (sysMenuService.deleteObject(id)) { return JsonResult.ok("删除成功!"); } return JsonResult.error("删除失败!记录可能已经不存在..."); } @ApiOperation(value = "添加菜单", notes = "根据菜单内容保存菜单") @ApiImplicitParam(name = "sysMenu", value = "菜单", dataType = "SysMenu", dataTypeClass = SysMenu.class) @PostMapping("/doSaveObject") public JsonResult doSaveObject(SysMenu sysMenu) { if (sysMenuService.saveObject(sysMenu)) { return JsonResult.ok("保存成功!"); } return JsonResult.error("保存失败!"); } @ApiOperation(value = "更新菜单", notes = "根据菜单内容更新菜单") @ApiImplicitParam(name = "sysMenu", value = "菜单", dataType = "SysMenu", dataTypeClass = SysMenu.class) @PostMapping("/doUpdateObject") public JsonResult doUpdateObject(SysMenu sysMenu) { if (sysMenuService.updateObject(sysMenu)) { return JsonResult.ok("更新成功!"); } return JsonResult.error("更新失败!"); } }
artem-sidorenko/chagen
datasource/connectors/gitlab/internal/testclient/generators.go
<filename>datasource/connectors/gitlab/internal/testclient/generators.go<gh_stars>1-10 /* Copyright 2019 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package testclient import ( "net/http" "time" gitlab "github.com/xanzy/go-gitlab" ) func genMR( number int, title, webURL, userLogin string, mergedAt time.Time, mergeCommitSHA string, labels []string, ) *gitlab.MergeRequest { mr := &gitlab.MergeRequest{ IID: number, Title: title, Labels: labels, WebURL: webURL, MergeCommitSHA: mergeCommitSHA, } mr.Author.Username = userLogin if (mergedAt != time.Time{}) { mr.MergedAt = &mergedAt } return mr } func genTag(name string, commit *gitlab.Commit) *gitlab.Tag { return &gitlab.Tag{ Name: name, Commit: commit, } } func genCommit(sha string, commitDate time.Time) *gitlab.Commit { return &gitlab.Commit{ ID: sha, AuthoredDate: &commitDate, } } func genResponse(statusCode int) *gitlab.Response { return &gitlab.Response{ Response: &http.Response{StatusCode: statusCode}, } } func genIssue(number int, title, webURL string, closedDate time.Time, labels []string, ) *gitlab.Issue { return &gitlab.Issue{ IID: number, Title: title, WebURL: webURL, ClosedAt: &closedDate, Labels: labels, } }
garganti/info2_oop_unibg
esercizicompleti/21/orario/ProvaOrari.java
package orario; import java.util.Collections; import java.util.Vector; public class ProvaOrari { public static void main(String[] args) { Ora now = new OraHM(10, 30); System.out.println(now); Ora mezzanotte = new OraHM(0, 0); System.out.println(mezzanotte); // Ora now2 = new OraSec((10*60 + 40) *60); System.out.println(now2); // Vector<Ora> ore = new Vector<>(); ore.add(now); ore.add(mezzanotte); ore.add(now2); System.out.println(ore); Collections.sort(ore); System.out.println(ore); } }
xiankgx/U-2-Net
evaluate.py
<reponame>xiankgx/U-2-Net import argparse import glob import os import matplotlib.pyplot as plt import numpy as np from skimage import io, transform from sklearn.metrics import fbeta_score, mean_absolute_error from tqdm import tqdm def iou(gt, pred, thresh=0.5): if thresh: gt = (gt >= thresh).astype(np.float32) pred = (pred >= thresh).astype(np.float32) intersection = (gt * pred).sum() union = gt.sum() + pred.sum() - intersection if union == 0: _iou = 1.0 else: _iou = intersection/union assert 0 <= _iou <= 1.0 return _iou def f_measure(gt, pred, beta_square=0.3): return fbeta_score(y_true=gt, y_pred=pred, beta=np.sqrt(beta_square), average="micro") def evaluate(gt_dir, pred_dir): gt_files = glob.glob(gt_dir + "/**/*.png", recursive=True) pred_files = list(map(lambda p: p.replace( gt_dir, pred_dir), gt_files)) # pred_files = list(map(lambda p: os.path.splitext(p)[0] + ".jpg", pred_files)) for f in pred_files: if not os.path.exists(f): raise FileNotFoundError(f"File not found: {f}") ious = [] f_measures = [] maes = [] for gt_file, pred_file in tqdm(zip(gt_files, pred_files), desc=f"Evaluating..."): gt = io.imread(gt_file) pred = io.imread(pred_file) if gt.dtype == np.uint8: gt = gt/255.0 if pred.dtype == np.uint8: pred = pred/255.0 if gt.ndim == 3: gt = gt[..., 0] # RGBA prediction if pred.ndim == 3: pred = pred[..., -1] # Make sure equal dimensions if pred.shape[:2] != gt.shape[:2]: pred = transform.resize(pred, gt.shape[:2]) ious.append(iou(gt=gt, pred=pred)) f_measures.append(f_measure(gt=(gt >= 0.5).astype(np.float32), pred=(pred >= 0.5).astype(np.float32))) maes.append(mean_absolute_error(y_true=gt, y_pred=pred)) return { "gt_dir": gt_dir, "pred_dir": pred_dir, "iou": np.array(ious).mean(), "f_measure": np.array(f_measures).mean(), "mae": np.array(maes).mean() } def parse_args(): parser = argparse.ArgumentParser( description="Salient object detection evaluation script.") parser.add_argument("--gt_dir", type=str, help="Ground truth root directory.") parser.add_argument("--pred_dir", type=str, help="Prediction root directory.") args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() metrics = evaluate(args.gt_dir, args.pred_dir) print(metrics) output_file = os.path.dirname(args.pred_dir) + ".txt" # print(output_file) with open(output_file, "w") as f: f.write(str(metrics))
BAHome/BAKit
Example/BAKit/Class/Define/BADefine_APPVersion.h
<reponame>BAHome/BAKit<gh_stars>10-100 // // BADefine_APPVersion.h // BAKit // // Created by 孙博岩 on 2019/1/31. // Copyright © 2019 boai. All rights reserved. // #ifndef BADefine_APPVersion_h #define BADefine_APPVersion_h #define BADefine_APPVersion_VersionString [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"] #define BADefine_APPVersion_BuildString [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey] #define BADefine_APPVersion_VersionBuildString [NSString stringWithFormat:@"%@-%@", BADefine_APPVersion_VersionString, BADefine_APPVersion_BuildString] //#define BADefine_APPVersion_BranchStr // //#define BADefine_APPVersion_UserEvnStr // //#define BADefine_APPVersion_FullStr #endif /* BADefine_APPVersion_h */
anilkumarkodali/lti-ready-virtual-classroom-with-amazon-chime-sdk
lti-components/web/amplify/backend/function/chimeEventApiAuthorizer/src/utils/Principal.js
const rasha = require(`rasha`); const got = require(`got`); const jwt = require(`jsonwebtoken`); const Principal = class { __token; get token() { return this.__token; } __context = {}; get context() { return this.__context; } __source = {}; get source() { return this.__source; } get title() { return this.__context.title || this.__context.label || ``; } __user = {}; get user() { return this.__user; } get authorizerContext() { const exports = { userID: this.__user.id, userName: this.__user.name, userEmail: this.__user.email, contextTitle: this.title, contextExternalId: this.__context.externalId, platformId: this.__source.id, ...(this.__token.config || {}) }; (this.__user.roles || []).forEach((role, id) => { exports[`userRole${id + 1}`] = role; }); return exports; } isAdministrator = () => { return this.hasRole(`Administrator`); } isModerator = (implyFromHigherPrivilege = false) => { return this.hasRole(`Moderator`) || (implyFromHigherPrivilege && this.isAdministrator(true)); } isUser = (implyFromHigherPrivilege = false) => { return this.hasRole(`User`) || (implyFromHigherPrivilege && this.isModerator(true)); } isGuest = (implyFromHigherPrivilege = false) => { return this.hasRole(`Guest`) || (implyFromHigherPrivilege && this.isUser(true)); } hasRole = (roleName) => { return (this.__user.roles || []).includes(roleName); } constructor(token) { this.__token = token; this.__user = Object.assign({ id: ``, name: ``, email: ``, roles: [] }, token[`user`] || {}); this.__context = Object.assign({ id: ``, externalId: ``, title: `` }, token[`context`] || {}); this.__source = Object.assign({ return_url: `` }, token[`source`] || {}); } static verify = async (publicKeySetUrl, idToken) => { return got.get(publicKeySetUrl, { timeout: 5000, retry: 2 }).json().then((response) => { return rasha.export({ jwk: response.keys[0] }).then((key) => { try { const decodedToken = jwt.verify(idToken, key, { algorithms: [`RS256`] }); return new Principal(decodedToken); } catch (err) { throw new Error(`Token could not be verified. (${err.name}: ${err.message})`); } }) }).catch((err) => { throw new Error(`Could not initiate token verification. (${err.name}: ${err.message})`); }); } }; module.exports = Principal;
MoritzGruber/mercurius
test/options.js
'use strict' const proxyquire = require('proxyquire') const sinon = require('sinon') const { test } = require('tap') const Fastify = require('fastify') const schema = ` type User { name: String! password: String! } type Query { read: [User] } ` const resolvers = { Query: { read: async (_, obj) => { return [ { name: 'foo', password: '<PASSWORD>' } ] } } } test('call compileQuery with correct options if compilerOptions specified', async t => { t.plan(1) const app = Fastify() t.teardown(() => app.close()) const compileQueryStub = sinon.stub() const GQL = proxyquire('../index', { 'graphql-jit': { compileQuery: compileQueryStub } }) await app.register(GQL, { schema, resolvers, jit: 1, compilerOptions: { customJSONSerializer: true } }) const queryStub = sinon.stub() compileQueryStub.returns({ query: queryStub }) queryStub.resolves({ errors: [] }) const query = `{ read { name password } }` // warm up the jit counter await app.inject({ method: 'POST', headers: { 'content-type': 'application/json', super: 'false' }, url: '/graphql', body: JSON.stringify({ query }) }) await app.inject({ method: 'POST', headers: { 'content-type': 'application/json', super: 'false' }, url: '/graphql', body: JSON.stringify({ query }) }) t.ok(compileQueryStub.calledOnceWith(sinon.match.any, sinon.match.any, sinon.match.any, { customJSONSerializer: true })) })
logix5/Blockyduino-para-MRTDuino
blocks/RotaryEncoder.js
<gh_stars>1-10 /** * @license * Visual Blocks Editor * * Copyright 2012 Google Inc. * https://developers.google.com/blockly/ * * 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. */ /** * @fileoverview Colour blocks for Blockly. * @author <EMAIL> (<NAME>) */ /*************************************************************** * * This module was created by <NAME>. <EMAIL> * ****************************************************************/ 'use strict'; goog.provide('Blockly.Blocks.RotaryEncoder'); goog.require('Blockly.Blocks'); Blockly.Blocks['Init_RotaryEncoderInterrupt'] = { helpUrl: '', init: function() { this.setColour(220); this.appendDummyInput() .appendField(new Blockly.FieldImage("images/rotaryencoder.png",44,38)) .appendField(Blockly.Msg.RotaryEncoderInit) .appendField(new Blockly.FieldDropdown([['1','1'],['2','2'],['3','3'],['4','4']]), "RE_NUMBER") this.appendDummyInput() .appendField(Blockly.Msg.RE_Interrupt) .appendField(Blockly.Msg.RE_PINDT) .appendField(new Blockly.FieldDropdown(profile.default.interrupt), "PINDT"); this.appendDummyInput() .appendField(Blockly.Msg.RE_PINCLK) .appendField(new Blockly.FieldDropdown(profile.default.interrupt), "PINCLK"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip('Init the libraries to manage rotary encoder using interrupts. More precision'); } }; Blockly.Blocks['Init_RotaryEncoder'] = { helpUrl: '', init: function() { this.setColour(220); this.appendDummyInput() .appendField(new Blockly.FieldImage("images/rotaryencoder.png",44,38)) .appendField(Blockly.Msg.RotaryEncoderInit) .appendField(new Blockly.FieldDropdown([['1','1'],['2','2'],['3','3'],['4','4']]), "RE_NUMBER") this.appendDummyInput() .appendField(Blockly.Msg.RE_withoutInterrupt) .appendField(Blockly.Msg.RE_PINDT) .appendField(new Blockly.FieldDropdown(profile.default.digital_input), "PINDT"); this.appendDummyInput() .appendField(Blockly.Msg.RE_PINCLK) .appendField(new Blockly.FieldDropdown(profile.default.digital_input), "PINCLK"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip('Init the libraries to manage rotary encoder without interrupts. Less precision'); } }; Blockly.Blocks['RotaryEncoder_Write'] = { helpUrl: '', init: function() { this.setColour(220); this.appendDummyInput() .appendField(new Blockly.FieldImage("images/rotaryencoder.png",44,38)) .appendField(Blockly.Msg.RotaryEncoderNumber) .appendField(new Blockly.FieldDropdown([['1','1'],['2','2'],['3','3'],['4','4']]), "RE_NUMBER") this.appendDummyInput() .appendField(Blockly.Msg.RE_WRITE); this.appendValueInput("Writecounter") .setCheck("Number"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip("Write the internal counter of the rotary Encoder"); } }; Blockly.Blocks['RotaryEncoder_Read'] = { helpUrl: '', init: function() { this.setColour(220); this.appendDummyInput() .appendField(new Blockly.FieldImage("images/rotaryencoder.png",44,38)) .appendField(Blockly.Msg.RotaryEncoderNumber) .appendField(new Blockly.FieldDropdown([['1','1'],['2','2'],['3','3'],['4','4']]), "RE_NUMBER") this.appendDummyInput() .appendField(Blockly.Msg.RE_READ) this.setOutput(true, 'Number'); this.setInputsInline(true); this.setTooltip('Read the internal counter of the rotary Encoder'); } }; Blockly.Blocks['rotaryencoder_button_sensor'] = { helpUrl: '', init: function() { this.setColour(220); this.appendDummyInput() .appendField(new Blockly.FieldImage("images/rotaryencoder.png",44,38)) .appendField(Blockly.Msg.RotaryEncoderNumber) .appendField(new Blockly.FieldDropdown([['1','1'],['2','2'],['3','3'],['4','4']]), "RE_NUMBER") this.appendDummyInput() .appendField(Blockly.Msg.RE_Button) .appendField(Blockly.Msg.PIN) .appendField(new Blockly.FieldDropdown(profile.default.digital_input), "PIN_RE_BUTTON"); this.appendDummyInput() .appendField(Blockly.Msg.RE_Pressed) this.setOutput(true, 'Boolean'); this.setInputsInline(true); this.setTooltip(''); } };
ZhenwenHe/gtl-java
common/src/main/java/cn/edu/cug/cs/gtl/index/rtree/RTreeVariant.java
<reponame>ZhenwenHe/gtl-java package cn.edu.cug.cs.gtl.index.rtree; /** * Created by ZhenwenHe on 2016/12/22. */ public enum RTreeVariant { RV_LINEAR, RV_QUADRATIC, RV_RSTAR }
googleapis/googleapis-gen
grafeas/v1/grafeas-v1-py/grafeas/grafeas_v1/types/package.py
<reponame>googleapis/googleapis-gen # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 proto # type: ignore __protobuf__ = proto.module( package='grafeas.v1', manifest={ 'Architecture', 'Distribution', 'Location', 'PackageNote', 'PackageOccurrence', 'Version', }, ) class Architecture(proto.Enum): r"""Instruction set architectures supported by various package managers. """ ARCHITECTURE_UNSPECIFIED = 0 X86 = 1 X64 = 2 class Distribution(proto.Message): r"""This represents a particular channel of distribution for a given package. E.g., Debian's jessie-backports dpkg mirror. Attributes: cpe_uri (str): Required. The cpe_uri in `CPE format <https://cpe.mitre.org/specification/>`__ denoting the package manager version distributing a package. architecture (grafeas.grafeas_v1.types.Architecture): The CPU architecture for which packages in this distribution channel were built. latest_version (grafeas.grafeas_v1.types.Version): The latest available version of this package in this distribution channel. maintainer (str): A freeform string denoting the maintainer of this package. url (str): The distribution channel-specific homepage for this package. description (str): The distribution channel-specific description of this package. """ cpe_uri = proto.Field( proto.STRING, number=1, ) architecture = proto.Field( proto.ENUM, number=2, enum='Architecture', ) latest_version = proto.Field( proto.MESSAGE, number=3, message='Version', ) maintainer = proto.Field( proto.STRING, number=4, ) url = proto.Field( proto.STRING, number=5, ) description = proto.Field( proto.STRING, number=6, ) class Location(proto.Message): r"""An occurrence of a particular package installation found within a system's filesystem. E.g., glibc was found in ``/var/lib/dpkg/status``. Attributes: cpe_uri (str): Required. The CPE URI in `CPE format <https://cpe.mitre.org/specification/>`__ denoting the package manager version distributing a package. version (grafeas.grafeas_v1.types.Version): The version installed at this location. path (str): The path from which we gathered that this package/version is installed. """ cpe_uri = proto.Field( proto.STRING, number=1, ) version = proto.Field( proto.MESSAGE, number=2, message='Version', ) path = proto.Field( proto.STRING, number=3, ) class PackageNote(proto.Message): r"""This represents a particular package that is distributed over various channels. E.g., glibc (aka libc6) is distributed by many, at various versions. Attributes: name (str): Required. Immutable. The name of the package. distribution (Sequence[grafeas.grafeas_v1.types.Distribution]): The various channels by which a package is distributed. """ name = proto.Field( proto.STRING, number=1, ) distribution = proto.RepeatedField( proto.MESSAGE, number=10, message='Distribution', ) class PackageOccurrence(proto.Message): r"""Details on how a particular software package was installed on a system. Attributes: name (str): Output only. The name of the installed package. location (Sequence[grafeas.grafeas_v1.types.Location]): Required. All of the places within the filesystem versions of this package have been found. """ name = proto.Field( proto.STRING, number=1, ) location = proto.RepeatedField( proto.MESSAGE, number=2, message='Location', ) class Version(proto.Message): r"""Version contains structured information about the version of a package. Attributes: epoch (int): Used to correct mistakes in the version numbering scheme. name (str): Required only when version kind is NORMAL. The main part of the version name. revision (str): The iteration of the package build from the above version. kind (grafeas.grafeas_v1.types.Version.VersionKind): Required. Distinguishes between sentinel MIN/MAX versions and normal versions. full_name (str): Human readable version string. This string is of the form <epoch>:<name>-<revision> and is only set when kind is NORMAL. """ class VersionKind(proto.Enum): r"""Whether this is an ordinary package version or a sentinel MIN/MAX version. """ VERSION_KIND_UNSPECIFIED = 0 NORMAL = 1 MINIMUM = 2 MAXIMUM = 3 epoch = proto.Field( proto.INT32, number=1, ) name = proto.Field( proto.STRING, number=2, ) revision = proto.Field( proto.STRING, number=3, ) kind = proto.Field( proto.ENUM, number=4, enum=VersionKind, ) full_name = proto.Field( proto.STRING, number=5, ) __all__ = tuple(sorted(__protobuf__.manifest))
hiroaki-ishikawa/freertps
systems/samv71_xplained_ultra-metal/pin.h
#ifndef PIN_H #define PIN_H #include <stdbool.h> #include <stdint.h> #include "component/component_pio.h" // ported from the STM32 stuff... not yet all implemented void pin_set_mux(Pio *pio, const unsigned pin_idx, const unsigned function_idx); void pin_enable_pullup(Pio *pio, const unsigned pin_idx, const bool enable_pullup); void pin_set_output(Pio *pio, const unsigned pin_idx, const bool output_state); void pin_set_output_state(Pio *pio, const unsigned pin_idx, const bool output_state); #define PERIPH_A 0 #define PERIPH_B 1 #define PERIPH_C 2 #define PERIPH_D 3 #if 0 #define PIN_OUTPUT_TYPE_PUSH_PULL 0 #define PIN_OUTPUT_TYPE_OPEN_DRAIN 1 void pin_set_output_type(GPIO_TypeDef *gpio, const uint8_t pin_idx, const uint8_t output_type); void pin_set_analog(GPIO_TypeDef *gpio, const uint8_t pin_idx); void pin_set_output(GPIO_TypeDef *gpio, const uint8_t pin_idx, const uint8_t initial_state); void pin_set_output_speed(GPIO_TypeDef *gpio, const uint_fast8_t pin_idx, const uint_fast8_t speed); void pin_set_output_state(GPIO_TypeDef *gpio, const uint8_t pin_idx, const uint8_t state); void pin_toggle_state(GPIO_TypeDef *gpio, const uint8_t pin_idx); void pin_set_input(GPIO_TypeDef *gpio, const uint8_t pin_idx, const bool enable_pullup); static inline void pin_set_output_high(GPIO_TypeDef *gpio, const uint8_t pin_idx) { gpio->BSRR = 1 << pin_idx; } static inline void pin_set_output_low(GPIO_TypeDef *gpio, const uint8_t pin_idx) { gpio->BSRR = (1 << pin_idx) << 16; } static inline bool pin_get_state(GPIO_TypeDef *gpio, const uint_fast8_t pin_idx) { return (gpio->IDR & (1 << pin_idx)) ? true : false; } #endif #endif
lonesafe/roubSite
RoubSiteSmarty4j/src/main/java/com/roubsite/smarty4j/Smarty4j.java
package com.roubsite.smarty4j; //import jargs.gnu.CmdLineParser; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; /** * Smarty4j Command Tools * * @version 1.5.0, 2011/01/01 * @author <NAME> * @since Common 1.0 */ public class Smarty4j { public static void main(String[] args) { // CmdLineParser parser = new CmdLineParser(); // CmdLineParser.Option leftOpt = parser.addStringOption("left"); // CmdLineParser.Option rightOpt = parser.addStringOption("right"); // CmdLineParser.Option charsetOpt = parser.addStringOption("charset"); // CmdLineParser.Option outputOpt = parser.addStringOption('o', "output"); // // Reader in = null; // Writer out = null; // // try { // parser.parse(args); // // String[] fileArgs = parser.getRemainingArgs(); // // Engine engine = new Engine(); // // String left = (String) parser.getOptionValue(leftOpt); // if (left != null) { // engine.setLeftDelimiter(left); // } // // String right = (String) parser.getOptionValue(rightOpt); // if (right != null) { // engine.setRightDelimiter(right); // } // // String charset = (String) parser.getOptionValue(charsetOpt); // if (charset == null) { // charset = System.getProperty("file.encoding"); // if (charset == null) { // charset = "UTF-8"; // } // } // engine.setEncoding(charset); // // String output = (String) parser.getOptionValue(outputOpt); // if (output == null) { // out = new OutputStreamWriter(System.out, charset); // } else { // out = new OutputStreamWriter(new FileOutputStream(output), charset); // } // // try { // if (fileArgs.length == 0) { // engine.setTemplatePath(System.getProperty("user.dir")); // in = new InputStreamReader(System.in, charset); // } else { // File file = new File(fileArgs[0]); // engine.setTemplatePath(file.getParentFile().getAbsolutePath()); // in = new InputStreamReader(new FileInputStream(file), charset); // } // } catch (Exception e) { // throw new NullPointerException(); // } // // new Template(engine, null, in, true).merge(new Context(), out); // } catch (NullPointerException e) { // e.printStackTrace(); // System.out.println("java -jar [JAR_FILE] filename [OPTIONS]"); // System.out.println("OPTIONS:"); // System.out.println("--left"); // System.out.println("--right"); // System.out.println("--charset"); // System.out.println("--output -o"); // System.exit(1); // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (in != null) { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // if (out != null) { // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } } }
Bedework/exchange-ws-client
src/test/java/com/microsoft/exchange/ExchangeAutodiscoverServiceTest.java
/** * See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Board of Regents of the University of Wisconsin System * 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 com.microsoft.exchange; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import com.microsoft.exchange.autodiscover.CompositeAutodiscoverServiceImpl; import com.microsoft.exchange.autodiscover.ExchangeAutodiscoverService; import com.microsoft.exchange.autodiscover.PoxAutodiscoverServiceImpl; import com.microsoft.exchange.autodiscover.SoapAutodiscoverServiceImpl; /** * @author ctcudd * */ public class ExchangeAutodiscoverServiceTest { private static final String TEST_ADDRESS = "<EMAIL>"; private Log log = LogFactory.getLog(this.getClass()); @Test public void getPotentialSoapAutodiscoverEndpoints(){ SoapAutodiscoverServiceImpl soapAutodiscoverService = new SoapAutodiscoverServiceImpl(); List<String> potentials = soapAutodiscoverService.getPotentialAutodiscoverEndpoints(TEST_ADDRESS); assertNotNull(potentials); assertNotNull(potentials.get(0)); assertTrue(potentials.get(0).startsWith("https://")); log.info("SoapAutodiscoverServiceImpl returned "+potentials.size() +" potential autodiscover endpoints for "+TEST_ADDRESS); for(String p: potentials){ assertTrue(p.endsWith(soapAutodiscoverService.getServiceSuffix())); log.info(p); } } @Test public void getPotentialPoxAutodiscoverEndpoints(){ PoxAutodiscoverServiceImpl poxAutodiscoverService = new PoxAutodiscoverServiceImpl(); List<String> potentials = poxAutodiscoverService.getPotentialAutodiscoverEndpoints(TEST_ADDRESS); assertNotNull(potentials); assertNotNull(potentials.get(0)); assertTrue(potentials.get(0).startsWith("https://")); log.info("PoxAutodiscoverServiceImpl returned "+potentials.size() +" potential autodiscover endpoints for "+TEST_ADDRESS); for(String p: potentials){ assertTrue(p.endsWith(poxAutodiscoverService.getServiceSuffix())); log.info(p); } } @Test public void getPotentialAutodiscoverEndpoints(){ PoxAutodiscoverServiceImpl poxAutodiscoverService = new PoxAutodiscoverServiceImpl(); SoapAutodiscoverServiceImpl soapAutodiscoverService = new SoapAutodiscoverServiceImpl(); Collection<ExchangeAutodiscoverService> autodiscoverCollection = new ArrayList<ExchangeAutodiscoverService>(); autodiscoverCollection.add(poxAutodiscoverService); autodiscoverCollection.add(soapAutodiscoverService); CompositeAutodiscoverServiceImpl compositeAutodiscoverService = new CompositeAutodiscoverServiceImpl(); compositeAutodiscoverService.setAutodiscoverServices(autodiscoverCollection); List<String> potentials = compositeAutodiscoverService.getPotentialAutodiscoverEndpoints(TEST_ADDRESS); log.info("CompositeAutodiscoverServiceImpl returned "+potentials.size() +" potential autodiscover endpoints for "+TEST_ADDRESS); assertNotNull(potentials); assertNotNull(potentials.get(0)); assertTrue(potentials.get(0).startsWith("https://")); for(String p: potentials){ log.info(p); } } }
gautamkmr/caffe2
third_party/aten/src/ATen/Retainable.h
<gh_stars>0 #pragma once #include <atomic> namespace at { // base class for refcounted things, allows for collects of generic // refcounted objects that include tensors struct Retainable { Retainable(): refcount(1) {} void retain() { ++refcount; } void release() { if(--refcount == 0) { delete this; } } int use_count() const { return refcount.load(); } virtual ~Retainable() {} private: std::atomic<int> refcount; }; }
Programming-Systems-Lab/dyclink
dyclink/src/test/java/cc/expbase/DecompilerTest.java
package cc.expbase; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import cern.colt.Arrays; public class DecompilerTest { public void formethod() { int sum = 0; for (int i = 0; i < 10; i++) { sum += i; } System.out.println(sum); } public void whilemethod() { int sum = 0; int i = 0; while (i < 10) { sum += i; i++; } System.out.println(sum); } public static void main(String[] args) throws Exception { CommandLineParser cParser = new DefaultParser(); Options options = new Options(); options.addOption("h", false, "Help"); options.addOption("t", false, "Only construct final graphs without mining"); Option templateOption = new Option("template", "The dir of template graphs"); templateOption.setArgs(1); options.addOption(templateOption); Option testOption = new Option("test", "The dir of test graphs"); testOption.setArgs(1); options.addOption(testOption); //options.addOption("graphrepo", false, "The dir of all graph repos"); Option o = new Option("graphrepo", "The dir of all graph repos"); o.setArgs(Option.UNLIMITED_VALUES); options.addOption(o); CommandLine cLine = cParser.parse(options, args); if (cLine.hasOption("h")) { System.out.println("t: Only construct final graphs without mining"); System.out.println("template: The dir of template graphs"); System.out.println("test: The dir of test graphs"); System.out.println("graphrepo: The dir of all graph repos"); System.exit(0); } if (cLine.hasOption("t")) { System.out.println("Construction only"); } System.out.println("Template: " + cLine.hasOption("template")); System.out.println("Test: " + cLine.hasOption("test")); for (Option tmp: cLine.getOptions()) { System.out.println(tmp.getOpt()); System.out.println(tmp.getValue()); } if (cLine.hasOption("template") && cLine.hasOption("test")) { System.out.println("Graph locations from command line"); System.out.println("Templates: " + cLine.getOptionValue("template")); System.out.println("Tests: " + cLine.getOptionValue("test")); } else if (cLine.hasOption("graphrepo")) { System.out.println("Graph repos: " + Arrays.toString(cLine.getOptionValues("graphrepo"))); } } }
humeng12/HuMengApp
HMMerchant/Controllers/BaseController/BaseViewController.h
// // BaseViewController.h // HMMerchant // // Created by HRT on 16/4/18. // Copyright © 2016年 HRT. All rights reserved. // #import <UIKit/UIKit.h> @interface BaseViewController : UIViewController { NSOperationQueue * mpOperationQueue; } @property(assign,nonatomic)BOOL isNavIcon; @property CGFloat ios7height; @property BOOL geren; @property(nonatomic,strong)NSUserDefaults *userData; -(void)setTitle:(NSString*)title; -(void)addLeftButton; -(void)leftBtnClick; -(void)hiddencellline:(UITableView*)tableview; #pragma mark 判断网络 -(BOOL)connectedToNetWork; @end
ilin-in/OP
hookflash-core/core/hookflash/services/RUDPPacket.h
<gh_stars>1-10 /* Copyright (c) 2012, SMB Phone Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #pragma once #include <hookflash/services/hookflashTypes.h> #include <boost/shared_array.hpp> #include <zsLib/Log.h> #define HOOKFLASH_SERVICES_RUDP_MAX_PACKET_SIZE_WHEN_PMTU_IS_NOT_KNOWN (512) namespace hookflash { namespace services { struct RUDPPacket { typedef zsLib::BYTE BYTE; typedef zsLib::WORD WORD; typedef zsLib::DWORD DWORD; typedef zsLib::QWORD QWORD; typedef zsLib::ULONG ULONG; typedef zsLib::Log Log; enum Flags { Flag_PS_ParitySending = (1 << 7), Flag_PG_ParityGSNR = (1 << 6), Flag_XP_XORedParityToGSNFR = (1 << 5), Flag_DP_DuplicatePacket = (1 << 4), Flag_EC_ECNPacket = (1 << 3), Flag_EQ_GSNREqualsGSNFR = (1 << 2), Flag_AR_ACKRequired = (1 << 1) }; enum VectorFlags { Flag_VP_VectorParity = (1 << 7) }; enum VectorStates { VectorState_Received = (0x00 << 6), VectorState_ReceivedECNMarked = (0x01 << 6), VectorState_NotReceived = (0x03 << 6), VectorState_Reserved = (0x02 << 6), VectorState_NoMoreData = (0xFF), }; struct VectorEncoderState { VectorStates mLastState; bool mXORedParityToNow; BYTE *mVector; ULONG mVectorFilledLengthInBytes; ULONG mMaxVectorSizeInBytes; QWORD mGSNR; QWORD mGSNFR; QWORD mCurrentSequenceNumber; }; struct VectorDecoderState { const BYTE *mVector; ULONG mVectorFilledLengthInBytes; ULONG mConsumedRLE; BYTE mSpecialCaseVector[2]; }; static RUDPPacketPtr create(); RUDPPacketPtr clone(); static RUDPPacketPtr parseIfRUDP( const BYTE *packet, ULONG packetLengthInBytes ); void packetize( boost::shared_array<BYTE> &outBuffer, ULONG &outBufferLengthInBytes ) const; bool isFlagSet(Flags flag) const; bool isFlagSet(VectorFlags flag) const; void setFlag(Flags flag); void setFlag(Flags flag, bool on); void setFlag(VectorFlags flag); void setFlag(VectorFlags flag, bool on); void clearFlag(Flags flag); void clearFlag(VectorFlags flag); QWORD getSequenceNumber(QWORD hintLastSequenceNumber) const; QWORD getGSNR(QWORD hintLastGSNR) const; QWORD getGSNFR(QWORD hintLastGSNFR) const; // only can call if the Flag_EQ_GSNREqualsGSNFR is *NOT* set, otherwise an exception will be thrown void setSequenceNumber(QWORD sequenceNumber); void setGSN( QWORD gsnr, // Greatest Sequence Number Received QWORD gsnfr // Greatest Sequence Number Fully Received ); ULONG getRoomAvailableForData(ULONG maxPacketLengthInBytes) const; void vectorEncoderStart( VectorEncoderState &outVectorState, QWORD gsnr, QWORD gsnfr, bool xoredParityToGSNFR ); static void vectorEncoderStart( VectorEncoderState &outVectorState, QWORD gsnr, QWORD gsnfr, bool xoredParityToGSNFR, BYTE *vector, // if pointer specified, will encode to an external buffer ULONG vectorLengthInBytes // if external buffer used, specify the max length of the external buffer ); // will return false if there is no more room in the vector for more information static bool vectorEncoderAdd( VectorEncoderState &ioVectorState, VectorStates vectorState, bool packetParity // this only applicable if the packet was received, otherwise it will be ignored ); void vectorEncoderFinalize(VectorEncoderState &ioVectorState); static void vectorEncoderFinalize( VectorEncoderState &ioVectorState, bool &outXORVectorParityFlag, ULONG &outVectorLengthInBytes ); void vectorDecoderStart(VectorDecoderState &ioVectorState) const; static void vectorDecoderStart( VectorDecoderState &ioVectorState, const BYTE *vector, // if pointer specified, will encode to an external buffer ULONG vectorLengthInBytes, // if external buffer used, specify the max length of the external buffer QWORD gsnr, QWORD gsnfr ); static VectorStates vectorDecoderGetNextPacketState(VectorDecoderState &outVectorState); void log( Log::Level level = Log::Debug, const char *message = NULL ) const; public: WORD mChannelNumber; DWORD mSequenceNumber; // only lower 24bits are valid and all upper bits are set to zero BYTE mFlags; DWORD mGSNR; // Greatest Sequence Number Received - only lower 24bis are valid and all upper bits are set to zero DWORD mGSNFR; // Greatest Sequence Number Fully Received - only valid if Flag_EQ_GSNREqualsGSNFR is not set and only lower 24bis are valid and all upper bits are set to zero BYTE mVectorFlags; // contains the vector flags BYTE mVectorLengthInBytes; // how big is the length of the vector in bytes (only lower 7 bits are valid and upper bit is always zero) BYTE mVector[128]; // contains the vector as RLE data const BYTE *mData; // pointer to data (only valid as long as buffer associated is valid) WORD mDataLengthInBytes; // how big is the data buffer in bytes }; } }
Zeitsperre/flyingpigeon
flyingpigeon/tests/test_cdo.py
<reponame>Zeitsperre/flyingpigeon import pytest from .common import TESTDATA from flyingpigeon.utils import local_path from cdo import Cdo cdo = Cdo() def test_sinfo(): cdo.sinfo(input=local_path(TESTDATA['cmip5_tasmax_2006_nc']))
MichelleTanzil/personal_portfolio_v2
src/components/Timeline/MarketingTimeline.js
<reponame>MichelleTanzil/personal_portfolio_v2 import React from "react" import { VerticalTimeline, VerticalTimelineElement, } from "react-vertical-timeline-component" import "react-vertical-timeline-component/style.min.css" import { FaBriefcase, FaRegWindowClose } from "react-icons/fa" const MarketingTimeline = ({ handleOpen }) => { return ( <div> <div onClick={handleOpen} className="closeMktg tooltip" onKeyDown={handleOpen} role="presentation" > <FaRegWindowClose /> <span className="tooltiptext">Overview Experience</span> </div> <VerticalTimeline className={"vertical-timeline-custom-line"}> <VerticalTimelineElement className="vertical-timeline-element--work vertical-timeline-custom-line-down" iconClassName={"timeline-icons"} dateClassName={"timeline-date"} date="2018 - 2019" icon={<FaBriefcase />} > <h3 className="vertical-timeline-element-title"> Marketing Associate </h3> <h4 className="vertical-timeline-element-subtitle"> Principal Financial Group </h4> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--work vertical-timeline-custom-line-down" iconClassName={"timeline-icons-alt"} dateClassName={"timeline-date"} date="2016 - 2018" icon={<FaBriefcase />} > <h3 className="vertical-timeline-element-title"> Sales/Production Coordinator </h3> <h4 className="vertical-timeline-element-subtitle">PromoShop</h4> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--work vertical-timeline-custom-line-down" iconClassName={"timeline-icons"} dateClassName={"timeline-date"} date="2016" icon={<FaBriefcase />} > <h3 className="vertical-timeline-element-title"> Sales Support Coordinator </h3> <h4 className="vertical-timeline-element-subtitle"> Brown & Bigelow </h4> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--work vertical-timeline-custom-line-down" iconClassName={"timeline-icons-alt"} dateClassName={"timeline-date"} date="2015 - 2016" icon={<FaBriefcase />} > <h3 className="vertical-timeline-element-title"> Digital Sales Assistant/Adminstrative Assistant </h3> <h4 className="vertical-timeline-element-subtitle">Pixel Motion</h4> </VerticalTimelineElement> </VerticalTimeline> </div> ) } export default MarketingTimeline
JaneliaSciComp/jacs
jacs2-services/src/test/java/org/janelia/jacs2/asyncservice/alignservices/CMTKAlignmentProcessorTest.java
<gh_stars>0 package org.janelia.jacs2.asyncservice.alignservices; import com.google.common.collect.ImmutableList; import org.janelia.jacs2.asyncservice.common.ComputationTestHelper; import org.janelia.jacs2.asyncservice.common.JacsServiceResult; import org.janelia.jacs2.asyncservice.common.ServiceArg; import org.janelia.jacs2.asyncservice.common.ServiceArgMatcher; import org.janelia.jacs2.asyncservice.common.ServiceComputation; import org.janelia.jacs2.asyncservice.common.ServiceComputationFactory; import org.janelia.jacs2.asyncservice.common.ServiceExecutionContext; import org.janelia.jacs2.asyncservice.common.ServiceProcessorTestHelper; import org.janelia.jacs2.asyncservice.common.ServiceResultHandler; import org.janelia.jacs2.asyncservice.utils.FileUtils; import org.janelia.jacs2.dataservice.persistence.JacsServiceDataPersistence; import org.janelia.jacs2.testhelpers.ListArgMatcher; import org.janelia.model.service.JacsServiceData; import org.janelia.model.service.JacsServiceDataBuilder; import org.janelia.model.service.JacsServiceState; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.function.Consumer; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class CMTKAlignmentProcessorTest { private static final Long TEST_SERVICE_ID = 1L; private static final String TEST_WORKING_DIR = "testWorkingDir"; private SingleCMTKAlignmentProcessor singleCMTKAlignmentProcessor; private CMTKAlignmentProcessor cmtkAlignmentProcessor; private Path testDirectory; @Before public void setUp() throws IOException { Logger logger = mock(Logger.class); ServiceComputationFactory computationFactory = ComputationTestHelper.createTestServiceComputationFactory(logger); JacsServiceDataPersistence jacsServiceDataPersistence = mock(JacsServiceDataPersistence.class); singleCMTKAlignmentProcessor = mock(SingleCMTKAlignmentProcessor.class); when(jacsServiceDataPersistence.findById(any(Number.class))).then(invocation -> { JacsServiceData sd = new JacsServiceData(); sd.setId(invocation.getArgument(0)); sd.setState(JacsServiceState.SUCCESSFUL); return sd; }); when(jacsServiceDataPersistence.createServiceIfNotFound(any(JacsServiceData.class))).then(invocation -> { JacsServiceData jacsServiceData = invocation.getArgument(0); jacsServiceData.setId(TEST_SERVICE_ID); jacsServiceData.setState(JacsServiceState.SUCCESSFUL); // mark the service as completed otherwise the computation doesn't return return jacsServiceData; }); ServiceProcessorTestHelper.prepareServiceProcessorMetadataAsRealCall(singleCMTKAlignmentProcessor); cmtkAlignmentProcessor = new CMTKAlignmentProcessor(computationFactory, jacsServiceDataPersistence, TEST_WORKING_DIR, singleCMTKAlignmentProcessor, logger); testDirectory = Files.createTempDirectory("testcmtk"); } @After public void tearDown() throws IOException { FileUtils.deletePath(testDirectory); } @Test public void processInputImages() { List<String> inputImages = ImmutableList.of( "GMR_09C10_AE_01_23-fA01b_C100120_20100120125311859_01.nrrd", "GMR_09C10_AE_01_23-fA01b_C100120_20100120125311859_02.nrrd", "GMR_09C11_AE_01_57-fA01b_C101214_20101214100952734_01.nrrd", "GMR_09C11_AE_01_57-fA01b_C101214_20101214100952734_02.nrrd", "GMR_09D12_AE_01_03-fA01b_C110218_20110218103433625_01.nrrd", "GMR_09D12_AE_01_03-fA01b_C110218_20110218103433625_02.nrrd" ); String outputDir = testDirectory.toString(); @SuppressWarnings("unchecked") ServiceResultHandler<CMTKAlignmentResultFiles> singleCmtkAlignmentResultHandler = mock(ServiceResultHandler.class); when(singleCMTKAlignmentProcessor.getResultHandler()).thenReturn(singleCmtkAlignmentResultHandler); when(singleCmtkAlignmentResultHandler.getServiceDataResult(any(JacsServiceData.class))).thenReturn(new CMTKAlignmentResultFiles()); JacsServiceData testServiceData = createTestServiceData(TEST_SERVICE_ID, inputImages, outputDir); ServiceComputation<JacsServiceResult<List<String>>> cmtkAlignment = cmtkAlignmentProcessor.process(testServiceData); @SuppressWarnings("unchecked") Consumer<JacsServiceResult<List<String>>> successful = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer<Throwable> failure = mock(Consumer.class); cmtkAlignment .thenApply(r -> { successful.accept(r); verify(singleCMTKAlignmentProcessor).createServiceData( any(ServiceExecutionContext.class), argThat(new ListArgMatcher<>( ImmutableList.of( new ServiceArgMatcher(new ServiceArg("-inputDir", outputDir + "/" + "GMR_09C10_AE_01_23-fA01b_C100120_20100120125311859/images")), new ServiceArgMatcher(new ServiceArg("-outputDir", outputDir + "/" + "GMR_09C10_AE_01_23-fA01b_C100120_20100120125311859")), new ServiceArgMatcher(new ServiceArg("-template", "")), new ServiceArgMatcher(new ServiceArg("-a", "true")), new ServiceArgMatcher(new ServiceArg("-w", "true")), new ServiceArgMatcher(new ServiceArg("-r", "0102030405")), new ServiceArgMatcher(new ServiceArg("-X", "26")), new ServiceArgMatcher(new ServiceArg("-C", "8")), new ServiceArgMatcher(new ServiceArg("-G", "80")), new ServiceArgMatcher(new ServiceArg("-R", "4")), new ServiceArgMatcher(new ServiceArg("-A", "--accuracy 0.8")), new ServiceArgMatcher(new ServiceArg("-W", "--accuracy 0.8")), new ServiceArgMatcher(new ServiceArg("-nthreads", "")), new ServiceArgMatcher(new ServiceArg("-verbose", false)) )) ) ); verify(singleCMTKAlignmentProcessor).createServiceData( any(ServiceExecutionContext.class), argThat(new ListArgMatcher<>( ImmutableList.of( new ServiceArgMatcher(new ServiceArg("-inputDir", outputDir + "/" + "GMR_09C11_AE_01_57-fA01b_C101214_20101214100952734/images")), new ServiceArgMatcher(new ServiceArg("-outputDir", outputDir + "/" + "GMR_09C11_AE_01_57-fA01b_C101214_20101214100952734")), new ServiceArgMatcher(new ServiceArg("-template", "")), new ServiceArgMatcher(new ServiceArg("-a", "true")), new ServiceArgMatcher(new ServiceArg("-w", "true")), new ServiceArgMatcher(new ServiceArg("-r", "0102030405")), new ServiceArgMatcher(new ServiceArg("-X", "26")), new ServiceArgMatcher(new ServiceArg("-C", "8")), new ServiceArgMatcher(new ServiceArg("-G", "80")), new ServiceArgMatcher(new ServiceArg("-R", "4")), new ServiceArgMatcher(new ServiceArg("-A", "--accuracy 0.8")), new ServiceArgMatcher(new ServiceArg("-W", "--accuracy 0.8")), new ServiceArgMatcher(new ServiceArg("-nthreads", "")), new ServiceArgMatcher(new ServiceArg("-verbose", false)) )) ) ); verify(singleCMTKAlignmentProcessor).createServiceData( any(ServiceExecutionContext.class), argThat(new ListArgMatcher<>( ImmutableList.of( new ServiceArgMatcher(new ServiceArg("-inputDir", outputDir + "/" + "GMR_09D12_AE_01_03-fA01b_C110218_20110218103433625/images")), new ServiceArgMatcher(new ServiceArg("-outputDir", outputDir + "/" + "GMR_09D12_AE_01_03-fA01b_C110218_20110218103433625")), new ServiceArgMatcher(new ServiceArg("-template", "")), new ServiceArgMatcher(new ServiceArg("-a", "true")), new ServiceArgMatcher(new ServiceArg("-w", "true")), new ServiceArgMatcher(new ServiceArg("-r", "0102030405")), new ServiceArgMatcher(new ServiceArg("-X", "26")), new ServiceArgMatcher(new ServiceArg("-C", "8")), new ServiceArgMatcher(new ServiceArg("-G", "80")), new ServiceArgMatcher(new ServiceArg("-R", "4")), new ServiceArgMatcher(new ServiceArg("-A", "--accuracy 0.8")), new ServiceArgMatcher(new ServiceArg("-W", "--accuracy 0.8")), new ServiceArgMatcher(new ServiceArg("-nthreads", "")), new ServiceArgMatcher(new ServiceArg("-verbose", false)) )) ) ); return r; }) .exceptionally(exc -> { failure.accept(exc); fail(exc.toString()); return null; }); } private JacsServiceData createTestServiceData(Long serviceId, List<String> inputImages, String outputDir) { JacsServiceDataBuilder testServiceDataBuilder = new JacsServiceDataBuilder(null) .setOwnerKey("testOwner") .addArgs("-inputImages", String.join(",", inputImages)) .addArgs("-outputDir", outputDir) .setWorkspace(TEST_WORKING_DIR); JacsServiceData testServiceData = testServiceDataBuilder.build(); testServiceData.setId(serviceId); return testServiceData; } }
samueleallegranza/polimi-info
ESE-13/ex2.c
<reponame>samueleallegranza/polimi-info<filename>ESE-13/ex2.c<gh_stars>0 /* <NAME> @ Polimi Fondamenti di informatica - Esercitazione > Esercizio: Scrivere un sottoprogramma selectitems che ricevuta in ingresso una lista per la gestione di valori interi e due interi min e max, crea una nuova lista contente tutti e soli i valori presenti nella list di ingresso strettamente compresi tra min e max, ordinati in modo crescente e la restituisce al chiamante. La lista di partenza non deve essere modificata. Si considerino dati i sottoprogrammi di gestione delle liste visti a lezione. */ #include <stdio.h> #include <stdlib.h> listi_t * selectitems(listi_t *, int, int); listi_t * selectitems(listi_t * h, int min, int max) { listi_t * res; listi_t * p; p = h; while(p) { if((h->v) > min && (h->v) < max) { res = insertup(h2, h->v); } p = p->next; } return res; }
NimBuzz01/Project-Miika_SDGP
miika_nlu/venv/Lib/site-packages/torch/include/ATen/ops/convolution_backward.h
#pragma once // @generated by tools/codegen/gen.py from Function.h #include <ATen/Context.h> #include <ATen/DeviceGuard.h> #include <ATen/TensorUtils.h> #include <ATen/TracerMode.h> #include <ATen/core/Generator.h> #include <ATen/core/Reduction.h> #include <ATen/core/Tensor.h> #include <c10/core/Scalar.h> #include <c10/core/Storage.h> #include <c10/core/TensorOptions.h> #include <c10/util/Deprecated.h> #include <c10/util/Optional.h> #include <ATen/ops/convolution_backward_ops.h> namespace at { // aten::convolution_backward(Tensor grad_output, Tensor input, Tensor weight, int[]? bias_sizes, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) TORCH_API inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> convolution_backward(const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, c10::optional<at::IntArrayRef> bias_sizes, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups, ::std::array<bool,3> output_mask) { return at::_ops::convolution_backward::call(grad_output, input, weight, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, output_mask); } }
zfang399/LeetCode-Problems
517.cpp
class Solution { public: int findMinMoves(vector<int>& machines) { vector<int> presum; presum.push_back(0); for(int i=0;i<machines.size();i++){ presum.push_back(presum.back()+machines[i]); } if(presum.back()%machines.size()!=0) return -1; int avg=presum.back()/machines.size(); int ans=0; for(int i=0;i<machines.size();i++){ int l=i*avg-presum[i]; int r=(machines.size()-i-1)*avg-(presum.back()-presum[i+1]); if(l>0 && r>0){ ans=max(ans,l+r); }else{ ans=max(ans,max(abs(l),abs(r))); } } return ans; } };
dirkluijk/infobip-spring-data-querydsl
infobip-spring-data-jdbc-annotation-processor-common/src/main/java/com/infobip/spring/data/jdbc/annotation/processor/CustomExtendedTypeFactory.java
<gh_stars>10-100 package com.infobip.spring.data.jdbc.annotation.processor; import com.google.common.base.CaseFormat; import com.querydsl.apt.Configuration; import com.querydsl.apt.ExtendedTypeFactory; import com.querydsl.codegen.*; import com.querydsl.codegen.utils.model.Type; import com.querydsl.codegen.utils.model.TypeCategory; import com.querydsl.sql.ColumnMetadata; import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.relational.core.mapping.Table; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.*; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; class CustomExtendedTypeFactory extends ExtendedTypeFactory { public static final String IS_EMBEDDED_DATA_KEY = "isEmbedded"; private final Configuration configuration; private final Elements elements; private final String defaultSchema; private final CaseFormat tableCaseFormat; private final CaseFormat columnCaseFormat; private final Types types; public CustomExtendedTypeFactory(RoundEnvironment roundEnv, ProcessingEnvironment env, Set<Class<? extends Annotation>> annotations, TypeMappings typeMappings, QueryTypeFactory queryTypeFactory, Configuration configuration, Elements elements, CaseFormat tableCaseFormat, CaseFormat columnCaseFormat) { super(env, annotations, typeMappings, queryTypeFactory, configuration.getVariableNameFunction()); this.types = env.getTypeUtils(); this.configuration = configuration; this.elements = elements; this.defaultSchema = getDefaultSchema(roundEnv); this.tableCaseFormat = tableCaseFormat; this.columnCaseFormat = columnCaseFormat; } @Override public boolean isSimpleTypeEntity(TypeElement typeElement, Class<? extends Annotation> entityAnn) { return typeElement.getAnnotation(entityAnn) != null || typeElement.getEnclosedElements() .stream() .anyMatch(element -> element.getAnnotation(entityAnn) != null); } @Override public EntityType getEntityType(TypeMirror typeMirror, boolean deep) { Element element = types.asElement(typeMirror); EntityType entityType = super.getEntityType(typeMirror, deep); List<Property> embeddedlessProperties = entityType.getProperties() .stream() .flatMap(property -> { if (Embeddeds.isEmbedded(configuration, element, property)) { return flattenEmbeddedProperty(property); } return Stream.of(property); }) .collect(Collectors.toList()); entityType.getProperties().clear(); entityType.getProperties().addAll(embeddedlessProperties); entityType.getPropertyNames().clear(); entityType.getPropertyNames() .addAll(embeddedlessProperties.stream().map(Property::getName).collect(Collectors.toList())); updateModel(element, entityType); return entityType; } protected String getDefaultSchema(RoundEnvironment roundEnv) { Set<? extends Element> defaultSchemaElements = roundEnv.getElementsAnnotatedWith(DefaultSchema.class); if (defaultSchemaElements.isEmpty()) { return null; } if (defaultSchemaElements.size() > 1) { throw new IllegalArgumentException("found multiple elements with DefaultSchema " + defaultSchemaElements); } return defaultSchemaElements.iterator().next().getAnnotation(DefaultSchema.class).value(); } private Stream<Property> flattenEmbeddedProperty(Property property) { Type type = property.getType(); if (!type.getCategory().equals(TypeCategory.ENTITY)) { return Stream.of(property); } return ((EntityType) type).getProperties().stream(); } private void updateModel(Element element, EntityType type) { Map<Object, Object> data = type.getData(); data.put("table", getTableName(type)); getSchema(element).ifPresent(schema -> data.put("schema", schema)); AtomicInteger counter = new AtomicInteger(); type.getProperties() .forEach(property -> addMetaData(element, counter, property)); } private Object addMetaData(Element element, AtomicInteger counter, Property property) { Map<Object, Object> data = property.getData(); if (Embeddeds.isEmbedded(configuration, element, property)) { data.put(IS_EMBEDDED_DATA_KEY, true); } return data.put("COLUMN", ColumnMetadata.named(getColumnName(property)) .withIndex(counter.getAndIncrement())); } protected Optional<String> getSchema(Element element) { Schema elementSchema = element.getAnnotation(Schema.class); if (Objects.isNull(elementSchema)) { return Optional.ofNullable(defaultSchema); } return Optional.of(elementSchema.value()); } protected String getTableName(EntityType model) { String simpleName = model.getSimpleName(); String className = model.getPackageName() + "." + simpleName; String tableName = CaseFormat.UPPER_CAMEL.to(tableCaseFormat, simpleName); return Optional.ofNullable(elements.getTypeElement(className) .getAnnotation(Table.class)) .map(Table::value) .orElse(tableName); } protected String getColumnName(Property property) { TypeElement parentType = elements.getTypeElement(property.getDeclaringType().getFullName()); return parentType.getEnclosedElements() .stream() .filter(element -> element instanceof VariableElement) .map(element -> (VariableElement) element) .filter(element -> element.getSimpleName().toString().equals(property.getName())) .filter(element -> element.getAnnotation(Column.class) != null) .map(element -> element.getAnnotation(Column.class).value()) .findAny() .orElseGet(() -> CaseFormat.LOWER_CAMEL.to(columnCaseFormat, property.getName())); } private Stream<? extends Element> getFields(Element element) { return element.getEnclosedElements() .stream() .filter(enclosedElement -> enclosedElement.getKind().equals(ElementKind.FIELD)); } }
Sypheos/lorawan-stack
pkg/identityserver/contact_info_registry.go
<filename>pkg/identityserver/contact_info_registry.go // Copyright © 2019 The Things Network Foundation, The Things Industries B.V. // // 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 identityserver import ( "context" "time" "github.com/gogo/protobuf/types" "github.com/jinzhu/gorm" "go.thethings.network/lorawan-stack/pkg/auth" "go.thethings.network/lorawan-stack/pkg/email" "go.thethings.network/lorawan-stack/pkg/identityserver/emails" "go.thethings.network/lorawan-stack/pkg/identityserver/store" "go.thethings.network/lorawan-stack/pkg/log" "go.thethings.network/lorawan-stack/pkg/ttnpb" ) func (is *IdentityServer) requestContactInfoValidation(ctx context.Context, ids *ttnpb.EntityIdentifiers) (*ttnpb.ContactInfoValidation, error) { id, err := auth.GenerateID(ctx) if err != nil { return nil, err } var contactInfo []*ttnpb.ContactInfo err = is.withDatabase(ctx, func(db *gorm.DB) (err error) { contactInfo, err = store.GetContactInfoStore(db).GetContactInfo(ctx, ids) return err }) if err != nil { return nil, err } now := time.Now() emailValidationsExpireAt := now.Add(24 * time.Hour) emailValidations := make(map[string]*ttnpb.ContactInfoValidation) for _, info := range contactInfo { if info.ContactMethod == ttnpb.CONTACT_METHOD_EMAIL && info.ValidatedAt == nil { validation, ok := emailValidations[info.Value] if !ok { key, err := auth.GenerateKey(ctx) if err != nil { return nil, err } validation = &ttnpb.ContactInfoValidation{ ID: id, Token: key, Entity: ids, CreatedAt: &now, ExpiresAt: &emailValidationsExpireAt, } emailValidations[info.Value] = validation } validation.ContactInfo = append(validation.ContactInfo, info) } } var pendingContactInfo []*ttnpb.ContactInfo if len(emailValidations) > 0 { err := is.withDatabase(ctx, func(db *gorm.DB) (err error) { for email, validation := range emailValidations { validation, err = store.GetContactInfoStore(db).CreateValidation(ctx, validation) if err != nil { return err } log.FromContext(ctx).WithFields(log.Fields( "email", email, "token", validation.Token, )).Info("Created email validation token") emailValidations[email] = validation } return nil }) if err != nil { return nil, err } for address, validation := range emailValidations { err := is.SendEmail(ctx, func(data emails.Data) email.MessageData { data.User.Email = address data.SetEntity(validation.Entity) return emails.Validate{ Data: data, ID: validation.ID, Token: validation.Token, } }) if err != nil { log.FromContext(ctx).WithError(err).Error("Could not send validation email") } pendingContactInfo = append(pendingContactInfo, validation.ContactInfo...) validation.Token = "" // Unset tokens after sending emails } } return &ttnpb.ContactInfoValidation{ ID: id, Entity: ids, ContactInfo: pendingContactInfo, CreatedAt: &now, }, nil } func (is *IdentityServer) validateContactInfo(ctx context.Context, req *ttnpb.ContactInfoValidation) (*types.Empty, error) { err := is.withDatabase(ctx, func(db *gorm.DB) error { return store.GetContactInfoStore(db).Validate(ctx, req) }) if err != nil { return nil, err } return ttnpb.Empty, nil } type contactInfoRegistry struct { *IdentityServer } func (cir *contactInfoRegistry) RequestValidation(ctx context.Context, ids *ttnpb.EntityIdentifiers) (*ttnpb.ContactInfoValidation, error) { return cir.requestContactInfoValidation(ctx, ids) } func (cir *contactInfoRegistry) Validate(ctx context.Context, req *ttnpb.ContactInfoValidation) (*types.Empty, error) { return cir.validateContactInfo(ctx, req) }
cuiyuemin365/books
spring3.x/chapter11/test/com/baobaotao/dao/TestTopicDao.java
<filename>spring3.x/chapter11/test/com/baobaotao/dao/TestTopicDao.java package com.baobaotao.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import com.baobaotao.dao.ForumDao; import com.baobaotao.dao.TopicDao; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) @TransactionConfiguration @Transactional public class TestTopicDao { @Autowired private TopicDao topicDao; @Test public void testGetReplyRate() { double rate = topicDao.getReplyRate(2); System.out.println("rate is:" + rate); } @Test public void testGetUserTopicNum() throws Throwable { int num = topicDao.getUserTopicNum(1); System.out.println("num is:" + num); } // // public void testGetUserTopicNum2() throws Throwable{ // int num = topicDao.getUserTopicNum2(1); // System.out.println("num is:" + num); // } @Test public void testGetTopicRowSet() { SqlRowSet srs = topicDao.getTopicRowSet(1); while (srs.next()) { System.out.println(srs.getString("topic_id")); } } }
ghoslation/opencsv
src/test/java/com/opencsv/bean/mocks/AnnotatedMockBeanCustom.java
<reponame>ghoslation/opencsv /* * Copyright 2016 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.opencsv.bean.mocks; import com.opencsv.bean.*; import com.opencsv.bean.customconverter.ConvertGermanToBoolean; import com.opencsv.bean.customconverter.ConvertSplitOnWhitespace; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; /** * A test class that should provide full coverage for tests of the opencsv * annotations and their custom functions. * * @author <NAME> */ public class AnnotatedMockBeanCustom { /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * <li>{@link com.opencsv.bean.StatefulBeanToCsvTest#writeEmptyFieldWithConvertGermanToBooleanRequired()}</li> * </ul></p> */ @CsvCustomBindByName(column = "bool1", converter = ConvertGermanToBoolean.class, required = true) @CsvCustomBindByPosition(position = 1, converter = ConvertGermanToBoolean.class, required = true) private Boolean boolWrapped; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(converter = ConvertGermanToBoolean.class, required = true) @CsvCustomBindByPosition(position = 2, converter = ConvertGermanToBoolean.class, required = true) private boolean boolPrimitive; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testCustomByNameWrappedPrimitiveDataTypeMismatch()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testCustomByPositionWrappedPrimitiveDataTypeMismatch()}</li> * </ul></p> * <p>Used for the following test cases, writing:<ul> * <li>Writing with ConvertGermanToBoolean</li> * </ul></p> */ @CsvCustomBindByName(column = "bool2", converter = ConvertGermanToBoolean.class) @CsvCustomBindByPosition(position = 45, converter = ConvertGermanToBoolean.class) private Boolean boolWrappedOptional; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * </ul></p> */ @CsvCustomBindByName(column = "bool3", converter = ConvertGermanToBoolean.class) @CsvCustomBindByPosition(position = 46, converter = ConvertGermanToBoolean.class) private boolean boolPrimitiveOptional; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "byte1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 3, converter = CustomTestMapper.class) private Byte byteWrappedDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * </ul></p> */ @CsvCustomBindByName(column = "byte2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 4, converter = CustomTestMapper.class) private Byte byteWrappedSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> * <p>Used for the following test cases, writing:<ul> * <li>Writing with @CsvBindByPosition and @CsvCustomBindByPosition</li> * </ul></p> */ @CsvCustomBindByName(column = "byte3", converter = CustomTestMapper.class) @CsvBindByName(column = "byte1") @CsvCustomBindByPosition(position = 5, converter = CustomTestMapper.class) @CsvBindByPosition(position = 3) private byte bytePrimitiveDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "double1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 7, converter = CustomTestMapper.class) private Double doubleWrappedDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "double2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 8, converter = CustomTestMapper.class) private Double doubleWrappedSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "double3", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 9, converter = CustomTestMapper.class) private double doublePrimitiveDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "double4", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 10, converter = CustomTestMapper.class) private double doublePrimitiveSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "float1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 11, converter = CustomTestMapper.class) private Float floatWrappedDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "float2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 12, converter = CustomTestMapper.class) private Float floatWrappedSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "float3", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 13, converter = CustomTestMapper.class) private float floatPrimitiveDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "float4", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 14, converter = CustomTestMapper.class) private float floatPrimitiveSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "integer1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 15, converter = CustomTestMapper.class) private Integer integerWrappedDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "integer2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 16, converter = CustomTestMapper.class) private Integer integerWrappedSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "integer3", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 17, converter = CustomTestMapper.class) private int integerPrimitiveDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "integer4", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 18, converter = CustomTestMapper.class) private int integerPrimitiveSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "long1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 19, converter = CustomTestMapper.class) private Long longWrappedDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "long2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 20, converter = CustomTestMapper.class) private Long longWrappedSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "long3", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 21, converter = CustomTestMapper.class) private long longPrimitiveDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "long4", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 22, converter = CustomTestMapper.class) private long longPrimitiveSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "short1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 23, converter = CustomTestMapper.class) private Short shortWrappedDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "short2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 24, converter = CustomTestMapper.class) private Short shortWrappedSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "short3", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 25, converter = CustomTestMapper.class) private short shortPrimitiveDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "short4", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 26, converter = CustomTestMapper.class) private short shortPrimitiveSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "char1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 27, converter = CustomTestMapper.class) private Character characterWrapped; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "char2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 28, converter = CustomTestMapper.class) private char characterPrimitive; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "bigdecimal1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 29, converter = CustomTestMapper.class) private BigDecimal bigdecimalDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "bigdecimal2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 30, converter = CustomTestMapper.class) private BigDecimal bigdecimalSetLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "biginteger1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 31, converter = CustomTestMapper.class) private BigInteger bigintegerDefaultLocale; /** * <p>Used for the following test cases:<ul> * <li></li> * </ul></p> */ @CsvCustomBindByName(column = "biginteger2", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 32, converter = CustomTestMapper.class) private BigInteger bigintegerSetLocale; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "string1", converter = CustomTestMapper.class) @CsvCustomBindByPosition(position = 0, converter = CustomTestMapper.class) private String stringClass; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> * <p>Used for the following test cases, writing:<ul> * <li>Writing with ConvertSplitOnWhitespace</li> * </ul></p> */ @CsvCustomBindByName(column = "string2", converter = ConvertSplitOnWhitespace.class) @CsvCustomBindByPosition(position = 47, converter = ConvertSplitOnWhitespace.class) private List<String> complexString; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "complex1", converter = ConverterComplexClassForCustomAnnotation.class) @CsvCustomBindByPosition(position = 48, converter = ConverterComplexClassForCustomAnnotation.class) private ComplexClassForCustomAnnotation complexClass1; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "complex2", converter = ConverterComplexClassForCustomAnnotation.class) @CsvCustomBindByPosition(position = 49, converter = ConverterComplexClassForCustomAnnotation.class) private ComplexClassForCustomAnnotation complexClass2; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testMapByNameComplexTypeWrongType()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testMapByPositionComplexTypeWrongType()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * </ul></p> */ @CsvCustomBindByName(column = "complex3", converter = ConverterComplexClassForCustomAnnotation.class) @CsvCustomBindByPosition(position = 50, converter = ConverterComplexClassForCustomAnnotation.class) private ComplexClassForCustomAnnotation complexClass3; /** * <p>Used for the following test cases:<ul> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByName()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testGoodDataCustomByPosition()}</li> * <li>{@link com.opencsv.bean.AnnotationTest#testCustomConverterRequiredEmptyInput()}</li> * </ul></p> */ @CsvCustomBindByName(column = "requiredWithCustom", converter = CustomTestMapper.class, required = true) @CsvCustomBindByPosition(position = 51, converter = CustomTestMapper.class, required = true) private String requiredWithCustom; public Boolean getBoolWrapped() { return boolWrapped; } public void setBoolWrapped(Boolean boolWrapped) { this.boolWrapped = boolWrapped; } public boolean isBoolPrimitive() { return boolPrimitive; } public void setBoolPrimitive(boolean boolPrimitive) { this.boolPrimitive = boolPrimitive; } public Byte getByteWrappedDefaultLocale() { return byteWrappedDefaultLocale; } public void setByteWrappedDefaultLocale(Byte byteWrappedDefaultLocale) { this.byteWrappedDefaultLocale = byteWrappedDefaultLocale; } public Byte getByteWrappedSetLocale() { return byteWrappedSetLocale; } public void setByteWrappedSetLocale(Byte byteWrappedSetLocale) { this.byteWrappedSetLocale = byteWrappedSetLocale; } public byte getBytePrimitiveDefaultLocale() { return bytePrimitiveDefaultLocale; } public void setBytePrimitiveDefaultLocale(byte bytePrimitiveDefaultLocale) { this.bytePrimitiveDefaultLocale = bytePrimitiveDefaultLocale; } public Double getDoubleWrappedDefaultLocale() { return doubleWrappedDefaultLocale; } public void setDoubleWrappedDefaultLocale(Double doubleWrappedDefaultLocale) { this.doubleWrappedDefaultLocale = doubleWrappedDefaultLocale; } public Double getDoubleWrappedSetLocale() { return doubleWrappedSetLocale; } public void setDoubleWrappedSetLocale(Double doubleWrappedSetLocale) { this.doubleWrappedSetLocale = doubleWrappedSetLocale; } public double getDoublePrimitiveDefaultLocale() { return doublePrimitiveDefaultLocale; } public void setDoublePrimitiveDefaultLocale(double doublePrimitiveDefaultLocale) { this.doublePrimitiveDefaultLocale = doublePrimitiveDefaultLocale; } public double getDoublePrimitiveSetLocale() { return doublePrimitiveSetLocale; } public void setDoublePrimitiveSetLocale(double doublePrimitiveSetLocale) { this.doublePrimitiveSetLocale = doublePrimitiveSetLocale; } public Float getFloatWrappedDefaultLocale() { return floatWrappedDefaultLocale; } public void setFloatWrappedDefaultLocale(Float floatWrappedDefaultLocale) { this.floatWrappedDefaultLocale = floatWrappedDefaultLocale; } public Float getFloatWrappedSetLocale() { return floatWrappedSetLocale; } public void setFloatWrappedSetLocale(Float floatWrappedSetLocale) { this.floatWrappedSetLocale = floatWrappedSetLocale; } public float getFloatPrimitiveDefaultLocale() { return floatPrimitiveDefaultLocale; } public void setFloatPrimitiveDefaultLocale(float floatPrimitiveDefaultLocale) { this.floatPrimitiveDefaultLocale = floatPrimitiveDefaultLocale; } public float getFloatPrimitiveSetLocale() { return floatPrimitiveSetLocale; } public void setFloatPrimitiveSetLocale(float floatPrimitiveSetLocale) { this.floatPrimitiveSetLocale = floatPrimitiveSetLocale; } public Integer getIntegerWrappedDefaultLocale() { return integerWrappedDefaultLocale; } public void setIntegerWrappedDefaultLocale(Integer integerWrappedDefaultLocale) { this.integerWrappedDefaultLocale = integerWrappedDefaultLocale; } public Integer getIntegerWrappedSetLocale() { return integerWrappedSetLocale; } public void setIntegerWrappedSetLocale(Integer integerWrappedSetLocale) { this.integerWrappedSetLocale = integerWrappedSetLocale; } public int getIntegerPrimitiveDefaultLocale() { return integerPrimitiveDefaultLocale; } public void setIntegerPrimitiveDefaultLocale(int integerPrimitiveDefaultLocale) { this.integerPrimitiveDefaultLocale = integerPrimitiveDefaultLocale; } public int getIntegerPrimitiveSetLocale() { return integerPrimitiveSetLocale; } public void setIntegerPrimitiveSetLocale(int integerPrimitiveSetLocale) { this.integerPrimitiveSetLocale = integerPrimitiveSetLocale; } public Long getLongWrappedDefaultLocale() { return longWrappedDefaultLocale; } public void setLongWrappedDefaultLocale(Long longWrappedDefaultLocale) { this.longWrappedDefaultLocale = longWrappedDefaultLocale; } public Long getLongWrappedSetLocale() { return longWrappedSetLocale; } public void setLongWrappedSetLocale(Long longWrappedSetLocale) { this.longWrappedSetLocale = longWrappedSetLocale; } public long getLongPrimitiveDefaultLocale() { return longPrimitiveDefaultLocale; } public void setLongPrimitiveDefaultLocale(long longPrimitiveDefaultLocale) { this.longPrimitiveDefaultLocale = longPrimitiveDefaultLocale; } public long getLongPrimitiveSetLocale() { return longPrimitiveSetLocale; } public void setLongPrimitiveSetLocale(long longPrimitiveSetLocale) { this.longPrimitiveSetLocale = longPrimitiveSetLocale; } public Short getShortWrappedDefaultLocale() { return shortWrappedDefaultLocale; } public void setShortWrappedDefaultLocale(Short shortWrappedDefaultLocale) { this.shortWrappedDefaultLocale = shortWrappedDefaultLocale; } public Short getShortWrappedSetLocale() { return shortWrappedSetLocale; } public void setShortWrappedSetLocale(Short shortWrappedSetLocale) { this.shortWrappedSetLocale = shortWrappedSetLocale; } public short getShortPrimitiveDefaultLocale() { return shortPrimitiveDefaultLocale; } public void setShortPrimitiveDefaultLocale(short shortPrimitiveDefaultLocale) { this.shortPrimitiveDefaultLocale = shortPrimitiveDefaultLocale; } public short getShortPrimitiveSetLocale() { return shortPrimitiveSetLocale; } public void setShortPrimitiveSetLocale(short shortPrimitiveSetLocale) { this.shortPrimitiveSetLocale = shortPrimitiveSetLocale; } public Character getCharacterWrapped() { return characterWrapped; } public void setCharacterWrapped(Character characterWrapped) { this.characterWrapped = characterWrapped; } public char getCharacterPrimitive() { return characterPrimitive; } public void setCharacterPrimitive(char characterPrimitive) { this.characterPrimitive = characterPrimitive; } public BigDecimal getBigdecimalDefaultLocale() { return bigdecimalDefaultLocale; } public void setBigdecimalDefaultLocale(BigDecimal bigdecimalDefaultLocale) { this.bigdecimalDefaultLocale = bigdecimalDefaultLocale; } public BigDecimal getBigdecimalSetLocale() { return bigdecimalSetLocale; } public void setBigdecimalSetLocale(BigDecimal bigdecimalSetLocale) { this.bigdecimalSetLocale = bigdecimalSetLocale; } public BigInteger getBigintegerDefaultLocale() { return bigintegerDefaultLocale; } public void setBigintegerDefaultLocale(BigInteger bigintegerDefaultLocale) { this.bigintegerDefaultLocale = bigintegerDefaultLocale; } public BigInteger getBigintegerSetLocale() { return bigintegerSetLocale; } public void setBigintegerSetLocale(BigInteger bigintegerSetLocale) { this.bigintegerSetLocale = bigintegerSetLocale; } public String getStringClass() { return stringClass; } public void setStringClass(String stringClass) { this.stringClass = stringClass; } public Boolean getBoolWrappedOptional() { return boolWrappedOptional; } public void setBoolWrappedOptional(Boolean boolWrappedOptional) { this.boolWrappedOptional = boolWrappedOptional; } public boolean isBoolPrimitiveOptional() { return boolPrimitiveOptional; } public void setBoolPrimitiveOptional(boolean boolPrimitiveOptional) { this.boolPrimitiveOptional = boolPrimitiveOptional; } public List<String> getComplexString() { return complexString; } public void setComplexString(List<String> complexString) { this.complexString = complexString; } public ComplexClassForCustomAnnotation getComplexClass1() { return complexClass1; } /* Commented out for test case mapping to complex object with private access, no setter method. public void setComplexClass1(ComplexClassForCustomAnnotation complexClass1) { this.complexClass1 = complexClass1; } */ public ComplexClassForCustomAnnotation getComplexClass2() { return complexClass2; } public void setComplexClass2(ComplexClassForCustomAnnotation complexClass2) { this.complexClass2 = complexClass2; this.complexClass2.i = Integer.MAX_VALUE - this.complexClass2.i; this.complexClass2.c = 'z'; this.complexClass2.s = "Inserted in setter method" + this.complexClass2.s; } public ComplexClassForCustomAnnotation getComplexClass3() { return complexClass3; } /* Private for test case mapping to private complex type with private setter. */ private void setComplexClass3(ComplexClassForCustomAnnotation complexClass3) { this.complexClass3 = new ComplexClassForCustomAnnotation(); this.complexClass3.i = -1; this.complexClass3.c = 'z'; this.complexClass3.s = "Inserted in setter method"; } public String getRequiredWithCustom() { return requiredWithCustom; } public void setRequiredWithCustom(String requiredWithCustom) { this.requiredWithCustom = requiredWithCustom; } }
arsdever/opengl_tutorials
src/components/sample_meshes/triangle_mesh.cpp
#include <profiler.hpp> #include "triangle_mesh.hpp" namespace gl { using namespace vertex_attributes; triangle_mesh::triangle_mesh() { auto scoped_profiler_instance = prof::profiler::profile(object().lock()->id() + "::" + __func__); _vertices.reserve(3); _vertices.push_back( vertex { position { 0, 0, 0 }, color { 1, 0, 0, 1 }, uv_coords { 0, 0 }, normal { 0, 0, 0 } }); _vertices.push_back( vertex { position { 1, 0, 0 }, color { 0, 1, 0, 1 }, uv_coords { 1, 0 }, normal { 0, 0, 0 } }); _vertices.push_back( vertex { position { 0, 1, 0 }, color { 0, 0, 1, 1 }, uv_coords { 0, 1 }, normal { 0, 0, 0 } }); _indices.reserve(3); _indices.push_back(0); _indices.push_back(1); _indices.push_back(2); } } // namespace gl
olivervbk/java-webapplication-example
src/main/java/com/github/olivervbk/dao/UserDao.java
<filename>src/main/java/com/github/olivervbk/dao/UserDao.java package com.github.olivervbk.dao; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.github.olivervbk.model.User; /** * @author oliver.kuster * @version 1.0 Created on 7 de jun de 2016 */ @Repository( "userDao" ) public class UserDao extends AbstractDao<User> { /** * @param sessionFactory */ @Autowired public UserDao( final SessionFactory sessionFactory ) { super( sessionFactory, User.class ); } /** * @param name * @return */ public User findByUsername( final String name ) { final Criteria critaeria = createCriteria(); critaeria.add( Restrictions.eq( "username", name ) ); return ( User ) critaeria.uniqueResult(); } }
shreejitverma/GeeksforGeeks
Competitive Programming/Bit Manipulation/first_set_bit.cpp
// { Driver Code Starts //Initial Template for C++ #include<bits/stdc++.h> using namespace std; // } Driver Code Ends //User function Template for C++ /* function to find position of first set bit in the given number * n: given input for which we want to get the position of first set bit */ unsigned int getFirstSetBit(int n){ // Your code here int ans; if((n & 1) != 0){ ans = 1; }else{ for(int i=1; i<20; i++){ if((n&(1<<i)) != 0){ ans = i+1; break; } } } return ans; } // { Driver Code Starts. // Driver code int main() { int t; cin>>t; // testcases while(t--) { int n; cin>>n; //input n printf("%u\n", getFirstSetBit(n)); // function to get answer } return 0; } // } Driver Code Ends
apsdehal/qunit-migrate
src/ast/rules/anonymous-function.js
var builder = require('recast').types.builders; var constants = require('../constants'); var path = require('path'); var utils = require('../utils'); var optionNames = require('../option-names'); var isAnonymous = require('../checks/is-anonymous'); module.exports = AnonymousFunction; function AnonymousFunction() { this._optionName = optionNames.AnonymousFunction; }; AnonymousFunction.prototype = { check: function (context) { return isAnonymous(context); }, update: function (context) { var _self = this; var node = context.node; var params = node.expression.callee.params; var paramLength = params.length; for(var i = 0; i < paramLength; i++) { var param = params[i]; if (param.type === 'Identifier' && param.name === constants.qunit) { return; } } params.unshift(builder.identifier(constants.qunit)); node.expression.arguments.unshift(builder.identifier(constants.qunit)); context.update(node); }, getOptionName: function () { return this._optionName; } };
zealoussnow/chromium
remoting/protocol/audio_reader.cc
<reponame>zealoussnow/chromium // Copyright (c) 2012 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. #include "remoting/protocol/audio_reader.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "net/socket/stream_socket.h" #include "remoting/base/compound_buffer.h" #include "remoting/base/constants.h" #include "remoting/proto/audio.pb.h" #include "remoting/protocol/audio_stub.h" #include "remoting/protocol/message_serialization.h" #include "remoting/protocol/session.h" #include "remoting/protocol/session_config.h" namespace remoting { namespace protocol { AudioReader::AudioReader(AudioStub* audio_stub) : ChannelDispatcherBase(kAudioChannelName), audio_stub_(audio_stub) {} AudioReader::~AudioReader() = default; void AudioReader::OnIncomingMessage(std::unique_ptr<CompoundBuffer> message) { std::unique_ptr<AudioPacket> audio_packet = ParseMessage<AudioPacket>(message.get()); if (audio_packet) { audio_stub_->ProcessAudioPacket(std::move(audio_packet), base::DoNothing()); } } } // namespace protocol } // namespace remoting
sympower/protobuf-javame
protobuf-javame-tests/src/test/java/net/jarlehansen/protobuf/javame/input/DelimitedInputStreamTest.java
<reponame>sympower/protobuf-javame package net.jarlehansen.protobuf.javame.input; import java.io.IOException; import java.io.InputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DelimitedInputStreamTest { private DelimitedInputStream delimitedInputStream; private static final int limit = 10; @Before public void setUp() { InputStream inputStream = new InputStream() { public int read() throws IOException { return limit; } }; delimitedInputStream = new DelimitedInputStream(inputStream, limit); } @After public void tearDown() { try { delimitedInputStream.close(); } catch (IOException io) { io.printStackTrace(); } } @Test public void testReadFromDelimitedInputStream() throws IOException { assertEquals(limit, delimitedInputStream.read()); } @Test public void testReadMoreThanLimitFromDelimitedInputStream() throws IOException { assertEquals(limit, delimitedInputStream.read(new byte[15], 0, 15)); } @Test public void testReadFromEmptyDelimitedInputStream() throws IOException { assertEquals(limit, delimitedInputStream.read(new byte[limit], 0, limit)); assertEquals(-1, delimitedInputStream.read(new byte[limit], 0, limit)); } }
markcorrea/comandasmart-v2-frontend
src/pages/Report/CancelationsPerUser/index.js
import React, {useState, useEffect, useCallback, useMemo, memo} from 'react' import {Button, Datetimepicker, Paper, ResponsiveTable, Select, SectionBox} from 'components' import {useLoader} from 'components/FadeLoader' import {useStore} from 'store' import services from 'services' import formatMoney from 'utils/formatMoney' import {datetimeToString} from 'utils/datetimeToString' import useMediaQuery from 'utils/mediaQuery' import {mediaQueryMD} from 'assets/styles/_mediaQueries.scss' import styles from './index.module.scss' const today = new Date() let lastMonth = new Date() lastMonth = new Date(lastMonth.setMonth(today.getMonth() - 1)) export const columns = [ { key: 'name', value: 'Nome', textAlign: 'left', }, { key: 'quantity', value: 'Quantidade', textAlign: 'left', }, { key: 'price', value: 'Total', }, { key: 'user', value: 'Usuário', }, ] const buttonMobileClass = {root: {minWidth: '20px', padding: '10px 15px 9px'}} const ReportCancelationsPerUser = () => { const {showMenu} = useStore() const mediaMD = useMediaQuery('min', mediaQueryMD) const [dates, setDates] = useState({ start_date: lastMonth, end_date: today, user_id: '', }) const [cancelations, setCancelations] = useState({ results: [], count: 0, next: null, previous: null, total_value: 0, }) const [validation, setValidation] = useState({ valid: true, message: '', }) const {withLoader, loading} = useLoader() const [users, setUsers] = useState([]) const [page, setPage] = useState(1) const fetchCancelationsPerUser = useCallback( async ({start_date, end_date, user_id}, page) => { const result = await withLoader(services.getCancelationsPerUserReport({start_date, end_date, user_id}, page)) if (result.success) setCancelations(prevProducts => ({...prevProducts, ...result.data})) }, [withLoader] ) const fetchUsers = useCallback(async () => { const result = await withLoader(services.getUsers()) if (result.success) setUsers(result.data) }, [withLoader]) const loadMoreCancelationsPerUser = useCallback( async ({start_date, end_date, user_id}, page) => { const result = await withLoader(services.getCancelationsPerUserReport({start_date, end_date, user_id}, page)) if (result.success) { setCancelations(prevProducts => ({ ...prevProducts, ...result.data, results: [...prevProducts.results, ...result.data.results], })) } }, [withLoader] ) const handleButtonClick = useCallback( ({start_date, end_date, user_id}, page) => { setPage(page) fetchCancelationsPerUser({start_date, end_date, user_id}, page) }, [fetchCancelationsPerUser] ) const onChangePage = useCallback( page => { if (validation.valid) { setPage(page) fetchCancelationsPerUser({start_date: dates.start_date, end_date: dates.end_date, user_id: dates.user_id}, page) } }, [fetchCancelationsPerUser, validation.valid, dates.start_date, dates.end_date, dates.user_id] ) const onLoadMore = useCallback( page => { if (validation.valid) { setPage(page) loadMoreCancelationsPerUser({start_date: dates.start_date, end_date: dates.end_date, user_id: dates.user_id}, page) } }, [loadMoreCancelationsPerUser, validation.valid, dates.start_date, dates.end_date, dates.user_id] ) const formattedCancelations = useMemo(() => { if (cancelations && cancelations.results) { return cancelations.results.map(item => ({ name: item.product.name, created: datetimeToString(item.created), quantity: item.quantity, price: formatMoney(parseFloat(item.price)), user: `${item.user.first_name} ${item.user.last_name}`, })) } return [] }, [cancelations]) const formattedUsers = useMemo( () => users.map(user => ({ name: `${user.first_name} ${user.last_name}`, value: user.id, })), [users] ) const selectedUserName = useMemo(() => { if (formattedUsers.length && dates.user_id) { const user = formattedUsers.find(user => user.value === dates.user_id) if (user) return user.name } return '-' }, [formattedUsers, dates.user_id]) useEffect(() => { showMenu() }, [showMenu]) useEffect(() => { fetchUsers() }, [fetchUsers]) useEffect(() => { if (formattedUsers.length) { const firstUserId = formattedUsers[0].value setDates(prev => ({...prev, user_id: firstUserId})) } }, [formattedUsers]) useEffect(() => { if (!dates.start_date) { setValidation({valid: false, message: 'Data inicial é um campo obrigatório'}) } else if (isNaN(dates.start_date.getTime())) { setValidation({valid: false, message: 'Formato de Data Inicial é inválido.'}) } else if (!dates.end_date) { setValidation({valid: false, message: 'Data final é um campo obrigatório'}) } else if (isNaN(dates.end_date.getTime())) { setValidation({valid: false, message: 'Formato de Data Final é inválido.'}) } else if (dates.end_date.getTime() < dates.start_date.getTime()) { setValidation({valid: false, message: 'Data final não pode ser menor que data inicial.'}) } else { setValidation({valid: true, message: ''}) } }, [dates.start_date, dates.end_date, setValidation]) return ( <> <header className={styles.header}> <h1>Cancelamento de Pedidos por Usuário</h1> </header> <Paper className={styles.paper}> <div className={styles.search}> <div className={styles.fields}> <Datetimepicker error={!validation.valid} className={styles.field} label='Início' value={dates.start_date} helperText='' onChange={value => setDates(prevDates => ({...prevDates, start_date: value}))} /> <Datetimepicker error={!validation.valid} className={styles.field} label='Fim' value={dates.end_date} helperText='' onChange={value => setDates(prevDates => ({...prevDates, end_date: value}))} /> <div className={styles.field}> <Select label='Usuário' items={formattedUsers} value={dates.user_id} onChange={event => setDates(prevDates => ({...prevDates, user_id: event.target.value}))} /> </div> <div className={styles.searchButton}> <Button disabled={!validation.valid} classes={!mediaMD ? buttonMobileClass : {}} onClick={() => handleButtonClick({start_date: dates.start_date, end_date: dates.end_date, user_id: dates.user_id}, 1) }> {mediaMD ? 'Buscar' : <i className='fa fa-search' />} </Button> </div> </div> {!validation.valid ? ( <div className={styles.validationMessage}>{validation.message}</div> ) : ( <div className={styles.searchText}> Data inicial: <span className={styles.searchTerm}>&nbsp;{datetimeToString(dates.start_date)}</span> <br /> Data final: <span className={styles.searchTerm}>&nbsp;{datetimeToString(dates.end_date)}</span> <br /> Usuário: <span className={styles.searchTerm}>&nbsp;{selectedUserName}</span> </div> )} </div> <ResponsiveTable columns={columns} rows={formattedCancelations} titleColumn='name' emptyTableMessage='Não há produtos vendidos até o momento.' loading={loading} pagination={{count: cancelations.count, page, onChangePage, next: cancelations.next, previous: cancelations.previous}} loadMore={{count: cancelations.count, page, onLoadMore}} /> <SectionBox className={styles.totalPriceBox}>Total: {formatMoney(parseFloat(cancelations.total_value))}</SectionBox> </Paper> </> ) } export default memo(ReportCancelationsPerUser)
chr0m3/boj-codes
1/0/10828/10828.py
<filename>1/0/10828/10828.py import sys input = sys.stdin.readline count = int(input()) stack = list() for i in range(0, count): command = input().split() if command[0] == 'push': stack.append(int(command[1])) elif command[0] == 'pop': if len(stack): print(stack.pop()) else: print(-1) elif command[0] == 'size': print(len(stack)) elif command[0] == 'empty': if len(stack): print(0) else: print(1) elif command[0] == 'top': if len(stack): print(stack[len(stack)-1]) else: print(-1)
zhaomengxiao/MITK
Modules/US/USModel/mitkUSVideoDeviceCustomControls.h
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKUSVideoDeviceCustomControls_H_HEADER_INCLUDED_ #define MITKUSVideoDeviceCustomControls_H_HEADER_INCLUDED_ #include "mitkUSAbstractControlInterface.h" #include "mitkUSImageVideoSource.h" #include "mitkUSVideoDevice.h" #include <itkObjectFactory.h> namespace mitk { /** * \brief Custom controls for mitk::USVideoDevice. * Controls image cropping of the corresponding mitk::USImageVideoSource. */ class MITKUS_EXPORT USVideoDeviceCustomControls : public USAbstractControlInterface { public: mitkClassMacro(USVideoDeviceCustomControls, USAbstractControlInterface); mitkNewMacro1Param(Self, itk::SmartPointer<USDevice>); /** * Activate or deactivate the custom controls. This is just for handling * widget visibility in a GUI for example. Cropping will not be deactivated * if this method is called with false. Use * mitk::USVideoDeviceCustomControls::SetCropArea() with an empty are * instead. */ void SetIsActive(bool isActive) override; /** * \return if this custom controls are currently activated */ bool GetIsActive() override; /** * \brief Sets the area that will be cropped from the US image. * Set [0,0,0,0] to disable it, which is also default. */ void SetCropArea(USImageVideoSource::USImageCropping newArea); /** * \return area currently set for image cropping defined by the actual current probe. */ mitk::USProbe::USProbeCropping GetCropArea(); /** * \brief Updates the cropping of the current probe given by the crop area of the * USImageVideoSource. */ void UpdateProbeCropping( mitk::USImageVideoSource::USImageCropping cropping ); /** * \brief Sets a new depth value to the current probe. */ void SetNewDepth(double depth); /** * \ brief Sets new probe identifier */ void SetNewProbeIdentifier(std::string probename); /** *\brief Get all the probes for the current device */ std::vector<mitk::USProbe::Pointer> GetProbes(); /** * \brief Get the scanning dephts of the given probe */ std::vector<int> GetDepthsForProbe(std::string name); /** * \brief Sets the first existing probe or the default probe of a USVideoDevice * as the current probe of the USVideoDevice. */ void SetDefaultProbeAsCurrentProbe(); protected: /** * Class needs an mitk::USImageVideoSource object for beeing constructed. * This object will be manipulated by the custom controls methods. */ USVideoDeviceCustomControls(itk::SmartPointer<USDevice> device); ~USVideoDeviceCustomControls() override; bool m_IsActive; USImageVideoSource::Pointer m_ImageSource; }; } // namespace mitk #endif // MITKUSVideoDeviceCustomControls_H_HEADER_INCLUDED_
asakura-yoshifumi/publication20200818
at210/fun_old.py
#!/usr/bin/env python ################################################################################ # MIT License # # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ ### to define functions to run on the ode ################ ### imports ################ import numpy as np import time import sys import os import shutil import pyper #from scipy.stats import multivariate_normal as multinormal from scipy.integrate import RK45 import math import matplotlib.pyplot as plt import seaborn as sns from matplotlib import animation as ani import pandas as pd ### handwrite from .fun_dir import di1 from .fun_dir import di2 class Euler_diff: def __init__(self, fun, t0, y0, t_bound, first_step, max_step): self.fun = fun self.t = t0 self.y = y0 self.t_bound = t_bound self.status = "running" self.first_step = first_step self.max_step = max_step # self.t_old = t0 # self.step_size = first_step # def set_dt(self, dt): self.step_size = dt # def step(self): if self.status == "running": self.t_old = self.t # self.t += self.step_size self.y += self.fun(self.t, self.y) * self.step_size else: self.t = None self.y = None # if self.t >= self.t_bound: self.status = "finished" # #
axetroy/go-server
internal/app/user_server/controller/transfer/to.go
<gh_stars>100-1000 // Copyright 2019-2020 Axetroy. All rights reserved. MIT license. package transfer import ( "encoding/json" "errors" "github.com/axetroy/go-server/internal/app/user_server/controller/finance" "github.com/axetroy/go-server/internal/app/user_server/controller/wallet" "github.com/axetroy/go-server/internal/library/exception" "github.com/axetroy/go-server/internal/library/helper" "github.com/axetroy/go-server/internal/library/logger" "github.com/axetroy/go-server/internal/library/router" "github.com/axetroy/go-server/internal/library/util" "github.com/axetroy/go-server/internal/library/validator" "github.com/axetroy/go-server/internal/middleware" "github.com/axetroy/go-server/internal/model" "github.com/axetroy/go-server/internal/schema" "github.com/axetroy/go-server/internal/service/database" "github.com/jinzhu/gorm" "github.com/mitchellh/mapstructure" "strconv" "strings" "time" ) type ToParams struct { Currency string `json:"currency" validate:"required" comment:"币种"` // 币种 To string `json:"to" validate:"required,numeric" comment:"转账对象"` // 转账给谁 Amount string `json:"amount" validate:"required,numeric,gt=0" comment:"转账数量"` // 转账数量 Note *string `json:"note" validate:"omitempty" comment:"转账备注"` // 转账备注 } func To(c helper.Context, input ToParams, signature string) (res schema.Response) { var ( err error tx *gorm.DB data = schema.TransferLog{} ) defer func() { if r := recover(); r != nil { switch t := r.(type) { case string: err = errors.New(t) case error: err = t default: err = exception.Unknown } } if tx != nil { if err != nil { _ = tx.Rollback().Error } else { logger.Infof("User %s transfer %v", c.Uid, input) err = tx.Commit().Error } } helper.Response(&res, data, nil, err) }() // 参数校验 if err = validator.ValidateStruct(input); err != nil { return } // 交验签名是否正确 if b, err1 := json.Marshal(input); err != nil { err = err1 return } else { s, err2 := util.Signature(string(b)) if err2 != nil { err = err2 return } // 如果签名不一致 if s != signature { err = exception.InvalidSignature return } } tx = database.Db.Begin() fromUserInfo := model.User{Id: c.Uid} toUserInfo := model.User{Id: input.To} if err = tx.Where(&fromUserInfo).Last(&fromUserInfo).Error; err != nil { if err == gorm.ErrRecordNotFound { err = exception.UserNotExist } return } if err = tx.Where(&toUserInfo).Last(&toUserInfo).Error; err != nil { if err == gorm.ErrRecordNotFound { err = exception.UserNotExist } return } walletTableName := wallet.GetTableName(input.Currency) // 对应的钱包表名 transferTableName := GetTransferTableName(input.Currency) // 对应的转账记录表名 financeLogTableName := finance.GetTableName(input.Currency) // 对应的财务日志表名 fromUserWallet := model.Wallet{ Id: c.Uid, } toUserWallet := model.Wallet{ Id: input.To, } if err = tx.Table(walletTableName).Where("id = ?", fromUserWallet.Id).FirstOrInit(&fromUserWallet).Error; err != nil { return } if err = tx.Table(walletTableName).Where("id = ?", toUserWallet.Id).FirstOrInit(&toUserWallet).Error; err != nil { return } var amount float64 // 转账数量 if amount, err = strconv.ParseFloat(input.Amount, 64); err != nil { return } if fromUserWallet.Balance < amount { err = exception.NotEnoughBalance return } // 变动前的余额/冻结 fromUserBeforeBalance := fromUserWallet.Balance fromUserBeforeFrozen := fromUserWallet.Frozen toUserBeforeBalance := toUserWallet.Balance toUserBeforeFrozen := toUserWallet.Frozen fromUserWallet.Balance = fromUserWallet.Balance - amount // - 自己的钱包 toUserWallet.Balance = toUserWallet.Balance + amount // + 对方的钱包 // 变动后的余额/冻结 fromUserAfterBalance := fromUserWallet.Balance fromUserAfterFrozen := fromUserWallet.Frozen toUserAfterBalance := toUserWallet.Balance toUserAfterFrozen := toUserWallet.Frozen // 余额不能为负数 if fromUserWallet.Balance < 0 { err = exception.NotEnoughBalance return } // 扣除我方的钱 if err = tx.Table(walletTableName).Where("id = ?", fromUserWallet.Id).UpdateColumn("balance", fromUserWallet.Balance).Error; err != nil { return } // 给对方加钱 if err = tx.Table(walletTableName).Where("id = ?", toUserWallet.Id).UpdateColumn("balance", toUserWallet.Balance).Error; err != nil { return } // 如果转账记录的表不存在的话,那么就生成这个表 if !tx.HasTable(transferTableName) { if err = tx.CreateTable(model.TransferLogMap[strings.ToUpper(input.Currency)]).Error; err != nil { return } } transferLog := model.TransferLog{ Currency: strings.ToUpper(input.Currency), From: c.Uid, To: input.To, Status: model.TransferStatusConfirmed, Amount: util.FloatToStr(amount), // 保留 8 未小数 Note: input.Note, } if err = tx.Table(transferTableName).Create(&transferLog).Error; err != nil { return } if err = mapstructure.Decode(transferLog, &data.TransferLogPure); err != nil { return } data.CreatedAt = transferLog.CreatedAt.Format(time.RFC3339Nano) data.UpdatedAt = transferLog.UpdatedAt.Format(time.RFC3339Nano) // 如果财务日志表不存在的话, 那么就生成这个表 if !tx.HasTable(financeLogTableName) { if err = tx.CreateTable(model.FinanceLogMap[input.Currency]).Error; err != nil { return } } // 生成我的财务日志 fromUserFinanceLog := model.FinanceLog{ OrderId: transferLog.Id, // 可用余额的变动 Uid: c.Uid, BeforeBalance: fromUserBeforeBalance, BalanceMutation: -amount, AfterBalance: fromUserAfterBalance, BeforeFrozen: fromUserBeforeFrozen, // 冻结余额的变动 FrozenMutation: 0, AfterFrozen: fromUserAfterFrozen, Type: model.FinanceTypeTransferOut, } // 生成对方的财务日志 toUserFinanceLog := model.FinanceLog{ OrderId: transferLog.Id, Uid: input.To, BeforeBalance: toUserBeforeBalance, // 可用余额的变动 BalanceMutation: amount, AfterBalance: toUserAfterBalance, BeforeFrozen: toUserBeforeFrozen, // 冻结余额的变动 FrozenMutation: 0, AfterFrozen: toUserAfterFrozen, Type: model.FinanceTypeTransferIn, } if err = tx.Table(financeLogTableName).Create(&fromUserFinanceLog).Error; err != nil { return } if err = tx.Table(financeLogTableName).Create(&toUserFinanceLog).Error; err != nil { return } return } var ToRouter = router.Handler(func(c router.Context) { var ( input ToParams ) // 获取数据签名 signature := c.GetHeader(middleware.SignatureHeader) c.ResponseFunc(c.ShouldBindJSON(&input), func() schema.Response { return To(helper.NewContext(&c), input, signature) }) })
Peter-Liang/LeetCode-Solutions
solutions/2020-May-30-day-leetcoding-challenge/5.First-Unique-Character-in-a-String.js
<reponame>Peter-Liang/LeetCode-Solutions<filename>solutions/2020-May-30-day-leetcoding-challenge/5.First-Unique-Character-in-a-String.js /** * @param {string} s * @return {number} */ var firstUniqChar = function (s) { const chars = Array.prototype.reduce.call( s, (p, c) => { if (p[c] == null) p[c] = 0; p[c]++; return p; }, {} ); for (let i = 0; i < s.length; i++) { if (chars[s[i]] > 1) continue; return i; } return -1; };
jonseddon/primavera-dmt
scripts/utils/fix_failed_et.py
<reponame>jonseddon/primavera-dmt #!/usr/bin/env python """ fix_failed_et.py Elastic tape retrievals occasionally fail when a significant way through a large retrieval. This script identfies files in this specified retrieval, checks their checksum and if they are fine then copies them into the DRS directory structure and updates the file's status in the DMT. """ import argparse import logging.config import os import sys import django django.setup() from pdata_app.models import DataFile, Settings from pdata_app.utils.common import (adler32, construct_drs_path, get_gws_any_dir, ilist_files, is_same_gws) __version__ = '0.1.0b' DEFAULT_LOG_LEVEL = logging.WARNING DEFAULT_LOG_FORMAT = '%(levelname)s: %(message)s' logger = logging.getLogger(__name__) def parse_args(): """ Parse command-line arguments """ parser = argparse.ArgumentParser(description='Check extracted data and ' 'move to DRS.') parser.add_argument('top_dir', help='The top-level directory to search ' 'for files') parser.add_argument('-l', '--log-level', help='set logging level to one of ' 'debug, info, warn (the ' 'default), or error') parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__)) args = parser.parse_args() return args def main(args): """Main entry point""" base_dir = Settings.get_solo().base_output_dir for extracted_file in ilist_files(args.top_dir): found_name = os.path.basename(extracted_file) try: data_file = DataFile.objects.get(name=found_name) except django.core.exceptions.ObjectDoesNotExist: logger.warning('Cannot find DMT entry. Skipping {}'. format(extracted_file)) continue found_checksum = adler32(extracted_file) if not found_checksum == data_file.checksum_set.first().checksum_value: logger.warning("Checksum doesn't match. Skipping {}". format(found_name)) continue dest_dir = os.path.join(get_gws_any_dir(extracted_file), 'stream1', construct_drs_path(data_file)) dest_path = os.path.join(dest_dir, found_name) if os.path.exists(dest_path): logger.warning('Skipping {} as it already exists at {}'. format(found_name, dest_path)) continue # create the directory if it doesn't exist if not os.path.exists(dest_dir): os.makedirs(dest_dir) os.rename(extracted_file, dest_path) # create a link from the base dir if not is_same_gws(dest_path, base_dir): link_dir = os.path.join(base_dir, construct_drs_path(data_file)) link_path = os.path.join(link_dir, data_file.name) if not os.path.exists(link_dir): os.makedirs(link_dir) os.symlink(dest_path, link_path) data_file.online = True data_file.directory = dest_dir data_file.save() if __name__ == "__main__": cmd_args = parse_args() # determine the log level if cmd_args.log_level: try: log_level = getattr(logging, cmd_args.log_level.upper()) except AttributeError: logger.setLevel(logging.WARNING) logger.error('log-level must be one of: debug, info, warn or error') sys.exit(1) else: log_level = DEFAULT_LOG_LEVEL # configure the logger logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': DEFAULT_LOG_FORMAT, }, }, 'handlers': { 'default': { 'level': log_level, 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { '': { 'handlers': ['default'], 'level': log_level, 'propagate': True } } }) # run the code main(cmd_args)
JDevlieghere/MAS
rinsim/src/main/java/rinde/sim/examples/pdptw/gradientfield/Truck.java
package rinde.sim.examples.pdptw.gradientfield; import java.util.Map; import javax.annotation.Nullable; import rinde.sim.core.TimeLapse; import rinde.sim.core.graph.Point; import rinde.sim.core.model.pdp.PDPModel; import rinde.sim.core.model.pdp.PDPModel.ParcelState; import rinde.sim.core.model.pdp.PDPModel.VehicleState; import rinde.sim.core.model.pdp.Parcel; import rinde.sim.core.model.road.RoadModel; import rinde.sim.core.model.road.RoadModels; import rinde.sim.core.model.road.RoadUser; import rinde.sim.pdptw.common.DefaultParcel; import rinde.sim.pdptw.common.DefaultVehicle; import rinde.sim.pdptw.common.VehicleDTO; import com.google.common.base.Predicate; class Truck extends DefaultVehicle implements FieldEmitter { private GradientModel gradientModel; public Truck(VehicleDTO pDto) { super(pDto); } @Override protected void tickImpl(TimeLapse time) { // Check if we can deliver nearby final Parcel delivery = getDelivery(time, 5); final RoadModel rm = roadModel.get(); final PDPModel pm = pdpModel.get(); if (delivery != null) { if (delivery.getDestination().equals(getPosition()) && pm.getVehicleState(this) == VehicleState.IDLE) { pm.deliver(this, delivery, time); } else { rm.moveTo(this, delivery.getDestination(), time); } return; } // Otherwise, Check if we can pickup nearby final DefaultParcel closest = (DefaultParcel) RoadModels.findClosestObject( rm.getPosition(this), rm, new Predicate<RoadUser>() { @Override public boolean apply(RoadUser input) { return input instanceof DefaultParcel && pm.getParcelState(((DefaultParcel) input)) == ParcelState.AVAILABLE; } }); if (closest != null && Point.distance(rm.getPosition(closest), getPosition()) < 10) { if (rm.equalPosition(closest, this) && pm.getTimeWindowPolicy().canPickup(closest.getPickupTimeWindow(), time.getTime(), closest.getPickupDuration())) { final double newSize = getPDPModel().getContentsSize(this) + closest.getMagnitude(); if (newSize <= getCapacity()) { pm.pickup(this, closest, time); } } else { rm.moveTo(this, rm.getPosition(closest), time); } return; } if (rm.getObjectsOfType(Parcel.class).isEmpty()) { rm.moveTo(this, dto.startPosition, time); return; } // If none of the above, let the gradient field guide us! @Nullable final Point p = gradientModel.getTargetFor(this); if (p != null) { rm.moveTo(this, p, time); } } @Nullable public Parcel getDelivery(TimeLapse time, int distance) { Parcel target = null; double closest = distance; final PDPModel pm = pdpModel.get(); for (final Parcel p : pm.getContents(this)) { final double dist = Point.distance(roadModel.get().getPosition(this), p.getDestination()); if (dist < closest && pm.getTimeWindowPolicy().canDeliver(p.getDeliveryTimeWindow(), time.getTime(), p.getPickupDuration())) { closest = dist; target = p; } } return target; } @Override public void setModel(GradientModel model) { gradientModel = model; } @Override public Point getPosition() { return roadModel.get().getPosition(this); } @Override public float getStrength() { return -1; } public Map<Point, Float> getFields() { return gradientModel.getFields(this); } }
GliderWinchItems/embed
svn_sensor/sensor/se1/trunk/tick_pod6.c
/******************** (C) COPYRIGHT 2013 ************************************** * File Name : tick_pod.c * Hackerees : deh * Date First Issued : 02/16/2013 * Board : STM32F103VxT6_pod_mm * Description : Post SYSTICK interrupt handling *******************************************************************************/ /* This routine is entered following a SYSTICK interrupt. The SYSTICK interrupt signals the end|start of a 1/64th sec interval. This is the reference point for the measurements, and as such the measurement is "closed out," calculations made, and a CAN messages send. The SYSTICK interrupt handling is done at high priority, where the time duration for the next interval is adjusted/updated, followed by triggering a low priority interrupt. The low priority interrupt calls a function via a pointer. The 'init' in this routine sets that pointer to point to the routine that continues the remainder of the setup. but at a priority that is higher than the polling loop of 'main', but lower that the CAN and other time dependent operations. */ #include "common_can.h" #include "canwinch_pod_common_systick2048.h" #include "se1.h" /* ==== test ======= */ static struct CANRCVBUF can_msg_shaft; static struct CANRCVBUF can_msg_speed; /* Pointer to next routine if these are chained */ // FIFO 1 -> I2C1_EV -> CAN_sync() -> I2C2_EV (very low priority) -> Here -> Next (or return) void (*Continuation_of_I2C2_EV_IRQHandler_ptr)(void) = 0; /* Error counter */ u32 can_msgovrflow = 0; // Count times xmt buffer was full /* Subroutine prototypes */ void Continuation_of_I2C2_EV_IRQHandler(void); /****************************************************************************** * void tick_pod6_init(void); * @brief : Enable preparation and CAN xmt of measurement *******************************************************************************/ void tick_pod6_init(void) { /* === test ==== */ can_msg_shaft.id = IAMUNITNUMBER | (CAN_DATAID_POD6_SHAFT << CAN_DATAID_SHIFT); can_msg_speed.id = IAMUNITNUMBER | (CAN_DATAID_POD6_SPEED << CAN_DATAID_SHIFT); /* Set address to routine to handle end-of-interval */ systickLOpriority2_ptr = &Continuation_of_I2C2_EV_IRQHandler; return; } /****************************************************************************** * void tick_send(struct CANRCVBUF * p); * @param : p = pointer to message to send * @brief : send CAN msg *******************************************************************************/ void tick_send(struct CANRCVBUF * p) { /* Prepare CAN msg */ // can_msg_rcv_compress(p); // Set byte count: according to MSB can_msg_setsize_sys(p, 8); // Set byte count: Fixed xmt /* Setup CAN msg in output buffer/queue */ if ( can_msg_put_sys(p) <= 0) can_msgovrflow += 1; return; } /*######################### WARNING UNDER INTERRUPT ##################################### * Continuation of I2C2_EV_IRQHandler (which was triggered by SYSTICK_IRQHandler * Complete any measurement wrapup and send CAN msg to CO logger & others *####################################################################################### */ static u32 throttleLED; u8 LEDflg = 0; void Continuation_of_I2C2_EV_IRQHandler(void) { /* ==== test ======= */ throttleLED += 1; if (throttleLED >= 64) { throttleLED = 0; LEDflg = 1; } /* Prepare & send CAN msg */ tick_send(&can_msg_shaft); can_msg_shaft.cd.ui[0] += 1; // Make the msg change for the next round /* Prepare & send CAN msg */ tick_send(&can_msg_speed); can_msg_speed.cd.ui[0] += 1; // Make the msg change for the next round /* ==== end test ======= */ /* Call other routines if an address is set up */ if (Continuation_of_I2C2_EV_IRQHandler_ptr != 0) // Having no address for the following is bad. (*Continuation_of_I2C2_EV_IRQHandler_ptr)(); // Go do something return; }
zyzisyz/OJ
hdu_oj/1003.cpp
/************************************************************************* > File Name: 1003.cpp > Author: <NAME> > Mail: <EMAIL> > Created Time: Tue 31 Dec 2019 06:19:59 PM CST ************************************************************************/ #include<iostream> #include<vector> using namespace std; void solve(int size, vector<int> num){ vector<int> sum(size); vector<int> start(size); sum[0] = num[0]; start[0] = 0; for(int i=1; i<size; i++){ int temp = num[i] + sum[i-1]; if(temp>=num[i]){ sum[i] = temp; start[i] = start[i-1]; }else{ sum[i] = num[i]; start[i] = i; } } //test //cout<<"num: "; //for(auto item : num){ // cout<<item<<" "; //} //cout<<endl; //cout<<"sum: "; //for(auto item : sum){ // cout<<item<<" "; //} //cout<<endl; int max_index = 0; for(int i=1; i<size; i++){ if(sum[max_index] < sum[i]) max_index = i; } cout<<sum[max_index]<<" "<<start[max_index]+1<<" "<<max_index+1<<endl; } int main(void){ int n; cin>>n; for(int i=0; i<n; i++){ int size; cin>>size; vector<int> num(size); for(int j=0; j<size; j++){ cin>>num[j]; } cout<<"Case "<<i+1<<":"<<endl; solve(size, num); if(i<n-1) cout<<endl; } }
mcuadrai/votekin
src/main/java/com/forum/domain/Region.java
package com.forum.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="region") public class Region implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id private Long codigo; @Column private String nombre; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Long getCodigo() { return codigo; } public void setCodigo(Long codigo) { this.codigo = codigo; } }
kiranmai-sfdev/aura
aura-components/src/test/components/uitest/input_themeingTest/input_themeingTestRenderer.js
({ afterRender : function(cmp){ cmp.find("inputTextBoxFocusable").getElement().focus(); cmp.find("inputTextBoxFocusable").getElement().select(); this.superAfterRender(); } })
SNL-GMS/GMS-PI7-OPEN
gms-common/java/gms/shared/mechanisms/object-storage-distribution/osd-channelsegments-repository-service/src/main/java/gms/shared/mechanisms/objectstoragedistribution/coi/channelsegments/service/Application.java
package gms.shared.mechanisms.objectstoragedistribution.coi.channelsegments.service; import gms.shared.mechanisms.objectstoragedistribution.coi.channelsegments.repository.ChannelSegmentsRepository; import gms.shared.mechanisms.objectstoragedistribution.coi.channelsegments.repository.jpa.ChannelSegmentsRepositoryJpa; import gms.shared.mechanisms.objectstoragedistribution.coi.common.datatransferobjects.CoiObjectMapperFactory; import gms.shared.mechanisms.objectstoragedistribution.coi.common.repository.CoiEntityManagerFactory; import gms.shared.mechanisms.objectstoragedistribution.coi.waveforms.repository.cassandra.JpaCassandraWaveformRepository; import gms.shared.mechanisms.objectstoragedistribution.coi.waveforms.repository.cassandra.configuration.CassandraConfig; import gms.shared.mechanisms.objectstoragedistribution.coi.waveforms.repository.jpa.FkSpectraRepositoryJpa; import gms.shared.utilities.service.HttpService; import gms.shared.utilities.service.Route; import gms.shared.utilities.service.ServiceDefinition; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.persistence.EntityManagerFactory; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.EnvironmentConfiguration; import org.apache.commons.configuration.PropertiesConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Application { /** * Starts the application with default parameters. * * @param args N/A */ public static void main(String[] args) { new HttpService(getHttpServiceDefinition(8080)).start(); } /** * Return the service definition. * * @param port port number * @return service definition */ private static ServiceDefinition getHttpServiceDefinition(int port) { Logger logger = LoggerFactory.getLogger(Application.class); Configuration config; try { config = Application.loadConfig(); } catch (ConfigurationException e) { logger.error(String.format("Cannot start application - failed to load configuration: %s", e.getMessage())); throw new IllegalStateException(e); } EntityManagerFactory entityManagerFactory = CoiEntityManagerFactory.create(loadHibernateConfig(config)); CassandraConfig cassandraConfig = Application.loadCassandraConfig(config); ChannelSegmentsRepository channelSegmentsRepository = ChannelSegmentsRepositoryJpa.create( entityManagerFactory, new JpaCassandraWaveformRepository(entityManagerFactory, cassandraConfig), new FkSpectraRepositoryJpa(entityManagerFactory, cassandraConfig) ); RequestHandlers handlers = RequestHandlers.create(channelSegmentsRepository); return ServiceDefinition.builder() .setJsonMapper(CoiObjectMapperFactory.getJsonObjectMapper()) .setMsgpackMapper(CoiObjectMapperFactory.getMsgpackObjectMapper()) .setRoutes(Set.of( Route.create( "/is-alive", handlers::isAlive), Route.create( "/coi/channel-segments/query/segment-ids", handlers::retrieveBySegmentIds ), Route.create( "/coi/channel-segments/query/channel-ids", handlers::retrieveByChannelIdsAndTime) )) .setPort(port) .build(); } private static CompositeConfiguration loadConfig() throws ConfigurationException { CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new EnvironmentConfiguration()); config.addConfiguration(new PropertiesConfiguration( "gms/shared/mechanisms/objectstoragedistribution/coi/channelsegments/service/application.properties")); return config; } private static Map<String, String> loadHibernateConfig(Configuration configuration) { String coiServiceHost = configuration.getString("persistence_url"); if (Objects.nonNull(coiServiceHost)) { return Map.ofEntries(Map.entry("hibernate.connection.url", coiServiceHost)); } else { return Map.of(); } } private static CassandraConfig loadCassandraConfig(Configuration configuration) { String cassandraUrl = configuration.getString("cassandra_url"); CassandraConfig.Builder cassandraConfigBuilder = CassandraConfig.builder(); if (Objects.nonNull(cassandraUrl)) { String[] cassandraHostAndPort = cassandraUrl.split(":"); if (cassandraHostAndPort.length != 2) { throw new IllegalArgumentException( "\"cassandra_url\" is not in the correct format, should be: <hostname>:<port>"); } String cassandraHost = cassandraHostAndPort[0]; int cassandraPort = Integer.parseInt(cassandraHostAndPort[1]); cassandraConfigBuilder.setConnectPoints(cassandraHost).setPort(cassandraPort); } return cassandraConfigBuilder.build(); } }
fossabot/evemonk
db/migrate/20191015202332_create_eve_icons.rb
<gh_stars>10-100 # frozen_string_literal: true class CreateEveIcons < ActiveRecord::Migration[6.0] def change create_table :eve_icons do |t| t.integer :icon_id t.text :description t.string :icon_file t.boolean :obsolete t.string :backgrounds, array: true t.string :foregrounds, array: true t.timestamps end end end
jarocho105/pre2
erp_desktop_all/src_nomina/com/bydan/erp/nomina/presentation/swing/jinternalframes/TipoColegioProfeDetalleFormJInternalFrame.java
<filename>erp_desktop_all/src_nomina/com/bydan/erp/nomina/presentation/swing/jinternalframes/TipoColegioProfeDetalleFormJInternalFrame.java<gh_stars>1-10 /* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.nomina.presentation.swing.jinternalframes; import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*; import com.bydan.erp.nomina.presentation.web.jsf.sessionbean.*;//; import com.bydan.erp.nomina.presentation.swing.jinternalframes.*; import com.bydan.erp.nomina.presentation.swing.jinternalframes.auxiliar.*; import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*; //import com.bydan.erp.nomina.presentation.report.source.*; import com.bydan.framework.erp.business.entity.Reporte; import com.bydan.erp.seguridad.business.entity.Modulo; import com.bydan.erp.seguridad.business.entity.Opcion; import com.bydan.erp.seguridad.business.entity.Usuario; import com.bydan.erp.seguridad.business.entity.ResumenUsuario; import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg; import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario; import com.bydan.erp.seguridad.util.SistemaParameterReturnGeneral; import com.bydan.erp.nomina.business.entity.*; import com.bydan.erp.nomina.util.TipoColegioProfeConstantesFunciones; import com.bydan.erp.nomina.business.logic.*; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.OrderBy; import com.bydan.framework.erp.business.entity.Mensajes; import com.bydan.framework.erp.business.logic.*; import com.bydan.framework.erp.presentation.desktop.swing.DateConverter; import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate; import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing; import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase; import com.bydan.framework.erp.presentation.desktop.swing.*; import com.bydan.framework.erp.util.*; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.io.File; import java.util.HashMap; import java.util.Map; import java.io.PrintWriter; import java.sql.SQLException; import java.sql.*; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.data.JRBeanArrayDataSource; import javax.swing.*; import java.awt.*; import javax.swing.border.EtchedBorder; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import java.awt.event.*; import javax.swing.event.*; import javax.swing.GroupLayout.Alignment; import javax.swing.table.TableColumn; import com.toedter.calendar.JDateChooser; @SuppressWarnings("unused") public class TipoColegioProfeDetalleFormJInternalFrame extends TipoColegioProfeBeanSwingJInternalFrameAdditional { private static final long serialVersionUID = 1L; public JToolBar jTtoolBarDetalleTipoColegioProfe; protected JMenuBar jmenuBarDetalleTipoColegioProfe; protected JMenu jmenuDetalleTipoColegioProfe; protected JMenu jmenuDetalleArchivoTipoColegioProfe; protected JMenu jmenuDetalleAccionesTipoColegioProfe; protected JMenu jmenuDetalleDatosTipoColegioProfe; protected JPanel jContentPane = null; protected JPanel jContentPaneDetalleTipoColegioProfe = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel(); protected GridBagLayout gridaBagLayoutTipoColegioProfe; protected GridBagConstraints gridBagConstraintsTipoColegioProfe; //protected JInternalFrameBase jInternalFrameParent; //ESTA EN BASE //protected TipoColegioProfeBeanSwingJInternalFrameAdditional jInternalFrameDetalleTipoColegioProfe; //VENTANAS PARA ACTUALIZAR Y BUSCAR FK protected EmpresaBeanSwingJInternalFrame empresaBeanSwingJInternalFrame; public String sFinalQueryGeneral_empresa=""; public TipoColegioProfeSessionBean tipocolegioprofeSessionBean; public EmpresaSessionBean empresaSessionBean; public TipoColegioProfeLogic tipocolegioprofeLogic; public JScrollPane jScrollPanelDatosTipoColegioProfe; public JScrollPane jScrollPanelDatosEdicionTipoColegioProfe; public JScrollPane jScrollPanelDatosGeneralTipoColegioProfe; protected JPanel jPanelCamposTipoColegioProfe; protected JPanel jPanelCamposOcultosTipoColegioProfe; protected JPanel jPanelAccionesTipoColegioProfe; protected JPanel jPanelAccionesFormularioTipoColegioProfe; protected Integer iXPanelCamposTipoColegioProfe=0; protected Integer iYPanelCamposTipoColegioProfe=0; protected Integer iXPanelCamposOcultosTipoColegioProfe=0; protected Integer iYPanelCamposOcultosTipoColegioProfe=0; ; ; //ELEMENTOS TABLAS PARAMETOS //ELEMENTOS TABLAS PARAMETOS_FIN public JButton jButtonNuevoTipoColegioProfe; public JButton jButtonModificarTipoColegioProfe; public JButton jButtonActualizarTipoColegioProfe; public JButton jButtonEliminarTipoColegioProfe; public JButton jButtonCancelarTipoColegioProfe; public JButton jButtonGuardarCambiosTipoColegioProfe; public JButton jButtonGuardarCambiosTablaTipoColegioProfe; protected JButton jButtonCerrarTipoColegioProfe; protected JButton jButtonProcesarInformacionTipoColegioProfe; protected JCheckBox jCheckBoxPostAccionNuevoTipoColegioProfe; protected JCheckBox jCheckBoxPostAccionSinCerrarTipoColegioProfe; protected JCheckBox jCheckBoxPostAccionSinMensajeTipoColegioProfe; //TOOLBAR protected JButton jButtonNuevoToolBarTipoColegioProfe; protected JButton jButtonModificarToolBarTipoColegioProfe; protected JButton jButtonActualizarToolBarTipoColegioProfe; protected JButton jButtonEliminarToolBarTipoColegioProfe; protected JButton jButtonCancelarToolBarTipoColegioProfe; protected JButton jButtonGuardarCambiosToolBarTipoColegioProfe; protected JButton jButtonGuardarCambiosTablaToolBarTipoColegioProfe; protected JButton jButtonMostrarOcultarTablaToolBarTipoColegioProfe; protected JButton jButtonCerrarToolBarTipoColegioProfe; protected JButton jButtonProcesarInformacionToolBarTipoColegioProfe; //TOOLBAR //MENU protected JMenuItem jMenuItemNuevoTipoColegioProfe; protected JMenuItem jMenuItemModificarTipoColegioProfe; protected JMenuItem jMenuItemActualizarTipoColegioProfe; protected JMenuItem jMenuItemEliminarTipoColegioProfe; protected JMenuItem jMenuItemCancelarTipoColegioProfe; protected JMenuItem jMenuItemGuardarCambiosTipoColegioProfe; protected JMenuItem jMenuItemGuardarCambiosTablaTipoColegioProfe; protected JMenuItem jMenuItemCerrarTipoColegioProfe; protected JMenuItem jMenuItemDetalleCerrarTipoColegioProfe; protected JMenuItem jMenuItemDetalleMostarOcultarTipoColegioProfe; protected JMenuItem jMenuItemProcesarInformacionTipoColegioProfe; protected JMenuItem jMenuItemNuevoGuardarCambiosTipoColegioProfe; protected JMenuItem jMenuItemMostrarOcultarTipoColegioProfe; //MENU protected JLabel jLabelAccionesTipoColegioProfe; @SuppressWarnings("rawtypes") protected JComboBox jComboBoxTiposRelacionesTipoColegioProfe; @SuppressWarnings("rawtypes") protected JComboBox jComboBoxTiposAccionesTipoColegioProfe; @SuppressWarnings("rawtypes") public JComboBox jComboBoxTiposAccionesFormularioTipoColegioProfe; protected Boolean conMaximoRelaciones=true; protected Boolean conFuncionalidadRelaciones=true; public Boolean conCargarMinimo=false; public Boolean conMostrarAccionesCampo=false; public Boolean permiteRecargarForm=false;//PARA NUEVO PREPARAR Y MANEJO DE EVENTOS, EVITAR QUE SE EJECUTE AL CARGAR VENTANA O LOAD public Boolean conCargarFormDetalle=false; public JPanel jPanelidTipoColegioProfe; public JLabel jLabelIdTipoColegioProfe; public JLabel jLabelidTipoColegioProfe; public JButton jButtonidTipoColegioProfeBusqueda= new JButtonMe(); public JPanel jPanelcodigoTipoColegioProfe; public JLabel jLabelcodigoTipoColegioProfe; public JTextField jTextFieldcodigoTipoColegioProfe; public JButton jButtoncodigoTipoColegioProfeBusqueda= new JButtonMe(); public JPanel jPanelnombreTipoColegioProfe; public JLabel jLabelnombreTipoColegioProfe; public JTextArea jTextAreanombreTipoColegioProfe; public JScrollPane jscrollPanenombreTipoColegioProfe; public JButton jButtonnombreTipoColegioProfeBusqueda= new JButtonMe(); public JPanel jPanelid_empresaTipoColegioProfe; public JLabel jLabelid_empresaTipoColegioProfe; @SuppressWarnings("rawtypes") public JComboBox jComboBoxid_empresaTipoColegioProfe; public JButton jButtonid_empresaTipoColegioProfe= new JButtonMe(); public JButton jButtonid_empresaTipoColegioProfeUpdate= new JButtonMe(); public JButton jButtonid_empresaTipoColegioProfeBusqueda= new JButtonMe(); //ELEMENTOS TABLAS PARAMETOS //ELEMENTOS TABLAS PARAMETOS_FIN protected JTabbedPane jTabbedPaneRelacionesTipoColegioProfe; public static int openFrameCount = 0; public static final int xOffset = 10, yOffset = 35; //LOS DATOS DE NUEVO Y EDICION ACTUAL APARECEN EN OTRA VENTANA(true) O NO(false) public static Boolean CON_DATOS_FRAME=true; public static Boolean ISBINDING_MANUAL=true; public static Boolean ISLOAD_FKLOTE=true; public static Boolean ISBINDING_MANUAL_TABLA=true; public static Boolean CON_CARGAR_MEMORIA_INICIAL=true; //Al final no se utilizan, se inicializan desde JInternalFrameBase, desde ParametroGeneralUsuario public static String STIPO_TAMANIO_GENERAL="NORMAL"; public static String STIPO_TAMANIO_GENERAL_TABLA="NORMAL"; public static Boolean CONTIPO_TAMANIO_MANUAL=false; public static Boolean CON_LLAMADA_SIMPLE=true; public static Boolean CON_LLAMADA_SIMPLE_TOTAL=true; public static Boolean ESTA_CARGADO_PORPARTE=false; public int iWidthScroll=0;//(screenSize.width-screenSize.width/2)+(250*0); public int iHeightScroll=0;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO); public int iWidthFormulario=450;//(screenSize.width-screenSize.width/2)+(250*0); public int iHeightFormulario=418;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO); public int iHeightFormularioMaximo=0; public int iWidthFormularioMaximo=0; public int iWidthTableDefinicion=0; public double dStart = 0; public double dEnd = 0; public double dDif = 0; public SistemaParameterReturnGeneral sistemaReturnGeneral; public List<Opcion> opcionsRelacionadas=new ArrayList<Opcion>(); public TipoColegioProfeDetalleFormJInternalFrame(String sTipo) throws Exception { super(PaginaTipo.FORMULARIO); try { if(sTipo.equals("MINIMO")) { /* this.jPanelCamposTipoColegioProfe=new JPanel(); this.jPanelAccionesFormularioTipoColegioProfe=new JPanel(); this.jmenuBarDetalleTipoColegioProfe=new JMenuBar(); this.jTtoolBarDetalleTipoColegioProfe=new JToolBar(); */ } } catch(Exception e) { FuncionesSwing.manageException(this, e, null); } } public TipoColegioProfeDetalleFormJInternalFrame(PaginaTipo paginaTipo) throws Exception { super(paginaTipo); //super("TipoColegioProfe No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable try { Boolean cargarRelaciones=false; this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,PaginaTipo.PRINCIPAL); } catch(Exception e) { FuncionesSwing.manageException(this, e, null); } } //ES AUXILIAR PARA WINDOWS FORMS public TipoColegioProfeDetalleFormJInternalFrame() throws Exception { super(PaginaTipo.FORMULARIO); //super("TipoColegioProfe No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable try { Boolean cargarRelaciones=false; this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,PaginaTipo.PRINCIPAL); } catch(Exception e) { FuncionesSwing.manageException(this, e, null); } } public TipoColegioProfeDetalleFormJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception { super(paginaTipo); //super("TipoColegioProfe No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable try { this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,paginaTipo); } catch(Exception e) { FuncionesSwing.manageException(this, e, null); } } public TipoColegioProfeDetalleFormJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception { super(paginaTipo); //super("TipoColegioProfe No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable try { this.initialize(null,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,null,null,null,null,null,null,paginaTipo); } catch(Exception e) { FuncionesSwing.manageException(this, e, null); } } public TipoColegioProfeDetalleFormJInternalFrame(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception { super(paginaTipo);//,jdesktopPane this.jDesktopPane=jdesktopPane; this.dStart=(double)System.currentTimeMillis(); //super("TipoColegioProfe No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable try { long start_time=0; long end_time=0; if(Constantes2.ISDEVELOPING2) { start_time = System.currentTimeMillis(); } this.initialize(jdesktopPane,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo); if(Constantes2.ISDEVELOPING2) { end_time = System.currentTimeMillis(); String sTipo="Clase Padre Ventana"; Funciones2.getMensajeTiempoEjecucion(start_time, end_time, sTipo,false); } } catch(Exception e) { FuncionesSwing.manageException(this, e, null); } } public JInternalFrameBase getJInternalFrameParent() { return jInternalFrameParent; } public void setJInternalFrameParent(JInternalFrameBase internalFrameParent) { jInternalFrameParent = internalFrameParent; } public JButton getjButtonActualizarToolBarTipoColegioProfe() { return this.jButtonActualizarToolBarTipoColegioProfe; } public JButton getjButtonEliminarToolBarTipoColegioProfe() { return this.jButtonEliminarToolBarTipoColegioProfe; } public JButton getjButtonCancelarToolBarTipoColegioProfe() { return this.jButtonCancelarToolBarTipoColegioProfe; } public JButton getjButtonProcesarInformacionTipoColegioProfe() { return this.jButtonProcesarInformacionTipoColegioProfe; } public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionTipoColegioProfe) { this.jButtonProcesarInformacionTipoColegioProfe = jButtonProcesarInformacionTipoColegioProfe; } @SuppressWarnings("rawtypes") public JComboBox getjComboBoxTiposAccionesTipoColegioProfe() { return this.jComboBoxTiposAccionesTipoColegioProfe; } @SuppressWarnings("rawtypes") public void setjComboBoxTiposRelacionesTipoColegioProfe( JComboBox jComboBoxTiposRelacionesTipoColegioProfe) { this.jComboBoxTiposRelacionesTipoColegioProfe = jComboBoxTiposRelacionesTipoColegioProfe; } @SuppressWarnings("rawtypes") public void setjComboBoxTiposAccionesTipoColegioProfe( JComboBox jComboBoxTiposAccionesTipoColegioProfe) { this.jComboBoxTiposAccionesTipoColegioProfe = jComboBoxTiposAccionesTipoColegioProfe; } @SuppressWarnings("rawtypes") public JComboBox getjComboBoxTiposAccionesFormularioTipoColegioProfe() { return this.jComboBoxTiposAccionesFormularioTipoColegioProfe; } @SuppressWarnings("rawtypes") public void setjComboBoxTiposAccionesFormularioTipoColegioProfe( JComboBox jComboBoxTiposAccionesFormularioTipoColegioProfe) { this.jComboBoxTiposAccionesFormularioTipoColegioProfe = jComboBoxTiposAccionesFormularioTipoColegioProfe; } private void initialize(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception { this.tipocolegioprofeSessionBean=new TipoColegioProfeSessionBean(); this.tipocolegioprofeSessionBean.setConGuardarRelaciones(conGuardarRelaciones); this.tipocolegioprofeSessionBean.setEsGuardarRelacionado(esGuardarRelacionado); this.conCargarMinimo=this.tipocolegioprofeSessionBean.getEsGuardarRelacionado(); this.conMostrarAccionesCampo=parametroGeneralUsuario.getcon_mostrar_acciones_campo_general() || opcionActual.getcon_mostrar_acciones_campo(); if(!this.conCargarMinimo) { } this.sTipoTamanioGeneral=FuncionesSwing.getTipoTamanioGeneral(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado); this.sTipoTamanioGeneralTabla=FuncionesSwing.getTipoTamanioGeneralTabla(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado); this.conTipoTamanioManual=FuncionesSwing.getConTipoTamanioManual(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado); this.conTipoTamanioTodo=FuncionesSwing.getConTipoTamanioTodo(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado); TipoColegioProfeJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral; TipoColegioProfeJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla; TipoColegioProfeJInternalFrame.CONTIPO_TAMANIO_MANUAL=this.conTipoTamanioManual; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int iWidth=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO); int iHeight=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO); //this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.opcionActual,this.usuarioActual,"Tipo Colegio Profe MANTENIMIENTO")); if(iWidth > 650) { iWidth=650; } if(iHeight > 660) { iHeight=660; } this.setSize(iWidth,iHeight); this.setFrameIcon(new ImageIcon(FuncionesSwing.getImagenBackground(Constantes2.S_ICON_IMAGE))); this.setContentPane(this.getJContentPane(iWidth,iHeight,jdesktopPane,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo)); if(!this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()) { this.setResizable(true); this.setClosable(true); this.setMaximizable(true); this.iconable=true; setLocation(xOffset*openFrameCount, yOffset*openFrameCount); if(Constantes.CON_VARIAS_VENTANAS) { openFrameCount++; if(openFrameCount==Constantes.INUM_MAX_VENTANAS) { openFrameCount=0; } } } TipoColegioProfeJInternalFrame.ESTA_CARGADO_PORPARTE=true; } public void inicializarToolBar() { this.jTtoolBarDetalleTipoColegioProfe= new JToolBar("MENU DATOS"); //TOOLBAR //PRINCIPAL this.jButtonProcesarInformacionToolBarTipoColegioProfe=new JButtonMe(); this.jButtonModificarToolBarTipoColegioProfe=new JButtonMe(); //PRINCIPAL //DETALLE this.jButtonActualizarToolBarTipoColegioProfe=FuncionesSwing.getButtonToolBarGeneral(this.jButtonActualizarToolBarTipoColegioProfe,this.jTtoolBarDetalleTipoColegioProfe, "actualizar","actualizar","Actualizar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"),"Actualizar",false); this.jButtonEliminarToolBarTipoColegioProfe=FuncionesSwing.getButtonToolBarGeneral(this.jButtonEliminarToolBarTipoColegioProfe,this.jTtoolBarDetalleTipoColegioProfe, "eliminar","eliminar","Eliminar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"),"Eliminar",false); this.jButtonCancelarToolBarTipoColegioProfe=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCancelarToolBarTipoColegioProfe,this.jTtoolBarDetalleTipoColegioProfe, "cancelar","cancelar","Cancelar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"),"Cancelar",false); this.jButtonGuardarCambiosToolBarTipoColegioProfe=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosToolBarTipoColegioProfe,this.jTtoolBarDetalleTipoColegioProfe, "guardarcambios","guardarcambios","Guardar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false); FuncionesSwing.setBoldButtonToolBar(this.jButtonActualizarToolBarTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldButtonToolBar(this.jButtonEliminarToolBarTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldButtonToolBar(this.jButtonCancelarToolBarTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); } public void cargarMenus() { this.jmenuBarDetalleTipoColegioProfe=new JMenuBarMe(); //DETALLE this.jmenuDetalleTipoColegioProfe=new JMenuMe("Datos Relacionados"); this.jmenuDetalleArchivoTipoColegioProfe=new JMenuMe("Archivo"); this.jmenuDetalleAccionesTipoColegioProfe=new JMenuMe("Acciones"); this.jmenuDetalleDatosTipoColegioProfe=new JMenuMe("Datos"); //DETALLE_FIN this.jMenuItemNuevoTipoColegioProfe= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO")); this.jMenuItemNuevoTipoColegioProfe.setActionCommand("Nuevo"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoTipoColegioProfe,"nuevo_button","Nuevo"); FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemModificarTipoColegioProfe= new JMenuItem("Editar" + FuncionesSwing.getKeyMensaje("MODIFICAR")); this.jMenuItemModificarTipoColegioProfe.setActionCommand("Editar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemModificarTipoColegioProfe,"modificar_button","Editar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemModificarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemActualizarTipoColegioProfe= new JMenuItem("Actualizar" + FuncionesSwing.getKeyMensaje("ACTUALIZAR")); this.jMenuItemActualizarTipoColegioProfe.setActionCommand("Actualizar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemActualizarTipoColegioProfe,"actualizar_button","Actualizar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemActualizarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemEliminarTipoColegioProfe= new JMenuItem("Eliminar" + FuncionesSwing.getKeyMensaje("ELIMINAR")); this.jMenuItemEliminarTipoColegioProfe.setActionCommand("Eliminar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemEliminarTipoColegioProfe,"eliminar_button","Eliminar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemEliminarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemCancelarTipoColegioProfe= new JMenuItem("Cancelar" + FuncionesSwing.getKeyMensaje("CANCELAR")); this.jMenuItemCancelarTipoColegioProfe.setActionCommand("Cancelar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCancelarTipoColegioProfe,"cancelar_button","Cancelar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemCancelarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemGuardarCambiosTipoColegioProfe= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS")); this.jMenuItemGuardarCambiosTipoColegioProfe.setActionCommand("Guardar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosTipoColegioProfe,"guardarcambios_button","Guardar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemCerrarTipoColegioProfe= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR")); this.jMenuItemCerrarTipoColegioProfe.setActionCommand("Cerrar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarTipoColegioProfe,"cerrar_button","Salir"); FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemDetalleCerrarTipoColegioProfe= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR")); this.jMenuItemDetalleCerrarTipoColegioProfe.setActionCommand("Cerrar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleCerrarTipoColegioProfe,"cerrar_button","Salir"); FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleCerrarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemMostrarOcultarTipoColegioProfe= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR")); this.jMenuItemMostrarOcultarTipoColegioProfe.setActionCommand("Mostrar Ocultar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarTipoColegioProfe,"mostrar_ocultar_button","Mostrar Ocultar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jMenuItemDetalleMostarOcultarTipoColegioProfe= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR")); this.jMenuItemDetalleMostarOcultarTipoColegioProfe.setActionCommand("Mostrar Ocultar"); FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarTipoColegioProfe,"mostrar_ocultar_button","Mostrar Ocultar"); FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); //DETALLE this.jmenuDetalleArchivoTipoColegioProfe.add(this.jMenuItemDetalleCerrarTipoColegioProfe); this.jmenuDetalleAccionesTipoColegioProfe.add(this.jMenuItemActualizarTipoColegioProfe); this.jmenuDetalleAccionesTipoColegioProfe.add(this.jMenuItemEliminarTipoColegioProfe); this.jmenuDetalleAccionesTipoColegioProfe.add(this.jMenuItemCancelarTipoColegioProfe); //this.jmenuDetalleDatosTipoColegioProfe.add(this.jMenuItemDetalleAbrirOrderByTipoColegioProfe); this.jmenuDetalleDatosTipoColegioProfe.add(this.jMenuItemDetalleMostarOcultarTipoColegioProfe); //this.jmenuDetalleAccionesTipoColegioProfe.add(this.jMenuItemGuardarCambiosTipoColegioProfe); //DETALLE_FIN //RELACIONES //RELACIONES //DETALLE FuncionesSwing.setBoldMenu(this.jmenuDetalleArchivoTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldMenu(this.jmenuDetalleAccionesTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldMenu(this.jmenuDetalleDatosTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); this.jmenuBarDetalleTipoColegioProfe.add(this.jmenuDetalleArchivoTipoColegioProfe); this.jmenuBarDetalleTipoColegioProfe.add(this.jmenuDetalleAccionesTipoColegioProfe); this.jmenuBarDetalleTipoColegioProfe.add(this.jmenuDetalleDatosTipoColegioProfe); //DETALLE_FIN //AGREGA MENU DETALLE A PANTALLA this.setJMenuBar(this.jmenuBarDetalleTipoColegioProfe); } public void inicializarElementosCamposTipoColegioProfe() { String sKeyStrokeName=""; KeyStroke keyStrokeControl=null; jLabelIdTipoColegioProfe = new JLabelMe(); jLabelIdTipoColegioProfe.setText(""+Constantes2.S_CODIGO_UNICO+""); jLabelIdTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); jLabelIdTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); jLabelIdTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); FuncionesSwing.setBoldLabel(jLabelIdTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); this.jPanelidTipoColegioProfe = new JPanelMe("fondo_formulario",true);//new JPanel(); this.jPanelidTipoColegioProfe.setToolTipText(TipoColegioProfeConstantesFunciones.LABEL_ID); this.gridaBagLayoutTipoColegioProfe= new GridBagLayout(); this.jPanelidTipoColegioProfe.setLayout(this.gridaBagLayoutTipoColegioProfe); jLabelidTipoColegioProfe = new JLabel(); jLabelidTipoColegioProfe.setText("Id"); jLabelidTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL)); jLabelidTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL)); jLabelidTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL)); this.jLabelcodigoTipoColegioProfe = new JLabelMe(); this.jLabelcodigoTipoColegioProfe.setText(""+TipoColegioProfeConstantesFunciones.LABEL_CODIGO+" : *"); this.jLabelcodigoTipoColegioProfe.setToolTipText("Codigo"); this.jLabelcodigoTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); this.jLabelcodigoTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); this.jLabelcodigoTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); FuncionesSwing.setBoldLabel(jLabelcodigoTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); this.jPanelcodigoTipoColegioProfe=new JPanelMe("fondo_formulario",true);//new JPanel(); this.jPanelcodigoTipoColegioProfe.setToolTipText(TipoColegioProfeConstantesFunciones.LABEL_CODIGO); this.gridaBagLayoutTipoColegioProfe = new GridBagLayout(); this.jPanelcodigoTipoColegioProfe.setLayout(this.gridaBagLayoutTipoColegioProfe); jTextFieldcodigoTipoColegioProfe= new JTextFieldMe(); jTextFieldcodigoTipoColegioProfe.setEnabled(false); jTextFieldcodigoTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jTextFieldcodigoTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jTextFieldcodigoTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); FuncionesSwing.setBoldTextField(jTextFieldcodigoTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); this.jButtoncodigoTipoColegioProfeBusqueda= new JButtonMe(); this.jButtoncodigoTipoColegioProfeBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtoncodigoTipoColegioProfeBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtoncodigoTipoColegioProfeBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); //this.jButtoncodigoTipoColegioProfeBusqueda.setText("U"); this.jButtoncodigoTipoColegioProfeBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")"); this.jButtoncodigoTipoColegioProfeBusqueda.setFocusable(false); FuncionesSwing.addImagenButtonGeneral(this.jButtoncodigoTipoColegioProfeBusqueda,"buscardatos","BUSCAR DATOS"); sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR"); keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR"); jTextFieldcodigoTipoColegioProfe.getInputMap().put(keyStrokeControl, sKeyStrokeName); jTextFieldcodigoTipoColegioProfe.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"codigoTipoColegioProfeBusqueda")); if(this.tipocolegioprofeSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) { this.jButtoncodigoTipoColegioProfeBusqueda.setVisible(false); } this.jLabelnombreTipoColegioProfe = new JLabelMe(); this.jLabelnombreTipoColegioProfe.setText(""+TipoColegioProfeConstantesFunciones.LABEL_NOMBRE+" : *"); this.jLabelnombreTipoColegioProfe.setToolTipText("Nombre"); this.jLabelnombreTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); this.jLabelnombreTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); this.jLabelnombreTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); FuncionesSwing.setBoldLabel(jLabelnombreTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); this.jPanelnombreTipoColegioProfe=new JPanelMe("fondo_formulario",true);//new JPanel(); this.jPanelnombreTipoColegioProfe.setToolTipText(TipoColegioProfeConstantesFunciones.LABEL_NOMBRE); this.gridaBagLayoutTipoColegioProfe = new GridBagLayout(); this.jPanelnombreTipoColegioProfe.setLayout(this.gridaBagLayoutTipoColegioProfe); jTextAreanombreTipoColegioProfe= new JTextAreaMe(); jTextAreanombreTipoColegioProfe.setEnabled(false); jTextAreanombreTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jTextAreanombreTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jTextAreanombreTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jTextAreanombreTipoColegioProfe.setLineWrap(true); jTextAreanombreTipoColegioProfe.setWrapStyleWord(true); jTextAreanombreTipoColegioProfe.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); jTextAreanombreTipoColegioProfe.setRows(5); FuncionesSwing.setBoldTextArea(jTextAreanombreTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); jscrollPanenombreTipoColegioProfe = new JScrollPane(jTextAreanombreTipoColegioProfe); jscrollPanenombreTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),70)); jscrollPanenombreTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),70)); jscrollPanenombreTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),70)); this.jButtonnombreTipoColegioProfeBusqueda= new JButtonMe(); this.jButtonnombreTipoColegioProfeBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtonnombreTipoColegioProfeBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtonnombreTipoColegioProfeBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); //this.jButtonnombreTipoColegioProfeBusqueda.setText("U"); this.jButtonnombreTipoColegioProfeBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")"); this.jButtonnombreTipoColegioProfeBusqueda.setFocusable(false); FuncionesSwing.addImagenButtonGeneral(this.jButtonnombreTipoColegioProfeBusqueda,"buscardatos","BUSCAR DATOS"); sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR"); keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR"); jTextAreanombreTipoColegioProfe.getInputMap().put(keyStrokeControl, sKeyStrokeName); jTextAreanombreTipoColegioProfe.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"nombreTipoColegioProfeBusqueda")); if(this.tipocolegioprofeSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) { this.jButtonnombreTipoColegioProfeBusqueda.setVisible(false); } } public void inicializarElementosCamposForeigKeysTipoColegioProfe() { String sKeyStrokeName=""; KeyStroke keyStrokeControl=null; this.jLabelid_empresaTipoColegioProfe = new JLabelMe(); this.jLabelid_empresaTipoColegioProfe.setText(""+TipoColegioProfeConstantesFunciones.LABEL_IDEMPRESA+" : *"); this.jLabelid_empresaTipoColegioProfe.setToolTipText("Empresa"); this.jLabelid_empresaTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); this.jLabelid_empresaTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); this.jLabelid_empresaTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0))); FuncionesSwing.setBoldLabel(jLabelid_empresaTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); this.jPanelid_empresaTipoColegioProfe=new JPanelMe("fondo_formulario",true);//new JPanel(); this.jPanelid_empresaTipoColegioProfe.setToolTipText(TipoColegioProfeConstantesFunciones.LABEL_IDEMPRESA); this.gridaBagLayoutTipoColegioProfe = new GridBagLayout(); this.jPanelid_empresaTipoColegioProfe.setLayout(this.gridaBagLayoutTipoColegioProfe); jComboBoxid_empresaTipoColegioProfe= new JComboBoxMe(); jComboBoxid_empresaTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jComboBoxid_empresaTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); jComboBoxid_empresaTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0))); FuncionesSwing.setBoldComboBox(jComboBoxid_empresaTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); jComboBoxid_empresaTipoColegioProfe.setEnabled(false); this.jButtonid_empresaTipoColegioProfe= new JButtonMe(); this.jButtonid_empresaTipoColegioProfe.setMinimumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL)); this.jButtonid_empresaTipoColegioProfe.setMaximumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL)); this.jButtonid_empresaTipoColegioProfe.setPreferredSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL)); this.jButtonid_empresaTipoColegioProfe.setText("Buscar"); this.jButtonid_empresaTipoColegioProfe.setToolTipText("Buscar ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA")+")"); this.jButtonid_empresaTipoColegioProfe.setFocusable(false); FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaTipoColegioProfe,"buscar_form","Buscar"); sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA"); keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSQUEDA"); jComboBoxid_empresaTipoColegioProfe.getInputMap().put(keyStrokeControl, sKeyStrokeName); jComboBoxid_empresaTipoColegioProfe.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaTipoColegioProfe")); this.jButtonid_empresaTipoColegioProfeBusqueda= new JButtonMe(); this.jButtonid_empresaTipoColegioProfeBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtonid_empresaTipoColegioProfeBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtonid_empresaTipoColegioProfeBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); //this.jButtonid_empresaTipoColegioProfeBusqueda.setText("U"); this.jButtonid_empresaTipoColegioProfeBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")"); this.jButtonid_empresaTipoColegioProfeBusqueda.setFocusable(false); FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaTipoColegioProfeBusqueda,"buscardatos","BUSCAR DATOS"); sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR"); keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR"); jComboBoxid_empresaTipoColegioProfe.getInputMap().put(keyStrokeControl, sKeyStrokeName); jComboBoxid_empresaTipoColegioProfe.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaTipoColegioProfeBusqueda")); if(this.tipocolegioprofeSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) { this.jButtonid_empresaTipoColegioProfeBusqueda.setVisible(false); } this.jButtonid_empresaTipoColegioProfeUpdate= new JButtonMe(); this.jButtonid_empresaTipoColegioProfeUpdate.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtonid_empresaTipoColegioProfeUpdate.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); this.jButtonid_empresaTipoColegioProfeUpdate.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO)); //this.jButtonid_empresaTipoColegioProfeUpdate.setText("U"); this.jButtonid_empresaTipoColegioProfeUpdate.setToolTipText("ACTUALIZAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR")+")"); this.jButtonid_empresaTipoColegioProfeUpdate.setFocusable(false); FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaTipoColegioProfeUpdate,"actualizardatos","ACTUALIZAR DATOS"); sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR"); keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_ACTUALIZAR"); jComboBoxid_empresaTipoColegioProfe.getInputMap().put(keyStrokeControl, sKeyStrokeName); jComboBoxid_empresaTipoColegioProfe.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaTipoColegioProfeUpdate")); } public void jButtonActionPerformedTecladoGeneral(String sTipo,ActionEvent evt) { //System.out.println("TRANSFIERE EL MANEJO AL PADRE O FORM PRINCIPAL"); jInternalFrameParent.jButtonActionPerformedTecladoGeneral(sTipo,evt); } //JPanel //@SuppressWarnings({"unchecked" })//"rawtypes" public JScrollPane getJContentPane(int iWidth,int iHeight,JDesktopPane jDesktopPane,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception { //PARA TABLA PARAMETROS String sKeyStrokeName=""; KeyStroke keyStrokeControl=null; this.jContentPane = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel(); this.usuarioActual=usuarioActual; this.resumenUsuarioActual=resumenUsuarioActual; this.opcionActual=opcionActual; this.moduloActual=moduloActual; this.parametroGeneralSg=parametroGeneralSg; this.parametroGeneralUsuario=parametroGeneralUsuario; this.jDesktopPane=jDesktopPane; this.conFuncionalidadRelaciones=parametroGeneralUsuario.getcon_guardar_relaciones(); int iGridyPrincipal=0; this.inicializarToolBar(); //CARGAR MENUS //this.jInternalFrameDetalleTipoColegioProfe = new TipoColegioProfeBeanSwingJInternalFrameAdditional(paginaTipo);//JInternalFrameBase("Tipo Colegio Profe DATOS"); this.cargarMenus(); this.gridaBagLayoutTipoColegioProfe= new GridBagLayout(); String sToolTipTipoColegioProfe=""; sToolTipTipoColegioProfe=TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO; if(Constantes.ISDEVELOPING) { sToolTipTipoColegioProfe+="(Nomina.TipoColegioProfe)"; } if(!this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()) { sToolTipTipoColegioProfe+="_"+this.opcionActual.getId(); } this.jButtonNuevoTipoColegioProfe = new JButtonMe(); this.jButtonModificarTipoColegioProfe = new JButtonMe(); this.jButtonActualizarTipoColegioProfe = new JButtonMe(); this.jButtonEliminarTipoColegioProfe = new JButtonMe(); this.jButtonCancelarTipoColegioProfe = new JButtonMe(); this.jButtonGuardarCambiosTipoColegioProfe = new JButtonMe(); this.jButtonGuardarCambiosTablaTipoColegioProfe = new JButtonMe(); this.jButtonCerrarTipoColegioProfe = new JButtonMe(); this.jScrollPanelDatosTipoColegioProfe = new JScrollPane(); this.jScrollPanelDatosEdicionTipoColegioProfe = new JScrollPane(); this.jScrollPanelDatosGeneralTipoColegioProfe = new JScrollPane(); this.jPanelCamposTipoColegioProfe = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true); this.jPanelCamposOcultosTipoColegioProfe = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true); this.jPanelAccionesTipoColegioProfe = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true); this.jPanelAccionesFormularioTipoColegioProfe = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true); //if(!this.conCargarMinimo) { ; ; //} this.sPath=" <---> Acceso: Tipo Colegio Profe"; if(!this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()) { this.jScrollPanelDatosTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Tipo Colegio Profes" + this.sPath)); } else { this.jScrollPanelDatosTipoColegioProfe.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); } this.jScrollPanelDatosEdicionTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos")); this.jScrollPanelDatosGeneralTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos")); this.jPanelCamposTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos")); this.jPanelCamposTipoColegioProfe.setName("jPanelCamposTipoColegioProfe"); this.jPanelCamposOcultosTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos Ocultos")); this.jPanelCamposOcultosTipoColegioProfe.setName("jPanelCamposOcultosTipoColegioProfe"); this.jPanelAccionesTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones")); this.jPanelAccionesTipoColegioProfe.setToolTipText("Acciones"); this.jPanelAccionesTipoColegioProfe.setName("Acciones"); this.jPanelAccionesFormularioTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones Extra/Post")); this.jPanelAccionesFormularioTipoColegioProfe.setToolTipText("Acciones"); this.jPanelAccionesFormularioTipoColegioProfe.setName("Acciones"); FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosEdicionTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldPanel(this.jPanelCamposTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldPanel(this.jPanelCamposOcultosTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldPanel(this.jPanelAccionesFormularioTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); //if(!this.conCargarMinimo) { ; ; //} //ELEMENTOS TABLAS PARAMETOS if(!this.conCargarMinimo) { } //ELEMENTOS TABLAS PARAMETOS_FIN this.jButtonNuevoTipoColegioProfe.setText("Nuevo"); this.jButtonModificarTipoColegioProfe.setText("Editar"); this.jButtonActualizarTipoColegioProfe.setText("Actualizar"); this.jButtonEliminarTipoColegioProfe.setText("Eliminar"); this.jButtonCancelarTipoColegioProfe.setText("Cancelar"); this.jButtonGuardarCambiosTipoColegioProfe.setText("Guardar"); this.jButtonGuardarCambiosTablaTipoColegioProfe.setText("Guardar"); this.jButtonCerrarTipoColegioProfe.setText("Salir"); FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoTipoColegioProfe,"nuevo_button","Nuevo",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonModificarTipoColegioProfe,"modificar_button","Editar",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonActualizarTipoColegioProfe,"actualizar_button","Actualizar",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonEliminarTipoColegioProfe,"eliminar_button","Eliminar",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonCancelarTipoColegioProfe,"cancelar_button","Cancelar",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTipoColegioProfe,"guardarcambios_button","Guardar",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaTipoColegioProfe,"guardarcambiostabla_button","Guardar",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarTipoColegioProfe,"cerrar_button","Salir",this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()); FuncionesSwing.setBoldButton(this.jButtonNuevoTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldButton(this.jButtonModificarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldButton(this.jButtonCerrarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this); FuncionesSwing.setBoldButton(this.jButtonActualizarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldButton(this.jButtonEliminarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); FuncionesSwing.setBoldButton(this.jButtonCancelarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); this.jButtonNuevoTipoColegioProfe.setToolTipText("Nuevo"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO")); this.jButtonModificarTipoColegioProfe.setToolTipText("Editar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO+"");// + FuncionesSwing.getKeyMensaje("MODIFICAR")) this.jButtonActualizarTipoColegioProfe.setToolTipText("Actualizar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR")); this.jButtonEliminarTipoColegioProfe.setToolTipText("Eliminar)"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR")); this.jButtonCancelarTipoColegioProfe.setToolTipText("Cancelar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR")); this.jButtonGuardarCambiosTipoColegioProfe.setToolTipText("Guardar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS")); this.jButtonGuardarCambiosTablaTipoColegioProfe.setToolTipText("Guardar"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS")); this.jButtonCerrarTipoColegioProfe.setToolTipText("Salir"+" "+TipoColegioProfeConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR")); //HOT KEYS /* N->Nuevo N->Alt + Nuevo Relaciones (ANTES R) A->Actualizar E->Eliminar S->Cerrar C->->Mayus + Cancelar (ANTES Q->Quit) G->Guardar Cambios D->Duplicar C->Alt + Cop?ar O->Orden N->Nuevo Tabla R->Recargar Informacion Inicial (ANTES I) Alt + Pag.Down->Siguientes Alt + Pag.Up->Anteriores NO UTILIZADOS M->Modificar */ String sMapKey = ""; InputMap inputMap =null; //NUEVO sMapKey = "NuevoTipoColegioProfe"; inputMap = this.jButtonNuevoTipoColegioProfe.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL")); inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey); this.jButtonNuevoTipoColegioProfe.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoTipoColegioProfe")); //ACTUALIZAR sMapKey = "ActualizarTipoColegioProfe"; inputMap = this.jButtonActualizarTipoColegioProfe.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL")); inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ACTUALIZAR") , FuncionesSwing.getMaskKey("ACTUALIZAR")), sMapKey); this.jButtonActualizarTipoColegioProfe.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ActualizarTipoColegioProfe")); //ELIMINAR sMapKey = "EliminarTipoColegioProfe"; inputMap = this.jButtonEliminarTipoColegioProfe.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL")); inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ELIMINAR") , FuncionesSwing.getMaskKey("ELIMINAR")), sMapKey); this.jButtonEliminarTipoColegioProfe.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"EliminarTipoColegioProfe")); //CANCELAR sMapKey = "CancelarTipoColegioProfe"; inputMap = this.jButtonCancelarTipoColegioProfe.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL")); inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CANCELAR") , FuncionesSwing.getMaskKey("CANCELAR")), sMapKey); this.jButtonCancelarTipoColegioProfe.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CancelarTipoColegioProfe")); //CERRAR sMapKey = "CerrarTipoColegioProfe"; inputMap = this.jButtonCerrarTipoColegioProfe.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL")); inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey); this.jButtonCerrarTipoColegioProfe.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarTipoColegioProfe")); //GUARDAR CAMBIOS sMapKey = "GuardarCambiosTablaTipoColegioProfe"; inputMap = this.jButtonGuardarCambiosTablaTipoColegioProfe.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL")); inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey); this.jButtonGuardarCambiosTablaTipoColegioProfe.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaTipoColegioProfe")); //HOT KEYS this.jCheckBoxPostAccionNuevoTipoColegioProfe = new JCheckBoxMe(); this.jCheckBoxPostAccionNuevoTipoColegioProfe.setText("Nuevo"); this.jCheckBoxPostAccionNuevoTipoColegioProfe.setToolTipText("Nuevo TipoColegioProfe"); FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionNuevoTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); this.jCheckBoxPostAccionSinCerrarTipoColegioProfe = new JCheckBoxMe(); this.jCheckBoxPostAccionSinCerrarTipoColegioProfe.setText("Sin Cerrar"); this.jCheckBoxPostAccionSinCerrarTipoColegioProfe.setToolTipText("Sin Cerrar Ventana TipoColegioProfe"); FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinCerrarTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); this.jCheckBoxPostAccionSinMensajeTipoColegioProfe = new JCheckBoxMe(); this.jCheckBoxPostAccionSinMensajeTipoColegioProfe.setText("Sin Mensaje"); this.jCheckBoxPostAccionSinMensajeTipoColegioProfe.setToolTipText("Sin Mensaje Confirmacion"); FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinMensajeTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); this.jComboBoxTiposAccionesTipoColegioProfe = new JComboBoxMe(); //this.jComboBoxTiposAccionesTipoColegioProfe.setText("Accion"); this.jComboBoxTiposAccionesTipoColegioProfe.setToolTipText("Tipos de Acciones"); this.jComboBoxTiposAccionesFormularioTipoColegioProfe = new JComboBoxMe(); //this.jComboBoxTiposAccionesFormularioTipoColegioProfe.setText("Accion"); this.jComboBoxTiposAccionesFormularioTipoColegioProfe.setToolTipText("Tipos de Acciones"); this.jLabelAccionesTipoColegioProfe = new JLabelMe(); this.jLabelAccionesTipoColegioProfe.setText("Acciones"); this.jLabelAccionesTipoColegioProfe.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL)); this.jLabelAccionesTipoColegioProfe.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL)); this.jLabelAccionesTipoColegioProfe.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL)); //HOT KEYS2 /* T->Nuevo Tabla */ //NUEVO GUARDAR CAMBIOS O NUEVO TABLA //HOT KEYS2 //ELEMENTOS this.inicializarElementosCamposTipoColegioProfe(); //ELEMENTOS FK this.inicializarElementosCamposForeigKeysTipoColegioProfe(); //ELEMENTOS TABLAS PARAMETOS if(!this.conCargarMinimo) { } //ELEMENTOS TABLAS PARAMETOS_FIN //ELEMENTOS TABLAS PARAMETOS_FIN this.jTabbedPaneRelacionesTipoColegioProfe=new JTabbedPane(); this.jTabbedPaneRelacionesTipoColegioProfe.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Relacionados")); //ESTA EN BEAN FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneRelacionesTipoColegioProfe,STIPO_TAMANIO_GENERAL,false,false,this); int iPosXAccionPaginacion=0; this.jComboBoxTiposAccionesTipoColegioProfe.setMinimumSize(new Dimension(145,20)); this.jComboBoxTiposAccionesTipoColegioProfe.setMaximumSize(new Dimension(145,20)); this.jComboBoxTiposAccionesTipoColegioProfe.setPreferredSize(new Dimension(145,20)); FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,true,this);; this.jComboBoxTiposAccionesFormularioTipoColegioProfe.setMinimumSize(new Dimension(145,20)); this.jComboBoxTiposAccionesFormularioTipoColegioProfe.setMaximumSize(new Dimension(145,20)); this.jComboBoxTiposAccionesFormularioTipoColegioProfe.setPreferredSize(new Dimension(145,20)); FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesFormularioTipoColegioProfe, STIPO_TAMANIO_GENERAL,false,false,this); GridBagLayout gridaBagLayoutCamposTipoColegioProfe = new GridBagLayout(); GridBagLayout gridaBagLayoutCamposOcultosTipoColegioProfe = new GridBagLayout(); this.jPanelCamposTipoColegioProfe.setLayout(gridaBagLayoutCamposTipoColegioProfe); this.jPanelCamposOcultosTipoColegioProfe.setLayout(gridaBagLayoutCamposOcultosTipoColegioProfe); ; ; //SUBPANELES SIMPLES //SUBPANELES POR CAMPO this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelidTipoColegioProfe.add(jLabelIdTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 1; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelidTipoColegioProfe.add(jLabelidTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelid_empresaTipoColegioProfe.add(jLabelid_empresaTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(this.conMostrarAccionesCampo) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); //this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 2; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(0, 0, 0, 0); this.jPanelid_empresaTipoColegioProfe.add(jButtonid_empresaTipoColegioProfeBusqueda, this.gridBagConstraintsTipoColegioProfe); } if(this.conMostrarAccionesCampo) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); //this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 3; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(0, 0, 0, 0); this.jPanelid_empresaTipoColegioProfe.add(jButtonid_empresaTipoColegioProfeUpdate, this.gridBagConstraintsTipoColegioProfe); } this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 1; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelid_empresaTipoColegioProfe.add(jComboBoxid_empresaTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelcodigoTipoColegioProfe.add(jLabelcodigoTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(this.conMostrarAccionesCampo) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); //this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 2; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(0, 0, 0, 0); this.jPanelcodigoTipoColegioProfe.add(jButtoncodigoTipoColegioProfeBusqueda, this.gridBagConstraintsTipoColegioProfe); } this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 1; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelcodigoTipoColegioProfe.add(jTextFieldcodigoTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelnombreTipoColegioProfe.add(jLabelnombreTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(this.conMostrarAccionesCampo) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); //this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 2; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(0, 0, 0, 0); this.jPanelnombreTipoColegioProfe.add(jButtonnombreTipoColegioProfeBusqueda, this.gridBagConstraintsTipoColegioProfe); } this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.HORIZONTAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = 1; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelnombreTipoColegioProfe.add(jscrollPanenombreTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); //SUBPANELES SIMPLES //SUBPANELES EN PANEL //SUBPANELES EN PANEL CAMPOS NORMAL this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.NONE; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.WEST; this.gridBagConstraintsTipoColegioProfe.gridy = iYPanelCamposTipoColegioProfe; this.gridBagConstraintsTipoColegioProfe.gridx = iXPanelCamposTipoColegioProfe++; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; //COLSPAN_NUEVAFILA this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelCamposTipoColegioProfe.add(this.jPanelidTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(iXPanelCamposTipoColegioProfe % 1==0) { iXPanelCamposTipoColegioProfe=0; iYPanelCamposTipoColegioProfe++; } this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.NONE; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.WEST; this.gridBagConstraintsTipoColegioProfe.gridy = iYPanelCamposTipoColegioProfe; this.gridBagConstraintsTipoColegioProfe.gridx = iXPanelCamposTipoColegioProfe++; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; //COLSPAN_NUEVAFILA this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelCamposTipoColegioProfe.add(this.jPanelcodigoTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(iXPanelCamposTipoColegioProfe % 1==0) { iXPanelCamposTipoColegioProfe=0; iYPanelCamposTipoColegioProfe++; } this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.NONE; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.WEST; this.gridBagConstraintsTipoColegioProfe.gridy = iYPanelCamposTipoColegioProfe; this.gridBagConstraintsTipoColegioProfe.gridx = iXPanelCamposTipoColegioProfe++; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; //COLSPAN_NUEVAFILA this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelCamposTipoColegioProfe.add(this.jPanelnombreTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(iXPanelCamposTipoColegioProfe % 1==0) { iXPanelCamposTipoColegioProfe=0; iYPanelCamposTipoColegioProfe++; } //SUBPANELES EN PANEL CAMPOS OCULTOS this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.NONE; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.WEST; this.gridBagConstraintsTipoColegioProfe.gridy = iYPanelCamposOcultosTipoColegioProfe; this.gridBagConstraintsTipoColegioProfe.gridx = iXPanelCamposOcultosTipoColegioProfe++; this.gridBagConstraintsTipoColegioProfe.ipadx = 0; //COLSPAN_NUEVAFILA this.gridBagConstraintsTipoColegioProfe.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING); this.jPanelCamposOcultosTipoColegioProfe.add(this.jPanelid_empresaTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); if(iXPanelCamposOcultosTipoColegioProfe % 1==0) { iXPanelCamposOcultosTipoColegioProfe=0; iYPanelCamposOcultosTipoColegioProfe++; } //SUBPANELES EN PANEL CAMPOS INICIO //SUBPANELES EN PANEL CAMPOS FIN //SUBPANELES EN PANEL //ELEMENTOS TABLAS PARAMETOS //SUBPANELES POR CAMPO if(!this.conCargarMinimo) { //SUBPANELES EN PANEL CAMPOS } //ELEMENTOS TABLAS PARAMETOS_FIN Integer iGridXParametrosAccionesFormulario=0; Integer iGridYParametrosAccionesFormulario=0; GridBagLayout gridaBagLayoutAccionesTipoColegioProfe= new GridBagLayout(); this.jPanelAccionesTipoColegioProfe.setLayout(gridaBagLayoutAccionesTipoColegioProfe); GridBagLayout gridaBagLayoutAccionesFormularioTipoColegioProfe= new GridBagLayout(); this.jPanelAccionesFormularioTipoColegioProfe.setLayout(gridaBagLayoutAccionesFormularioTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridYParametrosAccionesFormulario; this.gridBagConstraintsTipoColegioProfe.gridx = iGridXParametrosAccionesFormulario++; this.jPanelAccionesFormularioTipoColegioProfe.add(this.jComboBoxTiposAccionesFormularioTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridYParametrosAccionesFormulario; this.gridBagConstraintsTipoColegioProfe.gridx = iGridXParametrosAccionesFormulario++; this.jPanelAccionesFormularioTipoColegioProfe.add(this.jCheckBoxPostAccionNuevoTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); //DEBE CERRARSE Y ACTUALIZARSE TODO NUEVAMENTE, SI ES RELACIONADO PUEDE FUNCIONAR //if(!this.tipocolegioprofeSessionBean.getEstaModoGuardarRelaciones()) { //SE ARRIESGA //if(!this.conFuncionalidadRelaciones) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridYParametrosAccionesFormulario; this.gridBagConstraintsTipoColegioProfe.gridx = iGridXParametrosAccionesFormulario++; this.jPanelAccionesFormularioTipoColegioProfe.add(this.jCheckBoxPostAccionSinCerrarTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); //} //NO TIENE MENSAJE POR DEFINICION, O ES MUY COMPLEJO LA PANTALLA PARA HACERLO MAS COMPLICADO if(!this.tipocolegioprofeSessionBean.getEsGuardarRelacionado() ){ //&& !this.tipocolegioprofeSessionBean.getEstaModoGuardarRelaciones()) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridYParametrosAccionesFormulario; this.gridBagConstraintsTipoColegioProfe.gridx = iGridXParametrosAccionesFormulario++; this.jPanelAccionesFormularioTipoColegioProfe.add(this.jCheckBoxPostAccionSinMensajeTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); } int iPosXAccion=0; this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.VERTICAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = iPosXAccion++; this.jPanelAccionesTipoColegioProfe.add(this.jButtonModificarTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.VERTICAL; this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx =iPosXAccion++; this.jPanelAccionesTipoColegioProfe.add(this.jButtonEliminarTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = iPosXAccion++; this.jPanelAccionesTipoColegioProfe.add(this.jButtonActualizarTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx = iPosXAccion++; this.jPanelAccionesTipoColegioProfe.add(this.jButtonGuardarCambiosTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = 0; this.gridBagConstraintsTipoColegioProfe.gridx =iPosXAccion++; this.jPanelAccionesTipoColegioProfe.add(this.jButtonCancelarTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); //this.setJProgressBarToJPanel(); GridBagLayout gridaBagLayoutTipoColegioProfe = new GridBagLayout(); this.jContentPane.setLayout(gridaBagLayoutTipoColegioProfe); if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.tipocolegioprofeSessionBean.getEsGuardarRelacionado()) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; //this.gridBagConstraintsTipoColegioProfe.fill =GridBagConstraints.VERTICAL; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH this.gridBagConstraintsTipoColegioProfe.ipadx = 100; } //PROCESANDO EN OTRA PANTALLA int iGridxBusquedasParametros=0; //PARAMETROS TABLAS PARAMETROS if(!this.conCargarMinimo) { //NO BUSQUEDA } //PARAMETROS TABLAS PARAMETROS_FIN //PARAMETROS REPORTES this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy =iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx =0; this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.BOTH; //this.gridBagConstraintsTipoColegioProfe.ipady =150; this.jContentPane.add(this.jScrollPanelDatosTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); iWidthScroll=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO_RELSCROLL)+(250*0); iHeightScroll=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO_RELSCROLL); //if(TipoColegioProfeJInternalFrame.CON_DATOS_FRAME) { //this.jInternalFrameDetalleTipoColegioProfe = new TipoColegioProfeBeanSwingJInternalFrameAdditional();//JInternalFrameBase("Tipo Colegio Profe DATOS"); this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); //this.setjInternalFrameParent(this); iHeightFormularioMaximo=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO); if(iHeightFormulario>iHeightFormularioMaximo) { iHeightFormulario=iHeightFormularioMaximo; } iWidthFormularioMaximo=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO); if(iWidthFormulario>iWidthFormularioMaximo) { iWidthFormulario=iWidthFormularioMaximo; } //this.setTitle("[FOR] - Tipo Colegio Profe DATOS"); this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.usuarioActual,"Tipo Colegio Profe Formulario",PaginaTipo.FORMULARIO,paginaTipo)); this.setSize(iWidthFormulario,iHeightFormulario); this.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y)); this.setResizable(true); this.setClosable(true); this.setMaximizable(true); TipoColegioProfeModel tipocolegioprofeModel=new TipoColegioProfeModel(this); //SI USARA CLASE INTERNA //TipoColegioProfeModel.TipoColegioProfeFocusTraversalPolicy tipocolegioprofeFocusTraversalPolicy = tipocolegioprofeModel.new TipoColegioProfeFocusTraversalPolicy(this); //tipocolegioprofeFocusTraversalPolicy.settipocolegioprofeJInternalFrame(this); this.setFocusTraversalPolicy(tipocolegioprofeModel); this.jContentPaneDetalleTipoColegioProfe = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel(); int iGridyRelaciones=0; GridBagLayout gridaBagLayoutDetalleTipoColegioProfe = new GridBagLayout(); this.jContentPaneDetalleTipoColegioProfe.setLayout(gridaBagLayoutDetalleTipoColegioProfe); GridBagLayout gridaBagLayoutBusquedasParametrosTipoColegioProfe = new GridBagLayout(); if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) { //AGREGA TOOLBAR DETALLE A PANTALLA this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyRelaciones++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPaneDetalleTipoColegioProfe.add(jTtoolBarDetalleTipoColegioProfe, gridBagConstraintsTipoColegioProfe); } this.jScrollPanelDatosEdicionTipoColegioProfe= new JScrollPane(jContentPaneDetalleTipoColegioProfe,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); this.jScrollPanelDatosEdicionTipoColegioProfe.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosEdicionTipoColegioProfe.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosEdicionTipoColegioProfe.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosGeneralTipoColegioProfe= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); this.jScrollPanelDatosGeneralTipoColegioProfe.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosGeneralTipoColegioProfe.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosGeneralTipoColegioProfe.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll)); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyRelaciones++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPaneDetalleTipoColegioProfe.add(jPanelCamposTipoColegioProfe, gridBagConstraintsTipoColegioProfe); //if(!this.conCargarMinimo) { ; //} this.conMaximoRelaciones=true; if(this.parametroGeneralUsuario.getcon_cargar_por_parte()) { } //CARGA O NO CARGA RELACIONADOS(MAESTRO DETALLE) // ABAJO VIENE DE PARAMETRO GENERAL USUARIO if(conMaximoRelaciones) { // && this.conFuncionalidadRelaciones) { if(!this.conCargarMinimo) { if(cargarRelaciones && tipocolegioprofeSessionBean.getConGuardarRelaciones() ) { //paraCargarPorParte es false por defecto(y ejecuta funcion normal cargando detalle en tab panel), si se utiliza funcionalidad es true y carga tab panel auxiliar temporal if(this.tipocolegioprofeSessionBean.getConGuardarRelaciones()) { this.gridBagConstraintsTipoColegioProfe= new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyRelaciones++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPaneDetalleTipoColegioProfe.add(this.jTabbedPaneRelacionesTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); } //RELACIONES OTROS AGRUPADOS ; } else { //this.jButtonNuevoRelacionesTipoColegioProfe.setVisible(false); } } } Boolean tieneColumnasOcultas=false; tieneColumnasOcultas=true; if(!Constantes.ISDEVELOPING) { this.jPanelCamposOcultosTipoColegioProfe.setVisible(false); } else { if(tieneColumnasOcultas) { this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.fill=GridBagConstraints.NONE; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.WEST; this.gridBagConstraintsTipoColegioProfe.gridy = iGridyRelaciones++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPaneDetalleTipoColegioProfe.add(jPanelCamposOcultosTipoColegioProfe, gridBagConstraintsTipoColegioProfe); this.jPanelCamposOcultosTipoColegioProfe.setVisible(true); } } this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyRelaciones++;//1; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.CENTER;//WEST; this.jContentPaneDetalleTipoColegioProfe.add(this.jPanelAccionesFormularioTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyRelaciones;//1; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPaneDetalleTipoColegioProfe.add(this.jPanelAccionesTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); //this.setContentPane(jScrollPanelDatosEdicionTipoColegioProfe); //} else { //DISENO_DETALLE COMENTAR Y //DISENO_DETALLE(Solo Descomentar Seccion Inferior) //NOTA-DISENO_DETALLE(Si cambia lo de abajo, cambiar lo comentado, Al final no es lo mismo) /* this.jScrollPanelDatosEdicionTipoColegioProfe= new JScrollPane(this.jPanelCamposTipoColegioProfe,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); this.jScrollPanelDatosEdicionTipoColegioProfe.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosEdicionTipoColegioProfe.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll)); this.jScrollPanelDatosEdicionTipoColegioProfe.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll)); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.gridBagConstraintsTipoColegioProfe.fill = GridBagConstraints.BOTH; this.gridBagConstraintsTipoColegioProfe.ipady = this.getSize().height-yOffset*3; this.gridBagConstraintsTipoColegioProfe.anchor = GridBagConstraints.WEST; this.jContentPane.add(this.jScrollPanelDatosEdicionTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); //ACCIONES FORMULARIO this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy =iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPane.add(this.jPanelAccionesFormularioTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy =iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPane.add(this.jPanelAccionesTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); */ //} //DISENO_DETALLE-(Descomentar) /* this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPane.add(this.jPanelCamposTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy = iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx = 0; this.jContentPane.add(this.jPanelCamposOcultosTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); this.gridBagConstraintsTipoColegioProfe = new GridBagConstraints(); this.gridBagConstraintsTipoColegioProfe.gridy =iGridyPrincipal++; this.gridBagConstraintsTipoColegioProfe.gridx =0; this.jContentPane.add(this.jPanelAccionesTipoColegioProfe, this.gridBagConstraintsTipoColegioProfe); */ //pack(); //return this.jScrollPanelDatosGeneralTipoColegioProfe;//jContentPane; return jScrollPanelDatosEdicionTipoColegioProfe; } /* case "CONTROL_BUSQUEDA": sKeyName="F3"; case "CONTROL_BUSCAR": sKeyName="F4"; case "CONTROL_ARBOL": sKeyName="F5"; case "CONTROL_ACTUALIZAR": sKeyName="F6"; sKeyName="N"; */ }
4everalone/nano
sample/webservice/eBayDemoApp/src/com/ebay/trading/api/SearchStandingStatusCodeType.java
// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.trading.api; /** * * The Search standing that you have earned. * */ public enum SearchStandingStatusCodeType { /** * * Your listings may receive higher placement in search results * that are sorted by Best Match. * You earn this standing when you provide excellent customer service to eBay buyers * (such as good BuyerSatisfaction.Status and high detailed seller ratings). * If you already have a raised search standing, you can still boost your * ratings and increase the visibility of your items by maintaining or * improving your customer service. * */ RAISED("Raised"), /** * * Listings recieve standard placement in search results that are sorted by Best Match. * */ STANDARD("Standard"), /** * * Your listings may receive lower placement in search results that * are sorted by Best Match. * You earn this standing when you have not been successful in providing * eBay buyers with the customer service they expect. * You can still take positive steps to improve your customer service * and increase your ratings. * */ LOWERED("Lowered"), /** * * Reserved for internal or future use. * */ CUSTOM_CODE("CustomCode"); private final String value; SearchStandingStatusCodeType(String v) { value = v; } public String value() { return value; } public static SearchStandingStatusCodeType fromValue(String v) { if (v != null) { for (SearchStandingStatusCodeType c: SearchStandingStatusCodeType.values()) { if (c.value.equals(v)) { return c; } } } throw new IllegalArgumentException(v); } }
willp-bl/verify-frontend
app/helpers/redirect_to_idp_warning_helper.rb
module RedirectToIdpWarningHelper def other_ways(idp) requirement_text = idp.no_docs_requirement if requirement_text.empty? return '' end link_text = t('hub.redirect_to_idp_warning.other_ways_link', transaction: other_ways_description) link = link_to(link_text, other_ways_to_access_service_path, id: 'choose_other_ways') t('hub.redirect_to_idp_warning.no_docs_other_ways_message_html', idp_no_docs_requirement: requirement_text, other_ways_link: link) end end
matyasrichter/prisma-client-py
src/prisma_cleanup/__main__.py
<filename>src/prisma_cleanup/__main__.py<gh_stars>0 import sys from ._cleanup import main main(*sys.argv[1:])
owennewo/kfserving
vendor/github.com/tensorflow/tensorflow/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator_test.cc
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if GOOGLE_CUDA #include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h" #include <algorithm> #include <vector> #include "tensorflow/core/common_runtime/gpu/gpu_id.h" #include "tensorflow/core/common_runtime/gpu/gpu_id_utils.h" #include "tensorflow/core/common_runtime/gpu/gpu_init.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/random/simple_philox.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/stream_executor.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace { static void CheckStats(Allocator* a, int64 num_allocs, int64 bytes_in_use, int64 max_bytes_in_use, int64 max_alloc_size) { AllocatorStats stats; a->GetStats(&stats); LOG(INFO) << "Alloc stats: " << std::endl << stats.DebugString(); EXPECT_EQ(stats.bytes_in_use, bytes_in_use); EXPECT_EQ(stats.max_bytes_in_use, max_bytes_in_use); EXPECT_EQ(stats.num_allocs, num_allocs); EXPECT_EQ(stats.max_alloc_size, max_alloc_size); } TEST(GPUBFCAllocatorTest, NoDups) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); CheckStats(&a, 0, 0, 0, 0); // Allocate a lot of raw pointers std::vector<void*> ptrs; for (int s = 1; s < 1024; s++) { void* raw = a.AllocateRaw(1, s); ptrs.push_back(raw); } CheckStats(&a, 1023, 654336, 654336, 1024); std::sort(ptrs.begin(), ptrs.end()); // Make sure none of them are equal, and that none of them overlap. for (size_t i = 1; i < ptrs.size(); i++) { ASSERT_NE(ptrs[i], ptrs[i - 1]); // No dups size_t req_size = a.RequestedSize(ptrs[i - 1]); ASSERT_GT(req_size, 0); ASSERT_GE(static_cast<char*>(ptrs[i]) - static_cast<char*>(ptrs[i - 1]), req_size); } for (size_t i = 0; i < ptrs.size(); i++) { a.DeallocateRaw(ptrs[i]); } CheckStats(&a, 1023, 0, 654336, 1024); } TEST(GPUBFCAllocatorTest, AllocationsAndDeallocations) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); // Allocate 256 raw pointers of sizes between 100 bytes and about // a meg random::PhiloxRandom philox(123, 17); random::SimplePhilox rand(&philox); std::vector<void*> initial_ptrs; for (int s = 1; s < 256; s++) { size_t size = std::min<size_t>( std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576); void* raw = a.AllocateRaw(1, size); initial_ptrs.push_back(raw); } // Deallocate half of the memory, and keep track of the others. std::vector<void*> existing_ptrs; for (size_t i = 0; i < initial_ptrs.size(); i++) { if (i % 2 == 1) { a.DeallocateRaw(initial_ptrs[i]); } else { existing_ptrs.push_back(initial_ptrs[i]); } } // Ensure out of memory errors work and do not prevent future allocations from // working. void* out_of_memory_ptr = a.AllocateRaw(1, (1 << 30) + 1); CHECK_EQ(out_of_memory_ptr, nullptr); // Allocate a lot of raw pointers for (int s = 1; s < 256; s++) { size_t size = std::min<size_t>( std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576); void* raw = a.AllocateRaw(1, size); existing_ptrs.push_back(raw); } std::sort(existing_ptrs.begin(), existing_ptrs.end()); // Make sure none of them are equal for (size_t i = 1; i < existing_ptrs.size(); i++) { CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]); // No dups size_t req_size = a.RequestedSize(existing_ptrs[i - 1]); ASSERT_GT(req_size, 0); // Check that they don't overlap. ASSERT_GE(static_cast<char*>(existing_ptrs[i]) - static_cast<char*>(existing_ptrs[i - 1]), req_size); } for (size_t i = 0; i < existing_ptrs.size(); i++) { a.DeallocateRaw(existing_ptrs[i]); } } TEST(GPUBFCAllocatorTest, ExerciseCoalescing) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); CheckStats(&a, 0, 0, 0, 0); float* first_ptr = a.Allocate<float>(1024); a.DeallocateRaw(first_ptr); CheckStats(&a, 1, 0, 4096, 4096); for (int i = 0; i < 1024; ++i) { // Allocate several buffers of different sizes, and then clean them // all up. We should be able to repeat this endlessly without // causing fragmentation and growth. float* t1 = a.Allocate<float>(1024); int64* t2 = a.Allocate<int64>(1048576); double* t3 = a.Allocate<double>(2048); float* t4 = a.Allocate<float>(10485760); a.DeallocateRaw(t1); a.DeallocateRaw(t2); a.DeallocateRaw(t3); a.DeallocateRaw(t4); } CheckStats(&a, 4097, 0, 1024 * sizeof(float) + 1048576 * sizeof(int64) + 2048 * sizeof(double) + 10485760 * sizeof(float), 10485760 * sizeof(float)); // At the end, we should have coalesced all memory into one region // starting at the beginning, so validate that allocating a pointer // starts from this region. float* first_ptr_after = a.Allocate<float>(1024); EXPECT_EQ(first_ptr, first_ptr_after); a.DeallocateRaw(first_ptr_after); } TEST(GPUBFCAllocatorTest, AllocateZeroBufSize) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); float* ptr = a.Allocate<float>(0); EXPECT_EQ(nullptr, ptr); } TEST(GPUBFCAllocatorTest, TracksSizes) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); EXPECT_EQ(true, a.TracksAllocationSizes()); } TEST(GPUBFCAllocatorTest, AllocatedVsRequested) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); float* t1 = a.Allocate<float>(1); EXPECT_EQ(4, a.RequestedSize(t1)); EXPECT_EQ(256, a.AllocatedSize(t1)); a.DeallocateRaw(t1); } TEST(GPUBFCAllocatorTest, TestCustomMemoryLimit) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); // Configure a 1MiB byte limit GPUBFCAllocator a(sub_allocator, 1 << 20, "GPU_0_bfc"); float* first_ptr = a.Allocate<float>(1 << 6); float* second_ptr = a.Allocate<float>(1 << 20); EXPECT_NE(nullptr, first_ptr); EXPECT_EQ(nullptr, second_ptr); a.DeallocateRaw(first_ptr); } TEST(GPUBFCAllocatorTest, AllocationsAndDeallocationsWithGrowth) { GPUOptions options; options.set_allow_growth(true); // Max of 2GiB, but starts out small. PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1LL << 31, "GPU_0_bfc"); // Allocate 10 raw pointers of sizes between 100 bytes and about // 64 megs. random::PhiloxRandom philox(123, 17); random::SimplePhilox rand(&philox); const int32 max_mem = 1 << 27; std::vector<void*> initial_ptrs; for (int s = 1; s < 10; s++) { size_t size = std::min<size_t>( std::max<size_t>(rand.Rand32() % max_mem, 100), max_mem); void* raw = a.AllocateRaw(1, size); initial_ptrs.push_back(raw); } // Deallocate half of the memory, and keep track of the others. std::vector<void*> existing_ptrs; for (size_t i = 0; i < initial_ptrs.size(); i++) { if (i % 2 == 1) { a.DeallocateRaw(initial_ptrs[i]); } else { existing_ptrs.push_back(initial_ptrs[i]); } } const int32 max_mem_2 = 1 << 26; // Allocate a lot of raw pointers between 100 bytes and 64 megs. for (int s = 1; s < 10; s++) { size_t size = std::min<size_t>( std::max<size_t>(rand.Rand32() % max_mem_2, 100), max_mem_2); void* raw = a.AllocateRaw(1, size); existing_ptrs.push_back(raw); } std::sort(existing_ptrs.begin(), existing_ptrs.end()); // Make sure none of them are equal for (size_t i = 1; i < existing_ptrs.size(); i++) { CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]); // No dups size_t req_size = a.RequestedSize(existing_ptrs[i - 1]); ASSERT_GT(req_size, 0); // Check that they don't overlap. ASSERT_GE(static_cast<char*>(existing_ptrs[i]) - static_cast<char*>(existing_ptrs[i - 1]), req_size); } for (size_t i = 0; i < existing_ptrs.size(); i++) { a.DeallocateRaw(existing_ptrs[i]); } AllocatorStats stats; a.GetStats(&stats); LOG(INFO) << "Alloc stats: \n" << stats.DebugString(); } TEST(GPUBFCAllocatorTest, DISABLED_AllocatorReceivesZeroMemory) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1UL << 60, "GPU_0_bfc"); sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator b(sub_allocator, 1UL << 60, "GPU_0_bfc"); void* amem = a.AllocateRaw(1, 1); void* bmem = b.AllocateRaw(1, 1 << 30); a.DeallocateRaw(amem); b.DeallocateRaw(bmem); } static void BM_Allocation(int iters) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1uLL << 33, "GPU_0_bfc"); // Exercise a few different allocation sizes std::vector<size_t> sizes = {256, 4096, 16384, 524288, 512, 1048576, 10485760, 104857600, 1048576000, 2048576000}; int size_index = 0; while (--iters > 0) { size_t bytes = sizes[size_index++ % sizes.size()]; void* p = a.AllocateRaw(1, bytes); a.DeallocateRaw(p); } } BENCHMARK(BM_Allocation); static void BM_AllocationThreaded(int iters, int num_threads) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1uLL << 33, "GPU_0_bfc"); thread::ThreadPool pool(Env::Default(), "test", num_threads); std::atomic_int_fast32_t count(iters); mutex done_lock; condition_variable done; bool done_flag = false; for (int t = 0; t < num_threads; t++) { pool.Schedule([&a, &count, &done_lock, &done, &done_flag, iters]() { // Exercise a few different allocation sizes std::vector<int> sizes = {256, 4096, 16384, 524288, 512, 1048576, 10485760, 104857600}; int size_index = 0; for (int i = 0; i < iters; i++) { int bytes = sizes[size_index++ % sizes.size()]; void* p = a.AllocateRaw(1, bytes); a.DeallocateRaw(p); if (count.fetch_sub(1) == 1) { mutex_lock l(done_lock); done_flag = true; done.notify_all(); break; } } }); } mutex_lock l(done_lock); if (!done_flag) { done.wait(l); } } BENCHMARK(BM_AllocationThreaded)->Arg(1)->Arg(4)->Arg(16); // A more complex benchmark that defers deallocation of an object for // "delay" allocations. static void BM_AllocationDelayed(int iters, int delay) { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); // Exercise a few different allocation sizes std::vector<int> sizes = {256, 4096, 16384, 4096, 512, 1024, 1024}; int size_index = 0; std::vector<void*> ptrs; ptrs.reserve(delay); for (int i = 0; i < delay; i++) { ptrs.push_back(nullptr); } int pindex = 0; while (--iters > 0) { if (ptrs[pindex] != nullptr) { a.DeallocateRaw(ptrs[pindex]); ptrs[pindex] = nullptr; } int bytes = sizes[size_index++ % sizes.size()]; void* p = a.AllocateRaw(1, bytes); ptrs[pindex] = p; pindex = (pindex + 1) % ptrs.size(); } for (int i = 0; i < ptrs.size(); i++) { if (ptrs[i] != nullptr) { a.DeallocateRaw(ptrs[i]); } } } BENCHMARK(BM_AllocationDelayed)->Arg(1)->Arg(10)->Arg(100)->Arg(1000); } // namespace class GPUBFCAllocatorPrivateMethodsTest : public ::testing::Test { protected: void SetUp() override { CHECK_EQ(unsetenv("TF_FORCE_GPU_ALLOW_GROWTH"), 0); } // The following test methods are called from tests. The reason for this is // that this class is a friend class to BFCAllocator, but tests are not, so // only methods inside this class can access private members of BFCAllocator. void TestBinDebugInfo() { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 << 30, "GPU_0_bfc"); std::vector<void*> initial_ptrs; std::vector<size_t> initial_ptrs_allocated_sizes; for (int i = 0; i < 5; i++) { for (int j = 0; j < 2; j++) { size_t size = 256 << i; void* raw = a.AllocateRaw(1, size); ASSERT_NE(raw, nullptr); initial_ptrs.push_back(raw); initial_ptrs_allocated_sizes.push_back(a.AllocatedSize(raw)); } } std::array<BFCAllocator::BinDebugInfo, BFCAllocator::kNumBins> bin_infos; { mutex_lock l(a.lock_); bin_infos = a.get_bin_debug_info(); } for (int i = 0; i < BFCAllocator::kNumBins; i++) { const BFCAllocator::BinDebugInfo& bin_info = bin_infos[i]; if (i < 5) { const size_t requested_size = 2 * (256 << i); EXPECT_EQ(requested_size, a.RequestedSize(initial_ptrs[2 * i]) + a.RequestedSize(initial_ptrs[2 * i + 1])); size_t allocated_size = initial_ptrs_allocated_sizes[2 * i] + initial_ptrs_allocated_sizes[2 * i + 1]; EXPECT_EQ(bin_info.total_bytes_in_use, allocated_size); EXPECT_EQ(bin_info.total_bytes_in_bin, allocated_size); EXPECT_EQ(bin_info.total_requested_bytes_in_use, requested_size); EXPECT_EQ(bin_info.total_chunks_in_use, 2); EXPECT_EQ(bin_info.total_chunks_in_bin, 2); } else { EXPECT_EQ(bin_info.total_bytes_in_use, 0); EXPECT_EQ(bin_info.total_requested_bytes_in_use, 0); EXPECT_EQ(bin_info.total_chunks_in_use, 0); if (i == BFCAllocator::kNumBins - 1) { EXPECT_GT(bin_info.total_bytes_in_bin, 0); EXPECT_EQ(bin_info.total_chunks_in_bin, 1); } else { EXPECT_EQ(bin_info.total_bytes_in_bin, 0); EXPECT_EQ(bin_info.total_chunks_in_bin, 0); } } } for (size_t i = 1; i < initial_ptrs.size(); i += 2) { a.DeallocateRaw(initial_ptrs[i]); initial_ptrs[i] = nullptr; } { mutex_lock l(a.lock_); bin_infos = a.get_bin_debug_info(); } for (int i = 0; i < BFCAllocator::kNumBins; i++) { const BFCAllocator::BinDebugInfo& bin_info = bin_infos[i]; if (i < 5) { // We cannot assert the exact number of bytes or chunks in the bin, // because it depends on what chunks were coalesced. size_t requested_size = 256 << i; EXPECT_EQ(requested_size, a.RequestedSize(initial_ptrs[2 * i])); EXPECT_EQ(bin_info.total_bytes_in_use, initial_ptrs_allocated_sizes[2 * i]); EXPECT_GE(bin_info.total_bytes_in_bin, initial_ptrs_allocated_sizes[2 * i]); EXPECT_EQ(bin_info.total_requested_bytes_in_use, requested_size); EXPECT_EQ(bin_info.total_chunks_in_use, 1); EXPECT_GE(bin_info.total_chunks_in_bin, 1); } else { EXPECT_EQ(bin_info.total_bytes_in_use, 0); EXPECT_EQ(bin_info.total_requested_bytes_in_use, 0); EXPECT_EQ(bin_info.total_chunks_in_use, 0); } } } void TestLog2FloorNonZeroSlow() { PlatformGpuId platform_gpu_id(0); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator a(sub_allocator, 1 /* total_memory */, "GPU_0_bfc"); EXPECT_EQ(-1, a.Log2FloorNonZeroSlow(0)); EXPECT_EQ(0, a.Log2FloorNonZeroSlow(1)); EXPECT_EQ(1, a.Log2FloorNonZeroSlow(2)); EXPECT_EQ(1, a.Log2FloorNonZeroSlow(3)); EXPECT_EQ(9, a.Log2FloorNonZeroSlow(1023)); EXPECT_EQ(10, a.Log2FloorNonZeroSlow(1024)); EXPECT_EQ(10, a.Log2FloorNonZeroSlow(1025)); } void TestForceAllowGrowth() { PlatformGpuId platform_gpu_id(0); GPUOptions options; // Unset flag value uses provided option. unsetenv("TF_FORCE_GPU_ALLOW_GROWTH"); options.set_allow_growth(true); GPUMemAllocator* sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator unset_flag_allocator(sub_allocator, 1LL << 31, options, "GPU_0_bfc"); EXPECT_EQ(GPUBFCAllocator::RoundedBytes(size_t{1048576}), unset_flag_allocator.curr_region_allocation_bytes_); // Unparseable flag value uses provided option. setenv("TF_FORCE_GPU_ALLOW_GROWTH", "unparseable", 1); options.set_allow_growth(true); sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator unparsable_flag_allocator(sub_allocator, 1LL << 31, options, "GPU_1_bfc"); EXPECT_EQ(GPUBFCAllocator::RoundedBytes(size_t{1048576}), unparsable_flag_allocator.curr_region_allocation_bytes_); // Max of 2GiB total memory. Env variable set forces allow_growth, which // does an initial allocation of 1MiB. setenv("TF_FORCE_GPU_ALLOW_GROWTH", "true", 1); options.set_allow_growth(false); sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator force_allow_growth_allocator(sub_allocator, 1LL << 31, options, "GPU_2_bfc"); EXPECT_EQ(GPUBFCAllocator::RoundedBytes(size_t{1048576}), force_allow_growth_allocator.curr_region_allocation_bytes_); // If env variable forces allow_growth disabled, all available memory is // allocated. setenv("TF_FORCE_GPU_ALLOW_GROWTH", "false", 1); options.set_allow_growth(true); sub_allocator = new GPUMemAllocator( GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie(), platform_gpu_id, false /*use_unified_memory*/, {}, {}); GPUBFCAllocator force_no_allow_growth_allocator(sub_allocator, 1LL << 31, options, "GPU_3_bfc"); EXPECT_EQ(GPUBFCAllocator::RoundedBytes(1LL << 31), force_no_allow_growth_allocator.curr_region_allocation_bytes_); } }; TEST_F(GPUBFCAllocatorPrivateMethodsTest, BinDebugInfo) { TestBinDebugInfo(); } TEST_F(GPUBFCAllocatorPrivateMethodsTest, Log2FloorNonZeroSlow) { TestLog2FloorNonZeroSlow(); } TEST_F(GPUBFCAllocatorPrivateMethodsTest, ForceAllowGrowth) { TestForceAllowGrowth(); } } // namespace tensorflow #endif // GOOGLE_CUDA
cuisongliu/go-zero
core/stores/redis/redis_test.go
<filename>core/stores/redis/redis_test.go<gh_stars>1-10 package redis import ( "errors" "io" "testing" "time" "github.com/alicebob/miniredis" red "github.com/go-redis/redis" "github.com/stretchr/testify/assert" ) func TestRedis_Exists(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Exists("a") assert.NotNil(t, err) ok, err := client.Exists("a") assert.Nil(t, err) assert.False(t, ok) assert.Nil(t, client.Set("a", "b")) ok, err = client.Exists("a") assert.Nil(t, err) assert.True(t, ok) }) } func TestRedis_Eval(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Eval(`redis.call("EXISTS", KEYS[1])`, []string{"notexist"}) assert.NotNil(t, err) _, err = client.Eval(`redis.call("EXISTS", KEYS[1])`, []string{"notexist"}) assert.Equal(t, Nil, err) err = client.Set("key1", "value1") assert.Nil(t, err) _, err = client.Eval(`redis.call("EXISTS", KEYS[1])`, []string{"key1"}) assert.Equal(t, Nil, err) val, err := client.Eval(`return redis.call("EXISTS", KEYS[1])`, []string{"key1"}) assert.Nil(t, err) assert.Equal(t, int64(1), val) }) } func TestRedis_Hgetall(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.Nil(t, client.Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "bb", "bbb")) _, err := NewRedis(client.Addr, "").Hgetall("a") assert.NotNil(t, err) vals, err := client.Hgetall("a") assert.Nil(t, err) assert.EqualValues(t, map[string]string{ "aa": "aaa", "bb": "bbb", }, vals) }) } func TestRedis_Hvals(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.NotNil(t, NewRedis(client.Addr, "").Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "bb", "bbb")) _, err := NewRedis(client.Addr, "").Hvals("a") assert.NotNil(t, err) vals, err := client.Hvals("a") assert.Nil(t, err) assert.ElementsMatch(t, []string{"aaa", "bbb"}, vals) }) } func TestRedis_Hsetnx(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.Nil(t, client.Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "bb", "bbb")) _, err := NewRedis(client.Addr, "").Hsetnx("a", "bb", "ccc") assert.NotNil(t, err) ok, err := client.Hsetnx("a", "bb", "ccc") assert.Nil(t, err) assert.False(t, ok) ok, err = client.Hsetnx("a", "dd", "ddd") assert.Nil(t, err) assert.True(t, ok) vals, err := client.Hvals("a") assert.Nil(t, err) assert.ElementsMatch(t, []string{"aaa", "bbb", "ddd"}, vals) }) } func TestRedis_HdelHlen(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.Nil(t, client.Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "bb", "bbb")) _, err := NewRedis(client.Addr, "").Hlen("a") assert.NotNil(t, err) num, err := client.Hlen("a") assert.Nil(t, err) assert.Equal(t, 2, num) val, err := client.Hdel("a", "aa") assert.Nil(t, err) assert.True(t, val) vals, err := client.Hvals("a") assert.Nil(t, err) assert.ElementsMatch(t, []string{"bbb"}, vals) }) } func TestRedis_HIncrBy(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Hincrby("key", "field", 2) assert.NotNil(t, err) val, err := client.Hincrby("key", "field", 2) assert.Nil(t, err) assert.Equal(t, 2, val) val, err = client.Hincrby("key", "field", 3) assert.Nil(t, err) assert.Equal(t, 5, val) }) } func TestRedis_Hkeys(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.Nil(t, client.Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "bb", "bbb")) _, err := NewRedis(client.Addr, "").Hkeys("a") assert.NotNil(t, err) vals, err := client.Hkeys("a") assert.Nil(t, err) assert.ElementsMatch(t, []string{"aa", "bb"}, vals) }) } func TestRedis_Hmget(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.Nil(t, client.Hset("a", "aa", "aaa")) assert.Nil(t, client.Hset("a", "bb", "bbb")) _, err := NewRedis(client.Addr, "").Hmget("a", "aa", "bb") assert.NotNil(t, err) vals, err := client.Hmget("a", "aa", "bb") assert.Nil(t, err) assert.EqualValues(t, []string{"aaa", "bbb"}, vals) vals, err = client.Hmget("a", "aa", "no", "bb") assert.Nil(t, err) assert.EqualValues(t, []string{"aaa", "", "bbb"}, vals) }) } func TestRedis_Hmset(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.NotNil(t, NewRedis(client.Addr, "").Hmset("a", nil)) assert.Nil(t, client.Hmset("a", map[string]string{ "aa": "aaa", "bb": "bbb", })) vals, err := client.Hmget("a", "aa", "bb") assert.Nil(t, err) assert.EqualValues(t, []string{"aaa", "bbb"}, vals) }) } func TestRedis_Incr(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Incr("a") assert.NotNil(t, err) val, err := client.Incr("a") assert.Nil(t, err) assert.Equal(t, int64(1), val) val, err = client.Incr("a") assert.Nil(t, err) assert.Equal(t, int64(2), val) }) } func TestRedis_IncrBy(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Incrby("a", 2) assert.NotNil(t, err) val, err := client.Incrby("a", 2) assert.Nil(t, err) assert.Equal(t, int64(2), val) val, err = client.Incrby("a", 3) assert.Nil(t, err) assert.Equal(t, int64(5), val) }) } func TestRedis_Keys(t *testing.T) { runOnRedis(t, func(client *Redis) { err := client.Set("key1", "value1") assert.Nil(t, err) err = client.Set("key2", "value2") assert.Nil(t, err) _, err = NewRedis(client.Addr, "").Keys("*") assert.NotNil(t, err) keys, err := client.Keys("*") assert.Nil(t, err) assert.ElementsMatch(t, []string{"key1", "key2"}, keys) }) } func TestRedis_HyperLogLog(t *testing.T) { runOnRedis(t, func(client *Redis) { client.Ping() r := NewRedis(client.Addr, "") _, err := r.Pfadd("key1") assert.NotNil(t, err) _, err = r.Pfcount("*") assert.NotNil(t, err) err = r.Pfmerge("*") assert.NotNil(t, err) }) } func TestRedis_List(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Lpush("key", "value1", "value2") assert.NotNil(t, err) val, err := client.Lpush("key", "value1", "value2") assert.Nil(t, err) assert.Equal(t, 2, val) _, err = NewRedis(client.Addr, "").Rpush("key", "value3", "value4") assert.NotNil(t, err) val, err = client.Rpush("key", "value3", "value4") assert.Nil(t, err) assert.Equal(t, 4, val) _, err = NewRedis(client.Addr, "").Llen("key") assert.NotNil(t, err) val, err = client.Llen("key") assert.Nil(t, err) assert.Equal(t, 4, val) vals, err := client.Lrange("key", 0, 10) assert.Nil(t, err) assert.EqualValues(t, []string{"value2", "value1", "value3", "value4"}, vals) _, err = NewRedis(client.Addr, "").Lpop("key") assert.NotNil(t, err) v, err := client.Lpop("key") assert.Nil(t, err) assert.Equal(t, "value2", v) val, err = client.Lpush("key", "value1", "value2") assert.Nil(t, err) assert.Equal(t, 5, val) val, err = client.Rpush("key", "value3", "value3") assert.Nil(t, err) assert.Equal(t, 7, val) _, err = NewRedis(client.Addr, "").Lrem("key", 2, "value1") assert.NotNil(t, err) n, err := client.Lrem("key", 2, "value1") assert.Nil(t, err) assert.Equal(t, 2, n) _, err = NewRedis(client.Addr, "").Lrange("key", 0, 10) assert.NotNil(t, err) vals, err = client.Lrange("key", 0, 10) assert.Nil(t, err) assert.EqualValues(t, []string{"value2", "value3", "value4", "value3", "value3"}, vals) n, err = client.Lrem("key", -2, "value3") assert.Nil(t, err) assert.Equal(t, 2, n) vals, err = client.Lrange("key", 0, 10) assert.Nil(t, err) assert.EqualValues(t, []string{"value2", "value3", "value4"}, vals) }) } func TestRedis_Mget(t *testing.T) { runOnRedis(t, func(client *Redis) { err := client.Set("key1", "value1") assert.Nil(t, err) err = client.Set("key2", "value2") assert.Nil(t, err) _, err = NewRedis(client.Addr, "").Mget("key1", "key0", "key2", "key3") assert.NotNil(t, err) vals, err := client.Mget("key1", "key0", "key2", "key3") assert.Nil(t, err) assert.EqualValues(t, []string{"value1", "", "value2", ""}, vals) }) } func TestRedis_SetBit(t *testing.T) { runOnRedis(t, func(client *Redis) { err := NewRedis(client.Addr, "").SetBit("key", 1, 1) assert.NotNil(t, err) err = client.SetBit("key", 1, 1) assert.Nil(t, err) }) } func TestRedis_GetBit(t *testing.T) { runOnRedis(t, func(client *Redis) { err := client.SetBit("key", 2, 1) assert.Nil(t, err) _, err = NewRedis(client.Addr, "").GetBit("key", 2) assert.NotNil(t, err) val, err := client.GetBit("key", 2) assert.Nil(t, err) assert.Equal(t, 1, val) }) } func TestRedis_Persist(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Persist("key") assert.NotNil(t, err) ok, err := client.Persist("key") assert.Nil(t, err) assert.False(t, ok) err = client.Set("key", "value") assert.Nil(t, err) ok, err = client.Persist("key") assert.Nil(t, err) assert.False(t, ok) err = NewRedis(client.Addr, "").Expire("key", 5) assert.NotNil(t, err) err = client.Expire("key", 5) assert.Nil(t, err) ok, err = client.Persist("key") assert.Nil(t, err) assert.True(t, ok) err = NewRedis(client.Addr, "").Expireat("key", time.Now().Unix()+5) assert.NotNil(t, err) err = client.Expireat("key", time.Now().Unix()+5) assert.Nil(t, err) ok, err = client.Persist("key") assert.Nil(t, err) assert.True(t, ok) }) } func TestRedis_Ping(t *testing.T) { runOnRedis(t, func(client *Redis) { ok := client.Ping() assert.True(t, ok) }) } func TestRedis_Scan(t *testing.T) { runOnRedis(t, func(client *Redis) { err := client.Set("key1", "value1") assert.Nil(t, err) err = client.Set("key2", "value2") assert.Nil(t, err) _, _, err = NewRedis(client.Addr, "").Scan(0, "*", 100) assert.NotNil(t, err) keys, _, err := client.Scan(0, "*", 100) assert.Nil(t, err) assert.ElementsMatch(t, []string{"key1", "key2"}, keys) }) } func TestRedis_Sscan(t *testing.T) { runOnRedis(t, func(client *Redis) { key := "list" var list []string for i := 0; i < 1550; i++ { list = append(list, randomStr(i)) } lens, err := client.Sadd(key, list) assert.Nil(t, err) assert.Equal(t, lens, 1550) var cursor uint64 = 0 sum := 0 for { _, _, err := NewRedis(client.Addr, "").Sscan(key, cursor, "", 100) assert.NotNil(t, err) keys, next, err := client.Sscan(key, cursor, "", 100) assert.Nil(t, err) sum += len(keys) if next == 0 { break } cursor = next } assert.Equal(t, sum, 1550) _, err = NewRedis(client.Addr, "").Del(key) assert.NotNil(t, err) _, err = client.Del(key) assert.Nil(t, err) }) } func TestRedis_Set(t *testing.T) { runOnRedis(t, func(client *Redis) { _, err := NewRedis(client.Addr, "").Sadd("key", 1, 2, 3, 4) assert.NotNil(t, err) num, err := client.Sadd("key", 1, 2, 3, 4) assert.Nil(t, err) assert.Equal(t, 4, num) _, err = NewRedis(client.Addr, "").Scard("key") assert.NotNil(t, err) val, err := client.Scard("key") assert.Nil(t, err) assert.Equal(t, int64(4), val) _, err = NewRedis(client.Addr, "").Sismember("key", 2) assert.NotNil(t, err) ok, err := client.Sismember("key", 2) assert.Nil(t, err) assert.True(t, ok) _, err = NewRedis(client.Addr, "").Srem("key", 3, 4) assert.NotNil(t, err) num, err = client.Srem("key", 3, 4) assert.Nil(t, err) assert.Equal(t, 2, num) _, err = NewRedis(client.Addr, "").Smembers("key") assert.NotNil(t, err) vals, err := client.Smembers("key") assert.Nil(t, err) assert.ElementsMatch(t, []string{"1", "2"}, vals) _, err = NewRedis(client.Addr, "").Srandmember("key", 1) assert.NotNil(t, err) members, err := client.Srandmember("key", 1) assert.Nil(t, err) assert.Len(t, members, 1) assert.Contains(t, []string{"1", "2"}, members[0]) _, err = NewRedis(client.Addr, "").Spop("key") assert.NotNil(t, err) member, err := client.Spop("key") assert.Nil(t, err) assert.Contains(t, []string{"1", "2"}, member) _, err = NewRedis(client.Addr, "").Smembers("key") assert.NotNil(t, err) vals, err = client.Smembers("key") assert.Nil(t, err) assert.NotContains(t, vals, member) _, err = NewRedis(client.Addr, "").Sadd("key1", 1, 2, 3, 4) assert.NotNil(t, err) num, err = client.Sadd("key1", 1, 2, 3, 4) assert.Nil(t, err) assert.Equal(t, 4, num) num, err = client.Sadd("key2", 2, 3, 4, 5) assert.Nil(t, err) assert.Equal(t, 4, num) _, err = NewRedis(client.Addr, "").Sunion("key1", "key2") assert.NotNil(t, err) vals, err = client.Sunion("key1", "key2") assert.Nil(t, err) assert.ElementsMatch(t, []string{"1", "2", "3", "4", "5"}, vals) _, err = NewRedis(client.Addr, "").Sunionstore("key3", "key1", "key2") assert.NotNil(t, err) num, err = client.Sunionstore("key3", "key1", "key2") assert.Nil(t, err) assert.Equal(t, 5, num) _, err = NewRedis(client.Addr, "").Sdiff("key1", "key2") assert.NotNil(t, err) vals, err = client.Sdiff("key1", "key2") assert.Nil(t, err) assert.EqualValues(t, []string{"1"}, vals) _, err = NewRedis(client.Addr, "").Sdiffstore("key4", "key1", "key2") assert.NotNil(t, err) num, err = client.Sdiffstore("key4", "key1", "key2") assert.Nil(t, err) assert.Equal(t, 1, num) }) } func TestRedis_SetGetDel(t *testing.T) { runOnRedis(t, func(client *Redis) { err := NewRedis(client.Addr, "").Set("hello", "world") assert.NotNil(t, err) err = client.Set("hello", "world") assert.Nil(t, err) _, err = NewRedis(client.Addr, "").Get("hello") assert.NotNil(t, err) val, err := client.Get("hello") assert.Nil(t, err) assert.Equal(t, "world", val) ret, err := client.Del("hello") assert.Nil(t, err) assert.Equal(t, 1, ret) }) } func TestRedis_SetExNx(t *testing.T) { runOnRedis(t, func(client *Redis) { err := NewRedis(client.Addr, "").Setex("hello", "world", 5) assert.NotNil(t, err) err = client.Setex("hello", "world", 5) assert.Nil(t, err) _, err = NewRedis(client.Addr, "").Setnx("hello", "newworld") assert.NotNil(t, err) ok, err := client.Setnx("hello", "newworld") assert.Nil(t, err) assert.False(t, ok) ok, err = client.Setnx("newhello", "newworld") assert.Nil(t, err) assert.True(t, ok) val, err := client.Get("hello") assert.Nil(t, err) assert.Equal(t, "world", val) val, err = client.Get("newhello") assert.Nil(t, err) assert.Equal(t, "newworld", val) ttl, err := client.Ttl("hello") assert.Nil(t, err) assert.True(t, ttl > 0) _, err = NewRedis(client.Addr, "").SetnxEx("newhello", "newworld", 5) assert.NotNil(t, err) ok, err = client.SetnxEx("newhello", "newworld", 5) assert.Nil(t, err) assert.False(t, ok) num, err := client.Del("newhello") assert.Nil(t, err) assert.Equal(t, 1, num) ok, err = client.SetnxEx("newhello", "newworld", 5) assert.Nil(t, err) assert.True(t, ok) val, err = client.Get("newhello") assert.Nil(t, err) assert.Equal(t, "newworld", val) }) } func TestRedis_SetGetDelHashField(t *testing.T) { runOnRedis(t, func(client *Redis) { err := client.Hset("key", "field", "value") assert.Nil(t, err) _, err = NewRedis(client.Addr, "").Hget("key", "field") assert.NotNil(t, err) val, err := client.Hget("key", "field") assert.Nil(t, err) assert.Equal(t, "value", val) _, err = NewRedis(client.Addr, "").Hexists("key", "field") assert.NotNil(t, err) ok, err := client.Hexists("key", "field") assert.Nil(t, err) assert.True(t, ok) _, err = NewRedis(client.Addr, "").Hdel("key", "field") assert.NotNil(t, err) ret, err := client.Hdel("key", "field") assert.Nil(t, err) assert.True(t, ret) ok, err = client.Hexists("key", "field") assert.Nil(t, err) assert.False(t, ok) }) } func TestRedis_SortedSet(t *testing.T) { runOnRedis(t, func(client *Redis) { ok, err := client.Zadd("key", 1, "value1") assert.Nil(t, err) assert.True(t, ok) ok, err = client.Zadd("key", 2, "value1") assert.Nil(t, err) assert.False(t, ok) val, err := client.Zscore("key", "value1") assert.Nil(t, err) assert.Equal(t, int64(2), val) _, err = NewRedis(client.Addr, "").Zincrby("key", 3, "value1") assert.NotNil(t, err) val, err = client.Zincrby("key", 3, "value1") assert.Nil(t, err) assert.Equal(t, int64(5), val) _, err = NewRedis(client.Addr, "").Zscore("key", "value1") assert.NotNil(t, err) val, err = client.Zscore("key", "value1") assert.Nil(t, err) assert.Equal(t, int64(5), val) val, err = NewRedis(client.Addr, "").Zadds("key") assert.NotNil(t, err) val, err = client.Zadds("key", Pair{ Key: "value2", Score: 6, }, Pair{ Key: "value3", Score: 7, }) assert.Nil(t, err) assert.Equal(t, int64(2), val) pairs, err := NewRedis(client.Addr, "").ZRevRangeWithScores("key", 1, 3) assert.NotNil(t, err) pairs, err = client.ZRevRangeWithScores("key", 1, 3) assert.Nil(t, err) assert.EqualValues(t, []Pair{ { Key: "value2", Score: 6, }, { Key: "value1", Score: 5, }, }, pairs) rank, err := client.Zrank("key", "value2") assert.Nil(t, err) assert.Equal(t, int64(1), rank) rank, err = client.Zrevrank("key", "value1") assert.Nil(t, err) assert.Equal(t, int64(2), rank) _, err = NewRedis(client.Addr, "").Zrank("key", "value4") assert.NotNil(t, err) _, err = client.Zrank("key", "value4") assert.Equal(t, Nil, err) _, err = NewRedis(client.Addr, "").Zrem("key", "value2", "value3") assert.NotNil(t, err) num, err := client.Zrem("key", "value2", "value3") assert.Nil(t, err) assert.Equal(t, 2, num) ok, err = client.Zadd("key", 6, "value2") assert.Nil(t, err) assert.True(t, ok) ok, err = client.Zadd("key", 7, "value3") assert.Nil(t, err) assert.True(t, ok) ok, err = client.Zadd("key", 8, "value4") assert.Nil(t, err) assert.True(t, ok) _, err = NewRedis(client.Addr, "").Zremrangebyscore("key", 6, 7) assert.NotNil(t, err) num, err = client.Zremrangebyscore("key", 6, 7) assert.Nil(t, err) assert.Equal(t, 2, num) ok, err = client.Zadd("key", 6, "value2") assert.Nil(t, err) assert.True(t, ok) _, err = NewRedis(client.Addr, "").Zadd("key", 7, "value3") assert.NotNil(t, err) ok, err = client.Zadd("key", 7, "value3") assert.Nil(t, err) assert.True(t, ok) _, err = NewRedis(client.Addr, "").Zcount("key", 6, 7) assert.NotNil(t, err) num, err = client.Zcount("key", 6, 7) assert.Nil(t, err) assert.Equal(t, 2, num) _, err = NewRedis(client.Addr, "").Zremrangebyrank("key", 1, 2) assert.NotNil(t, err) num, err = client.Zremrangebyrank("key", 1, 2) assert.Nil(t, err) assert.Equal(t, 2, num) _, err = NewRedis(client.Addr, "").Zcard("key") assert.NotNil(t, err) card, err := client.Zcard("key") assert.Nil(t, err) assert.Equal(t, 2, card) _, err = NewRedis(client.Addr, "").Zrange("key", 0, -1) assert.NotNil(t, err) vals, err := client.Zrange("key", 0, -1) assert.Nil(t, err) assert.EqualValues(t, []string{"value1", "value4"}, vals) _, err = NewRedis(client.Addr, "").Zrevrange("key", 0, -1) assert.NotNil(t, err) vals, err = client.Zrevrange("key", 0, -1) assert.Nil(t, err) assert.EqualValues(t, []string{"value4", "value1"}, vals) _, err = NewRedis(client.Addr, "").ZrangeWithScores("key", 0, -1) assert.NotNil(t, err) pairs, err = client.ZrangeWithScores("key", 0, -1) assert.Nil(t, err) assert.EqualValues(t, []Pair{ { Key: "value1", Score: 5, }, { Key: "value4", Score: 8, }, }, pairs) _, err = NewRedis(client.Addr, "").ZrangebyscoreWithScores("key", 5, 8) assert.NotNil(t, err) pairs, err = client.ZrangebyscoreWithScores("key", 5, 8) assert.Nil(t, err) assert.EqualValues(t, []Pair{ { Key: "value1", Score: 5, }, { Key: "value4", Score: 8, }, }, pairs) _, err = NewRedis(client.Addr, "").ZrangebyscoreWithScoresAndLimit( "key", 5, 8, 1, 1) assert.NotNil(t, err) pairs, err = client.ZrangebyscoreWithScoresAndLimit("key", 5, 8, 1, 1) assert.Nil(t, err) assert.EqualValues(t, []Pair{ { Key: "value4", Score: 8, }, }, pairs) pairs, err = client.ZrangebyscoreWithScoresAndLimit("key", 5, 8, 1, 0) assert.Nil(t, err) assert.Equal(t, 0, len(pairs)) _, err = NewRedis(client.Addr, "").ZrevrangebyscoreWithScores("key", 5, 8) assert.NotNil(t, err) pairs, err = client.ZrevrangebyscoreWithScores("key", 5, 8) assert.Nil(t, err) assert.EqualValues(t, []Pair{ { Key: "value4", Score: 8, }, { Key: "value1", Score: 5, }, }, pairs) _, err = NewRedis(client.Addr, "").ZrevrangebyscoreWithScoresAndLimit( "key", 5, 8, 1, 1) assert.NotNil(t, err) pairs, err = client.ZrevrangebyscoreWithScoresAndLimit("key", 5, 8, 1, 1) assert.Nil(t, err) assert.EqualValues(t, []Pair{ { Key: "value1", Score: 5, }, }, pairs) pairs, err = client.ZrevrangebyscoreWithScoresAndLimit("key", 5, 8, 1, 0) assert.Nil(t, err) assert.Equal(t, 0, len(pairs)) _, err = NewRedis(client.Addr, "").Zrevrank("key", "value") assert.NotNil(t, err) }) } func TestRedis_Pipelined(t *testing.T) { runOnRedis(t, func(client *Redis) { assert.NotNil(t, NewRedis(client.Addr, "").Pipelined(func(pipeliner Pipeliner) error { return nil })) err := client.Pipelined( func(pipe Pipeliner) error { pipe.Incr("pipelined_counter") pipe.Expire("pipelined_counter", time.Hour) pipe.ZAdd("zadd", Z{Score: 12, Member: "zadd"}) return nil }, ) assert.Nil(t, err) _, err = NewRedis(client.Addr, "").Ttl("pipelined_counter") assert.NotNil(t, err) ttl, err := client.Ttl("pipelined_counter") assert.Nil(t, err) assert.Equal(t, 3600, ttl) value, err := client.Get("pipelined_counter") assert.Nil(t, err) assert.Equal(t, "1", value) score, err := client.Zscore("zadd", "zadd") assert.Nil(t, err) assert.Equal(t, int64(12), score) }) } func TestRedisString(t *testing.T) { runOnRedis(t, func(client *Redis) { client.Ping() _, err := getRedis(NewRedis(client.Addr, ClusterType)) assert.Nil(t, err) assert.Equal(t, client.Addr, client.String()) assert.NotNil(t, NewRedis(client.Addr, "").Ping()) }) } func TestRedisScriptLoad(t *testing.T) { runOnRedis(t, func(client *Redis) { client.Ping() _, err := NewRedis(client.Addr, "").scriptLoad("foo") assert.NotNil(t, err) _, err = client.scriptLoad("foo") assert.NotNil(t, err) }) } func TestRedisToPairs(t *testing.T) { pairs := toPairs([]red.Z{ { Member: 1, Score: 1, }, { Member: 2, Score: 2, }, }) assert.EqualValues(t, []Pair{ { Key: "1", Score: 1, }, { Key: "2", Score: 2, }, }, pairs) } func TestRedisToStrings(t *testing.T) { vals := toStrings([]interface{}{1, 2}) assert.EqualValues(t, []string{"1", "2"}, vals) } func TestRedisBlpop(t *testing.T) { runOnRedis(t, func(client *Redis) { client.Ping() var node mockedNode _, err := client.Blpop(nil, "foo") assert.NotNil(t, err) _, err = client.Blpop(node, "foo") assert.NotNil(t, err) }) } func TestRedisBlpopEx(t *testing.T) { runOnRedis(t, func(client *Redis) { client.Ping() var node mockedNode _, _, err := client.BlpopEx(nil, "foo") assert.NotNil(t, err) _, _, err = client.BlpopEx(node, "foo") assert.NotNil(t, err) }) } func runOnRedis(t *testing.T, fn func(client *Redis)) { s, err := miniredis.Run() assert.Nil(t, err) defer func() { client, err := clientManager.GetResource(s.Addr(), func() (io.Closer, error) { return nil, errors.New("should already exist") }) if err != nil { t.Error(err) } if client != nil { client.Close() } }() fn(NewRedis(s.Addr(), NodeType)) } type mockedNode struct { RedisNode } func (n mockedNode) BLPop(timeout time.Duration, keys ...string) *red.StringSliceCmd { return red.NewStringSliceCmd("foo", "bar") }
amedama41/bulb
test/v13/multipart/group_stats_test.cpp
#define BOOST_TEST_DYN_LINK #include <canard/net/ofp/v13/message/multipart/group_stats.hpp> #include <boost/test/unit_test.hpp> #include "../../test_utility.hpp" namespace ofp = canard::net::ofp; namespace v13 = ofp::v13; namespace protocol = v13::protocol; namespace multipart = v13::messages::multipart; namespace { struct bucket_counter_parameter { std::uint64_t packet_count = 0x0102030405060708; std::uint64_t byte_count = 0x1122334455667788; }; struct bucket_counter_fixture : bucket_counter_parameter { multipart::bucket_counter sut{packet_count, byte_count}; std::vector<std::uint8_t> bin = "\x01\x02\x03\x04\x05\x06\x07\x08""\x11\x22\x33\x44\x55\x66\x77\x88"_bin; }; struct group_stats_parameter { using bucket_stats_type = multipart::group_stats::bucket_stats_type; std::uint32_t group_id = 0x12345678; std::uint32_t ref_count = 0x87654321; std::uint64_t packet_count = 0x0102030405060708; std::uint64_t byte_count = 0x1122334455667788; std::uint32_t duration_sec = 0x11111111; std::uint32_t duration_nsec = 0x22222222; multipart::bucket_counter counter1{0x1111222233334444, 0x0101020203030404}; multipart::bucket_counter counter2{0x5555666677778888, 0x0505060607070808}; multipart::bucket_counter counter3{0xaaaabbbbccccdddd, 0x0a0a0b0b0c0c0d0d}; bucket_stats_type bucket_stats{counter1, counter2, counter3}; }; struct group_stats_fixture : group_stats_parameter { multipart::group_stats sut{ group_id, ref_count , packet_count, byte_count, duration_sec, duration_nsec , bucket_stats }; std::vector<std::uint8_t> bin = "\x00\x58\x00\x00\x12\x34\x56\x78""\x87\x65\x43\x21\x00\x00\x00\x00" "\x01\x02\x03\x04\x05\x06\x07\x08""\x11\x22\x33\x44\x55\x66\x77\x88" "\x11\x11\x11\x11\x22\x22\x22\x22""\x11\x11\x22\x22\x33\x33\x44\x44" "\x01\x01\x02\x02\x03\x03\x04\x04""\x55\x55\x66\x66\x77\x77\x88\x88" "\x05\x05\x06\x06\x07\x07\x08\x08""\xaa\xaa\xbb\xbb\xcc\xcc\xdd\xdd" "\x0a\x0a\x0b\x0b\x0c\x0c\x0d\x0d" ""_bin; }; struct group_stats_request_parameter { std::uint32_t group_id = 0x01020304; std::uint32_t xid = 0x12345678; }; struct group_stats_request_fixture : group_stats_request_parameter { multipart::group_stats_request sut{group_id, xid}; std::vector<std::uint8_t> bin = "\x04\x12\x00\x18\x12\x34\x56\x78""\x00\x06\x00\x00\x00\x00\x00\x00" "\x01\x02\x03\x04\x00\x00\x00\x00" ""_bin; }; struct group_stats_reply_parameter { multipart::bucket_counter counter1{0x1111222233334444, 0x0101020203030404}; multipart::bucket_counter counter2{0x5555666677778888, 0x0505060607070808}; multipart::bucket_counter counter3{0xaaaabbbbccccdddd, 0x0a0a0b0b0c0c0d0d}; multipart::group_stats stats1{ 0x11111111, 0x01010101 , 0x0102030405060708, 0x1020304050607080, 0x1a1a1a1a, 0x1b1b1b1b , { counter1, counter2 } }; multipart::group_stats stats2{ 0x22222222, 0x02020202 , 0x1100220033004400, 0x0011002200330044, 0x1c1c1c1c, 0x1d1d1d1d , { counter3, counter1 } }; multipart::group_stats stats3{ 0x33333333, 0x03030303 , 0x1111000022220000, 0x0000111100002222, 0x1e1e1e1e, 0x1f1f1f1f , {} }; using body_type = multipart::group_stats_reply::body_type; body_type body{stats1, stats2, stats3}; std::uint16_t flags = 1; std::uint32_t xid = 0x12345678; }; struct group_stats_reply_fixture : group_stats_reply_parameter { multipart::group_stats_reply sut{body, flags, xid}; std::vector<std::uint8_t> bin = "\x04\x13\x00\xc8\x12\x34\x56\x78""\x00\x06\x00\x01\x00\x00\x00\x00" "\x00\x48\x00\x00\x11\x11\x11\x11""\x01\x01\x01\x01\x00\x00\x00\x00" "\x01\x02\x03\x04\x05\x06\x07\x08""\x10\x20\x30\x40\x50\x60\x70\x80" "\x1a\x1a\x1a\x1a\x1b\x1b\x1b\x1b""\x11\x11\x22\x22\x33\x33\x44\x44" "\x01\x01\x02\x02\x03\x03\x04\x04""\x55\x55\x66\x66\x77\x77\x88\x88" "\x05\x05\x06\x06\x07\x07\x08\x08" "\x00\x48\x00\x00\x22\x22\x22\x22""\x02\x02\x02\x02\x00\x00\x00\x00" "\x11\x00\x22\x00\x33\x00\x44\x00""\x00\x11\x00\x22\x00\x33\x00\x44" "\x1c\x1c\x1c\x1c\x1d\x1d\x1d\x1d""\xaa\xaa\xbb\xbb\xcc\xcc\xdd\xdd" "\x0a\x0a\x0b\x0b\x0c\x0c\x0d\x0d""\x11\x11\x22\x22\x33\x33\x44\x44" "\x01\x01\x02\x02\x03\x03\x04\x04" "\x00\x28\x00\x00\x33\x33\x33\x33""\x03\x03\x03\x03\x00\x00\x00\x00" "\x11\x11\x00\x00\x22\x22\x00\x00""\x00\x00\x11\x11\x00\x00\x22\x22" "\x1e\x1e\x1e\x1e\x1f\x1f\x1f\x1f" ""_bin; }; } BOOST_AUTO_TEST_SUITE(message_test) BOOST_AUTO_TEST_SUITE(multipart_test) BOOST_AUTO_TEST_SUITE(bucket_counter) BOOST_AUTO_TEST_SUITE(constructor) BOOST_AUTO_TEST_CASE(constructible_from_parameters) { auto const packet_count = std::uint64_t{1234}; auto const byte_count = std::uint64_t{9384}; multipart::bucket_counter const sut{packet_count, byte_count}; BOOST_TEST(sut.length() == sizeof(protocol::ofp_bucket_counter)); BOOST_TEST(sut.packet_count() == packet_count); BOOST_TEST(sut.byte_count() == byte_count); } BOOST_AUTO_TEST_SUITE_END() // constructor BOOST_FIXTURE_TEST_SUITE(equality, bucket_counter_parameter) BOOST_AUTO_TEST_CASE(true_if_same_object) { auto const sut = multipart::bucket_counter{packet_count, byte_count}; BOOST_TEST((sut == sut)); } BOOST_AUTO_TEST_CASE(true_if_values_are_equal) { BOOST_TEST( (multipart::bucket_counter{packet_count, byte_count} == multipart::bucket_counter{packet_count, byte_count})); } BOOST_AUTO_TEST_CASE(false_if_packet_count_is_not_equal) { BOOST_TEST( (multipart::bucket_counter{1, byte_count} != multipart::bucket_counter{2, byte_count})); } BOOST_AUTO_TEST_CASE(false_if_byte_count_is_not_equal) { BOOST_TEST( (multipart::bucket_counter{packet_count, 1} != multipart::bucket_counter{packet_count, 2})); } BOOST_AUTO_TEST_SUITE_END() // equality BOOST_AUTO_TEST_SUITE(encode) BOOST_FIXTURE_TEST_CASE(generate_binary, bucket_counter_fixture) { auto buffer = std::vector<std::uint8_t>{}; add_const(sut).encode(buffer); BOOST_TEST(buffer.size() == sut.byte_length()); BOOST_TEST(buffer == bin, boost::test_tools::per_element{}); } BOOST_AUTO_TEST_SUITE_END() // equality BOOST_AUTO_TEST_SUITE(decode) BOOST_FIXTURE_TEST_CASE(construct_from_binary, bucket_counter_fixture) { auto it = bin.begin(); auto const bucket_counter = multipart::bucket_counter::decode(it, bin.end()); BOOST_TEST((it == bin.end())); BOOST_TEST((bucket_counter == sut)); } BOOST_AUTO_TEST_SUITE_END() // decode BOOST_AUTO_TEST_SUITE_END() // bucket_counter BOOST_AUTO_TEST_SUITE(group_stats) BOOST_AUTO_TEST_SUITE(constructor) BOOST_AUTO_TEST_CASE(constructible_from_parameters) { auto const group_id = std::uint32_t{0x12345678}; auto const ref_count = std::uint32_t{5}; auto const packet_count = std::uint64_t{1234}; auto const byte_count = std::uint64_t{1235}; auto const duration_sec = std::uint32_t{32}; auto const duration_nsec = std::uint32_t{91}; auto const bucket_stats = multipart::group_stats::bucket_stats_type{ multipart::bucket_counter{1, 2} , multipart::bucket_counter{3, 4} , multipart::bucket_counter{5, 6} }; multipart::group_stats const sut{ group_id, ref_count , packet_count, byte_count, duration_sec, duration_nsec , bucket_stats }; BOOST_TEST( sut.length() == sizeof(protocol::ofp_group_stats) + bucket_stats.length()); BOOST_TEST(sut.group_id() == group_id); BOOST_TEST(sut.ref_count() == ref_count); BOOST_TEST(sut.packet_count() == packet_count); BOOST_TEST(sut.byte_count() == byte_count); BOOST_TEST(sut.duration_sec() == duration_sec); BOOST_TEST(sut.duration_nsec() == duration_nsec); BOOST_TEST((sut.bucket_stats() == bucket_stats)); } BOOST_AUTO_TEST_CASE(constructible_from_empty_bucket_stats) { auto const group_id = std::uint32_t{1000}; auto const ref_count = std::uint32_t{2000}; auto const packet_count = std::uint64_t{3000}; auto const byte_count = std::uint64_t{4000}; auto const duration_sec = std::uint32_t{5000}; auto const duration_nsec = std::uint32_t{6000}; multipart::group_stats const sut{ group_id, ref_count , packet_count, byte_count, duration_sec, duration_nsec , multipart::group_stats::bucket_stats_type{} }; BOOST_TEST(sut.length() == sizeof(protocol::ofp_group_stats)); BOOST_TEST(sut.group_id() == group_id); BOOST_TEST(sut.ref_count() == ref_count); BOOST_TEST(sut.packet_count() == packet_count); BOOST_TEST(sut.byte_count() == byte_count); BOOST_TEST(sut.duration_sec() == duration_sec); BOOST_TEST(sut.duration_nsec() == duration_nsec); BOOST_TEST(sut.bucket_stats().empty()); } BOOST_FIXTURE_TEST_CASE(copy_constructible, group_stats_fixture) { auto const copy = add_const(sut); BOOST_TEST((copy == sut)); } BOOST_FIXTURE_TEST_CASE(move_constructible, group_stats_fixture) { auto moved = sut; auto const copy = std::move(moved); BOOST_TEST((copy == sut)); BOOST_TEST(moved.length() == sizeof(protocol::ofp_group_stats)); BOOST_TEST(moved.bucket_stats().empty()); } BOOST_AUTO_TEST_SUITE_END() // constructor BOOST_FIXTURE_TEST_SUITE(assignment, group_stats_fixture) BOOST_AUTO_TEST_CASE(copy_assignable) { auto copy = multipart::group_stats{0, 0, 0, 0, 0, 0, {}}; copy = add_const(sut); BOOST_TEST((copy == sut)); } BOOST_AUTO_TEST_CASE(move_assignable) { auto copy = multipart::group_stats{0, 0, 0, 0, 0, 0, {}}; auto moved = sut; copy = std::move(moved); BOOST_TEST((copy == sut)); BOOST_TEST(moved.length() == sizeof(protocol::ofp_group_stats)); BOOST_TEST(moved.bucket_stats().empty()); } BOOST_AUTO_TEST_SUITE_END() // assignment BOOST_FIXTURE_TEST_SUITE(equality, group_stats_parameter) BOOST_AUTO_TEST_CASE(true_if_same_object) { auto const sut = multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats }; BOOST_TEST((sut == sut)); } BOOST_AUTO_TEST_CASE(true_if_values_are_equal) { BOOST_TEST( (multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats } == multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_group_id_is_not_equal) { BOOST_TEST( (multipart::group_stats{ 1, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats } != multipart::group_stats{ 2, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_ref_count_is_not_equal) { BOOST_TEST( (multipart::group_stats{ group_id, 1, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats } != multipart::group_stats{ group_id, 2, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_packet_count_is_not_equal) { BOOST_TEST( (multipart::group_stats{ group_id, ref_count, 1, byte_count , duration_sec, duration_nsec, bucket_stats } != multipart::group_stats{ group_id, ref_count, 2, byte_count , duration_sec, duration_nsec, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_byte_count_is_not_equal) { BOOST_TEST( (multipart::group_stats{ group_id, ref_count, packet_count, 1 , duration_sec, duration_nsec, bucket_stats } != multipart::group_stats{ group_id, ref_count, packet_count, 2 , duration_sec, duration_nsec, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_duration_sec_is_not_equal) { BOOST_TEST( (multipart::group_stats{ group_id, ref_count, packet_count, byte_count , 1, duration_nsec, bucket_stats } != multipart::group_stats{ group_id, ref_count, packet_count, byte_count , 2, duration_nsec, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_duration_nsec_is_not_equal) { BOOST_TEST( (multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, 1, bucket_stats } != multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, 2, bucket_stats })); } BOOST_AUTO_TEST_CASE(false_if_bucket_stats_is_not_equal) { BOOST_TEST( (multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats_type{counter1} } != multipart::group_stats{ group_id, ref_count, packet_count, byte_count , duration_sec, duration_nsec, bucket_stats_type{counter2} })); } BOOST_AUTO_TEST_SUITE_END() // equality BOOST_AUTO_TEST_SUITE(extract_bucket_stats) BOOST_FIXTURE_TEST_CASE(move_bucket_stats_ownership, group_stats_fixture) { auto const original_bucket_stats = sut.bucket_stats(); auto const bucket_stats = sut.extract_bucket_stats(); BOOST_TEST((bucket_stats == original_bucket_stats)); BOOST_TEST(sut.length() == sizeof(protocol::ofp_group_stats)); BOOST_TEST(sut.bucket_stats().empty()); } BOOST_AUTO_TEST_SUITE_END() // extract_bucket_stats BOOST_AUTO_TEST_SUITE(encode) BOOST_FIXTURE_TEST_CASE(generate_binary, group_stats_fixture) { auto buffer = std::vector<std::uint8_t>{}; add_const(sut).encode(buffer); BOOST_TEST(buffer.size() == sut.byte_length()); BOOST_TEST(buffer == bin, boost::test_tools::per_element{}); } BOOST_AUTO_TEST_SUITE_END() // encode BOOST_AUTO_TEST_SUITE(decode) BOOST_FIXTURE_TEST_CASE(construct_from_binary, group_stats_fixture) { auto it = bin.begin(); auto const group_stats = multipart::group_stats::decode(it, bin.end()); BOOST_TEST((it == bin.end())); BOOST_TEST((group_stats == sut)); } BOOST_AUTO_TEST_SUITE_END() // decode BOOST_AUTO_TEST_SUITE_END() // group_stats BOOST_AUTO_TEST_SUITE(group_stats_request) BOOST_AUTO_TEST_SUITE(type_definition) BOOST_AUTO_TEST_CASE(message_type) { using sut = multipart::group_stats_request; constexpr auto message_type = sut::type(); BOOST_TEST(message_type == protocol::msg_type::multipart_request); } BOOST_AUTO_TEST_CASE(multipart_type) { using sut = multipart::group_stats_request; constexpr auto multipart_type = sut::multipart_type(); BOOST_TEST(multipart_type == protocol::multipart_type::group); } BOOST_AUTO_TEST_SUITE_END() // type_definition BOOST_AUTO_TEST_SUITE(constructor) BOOST_AUTO_TEST_CASE(constructible_from_parameters) { auto const group_id = std::uint32_t{32}; auto const xid = std::uint32_t{34129}; multipart::group_stats_request const sut{group_id, xid}; BOOST_TEST( sut.length() == sizeof(protocol::ofp_multipart_request) + sizeof(protocol::ofp_group_stats_request)); BOOST_TEST(sut.flags() == 0); BOOST_TEST(sut.group_id() == group_id); BOOST_TEST(sut.xid() == xid); } BOOST_AUTO_TEST_CASE(constructible_without_xid) { auto const group_id = std::uint32_t{0}; multipart::group_stats_request const sut{group_id}; BOOST_TEST( sut.length() == sizeof(protocol::ofp_multipart_request) + sizeof(protocol::ofp_group_stats_request)); BOOST_TEST(sut.flags() == 0); } BOOST_AUTO_TEST_SUITE_END() // constructor BOOST_FIXTURE_TEST_SUITE(equality, group_stats_request_parameter) BOOST_AUTO_TEST_CASE(true_if_same_object) { auto const sut = multipart::group_stats_request{group_id, xid}; BOOST_TEST((sut == sut)); } BOOST_AUTO_TEST_CASE(true_if_xid_is_equal) { BOOST_TEST( (multipart::group_stats_request{group_id, xid} == multipart::group_stats_request{group_id, xid})); } BOOST_AUTO_TEST_CASE(false_if_group_id_is_not_equal) { BOOST_TEST( (multipart::group_stats_request{1, xid} != multipart::group_stats_request{2, xid})); } BOOST_AUTO_TEST_CASE(false_if_xid_is_not_equal) { BOOST_TEST( (multipart::group_stats_request{group_id, 1} != multipart::group_stats_request{group_id, 2})); } BOOST_AUTO_TEST_SUITE_END() // equality BOOST_AUTO_TEST_SUITE(encode) BOOST_FIXTURE_TEST_CASE(generate_binary, group_stats_request_fixture) { auto buffer = std::vector<std::uint8_t>{}; add_const(sut).encode(buffer); BOOST_TEST(buffer.size() == sut.byte_length()); BOOST_TEST(buffer == bin, boost::test_tools::per_element{}); } BOOST_AUTO_TEST_SUITE_END() // encode BOOST_AUTO_TEST_SUITE(decode) BOOST_FIXTURE_TEST_CASE(construct_from_binary, group_stats_request_fixture) { auto it = bin.begin(); auto const group_stats_request = multipart::group_stats_request::decode(it, bin.end()); BOOST_TEST((it == bin.end())); BOOST_TEST((group_stats_request == sut)); } BOOST_AUTO_TEST_SUITE_END() // decode BOOST_AUTO_TEST_SUITE_END() // group_stats_request BOOST_AUTO_TEST_SUITE(group_stats_reply) BOOST_AUTO_TEST_SUITE_END() // group_stats_reply BOOST_AUTO_TEST_SUITE(group_stats_reply) BOOST_AUTO_TEST_SUITE(type_definition) BOOST_AUTO_TEST_CASE(message_type) { using sut = multipart::group_stats_reply; constexpr auto message_type = sut::type(); BOOST_TEST(message_type == protocol::msg_type::multipart_reply); } BOOST_AUTO_TEST_CASE(multipart_type) { using sut = multipart::group_stats_reply; constexpr auto multipart_type = sut::multipart_type(); BOOST_TEST(multipart_type == protocol::multipart_type::group); } BOOST_AUTO_TEST_SUITE_END() // type_definition BOOST_AUTO_TEST_SUITE(constructor) BOOST_FIXTURE_TEST_CASE( constructible_from_parameters, group_stats_reply_parameter) { auto const body = body_type{stats1, stats2}; auto const flags = std::uint16_t{1}; auto const xid = std::uint32_t{1234}; multipart::group_stats_reply const sut{body, flags, xid}; BOOST_TEST( sut.length() == sizeof(protocol::ofp_multipart_reply) + body.length()); BOOST_TEST(sut.xid() == xid); BOOST_TEST(sut.flags() == flags); BOOST_TEST((sut.body() == body)); } BOOST_FIXTURE_TEST_CASE( constructible_without_xid, group_stats_reply_parameter) { auto const body = body_type{stats3}; auto const flags = std::uint16_t{0}; multipart::group_stats_reply const sut{body, flags}; BOOST_TEST( sut.length() == sizeof(protocol::ofp_multipart_reply) + body.length()); BOOST_TEST(sut.flags() == flags); BOOST_TEST((sut.body() == body)); } BOOST_FIXTURE_TEST_CASE( constructible_without_flags, group_stats_reply_parameter) { auto const body = body_type{}; multipart::group_stats_reply const sut{body}; BOOST_TEST( sut.length() == sizeof(protocol::ofp_multipart_reply) + body.length()); BOOST_TEST(sut.flags() == 0); BOOST_TEST((sut.body() == body)); } BOOST_FIXTURE_TEST_CASE(copy_constructible, group_stats_reply_fixture) { auto const copy = add_const(sut); BOOST_TEST((copy == sut)); } BOOST_FIXTURE_TEST_CASE(move_constructible, group_stats_reply_fixture) { auto moved = sut; auto const copy = std::move(moved); BOOST_TEST((copy == sut)); BOOST_TEST(moved.length() == sizeof(protocol::ofp_multipart_reply)); BOOST_TEST(moved.body().empty()); } BOOST_AUTO_TEST_SUITE_END() // constructor BOOST_FIXTURE_TEST_SUITE(equality, group_stats_reply_parameter) BOOST_AUTO_TEST_CASE(true_if_same_object) { auto const sut = multipart::group_stats_reply{body, flags, xid}; BOOST_TEST((sut == sut)); } BOOST_AUTO_TEST_CASE(true_if_values_are_equal) { BOOST_TEST( (multipart::group_stats_reply{body, flags, xid} == multipart::group_stats_reply{body, flags, xid})); } BOOST_AUTO_TEST_CASE(false_if_body_is_not_equal) { BOOST_TEST( (multipart::group_stats_reply{body_type{stats1, stats2}, flags, xid} != multipart::group_stats_reply{body_type{stats2, stats1}, flags, xid})); } BOOST_AUTO_TEST_CASE(false_if_flags_is_not_equal) { BOOST_TEST( (multipart::group_stats_reply{body, 1, xid} != multipart::group_stats_reply{body, 2, xid})); } BOOST_AUTO_TEST_CASE(false_if_xid_is_not_equal) { BOOST_TEST( (multipart::group_stats_reply{body, flags, 1} != multipart::group_stats_reply{body, flags, 2})); } BOOST_AUTO_TEST_SUITE_END() // equality BOOST_AUTO_TEST_SUITE(encode) BOOST_FIXTURE_TEST_CASE(generate_binary, group_stats_reply_fixture) { auto buffer = std::vector<std::uint8_t>{}; add_const(sut).encode(buffer); BOOST_TEST(buffer.size() == sut.byte_length()); BOOST_TEST(buffer == bin, boost::test_tools::per_element{}); } BOOST_AUTO_TEST_SUITE_END() // encode BOOST_AUTO_TEST_SUITE(decode) BOOST_FIXTURE_TEST_CASE(construct_from_binary, group_stats_reply_fixture) { auto it = bin.begin(); auto const group_stats_reply = multipart::group_stats_reply::decode(it, bin.end()); BOOST_TEST((it == bin.end())); BOOST_TEST((group_stats_reply == sut)); } BOOST_AUTO_TEST_SUITE_END() // decode BOOST_AUTO_TEST_SUITE_END() // group_stats_reply BOOST_AUTO_TEST_SUITE_END() // multipart_test BOOST_AUTO_TEST_SUITE_END() // message_test
jonassignoreti/Python-CursoemVideo
venv/Exercises/ex109.py
'''Modifique as funções que foram criadas no desafio 107 para que elas aceitem um um parâmetro a mais, informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108.''' from pacotes import moedas p = float(input('Digite o preço R$: ')) print(f'A metade de {moedas.moeda(p)} é {moedas.metade(p, format=True)}') print(f'O dobro de {moedas.moeda(p)} é {moedas.dobro(p, format=True)}') print(f'Aumentando 10%, temos {moedas.aumentar(p, 10, format=True)}') print(f'Reduzindo 13%, temos {moedas.diminuir(p, 13, format=True)}')
wwdok/mask2json
convertmask/labelme_sub/cli/draw_json.py
<reponame>wwdok/mask2json<gh_stars>10-100 ''' lanhuage: python Descripttion: version: beta Author: xiaoshuyui Date: 2020-10-16 10:08:47 LastEditors: xiaoshuyui LastEditTime: 2020-10-16 11:00:53 ''' #!/usr/bin/env python import argparse import base64 import json import os import sys import imgviz import matplotlib.pyplot as plt from convertmask.labelme_sub import utils PY2 = sys.version_info[0] == 2 def main(): parser = argparse.ArgumentParser() parser.add_argument('json_file') args = parser.parse_args() json_file = args.json_file data = json.load(open(json_file)) if data['imageData']: imageData = data['imageData'] else: imagePath = os.path.join(os.path.dirname(json_file), data['imagePath']) with open(imagePath, 'rb') as f: imageData = f.read() imageData = base64.b64encode(imageData).decode('utf-8') img = utils.img_b64_to_arr(imageData) label_name_to_value = {'_background_': 0} for shape in sorted(data['shapes'], key=lambda x: x['label']): label_name = shape['label'] if label_name in label_name_to_value: label_value = label_name_to_value[label_name] else: label_value = len(label_name_to_value) label_name_to_value[label_name] = label_value lbl, _ = utils.shapes_to_label( img.shape, data['shapes'], label_name_to_value ) label_names = [None] * (max(label_name_to_value.values()) + 1) for name, value in label_name_to_value.items(): label_names[value] = name lbl_viz = imgviz.label2rgb( label=lbl, img=imgviz.rgb2gray(img), label_names=label_names, font_size=30, loc='rb', ) plt.subplot(121) plt.imshow(img) plt.subplot(122) plt.imshow(lbl_viz) plt.show() if __name__ == '__main__': main()
inspire12/robolectric
robolectric/src/test/java/org/robolectric/internal/bytecode/testing/AnInstrumentedClassWithoutToStringWithSuperToString.java
<gh_stars>10-100 package org.robolectric.internal.bytecode.testing; import org.robolectric.annotation.internal.Instrument; @Instrument public class AnInstrumentedClassWithoutToStringWithSuperToString extends AnUninstrumentedClassWithToString { }
rafasantos/matchandtrade-api
src/main/java/com/matchandtrade/rest/v1/transformer/AuthenticationTransformer.java
<filename>src/main/java/com/matchandtrade/rest/v1/transformer/AuthenticationTransformer.java package com.matchandtrade.rest.v1.transformer; import com.matchandtrade.persistence.entity.AuthenticationEntity; import com.matchandtrade.rest.v1.json.AuthenticationJson; public class AuthenticationTransformer extends Transformer<AuthenticationEntity, AuthenticationJson> { @Override public AuthenticationJson transform(AuthenticationEntity entity) { AuthenticationJson result = new AuthenticationJson(); result.setUserId(entity.getUser().getUserId()); return result; } @Override public AuthenticationEntity transform(AuthenticationJson json) { // So far nobody needs this method. Fell free to implement it when needed. throw new UnsupportedOperationException(); } }
KuntzeM/Medienprojekt-WebServer
public/filemanager/scripts/CodeMirror/test/phantom_driver.js
var page = require('webpage').create(); page.open("http://localhost:3000/test/index.html", function (status) { if (status != "success") { console.log("page couldn't be loaded successfully"); phantom.exit(1); } waitFor(function () { return page.evaluate(function () { var output = document.getElementById('status'); if (!output) { return false; } return (/^(\d+ failures?|all passed)/i).test(output.innerText); }); }, function () { var failed = page.evaluate(function () { return window.failed; }); var output = page.evaluate(function () { return document.getElementById('output').innerText + "\n" + document.getElementById('status').innerText; }); console.log(output); phantom.exit(failed > 0 ? 1 : 0); }); }); function waitFor(test, cb) { if (test()) { cb(); } else { setTimeout(function () { waitFor(test, cb); }, 250); } }
zealoussnow/chromium
net/test/android/javatests/src/org/chromium/net/test/EmbeddedTestServerService.java
// Copyright 2015 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. package org.chromium.net.test; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * A {@link android.app.Service} that creates a new {@link EmbeddedTestServer} when bound. */ public class EmbeddedTestServerService extends Service { @Override public IBinder onBind(Intent intent) { return new EmbeddedTestServerImpl(this); } }
kkauder/spack
var/spack/repos/builtin/packages/geoip-api-c/package.py
<reponame>kkauder/spack<filename>var/spack/repos/builtin/packages/geoip-api-c/package.py # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class GeoipApiC(AutotoolsPackage): """The GeoIP Legacy C library enables the user to find geographical and network information of an IP address.""" homepage = "https://github.com/maxmind/geoip-api-c" url = "https://github.com/maxmind/geoip-api-c/archive/v1.6.12.tar.gz" version('1.6.12', sha256='99b119f8e21e94f1dfd6d49fbeed29a70df1544896e76cd456f25e397b07d476') version('1.6.11', sha256='b0e5a92200b5ab540d118983f7b7191caf4faf1ae879c44afa3ff2a2abcdb0f5') version('1.6.10', sha256='cb44e0d0dbc45efe2e399e695864e58237ce00026fba8a74b31d85888c89c67a') depends_on('autoconf', type='build') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build')
dnvriend/serverless-test
aws-lambda-handler/src/main/scala/com/github/dnvriend/ops/FunctionalOps.scala
<reponame>dnvriend/serverless-test<gh_stars>1-10 package com.github.dnvriend.ops import com.github.dnvriend.ops.Functional.DisjunctionNel import scala.language.implicitConversions import scalaz.Scalaz._ import scalaz._ object Functional { type DisjunctionNel[A, B] = Disjunction[NonEmptyList[A], B] } trait FunctionalOps { implicit def ToFunctionalOpsImpl[A](that: => A) = new FunctionalOpsImpl(that) implicit class FEitherOps[F[_]: Functor: Traverse, A, B](that: F[Either[A, B]])(implicit x: Unapply[Applicative, Either[A, B]]) { implicit def toSequencedDisjunction: DisjunctionNel[A, F[B]] = { that.map(_.disjunction.validationNel).sequenceU.disjunction } } implicit class EitherOps[A, B](that: Either[A, B]) { def toDisjunctionNel: DisjunctionNel[A, B] = { that.disjunction.validationNel.disjunction } } } class FunctionalOpsImpl[A](that: => A) { def safe: Disjunction[Throwable, A] = Disjunction.fromTryCatchNonFatal(that) def safeNel: DisjunctionNel[Throwable, A] = Disjunction.fromTryCatchNonFatal(that).leftMap(_.wrapNel) def safeMsg(msg: String): DisjunctionNel[Throwable, A] = safe.leftMap(t => new RuntimeException(s"$msg, because: '${t.getMessage}'").wrapNel.widen[Throwable]) def ? : Option[A] = Option(that) def log(implicit show: Show[A] = null): A = { val msg: String = Option(show).map(_.shows(that)).getOrElse(that.toString) println(msg) that } }
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/util/QSHttpCallback.java
package org.song.http.framework.util; import android.app.Activity; import android.app.Fragment; import android.os.Build; import android.util.Log; import android.view.View; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import org.song.http.framework.HttpEnum; import org.song.http.framework.HttpException; import org.song.http.framework.ResponseParams; import org.song.http.framework.ability.HttpCallbackEx; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Created by song * Contact github.com/tohodog * Date 2019/4/11 * 回调封装,支持解析,泛型 * 生命周期销毁(外部类是activity销毁了不会回调),不想销毁覆盖isDestroy方法 */ public abstract class QSHttpCallback<T> implements HttpCallbackEx { protected Activity activity; protected ResponseParams response; public QSHttpCallback() { activity = findActivity(this); } public QSHttpCallback(Activity activity) { this.activity = activity; } public abstract void onComplete(T dataBean); @Override public void onSuccess(ResponseParams response) { this.response = response; try { if (response.resultType() == HttpEnum.ResultType.STRING) { onComplete(map(response.string())); } else if (response.resultType() == HttpEnum.ResultType.BYTES) { onComplete((T) response.bytes()); } else if (response.resultType() == HttpEnum.ResultType.FILE) { onComplete((T) new File(response.file())); } } catch (JSONException e) { e.printStackTrace(); onFailure(HttpException.Parser(e).responseParams(response)); } catch (HttpException e1) { onFailure(e1.responseParams(response)); } } protected T map(String result) throws HttpException { return parserT(result); } protected T parserT(String json) throws JSONException { T dataBean = null; Type type = findT(); if (type == String.class) { dataBean = (T) json; } else { dataBean = JSON.parseObject(json, type); } return dataBean; } protected Type findT() { Type type = getClass().getGenericSuperclass(); if (!(type instanceof ParameterizedType)) { type = String.class; } else { ParameterizedType parameterizedType = (ParameterizedType) type; // if (parameterizedType.getActualTypeArguments()[0] instanceof ParameterizedType) { // ParameterizedType parameterizedType1 = (ParameterizedType) parameterizedType.getActualTypeArguments()[0]; // type = parameterizedType1.getRawType(); //T=List<xxx> // Class<?> clazz = (Class<?>) parameterizedType1.getActualTypeArguments()[0]; // } else { type = parameterizedType.getActualTypeArguments()[0]; // } } return type; } @Override public void onFailure(HttpException e) { e.show(); } @Override public void onStart() { } @Override public void onEnd() { } @Override public boolean isDestroy() { return activity != null && activity.isFinishing(); } public static <T> List<T> parserList(JSONArray jsonArray, Class<T> _class) { List<T> list = new ArrayList<>(); if (jsonArray != null) for (int i = 0; i < jsonArray.size(); i++) { list.add(jsonArray.getJSONObject(i).toJavaObject(_class)); } return list; } public static Activity findActivity(Object o) { //获取外部类 Object ext = field(o, "this$0"); Log.d(Utils.TAG, "findActivity:" + ext); if (ext != null) { if (ext instanceof Activity) { return ((Activity) ext); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { if (ext instanceof Fragment && ((Fragment) ext).getActivity() != null) { return ((Fragment) ext).getActivity(); } } if (ext instanceof View) { View view = (View) ext; if ((view.getContext() instanceof Activity)) { return ((Activity) view.getContext()); } } try { Class<?> exClass = Class.forName("android.support.v4.app.Fragment"); if (exClass.isAssignableFrom(ext.getClass())) { Method method = exClass.getMethod("getActivity"); method.setAccessible(true); return (Activity) method.invoke(ext, new Object[0]); } } catch (Exception e) { // e.printStackTrace(); } try { Class<?> exClass = Class.forName("androidx.fragment.app.Fragment"); if (exClass.isAssignableFrom(ext.getClass())) { Method method = exClass.getMethod("getActivity"); method.setAccessible(true); return (Activity) method.invoke(ext, new Object[0]); } } catch (Exception e) { // e.printStackTrace(); } } return null; } public static Object field(Object base, String fieldName) { try { Class<?> clazz; if (base instanceof String) { clazz = Class.forName(base.toString()); base = clazz; } else if (base instanceof Class) clazz = (Class<?>) base; else clazz = base.getClass(); Field f = clazz.getDeclaredField(fieldName); f.setAccessible(true); return f.get(base); } catch (Exception e) { } return null; } }
izycheva/daisy
src/main/scala/daisy/analysis/SpecsProcessingPhase.scala
<reponame>izycheva/daisy<filename>src/main/scala/daisy/analysis/SpecsProcessingPhase.scala // Copyright 2017 MPI-SWS, Saarbruecken, Germany package daisy package analysis import scala.collection.immutable.{Map, Seq} import scala.util.parsing.combinator._ import lang.Trees._ import tools.{Interval, PartialInterval, Rational, FinitePrecision} import FinitePrecision._ import lang.Identifiers._ import lang.Extractors._ import lang.TreeOps.allVariablesOf import lang.Trees.Program /** This phase extracts information from the specifications (requires, ensuring) and puts it somewhere useful. Note: - extract upper and lower bounds as well as absolute errors on the precondition - strictly greater than is extracted as greater-equal - if a bound is defined twice, then any of the bounds can be recorded, i.e. there is no checking for weakest or strongest - absolute error can be only a single rational number, i.e. in the form x +/- 5 - does not check for completeness of spec - assumes fnc. body exists (does not check) - ignores functions without precondiion Prerequisite: None */ object SpecsProcessingPhase extends DaisyPhase with PrecisionsParser { override val name = "Specs processing" override val shortName = "specs" override val description = "Processes the specifications for later phases." implicit val debugSection = DebugSectionAnalysis var reporter: Reporter = null def runPhase(ctx: Context, prg: Program): (Context, Program) = { reporter = ctx.reporter val trackInitialErrs = !ctx.hasFlag("noInitialErrors") val trackRoundoffErrs = !ctx.hasFlag("noRoundoff") val defaultPrecision = ctx.option[Precision]("precision") // By default, each function's input variables are given defaultPrecision var inputPrecision: Map[Identifier, Map[Identifier, Precision]] = Map.empty.withDefaultValue(Map.empty.withDefaultValue(defaultPrecision)) // By default, each function will return with defaultPrecision var resultPrecisions: Map[Identifier, Precision] = Map.empty.withDefaultValue(defaultPrecision) ctx.option[Option[String]]("mixed-precision") match { case Some(file) => // a mixed-precision assignment file has been provided, parse it val precMapsParsed = parseMixedPrecisionFile(file, prg) prg.defs.foreach(fnc => { (precMapsParsed.get(fnc.id), fnc.body) match { // no spec is given, so use default precision case (None, _) => case (Some(precMap), None) => inputPrecision += fnc.id -> precMap case (Some(precMap), Some(body)) => val (completePrecMap, returnPrec) = typecheck(body, precMap, defaultPrecision) inputPrecision += fnc.id -> completePrecMap resultPrecisions += fnc.id -> returnPrec } }) case None => } // ctx.reporter.info("precision map:") // ctx.reporter.info(precisionMap) var allRanges: Map[Identifier, Map[Identifier, Interval]] = Map() var allErrors: Map[Identifier, Map[Identifier, Rational]] = Map() var resRanges: Map[Identifier, PartialInterval] = Map() var resErrors: Map[Identifier, Rational] = Map() var additionalConst: Map[Identifier, Expr] = Map() var resIds: Map[Identifier, Seq[Identifier]] = Map() // var requiredOutputRanges: Map[Identifier, Map[Identifier, PartialInterval]] = Map() // var requiredOutputErrors: Map[Identifier, Map[Identifier, Rational]] = Map() val newDefs = transformConsideredFunctions(ctx, prg){ fnc => fnc.precondition match { case Some(pre) => // TODO: additional constraints val (ranges, errors, addConds) = extractPreCondition(pre) val missingKeys = fnc.params.map(_.id).diff(ranges.keys.toSeq) if (!missingKeys.isEmpty) { reporter.fatalError("Incomplete or missing range for " + missingKeys.mkString(", ")) } allRanges += (fnc.id -> ranges.map(x => (x._1 -> Interval(x._2._1, x._2._2)))) // If we track both input and roundoff errors, then we pre-compute // the roundoff errors for those variables that do not have a user-defined // error, in order to keep correlations. allErrors += (fnc.id -> ({ // get the possibly mixed-precision map val precisionMap = inputPrecision(fnc.id) if (trackInitialErrs && trackRoundoffErrs){ val allIDs = fnc.params.map(_.id).toSet val missingIDs = allIDs -- errors.keySet errors ++ missingIDs.map(id => (id -> precisionMap(id).absRoundoff(allRanges(fnc.id)(id)))) } else if (trackInitialErrs) { val allIDs = fnc.params.map(_.id).toSet val missingIDs = allIDs -- errors.keySet errors ++ missingIDs.map(id => (id -> Rational.zero)) } else if (trackRoundoffErrs) { val allIDs = fnc.params.map(_.id) allIDs.map(id => (id -> precisionMap(id).absRoundoff(allRanges(fnc.id)(id)))).toMap } else { val allIDs = fnc.params.map(_.id) allIDs.map(id => (id -> Rational.zero)).toMap }})) addConds match { case Seq() => additionalConst += (fnc.id -> BooleanLiteral(true)) // no additional constraints case Seq(x) => additionalConst += (fnc.id -> x) case _ => additionalConst += (fnc.id -> And(addConds)) } // annotate the variables in the function body directly // preTraversal ({ // case x @ Variable(id) => // ranges.get(id) match { // case Some((a, b)) => x.interval = Interval(a, b) // case None => ; // } // errors.get(id) match { // case Some(err) => x.absError = err // case None => ; // } // case _ => ; // })(fnc.body.get) case _ => } // If there is a partial post condition, there will be an empty map for range or error // If there is no post condition, there will be no map at all. // This allows us to differentiate between these two cases - for future use fnc.postcondition match { case Some(post) => val (ranges, errors) = extractPostCondition(post) assert(ranges.size <= 1) assert(errors.size <= 1) // no range given in postcondition if (ranges.size == 1) { val tmp = ranges.values.head resRanges += (fnc.id -> PartialInterval(tmp._1, tmp._2)) } else if (ranges.size > 1) { ctx.reporter.error("Tuples are not supported.") } if (errors.size == 1) { val tmp = errors.values.head resErrors += (fnc.id -> tmp) } else if (errors.size > 1) { ctx.reporter.error("Tuples are not supported.") } // requiredOutputRanges += (fnc.id -> ranges.map( x => // (x._1 -> PartialInterval(x._2._1, x._2._2) ))) // requiredOutputErrors += (fnc.id -> errors) case _ => // ctx.reporter.info("No post-condition found\n") } // if the function returns a tuple, untuple it fnc.returnType match { case lang.Types.TupleType(_) => fnc.copy(body = Some(lang.TreeOps.replace { case Tuple(args) => val (newBody, resIdsTmp) = untuple(args) resIds += (fnc.id -> resIdsTmp) newBody } (fnc.body.get))) case _ => fnc } } ctx.reporter.debug("range bounds: " + resRanges.mkString("\n")) ctx.reporter.debug("error bounds: " + resErrors.mkString("\n")) (ctx.copy( specInputRanges = allRanges, specInputErrors = allErrors, specResultRangeBounds = resRanges, specResultErrorBounds = resErrors, specInputPrecisions = inputPrecision, specResultPrecisions = resultPrecisions, specAdditionalConstraints = additionalConst, resultTupleIds = resIds), Program(prg.id, newDefs)) } // turns a tuple into a Let statement with fresh variables private def untuple(args: Seq[Expr]): (Expr, Seq[Identifier]) = { if (args.size == 1) { val fresh = FreshIdentifier("#res1", args.head.getType) (Let(fresh, args.head, Variable(fresh)), Seq(fresh)) } else { val fresh = FreshIdentifier("#res" + args.size, args.last.getType) val (tmp, list) = untuple(args.init) (Let(fresh, args.last, tmp), list :+ fresh) } } def extractPreCondition(expr: Expr): (Map[Identifier, (Rational, Rational)], Map[Identifier, Rational], Seq[Expr]) = { val (lowerBound, upperBound, absError, addCond) = extractCondition(expr) // only return complete ranges, check for completeness is done later val bounds = (lowerBound.keySet.intersect(upperBound.keySet)).map(k => (k, (lowerBound(k), upperBound(k)))).toMap (bounds, absError, addCond) } def extractPostCondition(expr: Expr): (Map[Identifier, (Option[Rational], Option[Rational])], Map[Identifier, Rational]) = { val (lowerBound, upperBound, absError, _) = extractCondition(expr) val lowerMap = lowerBound.map({ case (x, r) => (x, (Some(r), upperBound.get(x))) }) val upperMap = upperBound.map({ case (x, r) => (x, (lowerBound.get(x), Some(r))) }) val resultMap = (lowerMap ++ upperMap) (resultMap, absError) } def extractCondition(e: Expr): (Map[Identifier, Rational], Map[Identifier, Rational], Map[Identifier, Rational], Seq[Expr]) = { var lowerBound: Map[Identifier, Rational] = Map.empty var upperBound: Map[Identifier, Rational] = Map.empty var absError: Map[Identifier, Rational] = Map.empty var additionalCond: Seq[Expr] = Seq.empty def extract(e: Expr): Unit = e match { case Lambda(args,body) => extract(body) case AbsError(Variable(id), RealLiteral(r)) => absError += (id -> r) case And(es) => es.foreach(extract(_)) case GreaterThan(Variable(id), RealLiteral(r)) => lowerBound += (id -> r) case GreaterEquals(Variable(id), RealLiteral(r)) => lowerBound += (id -> r) case LessThan(RealLiteral(r), Variable(id)) => lowerBound += (id -> r) case LessEquals(RealLiteral(r), Variable(id)) => lowerBound += (id -> r) case LessThan(Variable(id), RealLiteral(r)) => upperBound += (id -> r) case LessEquals(Variable(id), RealLiteral(r)) => upperBound += (id -> r) case GreaterThan(RealLiteral(r), Variable(id)) => upperBound += (id -> r) case GreaterEquals(RealLiteral(r), Variable(id)) => upperBound += (id -> r) case _ => ; additionalCond = additionalCond :+ e } extract(e) (lowerBound, upperBound, absError, additionalCond) } private def parseMixedPrecisionFile(f: String, prg: Program): Map[Identifier, Map[Identifier, Precision]] = { val fncIdMap: Map[String, Identifier] = prg.defs.map(fnc => fnc.id.toString -> fnc.id ).toMap val varIdMap: Map[String, Map[String, Identifier]] = prg.defs.map(fnc => fnc.id.toString -> allVariablesOf(fnc.body.get).map(id => id.toString -> id).toMap ).toMap def treeToMap(p: List[FunAssign]): Map[Identifier, Map[Identifier, Precision]] = { def typeAssignsToMap(l: List[TypeAssign], funcId: String): Map[Identifier, Precision] = { l.foldLeft[Map[Identifier, Precision]](Map())((m, tA) => tA match { case TypeAssign(varName, precision) => m + (varIdMap(funcId)(varName) -> precision) }) } p.foldLeft[Map[Identifier, Map[Identifier, Precision]]](Map())((m, fA) => fA match { case FunAssign(funName, types) => m + (fncIdMap(funName) -> typeAssignsToMap(types, funName)) }) } val bufferedSource = io.Source.fromFile(f) val sourceText = bufferedSource.mkString bufferedSource.close parse(overallFunction, sourceText) match { case Success(precisionsTree, _) => treeToMap(precisionsTree) case Failure(msg, _) => reporter.fatalError("Failure during the parsing of the type assignment file: " + msg) case Error(msg, _) => reporter.fatalError("Error during the parsing of the type assignment file: " + msg) } } def typecheck(expr: Expr, precisionMap: Map[Identifier, Precision], defaultPrecision: Precision): (Map[Identifier, Precision], Precision) = { def eval(e: Expr, precMap: Map[Identifier, Precision]): (Map[Identifier, Precision], Precision) = e match { case Variable(id) => precMap.get(id) match { case Some(m) => (precMap, m) case None => (precMap + (id -> defaultPrecision), defaultPrecision) } case RealLiteral(r) => (precMap, defaultPrecision) case ArithOperator(Seq(l, r), recons) => val (mapLeft, precLeft) = eval(l, precMap) val (mapRight, precRight) = eval(r, mapLeft) val precResult = getUpperBound(precLeft, precRight) (mapRight, precResult) case ArithOperator(Seq(u), recons) => eval(u, precMap) case Let(id, value, body) => val (mapValue, precValue) = eval(value, precMap) precMap.get(id) match { // precision of assigned variable is given case Some(m) => eval(body, mapValue) case None => eval(body, mapValue + (id -> precValue)) } } eval(expr, precisionMap) } } trait PrecisionsParser extends RegexParsers with JavaTokenParsers { def identifier: Parser[String] = """[a-zA-Z_][a-zA-Z0-9_]*""".r ^^ {x: String => x } def float256: Parser[Precision] = "QuadDouble" ^^ { case _ => QuadDouble } def float128: Parser[Precision] = ("DoubleDouble" ||| "Quad") ^^ { case _ => DoubleDouble } def float64: Parser[Precision] = ("Float64" ||| "Double") ^^ { case _ => Float64 } def float32: Parser[Precision] = ("Float32" ||| "Float") ^^ { case _ => Float32 } def float16: Parser[Precision] = "Float16" ^^ { case _ => Float16 } def typeVar: Parser[TypeAssign] = identifier ~ ":" ~ (float256 | float128 | float64 | float32) ^^ { case i ~ _ ~ p => TypeAssign(i, p) } def typemapFunction: Parser[FunAssign] = identifier ~ "=" ~ "{" ~ rep1(typeVar) ~ "}" ^^ { case i ~ _ ~ _ ~ types ~ _ => FunAssign(i, types) } def overallFunction: Parser[List[FunAssign]] = rep1(typemapFunction) ^^ { case l => l } } abstract class Precisions case class TypeAssign(f: String, p: Precision) extends Precisions case class FunAssign(f: String, s: List[TypeAssign]) extends Precisions
chi-w-ng/flatbuffers
tests/union_vector/Rapunzel.java
<reponame>chi-w-ng/flatbuffers<filename>tests/union_vector/Rapunzel.java<gh_stars>1000+ // automatically generated by the FlatBuffers compiler, do not modify import java.nio.*; import java.lang.*; import java.util.*; import com.google.flatbuffers.*; @SuppressWarnings("unused") public final class Rapunzel extends Struct { public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public Rapunzel __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public int hairLength() { return bb.getInt(bb_pos + 0); } public void mutateHairLength(int hair_length) { bb.putInt(bb_pos + 0, hair_length); } public static int createRapunzel(FlatBufferBuilder builder, int hairLength) { builder.prep(4, 4); builder.putInt(hairLength); return builder.offset(); } public static final class Vector extends BaseVector { public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } public Rapunzel get(int j) { return get(new Rapunzel(), j); } public Rapunzel get(Rapunzel obj, int j) { return obj.__assign(__element(j), bb); } } public RapunzelT unpack() { RapunzelT _o = new RapunzelT(); unpackTo(_o); return _o; } public void unpackTo(RapunzelT _o) { int _oHairLength = hairLength(); _o.setHairLength(_oHairLength); } public static int pack(FlatBufferBuilder builder, RapunzelT _o) { if (_o == null) return 0; return createRapunzel( builder, _o.getHairLength()); } }
brunolauze/openpegasus-providers-old
src/Providers/UNIXProviders/UsersCredential/UNIX_UsersCredential_VMS.hxx
<reponame>brunolauze/openpegasus-providers-old<filename>src/Providers/UNIXProviders/UsersCredential/UNIX_UsersCredential_VMS.hxx #ifdef PEGASUS_OS_VMS #ifndef __UNIX_USERSCREDENTIAL_PRIVATE_H #define __UNIX_USERSCREDENTIAL_PRIVATE_H #endif #endif
raoulvdberge/storagecraft
src/main/java/com/refinedmods/refinedstorage/apiimpl/autocrafting/CraftingPatternFactoryException.java
<gh_stars>100-1000 package com.refinedmods.refinedstorage.apiimpl.autocrafting; import net.minecraft.network.chat.Component; public class CraftingPatternFactoryException extends Exception { private final transient Component errorMessage; public CraftingPatternFactoryException(Component errorMessage) { this.errorMessage = errorMessage; } public Component getErrorMessage() { return errorMessage; } }
darconeous/coapblaster
src/test/java/com/google/iot/coap/RemoteServerTest.java
/* * Copyright (C) 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.iot.coap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.logging.Logger; import org.junit.jupiter.api.Test; public class RemoteServerTest { private static final boolean DEBUG = true; private static final Logger LOGGER = Logger.getLogger(RemoteServerTest.class.getCanonicalName()); @Test void testClientGetCoapMe_test() throws Exception { try (LocalEndpointManager manager = new LocalEndpointManager()) { manager.setDefaultBehaviorContext( new BehaviorContextPassthru(BehaviorContext.standard()) { @Override public int getCoapAckTimeoutMs() { return 250; } }); Client client = new Client(manager, "coap://coap.me/test"); try { Transaction transaction = client.newRequestBuilder().send(); Message response = transaction.getResponse(3000); if (DEBUG) LOGGER.info("Got response: " + response); assertTrue(response.isValid()); assertEquals(Type.ACK, response.getType()); assertEquals(Code.RESPONSE_CONTENT, response.getCode()); } finally { client.cancelAllTransactions(); } } } @Test void testClientGetCoapMe_large() throws Exception { try (LocalEndpointManager manager = new LocalEndpointManager()) { manager.setDefaultBehaviorContext( new BehaviorContextPassthru(BehaviorContext.standard()) { @Override public int getCoapAckTimeoutMs() { return 250; } }); Client client = new Client(manager, "coap://coap.me/large"); try { Transaction transaction = client.newRequestBuilder().send(); Message response = transaction.getResponse(3000); if (DEBUG) { LOGGER.info("Got response: " + response); } LOGGER.info(response.getPayloadAsString()); assertTrue(response.isValid()); assertEquals(Type.ACK, response.getType()); assertEquals(Code.RESPONSE_CONTENT, response.getCode()); } finally { client.cancelAllTransactions(); } } } @Test void testClientGetCoapMe_ping() throws Exception { try (LocalEndpointManager manager = new LocalEndpointManager()) { manager.setDefaultBehaviorContext( new BehaviorContextPassthru(BehaviorContext.standard()) { @Override public int getCoapAckTimeoutMs() { return 250; } }); Client client = new Client(manager, "coap://coap.me/"); try { Transaction transaction = client.ping(); Message response = transaction.getResponse(3000); if (DEBUG) LOGGER.info("Got response: " + response); assertTrue(response.isValid()); assertTrue(response.isEmpty()); assertEquals(Type.RST, response.getType()); } finally { client.cancelAllTransactions(); } } } @Test void testClientGetCoapMe_separate() throws Exception { try (LocalEndpointManager manager = new LocalEndpointManager()) { manager.setDefaultBehaviorContext( new BehaviorContextPassthru(BehaviorContext.standard()) { @Override public int getCoapAckTimeoutMs() { return 250; } }); Client client = new Client(manager, "coap://coap.me/separate"); try { Transaction transaction = client.newRequestBuilder().send(); Message response = transaction.getResponse(6000); LOGGER.info("Got response: " + response); assertFalse(response.isEmptyAck()); assertTrue(response.isValid()); assertEquals(Code.RESPONSE_CONTENT, response.getCode()); assertEquals(Type.CON, response.getType()); } finally { client.cancelAllTransactions(); } } } }
Internet-of-People/ApertusVR
plugins/jsAPI/nodeJsExtension/wrappers/ApeJsBindNodeImpl.h
<reponame>Internet-of-People/ApertusVR /*MIT License Copyright (c) 2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef APE_JSBIND_NODEIMPL_H #define APE_JSBIND_NODEIMPL_H #include "nbind/nbind.h" #include "nbind/api.h" #include "ApeNodeImpl.h" #ifdef NBIND_CLASS class NodeJsPtr { private: Ape::NodeWeakPtr mPtr; public: NodeJsPtr(Ape::NodeWeakPtr ptr) { mPtr = ptr; } // Pointers const Ape::NodeWeakPtr getNodeWeakPtr() { return mPtr; } const Ape::NodeSharedPtr getNodeSharedPtr() { return mPtr.lock(); } // ParentNode Ape::NodeWeakPtr getParentNodeWeakPtr() { return mPtr.lock()->getParentNode(); } void setParentNodeWeakPtr(Ape::NodeWeakPtr parentNode) { mPtr.lock()->setParentNode(parentNode); } NodeJsPtr getParentNodeJsPtr() { return NodeJsPtr(mPtr.lock()->getParentNode()); } void setParentNodeJsPtr(NodeJsPtr parentNode) { mPtr.lock()->setParentNode(parentNode.getNodeWeakPtr()); } // INode const std::string getName() { return mPtr.lock()->getName(); } const Ape::Vector3 getPosition() { return mPtr.lock()->getPosition(); } void setPosition(Ape::Vector3 position) { mPtr.lock()->setPosition(position); } const Ape::Vector3 getDerivedPosition() { return mPtr.lock()->getDerivedPosition(); } const Ape::Quaternion getOrientation() { return mPtr.lock()->getOrientation(); } void setOrientation(Ape::Quaternion orientation) { mPtr.lock()->setOrientation(orientation); } const Ape::Quaternion getDerivedOrientation() { return mPtr.lock()->getDerivedOrientation(); } const Ape::Vector3 getScale() { return mPtr.lock()->getScale(); } void setScale(Ape::Vector3 scale) { mPtr.lock()->setScale(scale); } const Ape::Vector3 getDerivedScale() { return mPtr.lock()->getDerivedScale(); } void translate(Ape::Vector3 transformVector, Ape::Node::TransformationSpace nodeTransformSpace) { mPtr.lock()->translate(transformVector, nodeTransformSpace); } void rotate(Ape::Radian angle, Ape::Vector3 axis, Ape::Node::TransformationSpace nodeTransformSpace) { mPtr.lock()->rotate(angle, axis, nodeTransformSpace); } }; NBIND_CLASS(NodeJsPtr) { construct<Ape::NodeWeakPtr>(); // Pointers method(getNodeWeakPtr); method(getNodeSharedPtr); // ParentNode method(getParentNodeWeakPtr); method(setParentNodeWeakPtr); method(getParentNodeJsPtr); method(setParentNodeJsPtr); // INode method(getName); method(getPosition); method(setPosition); method(getDerivedPosition); method(getOrientation); method(setOrientation); method(getDerivedOrientation); method(getScale); method(setScale); method(getDerivedScale); method(translate); method(rotate); } #endif #endif
drdrej/nodejs-json-get
impl/io/split.js
<gh_stars>1-10 exports.exec = function( ) { var streams = require('event-stream'); return streams.through(function write(data) { console.log( "-- exec split(data)" ); var _ = require( 'underscore' ); if(!_.isArray( data ) ) { console.log( "-- skip split(data). data is NOT AN ARRAY. Pass data to next transformation" ); return data; } var stream = this; _.each(data, function( element ){ stream.emit('data', element ); console.log( "-- element emitted: %j", element); }); }, function end () { this.emit('end'); }); };
yzq992778484/MVCHelper
app/src/main/java/com/shizhefei/test/view/adapters/multitype/provider/MessageProvider.java
package com.shizhefei.test.view.adapters.multitype.provider; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.shizhefei.test.view.adapters.multitype.Message; import com.shizhefei.view.multitype.ItemViewProvider; import com.shizhefei.view.mvc.demo.R; /** * Created by LuckyJayce on 2016/8/8. */ public class MessageProvider extends ItemViewProvider<Message> { public static final int ALIGN_LEFT = 0; public static final int ALIGN_RIGHT = 1; private int align; public MessageProvider(int align) { this.align = align; } @Override public RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int providerType) { if (align == ALIGN_LEFT) { return new ItemViewHolder(inflater.inflate(R.layout.item_message_left, parent, false)); } return new ItemViewHolder(inflater.inflate(R.layout.item_message_right, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, Message message) { ItemViewHolder vh = (ItemViewHolder) viewHolder; vh.textView.setText(message.text); } private class ItemViewHolder extends RecyclerView.ViewHolder { private final TextView textView; public ItemViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.item_message_textView); } } }
jishminor/model_analyzer
tests/common/test_result_collector.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import json class TestResultCollector(unittest.TestCase): """ TestResultCollector stores test result and prints it to stdout. In order to use this class, unit tests must inherit this class. Use `check_test_results` bash function from `common/util.sh` to verify the expected number of tests produced by this class """ @classmethod def setResult(cls, total, errors, failures): cls.total, cls.errors, cls.failures = \ total, errors, failures @classmethod def tearDownClass(cls): # this method is called when all the unit tests in a class are # finished. json_res = { 'total': cls.total, 'errors': cls.errors, 'failures': cls.failures } print(json.dumps(json_res)) def run(self, result=None): # result argument stores the accumulative test results test_result = super().run(result) if test_result: total = test_result.testsRun errors = len(test_result.errors) failures = len(test_result.failures) self.setResult(total, errors, failures)
roroclaw/wyedu
src/main/java/com/cloud9/biz/dao/mybatis/TchScheduleCourseOpenMapper.java
package com.cloud9.biz.dao.mybatis; import com.cloud9.biz.models.TchScheduleCourseOpen; import org.apache.ibatis.annotations.Param; import java.util.List; public interface TchScheduleCourseOpenMapper { int deleteByPrimaryKey(String id); int insert(TchScheduleCourseOpen record); int insertSelective(TchScheduleCourseOpen record); TchScheduleCourseOpen selectByPrimaryKey(String id); int updateByPrimaryKeySelective(TchScheduleCourseOpen record); int updateByPrimaryKey(TchScheduleCourseOpen record); int cleanScheduleCourseOpenRelInfo(TchScheduleCourseOpen record); List<TchScheduleCourseOpen> selectScheduleCourseOpenRelList(TchScheduleCourseOpen record); List<TchScheduleCourseOpen> selectScheduleCourseOpenRelListForShow(@Param("stuId")String stuId,@Param("schoolYear")String schoolYear,@Param("term")String term, @Param("teacherId")String teacherId,@Param("orderParam")String orderParam); List<TchScheduleCourseOpen> selectScheduleCourseOpenRelListForClassShow(@Param("schoolYear")String schoolYear,@Param("term")String term, @Param("classId")String classId,@Param("orderParam")String orderParam); List<TchScheduleCourseOpen> selectScheduleCourseOpenRelListForCollecting(@Param("schoolYear")String schoolYear,@Param("term")String term,@Param("period")String period); List<TchScheduleCourseOpen> selectClassInfoForCollectingShow(@Param("graduateYears")String graduateYears,@Param("term")String term,@Param("period")String period); List<TchScheduleCourseOpen> checkScheduleCourseOpenRelForTeacher(TchScheduleCourseOpen record); List<TchScheduleCourseOpen> checkScheduleCourseOpenRelForStu(TchScheduleCourseOpen record); }
peterfab9845/WebCheckers
src/main/java/com/webcheckers/appl/ai/AIManager.java
package com.webcheckers.appl.ai; public class AIManager { private static int AI_NUM = 0; private static int PIECE_ID = 0; private static final boolean debugging = true; private static final boolean TRAINING = true; public static String getName(){ AI_NUM++; return "AI" + AI_NUM; } public static int getPieceID(){ int id = PIECE_ID; PIECE_ID++; return id; } public static boolean isDebugging() { return debugging; } public static boolean isTraining() { return TRAINING; } }
Plaristote/Boots
include/Boots/Network/serializer.hpp
<reponame>Plaristote/Boots<filename>include/Boots/Network/serializer.hpp #ifndef _NETWORK_SERIALIZER_HPP # define _NETWORK_SERIALIZER_HPP # include "../Utils/serializer.hpp" namespace Network { class Socket; void WritePacket(Utils::Packet& packet, Network::Socket* socket); } #endif
mmore500/dishtiny
dishpylib/pydecorators/__init__.py
<gh_stars>10-100 from .announce_job_decorator_factory import announce_job_decorator_factory from .only_every_nth_stint_decorator_factory import only_every_nth_stint_decorator_factory from .try_except_missing_data_decorator_factory import try_except_missing_data_decorator_factory # adapted from https://stackoverflow.com/a/31079085 __all__ = [ 'announce_job_decorator_factory', 'only_every_nth_stint_decorator_factory', 'only_every_nth_stint_decorator_factory', ]
liquidg3/pong-pi
node_modules/openvg-canvas/lib/matrix.js
<reponame>liquidg3/pong-pi /*jslint indent: 2, node: true */ "use strict"; var matrix = module.exports; var create = matrix.create = function () { return new Float32Array(9); }; var m = matrix.m = function (a, b, c, d, e, f, g, h, k) { var r = new Float32Array(9); r[0] = a; r[1] = b; r[2] = c; r[3] = d; r[4] = e; r[5] = f; r[6] = g; r[7] = h; r[8] = k; return r; }; var logMatrix = matrix.log = function (label, m) { if (!m) { m = label; label = 'M'; } var maxLen = 0; var nums = new Array(9); for (var i = 0; i < 9; i++) { nums[i] = m[i].toString(); if (nums[i].length > maxLen) { maxLen = nums[i].length; } } var padSpaces = ' '; while (padSpaces.length < label.length) { padSpaces += padSpaces; } function pad(text) { return padSpaces.substr(0, maxLen - text.length) + text; } function padL(text) { return padSpaces.substr(0, text.length); } console.log( label + ': ⎡' + pad(nums[0]) + ' , ' + pad(nums[1]) + ' , ' + pad(nums[2]) + '⎤'); console.log(padL(label) + ' ⎢' + pad(nums[3]) + ' , ' + pad(nums[4]) + ' , ' + pad(nums[5]) + '⎥'); console.log(padL(label) + ' ⎣' + pad(nums[6]) + ' , ' + pad(nums[7]) + ' , ' + pad(nums[8]) + '⎦'); return m; }; var SVGMatrix = matrix.SVGMatrix = function (m) { this.m = m || matrix.m(1, 0, 0, 0, 1, 0, 0, 0, 1); }; SVGMatrix.prototype.getComponent = function (index) { var tMap = [0, 1, 3, 4, 6, 7]; // TO DO: Raise exception if index < 0 || index > 5 return this.m[tMap[index]]; }; SVGMatrix.prototype.mMultiplyF = function (o0, o1, o2, o3, o4, o5, o6, o7, o8) { var m = this.m, m0, m1, m2, m3, m4, m5, m6, m7, m8; m0 = m[0] * o0 + m[1] * o3 + m[2] * o6; m1 = m[0] * o1 + m[1] * o4 + m[2] * o7; m2 = m[0] * o2 + m[1] * o5 + m[2] * o8; m3 = m[3] * o0 + m[4] * o3 + m[5] * o6; m4 = m[3] * o1 + m[4] * o4 + m[5] * o7; m5 = m[3] * o2 + m[4] * o5 + m[5] * o8; m6 = m[6] * o0 + m[7] * o3 + m[8] * o6; m7 = m[6] * o1 + m[7] * o4 + m[8] * o7; m8 = m[6] * o2 + m[7] * o5 + m[8] * o8; m[0] = m0; m[1] = m1; m[2] = m2; m[3] = m3; m[4] = m4; m[5] = m5; m[6] = m6; m[7] = m7; m[8] = m8; return this; }; SVGMatrix.prototype.mMultiply = function (secondMatrix) { var m = secondMatrix.m, a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5], g = m[6], h = m[7], k = m[8]; return this.mMultiply(a, b, c, d, e, f, g, h, k); }; SVGMatrix.prototype.inverse = function () { var m = this.m, a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5], g = m[6], h = m[7], k = m[8]; var det = a * (e * k - f * h) - b * (d * k - f * g) + c * (d * h - e * g); // TO DO: Raise exception if det === 0 return new SVGMatrix(matrix.m( a / det, d / det, g / det, b / det, e / det, h / det, c / det, f / det, k / det )); }; SVGMatrix.prototype.mTranslate = function (x, y) { return this.mMultiplyF(1, 0, 0, 0, 1, 0, x, y, 1); }; SVGMatrix.prototype.mScale = function (scaleFactor) { return this.mMultiplyF(scaleFactor, 0, 0, 0, scaleFactor, 0, 0, 0, 1); }; SVGMatrix.prototype.vgScale = function (scaleFactorX, scaleFactorY) { return this.mMultiplyF(scaleFactorX, 0, 0, 0, scaleFactorY, 0, 0, 0, 1); }; SVGMatrix.prototype.mRotate = function (angle) { var sin = Math.sin(angle); var cos = Math.cos(angle); return this.mMultiplyF(cos, -sin, 0, sin, cos, 0, 0, 0, 1); };
MetOffice/cmip6-dreq-interface
dqi/lib/dqi/walker.py
<filename>dqi/lib/dqi/walker.py # (C) British Crown Copyright 2016, Met Office. # See LICENSE.md in the top directory for license details. # # A walker for the dreq # __all__ = ['MissingRule', 'MutantRule', 'MissingAttribute', 'BadLink', 'walk_dq', 'walk_thing', 'walk_into', 'walk_linked', 'return_from_thing', 'return_from_walk', 'thing_return', 'walk_return', 'dqtype', 'validp', 'mips_of_cmv'] from collections import defaultdict from .low import Badness # Things to think about. # # There are a lot of places where this knows about (documented) # details of the data request object: in particular it knows about the # various indices. I thought about abstracting all of this away with # accessor functions but I'm not actually sure it is helpful to do # that. It might become so if the language became richer: it might be # useful to be able to say 'walk everyone which links to me' for # instance. However that probabably will not happen (in fact: that # particular case has happened: see walk_linked below) # # Exceptions # # It would be good to classify these by whether they are bugs in the # request, the rules or the code, but it is vague # class MissingRule(Badness): # problem with rules, not request pass class MutantRule(Badness): # problem with rules, not request pass class MissingAttribute(Badness): # probably a problem with the rules pass class BadLink(Badness): # could be either? pass class BadDreq(Badness): # definitely the request pass # Control transfer protocol # # Python has almost no useful control abstractions: you can't say # 'return from a lexically-visible place' for instance. Using # exceptions is a hack -- it's like using CL-style THROW and CATCH # with all their problems (and probably even more expense). But I # think it is the only way of doing this. The use of exceptions is # wrapped by functions which actually do the raising. # # For these exceptions and the functions which wrap them: # - return_partial_results will cause the walker to return what it # has built so far # - value is the value to return otherwise -- return_partial_results # wins if both are given. # class Return(Exception): def __init__(self, value=None, return_partial_results=False): self.value = value self.return_partial_results = return_partial_results class ReturnFromThing(Return): pass def return_from_thing(value=None, return_partial_results=False): # Return from a level. raise ReturnFromThing(value=value, return_partial_results=return_partial_results) class ReturnFromWalk(Return): pass def return_from_walk(value=None, return_partial_results=False): # Return from the whole walk raise ReturnFromWalk(value=value, return_partial_results=return_partial_results) # The rules of how to walk things. # # A ruleset is a dict which maps from the type of thing (dreq section) # to a rule for that type. There can also be a wildcard rule, whose # type is None, and which matches any type if there is no more # specific rule for that type. # # Each rule is one of the following. # - A callable, which is called with v conventions (see below) # and which returns the result of the walk for this rule. # - A list of tuples of two elements: [(p, r), ...]: this is a # conditional, and each p is called with v conventions in # turn until one returns true, when its r is used as the rule. It is # fine if none return true. # - A tuple of instructions, each of which is processed in turn # # Each instruction is one of the following. # - A string: that field is extracted and recorded in the dictionary # returned (a string instruction s is shorthand for a tuple of (s, # s): see actions below). # - A two-element tuple of (name, action): the result of action is # recorded under name. # - A list of tuples [(p, i), ...]: this is a conditional as before, # but the matching i is evaluated as an instruction, not a rule. # Again, no predicate needs to return true, and in this case nothing # at all is done for this instruction. # # Finally, each action in a tuple instruction is one of the following. # - A callable: this is called (v convention), and its value recorded # under the instruction's name. # - A string: the corresponding attribute is recorded. # - A tuple (f, ...): f should be a callable and is called with f # conventions (see below) and its result is the value recorded. # - a list of tuples which is a conditional, as before, the result # being None if no clause matches. # # There are two calling conventions depending on whether a callable is # being used as a variable (v convention) or function (f convention): # # V convention arguments: # - the thing being walked; # - its dqtype, either inferred or provided; # - the ruleset; # - the dq object; # - for_side_effect as a keyword argument; # - any other keyword arguments passed down. # # F convention arguments: # - a tuple consisting of the arguments to the function in the action, # so in (f, a, b), f gets (a, b) as its first argument; # - the thing being walked; # - its dqtype, either inferred or provided; # - the ruleset; # - the dq object; # - for_side_effect as a keyword argument; # - any other keyword arguments passed down # F convention is the same as V convention but with an additional # first argument. # # What the walker builds. # # walk_dq walks each CMORvar in the request. If not called for side # effect it builds a structure which looks like # # {mt: {cmv: (walk, ...), ...}, ...} # # In other words a dict mapping from mip table names to a dict mapping # from CMORvar names to a tuple of the walks of all the CMORvars # belonging to the mip table with that name. We think there should # only be one element in each tuple (so the tuple of (mip table name, # CMORvar name) should uniquely identify a CMORvar, but this has not # always been true and may not need to be true in fact. An earlier # version of this code built structures like # # {mt: {cmv: walk, ...}, ...} # # which simply lost any duplicate CMORvar names: this at least does # not do that. # # If called for side effect, walk_dq simply walks all the CMORvars. # # In both cases the order the walk happens in is undefined, but each # CMORvar is walked only once. (There used to be all sorts of # spurious sorting, which was never needed and is now gone.) # # walk_thing normally constructs a dict mapping between # instruction-name and result-of-instruction (see above), which may # (and does in practice) happen recursively, via walk_into. However # in the case where the rule for a typeis a function, then it can # actually construct anything at all. # def walk_dq(dq, ruleset={None: ()}, for_side_effect=False, **kws): # walk the dq: this constructs the top of the tree, which is a # dict mapping from miptable to the names of the CMORvars that # refer to it. If for_side_effect is true the walk is done purely # for side effect: no result is returned and no data structure is # built. Any extra keyword arguments are passed down. # # The ruleset {None: ()} is what you need to minimally run the # walker. if not for_side_effect: results = defaultdict(lambda: defaultdict(list)) try: for cmv in dq.coll['CMORvar'].items: results[cmv.mipTable][cmv.label].append( walk_thing(cmv, "CMORvar", ruleset, dq, for_side_effect=False, **kws)) except ReturnFromWalk as returned: if not returned.return_partial_results: return returned.value return {mt: {name: tuple(walks) for (name, walks) in mt_cmvs.iteritems()} for (mt, mt_cmvs) in results.iteritems()} else: # for side effect try: for cmv in dq.coll['CMORvar'].items: walk_thing(cmv, "CMORvar", ruleset, dq, for_side_effect=True, **kws) except ReturnFromWalk: pass def walk_thing(thing, dqt, ruleset, dq, for_side_effect=False, **kws): # This is just a recursive descent parser for the rules for thing if dqt is None: dqt = dqtype(thing) # Box result to overcome Python scope braindeath result = [{}] if not for_side_effect else None def record(name, value): # record a value for a name if not for_side_effect: result[0][name] = value def eval_rule(rule): if callable(rule): # function: just return its result result[0] = rule(thing, dqt, ruleset, dq, for_side_effect=for_side_effect, **kws) elif isinstance(rule, list): # cond eval_cond(rule, eval_rule) elif isinstance(rule, tuple): # a sequence of instructions for instruction in rule: eval_instruction(instruction) else: # no other sorts of rules are legal raise MutantRule("{} makes no sense for {}: tuple syntax lossage?" .format(rules, thing)) def eval_cond(cond, continuation, fallback_continuation=None): # evaluate a conditional [(p, v), ...], obviously inspired by # http://www-formal.stanford.edu/jmc/recursive.html. It is # fine for no clauses to match: the fallback is called in that # case if it is defined. for clause in cond: if not ((isinstance(clause, tuple) or isinstance(clause, list)) and len(clause) == 2): raise MutantRule("bogus cond clause {}".format(clause)) (p, v) = clause if not callable(p): raise MutantRule("{} in {} is not callable".format(p, cond)) if p(thing, dqt, ruleset, dq, for_side_effect=for_side_effect, **kws): return continuation(v) if fallback_continuation: return fallback_continuation() def eval_instruction(instruction): if isinstance(instruction, str) or isinstance(instruction, unicode): # trivial instruction: record a field record(instruction, eval_action(instruction)) elif isinstance(instruction, tuple) and len(instruction) == 2: record(instruction[0], eval_action(instruction[1])) elif issinstance(instruction, list): eval_cond(instruction, eval_instruction) else: raise MutantRule("instruction {} is hopeless".format(instruction)) def eval_action(action): # Finally do something. This is unlike the other eval_* # functions as it returns a useful value which is stored by # eval_instruction rather than doing its own recording. if callable(action): return action(thing, dqt, ruleset, dq, for_side_effect=for_side_effect, **kws) elif isinstance(action, str) or isinstance(action, unicode): if hasattr(thing, action): return getattr(thing, action) else: raise MissingAttribute("{} is missing {}".format(dqt, action)) elif isinstance(action, tuple) and len(action) >= 1: (f, args) = (action[0], action[1:]) if callable(f): return f(args, thing, dqt, ruleset, dq, for_side_effect=for_side_effect, **kws) else: raise MutantRule("no callable in {}".format(action)) elif isinstance(action, list): return eval_cond(action, eval_action, lambda: None) else: raise MutantRule("mutant action {}".format(action)) # OK, go if dqt not in ruleset and None not in ruleset: raise MissingRule("no rule for {}".format(dqt)) try: eval_rule(ruleset[dqt] if dqt in ruleset else ruleset[None]) except ReturnFromThing as returned: if not returned.return_partial_results: if not for_side_effect: return returned.value else: return if not for_side_effect: return result[0] else: return def walk_into(args, thing, dqt, ruleset, dq, for_side_effect=False, **kws): # F convention walker to walk into a slot if not 1 <= len(args) <= 2: raise MutantRule("walk_into needs one or two arguments") child_attr = args[0] child_dqt = args[1] if len(args) == 2 else None if not hasattr(thing, child_attr): raise MissingAttribute( "{} is missing {}".format(dqt, child_attr)) child_id = getattr(thing, child_attr) if child_id not in dq.inx.uid: raise BadLink("missing {}".format(child_id)) child = dq.inx.uid[child_id] if validp(child): # OK recurse (note that child_dqt may be None: see above) return walk_thing(child, child_dqt, ruleset, dq, for_side_effect=for_side_effect, **kws) else: # Leave a trace that the child was invalid return None def walk_linked(args, thing, dqt, ruleset, dq, for_side_effect=False, **kws): # F convention walker to walk elements which link to this one, # returning a tuple. If no args are given walk all sections as # their normal types; if one, walk single section as its own # dqtype; if two, then if the first is not None walk that section # with the type given by the second argument, and if the first is # None walk all sections with the type given by the second # argument. def walk_all(as_type=None): # walk all sections, optionally with a type (note that # walk_thing defaults types given as None to be right). # # Martin's description implies that dq.inx.iref_by_uid returns # tuples of (section, identifier): it doesn't, it returns # (linking_field_name, identifier). linked = (link for link in (dq.inx.uid[l[1]] for l in dq.inx.iref_by_uid[thing.uid]) if validp(link)) if not for_side_effect: return tuple(walk_thing(link, as_type, ruleset, dq, for_side_effect=False, **kws) for link in linked) else: for link in linked: walk_thing(link, as_type, ruleset, dq, for_side_effect=True, **kws) def walk_sect(sect, as_type=None): # walk one section sects = dq.inx.iref_by_sect[thing.uid].a if sect in sects: linked = (link for link in (dq.inx.uid[l] for l in sects[sect]) if validp(link)) if not for_side_effect: return (tuple(walk_thing(link, as_type, ruleset, dq, for_side_effect=False, **kws) for link in linked)) else: for link in linked: walk_thing(link, as_type, ruleset, dq, for_side_effect=True, **kws) else: return None if len(args) == 0: return walk_all(None) elif len(args) == 1: return walk_sect(args[0], args[0]) elif len(args) == 2: if args[0] is None: return walk_all(args[1]) else: return walk_sect(args[0], args[1]) else: raise MutantRule("walk_linked: need 0-2 args but got {}?" .format(args)) def thing_return(args, thing, dqt, ruleset, dq, for_side_effect=False, **kws): # F-convention walker which returns from this level, returning its # argument if given, otherwise whatever the partial result was. l = len(args) if l == 0: return_from_thing(value=None, return_partial_results=True) elif l == 1: return_from_thing(value=args[0]) else: raise MutantRule("thing_return: need 0 or 1 args but got {}?" .format(args)) def walk_return(args, thing, dqt, ruleset, dq, for_side_effect=False, **kws): # F-convention walker which returns from the walk, returning its # argument if given, otherwise whatever the partial result was. l = len(args) if l == 0: return_from_walk(value=None, return_partial_results=True) elif l == 1: return_from_walk(value=args[0]) else: raise MutantRule("walk_return: need 0 or 1 args but got {}?" .format(args)) def dqtype(item): # an item's type in the request return item._h.label def validp(item): # something is valid if its dqt is not 'remarks' return dqtype(item) != 'remarks' def mips_of_cmv(cmv, dq, direct=False): # Return a set of the mips of a CMORvar in dq. If direct is true, # only use the MIP directly, not its experiments # # This is a simplified version of vrev.checkVar.chkCmv (in # vrev.py) But it is simpler in the sense that I do not understand # what the original code really does, so I have just tried to make # something which is a bit less horrible and which might do # something useful. In particular it does not deal with any of # the experiment stuff. # requestVar ids which refer to cmv and whose groups are valid rvids = set(rvid for rvid in dq.inx.iref_by_sect[cmv.uid].a['requestVar'] if validp(dq.inx.uid[dq.inx.uid[rvid].vgid])) # construct a dict mapping from variable group id to the highest # priority in that group vgpri = dict() for rvid in rvids: rv = dq.inx.uid[rvid] # the requestVar rvp = rv.priority # its priority vgid = rv.vgid # its group if vgid not in vgpri or rvp > vgpri[vgid]: vgpri[vgid] = rvp linkids = set() for (vgid, pri) in vgpri.iteritems(): if dq.inx.iref_by_sect[vgid].a.has_key('requestLink'): for rlid in dq.inx.iref_by_sect[vgid].a['requestLink']: rl = dq.inx.uid[rlid] # requestLink if rl.opt == 'priority': # if it has a priority, add it if it is high # enough. This is what he does: rounding? (See # .../djq/variables/varmip.py for comments on a # long-standing bug here) if int(float(rl.opar)) >= pri: linkids.add(rlid) else: # no priority, just add it linkids.add(rlid) # OK, so here is the first chunk of mips: just the mip fields of # all these requestLink objects mips = set(dq.inx.uid[rlid].mip for rlid in linkids) if not direct: # Now deal with experiments, if asked # # The IDs of all the experiments corresponding to the # requestLinks, I think esids = set(dq.inx.uid[u].esid for rlid in linkids for u in dq.inx.iref_by_sect[rlid].a['requestItem']) # Empty IDs can leak in (which is looks like is a bug?) esids.discard('') for esid in esids: # what sort of thing is this dqt = dqtype(dq.inx.uid[esid]) if dqt == 'mip': # it's a MIP, directly mips.add(esid) else: # if it's a group of experiments they all must belong # to the same MIP I think, so this just picks the # first. Otherwiwise assume it is an experiment itself expt = (dq.inx.uid[dq.inx.iref_by_sect[esid].a['experiment'][0]] if dqt == 'exptgroup' else dq.inx.uid[esid]) if validp(expt): exptdqt = dqtype(expt) if exptdqt == 'experiment': # just add its MIP mips.add(expt.mip) else: raise BadDreq("{} isn't an experiment".format(exptdqt)) return mips
5cript/SimpleJSON
parse/jsd_unordered_map.hpp
#pragma once #include "jsd_core.hpp" #include <unordered_map> namespace JSON { template <typename ValueT, typename HashT = std::hash <std::string>, class PredT = std::equal_to <std::string>, typename AllocT = std::allocator <std::pair <const std::string, ValueT>>> void parse(std::unordered_map<std::string, ValueT, HashT, PredT, AllocT>& value, std::string const& name, PropertyTree const& object, ParsingOptions const& options = {}) { try { SJSON_GET_CHILD(name, pt, (std::unordered_map<std::string, ValueT>())); for (auto const& i : pt) { ValueT temp; parse(temp, "", i.second, options); value[i.first] = temp; } } catch (boost::property_tree::ptree_bad_data& exc) { SJSON_DEFAULT_PROPERTY_ERROR_HANDLER((std::unordered_map<std::string, ValueT>()), (std::unordered_map<std::string, ValueT>())); } catch (boost::property_tree::ptree_bad_path& exc) { SJSON_DEFAULT_PATH_ERROR_HANDLER((std::unordered_map<std::string, ValueT>()), (std::unordered_map<std::string, ValueT>())); } } }
nowifi4u/Commando
src/types/string/string-reset.js
<reponame>nowifi4u/Commando const baseString = require('./baseString'); module.exports = baseString('reset', ['reset']);
Coolzyh/Leetcode
[162] Find Peak Element/162.find-peak-element.java
/* * @lc app=leetcode id=162 lang=java * * [162] Find Peak Element */ // @lc code=start class Solution { public int findPeakElement(int[] nums) { if (nums.length == 1) return 0; int n = nums.length; int left = 0, right = n-1; while (left < right) { int mid = left + (right-left)/2; // make nums[mid] > nums[mid+1] if (nums[mid] > nums[mid+1]) right = mid; // make nums[mid] > nums[mid-1] else left = mid+1; } return left; } } // @lc code=end
iganna/lspec
ugene/src/corelibs/U2View/src/util_dna_assembly/BuildIndexDialog.cpp
<reponame>iganna/lspec<filename>ugene/src/corelibs/U2View/src/util_dna_assembly/BuildIndexDialog.cpp /** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <<EMAIL>> * http://ugene.unipro.ru * * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BuildIndexDialog.h" #include "DnaAssemblyGUIExtension.h" #include <U2Core/GUrlUtils.h> #include <U2Core/DocumentUtils.h> #include <U2Core/AppContext.h> #include <U2Core/ExternalToolRegistry.h> #include <U2Algorithm/DnaAssemblyAlgRegistry.h> #include <U2Gui/LastUsedDirHelper.h> #include <U2Gui/AppSettingsGUI.h> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> namespace U2 { QString BuildIndexDialog::genomePath; BuildIndexDialog::BuildIndexDialog(const DnaAssemblyAlgRegistry* registry, QWidget* p) : QDialog(p), assemblyRegistry(registry), customGUI(NULL) { setupUi(this); QStringList names = registry->getRegisteredAlgorithmsWithIndexFileSupport(); methodNamesBox->addItems(names); // TODO: change the way default method is set if (names.size() > 0) { methodNamesBox->setCurrentIndex(names.size() - 1); } sl_onAlgorithmChanged(methodNamesBox->currentText()); connect(setIndexFileNameButton, SIGNAL(clicked()), SLOT(sl_onSetIndexFileNameButtonClicked())); connect(addRefButton, SIGNAL(clicked()), SLOT(sl_onAddRefButtonClicked()) ); connect(methodNamesBox, SIGNAL(currentIndexChanged(const QString &)), SLOT(sl_onAlgorithmChanged(const QString &))); if (!genomePath.isEmpty()) { refSeqEdit->setText(genomePath); buildIndexUrl(genomePath); } } void BuildIndexDialog::sl_onAddRefButtonClicked() { LastUsedDirHelper lod; QString filter; lod.url = QFileDialog::getOpenFileName(this, tr("Open reference sequence"), lod.dir, filter); if (lod.url.isEmpty()) { return; } refSeqEdit->setText(lod.url); buildIndexUrl(lod.url); } void BuildIndexDialog::sl_onSetIndexFileNameButtonClicked() { LastUsedDirHelper lod; lod.url = QFileDialog::getSaveFileName(this, tr("Set index file name"), lod.dir); if (!lod.url.isEmpty()) { GUrl index = lod.url; if (index.lastFileSuffix().isEmpty() && customGUI != NULL) { QString extension = customGUI->getIndexFileExtension(); if (extension.isEmpty()) { index = QString( "%1" ).arg( index.getURLString() ); } else { index = QString( "%1.%2" ).arg( index.getURLString() ).arg(extension); } } indexFileNameEdit->setText(index.getURLString()); } } void BuildIndexDialog::sl_onAlgorithmChanged(const QString &) { updateState(); } void BuildIndexDialog::updateState() { addGuiExtension(); } void BuildIndexDialog::addGuiExtension() { int insertPos = verticalLayout->count() - 2; // cleanup previous extension if (customGUI != NULL) { layout()->removeWidget(customGUI); setMinimumHeight(minimumHeight() - customGUI->minimumHeight()); delete customGUI; customGUI = NULL; } // insert new extension widget DnaAssemblyAlgorithmEnv* env = assemblyRegistry->getAlgorithm(methodNamesBox->currentText()); if (NULL == env) { adjustSize(); return; } DnaAssemblyGUIExtensionsFactory* gui = env->getGUIExtFactory(); if (gui!=NULL && gui->hasBuildIndexWidget()) { customGUI = gui->createBuildIndexWidget(this); int extensionMinWidth = customGUI->sizeHint().width(); int extensionMinHeight = customGUI->sizeHint().height(); customGUI->setMinimumWidth(extensionMinWidth); customGUI->setMinimumHeight(extensionMinHeight); verticalLayout->insertWidget(insertPos, customGUI); // adjust sizes setMinimumHeight(customGUI->minimumHeight() + minimumHeight()); if (minimumWidth() < customGUI->minimumWidth()) { setMinimumWidth(customGUI->minimumWidth()); } if (!refSeqEdit->text().isEmpty()) { buildIndexUrl(refSeqEdit->text()); } customGUI->show(); adjustSize(); } else { adjustSize(); } } void BuildIndexDialog::buildIndexUrl(const GUrl& refUrl ) { QString extension(""); if (NULL != customGUI) { extension = customGUI->getIndexFileExtension(); customGUI->buildIndexUrl(refUrl); } GUrl url; if (extension.isEmpty()) { url = GUrlUtils::rollFileName(refUrl.dirPath() + "/" + refUrl.baseFileName(), DocumentUtils::getNewDocFileNameExcludesHint()); } else { url = GUrlUtils::rollFileName(refUrl.dirPath() + "/" + refUrl.baseFileName()+ "." + extension, DocumentUtils::getNewDocFileNameExcludesHint()); } indexFileNameEdit->setText(url.getURLString()); } void BuildIndexDialog::accept() { if (getAlgorithmName() == "Bowtie") { if(AppContext::getExternalToolRegistry()->getByName("Bowtie-build")->getPath().isEmpty()) { QMessageBox msgBox; msgBox.setWindowTitle(tr("DNA Assembly")); msgBox.setInformativeText(tr("Do you want to select it now?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); msgBox.setText(tr("Path for <i>Bowtie-build</i> tool is not selected.")); int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: AppContext::getAppSettingsGUI()->showSettingsDialog(APP_SETTINGS_EXTERNAL_TOOLS); break; case QMessageBox::No: return; break; default: assert(NULL); break; } if(AppContext::getExternalToolRegistry()->getByName("Bowtie-build")->getPath().isEmpty()) { return; } } } if (refSeqEdit->text().isEmpty()) { QMessageBox::information(this, tr("Build Index"), tr("Reference sequence url is not set!") ); } else if (indexFileNameEdit->text().isEmpty() ) { QMessageBox::information(this, tr("Build Index"), tr("Index file name is not set!") ); } else { genomePath.clear(); genomePath = refSeqEdit->text(); QDialog::accept(); } } const GUrl BuildIndexDialog::getRefSeqUrl() { return refSeqEdit->text(); } const QString BuildIndexDialog::getAlgorithmName() { return methodNamesBox->currentText(); } const QString BuildIndexDialog::getIndexFileName() { return indexFileNameEdit->text(); } QMap<QString, QVariant> BuildIndexDialog::getCustomSettings() { if (customGUI != NULL) { return customGUI->getBuildIndexCustomSettings(); } else { return QMap<QString, QVariant>(); } } }//namespace
sezero/windows-sdk-headers
Include/v7.1/persist.h
<filename>Include/v7.1/persist.h //----------------------------------------------------------------------------- // // File: persist.h // // Copyright: Copyright (c) Microsoft Corporation // // Contents: MSPersist external constants GUIDS and other things users need // // Comments: // //----------------------------------------------------------------------------- #ifndef PERSIST_H #define PERSIST_H #undef PERSISTDECLSPEC #if _MSC_VER >= 1100 && (!defined(SHx) || (defined(SHx) && _MSC_VER >= 1200)) #define PERSISTDECLSPEC __declspec(selectany) #else #define PERSISTDECLSPEC #endif //_MSC_VER // Persist Properties #define DBPROPFLAGS_PERSIST 0x2000 #define DBPROPVAL_PERSIST_ADTG 0 #define DBPROPVAL_PERSIST_XML 1 #define DBPROP_PersistFormat 2 #define DBPROP_PersistSchema 3 #define DBPROP_HCHAPTER 4 #define DBPROP_MAINTAINPROPS 5 // XML writing only properties #define DBPROP_Unicode 6 // internal property (read-only) #define DBPROP_INTERLEAVEDROWS 8 extern const PERSISTDECLSPEC CLSID CLSID_MSPersist = { 0x7c07e0d0, 0x4418, 0x11d2, { 0x92, 0x12, 0x0, 0xc0, 0x4f, 0xbb, 0xbf, 0xb3 } }; // {4D7839A0-5B8E-11d1-A6B3-00A0C9138C66} extern const PERSISTDECLSPEC GUID DBPROPSET_PERSIST = { 0x4d7839a0, 0x5b8e, 0x11d1, { 0xa6, 0xb3, 0x0, 0xa0, 0xc9, 0x13, 0x8c, 0x66 } }; #define MS_PERSIST_PROGID "MSPersist" extern const PERSISTDECLSPEC char *PROGID_MSPersist = MS_PERSIST_PROGID; extern const PERSISTDECLSPEC WCHAR *PROGID_MSPersist_W = L"MSPersist"; extern const PERSISTDECLSPEC char *PROGID_MSPersist_Version = MS_PERSIST_PROGID ".1"; extern const PERSISTDECLSPEC WCHAR *PROGID_MSPersist_Version_W = L"MSPersist.1"; #endif // PERSIST_H
hausea/legend-pure
legend-pure-runtime-java-engine-compiled/src/main/java/org/finos/legend/pure/runtime/java/compiled/metadata/CompiledCoreInstanceBuilder.java
// Copyright 2020 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.finos.legend.pure.runtime.java.compiled.metadata; import org.eclipse.collections.api.block.procedure.Procedure2; import org.eclipse.collections.api.map.ImmutableMap; import org.eclipse.collections.api.map.MapIterable; import org.eclipse.collections.api.map.MutableMap; import org.eclipse.collections.impl.block.function.checked.CheckedFunction0; import org.eclipse.collections.impl.factory.Maps; import org.eclipse.collections.impl.map.mutable.UnifiedMap; import org.finos.legend.pure.m4.coreinstance.CoreInstance; import org.finos.legend.pure.m4.coreinstance.SourceInformation; import org.finos.legend.pure.runtime.java.compiled.generation.JavaPackageAndImportBuilder; import org.finos.legend.pure.runtime.java.compiled.generation.processors.type.EnumProcessor; import java.lang.reflect.Constructor; import java.lang.reflect.Field; /** * Creates core instances in compiled mode */ public final class CompiledCoreInstanceBuilder { private final ClassCacheByClassifier classCacheByClassifier = new ClassCacheByClassifier(); private final ThreadLocal<ClassCacheByClassifier> added = new ThreadLocal<>(); public void startTransaction() { this.added.set(new ClassCacheByClassifier()); } public void commitTransaction() { ClassCacheByClassifier trans = this.added.get(); if (trans != null) { this.added.remove(); this.classCacheByClassifier.commitChanges(trans); } } public void rollbackTransaction() { this.added.remove(); } public void clear() { this.classCacheByClassifier.clear(); this.added.remove(); } public MapIterable<String, Field> getFields(String classifier) { MapIterable<String, Field> fields = this.classCacheByClassifier.getFields(classifier); if (fields == null && this.isInTransaction()) { fields = this.added.get().getFields(classifier); } return fields; } public CoreInstance newCoreInstance(String classifier, String name, SourceInformation sourceInformation, ClassLoader classLoader) { String nameWithoutPath = name; if (nameWithoutPath.lastIndexOf("::") != -1) { nameWithoutPath = nameWithoutPath.substring(nameWithoutPath.lastIndexOf("::") + 2); } ClassCache classCache = this.getClassCache(classifier); if (classCache == null) { classCache = this.classCacheByClassifier.addToClassCache(classifier, classLoader); } try { CoreInstance inst = (CoreInstance)classCache.constructor.newInstance(nameWithoutPath); inst.setSourceInformation(sourceInformation); //this.getMetamodel().add(classifier, identifier, inst); return inst; } catch (Exception ex) { throw new RuntimeException(ex); } } public CoreInstance newEnumCoreInstance(String classifier, String name, SourceInformation sourceInformation, ClassLoader classLoader) { ClassCache classCache = this.getClassCache(EnumProcessor.ENUM_CLASS_NAME); if (classCache == null) { classCache = this.classCacheByClassifier.addEnumToClassCache(EnumProcessor.ENUM_CLASS_NAME, classLoader); } try { CoreInstance inst = (CoreInstance)classCache.constructor.newInstance(name, classifier); inst.setSourceInformation(sourceInformation); //this.getMetamodel().add(classifier, name, inst); return inst; } catch (Exception ex) { throw new RuntimeException(ex); } } private ClassCache getClassCache(String classifier) { ClassCache classCache = this.classCacheByClassifier.classCache.get(classifier); if (classCache == null && this.isInTransaction()) { classCache = this.added.get().classCache.get(classifier); } return classCache; } private boolean isInTransaction() { return this.added.get() != null; } public int getClassCacheSize() { return this.classCacheByClassifier.classCache.size(); } private static class ClassCacheByClassifier { private final MutableMap<String, ClassCache> classCache = UnifiedMap.newMap(); private void clear() { this.classCache.clear(); } private MapIterable<String, Field> getFields(String classifier) { return this.classCache.get(classifier).fields; } private ClassCache addToClassCache(final String classifier, final ClassLoader classLoader) { try { return this.classCache.getIfAbsentPut(classifier, new CheckedFunction0<ClassCache>() { @Override public ClassCache safeValue() throws Exception { Class cl = classLoader.loadClass(JavaPackageAndImportBuilder.buildImplClassReferenceFromUserPath(classifier)); return new ClassCache(cl, true, String.class); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } private ClassCache addEnumToClassCache(final String classifier, final ClassLoader classLoader) { try { return this.classCache.getIfAbsentPut(classifier, new CheckedFunction0<ClassCache>() { @Override public ClassCache safeValue() throws Exception { Class<?> cl = classLoader.loadClass(JavaPackageAndImportBuilder.buildPackageFromSystemPath(classifier) + "." + classifier); return new ClassCache(cl, true, String.class, String.class); } }); } catch (Exception ex) { throw new RuntimeException(ex); } } private void commitChanges(ClassCacheByClassifier toBeAdded) { toBeAdded.classCache.forEachKeyValue(new Procedure2<String, ClassCache>() { @Override public void value(String classifer, ClassCache classCache) { ClassCacheByClassifier.this.classCache.getIfAbsentPut(classifer, classCache); } }); } } private static class ClassCache { private final Constructor<?> constructor; private final ImmutableMap<String, Field> fields; private ClassCache(Class<?> cls, boolean cacheConstructor, Class<?>... parameterTypes) { this.constructor = cacheConstructor ? getConstructor(cls, parameterTypes) : null; this.fields = indexFieldsByName(cls); } private static Constructor<?> getConstructor(Class<?> cls, Class<?>... parameterTypes) { try { Constructor<?> constructor = cls.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException("Error finding constructor for " + cls.getCanonicalName(), e); } } private static ImmutableMap<String, Field> indexFieldsByName(Class<?> cls) { // Is this logic correct? What about overrides and non-override name clashes? MutableMap<String, Field> fieldsByName = Maps.mutable.empty(); for (Class<?> current = cls; current != null; current = current.getSuperclass()) { for (Field field : current.getDeclaredFields()) { fieldsByName.put(field.getName(), field); } } return fieldsByName.toImmutable(); } } }
bl4ckic3/fsfw
timemanager/TimeStamperIF.h
<gh_stars>0 #ifndef FRAMEWORK_TIMEMANAGER_TIMESTAMPERIF_H_ #define FRAMEWORK_TIMEMANAGER_TIMESTAMPERIF_H_ #include "../returnvalues/HasReturnvaluesIF.h" /** * A class implementing this IF provides facilities to add a time stamp to the * buffer provided. * Implementors need to ensure that calling the method is thread-safe, i.e. * addTimeStamp may be called in parallel from a different context. */ class TimeStamperIF { public: static const uint8_t INTERFACE_ID = CLASS_ID::TIME_STAMPER_IF; static const ReturnValue_t BAD_TIMESTAMP = MAKE_RETURN_CODE(1); //! This is a mission-specific constant and determines the total //! size reserved for timestamps. //! TODO: Default define in FSFWConfig ? static const uint8_t MISSION_TIMESTAMP_SIZE = 8; virtual ReturnValue_t addTimeStamp(uint8_t* buffer, const uint8_t maxSize) = 0; virtual ~TimeStamperIF() {} }; #endif /* FRAMEWORK_TIMEMANAGER_TIMESTAMPERIF_H_ */
VladGordienko28/FluorineEngine-I
Src/Engine/FrCore.cpp
<filename>Src/Engine/FrCore.cpp /*============================================================================= FrCore.cpp: Various engine core functions. Copyright Jun.2016 <NAME>. =============================================================================*/ #include "Engine.h" // // Globals. // CDebugOutputBase* GOutput = nullptr; Bool GIsEditor = false; CPlatformBase* GPlat = nullptr; String GDirectory = L""; DWord GFrameStamp = 0; String GCmdLine[8] = {}; /*----------------------------------------------------------------------------- String implementation. -----------------------------------------------------------------------------*/ // // String serialization. // void Serialize( CSerializer& S, String& V ) { if( S.GetMode() == SM_Load ) { // Load string. Integer L; V.DeleteString(); Serialize( S, L ); if( L > 0 ) { V.NewString( L ); S.SerializeData( *V, sizeof(Char) * L ); } } else { // Store or count string. Integer Len = V.Len(); Serialize( S, Len ); if( Len > 0 ) S.SerializeData( *V, sizeof(Char)*Len ); } } // // Convert string into integer value, return true if // converted successfully, otherwise return false and out value // will be set default. // Bool String::ToInteger( Integer& Value, Integer Default ) const { if (!Len()) return false; Integer iChar = 0; Bool bNeg = false; Value = Default; // Detect sign. if( Self->Data[0] == L'-' ) { iChar++; bNeg = true; } else if( Self->Data[0] == L'+' ) { iChar++; bNeg = false; } // Parse digit by digit. Integer Result = 0; for (Integer i = iChar; i < Len(); i++) if (Self->Data[i] >= L'0' && Self->Data[i] <= L'9') { Result *= 10; Result += (Integer)(Self->Data[i] - L'0'); } else return false; Value = bNeg ? -Result : Result; return true; } // // Convert string into float value, return true if // converted successfully, otherwise return false and out value // will be set default. // Bool String::ToFloat( Float& Value, Float Default ) const { if (!Len()) return false; Integer iChar = 0; Bool bNeg = false; Float Frac = 0.f, Ceil = 0.f; Value = Default; // Detect sign. if (Self->Data[0] == L'-') { iChar++; bNeg = true; } else if (Self->Data[0] == L'+') { iChar++; bNeg = false; } if( iChar < Len() ) { if( Self->Data[iChar] == L'.' ) { // Parse fractional part. ParseFrac: iChar++; Float m = 0.1f; for( ; iChar < Len(); iChar++ ) if( Self->Data[iChar] >= L'0' && Self->Data[iChar] <= L'9' ) { Frac += (Integer)(Self->Data[iChar] - L'0') * m; m /= 10.f; } else return false; } else if( Self->Data[iChar] >= L'0' && Self->Data[iChar] <= L'9' ) { // Parse ceil part. for( ; iChar < Len(); iChar++ ) if( Self->Data[iChar] >= L'0' && Self->Data[iChar] <= L'9' ) { Ceil *= 10.f; Ceil += (Integer)(Self->Data[iChar] - L'0'); } else if( Self->Data[iChar] == L'.' ) { goto ParseFrac; } else return false; } else return false; } else return false; Value = bNeg ? -(Ceil+Frac) : +(Ceil+Frac); return true; } // // Remove Count symbols from StartChar position. // String String::Delete( String Str, Integer StartChar, Integer Count ) { StartChar = Clamp( StartChar, 0, Str.Len()-1 ); Count = Clamp( Count, 0, Str.Len()-StartChar ); return Copy( Str, 0, StartChar ) + Copy( Str, StartChar+Count, Str.Len()-StartChar-Count ); } // // Copy substring. // String String::Copy( String Source, Integer StartChar, Integer Count ) { StartChar = Clamp( StartChar, 0, Source.Len()-1 ); Count = Clamp( Count, 0, Source.Len()-StartChar ); return Count ? String( &Source.Self->Data[StartChar], Count ) : String(); } // // Search needle in haystack :), of string // of course. if not found return -1. // Integer String::Pos( String Needle, String HayStack ) { const Char* P = wcsstr( *HayStack, *Needle ); return P ? ((Integer)P - (Integer)*HayStack)/sizeof(Char) : -1; } // // Return string copy with upper case. // String String::UpperCase( String Str ) { String N; N.NewString(Str.Len()); for( Integer i=0; i<Str.Len(); i++ ) { N.Self->Data[i] = towupper(Str(i)); } return N; } // // Return string copy with lower case. // String String::LowerCase( String Str ) { String N; N.NewString(Str.Len()); for( Integer i=0; i<Str.Len(); i++ ) { N.Self->Data[i] = towlower(Str(i)); } return N; } // // Format string. // String String::Format( String Fmt, ... ) { static Char Dest[2048] = {}; va_list ArgPtr; va_start( ArgPtr, Fmt ); _vsnwprintf( Dest, 2048, *Fmt, ArgPtr ); va_end( ArgPtr ); return Dest; } // // String comparison. // Return: // < 0: Str1 < Str2. // = 0: Str1 = Str2. // > 0: Str1 > Str2. // Integer String::CompareText( String Str1, String Str2 ) { #if 0 return wcscmp( *Str1, *Str2 ); #else return _wcsicmp( *Str1, *Str2 ); #endif } // // Wrap text and put lines into array of string. // TArray<String> String::WrapText( String Text, Integer MaxColumnSize ) { TArray<String> Result; Integer i=0; do { Integer iCleanWordEnd = 0; Bool bGotWord = false; Integer iTestWord = 0; while ( ( i+iTestWord < Text.Len() )&& (Text(i+iTestWord) != '\n') ) { if( iTestWord++ > MaxColumnSize ) break; Bool bWordBreak = (Text(iTestWord+i)==' ')||(Text(iTestWord+i)=='\n')||(iTestWord+i>=Text.Len()); if( bWordBreak || !bGotWord ) { iCleanWordEnd = iTestWord; bGotWord = bGotWord || bWordBreak; } } if( iCleanWordEnd == 0 ) break; // Add to array. Result.Push(String::Copy( Text, i, iCleanWordEnd )); i += iCleanWordEnd; // Skip whitespace after word. while( Text(i) == ' ' ) i++; } while( i<Text.Len() ); return Result; } /*----------------------------------------------------------------------------- TColor implementation. -----------------------------------------------------------------------------*/ // // Convert RGB color value to HSL value // where H(Hue), S(Saturation), L(Lightness). // void TColor::RGBToHSL( TColor Color, Byte& H, Byte& S, Byte& L ) { Float R = Color.R / 256.f; Float G = Color.G / 256.f; Float B = Color.B / 256.f; Float MinValue = Min( R, Min( G, B ) ); Float MaxValue = Max( R, Max( G, B ) ); if( R == G && G == B ) { H = 0; S = 0; L = Color.G; } else { Float FH, FS, FL; FL = ( MinValue + MaxValue ) * 0.5f; if( FL < 0.5f ) FS = ( MaxValue - MinValue ) / ( MaxValue + MinValue ); else FS = ( MaxValue - MinValue ) / ( 2.f - MaxValue - MinValue ); if( R == MaxValue ) FH = ( G - B ) / ( MaxValue - MinValue ); else if( G == MaxValue ) FH = 2.f + ( B - R ) / ( MaxValue - MinValue ); else if( B == MaxValue ) FH = 4.f + ( R - G ) / ( MaxValue - MinValue ); FH /= 6.f; if( FH < 0.f ) FH += 1.f; H = Trunc( FH * 254.9f ); S = Trunc( FS * 254.9f ); L = Trunc( FL * 254.9f ); } } // // Convert HSL color value to RGB value // where H(Hue), S(Saturation), L(Lightness). // TColor TColor::HSLToRGB( Byte H, Byte S, Byte L ) { Float FH = H / 256.f; Float FS = S / 256.f; Float FL = L / 256.f; if( S == 0 ) { return TColor( L, L, L, 0xff ); } else { Float FR, FG, FB, temp1, temp2, tempR, tempG, tempB; if( FL < 0.5f ) temp2 = FL * ( 1.f + FS ); else temp2 = ( FL + FS ) - ( FL * FS ); temp1 = 2.f * FL - temp2; tempR = FH + 1.f / 3.f; if( tempR > 1.f ) tempR -= 1.f; tempG = FH; tempB = FH - 1.f / 3.f; if( tempB < 0.f ) tempB += 1.f; // Red channel. if( tempR < 1.f/6.f ) FR = temp1 + (temp2-temp1)*6.f * tempR; else if( tempR < 0.5f ) FR = temp2; else if( tempR < 2.f/3.f ) FR = temp1 + (temp2-temp1)*((2.f/3.f)-tempR)*6.f; else FR = temp1; // Green channel. if( tempG < 1.f/6.f ) FG = temp1 + (temp2-temp1)*6.f * tempG; else if( tempG < 0.5f ) FG = temp2; else if( tempG < 2.f/3.f ) FG = temp1 + (temp2-temp1)*((2.f/3.f)-tempG)*6.f; else FG = temp1; // Blue channel. if( tempB < 1.f/6.f ) FB = temp1 + (temp2-temp1)*6.f * tempB; else if( tempB < 0.5f ) FB = temp2; else if( tempB < 2.f/3.f ) FB = temp1 + (temp2-temp1)*((2.f/3.f)-tempB)*6.0; else FB = temp1; return TColor( Trunc( FR * 254.9f ), Trunc( FG * 254.9f ), Trunc( FB * 254.9f ), 0xff ); } } /*----------------------------------------------------------------------------- TArray implementation. -----------------------------------------------------------------------------*/ // // Figure out how much extra items should alloc for array, // this depend on array' inner size. Result is always power // of two. // Integer ExtraSpace( DWord InnerSize ) { if( InnerSize <= 1 ) return 128; else if( InnerSize <= 4 ) return 64; else if( InnerSize <= 8 ) return 32; else return 16; } // // Main reallocation function, now it's allocate more items, // to make faster next allocation. // void ReallocateArray( void*& Data, Integer& Count, Integer NewCount, DWord InnerSize ) { // Don't reallocate. if( Count == NewCount ) return; if( NewCount == 0 ) { // Get rid data. MemFree( Data ); Data = nullptr; Count = 0; } else if( Data == nullptr ) { // Allocate new data. Integer OverItems = ExtraSpace( InnerSize ) - 1; Integer TrueNew = NewCount | OverItems; Data = MemAlloc( TrueNew * InnerSize ); Count = NewCount; } else { // Reallocate array. if( NewCount > Count ) { // Add new item. Integer OverItems = ExtraSpace( InnerSize ) - 1; Integer TrueOld = Count | OverItems; if( NewCount >= TrueOld ) { // Need extra items. Integer TrueNew = NewCount | OverItems; Data = MemRealloc( Data, TrueNew * InnerSize ); MemZero ( (Byte*)Data + Count * InnerSize, (NewCount - Count) * InnerSize ); } else { // Memory enough, but need zero. MemZero ( (Byte*)Data + Count * InnerSize, (NewCount - Count) * InnerSize ); } Count = NewCount; } else { // Remove some items. Integer OverItems = ExtraSpace( InnerSize ) - 1; Integer TrueNew = OverItems | NewCount; Integer TrueOld = OverItems | Count; if( TrueOld != TrueNew ) Data = MemRealloc( Data, TrueNew * InnerSize ); Count = NewCount; } } } /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/