language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
4,492
2.640625
3
[]
no_license
$( document ).ready(function() { //============================================================================== var activeItem; function initialize() { //-----------start variable scope for each object---------------------- var mapOptions = { zoom: 13, center: new google.maps.LatLng(42.139541,-87.928747) }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); var infoWindow = new google.maps.InfoWindow({ maxWidth: Math.round( $('#map').width()*.65 ) }); $('#map_objects > div[data-visible="true"]').each(function(){ //-----------start building map objects----------- var id = $(this).attr('id'); var type = $(this).data('type'); var parkDetails = this.outerHTML; //var infoWidth = ; var pin_latlng; var pinImage; //creating pin location from GPS coordinates either manually inputed or derived from the provided address if ( $(this).data('custom_lat') && $(this).data('custom_lng') ){ pin_latlng = new google.maps.LatLng( $(this).data('custom_lat') , $(this).data('custom_lng') ) } else{ pin_latlng = new google.maps.LatLng( $(this).data('BC_lat') , $(this).data('BC_lng') ) }; //setting pin color based on 'type' if (type == 'Pool'){pinImage = 'http://maps.google.com/mapfiles/ms/micons/blue.png'} else if (type == 'Country Club'){pinImage = 'http://maps.google.com/mapfiles/ms/micons/lightblue.png'} else if (type == 'Golf Course'){pinImage = 'http://maps.google.com/mapfiles/ms/micons/orange.png'} else if (type == 'Park'){pinImage = 'http://maps.google.com/mapfiles/ms/micons/green.png'} else if (type == 'Recreation Center'){pinImage = 'http://maps.google.com/mapfiles/ms/micons/red.png'} else {pinImage = 'http://maps.google.com/mapfiles/ms/micons/red.png'}; var marker = new google.maps.Marker({ map: map, position: pin_latlng, title: $(this).data('name'), icon: pinImage }); //result google.maps.event.addListener( marker, 'click', function() { infoWindow.close() infoWindow.setContent( parkDetails ) infoWindow.open( map, marker); }); if( $(this).data('active') == 'true' ) { activeItem = marker; //infoWindow.open(map, marker) } //-----------end building map objects----------- }); }; //============================================================================== function filterMapObjects() { var typeSpecified = $('#typeToggles label input:checked').length>=1; var featureSpecified = $('#featureToggles label input:checked').length>=1; function setVisibleType(){ $('#typeToggles label input:checked').each( function(){ var type = $(this).parent().attr('id').slice( $(this).parent().attr('id').indexOf('_')+1 ).replace(/-/,' '); $('#map_objects').children('div[data-type="'+type+'"]').attr('data-visible','true') }) }; function setVisibleFeature(){ $('#featureToggles label input:checked').each( function() { $('#map_objects').children('div[data-features*="'+$(this).val()+'"]').attr('data-visible', 'true') ; }); }; if ( typeSpecified || featureSpecified) { $('#map_objects').children('div').attr('data-visible', 'false'); } else { $('#map_objects').children('div').attr('data-visible', 'true'); }; if (featureSpecified && !typeSpecified) { setVisibleFeature() }; if (!featureSpecified && typeSpecified) { setVisibleType() }; if (featureSpecified && typeSpecified) { setVisibleType() var array = $('#map_objects').children('div[data-visible="true"]'); array.each( function() { $(this).attr('data-visible', 'false'); }); $('#featureToggles label input:checked').each( function() { array.filter( $('div[data-features*="'+$(this).val()+'"]') ).attr('data-visible', 'true') }); }; } //============================================================================== $('#typeToggles label input').change( function(){ filterMapObjects() // $('#map_objects').children('div').attr('data-visible', 'true') $('body').trigger('mapRefresh'); }); //============================================================================== $('#featureToggles label input').change( function() { filterMapObjects() $('body').trigger('mapRefresh'); }); //============================================================================== $('body').on('mapRefresh', function(event) { initialize(); if(activeItem){ google.maps.event.trigger(activeItem, 'click' ); } //-----------end initialize function---------------------- }); initialize(); });
C++
UTF-8
2,397
2.65625
3
[]
no_license
#include "framebuffer.h" namespace gl { Framebuffer::Framebuffer() { float quadVertices[24] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glGenTextures(1, &texColorBuffer); glBindTexture(GL_TEXTURE_2D, texColorBuffer); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, 1024, 720, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColorBuffer, 0); // RBO renderbuffer object glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1024, 720); glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); // rbo error if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); // QuadVAO glGenVertexArrays(1, &quadVAO); glBindVertexArray(quadVAO); // QuadVBO glGenBuffers(1, &quadVBO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData( GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); } void Framebuffer::Draw() const { glBindVertexArray(quadVAO); glDrawArrays(GL_TRIANGLES, 0, 6); } void Framebuffer::Bind() const { glBindFramebuffer(GL_FRAMEBUFFER, fbo); } void Framebuffer::Unbind() const { glBindFramebuffer(GL_FRAMEBUFFER, 0); } unsigned int Framebuffer::GetColorBuffer() { return texColorBuffer; } }
Go
UTF-8
3,213
2.78125
3
[]
no_license
package dbservice import ( "log" dbcommon "github.com/Ankr-network/dccn-common/db" common_proto "github.com/Ankr-network/dccn-common/protos/common" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type DBService interface { // Get gets a dc item by pb's id. Get(id int64) (*common_proto.DataCenter, error) // Get gets a dc item by pb's name. GetByName(name string) (*common_proto.DataCenter, error) // Create Creates a new dc item if not exits. Create(center *common_proto.DataCenter) error // GetAll gets all task related to user id. GetAll() (*[]*common_proto.DataCenter, error) // Update updates dc item Update(center *common_proto.DataCenter) error // UpdateStatus updates dc item UpdateStatus(name string, status common_proto.DCStatus) error // Close closes db connection Close() // dropCollection for testing usage dropCollection() } // UserDB implements DBService type DB struct { dbName string collectionName string session *mgo.Session } // New returns DBService. func New(conf dbcommon.Config) (*DB, error) { session, err := dbcommon.CreateDBConnection(conf) if err != nil { return nil, err } return &DB{ dbName: conf.DB, collectionName: conf.Collection, session: session, }, nil } func (p *DB) collection(session *mgo.Session) *mgo.Collection { return session.DB(p.dbName).C(p.collectionName) } // Get gets user item by id. func (p *DB) Get(id int64) (*common_proto.DataCenter, error) { session := p.session.Clone() defer session.Close() var center common_proto.DataCenter err := p.collection(session).Find(bson.M{"id": id}).One(&center) return &center, err } // Get gets user item by name. func (p *DB) GetByName(name string) (*common_proto.DataCenter, error) { session := p.session.Clone() defer session.Close() var center common_proto.DataCenter err := p.collection(session).Find(bson.M{"name": name}).One(&center) return &center, err } // Create creates a new data center item if it not exists func (p *DB) Create(center *common_proto.DataCenter) error { session := p.session.Clone() defer session.Close() return p.collection(session).Insert(center) } // Update updates user item. func (p *DB) Update(datacenter *common_proto.DataCenter) error { session := p.session.Clone() defer session.Close() return p.collection(session).Update( bson.M{"name": datacenter.Name}, bson.M{"$set": bson.M{ "Report": datacenter.DcHeartbeatReport.Report, "Metrics": datacenter.DcHeartbeatReport.Metrics}}) } func (p *DB) UpdateStatus(name string, status common_proto.DCStatus) error { session := p.session.Clone() defer session.Close() return p.collection(session).Update( bson.M{"name": name}, bson.M{"$set": bson.M{"status": status}}) } // Close closes the db connection. func (p *DB) Close() { p.session.Close() } func (p *DB) dropCollection() { log.Println(p.session.DB(p.dbName).C(p.collectionName).DropCollection().Error()) } func (p *DB) GetAll() (*[]*common_proto.DataCenter, error) { session := p.session.Clone() defer session.Close() var dcs []*common_proto.DataCenter if err := p.collection(session).Find(bson.M{}).All(&dcs); err != nil { return nil, err } return &dcs, nil }
PHP
UTF-8
9,231
2.546875
3
[ "Apache-2.0" ]
permissive
<?php /** ---- eapie ---- * 优狐积木框架,让开发就像组装积木一样简单! * 解放千千万万程序员!这只是1.0版本,后续版本势如破竹! * * QQ群:523668865 * 开源地址 https://gitee.com/lxh888/openshop * 官网 http://eonfox.com/ * 后端框架文档 http://cao.php.eonfox.com * * 作者:绵阳市优狐网络科技有限公司 * 电话/微信:18981181942 * QQ:294520544 */ namespace eapie\engine\table; use eapie\main; class session extends main { /** * 数据检测 * @var array */ public $check = array( 'websocket_client_id' => array( 'args' => array( 'exist'=> array('缺少websocket连接ID参数'), 'echo' => array('websocket连接ID的数据类型不合法'), '!null'=> array('websocket连接ID不能为空'), ), ), 'session_websocket_token' => array( 'args' => array( 'exist'=> array('缺少websocket会话令牌参数'), 'echo' => array('websocket会话令牌的数据类型不合法'), '!null'=> array('websocket会话令牌不能为空'), ), ), 'websocket_server_time' => array( 'args' => array( 'exist'=> array('缺少websocket服务器时间参数'), 'echo' => array('websocket服务器时间的数据类型不合法'), 'match'=>array('/^[\d]{1,}$/', "websocket服务器时间必须是整数"), ), ), ); /** * 获取一个id号 * * @param void * @return string */ public function get_unique_id(){ //保持会话id为72位 return cmd(array(58), 'random autoincrement'); } /** * 获取失效时间 * * @param void * @return string */ public function get_expire_time(){ if( empty($_SESSION['user_id']) ){ //当前时间+ 1个小时的秒数 return time() + 3600; }else{ //登录状态,当前时间+ 30天的秒数 return time() + 2592000; } } /** * 获取一个令牌号 * * @param string $session_id * @return string */ public function get_token_id($session_id = ''){ if( empty($session_id) && !empty($_SESSION['session_id']) ){ $session_id = $_SESSION['session_id']; } $time = time(); return md5($session_id.$time).cmd(array(18), 'random autoincrement').md5($time.$session_id); } /** * 根据ID,判断数据是否存在 * * @param string $session_id */ public function find_exists_id($session_id = ''){ if( empty($session_id) ){ return false; } return (bool)db(parent::DB_SYSTEM_ID) ->table('session') ->where(array('session_id=[+]', (string)$session_id)) ->find('session_id'); } /** * 根据令牌 获取会话编号 * * @param string $token * @return array */ public function find_token_get_id($token = ''){ if( empty($token) ){ return false; } return db(parent::DB_SYSTEM_ID) ->table('session') ->where(array('session_right_token=[+]', (string)$token), array('[or] session_left_token=[+]', (string)$token)) ->find('session_id', 'session_right_token', 'session_left_token', 'session_lock'); } /** * 根据websocket令牌 获取会话数据 * * @param string $session_websocket_token * @return array */ public function find_websocket_token($session_websocket_token = ''){ if( empty($session_websocket_token) ){ return false; } return db(parent::DB_SYSTEM_ID) ->table('session') ->where( array('session_websocket_token=[+]', (string)$session_websocket_token) ) ->find(); } /** * 获取一个数据 * * @param string $session_id * @return array */ public function find($session_id = ''){ if( empty($session_id) ){ return false; } return db(parent::DB_SYSTEM_ID) ->table('session') ->where(array('session_id=[+]', (string)$session_id)) ->find(); } /** * 更新数据 * * @param array $where * @param array $data * @param array $call_data * @return bool */ public function update($where = array(), $data = array(), $call_data = array()){ if( empty($where) || empty($data) ){ return false; } return (bool)db(parent::DB_SYSTEM_ID) ->table('session') ->call('where', $where) ->call('data', $call_data) ->update($data); } /** * 删除数据 * * @param array $where * @return array */ public function delete($where = array()){ if( empty($where) ){ return false; } return (bool)db(parent::DB_SYSTEM_ID) ->table('session') ->call('where', $where) ->delete(); } /** * 根据唯一标识,删除数据 * * @param array $session_id * @return array */ public function remove($session_id = ''){ if( empty($session_id) ){ return false; } return (bool)db(parent::DB_SYSTEM_ID) ->table('session') ->where(array('session_id=[+]', (string)$session_id)) ->delete(); } /** * 获取多个用户数据 * $config = array( * 'where' => array(), //条件 * 'orderby' => array(), //排序 * 'limit' => array(0, page_size), //取出条数,默认不限制 * 'select' => array(),//查询的字段,可以是数组和字符串 * ); * * @param array $config * @return array */ public function select($config = array()){ $where = isset($config['where']) && is_array($config['where'])? $config['where'] : array(); $orderby = isset($config['orderby']) && is_array($config['orderby'])? $config['orderby'] : array(); $limit = isset($config['limit']) && is_array($config['limit'])? $config['limit'] : array(); $select = isset($config['select']) && is_array($config['select'])? $config['select'] : array(); return db(parent::DB_SYSTEM_ID) ->table('session') ->call('where', $where) ->call('orderby', $orderby) ->call('limit', $limit) ->select($select); } /** * 根据用户ID和应用ID 获取会话数据 * * @param string $user_id * @return array */ public function select_application_user($application_id = '', $user_id = ''){ if( empty($user_id) ){ return false; } if( is_array($user_id) ){ $in_string = "\"".implode("\",\"", $user_id)."\""; $where_user_id = array('user_id IN([-])', $in_string, true); }else{ $where_user_id = array('user_id=[+]', (string)$user_id); } return db(parent::DB_SYSTEM_ID) ->table('session') ->where( $where_user_id, array('[and] application_id=[+]', (string)$application_id) ) ->select(); } /** * 初始化会话 * * @param string $session_id 会话id * @param bool | NULL $exists 开启会话时,会话数据是否存在 * @return bool */ public function insert_init($session_id = '', $exists = NULL){ $session_id = is_string($session_id) || is_numeric($session_id)? (string)$session_id : ''; //获取数据库配置 $info = db(parent::DB_SYSTEM_ID)->info(); $db_config = $info['config']; $db_system_id = parent::DB_SYSTEM_ID; $_SESSION = db(parent::DB_SYSTEM_ID, true, $db_config)->session($session_id, $exists); if( empty($_SESSION['session_id']) ){ return false; } //sleep ( 30 );//先延迟0.5秒 //析构,覆盖更新会话 destruct('db.session.update:'.$_SESSION['session_id'], true, array($db_config, $db_system_id), function($db_config, $db_system_id){ //再会话更新之前,锁设为0 $_SESSION['session_lock'] = 0; db($db_system_id, true, $db_config)->session($_SESSION); }); return true; } /** * 删除数据 * * @param array $where * @return array */ public function delete_destruct($where = array()){ if( !isset($_SESSION['session_id']) ){ return true; } //登陆的用户 更新 user_log_out_time if( !empty($_SESSION['user_id']) ){ object(parent::TABLE_USER_LOG)->update_log_out(); } //删除当前会话 $bool = $this->remove($_SESSION['session_id']); return $bool; } /** * 获取当前接口合法会话数据 * * @param void * @return array */ public function get_api_legal_data(){ if( empty($_SESSION) || empty($_SESSION['session_id']) ){ return false; } //白名单 私密数据不能获取 $whitelist = array( 'session_found_time', 'session_now_time', 'session_expire_time', 'session_websocket_token', 'session_right_token', 'session_left_token' ); $session_data = cmd(array($_SESSION, $whitelist), 'arr whitelist'); return $session_data; } /** * 获取当前合法会话数据 * * @param void * @return array */ public function get_legal_data(){ if( empty($_SESSION) || empty($_SESSION['session_id']) ){ return false; } ///白名单 私密数据不能获取 $whitelist = array( 'session_id', 'user_id', 'session_ip', 'session_browser', 'session_public', 'session_found_time', 'session_now_time', 'session_expire_time', 'session_websocket_token', 'session_right_token', 'session_left_token' ); $session_data = cmd(array($_SESSION, $whitelist), 'arr whitelist'); return $session_data; } } ?>
PHP
UTF-8
602
2.5625
3
[ "MIT" ]
permissive
<?php use App\KindSport; use Illuminate\Database\Seeder; class KindSportSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $type_sports = [ 'Футбол', 'Баскетбол', 'Бокс', 'Хокей', 'Біатлон', 'Плавання', 'Покер', ]; foreach ($type_sports as $key => $value) { KindSport::create([ 'name_kind_sport' => $value ]); } } }
Swift
UTF-8
1,696
3.03125
3
[ "MIT" ]
permissive
// import RangicCore import SwiftyJSON class SensitiveLocations { let SensitiveDistanceInMeters: Double = 50 static var sharedInstance: SensitiveLocations { struct _Singleton { static let instance = SensitiveLocations() } return _Singleton.instance } fileprivate(set) var locations = [Location]() func isSensitive(_ location: Location) -> Bool { for loc in locations { if loc.metersFrom(location) < SensitiveDistanceInMeters { return true } } return false } fileprivate func locationToDictionary(_ location: Location) -> Dictionary<String, AnyObject> { return [ "latitude" : location.latitude as AnyObject, "longitude" : location.longitude as AnyObject] } fileprivate var fullLocationFilename: String { return Preferences.preferencesFolder.stringByAppendingPath("rangic.PeachMetadata.sensitive.locations") } fileprivate init() { if let data = NSData(contentsOfFile: fullLocationFilename) { if let json = try? JSON(data:NSData(data: data as Data) as Data) { var rawLocationList = [Location]() for (_,subjson):(String,JSON) in json { let latitude = subjson["latitude"].doubleValue let longitude = subjson["longitude"].doubleValue rawLocationList.append(Location(latitude: latitude, longitude: longitude)) } updateLocations(rawLocationList) } } } fileprivate func updateLocations(_ rawList: [Location]) { locations = rawList } }
TypeScript
UTF-8
422
3.15625
3
[]
no_license
export interface IQuestion { statement: string; answer: string; penalty: number; } export class Question implements IQuestion { public statement: string; public answer: string; public penalty: number; constructor( statement?: string, answer?: string, penalty?: number, ) { this.statement = statement || ''; this.answer = answer || ''; this.penalty = penalty || -1; } }
Java
UTF-8
8,951
2.234375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.chl.LifeOfAGoblin.jME3.factory; import com.jme3.bullet.collision.shapes.BoxCollisionShape; import com.jme3.bullet.collision.shapes.CapsuleCollisionShape; import com.jme3.bullet.control.CharacterControl; import com.jme3.bullet.control.GhostControl; import com.jme3.input.InputManager; import com.jme3.input.RawInputListener; import com.jme3.input.TouchInput; import com.jme3.input.awt.AwtKeyInput; import com.jme3.input.awt.AwtMouseInput; import com.jme3.input.lwjgl.JInputJoyInput; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.control.Control; import edu.chl.LifeOfAGoblin.jME3.controller.ModelControl; import edu.chl.LifeOfAGoblin.jME3.controller.character.NPCCollisionControl; import edu.chl.LifeOfAGoblin.jME3.controller.character.NPCMoveControl; import edu.chl.LifeOfAGoblin.jME3.controller.character.PlayerHealthControl; import edu.chl.LifeOfAGoblin.jME3.controller.character.PlayerMoveControl; import edu.chl.LifeOfAGoblin.model.character.AbstractCharacter; import edu.chl.LifeOfAGoblin.model.character.Minion; import edu.chl.LifeOfAGoblin.model.character.Player; import edu.chl.LifeOfAGoblin.model.character.Weapon; import edu.chl.LifeOfAGoblin.utils.InputManagerWrapper; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author fredrik */ public class CharacterFactoryTest { private Player player; private Minion minion; private Node node1; private Node node2; public CharacterFactoryTest() { } @Before public void setUp() { player = new Player(); minion = new Minion(); node1 = new Node(); node2 = new Node(); /** * You need a TouchInput to create an Inputmanager and the only class in * jme3 that implements TouchInput cannot be imported, and that is * the reason this exists */ class TestTouchInput implements TouchInput{ @Override public void setSimulateMouse(boolean bln) { } @Override public boolean getSimulateMouse() { return true; } @Override public boolean isSimulateMouse() { return true; } @Override public void setSimulateKeyboard(boolean bln) { } @Override public void setOmitHistoricEvents(boolean bln) { } @Override public void initialize() { } @Override public void update() { } @Override public void destroy() { } @Override public boolean isInitialized() { return true; } @Override public void setInputListener(RawInputListener rl) { } @Override public long getInputTimeNanos() { return 1; } } InputManagerWrapper.getInstance().initialize(new InputManager(new AwtMouseInput(), new AwtKeyInput(), new JInputJoyInput(), new TestTouchInput())); } @After public void tearDown() { } @Test public void testCreateCharacter() { //setup CharacterPainter.paintCharacter(node1, player); CharacterPainter.paintCharacter(node2, minion); Control c1; Control c2; //tests that ghostControls are added correctly try { //setup c1 = node1.getControl(GhostControl.class); c2 = node2.getControl(GhostControl.class); Vector3f measurements1 = ((BoxCollisionShape)((GhostControl)c1).getCollisionShape()).getHalfExtents(); Vector3f measurements2 = ((BoxCollisionShape)((GhostControl)c2).getCollisionShape()).getHalfExtents(); //tests that ghostcontrols have a correct shape assertTrue(measurements1.x == 1); assertTrue(measurements1.y == player.getCollisionHeight()); assertTrue(measurements1.z == player.getCollisionWidth()); assertTrue(measurements2.x == 1); assertTrue(measurements2.y == minion.getCollisionHeight()); assertTrue(measurements2.z == minion.getCollisionWidth()); } catch (NullPointerException ex) { fail(); } //tests that modelcontrols are added correctly try { //setup c1 = node1.getControl(ModelControl.class); c2 = node2.getControl(ModelControl.class); AbstractCharacter char1 = ((AbstractCharacter)((ModelControl)c1).getModel()); AbstractCharacter char2 = ((AbstractCharacter)((ModelControl)c2).getModel()); //tests that modelcontrols have the right model assertTrue(char1.equals(player)); assertTrue(char2.equals(minion)); } catch (NullPointerException ex) { fail(); } //tests that characterControls are added correctly try { c1 = node1.getControl(CharacterControl.class); c2 = node2.getControl(CharacterControl.class); float height1 = ((CapsuleCollisionShape)((CharacterControl)c1).getCollisionShape()).getHeight(); float radius1 = ((CapsuleCollisionShape)((CharacterControl)c1).getCollisionShape()).getRadius(); int axis1 = ((CapsuleCollisionShape)((CharacterControl)c1).getCollisionShape()).getAxis(); float height2 = ((CapsuleCollisionShape)((CharacterControl)c2).getCollisionShape()).getHeight(); float radius2 = ((CapsuleCollisionShape)((CharacterControl)c2).getCollisionShape()).getRadius(); int axis2 = ((CapsuleCollisionShape)((CharacterControl)c2).getCollisionShape()).getAxis(); //tests that CharacterControls have a correct shape assertTrue(axis1 == 1); assertTrue(height1 == player.getHeight()); assertTrue(radius1 == player.getWidth()); assertTrue(axis2 == 1); assertTrue(height2 == minion.getHeight()); assertTrue(radius2 == minion.getWidth()); } catch (NullPointerException ex) { fail(); } //tests that a playerhealthcontrol is added to the player try { //setup node1.getControl(PlayerHealthControl.class).setEnabled(true); } catch (NullPointerException ex) { fail(); } //tests that a playermovecontrol is added to the player try { //setup node1.getControl(PlayerMoveControl.class).setEnabled(true); } catch (NullPointerException ex) { fail(); } //tests that a npccollisioncontrol is added to the minion try { //setup node2.getControl(NPCCollisionControl.class).setEnabled(true); } catch (NullPointerException ex) { fail(); } //tests that a npcmovecontrol is added to the minion try { //setup node2.getControl(NPCMoveControl.class).setEnabled(true); } catch (NullPointerException ex) { fail(); } //tests that a weapon is added to the minion try { //setup ((Minion)node2.getControl(ModelControl.class).getModel()).getWeapon().getClass(); } catch (NullPointerException ex) { fail(); } //tests that a ghostControl is added to the weapon correctly try { //setup c2 = node2.getChild(0).getControl(GhostControl.class); Vector3f measurements2 = ((BoxCollisionShape)((GhostControl)c2).getCollisionShape()).getHalfExtents(); assertTrue(measurements2.z == 1); assertTrue(measurements2.y == minion.getWeapon().getCollisionHeight()); assertTrue(measurements2.x == minion.getWeapon().getCollisionWidth()); } catch (NullPointerException ex) { fail(); } //tests that a modelControl is added to the weapon correctly try { //setup node2.getChild(0).getControl(ModelControl.class).setEnabled(true); c2 = node2.getChild(0).getControl(ModelControl.class); assertTrue(((ModelControl)c2).getModel() instanceof Weapon); } catch (NullPointerException ex) { fail(); } } }
Python
UTF-8
2,736
2.90625
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bih/env python from ..signalfd import Signalfd as _Signalfd from collections import deque as _deque import asyncio as _asyncio class Signalfd_async: def __init__(self, signals=[], flags=0, *, loop=None): self._loop = loop or _asyncio.get_event_loop() self._signalfd = _Signalfd(signals, flags) self._getters = _deque() self.enable = self._signalfd.enable self.enable_all = self._signalfd.enable_all self.disable = self._signalfd.disable self.disable_all = self._signalfd.disable_all @_asyncio.coroutine def wait(self): """Wait for the timer to expire, returning how many events have elappsed since the last call to wait() Returns -------- :return: The current count of the timer :rtype: int """ self._loop.add_reader(self._signalfd.fileno(), self._read_event) waiter = _asyncio.Future(loop=self._loop) self._getters.append(waiter) return (yield from waiter) def _consume_done_getters(self): # Delete waiters at the head of the get() queue who've timed out. while self._getters and self._getters[0].done(): self._getters.popleft() def _read_event(self): value = self._signalfd.read_event() self._put_event(value) def _put_event(self, value): """Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull. """ self._loop.remove_reader(self._signalfd.fileno()) self._consume_done_getters() for getter in self._getters: getter.set_result(value) def close(self): self._signalfd.close() def __repr__(self): fd = self._signalfd._fd or "closed" return "<{} fd={}>".format(self.__class__.__name__, fd) def watcher(loop): from asyncio import sleep from ..signalfd import pthread_sigmask, SIG_BLOCK import signal import os test_signal = signal.SIGUSR1 sfd = Signalfd_async(test_signal) pthread_sigmask(SIG_BLOCK, test_signal) sfd.enable(test_signal) print(sfd) count = 5 for i in range(count): os.kill(os.getpid(), test_signal) sig = yield from sfd.wait() print(sig) print("Got all 5 signals") sfd.close() print(sfd) def main(): import logging import asyncio log = logging.getLogger() log.setLevel(logging.DEBUG) log.addHandler(logging.StreamHandler()) loop = asyncio.get_event_loop() from asyncio import Task task = Task(watcher(loop)) loop.run_until_complete(task) if __name__ == "__main__": main()
Python
UTF-8
2,426
3.125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Oct 5 22:13:34 2016 @author: Yulia PC Графики зависимостей уровня употребления алкогольных напитков для девушек и парней по возрасту в рабочие дни """ import pylab pylab.xkcd() import matplotlib.pyplot as plt import seaborn import pandas as pd # открываем файл с данными df2 = pd.read_csv("student_alc.csv",";"); f2 = pd.read_csv("f2.csv",";"); # меняем значение колонки sex на бинарный формат df2 = df2.replace(to_replace=['M', 'F'], value=[1, 0]) """ средний уровень выпивания алкогольных напитков в рабочий день женщинами по возрасту""" age = [15, 16, 17, 18, 19, 20, 21, 22] DWF = [] a = 15; while a < 23: average = df2['DW'][df2['age']==a][df2['sex']==1].mean(); DWF.append(average); a = a + 1; avgDWF1 = pd.DataFrame([[DWF[0]], [DWF[1]],[DWF[2]],[DWF[3]],[DWF[4]],[DWF[5]],[DWF[6]],[DWF[7]]], columns=["avg_DWF"]) ages = pd.DataFrame([[age[0]], [age[1]],[age[2]],[age[3]],[age[4]],[age[5]],[age[6]],[age[7]],], columns=["age"]) avgDWF = pd.DataFrame([[age[0],DWF[0]], [age[1],DWF[1]],[age[2],DWF[2]],[age[3],DWF[3]],[age[4],DWF[4]],[age[5],DWF[5]],[age[6],DWF[6]],[age[7],DWF[7]]], columns=["age","avg_DWF"]) DW_F = pd.crosstab(avgDWF1.avg_DWF,ages.age) """ средний уровень выпивания алкогольных напитков в рабочий день мужчин по возрасту""" DWM = [] a = 15; while a < 23: averageM = df2['DW'][df2['age']==a][df2['sex']==0].mean(); DWM.append(averageM); a = a + 1; avgDWM1 = pd.DataFrame([[DWM[0]], [DWM[1]],[DWM[2]],[DWM[3]],[DWM[4]],[DWM[5]],[DWM[6]],[DWM[7]]], columns=["avg_DWM"]) avgDWM = pd.DataFrame([[age[0],DWM[0]], [age[1],DWM[1]],[age[2],DWM[2]],[age[3],DWM[3]],[age[4],DWM[4]],[age[5],DWM[5]],[age[6],DWM[6]],[age[7],DWM[7]]], columns=["age","avg_DWM"]) DW_F = pd.crosstab(avgDWM1.avg_DWM,ages.age) # построение двух графиков line_10, line_20 = plt.plot(avgDWM['age'], avgDWM['avg_DWM'], 'bD:', avgDWF['age'], avgDWF['avg_DWF'], 'r^:') plt.xlabel('age') plt.ylabel('average level of drink alc') plt.title('average level of drink alc in work day') plt.legend( (line_10, line_20), (u'Male', u'Female'), loc = 'best')
C#
UTF-8
954
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeEval { class DeltaTime { static void CalcTimeDiff(DateTime s1, DateTime s2) { long diff = Math.Max(s1.Ticks, s2.Ticks) - Math.Min(s1.Ticks, s2.Ticks); Console.WriteLine(new DateTime(diff).ToString("HH:mm:ss")); } static void Main(string[] args) { using (StreamReader reader = File.OpenText(args[0])) { while (!reader.EndOfStream) { string line = reader.ReadLine(); if (line == null) continue; string[] arr = line.Split(' ').ToArray(); CalcTimeDiff(DateTime.Parse(arr.First()), DateTime.Parse(arr.Last())); } } } } }
Java
UTF-8
30,325
2.296875
2
[]
no_license
package org.cougaar.cpe.unittests; import org.cougaar.cpe.model.*; import org.cougaar.cpe.mplan.ManueverPlanner; import org.cougaar.cpe.splan.SPlanner; import org.cougaar.cpe.planning.zplan.BNAggregate; import org.cougaar.cpe.planning.zplan.ZoneWorld; import org.cougaar.cpe.planning.zplan.ZonePlanner; import org.cougaar.cpe.planning.zplan.ZoneTask; import java.util.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class CPESimulator { protected long totalPlanningTime = 0 ; protected int planningCycles = 0 ; protected ZoneWorld zoneWorld ; protected float boardWidth = 36 ; protected float zoneGridSize = 2 ; protected float boardHeight = 28 ; protected float penaltyHeight = 4 ; protected double deltaT = 5; protected double recoveryHeight = - VGWorldConstants.getSupplyVehicleMovementRate() * deltaT * 4 ; protected int numTimeDeltasPerTask = 4 ; /** * Zone planning should be multiples of numTimeDeltasPerTask. */ protected int numTimeDeltasPerZoneSchedule = numTimeDeltasPerTask * 3 ; /** * Number of deltaTs per plan element. */ protected int numIncrementsPerPlan = 2 ; protected int searchDepth = 5 ; protected int maxBranchFactor = 60 ; protected int zoneSearchDepth = 7 ; protected int zoneBranchFactor = 60 ; protected int ASSUMED_BN_PLANNING_DELAY = 10000 ; // Pretend it tasks this long to generate the supply plan. protected int ASSUMED_SUPPLY_PLANNING_DELAY = ASSUMED_BN_PLANNING_DELAY + 5000 ; private ArrayList allSupplyEntities = new ArrayList(); private boolean verbose = false ; /** * The number of delta Ts to run this for. */ int maxDeltaTs = 1000 ; int numBNEntities = 3 ; int numCPYEntitiesPerBN = 3 ; int numSupplyOrganizations = 2 ; int numSupplyUnitsPerOrg = 5 ; private ArrayList allBNUnits = new ArrayList() ; private ArrayList allCPYUnits = new ArrayList() ; private long zonePlannerDelay = ( long ) ( numTimeDeltasPerZoneSchedule * deltaT * VGWorldConstants.MILLISECONDS_PER_SECOND ) ; private boolean isInited = false ; private boolean debugDumpPlanNodes = false ; private File debugPlanFile = null ; private int deltaIndex = 0 ; private boolean isRunning = false ; private ArrayList[] supplyVehicles; private TargetGeneratorModel targetGeneratorModel; private int numInitialTargetGenerationDeltas = 120 ; private FileWriter writer; private PrintWriter planDebugPrintWriter; private boolean configured = false ; private boolean doZonePlanning = true ; public CPESimulator() { // configureDefaultScenario(); runThread.start() ; } public void configureDefaultScenario() { configured = true ; ws = new ReferenceWorldState( boardWidth, boardHeight, penaltyHeight, recoveryHeight, deltaT ) ; // The zone world is maintained to be "independent" of the ws. It must be updated from the reference worldState // before every planning cycle. zoneWorld = new ZoneWorld( ws, zoneGridSize ) ; // Calculate what the visible time horizon is. (E.g. the furthest in time which is actually visible. double timeHorizon = ( ws.getUpperX() - ws.getLowerX() ) / VGWorldConstants.getTargetMoveRate() ; System.out.println("CPE Simulation Initialization"); System.out.println("\tTime horizon=" + timeHorizon + ", planningHorizon=" + ws.getDeltaT() * numTimeDeltasPerTask * searchDepth + ", zonePlanningHorizon=" + ( zonePlannerDelay * VGWorldConstants.SECONDS_PER_MILLISECOND + zoneSearchDepth * numTimeDeltasPerZoneSchedule * ws.getDeltaT() ) ); // Create a manuever planner per BN entity. manueverPlanners = new ManueverPlanner[ numBNEntities ] ; ws.setLogEvents( true ); double currentZoneIndex = 0 ; double averageZoneSize = ( ws.getUpperX() / ( numBNEntities * zoneGridSize ) ) ; int cpyCount= 0 ; for (int i=0;i<numBNEntities;i++) { // Now, break the BNs into zones. String id = "BN" + (i+1) ; String[] subentities = new String[numCPYEntitiesPerBN] ; int lowerZoneIndex = (int ) Math.floor( currentZoneIndex ) ; currentZoneIndex += averageZoneSize ; int upperZoneIndex = (int ) Math.floor( currentZoneIndex ) - 1 ; // Make sure the upper zone takes up all the slack. if ( i == numBNEntities - 1 ) { upperZoneIndex = zoneWorld.getNumZones() - 1 ; } IndexedZone zone = new IndexedZone( lowerZoneIndex, upperZoneIndex ) ; float lower = zoneWorld.getZoneLower( zone ) ; float upper = zoneWorld.getZoneUpper( zone ) ; ArrayList subordinateEntities = new ArrayList() ; /* * Space the CPY entities evenly within the zone. */ for (int j=0;j<numCPYEntitiesPerBN;j++) { UnitEntity entity = ws.addUnit( (j + 0.5 ) * ( upper - lower ) / numCPYEntitiesPerBN + lower , 0, "CPY" + cpyCount++ ) ; subordinateEntities.add( entity.getId() ) ; subentities[j] = entity.getId() ; allCPYUnits.add( entity.getId() ) ; } // Create the aggregated BN units. BNAggregate bnAggregate = new BNAggregate( id, subentities) ; bnAggregate.setCurrentZone( zone ); zoneWorld.addAggUnitEntity( bnAggregate ); allBNUnits.add( id ) ; manueverPlanners[i] = new ManueverPlanner( id, subordinateEntities ) ; manueverPlanners[i].setDeltaValues( numTimeDeltasPerTask, numIncrementsPerPlan ); replanFrequency = ( searchDepth * numTimeDeltasPerTask * 3 ) / 4 ; // Max Depth * numDeltas = search depth in delta Ts. manueverPlanners[i].setMaxDepth( searchDepth ); manueverPlanners[i].setMaxBranchFactor( maxBranchFactor ); } // Initialize the zone planner. zonePlanner = new ZonePlanner( allBNUnits, zoneWorld, numTimeDeltasPerZoneSchedule ) ; zonePlanner.setMaxDepth( zoneSearchDepth ); zonePlanner.setMaxBranchFactor( zoneBranchFactor ); // Count of supply units. int k = 0 ; float index = 0 ; // Count of CPY units to be assigned as customers int l = 0 ; float numCPYUnitsPerOrganization = ( float ) allCPYUnits.size() / ( float ) numSupplyOrganizations ; supplyCustomers = new ArrayList[ numSupplyOrganizations ] ; supplyVehicles = new ArrayList[ numSupplyOrganizations ] ; targetGeneratorModel = new TargetGeneratorModel(ws, 0xcafebabe, 4, 0.5f) ; for (int j=0;j<numSupplyOrganizations;j++) { supplyCustomers[j] = new ArrayList() ; supplyVehicles[j] = new ArrayList() ; for (int i=0;i<numSupplyUnitsPerOrg;i++) { SupplyVehicleEntity se = ws.addSupplyVehicle( (k + 0.5) * ws.getBoardWidth()/( numSupplyUnitsPerOrg * numSupplyOrganizations ), ws.getRecoveryLine(), "Supply" + (k+1) ) ; k++ ; allSupplyEntities.add( se.getId() ) ; supplyVehicles[j].add( se.getId() ) ; } index += numCPYUnitsPerOrganization ; // Assign the first while ( l < index && l < allCPYUnits.size() ) { supplyCustomers[j].add( allCPYUnits.get(l) ) ; l++ ; } } } public void configureZoneTestScenario() { doZonePlanning = false ; allBNUnits.clear(); allCPYUnits.clear(); ws = new ReferenceWorldState( boardWidth, boardHeight, penaltyHeight, recoveryHeight, deltaT ) ; zoneWorld = new ZoneWorld( ws, zoneGridSize ) ; manueverPlanners = new ManueverPlanner[ 1 ] ; double averageZoneSize = ( ws.getUpperX() / ( numBNEntities * zoneGridSize ) ) ; double currentZoneIndex = averageZoneSize ; int lowerZoneIndex = (int ) Math.floor( currentZoneIndex ) ; currentZoneIndex += averageZoneSize ; int upperZoneIndex = (int ) Math.floor( currentZoneIndex ) - 1 ; IndexedZone zone = new IndexedZone( lowerZoneIndex, upperZoneIndex ) ; float lower = zoneWorld.getZoneLower( zone ) - 3 ; float upper = zoneWorld.getZoneUpper( zone ) + 3 ; /* * Space the CPY entities evenly within the zone. */ ArrayList subordinateEntities = new ArrayList() ; String[] subentities = new String[numCPYEntitiesPerBN] ; int cpyCount = 4 ; for (int j=0;j<numCPYEntitiesPerBN;j++) { UnitEntity entity = ws.addUnit( (j + 0.5 ) * ( upper - lower ) / numCPYEntitiesPerBN + lower , 0, "CPY" + cpyCount++ ) ; subordinateEntities.add( entity.getId() ) ; subentities[j] = entity.getId() ; allCPYUnits.add( entity.getId() ) ; } manueverPlanners[0] = new ManueverPlanner( "BN2", subordinateEntities ) ; manueverPlanners[0].setDeltaValues( numTimeDeltasPerTask, numIncrementsPerPlan ); replanFrequency = ( searchDepth * numTimeDeltasPerTask * 3 ) / 4 ; // Max Depth * numDeltas = search depth in delta Ts. manueverPlanners[0].setMaxDepth( searchDepth ); manueverPlanners[0].setMaxBranchFactor( maxBranchFactor ); BNAggregate bnAggregate = new BNAggregate( "BN2", subentities) ; bnAggregate.setCurrentZone( zone ); zoneWorld.addAggUnitEntity( bnAggregate ); // // Make a plan and convert it to // ArrayList zoneTasks = new ArrayList() ; ZoneTask t1 = new ZoneTask( 0, numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS(), zone, new IndexedZone( zone.getStartIndex() + 1, zone.getEndIndex() - 1 ) ) ; zoneTasks.add( t1 ) ; ZoneTask t2 = new ZoneTask( numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS(), 2 * numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS(), new IndexedZone( zone.getStartIndex() + 1, zone.getEndIndex() - 1 ), new IndexedZone( zone.getStartIndex() + 2, zone.getEndIndex() - 2 ) ) ; zoneTasks.add( t2 ) ; ZoneTask t3 = new ZoneTask( numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 2, numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 3 , new IndexedZone( zone.getStartIndex() + 2, zone.getEndIndex() - 2 ), new IndexedZone( zone.getStartIndex() + 2, zone.getEndIndex() - 2 ) ) ; zoneTasks.add( t3 ) ; ZoneTask t4 = new ZoneTask( numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 3, numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 4 , new IndexedZone( zone.getStartIndex() + 2, zone.getEndIndex() - 2 ), new IndexedZone( zone.getStartIndex() + 1, zone.getEndIndex() - 1 ) ) ; zoneTasks.add( t4 ) ; ZoneTask t5 = new ZoneTask( numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 4, numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 5 , new IndexedZone( zone.getStartIndex() + 1, zone.getEndIndex() - 1 ), new IndexedZone( zone.getStartIndex() + 2, zone.getEndIndex() ) ) ; zoneTasks.add( t5 ) ; ZoneTask t6 = new ZoneTask( numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 5, numTimeDeltasPerZoneSchedule * ws.getDeltaTInMS() * 6 , new IndexedZone( zone.getStartIndex() + 2, zone.getEndIndex() ), new IndexedZone( zone.getStartIndex() + 3, zone.getEndIndex() + 1) ) ; zoneTasks.add( t6 ) ; Plan zonePlan = new Plan( zoneTasks ) ; bnAggregate.setZonePlan( zonePlan ); Plan intervalPlan = WorldStateUtils.convertIndexPlanToIntervalPlan( zoneWorld, zonePlan ) ; manueverPlanners[0].setZonePlan( intervalPlan ); // Add a supplier for this one entity. supplyCustomers = new ArrayList[1] ; supplyCustomers[0] = new ArrayList() ; supplyCustomers[0].addAll( allCPYUnits ) ; supplyVehicles = new ArrayList[1] ; supplyVehicles[0] = new ArrayList( ) ; int numTestSupplyVehicles = 6 ; for (int i=0;i<numTestSupplyVehicles;i++) { SupplyVehicleEntity se = ws.addSupplyVehicle( (i + 0.5) * ws.getBoardWidth()/( numTestSupplyVehicles ), ws.getRecoveryLine(), "Supply" + (i+1) ) ; supplyVehicles[0].add( se.getId() ) ; } } public void setBoardParameters( float width, float height, float penaltyHeight, float recoveryHeight ) { this.boardWidth = width ; this.boardHeight = height ; this.penaltyHeight = penaltyHeight ; this.recoveryHeight = recoveryHeight ; } public void printState() { System.out.println("\n---------------------------------------\nWORLD CONFIGURATION "); System.out.println("BoardWidth=" + ws.getBoardWidth() ); System.out.println("BoardHeight=" + ws.getBoardHeight() ); System.out.println("RecoveryHeight=" + ws.getRecoveryLine() ); System.out.println("DeltaT=" + ws.getDeltaT() + " secs." ); System.out.println("PenaltyHeight=" + ws.getPenaltyHeight() ); System.out.println("Replan Frequency=" + replanFrequency ); System.out.println("Search depth=" + searchDepth ); System.out.println("Branch Factor=" + maxBranchFactor ); System.out.println("----------------------------------------"); } public boolean isDebugDumpPlanNodes() { return debugDumpPlanNodes; } public void setDebugDumpPlanNodes(boolean debugDumpPlanNodes ) { this.debugDumpPlanNodes = debugDumpPlanNodes; if ( !debugDumpPlanNodes ) { if ( writer != null ) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } writer = null ; planDebugPrintWriter = null ; } } public File getDebugPlanFile() { return debugPlanFile; } public void setDebugPlanFile(File debugPlanFile) { this.debugPlanFile = debugPlanFile; if ( isDebugDumpPlanNodes() ) { try { writer = new FileWriter( debugPlanFile ) ; planDebugPrintWriter = new PrintWriter( writer ) ; } catch (IOException e) { e.printStackTrace(); } } } public ZoneWorld getZoneWorld() { return zoneWorld; } public int getNumTimeDeltasPerTask() { return numTimeDeltasPerTask; } public int getSearchDepth() { return searchDepth; } public void setSearchDepth(int searchDepth) { this.searchDepth = searchDepth; } public int getMaxBranchFactor() { return maxBranchFactor; } public void setMaxBranchFactor(int maxBranchFactor) { this.maxBranchFactor = maxBranchFactor; } public int getReplanFrequency() { return replanFrequency; } public void setReplanFrequency(int replanFrequency) { this.replanFrequency = replanFrequency; } public boolean isVerbose() { return verbose; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public void planZones() { WorldState longRangeSensedWorld = null ; // Copy over the results from the ws before invoking the zone planner. synchronized ( ws ) { longRangeSensedWorld = ws.filter( WorldStateModel.SENSOR_LONG, false, false, null ) ; zoneWorld.copyUnitAndTargetStatus( longRangeSensedWorld, true, false, false ); } System.out.println("ZONE PLANNER: Planning with (delayed) start time " + ( zoneWorld.getTimeInSeconds() + zonePlannerDelay/1000.0 ) + " and horizon=" + zonePlanner.getMaxDepth() * zonePlanner.getDeltaTPerPhase() * zoneWorld.getDeltaT() + " sec."); zonePlanner.plan( zoneWorld, zonePlannerDelay); Object[][] zplans = zonePlanner.getPlans( false ) ; updateZonePlans( zplans ) ; // Get the converted plans and distribute them to the manuever planners. // These use Interval elements rather than IndexedZone elements within the zone Plans. This is because the manuever planner does // not understand intervals yet. zplans = zonePlanner.getPlans( true ) ; for (int i = 0; i < zplans.length; i++) { Object[] zplan = zplans[i]; System.out.println("\tZONE PLAN for " + zplan[0] + "=" + zplan[1]); for (int j = 0; j < manueverPlanners.length; j++) { ManueverPlanner manueverPlanner = manueverPlanners[j]; if ( manueverPlanner.getId().equals( zplan[0] ) ) { manueverPlanner.setZonePlan( ( Plan) zplan[1] ) ; break ; } } } zonePlanner.release(); } public void planAndDistribute() { if ( doZonePlanning ) { planZones(); } System.out.println("\nCREATING MANUEVER PLAN..."); // // Initialize the manuever planners with the initial assumed zone. The initial assumed zone must // be extracted from the reference zone world. for (int i = 0; i < manueverPlanners.length; i++) { ManueverPlanner manueverPlanner = manueverPlanners[i]; BNAggregate agg = (BNAggregate) zoneWorld.getAggUnitEntity( manueverPlanner.getId() ) ; manueverPlanner.setInitialZone( zoneWorld.getIntervalForZone( ( IndexedZone )agg.getCurrentZone() ) ) ; } // Plan with a fixed delay, e.g. assume we execute the current plans into the future and then // plan from there. If ws already has active manuever plans, use those. for (int i=0;i<manueverPlanners.length;i++) { ManueverPlanner planner = this.manueverPlanners[i] ; System.out.println("\nPLANNING for " + planner.getId() + " with initial zone " + planner.getInitialZone() ); // planner.getSearchStrategy().setZoneSchedule( plan ); long startTime = System.currentTimeMillis() ; planner.plan( ws, ASSUMED_BN_PLANNING_DELAY ); if ( isDebugDumpPlanNodes() ) { planDebugPrintWriter.println( "\n\n------------------------------------\nNodes for " + planner.getId() ); planner.dump( planDebugPrintWriter ); planDebugPrintWriter.flush(); } Object[][] plans = planner.getPlans() ; planner.release() ; System.out.println("SIMULATOR:: ELAPSED PLANNING TIME = " + ( System.currentTimeMillis() - startTime ) * VGWorldConstants.SECONDS_PER_MILLISECOND ); updateManueverPlans(plans); } System.out.println("\nCREATING SUSTAINMENT PLAN FOR TIME ..." + ws.getTime() + ", DELAY=" + ( ASSUMED_BN_PLANNING_DELAY + ASSUMED_SUPPLY_PLANNING_DELAY ) ); // Now make a sustainment plan for each organization. for (int i=0;i<supplyCustomers.length;i++) { SPlanner sp = new SPlanner() ; sp.plan( ws, ASSUMED_BN_PLANNING_DELAY + ASSUMED_SUPPLY_PLANNING_DELAY, supplyCustomers[i], supplyVehicles[i] ) ; HashMap splans = sp.getPlans() ; System.out.println("SIMULATOR:: Updating supply plans at time " + ws.getTime() ); updateSustainmentPlans(splans); } } // private void distributeZonePlans(Object[][] zplans) // { // for (int i = 0; i < zplans.length; i++) // { // Object[] zplan = zplans[i]; // ManueverPlanner mp = manueverPlanners[i] ; // mp.getSearchStrategy().setZoneSchedule( ( Plan) zplan[1] ); // } // } public ReferenceWorldState getWorldState() { return ws ; } public boolean isRunning() { return isRunning; } public ManueverPlanner[] getPlanners( ) { return manueverPlanners ; } private void updateZonePlans(Object[][] zplans) { for (int i = 0; i < zplans.length; i++) { Object[] zplan = zplans[i]; String id = (String) zplan[0] ; Plan plan = (Plan) zplan[1] ; BNAggregate agg = (BNAggregate) zoneWorld.getAggUnitEntity( id ) ; agg.setZonePlan( plan ); } } private void updateSustainmentPlans(HashMap splans) { ArrayList sortedSPlans = new ArrayList() ; for (Iterator iterator = splans.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); sortedSPlans.add( new Object[] { entry.getKey(), entry.getValue() } ) ; } Collections.sort( sortedSPlans, new Comparator() { public int compare(Object o1, Object o2) { Object[] p1 = (Object[]) o1, p2 = (Object[]) o2 ; return ( ( String ) p1[0]).compareTo( ( String ) p2[0] ) ; } }); for (int i = 0; i < sortedSPlans.size(); i++) { Object[] objects = (Object[])sortedSPlans.get(i); SupplyVehicleEntity sentity = (SupplyVehicleEntity) ws.getEntity( ( String ) objects[0] ) ; if ( verbose ) { System.out.println("UPDATING " + sentity.getId() ); System.out.println("OLD PLAN " + sentity.getSupplyPlan() ) ; System.out.println("NEW PLAN " + objects[1] ); } sentity.updateSupplyPlan( (Plan) objects[1] ); if ( verbose ) { System.out.println("MERGED PLAN " + sentity.getSupplyPlan() ); } } } private void updateManueverPlans(Object[][] plans) { // Sort these guys for printing out. ArrayList sortedPlans = new ArrayList() ; for (int i = 0; i < plans.length; i++) { Object[] plan = plans[i]; sortedPlans.add( plan ) ; } Collections.sort( sortedPlans, new Comparator() { public int compare(Object o1, Object o2) { Object[] p1 = (Object[]) o1, p2 = (Object[]) o2 ; return ( ( String ) p1[0]).compareTo( ( String ) p2[0] ) ; } }); if ( verbose ) { System.out.println("SIMULATOR:: Manuever plans at time " + ws.getTime() ); } for (int i=0;i<sortedPlans.size();i++) { Object[] pair = (Object[]) sortedPlans.get(i) ; EntityInfo info = ws.getEntityInfo( ( String ) ( pair[0]) ) ; Plan p = (Plan) pair[1] ; UnitEntity entity = (UnitEntity) info.getEntity() ; if ( verbose ) { System.out.println("NEW PLAN for " + entity.getId() + "=" + p ); } entity.updateManeuverPlan( p ); if ( verbose ) { System.out.println("MERGED PLAN for " + entity.getId() + "=" + entity.getManueverPlan() ); } } } protected void doPopulateTargets() { if ( ws == null ) { return ; } // Populate the board with targets WorldStateModel temp = new WorldStateModel( ws, false, false, false ) ; for (int i=0;i<numInitialTargetGenerationDeltas;i++) { targetGeneratorModel.execute( temp ); temp.updateWorldState(); } // Now, copy back into the ws. Iterator iter = temp.getTargets() ; while (iter.hasNext()) { TargetEntity entity = (TargetEntity) iter.next(); ws.addEntity( entity ); } // Now, reset back to the beginning. targetGeneratorModel.resetTime( ws.getTime() ); } protected void generateNewTargets() { // Generate any new targets if ( targetGeneratorModel != null ) { targetGeneratorModel.execute(); } } public long getTotalPlanningTime() { return totalPlanningTime; } public int getPlanningCycles() { return planningCycles; } public void pause() { isRunning = false ; } public void run() { isRunning = true ; System.out.println("Running simulation for a total of " + ( ( maxDeltaTs * ws.getDeltaT() ) ) + " seconds."); runThread.interrupt(); // while ( deltaIndex < maxDeltaTs && isRunning ) { // step(); // } } public void stop() { isRunning = false ; } private void init() { isInited = true ; // for (int i=0;i<numInitialTargets;i++) { // placeTarget(); // } } public void step() { if ( !isInited ) { init(); isInited = true ; } long st = System.currentTimeMillis() ; if ( deltaIndex % replanFrequency == 0 ) { System.out.println("PLANNING..."); long startTime = System.currentTimeMillis() ; planAndDistribute(); long endTime = System.currentTimeMillis() ; System.out.println("Planning time " + ( endTime - startTime ) / 1000 + " secs." ); totalPlanningTime += ( endTime - startTime ) ; planningCycles ++ ; // ws.dump() ; } System.out.println("Simulating..."); System.out.println("Iteration " + deltaIndex + ", time=" + ws.getTime() ); // Generate new targets. synchronized ( ws ) { generateNewTargets(); ws.updateWorldState() ; // Project what zone we are currently in. updateZoneWorld( ws, zoneWorld ) ; } if ( verbose ) { System.out.println( "End state =" + ws.toString() ) ; } // Increment the count. deltaIndex ++ ; // Regulate time if we are running. if ( timeAdvanceRate > 0 && isRunning ) { long et = System.currentTimeMillis() ; // Slow down the simulation to the time advance rate. long delayTime = (long) ( ws.getDeltaT() * VGWorldConstants.MILLISECONDS_PER_SECOND / timeAdvanceRate ) ; if ( ( et - st ) < delayTime ) { try { Thread.sleep( delayTime - ( et - st ) ); } catch (InterruptedException e) { e.printStackTrace(); } } } display.repaint(); } private void updateZoneWorld(WorldState ws, ZoneWorld zw) { long time = ws.getTime() ; for (int i=0;i<zw.getNumAggUnitEntities();i++) { BNAggregate agg = (BNAggregate) zw.getAggUnitEntity( i ) ; Plan zp = agg.getZonePlan() ; ZoneTask t = (ZoneTask) zp.getNearestTaskForTime( time ) ; if ( time >= t.getStartTime() && time <= t.getEndTime() ) { agg.setCurrentZone( ( IndexedZone ) t.getEndZone() ); } else if ( time < t.getStartTime() ) { agg.setCurrentZone( ( IndexedZone ) t.getStartZone() ); } else if ( time > t.getEndTime() ) { agg.setCurrentZone( ( IndexedZone ) t.getEndZone() ); } zw.copyUnitAndTargetStatus( ws, true, true, false ); } } public int getMaxDeltaTs() { return maxDeltaTs; } public void setMaxDeltaTs(int maxDeltaTs) { this.maxDeltaTs = maxDeltaTs; } public double getTimeAdvanceRate() { return timeAdvanceRate; } public void setTimeAdvanceRate(double timeAdvanceRate) { this.timeAdvanceRate = timeAdvanceRate; } public VGFrame getDisplay() { return display; } public void setDisplay(VGFrame display) { this.display = display; } protected class RunThread extends Thread { public void run() { while ( true ) { while ( !isRunning() ) { try { sleep( 5000 ); } catch (InterruptedException e) { } } if ( isRunning ) { if ( deltaIndex < maxDeltaTs ) { step(); } else { break ; } } } System.out.println("CPESimulator:: Run terminated at " + ws.getTime() ); } } public static final void main( String[] args) { CPESimulator simulator = new CPESimulator() ; VGFrame frame = new VGFrame( simulator.getWorldState(), simulator ) ; simulator.setDisplay( frame ); frame.setVisible( true ); } /** * Replan frequency in delta Ts. */ int replanFrequency = 6 ; int numInitialTargets = 3 ; double timeAdvanceRate = 4.0 ; /** * Arrival rate. */ double targetPopupProb = 0.075 ; Random targetGenerator = new Random(0) ; ReferenceWorldState ws ; ManueverPlanner[] manueverPlanners ; /** * An array of lists of supply customers. */ ArrayList[] supplyCustomers ; ZonePlanner zonePlanner ; VGFrame display ; RunThread runThread = new RunThread() ; }
Python
UTF-8
1,721
3.28125
3
[]
no_license
import unittest from classes import State class StateTest(unittest.TestCase): def test_access(self): s = State() s.field = 3 self.assertEqual(s.field, 3) def test_nested_access(self): s = State() s.field = State() s.field.subfield = 3 self.assertEqual(s.field.subfield, 3) def test_field_creation(self): s = State() s.field s.field.subfield = 3 self.assertEqual(s.field.subfield, 3) def test_nested_field_creation(self): s = State() s.field.subfield s.field.subfield.value = 3 self.assertEqual(s.field.subfield.value, 3) def test_zero(self): s = State() self.assertFalse(s) def test_nonzero(self): s = State() s.field = 3 self.assertTrue(s) def test_not_contains(self): s = State() self.assertFalse('field' in s) def test_contains(self): s = State() s.field = 3 self.assertTrue('field' in s) def test_to_from_empty(self): d = {} self.assertEqual(d, dict(State.from_dict(d))) def test_to_from_singleton(self): d = {'a': 1} self.assertEqual(d, dict(State.from_dict(d))) def test_to_from_many(self): d = dict(enumerate('hello world what a beautiful day'.split())) self.assertEqual(d, dict(State.from_dict(d))) def test_to_from_lists(self): d = dict(enumerate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) self.assertEqual(d, dict(State.from_dict(d))) def test_to_from_nested(self): d = {'a': {'b': -1784}, 'c': {'d': 51397, 'e': {'f': 42}}} self.assertEqual(d, dict(State.from_dict(d)))
Python
UTF-8
134
3.90625
4
[]
no_license
#Accept an integer as input. Find the quotient when 3^{35} is divided by x and print the output. x=int(input()) y=(3**35) print(y//x)
C#
UTF-8
2,431
2.921875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security; namespace CryptoExchange.Net { public static class ExtensionMethods { public static void AddParameter(this Dictionary<string, object> parameters, string key, string value) { parameters.Add(key, value); } public static void AddParameter(this Dictionary<string, object> parameters, string key, object value) { parameters.Add(key, value); } public static void AddOptionalParameter(this Dictionary<string, object> parameters, string key, object value) { if(value != null) parameters.Add(key, value); } public static void AddOptionalParameter(this Dictionary<string, string> parameters, string key, string value) { if (value != null) parameters.Add(key, value); } public static string CreateParamString(this Dictionary<string, object> parameters) { var uriString = "?"; var arraysParameters = parameters.Where(p => p.Value.GetType().IsArray).ToList(); foreach (var arrayEntry in arraysParameters) { uriString += $"{string.Join("&", ((object[])arrayEntry.Value).Select(v => $"{arrayEntry.Key}[]={v}"))}&"; } uriString += $"{string.Join("&", parameters.Where(p => !p.Value.GetType().IsArray).Select(s => $"{s.Key}={s.Value}"))}"; uriString = uriString.TrimEnd('&'); return uriString; } public static string GetString(this SecureString source) { lock (source) { string result; int length = source.Length; IntPtr pointer = IntPtr.Zero; char[] chars = new char[length]; try { pointer = Marshal.SecureStringToBSTR(source); Marshal.Copy(pointer, chars, 0, length); result = string.Join("", chars); } finally { if (pointer != IntPtr.Zero) { Marshal.ZeroFreeBSTR(pointer); } } return result; } } } }
C#
UTF-8
329
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameOfDice { class Dice { public int value; public void rollDice() { Random rnd = new Random(); this.value = rnd.Next(1, 6); } } }
Java
UTF-8
1,517
3.96875
4
[]
no_license
class Collar { } class Dog { Collar c; // instance var String name; // instance var public Dog(String name) { this.name = name; } public static void main(String [] args) { Dog d; // local var: d d = new Dog("Lassie"); d.go(d); } void go(Dog dog) // local var: dog { c = new Collar(); dog.setName("Tyson"); } void setName(String dogName) // local var: dogName { name = dogName; // do more stuff } @Override public String toString() { return name; } } /* line 7 - main() is placed on the stack line 9 - reference variable d is created on the stack, but there's no Dog object yet. line 10 - A new Dog object is created and is assigned to the d reference variable. line 11 - a copy of the reference variable d is passed to the go() method. line 13 - the go() method is placed on the stack, with the dog parameter as a local variable line 14 - a new Collar object is created on the heap and assigned to the Dog's instance variable. line 17 - setName() is added to the stack, with the dogName parameter as it's local variable. line 18 - the name instance variable now also refers to the String object. notice that two different local variables refer to the same Dog object. notice that one local variable and one instance variable both refer to the same String Aiko. After line 19 completes, setName() completes and is removed from the stack. at this point the local variable dogName dispppears, too, although the String object it referred to iis still on the heap. */
Java
UTF-8
388
1.773438
2
[]
no_license
package th.go.excise.ims.ia.vo; public class Int0804HeaderTable { private String gfDepositCode; private String area; public String getGfDepositCode() { return gfDepositCode; } public void setGfDepositCode(String gfDepositCode) { this.gfDepositCode = gfDepositCode; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } }
Java
ISO-8859-1
8,533
2.453125
2
[]
no_license
package Pacman.game; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Date; import Pacman.creatures.Ghost; import Pacman.creatures.Player; import Pacman.gui.Display; import Pacman.level.Level; import Pacman.stats.StatNames; import Pacman.stats.Stats; import Pacman.steuerung.Steuerung; import Pacman.tiles.Tile; public class Game implements Runnable { private boolean running = false; private boolean levelIsPlayed = false; private boolean playing = false; private boolean paused = false; private boolean escapePressed = false; private int width, height; private Display display; private int levelIndex; private ArrayList<String> allLevel; private Canvas canvas; private BufferStrategy bs; private Graphics g; private Level level; private GameInformationPanel gi; private int outtime = 50; private Player player; private Date modeTime; private int score, lifeCount; // score und anzahl der verbleibenden leben private Stats stats; private Long playedTime = 0L; private Date playedTimeStart; public Game(Display display, int levelIndex, ArrayList<String> allLevel) { this.display = display; this.levelIndex = levelIndex; this.allLevel = allLevel; this.stats = display.getStats(); gi = new GameInformationPanel(); lifeCount = 3; score = 0; } @Override // Gameloop public void run() { init(); canvas.requestFocus(); while (levelIsPlayed) { renderCountdown(); playedTimeStart = new Date(); while (running) { Date start = new Date(); // Messung if (modeTime == null) modeTime = new Date(); if (!paused) { tick(); render(); checkCollision(); } if ((new Date().getTime() - modeTime.getTime()) >= 15000 && !paused) { modeTime = null; level.changeModes(); } Date end = new Date(); long delta = end.getTime() - start.getTime(); try { if((outtime - delta) >= 0) Thread.sleep(outtime - delta); else Thread.sleep(outtime); } catch (InterruptedException e) { } } Date playedTimeEnd = new Date(); playedTime += (playedTimeEnd.getTime()-playedTimeStart.getTime()); if(levelIsPlayed) onLifeLost(); } // Level hrt auf Tod oder abgeschlossen if(playing) levelOver(); } private void init() { // score = 0; initGhostPaths(); width = display.getWidth(); height = display.getHeight(); display.getFrame().getContentPane().removeAll(); display.getFrame().getContentPane().setBackground(null); display.getFrame().setLayout(new BorderLayout()); canvas = new Canvas(); Dimension dim = new Dimension(width, height); canvas.setPreferredSize(dim); canvas.setMaximumSize(dim); canvas.setMinimumSize(dim); // canvas.setFocusable(false); canvas.addKeyListener(new Steuerung(level.getPlayer(), this)); display.getFrame().add(gi, BorderLayout.NORTH); display.getFrame().add(canvas); display.getFrame().pack(); display.getFrame().repaint(); display.getFrame().revalidate(); render(); } private void initGhostPaths() { for (Ghost g : level.getGhosts()) { g.updateFields(); } } public synchronized void start() { if(!playing) playing = true; if (levelIsPlayed == false) levelIsPlayed = true; new Thread(this).start(); } public synchronized void stop() { if(playedTimeStart != null){ Date playedTimeEnd = new Date(); playedTime += (playedTimeEnd.getTime() - playedTimeStart.getTime()); stats.add(StatNames.PLAYED_TIME, playedTime); } if(playing) playing = false; if (levelIsPlayed == true) { running = false; levelIsPlayed = false; } else return; try { new Thread(this).join(); } catch (InterruptedException e) {} } public void tick() { level.tick(); gi.getScoreLabel().setText("Score: " + (score + level.getLevelScore())); if (level.getLevelScore() >= level.getFullWayCount()) if ((player.getRenderX() % Tile.TILEWIDTH == 0) && (player.getRenderY() % Tile.TILEHEIGHT == 0)) { running = false; levelIsPlayed = false; } } public void render() { bs = canvas.getBufferStrategy(); if (bs == null) { canvas.createBufferStrategy(3); bs = canvas.getBufferStrategy(); } g = bs.getDrawGraphics(); g.clearRect(0, 0, width, height); // Draw // Bei 600x 600 : xMax = 550, yMax = 575 // Tile.tileTextures[0].render(g, 0, 0); // Muss Level rendern, Player, 3 Ghosts level.render(g); bs.show(); g.dispose(); } private void renderCountdown() { for (int number = 3; number > 0; number--) { if (!levelIsPlayed) return; renderNumber(number); } if (levelIsPlayed) running = true; } private void renderNumber(int number) { render(); Graphics g = canvas.getGraphics(); g.setColor(Color.RED); switch (number) { case 3: g.fillRect(9 * Tile.TILEWIDTH, 7 * Tile.TILEHEIGHT, 7 * Tile.TILEWIDTH, Tile.TILEHEIGHT); g.fillRect(10 * Tile.TILEWIDTH, 11 * Tile.TILEHEIGHT, 6 * Tile.TILEWIDTH, Tile.TILEHEIGHT); g.fillRect(9 * Tile.TILEWIDTH, 15 * Tile.TILEHEIGHT, 7 * Tile.TILEWIDTH, Tile.TILEHEIGHT); g.fillRect(15 * Tile.TILEWIDTH, 7 * Tile.TILEHEIGHT, Tile.TILEWIDTH, 9 * Tile.TILEHEIGHT); break; case 2: g.fillRect(9 * Tile.TILEWIDTH, 7 * Tile.TILEHEIGHT, 7 * Tile.TILEWIDTH, Tile.TILEHEIGHT); g.fillRect(15 * Tile.TILEWIDTH, 8 * Tile.TILEHEIGHT, Tile.TILEWIDTH, 3 * Tile.TILEHEIGHT); g.fillRect(9 * Tile.TILEWIDTH, 11 * Tile.TILEHEIGHT, 7 * Tile.TILEWIDTH, Tile.TILEHEIGHT); g.fillRect(9 * Tile.TILEWIDTH, 12 * Tile.TILEHEIGHT, Tile.TILEWIDTH, 3 * Tile.TILEHEIGHT); g.fillRect(9 * Tile.TILEWIDTH, 15 * Tile.TILEHEIGHT, 7 * Tile.TILEWIDTH, Tile.TILEHEIGHT); break; case 1: g.fillRect(15 * Tile.TILEWIDTH, 7 * Tile.TILEHEIGHT, Tile.TILEWIDTH, 9 * Tile.TILEHEIGHT); break; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } private void onLifeLost() { modeTime = null; level.resetSpawns(); try { Thread.sleep(1500); } catch (InterruptedException e) { } if (levelIsPlayed) render(); } public void setLevel(Level level) { this.level = level; this.player = level.getPlayer(); this.level.setStats(stats); } public Level getLevel() { return level; } public void setPaused(boolean paused) { this.paused = paused; } public boolean isPaused() { return paused; } public Display getDisplay() { return display; } public Date getModeTime() { return modeTime; } public void setModeTime(Date modeTime) { this.modeTime = modeTime; } private void loseLife() { if (lifeCount != 0) gi.getLifes()[lifeCount - 1].setIcon(null); lifeCount--; stats.add(StatNames.DEATHS, new Long(1)); } public boolean isRunning() { return running; } private void checkCollision() { Player p = level.getPlayer(); Ghost[] ghosts = level.getGhosts(); for (Ghost g : ghosts) { if (p.getHitbox().intersects(g.getHitbox())) { loseLife(); running = false; if (lifeCount < 0) levelIsPlayed = false; } } } public void manipulateOuttime(int dif) { if ((outtime + dif) < 55 && (outtime + dif) > 15) outtime += dif; } private void levelOver(){ stats.add(StatNames.PLAYED_TIME, playedTime); if(lifeCount == -1){ score += level.getLevelScore(); new GameOverThread(this, level).run(); }else{ score += level.getLevelScore(); stats.add(StatNames.LEVEL_FINISHED, new Long(1)); do{ if(++levelIndex == allLevel.size()) levelIndex = 0; level = new Level(allLevel.get(levelIndex)); level.setStats(stats); }while(!level.isValidToPlay()); try {Thread.sleep(1000);} catch (InterruptedException e) {} start(); } } public int getScore(){ return score; } public boolean escapeHasBeenPressed(){ return escapePressed; } public void setEscapePressed(boolean ep){ escapePressed = ep; } public boolean levelIsPlayed(){ return levelIsPlayed; } }
JavaScript
UTF-8
3,707
2.78125
3
[ "MIT" ]
permissive
"use strict" const Zet = require('./zet') // Zet.profile({ // scope : exports // }); var ZetTestClass = Zet.declare({ // superclass : null, defineBody: function (self) { // Constructor Function self.construct = function construct(id) { self.id = id } } }) var ZetTestClass2 = Zet.declare({ superclass: null, CLASS_ID: "ZetTestClass2_OVERRIDE", defineBody: function (self) { // Constructor Function self.construct = function construct(id) { self.myId = id } self.getSomething = function () { return "ZetTestClass returns something" } } }) var ZetTestClass3 = Zet.declare({ superclass: ZetTestClass2, defineBody: function (self) { self.getUnique = function () { return "ZetTestClass3 returns unique" } } }) describe('ZetTests', () => { it('testIsInstance', () => { let x = ZetTestClass(1) let y = ZetTestClass2(2) let z = ZetTestClass3(3) expect(ZetTestClass.isInstance(x)).to.be.true expect(ZetTestClass.isInstance(y)).to.be.false expect(ZetTestClass.isInstance(z)).to.be.false expect(ZetTestClass.isInstance(1)).to.be.false expect(x.isInstance(x)).to.be.true expect(x.isInstance(y)).to.be.false expect(x.isInstance(1)).to.be.false // Check Y (Class 2) expect(ZetTestClass2.isInstance(x)).to.be.false expect(ZetTestClass2.isInstance(y)).to.be.true expect(ZetTestClass2.isInstance(z)).to.be.true expect(ZetTestClass2.isInstance(1)).to.be.false expect(y.isInstance(x)).to.be.false expect(y.isInstance(y)).to.be.true expect(y.isInstance(z)).to.be.true expect(y.isInstance(1)).to.be.false // Check Z (Class 3) expect(ZetTestClass3.isInstance(x)).to.be.false expect(ZetTestClass3.isInstance(y)).to.be.false expect(ZetTestClass3.isInstance(z)).to.be.true expect(ZetTestClass3.isInstance(1)).to.be.false expect(z.isInstance(x)).to.be.false expect(z.isInstance(y)).to.be.false expect(z.isInstance(z)).to.be.true expect(z.isInstance(1)).to.be.false }) it("testInstanceOf", () => { let x = ZetTestClass(1), y = ZetTestClass2(2), z = ZetTestClass3(3) expect(x.instanceOf(ZetTestClass)).to.be.true expect(x.instanceOf(ZetTestClass2)).to.be.false expect(x.instanceOf(ZetTestClass3)).to.be.false expect(y.instanceOf(ZetTestClass)).to.be.false expect(y.instanceOf(ZetTestClass2)).to.be.true expect(y.instanceOf(ZetTestClass3)).to.be.false expect(z.instanceOf(ZetTestClass)).to.be.false expect(z.instanceOf(ZetTestClass2)).to.be.true expect(z.instanceOf(ZetTestClass3)).to.be.true }) it('testCLASS_ID', () => { let x = ZetTestClass(1), y = ZetTestClass2(2), z = ZetTestClass3(3) expect(x.CLASS_ID === null).to.be.true expect(ZetTestClass.CLASS_ID === null).to.be.true expect(y.CLASS_ID === 'ZetTestClass2_OVERRIDE').to.be.true expect(ZetTestClass2.CLASS_ID === 'ZetTestClass2_OVERRIDE').to.be.true expect(z.CLASS_ID === null).to.be.true expect(ZetTestClass3.CLASS_ID === null).to.be.true }) it('testOverridden functions', () => { let a = ZetTestClass3() expect(a.getUnique).to.be.ok expect(a.getSomething).to.be.ok expect(a.getUnique()==="ZetTestClass3 returns unique").to.be.true; expect(a.getSomething()==="ZetTestClass returns something").to.be.true; }) })
Java
UTF-8
834
2.46875
2
[ "Apache-2.0" ]
permissive
package org.adligo.xml_io.shared.schema; public class AnyMutant implements I_Any { private String minOccurs; private String maxOccurs; public AnyMutant() { } public AnyMutant(I_Any other) { minOccurs = other.getMinOccurs(); maxOccurs = other.getMaxOccurs(); } /* (non-Javadoc) * @see org.adligo.xml_io.client.schema.I_Any#getMinOccurs() */ @Override public String getMinOccurs() { return minOccurs; } public void setMinOccurs(String minOccurs) { this.minOccurs = minOccurs; } /* (non-Javadoc) * @see org.adligo.xml_io.client.schema.I_Any#getMaxOccurs() */ @Override public String getMaxOccurs() { return maxOccurs; } public void setMaxOccurs(String maxOccurs) { this.maxOccurs = maxOccurs; } @Override public SequenceChildTypes getNodeType() { return SequenceChildTypes.ANY; } }
Python
UTF-8
538
3.375
3
[]
no_license
import sys import calendar def main(year): cal = calendar.Calendar(year) cal.mark_days(1, [13,21]) cal.mark_days(2, [1,28]) cal.mark_days(4, [21], '\u263a') cal.mark_days(10, [31], 'H') cal.set_month(1) cal.display_calendar() cal.set_month(2) cal.display_calendar() cal.set_month(4) cal.display_calendar() cal.set_month(10) cal.display_calendar() if __name__ == "__main__": if len(sys.argv) > 1: year = int(sys.argv[1]) else: year = 2018 main(year)
Java
UTF-8
904
3.453125
3
[ "Apache-2.0" ]
permissive
package ru.job4j.array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /**. * class for selection sort array (Bubble sort) * @author * @version $Id$ * @since 0.1 */ public class BubbleSortTest { /**. * test {1, 2, 3, 4, 5} to {5, 4, 3, 2, 1} */ @Test public void whenOddOfElementsThen() { BubbleSort t = new BubbleSort(); int[] m = new int[] {5, 1, 2, 7, 3}; int[] r = t.sort(m); int[] expected = new int[] {1, 2, 3, 5, 7}; assertThat(r, is(expected)); } /**. * test {2, 1, 4, 3} to {1, 2, 3, 4} */ @Test public void whenEvenOfElementsThen() { BubbleSort t = new BubbleSort(); int[] m = new int[] {2, 1, 4, 3}; int[] r = t.sort(m); int[] expected = new int[] {1, 2, 3, 4}; assertThat(r, is(expected)); } }
Java
UTF-8
4,101
1.742188
2
[]
no_license
package poly.entity; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class PHONG { @Id private int ID_PHONG; @ManyToOne @JoinColumn(name = "ID_LP") private LOAI_PHONG loai_phong; private String TEN_PHONG; private String ANH; private String GIOI_THIEU; private int SLPHONG; private int SLNGUOI; private Float GIA_PHONG; private String MOTA_1; private String MOTA_2; private String MOTA_3; private String MOTA_4; private String MOTA_5; private String MOTA_6; private String MOTA_7; private String TIENICH_1; private String TIENICH_2; private String TIENICH_3; private String TIENICH_4; private String TIENICH_5; private String TIENICH_6; private String TIENICH_7; private String TIENICH_8; private String TIENICH_9; private String TIENICH_10; private int STATUS; public int getID_PHONG() { return ID_PHONG; } public void setID_PHONG(int iD_PHONG) { ID_PHONG = iD_PHONG; } public LOAI_PHONG getLoai_phong() { return loai_phong; } public void setLoai_phong(LOAI_PHONG loai_phong) { this.loai_phong = loai_phong; } public String getTEN_PHONG() { return TEN_PHONG; } public void setTEN_PHONG(String tEN_PHONG) { TEN_PHONG = tEN_PHONG; } public String getANH() { return ANH; } public void setANH(String aNH) { ANH = aNH; } public String getGIOI_THIEU() { return GIOI_THIEU; } public void setGIOI_THIEU(String gIOI_THIEU) { GIOI_THIEU = gIOI_THIEU; } public int getSLPHONG() { return SLPHONG; } public void setSLPHONG(int sLPHONG) { SLPHONG = sLPHONG; } public int getSLNGUOI() { return SLNGUOI; } public void setSLNGUOI(int sLNGUOI) { SLNGUOI = sLNGUOI; } public Float getGIA_PHONG() { return GIA_PHONG; } public void setGIA_PHONG(Float gIA_PHONG) { GIA_PHONG = gIA_PHONG; } public String getMOTA_1() { return MOTA_1; } public void setMOTA_1(String mOTA_1) { MOTA_1 = mOTA_1; } public String getMOTA_2() { return MOTA_2; } public void setMOTA_2(String mOTA_2) { MOTA_2 = mOTA_2; } public String getMOTA_3() { return MOTA_3; } public void setMOTA_3(String mOTA_3) { MOTA_3 = mOTA_3; } public String getMOTA_4() { return MOTA_4; } public void setMOTA_4(String mOTA_4) { MOTA_4 = mOTA_4; } public String getMOTA_5() { return MOTA_5; } public void setMOTA_5(String mOTA_5) { MOTA_5 = mOTA_5; } public String getMOTA_6() { return MOTA_6; } public void setMOTA_6(String mOTA_6) { MOTA_6 = mOTA_6; } public String getMOTA_7() { return MOTA_7; } public void setMOTA_7(String mOTA_7) { MOTA_7 = mOTA_7; } public String getTIENICH_1() { return TIENICH_1; } public void setTIENICH_1(String tIENICH_1) { TIENICH_1 = tIENICH_1; } public String getTIENICH_2() { return TIENICH_2; } public void setTIENICH_2(String tIENICH_2) { TIENICH_2 = tIENICH_2; } public String getTIENICH_3() { return TIENICH_3; } public void setTIENICH_3(String tIENICH_3) { TIENICH_3 = tIENICH_3; } public String getTIENICH_4() { return TIENICH_4; } public void setTIENICH_4(String tIENICH_4) { TIENICH_4 = tIENICH_4; } public String getTIENICH_5() { return TIENICH_5; } public void setTIENICH_5(String tIENICH_5) { TIENICH_5 = tIENICH_5; } public String getTIENICH_6() { return TIENICH_6; } public void setTIENICH_6(String tIENICH_6) { TIENICH_6 = tIENICH_6; } public String getTIENICH_7() { return TIENICH_7; } public void setTIENICH_7(String tIENICH_7) { TIENICH_7 = tIENICH_7; } public String getTIENICH_8() { return TIENICH_8; } public void setTIENICH_8(String tIENICH_8) { TIENICH_8 = tIENICH_8; } public String getTIENICH_9() { return TIENICH_9; } public void setTIENICH_9(String tIENICH_9) { TIENICH_9 = tIENICH_9; } public String getTIENICH_10() { return TIENICH_10; } public void setTIENICH_10(String tIENICH_10) { TIENICH_10 = tIENICH_10; } public int getSTATUS() { return STATUS; } public void setSTATUS(int sTATUS) { STATUS = sTATUS; } }
Python
UTF-8
377
3.625
4
[]
no_license
#CREAR UNA FUNCION QUE CALCULE EL PROMEDIO DE NOTAS DE UN ARREGLO. def promedioNotas(arreglo): avg = 0.0 suma = 0.0 for c in range(len(arreglo)): suma = arreglo[c] + suma avg = suma / len(arreglo) return avg notas = [5.5, 6.6, 7, 2.5, 4.5, 5.3, 3.4, 5.8, 7, 1.1, 2.3] res = promedioNotas(notas) print("El promedio de las notas es: ", round(res,2))
C++
UTF-8
888
3.3125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; void swap(int &x, int &y) { int tmp = x; x = y; y = tmp; } void backtracking(vector<int>& nums, vector<vector<int> > &ans, int k, int n) { if (k == n) { ans.push_back(nums); return; } for (int i = k; i < n; i++) { swap(nums[k], nums[i]); backtracking(nums, ans, k + 1, n); swap(nums[k], nums[i]); } } vector<vector<int> > permute(vector<int>& nums) { vector<vector<int> > ans; backtracking(nums, ans, 0, nums.size()); return ans; } int main() { vector<int> nums; for (int i = 1; i <= 3; i++) nums.push_back(i); vector<vector<int> > ans = permute(nums); for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) { cout << ans[i][j] < " "; } cout << endl; } }
C
UTF-8
373
3.796875
4
[]
no_license
#include <stdio.h> int main() { int n, o, rem, r= 0; printf("Enter a three digit integer: "); scanf("%d", &number); o= n; while (o!= 0) { rem= o%10; r+= rem*rem*rem; o /= 10; } if(r== n) printf("%d is an Armstrong number.",n); else printf("%d is not an Armstrong number.",n); return 0; }
C++
UTF-8
3,661
2.546875
3
[]
no_license
// // main.cpp // cplusplus // // Created by soonhyuk on 2020/01/22. // Copyright © 2020 soonhyuk. All rights reserved. // #include <iostream> #include <set> #include <vector> #include <queue> #include <utility> #include <string.h> #include <algorithm> #include <stdio.h> using namespace std; vector<pair<int,int> > v; vector<pair<int,int> > active; set<int> res; int N,M,remain; int board[50][50]; int temp[50][50]; void dfs(int depth,int num); int main(int argc, const char * argv[]) { remain = 0; scanf("%d %d",&N,&M); for(int r = 0 ; r < N ; r++){ for(int c = 0 ; c < N ; c++) { scanf("%d",&board[r][c]); if (board[r][c] == 0) remain++; else if(board[r][c] == 2) v.push_back(pair<int,int>(r,c)); } } dfs(0,0); if(res.size() == 0 ) printf("-1"); else printf("%d",*(res.begin())); return 0; } void dfs(int depth,int num){ // depth : number of activated virus int r,t = 0,row,col; queue<pair<int,int> > q; if (depth >= M) { // spread virus r = remain; for (int i = 0 ; i < N; i++) { for(int j = 0 ; j < N ; j++) temp[i][j] = board[i][j]; } for (int i = 0; i < active.size(); i++) { q.push(pair<int, int>(active[i].first,active[i].second)); } //printf("\n-------------------------------------\n"); while(!(q.empty()) && r > 0){ //whole loop for(int co = int(q.size())-1 ; co >= 0 ; co--){ row = q.front().first; col = q.front().second; q.pop(); temp[row][col] = 3; if (row + 1 < N && (temp[row+1][col] == 0 || temp[row+1][col] == 2)) { // down if(temp[row+1][col] == 0) r--; temp[row+1][col] = 3; q.push(pair<int, int>(row+1,col)); } if (row - 1 >= 0 && (temp[row-1][col] == 0 || temp[row-1][col] == 2)) { // up if(temp[row-1][col] == 0) r--; temp[row-1][col] = 3; q.push(pair<int, int>(row-1,col)); } if (col + 1 < N && (temp[row][col+1] == 0 || temp[row][col+1] == 2)) { // right if(temp[row][col+1] == 0) r--; temp[row][col+1] = 3; q.push(pair<int, int>(row,col+1)); } if (col - 1 >= 0 && (temp[row][col-1] == 0 || temp[row][col-1] == 2)) { // left if(temp[row][col-1] == 0) r--; temp[row][col-1] = 3; q.push(pair<int, int>(row,col-1)); } } /* printf("\n"); for(int a = 0 ; a < N ; a ++){ for(int b= 0; b < N ; b++) printf("%d ",temp[a][b]); printf("\n"); }*/ t++; } if (r == 0) { res.insert(t); } } else { //combination for(int i = num; i < v.size() ; i++){ if (depth < active.size()) { //already exist active[depth] = pair<int,int>(v[i].first,v[i].second); } else{ // depth >= active size active.push_back(pair<int,int>(v[i].first,v[i].second)); } dfs(depth+1,i+1); } } return; }
Java
UTF-8
1,604
2.359375
2
[]
no_license
package com.github.valentin.fedoskin.fb2me.desktop; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.util.Callback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.valentin.fedoskin.fb2me.desktop.shell.ShellView; public final class NavigationUtil { private static final Logger LOGGER = LoggerFactory.getLogger(NavigationUtil.class); public static void assignPresenter(final ApplicationContext context, final Place place, final Callback<Object, Void> receiver) { Task<Object> task = new Task<Object>() { @Override protected Object call() { LOGGER.debug(place.getPresenterType() + " : start creation"); return place.getPresenter(); } }; task.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { LOGGER.debug(place.getPresenterType() + " : end creation"); receiver.call(e.getSource().getValue()); context.getView(ShellView.class).getProgressProperty().unbind(); context.getView(ShellView.class).getProgressProperty().setValue(1); } }); context.getView(ShellView.class).getProgressProperty().unbind(); context.getView(ShellView.class).getProgressProperty().bind(task.progressProperty()); new Thread(task).start(); } private NavigationUtil() { } }
Markdown
UTF-8
602
3
3
[ "MIT" ]
permissive
# db-truncate db-truncate truncates MySql database tables to specified number of rows. It's useful for developing purposes when you want to reduce database size and preserve its structure. ### Installation db-truncate requires PHP >= 5.3 ``` composer global require idealogica/db-truncate:~1.0.0 ``` ### Usage ``` db-truncate [-u username (root)] [-p password] [-h host (localhost)] [-P port] [-S unix socket] [-e comma-separated tables to exclude (changelog)] database [records to keep (500)] ``` ### License db-truncate is licensed under a [MIT License](https://opensource.org/licenses/MIT).
Java
UTF-8
1,817
3.046875
3
[]
no_license
package shapes; import java.util.LinkedList; import impl.Calc; import impl.CalcTuple; import impl.MyMaterial; import impl.MyPoint3D; import impl.MyRay; public class MySphere implements MyShape{ private LinkedList<MyPoint3D> keyPoints; // sphere center private MyMaterial material; // material private float radius; // radius public MySphere(MyPoint3D position, float radius, MyMaterial material) { super(); LinkedList<MyPoint3D> points = new LinkedList<MyPoint3D>(); points.add(position); this.keyPoints = points; this.radius = radius; this.material = material; } @Override public CalcTuple rayIntersect(MyRay ray) { float boundingSquare = radius*radius; MyPoint3D origin = ray.getOrigin().sub(keyPoints.getFirst()); float a, b, c; a = ray.getDirection().dotProduct(ray.getDirection()); b = 2*(origin.dotProduct(ray.getDirection())); c = origin.dotProduct(origin)-boundingSquare; // solve quad. equation CalcTuple tup = Calc.CalcQuadRoot(a, b, c); // return closest intersection point (if any) if(tup.getRoots() > 0) { if(tup.getIntersectionA() >= 0) tup.setClosestIntersection(tup.getIntersectionA()); else tup.setClosestIntersection(tup.getIntersectionB()); return tup; } else { tup.setClosestIntersection(-1); return tup; } } @Override public MyPoint3D getNormal(MyPoint3D point) { return point.sub(keyPoints.getFirst()).div(radius); } public double getRadius() { return radius; } @Override public MyMaterial getMaterial() { return material; } @Override public LinkedList<MyPoint3D> getKeyPoints() { return keyPoints; } @Override public void setMaterial(MyMaterial material) { this.material = material; } @Override public void setKeyPoints(LinkedList<MyPoint3D> keyPoints) { this.keyPoints = keyPoints; } }
Markdown
UTF-8
1,049
2.859375
3
[]
no_license
# Frontend Mentor - 3-column preview card component solution This is a solution to the [3-column preview card component challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/3column-preview-card-component-pH92eAR2-). Frontend Mentor challenges help you improve your coding skills by building realistic projects. ## Table of contents - [Overview](#overview) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [Author](#author) ## Overview ### Screenshots ![Desktop Screenshot](./images/ss_desktop.png) ![Mobile Screenshot](./images/ss_mobile.png) ### Links -[Solution URL](https://github.com/iftkhr/column-preview-card) -[Live Site URL](https://iftkhr.github.io/column-preview-card) ## My process ### Built with - Semantic HTML5 markup - CSS custom properties - CSS Grid - Mobile-first workflow ## Author - Website - [Iftakhar Kaunain Ashhar](https://iftkhr.github.io/) - Frontend Mentor - [@iftkhr](https://www.frontendmentor.io/profile/iftkhr)
Java
UTF-8
353
3.8125
4
[]
no_license
package com.dsa.recursion; public class FibonacciSeries { public static void main(String[] args) { System.out.println(printFibonacciNumber(6)); // 0 1 1 2 3 5 8 13 21 34 } private static int printFibonacciNumber(int i) { if (i <= 1) { return i; } return printFibonacciNumber(i - 1) + printFibonacciNumber(i - 2); } }
Ruby
UTF-8
469
2.796875
3
[ "MIT" ]
permissive
module OptionsManager def require_options(options, required_params) missing_args = [] required_params.each do |param| missing_args << param.to_s if options[param].nil? end raise ArgumentError, "Missing required argument: #{missing_args.join(',')}" unless missing_args.empty? end def validate_option_in_list(option, list) raise ArgumentError, "Option: #{option} should be one of #{list.inspect}" unless list.include?(option) end end
C++
UTF-8
3,180
2.6875
3
[]
no_license
#include "TriangularObstacleModel.h" #include "../../../../../common/definitionlevels/DefinitionLevel3.h" #include "../../../../../common/Definition.h" #include "../../../../../utils/physics/CustomPhysicsBody.h" const int TriangularObstacleModel::MOVE_VERTICAL = 0; const int TriangularObstacleModel::MOVE_HORIZONTAL = 1; TriangularObstacleModel::TriangularObstacleModel(cocos2d::Scene* scene, int move) : CoreModel(TRIANGULAR_NAME_PATH) { mMoveType = move; Init(); scene->addChild(mCoreSprite); } TriangularObstacleModel::TriangularObstacleModel(cocos2d::Node* node, int move) : CoreModel(TRIANGULAR_NAME_PATH) { mMoveType = move; Init(); node->addChild(mCoreSprite); } TriangularObstacleModel::~TriangularObstacleModel() { // Destructor } void TriangularObstacleModel::Init() { mCoreSprite = cocos2d::Sprite::create(mModelName); mCoreSprite->setTag(OBSTACLES_TAG); // Create physics CustomPhysicsBody::getInstance()->parseJsonFile(TRIANGULAR_PHYSICS_JSON); mCorePhysicsBody = CustomPhysicsBody::getInstance()->bodyFormJson(mCoreSprite, TRIANGULAR_PHYSICS_NAME, cocos2d::PhysicsMaterial(1, 1, 0)); if (mCorePhysicsBody != nullptr) { mCorePhysicsBody->setDynamic(false); mCorePhysicsBody->setCollisionBitmask(OBSTACLES_COLLISION_BITMASK); mCorePhysicsBody->setContactTestBitmask(true); mCoreSprite->addComponent(mCorePhysicsBody); } // create local vatialbe mIsGoAhead = true; mIsMoveToRight = true; mIsRotateHasFinish = true; mCountStep = 0; if (mMoveType == MOVE_HORIZONTAL) { mCoreSprite->setRotation(90); } } void TriangularObstacleModel::Update() { // Move vertical if (mMoveType == MOVE_VERTICAL) { // Move triangular if (mIsGoAhead) { mCoreSprite->setPositionY(GetPositionY() + 1); mCountStep += 1; } else { mCoreSprite->setPositionY(GetPositionY() - 1); mCountStep -= 1; } // Check triangular move to ahead if (mCountStep >= GetContentSize().height / 2) { mIsGoAhead = false; } else if (mCountStep <= -GetContentSize().height / 2) { mIsGoAhead = true; } } // Move horizontal else if (mMoveType == MOVE_HORIZONTAL) { // Rotate triangular RotateTriangularObstacle(); // Move triangular if (mIsMoveToRight) { mCoreSprite->setPositionX(mCoreSprite->getPositionX() + 1); } else { mCoreSprite->setPositionX(mCoreSprite->getPositionX() - 1); } // Check move triangular if (GetPositionX() <= mCoreSprite->getContentSize().width / 2) { mIsMoveToRight = true; } else if (GetPositionX() >= (cocos2d::Director::getInstance()->getVisibleSize().width) - (mCoreSprite->getContentSize().width / 2)) { mIsMoveToRight = false; } } } void TriangularObstacleModel::RotateTriangularObstacle() { mCoreSprite->setRotation(mCoreSprite->getRotation() + 2); }
Java
UTF-8
863
2.984375
3
[]
no_license
import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import java.util.Objects; @AllArgsConstructor @Setter @Getter public class Match implements Comparable<Match> { private long size; private String name; public int compareTo(Match o) { if (this.getSize() == o.getSize()) { return 0; } else if (this.getSize() > o.getSize()) { return 1; } else return -1; } @Override public String toString() { return "Size=" + this.getSize() + " bytes and the name of file: '" + this.getName() + '\''; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Match match = (Match) o; return Objects.equals(name, match.name); } }
C#
UTF-8
2,402
3.921875
4
[]
no_license
using System; using System.IO; using System.Collections.Generic; namespace AlgorithmPrograms { class Program { static void Main(string[] args) { Console.WriteLine("Welcome To Algorithm Programs!"); Console.WriteLine("\nEnter 1-to Calculate Permutation of a string using Recursion Method\nEnter 2-to Calculate Permutation of a string using Iterative Method\nEnter 3-Binary Search Word from a file\nEnter 4-InsertionSort\nEnter 5-BubbleSort\nEnter 6- Anagram check\nEnter 7-PrimeNumbers in range\nEnter 8-Prime numbers that are Palindrome and Anagram"); int ch = Convert.ToInt32(Console.ReadLine()); switch (ch) { case 1: Console.WriteLine("Enter a string to calculate Permutation"); string str = Console.ReadLine(); int n = str.Length; Console.WriteLine("Permutation through Recursion Method"); Permutations.RecursivePermutation(str, 0, n - 1); break; case 2: Console.WriteLine("\nPermutation through Iteration Method"); string str1 = Console.ReadLine(); int n1 = str1.Length; Permutations.IterativePermutation(str1, n1); break; case 3: Console.WriteLine("\nBinary Search word from a file"); string filePath = File.ReadAllText(@"C:\Users\charan kanduri\source\repos\AlgorithmPrograms_BridgeLabz\AlgorithmPrograms\SampleTextFile.txt"); List<string> wordList = new List<string>(filePath.Split(" ")); wordList.Sort(); BinarySearchWord.BinarySearch(wordList); break; case 4: List<int> arr = InsertionSort.ArrayInput(); InsertionSort.InsertionSorting(arr); break; case 5: List<int> arr1 = BubbleSort.ArrayInput(); BubbleSort.BubbleSorting(arr1); break; case 6: AnagramCheck.Anagram(); break; case 7: PrimeNumbersInRange.PrimeNumbers(); break; } } } }
Java
UTF-8
97
1.6875
2
[]
no_license
package org.hcj.spring.Work.Automation; public interface IStudent4 { public void read4(); }
Python
UTF-8
695
2.65625
3
[ "MIT" ]
permissive
__author__ = 'Guorong Xu<g1xu@ucsd.edu>' import os import sys import subprocess from multiprocessing import Pool def upload_file(input_file): print input_file s3_location = "" subprocess.call(["aws", "s3", "cp", input_file, s3_location]) if __name__ == '__main__': work_dir = sys.argv[1] file_extension = sys.argv[2] file_list = [] for dirpath, directories, filenames in os.walk(work_dir): for filename in filenames: if filename.endswith(file_extension): input_file = os.path.join(dirpath, filename) file_list.append(input_file) pool = Pool(4) pool.map(upload_file, file_list) pool.close() pool.join()
Python
UTF-8
766
3.03125
3
[]
no_license
# https://codeforces.com/contest/722/problem/A #coding: utf-8 time_format1 = raw_input() time_format2 = raw_input().split(":") aux = "" if (time_format1 == "12"): if(int(time_format2[0]) > 12): if(time_format2[0][1] == "0"): aux += "1" else: aux += "0" aux += time_format2[0][1] elif(int(time_format2[0]) < 1): aux += "0" aux += "1" else: aux += time_format2[0] aux += ":" if(int(time_format2[1]) > 59): aux += "0" aux += time_format2[1][1] else: aux += time_format2[1] else: if(int(time_format2[0]) > 23): aux += "0" aux += time_format2[0][1] else: aux += time_format2[0] aux += ":" if(int(time_format2[1]) > 59): aux += "0" aux += time_format2[1][1] else: aux += time_format2[1] print aux
C++
UTF-8
2,654
2.609375
3
[]
no_license
/* * Security.h */ #ifndef SECURITY_H_ #define SECURITY_H_ #include "CommandClass.h" #include "Mutex.h" #include "AES.h" namespace OpenZWave { class ValueBool; class Msg; /** \brief Implements COMMAND_CLASS_SECURITY (0x98), a Z-Wave device command class. */ class Security: public CommandClass { public: static CommandClass* Create( uint32 const _homeId, uint8 const _nodeId ){ return new Security( _homeId, _nodeId ); } virtual ~Security() {} static uint8 const StaticGetCommandClassId(){ return 0x98; } static string const StaticGetCommandClassName(){ return "COMMAND_CLASS_SECURITY"; } // From CommandClass virtual uint8 const GetCommandClassId()const{ return StaticGetCommandClassId(); } virtual string const GetCommandClassName()const{ return StaticGetCommandClassName(); } virtual bool RequestState ( uint32 const _requestFlags, uint8 const _instance, Driver::MsgQueue const _queue ); virtual bool GetScheme (uint32 const _requestFlags, uint8 const _dummy1, uint8 const _instance, Driver::MsgQueue const _queue); virtual bool HandleMsg( uint8 const* _data, uint32 const _length, uint32 const _instance ); // virtual bool SupportedGet(Driver::MsgQueue const _queue); virtual bool EncryptMessage ( uint8 const* _nonce ); virtual bool DecryptMessage ( uint8 const* _data, uint32 const _length ); virtual void SendMsg ( Msg* _msg ); struct SecurityPayload {uint32 m_length; uint32 m_part; uint8 * m_data; } payload, payload1, payload2; virtual void QueuePayload ( SecurityPayload const& _payload ); virtual void RequestNonce (); virtual void SendNonceReport (); protected: virtual void GenerateAuthentication (uint8 const* _data, uint32 const _length, uint8 const _sendingNode, uint8 const _receivingNode, char* _authentication, char const * m_initializationVector); virtual bool GetSenderNonce(int id){return senderNonce;} ; virtual void GenerateNonce( uint8* _nonce); private: Security( uint32 const _homeId, uint8 const _nodeId ): CommandClass( _homeId, _nodeId ){} uint8 Network_Key[16]; uint8 Encrypt_Key[16]; uint8 Auth_Key[16]; uint32 m_w,m_z; uint8 senderNonce[8]; uint32 nonceExpiredTime; // We should clean the publicNonceId and publicNonce when this time is expired. Mutex* m_queueMutex; std::vector <SecurityPayload> m_queue; }; } #endif /* SECURITY_H_ */
C++
UTF-8
1,442
2.75
3
[ "MIT" ]
permissive
#ifndef __STRUCTUREAGENT_H__ #define __STRUCTUREAGENT_H__ #include "../MainAgents/BaseAgent.h" using namespace BWAPI; using namespace std; /** The StructureAgent is the base agent class for all agents handling buildings. If a building is created and no * specific agent for that type is found, the building is assigned to a StructureAgent. StructureAgents are typically * agents without logic, for example supply depots. To add logic to a building, for example Terran Academy researching * stim packs, an agent implementation for that unit type must be created. * * Author: Johan Hagelback (johan.hagelback@gmail.com) */ class StructureAgent : public BaseAgent { private: protected: bool repairing; bool canBuildUnit(UnitType type); bool canEvolveUnit(UnitType type); vector<TilePosition> hasScanned; /** Checks if the specified unit/building can be constructed */ bool canBuild(UnitType type); public: StructureAgent(); StructureAgent(Unit mUnit); virtual ~StructureAgent(); /** Called each update to issue orders. */ virtual void computeActions(); /** Used in debug modes to show a line to the agents' goal. */ virtual void debug_showGoal(); /** Checks if the agent can morph into the specified type. Zerg only. */ bool canMorphInto(UnitType type); /** Sends a number of workers to a newly constructed base. */ void sendWorkers(); /** Used to print info about this agent to the screen. */ virtual void printInfo(); }; #endif
JavaScript
UTF-8
4,669
2.796875
3
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
'use strict'; (function(){ $(document).ready(function(){ tableau.extensions.initializeAsync({'configure': configure}).then(function(){ const dashboard=tableau.extensions.dashboardContent.dashboard; var selectedValues=[]; try{ dashboard.getParametersAsync().then(function(parameters){ // Create checkbox with each option from the parameter values parameters.find(p=>p.parameterImpl.name=='Dimension 1').allowableValues.allowableValues.forEach(function(field){ try { if(!(field.formattedValue=='Seleccione una dimensión')){ var checkbox = document.createElement('input'); checkbox.type='checkbox'; checkbox.name=field.value; // Each checkbox holds the string value to be selected checkbox.value=field.formattedValue; checkbox.id='cb'+field.value; checkbox.className='css-checkbox'; checkbox.addEventListener('change', (event)=>{ if(event.target.checked){ selectedValues.push(checkbox.name); }else if(!event.target.checked){ selectedValues.splice(selectedValues.indexOf(checkbox.name), 1); }else{ checkbox.checked=false; } }) var label = document.createElement('label'); label.className='css-label' label.htmlFor='cb'+field.value; label.appendChild(document.createTextNode(field.formattedValue)); var container=document.getElementById('Dimensiones'); container.appendChild(checkbox); container.appendChild(label); container.appendChild(document.createElement('br')); } } catch (error) { document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Oops!'+error))); } }) //Botón de aplicar para seleccionar más de una dimensión y luego proceder. var button = document.createElement('button'); button.className='button'; button.textContent='Aplicar'; button.addEventListener('click', (event)=>{ dashboard.getParametersAsync().then(function(parameters){ let selectedString=''; selectedValues.forEach(function(val){ selectedString+=val +'|'; }); //Eliminate the last | for formatting selectedString.slice(0,-1); parameters.find(p=>p.name==='Dimensiones Seleccionadas').changeValueAsync(selectedString); }) }) var container=document.getElementById('Dimensiones'); container.appendChild(document.createElement('br')); container.appendChild(button); }) }catch(e){ document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Oops!'+e))); } }); }); function configure() { const defaultPayload=1; const popupUrl = `${window.location.origin}/MyExtensions/DimAsCb/Setup.html`; tableau.extensions.ui.displayDialogAsync(popupUrl, defaultPayload, { height: 500, width: 500 }).then((closePayload) => { // This is executed when the dialog is succesfully closed console.log(closePayload); }).catch((error) => { //In case they just click the X to close. switch (error.errorCode) { case tableau.ErrorCodes.DialogClosedByUser: console.log('Dialog was closed by user'); break; default: console.error(error.message); } }); } })();
Java
UTF-8
1,591
3.6875
4
[]
no_license
package exams.n0; import java.util.Arrays; public class N88 { public static void main(String[] args) { int[] nums1 = new int[]{3,5,7,9, 0, 0, 0, 0, 0, 0,0,0}; int[] nums2 = new int[]{2,4,6,8,10,12,14}; new N88().merge(nums1, 4, nums2, 7); System.out.println(Arrays.toString(nums1)); int[] nums = {45,23,11,89,77,98,4,28,65,43}; new N88().mergeSort(nums, new int[nums.length], 0, nums.length-1); System.out.println(Arrays.toString(nums)); } /* * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ public void merge(int[] nums1, int m, int[] nums2, int n) { int i=m-1; int j=n-1; while(i>=0 && j>=0) { if(nums1[i] >= nums2[j]) { nums1[i+j+1] = nums1[i]; i--; } else { nums1[i+j+1] = nums2[j]; j--; } } while(j>=0) { nums1[j] = nums2[j]; j--; } } public void mergeSort(int[] nums, int[] tmp, int s, int e) { int mid = (s+e)/2; if(s<mid) { mergeSort(nums, tmp, s, mid); } if(mid+1 < e) { mergeSort(nums, tmp, mid+1, e); } for(int i=s; i<=e; i++) { tmp[i] = nums[i]; } int i=s; int j=mid+1; int k=s; while(i<=mid && j<=e) { if(tmp[i]<=tmp[j]) { nums[k++]=tmp[i++]; } else { nums[k++]=tmp[j++]; } } while(i<=mid) { nums[k++]=tmp[i++]; } while(j<=e) { nums[k++]=tmp[j++]; } } }
C++
UTF-8
1,416
2.625
3
[ "BSD-2-Clause" ]
permissive
/////////////////////////////////////////////////////////// // Registration.h // Implementation of the Class Registration // Created on: 13-Apr-2020 2:51:39 PM // Original author: svanausdall /////////////////////////////////////////////////////////// #if !defined(EA_5144F149_491F_42ae_8A59_8CBC9AE58D6A__INCLUDED_) #define EA_5144F149_491F_42ae_8A59_8CBC9AE58D6A__INCLUDED_ #include "TimeType.h" #include "PINType.h" #include "UInt32.h" #include "Resource.h" /** * Registration represents an authorization to access the resources on a host. */ class Registration : public Resource { public: Registration(); virtual ~Registration(); /** * Contains the time at which this registration was created, by which clients MAY * prioritize information providers with the most recent registrations, when no * additional direction from the consumer is available. */ TimeType dateTimeRegistered; /** * Contains the registration PIN number associated with the device, including the * checksum digit. */ PINType pIN; /** * The default polling rate for this function set (this resource and all resources * below), in seconds. If not specified, a default of 900 seconds (15 minutes) is * used. It is RECOMMENDED a client poll the resources of this function set every * pollRate seconds. */ UInt32 pollRate; }; #endif // !defined(EA_5144F149_491F_42ae_8A59_8CBC9AE58D6A__INCLUDED_)
JavaScript
UTF-8
373
2.984375
3
[]
no_license
window.addEventListener('load',inicializarEventos,false); function inicializarEventos() { var ob1=document.querySelector("#boton1"); ob1.addEventListener('click',presion,false); } function presion(e) { var ob1=document.querySelector(".mensaje"); ob1.style.backgroundColor='#ff0'; var ob2=document.querySelector("#lista1"); ob2.style.backgroundColor='#0ff'; }
C++
UTF-8
3,051
3.3125
3
[]
no_license
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; const long long MIN_VALUE = -100000000; struct SegTree { int vl = 0; int vr = 0; long long data = 0; long long setted = MIN_VALUE; SegTree *left_child = nullptr; SegTree *right_child = nullptr; SegTree(int vl_, int vr_) { vl = vl_; vr = vr_; } void check() { int vm = vl - (vl - vr) / 2; if (left_child == nullptr) { left_child = new SegTree(vl, vm); } if (right_child == nullptr) { right_child = new SegTree(vm + 1, vr); } } SegTree* get(int l, int r) { check(); if (setted != MIN_VALUE) { push(); } int vm = vl - (vl - vr) / 2; if (l == vl && r == vr) { return this; }; if (r <= vm) { return left_child->get(l, r); } else if (l > vm) { return right_child->get(l, r); } else { SegTree *left = left_child->get(l, vm); SegTree *right = right_child->get(vm + 1, r); if (left->data <= right->data) { return left; } else { return right; } } } void set(int l, int r, long long value) { check(); if (setted != MIN_VALUE) { push(); } int vm = vl - (vl - vr) / 2; if (l == vl && r == vr) { data = max(value, data); setted = max(setted, value); return; } if (r <= vm) { left_child->set(l, r, value); } else if (l > vm) { right_child->set(l, r, value); } else { left_child->set(l, vm, value); right_child->set(vm + 1, r, value); } data = min(left_child->data, right_child->data); } void push() { left_child->data = max(left_child->data, setted); right_child->data = max(right_child->data, setted); left_child->setted = max(left_child->setted, setted); right_child->setted = max(right_child->setted, setted); setted = MIN_VALUE; } int getIndex() { if (vl == vr) { return vl; } check(); if (setted != MIN_VALUE) { push(); } if (left_child->data == data) { return left_child->getIndex(); } else { return right_child->getIndex(); } } }; int main() { int n, m; int l, r; string s; cin >> n >> m; auto *root = new SegTree(1, 1000000); for (int i = 0; i < m; i++) { cin >> s >> l >> r; if (s[0] == 'a') { SegTree *res = root->get(l, r); int ans = res->getIndex(); cout << res->data << " " << ans << endl; } if (s[0] == 'd') { long long val; cin >> val; root->set(l, r, val); } } return 0; }
Markdown
UTF-8
2,019
2.5625
3
[ "MIT" ]
permissive
<h2 align="center"> Dog_Breed_Classifier </h2> ![forks](https://img.shields.io/github/forks/ClownMonster/Dog_Breed_Classifier) ![license](https://img.shields.io/github/license/ClownMonster/Dog_Breed_Classifier) ![stars](https://img.shields.io/github/stars/ClownMonster/Dog_Breed_Classifier) <h3>Abstract: </h3> <p>The neural network is the most advanced method at the moment to train the system to do a task. Among them CNN (convolution neural network ) and its derivatives are the most used for training the system to identify and classify images and in computer vision.</p> </br> <h3>Network Used: </h3> <p> Convolution Neural Network (CNN)</p> </br> <h3>Layers in the network : </h3> * cnn.add(Conv2D(filters=128,kernel_size=5,activation='relu',input_shape=[64,64,3])) * cnn.add(MaxPool2D(pool_size=3,strides=1)) * cnn.add(Dropout(0.2)) * cnn.add(BatchNormalization()) * cnn.add(Conv2D(filters=64,kernel_size=3,activation='relu')) * cnn.add(MaxPool2D(pool_size=3,strides=1)) * cnn.add(Dropout(0.2)) * cnn.add(BatchNormalization()) * cnn.add(Conv2D(filters=32,kernel_size=3,activation='relu')) * cnn.add(MaxPool2D(pool_size=3,strides=1)) * cnn.add(Dropout(0.2)) * cnn.add(BatchNormalization()) * cnn.add(Conv2D(filters=32,kernel_size=3,activation='relu')) * cnn.add(MaxPool2D(pool_size=3,strides=1)) * cnn.add(Dropout(0.2)) * cnn.add(BatchNormalization()) * cnn.add(Conv2D(filters=32,kernel_size=3,activation='relu')) * cnn.add(MaxPool2D(pool_size=3,strides=1)) * cnn.add(Dropout(0.2)) * cnn.add(BatchNormalization()) * cnn.add(GlobalAveragePooling2D(data_format='channels_last')) * cnn.add(Dense(units=10,activation='softmax'))</p> </br> <h3>Accurracy Score: </h3> <p>32%. Due to lack of computation power number of epochs had to be set to less, so the accuracy is low.</p> </br> </br> <h3>Dataset : Data set is taken from kaagle </h3> </br> <h3>Contributors : </h3> <h4>Sanjay urs K P , Jyothi B R, Karthik B S, Nayana , Mohan Kumar K</h4> <h3>Licensed To : MIT</h3> <h3>Images : </h3>
Markdown
UTF-8
1,868
2.984375
3
[]
no_license
<h1> Django Based URL Shortener</h1> <p>A Django web based application which takes a url and shortens the given url in from of 7.0.0.1:8000/{Some_Short_Url}. When the short url is generated the user can click on the given short url or can copy anc paste that url in the new tab.</p> <h2>How it works</h2> <p> The url shortener first takes the long url and stores it into the database and assigns it a number. The number is then fed into a base62 conversion algorithm which takes the number and converts it to base62 with base 0-9A-Za-z. The short url which is generated is also stored in the databse. For resolution of short url to the long one we use the base 62 to Decimal algo to convert it back to deciaml number and using that number we query the database to get the long URL. </p> <h2>Issues</h2> No currently known issues. Test cases needs to be formed in future release. <h2>Future Features</h2> <p> The following features are scheduled to be added in the future releases- <ol> <li><strike>Bootsrtapping the whole website. Adding appropriate CSS and JS where neccessary in very future releases</strike> there is a provison for adding React JS.</li> <li>Count, Copy to clipboard and open in new window features to increasing the user experience.</li> <li>Building a REST api. The REST api then can be used on the other site to shorten the URL on the other sites where it is neccessary.</li> <li>Building a Google Chrome extension for the website which could in a click shorten the URL of the page on which user is currently on</li> <li>Publishing the site on the server.</li> </ol> </p> <h2>Version</h2> Shortify- 1.0.1 <h2>Additions</h2> <ol> <li>Added bootstrap and custom css on the website. Added the copy to clipboard functionality on the website to increase the UX</li> </ol> <h2>Contributor</h2> <ul> <li>Anidh Singh</li> <li>Shubhangi Chaturvedi</li> </ul>
Java
UTF-8
3,928
1.984375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2021 ThoughtWorks, 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 cd.go.contrib.plugins.configrepo.groovy.dsl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class BranchContextSerializationTest { @Test void deserialization() throws JsonProcessingException { final String payload = "{" + "\"branch_name\": \"foo\"," + "\"sanitized_branch_name\": \"foo\"," + "\"full_ref_name\": \"refs/heads/foo\"," + "\"title\": \"this is a foo\"," + "\"author\": \"me\"," + "\"reference_url\": \"https://pull/request\"," + "\"labels\": [\"a\", \"b\"]," + "\"repo\": {" + " \"type\": \"git\"," + " \"url\": \"https://gitbud.com/repo.git\"," + " \"branch\": \"foo\"," + " \"username\": \"git\"," + " \"encrypted_password\": \"abcd1234\"," + " \"shallow_clone\": true" + "}" + "}"; final BranchContext c = new ObjectMapper().readValue(payload, BranchContext.class); assertNotNull(c); assertNotNull(c.getRepo()); assertEquals("foo", c.getBranch()); assertEquals("https://gitbud.com/repo.git", ((GitMaterial) c.getRepo()).getUrl()); assertEquals("this is a foo", c.getTitle()); assertEquals("me", c.getAuthor()); assertEquals("https://pull/request", c.getReferenceUrl()); assertEquals(List.of("a", "b"), c.getLabels()); } @Test void deserializationList() throws JsonProcessingException { final String payload = "[{" + "\"branch_name\": \"foo\"," + "\"sanitized_branch_name\": \"foo\"," + "\"full_ref_name\": \"refs/heads/foo\"," + "\"title\": \"this is a foo\"," + "\"author\": \"me\"," + "\"reference_url\": \"https://pull/request\"," + "\"labels\": [\"a\", \"b\"]," + "\"repo\": {" + " \"type\": \"git\"," + " \"url\": \"https://gitbud.com/repo.git\"," + " \"branch\": \"foo\"," + " \"username\": \"git\"," + " \"encrypted_password\": \"abcd1234\"," + " \"shallow_clone\": true" + "}" + "}]"; final List<BranchContext> l = new ObjectMapper().readValue(payload, new TypeReference<>() { }); assertNotNull(l); assertEquals(1, l.size()); final BranchContext c = l.get(0); assertNotNull(c); assertNotNull(c.getRepo()); assertEquals("foo", c.getBranch()); assertEquals("https://gitbud.com/repo.git", ((GitMaterial) c.getRepo()).getUrl()); assertEquals("this is a foo", c.getTitle()); assertEquals("me", c.getAuthor()); assertEquals("https://pull/request", c.getReferenceUrl()); assertEquals(List.of("a", "b"), c.getLabels()); } }
C
UTF-8
544
3.734375
4
[]
no_license
#include <stdio.h> int main(int argc, char** argv) { // This is a signle line comment // It will be ignored by the compiler // Even if there's code after it! // int a = 420; /* This is a block comment * You don't _need_ to format it like this, * but I like it this way because it looks pretty. * This comment too will ignore code! * int b = 22; * float f = 2.54; * printf("a: %d b: %d f: %f\n", a, b, f); */ // The code below will be executed printf("Hello world!\n"); return 0; }
Ruby
UTF-8
1,296
2.90625
3
[ "MIT" ]
permissive
module MdnQuery # An entry of the Mozilla Developer Network documentation. class Entry # @return [String] attr_reader :title, :description, :url # Creates a new entry. # # @param title [String] the title of the entry # @param description [String] a small excerpt of the entry # @param url [String] the URL to the entry on the web # @return [MdnQuery::Entry] def initialize(title, description, url) @title = title @description = description @url = url @content = nil end # Returns the string representation of the entry. # # @return [String] def to_s "#{title}\n#{description}\n#{url}" end # Opens the entry in the default web browser. # # @return [void] def open Launchy.open(@url) end # Returns the content of the entry. # # The content is fetched from the Mozilla Developer Network's documentation. # The fetch occurs only once and subsequent calls return the previously # fetched content. # # @raise [MdnQuery::HttpRequestFailed] if a HTTP request fails # @return [MdnQuery::Document] the content of the entry def content return @content unless @content.nil? @content = MdnQuery::Document.from_url(url) end end end
Java
UTF-8
985
2.109375
2
[]
no_license
package my.rinat.wsserver.boundary; import lombok.RequiredArgsConstructor; import my.rinat.country.gen.GetCountryRequest; import my.rinat.country.gen.GetCountryResponse; import my.rinat.wsserver.domain.country.Countries; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; @Endpoint @RequiredArgsConstructor public class CountryEndpoint { private final Countries countries; @PayloadRoot(namespace = "http://www.rinat.my/country/gen", localPart = "getCountryRequest") @ResponsePayload public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) { GetCountryResponse response = new GetCountryResponse(); response.setCountry(countries.findCountry(request.getName())); return response; } }
Python
UTF-8
384
2.953125
3
[]
no_license
f=open("archivo.txt","w") f.write("32 espacio \n") f.write("33 !\n") f.write("34 '' \n") f.write("35 # \n") f.write("36 $ \n") f.write("37 % \n") f.write("38 & \n") f.write("39 ' \n") f.write("40 ( \n") f.write("41 ) \n") f.write("41 * \n") f.write("43 + \n") f.write("44 , \n") f.close() f=open("archivo.txt","r") content=f.read() print(content) f.close()
C++
UTF-8
3,166
3.609375
4
[]
no_license
#include <iostream> #include <string> class DataMahasiswa { private: std::string nama; char nim[15]; public: void inputData() { std::cout << "\n"; inputNama(); inputNim(); std::cout << "\n"; } void inputNama() { std::cout << "Input Nama Anda : "; getline(std::cin, nama); } std::string getNama() { return nama; } void inputNim() { std::cout << "Input NIM Anda : "; std::cin.getline(nim, 15); } void showResult() { std::cout << "\nNama : " << nama << std::endl; std::cout << "NIM : " << nim << std::endl; } }; const int max_data = 3; DataMahasiswa data_mahasiswa[max_data]; int head = -1; int tail = -1; bool isEmpty(); bool isFull(); void antrianMasuk(); void antrianKeluar(); void showAllDataMasuk(); void clear(); int main() { int command; bool run_app; std::cout << "\n1. Tambah Antrian" << "\n2. Panggil Antrian" << "\n3. Lihat Daftar Yang Sedang Menunggu" << "\n4. Clear Data" << "\n5. Exit \n\n"; while (true) { std::cout << "\nMasukkan Perintah : "; std::cin >> command; std::cin.ignore(); if (command == 5) { std::cout << "\nKeluar Aplikasi"; break; } else if (command == 1) { if (isFull()) { std::cout << "\nAntrian sudah penuh !!!\n"; } else { antrianMasuk(); } } else if (command == 2) { antrianKeluar(); } else if (command == 3) { showAllDataMasuk(); } else if (command == 4) { clear(); } else { std::cout << "\nPerintah yang anda masukkan tidak valid"; break; } } return 0; } bool isEmpty() { if (tail == -1) { return true; } else { return false; } } bool isFull() { if (tail == max_data - 1) { return true; } else { return false; } } void antrianMasuk() { if (isEmpty()) { head = 0; tail = 0; } else { tail++; } data_mahasiswa[tail].inputData(); } void antrianKeluar() { if (isEmpty()) { std::cout << "\nAntrian sudah kosong ! \n"; } else { std::cout << "\nUntuk data ini silahkan masuk ke ruang prodi : \n"; data_mahasiswa[0].showResult(); for (int a = head; a < tail; a++) { data_mahasiswa[a] = data_mahasiswa[a + 1]; } tail--; if (tail == -1) { head = -1; } } } void clear() { std::cout << "\nData berhasil diclear\n"; head = tail = -1; } void showAllDataMasuk() { if (isEmpty()) { std::cout << "\nAntrian kosong ! \n"; } else { for (int a = head; a <= tail; a++) { data_mahasiswa[a].showResult(); } } }
PHP
UTF-8
1,055
3.421875
3
[]
no_license
<?php namespace model; class Boat { private $id; private $type; private $length; private $owner; public function __construct($type, $length, $ownerID, $id = 0){ $this->SetType($type); $this->SetLength($length); $this->SetOwner($ownerID); $this->SetID($id); } public function GetType(){ return $this->type; } public function SetType($type){ if(Type::IsType($type) == false){ throw new \Exception("Type not valid"); } $this->type = $type; } public function GetLength(){ return $this->length; } public function SetLength($length){ //Make compatible for entering 2,14 $this->length = str_replace(',', '.', $length); } public function GetOwner(){ return $this->owner; } public function SetOwner($ownerID){ $this->owner = $ownerID; } public function SetID($id){ $this->id = $id; } public function GetID(){ return $this->id; } }
Markdown
UTF-8
926
2.671875
3
[]
no_license
### Naive Bayes Classifier The file presents Naive Bayes Classifier written by me. The class was testes with data sets taken from website: [Machine Learning Depository](https://archive.ics.uci.edu/ml/datasets.html) The algorithm is good for classification problem with categorital data. Exemplary results: * Balloon data set Train set size 10, Test set size 10, Accuracy 0.8 Train set size 13, Test set size 7, Accuracy 0.571428571429 Train set size 15, Test set size 5, Accuracy 0.8 * Balance data Train set size 312, Test set size 312, Accuracy 0.987179487179 Train set size 416, Test set size 208, Accuracy 0.951923076923 Train set size 468, Test set size 156, Accuracy 0.974358974359 * Car data Train set size 864, Test set size 864, Accuracy 0.709490740741 Train set size 1296, Test set size 432, Accuracy 0.724537037037 Train set size 1382, Test set size 346, Accuracy 0.696531791908
Python
UTF-8
525
3.15625
3
[]
no_license
# -*- coding: utf-8 -*- # 標準入力を取得 N, X, M = list(map(int, input().split())) # 求解処理 def f(x: int, m: int) -> int: return x**2 % m A = [X] s = {X} i = 0 while True: A_next = f(A[-1], M) if A_next in s: i = A.index(A_next) break else: A.append(A_next) s.add(A_next) loop_length = len(A) - i loop_cnt = (N - i) // loop_length loop_res = (N - i) % loop_length ans = sum(A[:i]) + loop_cnt * sum(A[i:]) + sum(A[i: i + loop_res]) # 結果出力 print(ans)
C#
UTF-8
10,539
2.875
3
[]
no_license
using UnityEngine; using System.Collections.Generic; using System.Linq; /// <summary> /// Contains information about a city and its contents. /// Also contains a reference to its neighbors and the /// GameObject that represents it. /// </summary> public class City : Place { // Tracks adjacent cities private List<Neighbor> neighbors { get; set; } // Governor in charge of controlling independent cities public Governor governor { get; set; } // Tracks which units the city can sell public List<TroopClassification> unitsForSale; // This is the maximum amount of money a city will produce per turn public int wealth { get; set; } // This is the percentage of wealth the leader will take from this city per turn. // Taking a larger portion increases the chance that a city will enter a state of revolt. // This should always be between 0 and 1 private float _taxRate; public float taxRate { get => _taxRate; set { _taxRate = Mathf.Clamp(value, 0f, 1f); } } // This is the chance per turn that a city will revolt per turn. // This should always be between 0 and 1. private float _publicUnrest; public float publicUnrest { get => _publicUnrest; set { _publicUnrest = Mathf.Clamp(value, 0f, 1f); } } // Any time a city does something, set this to false. // It will be reset to true at the beginning of each turn. public bool hasAction { get; private set; } // Buildings built in the city. // Each building has a unique effect on the city. // Only a limited number of buildings can be build in any one city at a time. public int buildingLimit { get; set; } public List<Building> buildings { get; set; } public List<Building> buildingsForPurchase { get; set; } /// Called whenever the component is added to an object. void Awake() { neighbors = new List<Neighbor>(); buildings = new List<Building>(); unitsForSale = new List<TroopClassification>(); buildingsForPurchase = new List<Building>() { new Barracks(), new Range(), new Stables() }; occupyingUnits = new List<Unit>(); allegiance = Allegiance.NONE; buildingLimit = 3; publicUnrest = 0f; taxRate = 0f; hasAction = true; } override public void AddOccupyingUnits<T>(List<T> units) { occupyingUnits.AddRange(units); EventManager.instance.fireUnitsChangedEvent(this); /// Handles changing allegiances if friendly units are the only units in the city. if (this.occupyingUnits.Count > 0) { ChangeAllegiance(occupyingUnits[0].allegiance); } } override public void RemoveOccupyingUnits(List<Unit> units) { /// TODO: Is it necessary to destroy the game objects too? List<Unit> revisedUnitsList = new List<Unit>(this.occupyingUnits); foreach (Unit unit in this.occupyingUnits) { if (units.Contains(unit)) { revisedUnitsList.Remove(unit); } } this.occupyingUnits = revisedUnitsList; /// Send an event informing the rest of the game that the units have changed. EventManager.instance.fireUnitsChangedEvent(this); } /// <summary> /// Tracks adjacent cities. /// Pairs a City with an integer representing how many days /// of travel it will take to travel the connecting road. /// </summary> private class Neighbor { public City city; public int travelLength; public Neighbor(City city, int travelLength) { this.city = city; this.travelLength = travelLength; } } /// <summary> /// Adds the taxes owed by the city to the leader's gold reserve. /// Before that, considers if the city should revolt. /// After the taxes are collected, adjusts the public unrest. /// </summary> public void CollectTaxes() { int tax = (int)(wealth * taxRate); /// Independent cities give their taxes directly to the governor /// And don't calculate public unrest or revolt if (this.allegiance != Allegiance.INDEPENDENT && this.allegiance != Allegiance.NONE) { /// Check if the city should revolt float chance = UnityEngine.Random.Range(0f, 1f); if (publicUnrest > chance) { Revolt(); } else { GameManager.instance.allegianceToLeaderMapping[allegiance].gold += tax; } CalculatePublicUnrest(); } else { governor.gold += tax; } } /// <summary> /// Performs calculation logic to figure the amount of public unrest in a city. /// </summary> private void CalculatePublicUnrest() { if (taxRate >= 0f && taxRate <= .1f) { publicUnrest = publicUnrest + CityManagementConstants.TIER_1_UNREST_DIFFERENCE; } else if (taxRate > .1f && taxRate <= .25f) { publicUnrest = publicUnrest + CityManagementConstants.TIER_2_UNREST_DIFFERENCE; } else if (taxRate > .25f && taxRate <= .4f) { publicUnrest = publicUnrest + CityManagementConstants.TIER_3_UNREST_DIFFERENCE; } else if (taxRate > .4f) { publicUnrest = publicUnrest + CityManagementConstants.TIER_4_UNREST_DIFFERENCE; } } /// <summary> /// Consumes the city's per-turn action. /// </summary> public void UseAction() { this.hasAction = false; } /// <summary> /// Resets the city's per-turn action. /// </summary> public void ResetAction() { this.hasAction = true; } /// <summary> /// Performs revolt logic, primarily setting the allegiance to independent. /// Also removes any friendly units in the city and /// will eventually spawn independently aligned units. /// </summary> private void Revolt() { ClearOccupyingUnits(); AddOccupyingUnits(UnitFactory.instance.GenerateTroop(TroopClassification.INFANTRY, Allegiance.INDEPENDENT)); } /// <summary> /// If no road exists between the city and its neighbors, /// creates the road. /// </summary> public void ConnectWithNeighbors() { // Validates the road doesn't exist first foreach(Neighbor neighbor in neighbors) { // If we get here, the road doesn't exist so we should make one and // add it to the MapManager's roads list. Road newRoad = MapManager.instance.TryToCreateRoad(this, neighbor.city, neighbor.travelLength); } } /// <summary> /// Get a list of the roads connected to the city. /// </summary> public List<Road> GetConnectedRoads() { List<Road> roads = new List<Road>(); foreach (Neighbor neighbor in neighbors){ roads.Add(MapManager.instance.GetRoad(this, neighbor.city)); } return roads; } /// <summary> /// Sends a group of units on the road to a neighboring city. /// </summary> public void SendFriendlyUnitsToNeighbor(List<Unit> units, City city) { Road roadToNeighbor = MapManager.instance.GetRoad(this, city); if (units.Count > 0) { if (roadToNeighbor.CanPlace(units[0])) { roadToNeighbor.PutUnitsOnRoad(units, this); /// Removes units from the city if they're being put on the road List<Unit> revisedUnitsList = new List<Unit>(this.occupyingUnits); foreach (Unit unit in this.occupyingUnits) { if (units.Contains(unit)) { revisedUnitsList.Remove(unit); } } this.occupyingUnits = revisedUnitsList; } } } /// <summary> /// Adds a neighbor to the list of neighboring cities. /// Automatically adds this city to the neighboring city's neighbors. /// </summary> public void AddNeighbor(City neighboringCity, int distance) { neighbors.Add(new Neighbor(neighboringCity, distance)); } /// <summary> /// Returns a list of the cities that are connected to this city. /// </summary> public List<City> GetNeighbors() { List<City> neighboringCities = new List<City>(); foreach (Neighbor neighbor in this.neighbors) { neighboringCities.Add(neighbor.city); } return neighboringCities; } /// <summary> /// Changes the city's allegiance to the provided allegiance. /// </summary> public void ChangeAllegiance(Allegiance newAllegiance) { this.allegiance = newAllegiance; EventManager.instance.fireSelectedCityUpdatedEvent(this); } /// <summary> /// Clears the occupied units list. /// </summary> public void ClearOccupyingUnits() { /// TODO: Is it necessary to destroy the game objects too? occupyingUnits.Clear(); EventManager.instance.fireUnitsChangedEvent(this); } /// <summary> /// Returns whether or not a building can be built. /// </summary> public bool CanBuild<T>(T building) where T : Building { /// Can't build past the city's building limit if (this.buildings.Count >= this.buildingLimit) { return false; } /// Can't build two of the same building else if (this.buildings.Contains(building)) { return false; } else { return true; } } /// <summary> /// Adds the building to the list of buildings, if able. /// Applies the building's affect and consumes the city's action. /// </summary> public void AddBuilding<T>(T building) where T : Building { if (CanBuild(building)) { this.buildings.Add(building); building.ApplyEffect(this); this.UseAction(); } } /// <summary> /// Removes the building from the list of buildings, if able. /// Removes the building's affect and consumes the city's action. /// </summary> public void RemoveBuilding<T>(T building) where T : Building { if (this.buildings.Contains(building)) { this.buildings.Add(building); building.RemoveEffect(this); this.UseAction(); } } }
Markdown
UTF-8
3,930
2.84375
3
[ "MIT" ]
permissive
# 설정 파일 만들기 [출처](https://www.wagavulin.jp/entry/2011/11/27/222654 ) ## 조건 있는 컴파일 지정 방법 ``` #include <cstdio> int main(){ #if USE_FEATURE_X printf("use feature-x\n"); #else printf("do not use feature-x\n"); #endif return 0; } ``` 이 코드는 USE_FEATURE_X 값에 의해 컴파일 결과가 달라질 것이지만, 이 값을 결정하는 방법은 2가지가 있다. - 컴파일러 옵션으로 지정 (-DUSE_FEATURE_X = 1) - 소스 코드의 다른 위치에서 정의 (#define USE_FEATURE_X 1을 추가) 컴파일 결과는 같게 되므로 일일이 파일을 편집 할 필요가 없는 컴파일러 옵션을 지정하는 것이 편하다. 그러나 경우에 따라서는 그것이 바람직하지 않은 경우도 있다. 예를 들어, 실행 파일이 아닌 라이브러리(libHoge.so)를 만들고 있다고 하자. 다음과 같은 구성이다. 소스 파일 Hoge.cpp 헤더 파일 Hoge.h 이것은 라이브러리의 사용자에 대한 공개 헤더이기도 하다 그리고 Hoge.h에 다음과 같은 조건 분기가있다. ``` class Hoge { public: Hoge(); ~Hoge(); private: int n; #if USE_FEATURE_X int x; #endif }; ``` 이런 경우 당연히 libHoge.so 빌드 시와 이것을 사용하는 응용 프로그램 빌드 시 USE_FEATURE_X 값을 모아 두지 않으면 안된다. 그러나 libHoge.so 빌드 할 때 컴파일러 옵션 -DUSE_FEATURE_X = 1로 한 경우 응용 프로그램을 빌드 할 때 같은 옵션을 켜야 한다. 이렇게 되면 응용 프로그램 개발자는 자신이 사용하는 모든 라이브러리에 매크로 설정을 파악해 두어야 하고, 당연히 파악하지 못하여 파산하게 될 것이다. 이런 경우 USE_FEATURE_X를 헤더 파일에 정의 해 두지 않으면 안된다. 따라서 환경 의존 부분이 헤더 파일은 CMake에 자동 생성 되도록 한다. - 헤더 파일의 바탕이 되는 뼈대를 준비해 두고 libHoge.so 빌드 시 지정한 옵션에 따라 실제로 사용되는 헤더 파일을 생성하는 것이다. - 물론 HogeConfig.h를 자동 생성 시켜도 좋지만, 이런 것은 전용의 별도 파일에 두면 보기가 좋아진다. 따라서 환경에 맞는 설정을 기술하는 HogeConfig.h을 마련하기로 하자. 이것을 Hoge.h에서 포함하면 된다. ## CMake에서 설정 파일을 만드는 방법 우선 HogeConfig.h의 양식이 되는 HogeConfig.h.in을 준비한다. ``` #ifndef HOGECONFIG_H #define HOGECONFIG_H #define USE_FEATURE_X @USE_FEATURE_X@ #endif // HOGECONFIG_H ``` @로 둘러 싸인 부분은 CMake로 대체되는 부분이다. 또한 CMakeLists.txt은 다음과 같이한다. ``` cmake_minimum_required(VERSION 2.8) configure_file("HogeConfig.h.in" "HogeConfig.h") add_executable(myapp main.cpp Hoge.cpp) ``` configure_file 명령으로 프로토타입이 되는 파일과 자동 생성하는 파일의 이름을 지정한다. 파일 이름은 무엇이든 좋지만, GNU Autotools의 관습에 따라 {원래 파일 이름}.in 하는 것이 좋겠다. 이제 HogeConfig.h는 USE_FEATURE_X 값이 반영된 것이 된다. <pre> > cmake -DUSE_FEATURE_X=1 (snip) > cat HogeConfig.h #ifndef HOGECONFIG_H #define HOGECONFIG_H #define USE_FEATURE_X 1 #endif // HOGECONFIG_H > cmake -DUSE_FEATURE_X=0 (snip) > cat HogeConfig.h #ifndef HOGECONFIG_H #define HOGECONFIG_H #define USE_FEATURE_X 0 #endif // HOGECONFIG_H </pre> 경로 설정 여기에서는 configure_file 명령의 인수로 단순히 파일 이름만 설명했지만, 실제로는 PROJECT_SOURCE_DIR 이하인 것을 설명하는 것ㅇ이 좋다. ``` configure_file( "${PROJECT_SOURCE_DIR}/HogeConfig.h.in" "${PROJECT_SOURCE_DIR}/HogeConfig.h" ) ```
Java
UTF-8
4,536
2.40625
2
[]
no_license
package pers.hyu.jwtdemo.share.util; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.*; import org.springframework.beans.factory.annotation.Autowired; import pers.hyu.jwtdemo.share.dto.UserDto; public class AmazonSES { final String FROM = "hy.projects.wpg@gmail.com"; // sender email address final String SUBJECT = "Last step for complete your registration with the jwtdemo app"; // the subject of the email // html body for the email final String HTML_BODY = "<h1>Please verify your email address</h1>" + "<p>Thank you for registering with this app. To complete the registration, click on the following link:</p>" + "<a href='http://localhost:8081/email-verification.html?token=$tokenValue'>Last step to complete your registration</a>" + "<br/><br/>"; // the email body for the receiver that with non-html client final String TEXT_BODY = "Please verify your email address" + "Thank you for registering with this app. To complete the registration, please open the following link:" + "http://localhost:8080/jwtdemo/users/email_verification?token=$tokenValue" + "This is the text body"; final String RESET_PASSWORD_SUBJECT = "Please conform and reset the password"; // the subject of the email // html body for the email final String RESET_PASSWORD_HTML_BODY = "<h1>Hi, $firstName</h1>" + "<p>You got this email because you are request to reset your password.</p>" + "<p>If it was not you, please check your account security</p>" + "<p>If it was you, please click on the following link to reset your password within 2 hours:</p>" + "<a href='http://localhost:8081/reset-password-request.html?token=$tokenValue'>Reset the password</a>" + "<br/><br/>"; final String RESET_PASSWORD_TEXT_BODY = "Hi, $firstName" + "You got this email because you are request to reset your password." + "If it was not you, please check your account security" + "If it was you, please click on the following link to reset your password within 2 hours:" + "<a href='http://localhost:8081/reset-password-request.html?token=$tokenValue'>Reset the password" ; public void sendVerifyEmail(UserDto userDto) { AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard().withRegion("ca-central-1").build(); String htmlBodyWithToken = HTML_BODY.replace("$tokenValue", userDto.getEmailVerificationToken()); String textBodyWithToken = TEXT_BODY.replace("$tokenValue", userDto.getEmailVerificationToken()); SendEmailRequest request = new SendEmailRequest() .withDestination(new Destination().withToAddresses(userDto.getEmail())) .withMessage(new Message() .withBody(new Body().withHtml(new Content().withCharset("UTF-8").withData(htmlBodyWithToken)) .withText(new Content().withCharset("UTF-8").withData(textBodyWithToken))) .withSubject(new Content().withCharset("UTF-8").withData(SUBJECT))) .withSource(FROM); client.sendEmail(request); // System.out.println("Email has sent"); } public void sendResetPasswordEmail(String firstName, String email, String resetPasswordToken){ AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard().withRegion("ca-central-1").build(); String htmlBodyWithToken = RESET_PASSWORD_HTML_BODY.replace("$tokenValue", resetPasswordToken); htmlBodyWithToken = htmlBodyWithToken.replace("$firstName", firstName); String textBodyWithToken = RESET_PASSWORD_TEXT_BODY.replace("$tokenValue", resetPasswordToken); textBodyWithToken = textBodyWithToken.replace("$firstName", firstName); SendEmailRequest request = new SendEmailRequest() .withDestination(new Destination().withToAddresses(email)) .withMessage(new Message() .withSubject(new Content().withCharset("UTF-8").withData(RESET_PASSWORD_SUBJECT)) .withBody(new Body().withHtml(new Content().withCharset("UTF-8").withData(htmlBodyWithToken)))) .withSource(FROM); client.sendEmail(request); System.out.println("Reset password link sent!!!"); } }
Java
UTF-8
6,341
2.5625
3
[]
no_license
package com.gempukku.lotro.game; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class LotroCardBlueprintLibrary { private String[] _packageNames = new String[]{ "", ".dwarven", ".dunland", ".elven", ".fallenRealms", ".gandalf", ".gollum", ".gondor", ".isengard", ".men", ".orc", ".raider", ".rohan", ".moria", ".wraith", ".sauron", ".shire", ".site", ".uruk_hai" }; private Map<String, LotroCardBlueprint> _blueprintMap = new HashMap<String, LotroCardBlueprint>(); private Map<String, String> _blueprintMapping = new HashMap<String, String>(); private Map<String, Set<String>> _fullBlueprintMapping = new HashMap<String, Set<String>>(); public LotroCardBlueprintLibrary() { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(LotroCardBlueprintLibrary.class.getResourceAsStream("/blueprintMapping.txt"), "UTF-8")); try { String line; while ((line = bufferedReader.readLine()) != null) { if (!line.startsWith("#")) { String[] split = line.split(","); _blueprintMapping.put(split[0], split[1]); addAlternatives(split[0], split[1]); } } } finally { bufferedReader.close(); } } catch (IOException exp) { throw new RuntimeException("Problem loading blueprint mapping", exp); } } public String getBaseBlueprintId(String blueprintId) { blueprintId = stripBlueprintModifiers(blueprintId); String base = _blueprintMapping.get(blueprintId); if (base != null) return base; return blueprintId; } private void addAlternatives(String newBlueprint, String existingBlueprint) { Set<String> existingAlternates = _fullBlueprintMapping.get(existingBlueprint); if (existingAlternates != null) { for (String existingAlternate : existingAlternates) { addAlternative(newBlueprint, existingAlternate); addAlternative(existingAlternate, newBlueprint); } } addAlternative(newBlueprint, existingBlueprint); addAlternative(existingBlueprint, newBlueprint); } private void addAlternative(String from, String to) { Set<String> list = _fullBlueprintMapping.get(from); if (list == null) { list = new HashSet<String>(); _fullBlueprintMapping.put(from, list); } list.add(to); } public Set<String> getAllAlternates(String blueprintId) { return _fullBlueprintMapping.get(blueprintId); } public boolean hasAlternateInSet(String blueprintId, int setNo) { Set<String> alternatives = _fullBlueprintMapping.get(blueprintId); if (alternatives != null) for (String alternative : alternatives) if (alternative.startsWith(setNo + "_")) return true; return false; } public LotroCardBlueprint getLotroCardBlueprint(String blueprintId) throws CardNotFoundException { blueprintId = stripBlueprintModifiers(blueprintId); if (_blueprintMap.containsKey(blueprintId)) return _blueprintMap.get(blueprintId); LotroCardBlueprint blueprint = getBlueprint(blueprintId); _blueprintMap.put(blueprintId, blueprint); return blueprint; } public String stripBlueprintModifiers(String blueprintId) { if (blueprintId.endsWith("*")) blueprintId = blueprintId.substring(0, blueprintId.length() - 1); if (blueprintId.endsWith("T")) blueprintId = blueprintId.substring(0, blueprintId.length() - 1); return blueprintId; } // public void initializeLibrary(String setNo, int maxCardIndex) { // for (int i = 1; i <= maxCardIndex; i++) { // try { // getLotroCardBlueprint(setNo + "_" + i); // } catch (IllegalArgumentException exp) { // // Ignore // } // } // } // // public Collection<LotroCardBlueprint> getAllLoadedBlueprints() { // return _blueprintMap.values(); // } // private LotroCardBlueprint getBlueprint(String blueprintId) throws CardNotFoundException { if (_blueprintMapping.containsKey(blueprintId)) return getBlueprint(_blueprintMapping.get(blueprintId)); String[] blueprintParts = blueprintId.split("_"); String setNumber = blueprintParts[0]; String cardNumber = blueprintParts[1]; for (String packageName : _packageNames) { LotroCardBlueprint blueprint = null; try { blueprint = tryLoadingFromPackage(packageName, setNumber, cardNumber); } catch (IllegalAccessException e) { throw new CardNotFoundException(); } catch (InstantiationException e) { throw new CardNotFoundException(); } if (blueprint != null) return blueprint; } throw new CardNotFoundException(); } private LotroCardBlueprint tryLoadingFromPackage(String packageName, String setNumber, String cardNumber) throws IllegalAccessException, InstantiationException { try { Class clazz = Class.forName("com.gempukku.lotro.cards.set" + setNumber + packageName + ".Card" + setNumber + "_" + normalizeId(cardNumber)); return (LotroCardBlueprint) clazz.newInstance(); } catch (ClassNotFoundException e) { // Ignore return null; } } private String normalizeId(String blueprintPart) { int id = Integer.parseInt(blueprintPart); if (id < 10) return "00" + id; else if (id < 100) return "0" + id; else return String.valueOf(id); } }
Java
UTF-8
6,550
3.390625
3
[]
no_license
/** * Program: NFLPlayer * File: NFLPlayer.java * Summary: Programs creates a abstract NFLPlayer class. * Author: Jason E. Borum Date: * December 24, 2017 **/ abstract class NFLPlayer { // Begin abstract NFL Player Class // Declaring NFL Player Instance Variables private String playerNameFirst; // Player First Name private String playerNameLast; // Player Last Name private String playerNameFull; // Player Full Name private String playerCollege; // Player College private String playerPosition; // Player position private Double playerHeight; // Player height in inches private Double playerWeight; // Player weight in pounds private String playerBirthDate; // Player Birthday private int playerAge; // Player age in years private double playerBodyMassIndex; // Player BMI number private double player40yardDash; // Player 40 yrd dash in seconds private double playerVerticalJump; // Player vertical jump height in inches // NFL Player Constructor with Arguments public NFLPlayer(String cplayerNameFirst, String cplayerNameLast, String cplayerCollege, String cplayerPosition, double cplayerHeight, double cplayerWeight, String cplayerBirthDate, int cplayerAge, double cplayer40yardDash, double cplayerVerticalJump) { playerNameFirst = cplayerNameFirst; // Player First Name playerNameLast = cplayerNameLast; // Player Last Name playerNameFull = cplayerNameFirst + " " + cplayerNameLast; // Combine players first name and last name playerCollege = cplayerCollege; // Player College playerPosition = cplayerPosition;// Player position playerHeight = cplayerHeight;// Player height in inches playerWeight = cplayerWeight;// Player weight in pounds playerBirthDate = cplayerBirthDate;// Player Birthday playerAge = cplayerAge;// Player age in years playerBodyMassIndex = 703 * (cplayerWeight / (cplayerHeight * cplayerHeight)); // Calculate players body mas // index player40yardDash = cplayer40yardDash; // Player 40 yrd dash in seconds playerVerticalJump = cplayerVerticalJump; // Player vertical jump height in inches } // End of NFLPlayer Constructor // NFL Player Constructor without Arguments public NFLPlayer() { playerNameFirst = "Mitchell"; playerNameLast = "Trubisky"; playerNameFull = playerNameFirst + " " + playerNameLast; playerCollege = "North Carolina"; playerPosition = "QB"; playerHeight = 74.0; playerWeight = 222.0; playerBirthDate = "08/20/94"; playerAge = 23; playerBodyMassIndex = (int) ((703 * (playerWeight / (playerHeight * playerHeight))) * 100) / 100.0; player40yardDash = 4.67; playerVerticalJump = 27.5; }// End of NFLPlayer Constructor // Create Setters and Getters for NFL Player Attributes public String getPlayerNameFirst() { return playerNameFirst; } // End of getPlayerNameFirst method public void setPlayerNameFirst(String playerNameFirst) { this.playerNameFirst = playerNameFirst; } // End of setPlayerNameFirst method public String getPlayerNameLast() { return playerNameLast; } // End of getPlayerNameLast method public void setPlayerNameLast(String playerNameLast) { this.playerNameLast = playerNameLast; } // End of setPlayerNameLast method public String getPlayerNameFull() { playerNameFull = playerNameFirst + " " + playerNameLast; return playerNameFull; } // End of getPlayerNameFull method public void setPlayerNameFull(String playerNameFull) { this.playerNameFull = playerNameFull; } // End of setPlayerNameFull method public String getPlayerCollege() { return playerCollege; } // End of getPlayerCollege method public void setPlayerCollege(String playerCollege) { this.playerCollege = playerCollege; } // End of setPlayerCollege method public String getPlayerPosition() { return playerPosition; } // End of getPlayerPosition method public void setPlayerPosition(String playerPosition) { this.playerPosition = playerPosition; } // End of setPlayerPosition method public Double getPlayerHeight() { return playerHeight; } // End of getPlayerHeight method public void setPlayerHeight(Double playerHeight) { this.playerHeight = playerHeight; } // End of setPlayerHeight method public Double getPlayerWeight() { return playerWeight; } // End of getPlayerWeight method public void setPlayerWeight(Double playerWeight) { this.playerWeight = playerWeight; } // End of setPlayerWeight method public String getPlayerBirthDate() { return playerBirthDate; } // End of getPlayerBirthDate method public void setPlayerBirthDate(String playerBirthDate) { this.playerBirthDate = playerBirthDate; } // End of setPlayerBirthDate method public int getPlayerAge() { return playerAge; } // End of getPlayerAge method public void setPlayerAge(int playerAge) { this.playerAge = playerAge; } // End of setPlayerAge method public double getPlayerBodyMassIndex() { playerBodyMassIndex = (int) ((703 * (playerWeight / (playerHeight * playerHeight))) * 100) / 100.0; return playerBodyMassIndex; } // End of getPlayerBodyMassIndex method public void setPlayerBodyMassIndex(double playerBodyMassIndex) { this.playerBodyMassIndex = playerBodyMassIndex; } // End of setPlayerBodyMassIndex method public double getPlayer40yardDash() { return player40yardDash; } // End of getPlayer40yardDash method public void setPlayer40yardDash(double player40yardDash) { this.player40yardDash = player40yardDash; } // End of setPlayer40yardDash method public double getPlayerVerticalJump() { return playerVerticalJump; } // End of getPlayerVerticalJump method public void setPlayerVerticalJump(double playerVerticalJump) { this.playerVerticalJump = playerVerticalJump; } // End of setPlayerVerticalJump method // To String Method Returning NFL Players public String toString() { return "NFLPlayer [playerNameFirst=" + playerNameFirst + ", playerNameLast=" + playerNameLast + ", playerNameFull=" + playerNameFull + ", playerCollege=" + playerCollege + ", playerPosition=" + playerPosition + ", playerHeight=" + playerHeight + ", playerWeight=" + playerWeight + ", playerBirthDate=" + playerBirthDate + ", playerAge=" + playerAge + ", playerBodyMassIndex=" + playerBodyMassIndex + ", player40yardDash=" + player40yardDash + ", playerVerticalJump=" + playerVerticalJump + "]"; } // End of toString Method } // End of NFL Player Class
C++
UTF-8
992
2.53125
3
[ "MIT" ]
permissive
#include<iostream> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> using namespace std; int main() { //freopen("c:\\cygwin64\\home\\xs\\mygit\\acm\\in", "r", stdin); //insert code int t; cin>>t; while(t--) { int n,m,k; cin>>n>>m>>k; int ar[12][12]={0}; char re[12][12]={0}; int x,y; //initializing for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { re[i][j]='.'; } } //in for(int i=1;i<=k;i++) { cin>>x>>y; x; y; ar[x][y]=1; re[x][y]='M'; } //sovle for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(ar[i][j]==1)continue; re[i][j]='0'+ar[i-1][j-1]+ar[i][j-1]+ar[i+1][j-1] +ar[i-1][j]+ ar[i+1][j] +ar[i-1][j+1]+ar[i][j+1]+ar[i+1][j+1]; if(re[i][j]=='0')re[i][j]='.'; if(ar[i][j]==1)re[i][j]='M'; } } //display for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { cout<<re[i][j]; } cout<<endl; } cout<<endl; } //insert code return 0; }
C++
WINDOWS-1251
8,523
3.125
3
[]
no_license
#include "spinlock.h" size_t spinlock::count; void spinlock::lock() { //. while (f.test_and_set(std::memory_order_relaxed))//// true { // std::cout<<"\nlock..."; m_write_entered = 1; } //std::cout << "\nlock once"; } void spinlock::unlock() { f.clear(); // false //std::cout << "\n...unlock"; m_write_entered = 0; } bool spinlock::try_lock() { return !f.test_and_set(); } void spinlock::lock_shared() { /* if (try_lock()==true) { numLock.fetch_add(1); } a.fetch_add(1);*/ do_lock_shared(); } void spinlock::unlock_shared() { // std::shared_lock<spinlock> sh() /* if (a == numLock) { unlock(); } a.fetch_sub(1);*/ do_unlock_shared(); } unsigned long spinlock::number_of_readers() const { return m_state;//m_num_readers; } bool spinlock::maximal_number_of_readers_reached() const { return number_of_readers() == m_max_readers; } bool spinlock::someone_has_exclusive_lock() const { return (m_write_entered != 0);//1!=0 - true } void spinlock::increment_readers() { if (m_num_readers < 32u) { m_state |= (1 << m_num_readers); m_num_readers++; } } void spinlock::decrement_readers() { if (m_num_readers > 0) { m_num_readers--; m_state &= ~(1 << (m_num_readers)); } } void spinlock::do_lock_shared() {// , .. while (someone_has_exclusive_lock() || maximal_number_of_readers_reached()) {// lock_shared() . // , ulong (32bits), lock_shared() . // lock();//wait bool b = f.test_and_set(std::memory_order_relaxed);//?? // /* if (b) { std::cout << "\ndo_lock_shared TRUE"; } else { std::cout << "\ndo_lock_shared FALSE"; }*/ //std::condition_variable_any } increment_readers();// , //shared- ( ) } void spinlock::do_unlock_shared() { decrement_readers(); if (someone_has_exclusive_lock())// . { if (number_of_readers() == 0) { unlock();//notify_one } } else {//last if (number_of_readers() == 0)// unlock();//notify_one } } /* std::memory_order C++ <atomic> enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst }; ( C++11) std::memory_order( ) , , , . - , , , , , . , . (sequentially consistent ordering) ( ). , std::memory_order , , , . <atomic> memory_order_relaxed (Relaxed) : , . memory_order_consume (consume) : , , (release), . memory_order_acquire (acquire) : , , (release), . memory_order_release (release) : , , (consume) (acquire) . memory_order_acq_rel (acquire) . (release). memory_order_seq_cst(sequentially - consistent - ) , memory_order_acq_rel, , (.) . , . : */
C++
UTF-8
2,099
3.25
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <set> #include <map> #include <stack> #include <queue> #include <functional> #include <iterator> #include <utility> using namespace std; class Solution { public: string shortestCompletingWord(string licensePlate, vector<string>& words) { unordered_map<char, int> orgHash; //licensePlate. for (char c : licensePlate) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { char t = c >= 'a' ? c : c += 'a' - 'A'; if (orgHash.find(t) == orgHash.end()) orgHash[t] = 0; ++orgHash[t]; } } // sort should be changed to hash table by length. sort(words.begin(), words.end(), [](string first, string second) -> bool { return first.length() < second.length(); //if (first.length() != second.length()) return first.length() < second.length(); //return first < second; }); // sort by length and dic order. for (auto w : words) cout << w << endl; for(auto w : words) { unordered_map<char, int> tHash; //copy(tHash.begin(), tHash.end(), orgHash.begin()); for_each(orgHash.begin(), orgHash.end(), [&](pair<char, int> p) { tHash[p.first] = p.second; }); for (char c : w) { if (tHash.find(c) != tHash.end()) --tHash[c]; } if (none_of(tHash.begin(), tHash.end(), [&](pair<char, int> p) -> bool { if (p.second > 0) return true; return false; })) { return w; } } return ""; } }; int main() { Solution obj = Solution(); vector<string> v{ "looks", "pest", "stew", "show" }; string lp1 = "1s3 456"; cout << obj.shortestCompletingWord(lp1, v) << endl; return 0; }
C
UTF-8
1,476
4.03125
4
[]
no_license
#include <stdio.h> #define DATA_SIZE 8 void ShowData(int num[], int n); void BubbleSort(int num[], int n); void InsSort(int num[], int n) ; // データを表示する関数 void ShowData(int num[], int n) { int i; for(i=0; i < n; i++) { printf("%d ", num[i]); } printf("\n"); } void BubbleSort(int x[ ], int n) { int i, j, temp; for (i = 0; i < n - 1; i++) { for (j = n - 1; j > i; j--) { if (x[j - 1] > x[j]) { /* 前の要素の方が大きかったら */ temp = x[j]; /* 交換する */ x[j] = x[j - 1]; x[j - 1]= temp; } } /* ソートの途中経過を表示 */ ShowData(x, DATA_SIZE); } } void InsSort(int num[ ], int n) { int i, j, temp; for (i = 1; i < n; i++) { /* i 番目の要素をソート済みの配列に挿入 */ temp = num[i]; /* i 番目の要素を temp に保存 */ for (j = i; j > 0 && num[j-1] > temp; j--) { /* このループで */ num[j] = num[j -1]; /* temp を挿入する位置を決める */ } num[j] = temp; /* temp を挿入 */ ShowData(num, n); /* 途中経過を表示 */ } } int main() { // データ定義 int num[ ] = {3, 7, 1, 5, 4, 2, 6, 0}; // ソート前のデータを表示 //ShowData(num, DATA_SIZE); // バブルソートの実行 //BubbleSort(num, DATA_SIZE); // 単純挿入ソートの実行 InsSort(num, DATA_SIZE); return 0; }
PHP
UTF-8
1,192
3.171875
3
[]
no_license
<?php declare(strict_types=1); namespace XonneX\AdventOfCode\Y2020\Solutions\Day2; use PHPUnit\Framework\TestCase; class Day2Test extends TestCase { public function testSolvePartOneExample(): void { $day2 = new Day2(); /** @noinspection SpellCheckingInspection */ $day2->setDebugInput(<<<TXT 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc TXT ); self::assertSame('2', $day2->solvePartOne()); } public function testSolvePartOne(): void { $day2 = new Day2(); self::assertSame('556', $day2->solvePartOne()); } public function testSolvePartTwoExample(): void { $day2 = new Day2(); /** @noinspection SpellCheckingInspection */ $day2->setDebugInput(<<<TXT 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc TXT ); self::assertSame('1', $day2->solvePartTwo()); } public function testSolvePartTwoWrongAnswerOne(): void { $day2 = new Day2(); self::assertNotSame('407', $day2->solvePartTwo()); } public function testSolvePartTwo(): void { $day2 = new Day2(); self::assertSame('605', $day2->solvePartTwo()); } }
Java
UTF-8
2,449
2.53125
3
[]
no_license
package com.example.exam_set1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Set_7_second extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_7_second); final EditText no = (EditText)findViewById(R.id.no); final TextView odd = (TextView) findViewById(R.id.odd); final TextView prime = (TextView)findViewById(R.id.prime); final TextView sum1 = (TextView)findViewById(R.id.sum); Button submit = (Button)findViewById(R.id.submit); Button home = (Button)findViewById(R.id.home); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Condition One(Odd Even) int no1 = Integer.parseInt(no.getText().toString()); if(no1 %2 == 0) { odd.setText("Number is Even"); } else { odd.setText("Number is Odd"); } //Condition 2 () Prime Number or Not double number = Double.parseDouble(no.getText().toString()); int f=0; for(int i=2; i<number; i++) { if(number % i == 0) f = 1; } if(f == 0) { prime.setText("Prime Number"); } else { prime.setText("Not a Prime Number"); } //Condition 3 () Sum of Digits long sum; long n = Long.parseLong(no.getText().toString()); for(sum=0; n!=0; n/=10) { sum+= n%10; } sum1.setText("Sum of all digits is:"+sum); } }); home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent iv = new Intent(Set_7_second.this,Home.class); startActivity(iv); } }); } }
Java
UTF-8
324
1.6875
2
[]
no_license
/* * Decompiled with CFR 0_129. */ package org.apache.http.auth; /* * This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6. */ public enum AuthProtocolState { UNCHALLENGED, CHALLENGED, HANDSHAKE, FAILURE, SUCCESS; private AuthProtocolState() { } }
JavaScript
UTF-8
4,712
2.71875
3
[]
no_license
import http from 'http'; import fs from 'fs'; import {join} from 'path'; import pipe from './pipe'; import Router from './Router'; let server = http.createServer(); // fs.readFile('./assets/img/goo.png', (err, data) => { // if (err) { // throw err; // } // console.log('data gambar !!', data); // }); let dummyData = { Product: [ {id: 1, name: 'banana', price: '100'}, {id: 3, name: 'apple', price: '20000'}, {id: 2, name: 'blackberry', price: '10'}, ], }; let supportedType = { mp4: 'video/mp4', mp3: 'audio/mpeg', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', txt: 'plain/text', html: 'text/html', }; function serveNotFoundPage(request, response) { response.statusCode = 404; response.setHeader('Content-Type', 'text/html'); response.end(`<h1>Bad Request !</h1>`); } function serveErrorPage(request, response, error) { response.statusCode = 404; response.setHeader('Content-Type', 'text/html'); response.end(`<h1>Error ${error}</h1>`); } function serveAsset(request, response, filePath) { let readStream = fs.createReadStream(filePath); // readStream.pipe() // pipe(readStream, response); readStream.on('error', (error) => { console.log(error); serveErrorPage(request, response, error); }); readStream.pipe(response); readStream.on('end', () => { response.end(); }); } function serveFile(request, response, filePath) { let fileName = filePath.split('/').pop(); let fileExtension = fileName.split('.').pop(); if (supportedType[fileExtension]) { response.statusCode = 200; response.setHeader('Content-Type', supportedType[fileExtension]); serveAsset(request, response, filePath); } else { serveNotFoundPage(request, response); } } function typeChecking(jsonRes) { if (!Array.isArray(jsonRes) && typeof jsonRes === 'object') { for (let key of Object.keys(jsonRes)) { if (key === 'name') { if (typeof jsonRes[key] !== 'string') { console.log('Woops! The name type does not match!'); return; } } if (key === 'age') { if (typeof jsonRes[key] !== 'number') { console.log('Woops! The age type does not match!'); return; } } } } else { console.log('Woops! The result type does not match!'); } } let router = new Router(); router.addRoute('/', ({request, response}) => { let filePath = join(__dirname, './assets/main.html'); serveFile(request, response, filePath); }); router.addRoute('/assets/:fileName', ({request, response}, fileName) => { let filePath = join(__dirname, './', request.url); console.log('>>File Path', filePath); console.log('>>File Name', fileName); serveFile(request, response, filePath); }); router.addRoute('/users/:userID', ({request, response}, userID) => { response.statusCode = 200; response.setHeader('Content-Type', 'text/html'); response.end(`<h1>User ID: ${userID}</h1>`); }); router.addRoute('/submit-json', ({request, response}) => { response.statusCode = 200; response.setHeader('Content-Type', 'text/html'); // let body = []; request.on('data', (data) => { let jsonRes = JSON.parse(data.toString()); // console.log('typeof jsonRes', typeof jsonRes, jsonRes); typeChecking(jsonRes); let result = JSON.stringify(jsonRes); response.write(result); response.end(); }); }); server.on('request', (request, response) => { router.handleRequest(request.url, {request, response}); // if (request.url.startsWith('/assets/')) { // let filePath = join(__dirname, './', request.url); // console.log('>>File Path', filePath); // serveFile(request, response, filePath); // } // console.log('request received', request.url); // if (request.url.startsWith('/assets/')) { // let filePath = join(__dirname, '../', request.url); // serveFile(request, response, filePath); // } else if (request.url === '/page/') { // let filePath = join(__dirname, './assets/main.html'); // serveFile(request, response, filePath); // } else if (request.url === '/submit-json') { // response.statusCode = 200; // response.setHeader('Content-Type', 'text/html'); // let body = []; // request.on('data', (data) => { // let jsonRes = JSON.parse(data.toString()); // let result = JSON.stringify(jsonRes); // response.write(result); // response.end(); // }); // // let a = JSON.stringify({name: 123}); // // response.write(a); // // response.end(); // // console.log('>>>Submit-json', response); // // fs.createWriteStream('path, options?') // } else { // serveNotFoundPage(request, response); // } }); server.listen(8080);
C++
UTF-8
1,071
2.640625
3
[]
no_license
#pragma once #include <functional> #include <condition_variable> #include <mutex> #include "Types.hpp" #include "Work.hpp" class ParIter; class ParIterExecutor { public: using Func = std::function<void(uint64 value)>; ParIterExecutor(ParIter& parIter, const Func& func, uint64 start, uint64 end) : parIter(parIter), func(func), start(start), end(end) { } void operator()(); private: ParIter& parIter; const Func& func; uint64 start; uint64 end; }; class ParIter { public: using Func = std::function<void(uint64 value)>; ParIter(uint64 start = 0, uint64 end = 0); void setPar(bool value); void change(uint64 start, uint64 end); void go(const Func& func); void notify(); private: void compute(); void schedule(const Func& func); void waitCompletion(); bool par; uint64 start; uint64 end; uint64 count; uint64 threadCount; std::mutex mtx; uint64 completedCount; std::condition_variable waiter; std::vector<ParIterExecutor> executors; };
Java
UTF-8
342
3.078125
3
[]
no_license
import java.util.*; public class LinkedListTest { public static void main(String[] args) { LinkedList ll = new LinkedList(); ll.offer("Alex"); ll.offer("Bob"); ll.offer("Catalina"); System.out.println(ll); ll.offerLast("Dick"); System.out.println(ll); ll.offerFirst("Easbella"); System.out.println(ll); } }
Shell
UTF-8
655
2.953125
3
[]
no_license
#!/bin/bash RPCLIST="discover fan verify user modify limit config" SPECLIST="share" function gen_rpc() { for srv in $RPCLIST; do echo $srv protoc --go_out=plugins=grpc:../proto/$srv/ ../proto/$srv/$srv.proto -I../.. -I../proto/$srv done } function gen_spec() { for srv in $SPECLIST; do echo $srv protoc --go_out=plugins=grpc:../proto/$srv/ ../proto/$srv/$srv.proto -I../.. -I../proto/$srv sed -i "s/\"uid,omitempty\"/\"uid\"/g" ../proto/$srv/$srv.pb.go done } function gen_comm() { protoc --go_out=../proto/common ../proto/common/common.proto -I../proto/common } gen_comm gen_rpc gen_spec
Ruby
UTF-8
304
3.546875
4
[]
no_license
name_age ={"ajay"=>23,"Kalyan"=>25,"naveen"=>23} puts name_age.keys puts name_age.values puts name_age.has_key?("ajay") puts name_age.select {|k,v| v == 25} puts name_age.select {|k,v| k=="ajay"} str ="this is a string" puts s=String.new(str) puts name_age.inspect puts name_age.rehash
SQL
UTF-8
5,187
3.40625
3
[]
no_license
-- -------------------------------------------------------- -- Host: 127.0.0.1 -- Versión del servidor: 10.1.21-MariaDB - mariadb.org binary distribution -- SO del servidor: Win32 -- HeidiSQL Versión: 9.4.0.5125 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Volcando estructura de base de datos para bananagroupmaven CREATE DATABASE IF NOT EXISTS `bananagroupmaven` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `bananagroupmaven`; -- Volcando estructura para tabla bananagroupmaven.proyecto CREATE TABLE IF NOT EXISTS `proyecto` ( `pid` int(11) NOT NULL AUTO_INCREMENT, `titulo` varchar(100) NOT NULL, `descripcion` varchar(300) NOT NULL, `fechaI` date NOT NULL, `responsable` int(11) NOT NULL, `activo` varchar(45) NOT NULL, PRIMARY KEY (`pid`), UNIQUE KEY `pid_UNIQUE` (`pid`), KEY `fk_proyecto_usuario_idx` (`responsable`), CONSTRAINT `fk_proyecto_usuario` FOREIGN KEY (`responsable`) REFERENCES `usuario` (`uid`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- Volcando datos para la tabla bananagroupmaven.proyecto: ~9 rows (aproximadamente) /*!40000 ALTER TABLE `proyecto` DISABLE KEYS */; INSERT INTO `proyecto` (`pid`, `titulo`, `descripcion`, `fechaI`, `responsable`, `activo`) VALUES (1, 'Proyecto VinRun', 'Diseño pruebas preproducto VinRun 3,0', '2017-02-03', 1111, 'Si'), (2, 'Proyecto VinRun', 'Nuevas funcionalidades VinRun 3,0', '2017-02-15', 3333, 'No'), (3, 'Proyecto Front', 'Diseño capas html', '2017-02-01', 1111, 'No'), (4, 'Proyecto Back', 'Nuevo controlador ', '2017-02-27', 2222, 'Si'), (5, 'Proyecto Descargas', 'Descarga parche 3,0001', '2017-02-10', 3333, 'Si'), (6, 'Proyecto VinDown', 'Definición equipos de ataque', '2017-02-03', 2222, 'Si'), (7, 'Proyecto VinDown', 'Diseño Roadmap VinDown 4,0', '2017-02-04', 2222, 'No'), (8, 'Proyecto clientes Francia', 'Gestión bugs VinRun 3,0', '2017-02-07', 1111, 'Si'), (9, 'Proyecto Refactor', 'Nueva clase de bbdd MySql', '2017-02-24', 3333, 'No'); /*!40000 ALTER TABLE `proyecto` ENABLE KEYS */; -- Volcando estructura para tabla bananagroupmaven.tarea CREATE TABLE IF NOT EXISTS `tarea` ( `tid` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(150) NOT NULL, `responsable` int(11) NOT NULL, `proyecto_padre` int(11) NOT NULL, PRIMARY KEY (`tid`), UNIQUE KEY `idtarea_UNIQUE` (`tid`), KEY `fk_tarea_usuario1_idx` (`responsable`), KEY `fk_tarea_proyecto1_idx` (`proyecto_padre`), CONSTRAINT `fk_tarea_proyecto` FOREIGN KEY (`proyecto_padre`) REFERENCES `proyecto` (`pid`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_tarea_usuario` FOREIGN KEY (`responsable`) REFERENCES `usuario` (`uid`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8; -- Volcando datos para la tabla bananagroupmaven.tarea: ~18 rows (aproximadamente) /*!40000 ALTER TABLE `tarea` DISABLE KEYS */; INSERT INTO `tarea` (`tid`, `descripcion`, `responsable`, `proyecto_padre`) VALUES (11, 'Pruebas regresión', 1111, 1), (22, 'Pruebas aceptación', 3333, 1), (33, 'Barra lateral', 2222, 3), (44, 'Implementación css', 3333, 5), (55, 'Descarga web y msi', 2222, 6), (66, 'Reportar bug mantis', 2222, 2), (77, 'Modelaje mysqlbench', 1111, 3), (88, 'Timing por versiones', 1111, 7), (99, 'Analisis versiones anteriores', 3333, 8), (111, 'Reporting incidencias clientes', 2222, 8), (222, 'Desarrollo nuevo controlador', 1111, 9), (333, 'Implementación nueva clase', 2222, 9), (444, 'Restructuración base', 3333, 1), (555, 'Update bbdd', 3333, 3), (666, 'Construcción controladores', 1111, 5), (777, 'Revisión proyecto', 2222, 6), (888, 'Evaluación proyecto', 3333, 2), (999, 'Edición mockers', 3333, 7); /*!40000 ALTER TABLE `tarea` ENABLE KEYS */; -- Volcando estructura para tabla bananagroupmaven.usuario CREATE TABLE IF NOT EXISTS `usuario` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(20) NOT NULL, PRIMARY KEY (`uid`), UNIQUE KEY `idusuario_UNIQUE` (`uid`), UNIQUE KEY `email_UNIQUE` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=3334 DEFAULT CHARSET=utf8 COMMENT=' '; -- Volcando datos para la tabla bananagroupmaven.usuario: ~3 rows (aproximadamente) /*!40000 ALTER TABLE `usuario` DISABLE KEYS */; INSERT INTO `usuario` (`uid`, `nombre`, `email`, `password`) VALUES (1111, 'Ricardo', 'ricardo@r.es', 'r123456'), (2222, 'Juana', 'juana@j.es', 'j123456'), (3333, 'Luis', 'luis@l.es', 'l123456'); /*!40000 ALTER TABLE `usuario` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
Java
UTF-8
570
3.421875
3
[]
no_license
package com.skilldistillery.blackjack; public class Dealer extends BlackJackHand implements ShowHand { public Dealer() {} // Shows one card face and one blank card. public String toString() { String showCards = "" + cards.get(0); return showCards; } @Override // The interface method shows full had when necessary. public String showHand() { String showCards = ""; for (int i = 0; i < cards.size(); i++) { if (i < cards.size() - 1) { showCards += cards.get(i) + " "; } else { showCards += cards.get(i); } } return showCards; } }
C++
UTF-8
1,124
2.640625
3
[]
no_license
// // compiler.cpp // CARM-Compiler // // Created by Ollie Ford on 01/03/2015. // Copyright (c) 2015 OJFord. All rights reserved. // #include <iostream> #include <fstream> #include <stdexcept> #include <string> #include "invoc-args.h" #include "parser/parser.h" int main(const int argc, const char* argv[]){ InvocationArguments ia(argc, argv); Parser* parser; bool verbose = ia.flagExists("-v") ? true : false; if( !ia.flagExists("-S") ){ std::cerr << "That's not supported." << std::endl; exit(EXIT_FAILURE); } std::streambuf* buf; std::ofstream of; if( ia.flagExists("-o") ){ const char* ofname; if( (ofname = ia.getOption("-o")) ){ of.open(ofname); buf = of.rdbuf(); } else{ std::cout << "Argument to '-o' is missing." << std::endl; exit(EXIT_FAILURE); } } else { buf = std::cout.rdbuf(); } std::ostream out(buf); try{ // Naively assume input file is given last parser = new Parser(verbose, &of, argv[argc-1]); } catch(std::out_of_range& e){ std::cout << "No input files specified." << std::endl; exit(EXIT_FAILURE); } parser->parse(); parser->reduce(); }
C++
UTF-8
1,147
2.703125
3
[ "MIT" ]
permissive
// // Window.cpp // GorillaBeats // // Created by Cyrus Gao on 25/05/2019. // Copyright © 2019 gb. All rights reserved. // #include "Window.hpp" int Window::run() { // safely convert long to int without warning int size = static_cast<int>(this->objectVector.size()); while (!glfwWindowShouldClose(window)) { processInput(window); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); for (int i = 0; i < size; i++) { objectVector.at(i)->render(); } glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } void Window::framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width // and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } void Window::processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } void Window::add(Object* obj) { obj->ready(); objectVector.push_back(obj); }
Shell
UTF-8
1,504
3.140625
3
[]
no_license
#!/bin/bash # Download Drush v3 from D.O and make it work on `drush` (OS X / Linux / *nix) # quickly put together by stemount, adapted by KarenS # move to home dir cd ~ # remove current drush (if existent) rm -rf ~/.drush/ # create drush directory (and hide it) mkdir ~/.drush/ # move to new dir cd ~/.drush/ # get Drush curl -C - -O http://ftp.drupal.org/files/projects/drush-7.x-4.5.tar.gz # extract Drush tar -xf drush*.tar.gz # bin Drush tar rm -f drush*.tar.gz # get Pear Console Table library #cd drush/includes #curl -C - -O http://download.pear.php.net/package/Console_Table-1.1.3.tgz # extract Pear #tar -xf Console_Table*.tgz # copy the file we need #cp Console_Table-1.1.3/Table.php table.inc # bin Console_Table tar #rm -r Console_Table-1.1.3 #rm -f Console_Table*.tgz # get Drush Make # cd .. cd drush/commands curl -C - -O http://ftp.drupal.org/files/projects/drush_make-6.x-2.3.tar.gz # extract Drush Make tar -xf drush*.tar.gz # bin Drush tar rm -f drush_make*.tar.gz # # get Provision # curl -C - -O http://ftp.drupal.org/files/projects/provision-6.x-0.3.tar.gz # # extract Provision # tar -xf provision*.tar.gz # # bin Provision tar # rm -f provision*.tar.gz # make drush command executable cd ~ chmod u+x .drush/drush/drush # alias drush and put in bash profile touch ~/.bash_profile echo "alias drush='~/.drush/drush/drush'" >> ~/.bash_profile # add symbolic link to drush files so they are executable anywhere # rm /usr/bin/drush # ln -s ~/.drush/drush/drush /usr/bin/drush
C++
UTF-8
1,914
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int prod, i, ind, j; string g[100], str; char T, NT; string a, b; vector <string> alpha; vector <string> beta; cin>>prod; for (i = 0; i < prod; i++) cin>>g[i]; cout<<endl; for (i = 0; i < prod; i++) { str = g[i]; NT = str[0]; ind = 3; a = ""; b = ""; j = ind; alpha.clear(); beta.clear(); bool flag = false; if (str[0] == str[3]) flag = true; if (flag == false) cout<<str<<endl; else { while (j < str.length()) { a = ""; ind = j; if (NT == str[ind]) { ind++; while (str[ind] != 0 && str[ind] != '|') a += str[ind++]; ind++; alpha.push_back(a); j = ind; } else j++; } ind = 3; j = ind; while (j < str.length()) { b = ""; if (NT == str[ind]) { while (str[ind] != 0 && str[ind] != '|') ind++; ind++; } if (NT != str[ind] && flag == true && ind < str.size()) { while (str[ind] != 0 && str[ind] != '|') b += str[ind++]; ind++; //cout<<b<<endl; beta.push_back(b); j = ind; } else j++; } if (flag == false) cout<<str<<endl; else { if (beta.size() == 0) cout<<"Error in Grammar"<<endl; else { cout<<NT<<"->"; for (j = 0; j < beta.size(); j++) { if (j > 0) cout<<"|"; cout<<beta[j]<<NT<<"'"; } cout<<endl; cout<<NT<<"'->"; for (j = 0; j < alpha.size(); j++) { if (j > 0) cout<<"|"; cout<<alpha[j]<<NT<<"'"; } cout<<"|ep"; } } cout<<endl; } } return 0; } /* Test Cases 3 E->E+T|T T->T*F|F F->(E)|id 3 E->E+T|E+Z|T T->T*F|F F->(E)|id 3 E->E+T|T T->T*F|F F->F*S|id 3 E->E+T|T|a|b|c T->T*F|F F->(E)|id 3 E->P|E+T|L|E/T F->L|F*X|lg|F*S X->id|S|re */
Python
UTF-8
494
2.890625
3
[]
no_license
import logging # 提前进行logger的创建,模块的日志按照原始root的配置 import foo logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('Start reading database') # read database here records = {'john': 55, 'tom': 66} logger.debug('Records: %s', records) logger.info('Updating records ...') # 经过上面的渲染,更改了foo里面的logger的配置,所以调用函数可以输出info的basic格式 foo.foo() bar = foo.Bar() bar.bar()
C++
UTF-8
2,146
3.390625
3
[]
no_license
#include <iostream> #include "string.h" #include <iomanip> using namespace std; class MyTime { public: MyTime(); MyTime(int h, int m,int s):hour(h),minute(m),second(s){} void SetTime(int hh,int mm,int ss){ hour=hh; minute=mm; second=ss; } void print_12(){ if (hour>=12) { zone[0]='P'; print(hour-12); }else{ print(hour); } cout<<":"; print(minute); cout<<":"; print(second); cout<<" "<<zone[0]<<zone[1]<<endl; } void print_24(){ print(hour); cout<<":"; print(minute); cout<<":"; print(second); cout<<endl; } MyTime operator+(const MyTime &a){ MyTime time; time.hour=a.hour+hour; time.minute=a.minute+minute; time.second=a.second+second; if (time.second>59) { time.second-=60; time.minute++; } if (time.minute>59) { time.minute-=60; time.hour++; } if (time.hour>23) { time.hour-=24; } return time; } MyTime operator-(const MyTime &a){ MyTime time; time.hour=a.hour-hour; time.minute=a.minute-minute; time.second=a.second-second; if (time.second<0) { time.second+=60; time.minute--; } if (time.minute<0) { time.minute+=60; time.hour--; } if (time.hour<0) { time.hour+=24; } return time; } private: int hour; int minute; int second; char zone[2]={'A','M'}; void print(int num){ cout<<setfill('0')<<setw(2)<<num; } }; MyTime::MyTime(){ hour=0; minute=0; second=0 } int main(int argc, const char * argv[]) { int hh,mm,ss; //cout<<setfill('0')<<setw(2)<<1; cin>>hh>>mm>>ss; MyTime* t1=new MyTime(); MyTime* t2=new MyTime(8,10,30); t1->print_12(); t1->print_24(); t2->print_12(); t2->print_24(); t1->SetTime(hh,mm,ss); cin>>hh>>mm>>ss; MyTime* origin=new MyTime(hh,mm,ss); (t1+origin)->print_12(); (t1+origin)->print_24(); (t2-origin)->print_12(); (t2-origin)->print_24(); return 0; }
C
UTF-8
575
2.953125
3
[ "MIT" ]
permissive
// // Created by James Miles on 31/08/2021. // #include <sys/socket.h> #include <netdb.h> #include <printf.h> int main() { int s; struct addrinfo hints, *res; // do the lookup - assume that 'hints' has already been filled in getaddrinfo("www.example.com", "http", &hints, &res); // you should do error checking when you run getaddrinfo() and walk the res linked-list // you should be checking for valid entries instead of just assuming the first is good s = socket(res -> ai_family, res -> ai_socktype, res -> ai_protocol); printf("%i", s); }
Java
UTF-8
1,238
2.75
3
[]
no_license
package client.client.modele.entite; import java.util.Objects; public class User { private String id; private String pseudo; private String pwd; public User() { } public User(String pseudo, String password) { this.pseudo = pseudo; this.pwd = password; } public User(String id, String pseudo, String pwd) { this.id = id; this.pseudo = pseudo; this.pwd = pwd; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPwd() { return pwd; } public void setPwd(String password) { this.pwd = password; } public String getPseudo() { return pseudo; } public void setPseudo(String pseudo) { this.pseudo = pseudo; } @Override public String toString() { return pseudo; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return pseudo.equals(user.pseudo); } @Override public int hashCode() { return Objects.hash(pseudo); } }
Python
UTF-8
106,040
2.515625
3
[]
no_license
# -*- coding: utf-8 -*- # IMPORTANDO LIBRERIAS NECESARIAS from reportlab.platypus import Paragraph from reportlab.platypus import Image from reportlab.platypus import SimpleDocTemplate, Image from reportlab.platypus import Spacer from reportlab.lib.styles import getSampleStyleSheet # -> Importa clase de hoja de estilo from reportlab.lib.pagesizes import A4,A3,letter,B2 from reportlab.lib import colors # -> Importa colores from reportlab.platypus import Table # -> Importa las funcionalidades para crear tablas from reportlab.lib.units import cm from reportlab.platypus import SimpleDocTemplate, Paragraph, TableStyle, PageBreak from reportlab.lib.styles import ParagraphStyle as PS from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT from reportlab.graphics.barcode import code39,code128 import arcpy import math EscudoNacional = r'D:\Dropbox\imagenes\Escudo_BN.png' LogoInei = r'D:\Dropbox\imagenes\Inei_BN.png' def contar_registros(rows,ini,rango): dato = ini while dato < rows: dato = dato + rango lista_ini = list(range(ini, dato - (rango - 1), rango)) lista_fin = list(range(ini + rango, dato + 1, rango)) lista_fin[-1] = rows final = zip(lista_ini, lista_fin) #print final return final # DECLARANDO LAS VARIABLES QUE CONTIENEN LA FUENTE DE INFORMACION def ListadoAEU(info , output,flag_desastre=0): cab=info[0] data =info[1] coddep = cab[0] departamento = cab[1] codprov = cab[2] provincia = cab[3] coddist = cab[4] distrito = cab[5] codccpp = cab[6] nomccpp = cab[7] catccpp = cab[8] zona = cab[9] subzona=cab[10] seccion = cab[11] aeus = cab[12] viviendas = cab[13] # CREACION DE PLANTILLA Plantilla = getSampleStyleSheet() # CREADO ESTILOS DE TEXTO h1 = PS( name = 'Heading1', fontSize = 7, leading = 8 ) h11 = PS( name = 'Heading1', fontSize = 7, leading = 8, alignment = TA_CENTER ) h111 = PS( name = 'Heading1', fontSize = 7, leading = 8, alignment = TA_RIGHT ) h3 = PS( name = 'Normal', fontSize = 6.5, leading = 10, alignment = TA_CENTER ) h4 = PS( name = 'Normal', fontSize = 7, leading = 10, alignment = TA_LEFT ) h5 = PS( name='Normal', fontSize=10, leading=10, alignment=TA_CENTER ) h6 = PS( name='Normal', fontSize=6, leading=5, alignment=TA_CENTER ) h_sub_tile = PS( name = 'Heading1', fontSize = 10, leading = 14, alignment = TA_CENTER ) h_sub_tile_2 = PS( name = 'Heading1', fontSize = 11, leading = 14, alignment = TA_CENTER ) # LISTA QUE CONTIENE LOS ELEMENTOS A GRAFICAR EN EL PDF Elementos = [] if flag_desastre==0: Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS <br/> III Censo de Comunidades Nativas y I Censo de Comunidades Campesinas',h_sub_tile) SubTitulo = Paragraph(u'<strong>LISTADO DE VIVIENDAS DEL AREA DE EMPADRONAMIENTO URBANO</strong>', h_sub_tile_2) else: Titulo = Paragraph(u'CENSOS DE LAS ÁREAS AFECTADAS POR EL<BR/>FENÓMENO DEL NIÑO COSTERO',h_sub_tile) SubTitulo = Paragraph(u'<strong>LISTADO DE VIVIENDAS DEL AREA DE EMPADRONAMIENTO </strong>', h_sub_tile_2) CabeceraPrincipal = [[ Titulo,'',''], [Image(EscudoNacional, width=50, height=50), SubTitulo, Image(LogoInei, width=55, height=50)]] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (2, 0)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0,10)) if (flag_desastre)==0: Filas = [ ['', '', '', '', Paragraph('<b>Doc.CPV.03.20</b>', h111),''], [ Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>',h11), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>',h11), ''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '', Paragraph(u'<b>ZONA Nº</b>', h1),u'{}'.format(zona), Paragraph(u'<b>SUB ZONA</b>', h1),u'{}'.format(subzona)], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SECCIÓN Nº</b>', h1), '',u'{}'.format(seccion),'' ], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', Paragraph(u'<b>A.E.U. Nº</b>', h1),'', u'{}'.format(aeus),''], [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', '','',''], [Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'{}'.format(catccpp), '', '',Paragraph(u'<b>TOTAL DE VIVIENDAS<br/>DEL A.E.U.</b>', h1),'','{}'.format(viviendas),''] ] Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 8.1 * cm, 0.3 * cm, 2 * cm, 1.7 * cm, 2 * cm, 1 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.7 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (7, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 5), 'CENTER'), ('ALIGN', (5, 2), (5, 6), 'CENTER'), ('ALIGN', (6, 3), (7, 6), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -2), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, 6), 1, colors.black), ('GRID', (4, 1), (7, 4), 1, colors.black), ('GRID', (4, 6), (7, 6), 1, colors.black), ('SPAN', (4, 0), (7, 0)), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (4, 3), (5, 3)), ('SPAN', (4, 4), (5, 4)), ('SPAN', (4, 6), (5, 6)), ('SPAN', (6, 3), (7, 3)), ('SPAN', (6, 4), (7, 4)), ('SPAN', (6, 6), (7, 6)), ('SPAN', (1, 6), (2, 6)), ('BACKGROUND', (0, 1), (0, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (7, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 3), (5, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 6), (4, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (6, 2), (6, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)) ])) else: Filas = [ ['', '', '', '', '', '','',''], [Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h11), '', '', '',Paragraph(u'<b>B. UBICACIÓN CENSAL</b>', h11), '',''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '', Paragraph(u'<b>ZONA Nº</b>', h1),'', u'{}'.format(zona),''], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SECCIÓN Nº</b>', h1), '', u'{}'.format(seccion), ''], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', Paragraph(u'<b>A.E. Nº</b>', h1), '', u'{}'.format(aeus), ''], [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', '', '', ''], [Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'{}'.format(catccpp), '', '', Paragraph(u'<b>TOTAL DE VIVIENDAS/ESTABLECIMIENTOS DEL AE.</b>', h1), '', '{}'.format(viviendas), ''] ] Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 6.3 * cm, 0.3 * cm, 2 * cm, 1.7 * cm, 2 * cm, 1 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.7 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (7, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 5), 'CENTER'), ('ALIGN', (5, 2), (5, 6), 'CENTER'), ('ALIGN', (6, 2), (7, 6), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -2), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, 6), 1, colors.black), ('GRID', (4, 1), (7, 4), 1, colors.black), ('GRID', (4, 6), (7, 6), 1, colors.black), ('SPAN', (4, 0), (7, 0)), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (4, 2), (5, 2)), ('SPAN', (4, 3), (5, 3)), ('SPAN', (4, 4), (5, 4)), ('SPAN', (4, 6), (5, 6)), ('SPAN', (6, 2), (7, 2)), ('SPAN', (6, 3), (7, 3)), ('SPAN', (6, 4), (7, 4)), ('SPAN', (6, 6), (7, 6)), ('SPAN', (1, 6), (2, 6)), ('BACKGROUND', (0, 1), (0, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (7, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 3), (5, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 6), (4, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla) Elementos.append(Spacer(0,10)) if flag_desastre==0: Filas2 = [ [Paragraph(e, h3) for e in [u"<strong>Viv Nº</strong>", u"<strong>Mz Nº</strong>", u"<strong>Frent Nº</strong>", u"<strong>DIRECCIÓN DE LA VIVIENDA</strong>", "", "", "", "", "", "", "", "", u"<strong>Nombres y Apellidos del<br/>JEFE DEL HOGAR</strong>"]], [Paragraph(e, h3) for e in ["", "", "", u"<strong>Tipo de Vía</strong>", u"<strong>Nombre de Vía</strong>", u"<strong>Nº de Puerta</strong>", u"<strong>Block</strong>", u"<strong>Mz Nº</strong>", u"<strong>Lote Nº</strong>", u"<strong>Piso Nº</strong>", u"<strong>Int. Nº</strong>", u"<strong>Km. Nº</strong>", ""]], [Paragraph(e, h3) for e in [u"<strong>(1)</strong>", u"<strong>(2)</strong>", u"<strong>(3)</strong>", u"<strong>(4)</strong>", u"<strong>(5)</strong>", u"<strong>(6)</strong>", u"<strong>(7)</strong>", u"<strong>(8)</strong>", u"<strong>(9)</strong>", u"<strong>(10)</strong>", u"<strong>(11)</strong>", u"<strong>(12)</strong>", u"<strong>(13)</strong>"]] ] Tabla2 = Table(Filas2, colWidths = [0.8 * cm, 0.8 * cm, 1 * cm, 1.2 * cm, 3.5 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 5.6 * cm]) Tabla2.setStyle(TableStyle([ ('GRID', (1, 1), (-2, -2), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (3, 0), (11, 0)), ('SPAN', (12,0), (12,1)), ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (13, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla2) nrows = len(data) if nrows > 19: HojaRegistros = contar_registros(nrows,19,26) HojaRegistros.append((0, 19)) HojaRegistros.sort(key = lambda n:n[0]) for rangos in HojaRegistros: for viv in (data)[rangos[0]:rangos[1]]: #for viv in ([x for x in arcpy.da.SearchCursor(VIV_fc, ListFields)])[rangos[0]:rangos[1]]: #for viv in ([x for x in arcpy.da.SearchCursor(VIV_fc, ListFields, "LLAVE_AEU = '{}'".format(identificador))])[rangos[0]:rangos[1]]: vivn = "" if str(viv[0])=="0" else str(viv[0]) mzinei = viv[1] idregord = viv[2] frente = viv[3] tvia = viv[4] nomvia = u"{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] kmn = viv[12] jefehogar = viv[13] registros = [[vivn, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, kmn, Paragraph(u'{}'.format(jefehogar), h4)]] RegistrosIngresados = Table(registros, colWidths = [0.8 * cm, 0.8 * cm, 1 * cm, 1.2 * cm, 3.5 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 5.6 * cm], rowHeights=[1 * cm]) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (12, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) Elementos.append(PageBreak()) Elementos.append(Tabla2) del Elementos[-1] del Elementos[-1] else: for viv in (data): #[x for x in arcpy.da.SearchCursor(VIV_fc, ListFields)]): #for viv in ([x for x in arcpy.da.SearchCursor(VIV_fc, ListFields, "LLAVE_AEU = '{}'".format(identificador))]): vivn = "" if str(viv[0])=="0" else str(viv[0]) mzinei = viv[1] idregord = viv[2] frente = viv[3] tvia = viv[4] nomvia = u"{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] kmn = viv[12] jefehogar = viv[13] registros = [[vivn, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso,interior, kmn, Paragraph(u'{}'.format(jefehogar), h4)]] RegistrosIngresados = Table(registros, colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.2 * cm, 3.5 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 5.6 * cm], rowHeights=[1 * cm]) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (12, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) if (nrows > 17): Elementos.append(PageBreak()) else: Filas2 = [ [Paragraph(e, h3) for e in [u"<strong>Viv Nº</strong>", u"<strong>Mz Nº</strong>", u"<strong>Frent Nº</strong>", u"<strong>DIRECCIÓN DE LA VIVIENDA</strong>", "", "", "", "", "", "", "", "", u"<strong>Nombres y Apellidos del<br/>JEFE DEL HOGAR</strong>",u"Viv. Afectada <br/>1.Si<br/>2.No"]], [Paragraph(e, h3) for e in ["", "", "", u"<strong>Tipo de Vía</strong>", u"<strong>Nombre de Vía</strong>", u"<strong>Nº de Puerta</strong>", u"<strong>Block</strong>", u"<strong>Mz Nº</strong>", u"<strong>Lote Nº</strong>", u"<strong>Piso Nº</strong>", u"<strong>Int. Nº</strong>", u"<strong>Km. Nº</strong>", "",""]], [Paragraph(e, h3) for e in [u"<strong>(1)</strong>", u"<strong>(2)</strong>", u"<strong>(3)</strong>", u"<strong>(4)</strong>", u"<strong>(5)</strong>", u"<strong>(6)</strong>", u"<strong>(7)</strong>", u"<strong>(8)</strong>", u"<strong>(9)</strong>", u"<strong>(10)</strong>", u"<strong>(11)</strong>", u"<strong>(12)</strong>", u"<strong>(13)</strong>", u"<strong>(14)</strong>"]] ] Tabla2 = Table(Filas2, colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.2 * cm, 3.5 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 4.6 * cm,1.5*cm]) Tabla2.setStyle(TableStyle([ ('GRID', (1, 1), (-2, -2), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (3, 0), (11, 0)), ('SPAN', (13,0), (13, 1)), ('SPAN', (12, 0), (12, 1)), ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (13, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla2) nrows = len(data) if nrows > 19: HojaRegistros = contar_registros(nrows, 19, 26) # print HojaRegistros HojaRegistros.append((0, 19)) HojaRegistros.sort(key=lambda n: n[0]) for rangos in HojaRegistros: for viv in (data)[rangos[0]:rangos[1]]: vivn = "" if str(viv[0]) == "0" else str(viv[0]) mzinei = viv[1] idregord = viv[2] frente = viv[3] tvia = viv[4] nomvia = "{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] kmn = viv[12] jefehogar = viv[13] registros = [ [vivn, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, kmn, Paragraph(u'{}'.format(jefehogar), h4),""]] RegistrosIngresados = Table(registros, colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.2 * cm, 3.5 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 4.6 * cm,1.5*cm], rowHeights=[1 * cm]) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (12, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) Elementos.append(PageBreak()) Elementos.append(Tabla2) cant_reg_ult_pag = HojaRegistros[-1][1] - HojaRegistros[-1][0] del Elementos[-1] if cant_reg_ult_pag < 24: del Elementos[-1] else: for viv in (data): vivn = "" if str(viv[0]) == "0" else str(viv[0]) mzinei = viv[1] idregord = viv[2] frente = viv[3] tvia = viv[4] nomvia = "{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] kmn = viv[12] jefehogar = viv[13] registros = [ [vivn, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, kmn, Paragraph(u'{}'.format(jefehogar), h4),""]] RegistrosIngresados = Table(registros, colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.2 * cm, 3.5 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 4.6 * cm,1.5*cm], rowHeights=[1 * cm]) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (12, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) if (nrows > 17): Elementos.append(PageBreak()) Elementos.append(Spacer(0, 10)) if flag_desastre==0: PiePagina = [[Paragraph(u'{}'.format("EMPADRONADOR"), h5)], [Paragraph('{}'.format("Todas las viviendas que estén dentro de los límites de tu A.E.U. deben ser empadronadas. Debes tener cuidado de no omitir ninguna vivienda"), h5)]] else: PiePagina = [[Paragraph(u'{}'.format("EMPADRONADOR"), h5)], [Paragraph('{}'.format( "Todas las viviendas que estén dentro de los límites de tu A.E. deben ser empadronadas. Debes tener cuidado de no omitir ninguna vivienda"), h5)]] Tabla_Pie = Table(PiePagina, colWidths = [20 * cm],rowHeights=[0.8 * cm,1.6* cm]) Tabla_Pie.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla_Pie) destino=output pdf = SimpleDocTemplate(destino, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm, ) pdf.build(Elementos) def ListadoSeccion(info, output): cab=info[0] data=info[1] coddep = cab[0] departamento = cab[1] codprov = cab[2] provincia = cab[3] coddist = cab[4] distrito = cab[5] codccpp = cab[6] nomccpp = cab[7] catccpp = cab[8] zona = cab[9] subzona = cab[10] seccion = cab[11] aeus=cab[12] viviendas = cab[13] Plantilla = getSampleStyleSheet() # CREADO ESTILOS DE TEXTO h1 = PS( name='Heading1', fontSize=7, leading=8 ) h11 = PS( name = 'Heading1', fontSize = 7, leading = 8, alignment = TA_CENTER ) h111 = PS( name = 'Heading1', fontSize = 7, leading = 8, alignment = TA_RIGHT ) h3 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=7, leading=10, alignment=TA_LEFT ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) # LISTA QUE CONTIENE LOS ELEMENTOS A GRAFICAR EN EL PDF Elementos = [] Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS <br/> III Censo de Comunidades Nativas y I Censo de Comunidades Campesinas',h_sub_tile) SubTitulo = Paragraph(u'<strong>LISTADO DE LA SECCIÓN CENSAL URBANA POR ÁREAS DE EMPADRONAMIENTO, MANZANAS Y VIVIENDAS</strong>', h_sub_tile_2) CabeceraPrincipal = [[Titulo,'',''], [Image(EscudoNacional, width=50, height=50), SubTitulo, Image(LogoInei, width=55, height=50)]] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (2, 0)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0, 10)) # CREACION DE LAS TABLAS PARA LA ORGANIZACION DEL TEXTO # Se debe cargar la informacion en aquellos espacios donde se encuentra el texto 'R' Filas = [ ['', '', '', '', Paragraph('<b>Doc.CPV.03.206</b>', h111),''], [ Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>',h11), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>',h11), ''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '', Paragraph(u'<b>ZONA Nº</b>', h1),u'{}'.format(zona), Paragraph(u'<b>SUB ZONA</b>', h1),u'{}'.format(subzona)], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SECCIÓN Nº</b>', h1), '',u'{}'.format(seccion),'' ], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', Paragraph(u'<b>A.E.U. Nº</b>', h1),'', u'{}'.format(aeus),''], [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', '','',''], [Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'{}'.format(catccpp), '', '',Paragraph(u'<b>C. TOTAL DE VIVIENDAS<br/>DE LA SECCION</b>', h1),'','{}'.format(viviendas),''] ] Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 6.3 * cm, 0.3 * cm, 2 * cm, 1.7 * cm, 2 * cm, 1 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.7 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (7, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 5), 'CENTER'), ('ALIGN', (5, 2), (5, 6), 'CENTER'), ('ALIGN', (6, 3), (7, 6), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -2), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, 6), 1, colors.black), ('GRID', (4, 1), (7, 4), 1, colors.black), ('GRID', (4, 6), (7, 6), 1, colors.black), ('SPAN', (4, 0), (7, 0)), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (4, 3), (5, 3)), ('SPAN', (4, 4), (5, 4)), ('SPAN', (4, 6), (5, 6)), ('SPAN', (6, 3), (7, 3)), ('SPAN', (6, 4), (7, 4)), ('SPAN', (6, 6), (7, 6)), ('SPAN', (1, 6), (2, 6)), ('BACKGROUND', (0, 1), (0, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (7, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 3), (5, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 6), (4, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (6, 2), (6, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)) ])) # AGREGANDO LAS TABLAS A LA LISTA DE ELEMENTOS DEL PDF Elementos.append(Tabla) Elementos.append(Spacer(0, 10)) # CABECERA N° 2 CabeceraSecundaria = [ [Paragraph(e, h3) for e in [u"<strong> D. INFORMACIÓN DE LA SECCIÓN CENSAL URBANA</strong>", "", "", ]], [Paragraph(e, h3) for e in [u"<strong>A.E.U. Nº</strong>", u"<strong>MANZANA Nº</strong>", u"<strong>Nº DE VIVIENDAS POR A.E.U.</strong>"]] ] Tabla1 = Table(CabeceraSecundaria, colWidths=[4 * cm, 10* cm, 4 * cm]) Tabla1.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, -1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (2, 0)) ] )) Elementos.append(Tabla1) # CUERPO QUE CONTIENE LOS LA INFORMACION A MOSTRAR for el in data: aeu=el[0] manzanas=el[1] viviendas_aeu=el[2] Registros = [[Paragraph(e, h3) for e in [ u'{}'.format(aeu).zfill(3), u'{}'.format(manzanas), u'{}'.format(viviendas_aeu)]]] Tabla2 = Table(Registros, colWidths=[4 * cm, 10* cm, 4 * cm]) Tabla2.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER') ])) Elementos.append(Tabla2) pdf = SimpleDocTemplate(output, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm, ) pdf.build(Elementos) def ListadoZona(informacion, output,flag_desastre=0): cab=informacion[0] data = informacion[1] resumen= informacion[2] coddep = cab[0] departamento = cab[1] codprov = cab[2] provincia = cab[3] coddist = cab[4] distrito = cab[5] codccpp = cab[6] nomccpp = cab[7] catccpp = cab[8] zona = cab[9] subzona = cab[10] secciones=cab[11] aeus=cab[12] viviendas = cab[13] cant_secc = resumen[0] cant_mzs = resumen[1] cat_aeus = resumen[2] Plantilla = getSampleStyleSheet() h1 = PS( name='Heading1', fontSize=7, leading=8 ) h11 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER ) h111 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_RIGHT ) h3 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=7, leading=10, alignment=TA_LEFT ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) Elementos = [] if flag_desastre==0: Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS <br/> III Censo de Comunidades Nativas y I Censo de Comunidades Campesinas',h_sub_tile) SubTitulo = Paragraph(u'<strong>LISTADO DE LA ZONA CENSAL POR SECCIONES Y ÁREAS DE EMPADRONAMIENTO URBANO</strong>', h_sub_tile_2) else: Titulo = Paragraph(u'CENSOS DE LAS ÁREAS AFECTADAS POR EL<BR/>FENÓMENO DEL NIÑO COSTERO', h_sub_tile) SubTitulo = Paragraph(u'<strong>LISTADO DE LA ZONA CENSAL POR SECCIONES Y ÁREAS DE EMPADRONAMIENTO</strong>', h_sub_tile_2) CabeceraPrincipal = [[Titulo,'',''], [Image(EscudoNacional, width=50, height=50), SubTitulo, Image(LogoInei, width=55, height=50)]] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (2, 0)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0, 10)) if flag_desastre==0: Filas = [ ['', '', '', '', Paragraph('<b>Doc.CPV.03.204</b>', h111),''], [ Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>',h11), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>',h11), ''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '', Paragraph(u'<b>ZONA Nº</b>', h1),u'{}'.format(zona), Paragraph(u'<b>SUB ZONA</b>', h1),u'{}'.format(subzona)], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SECCIÓN Nº</b>', h1), '',u'{}'.format(secciones),'' ], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', Paragraph(u'<b>A.E.U. Nº</b>', h1),'', u'{}'.format(aeus),''], [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', '','',''], [Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'{}'.format(catccpp), '', '',Paragraph(u'<b>TOTAL DE VIVIENDAS<br/>DE LA ZONA</b>', h1),'','{}'.format(viviendas),''] ] Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 6.3 * cm, 0.3 * cm, 2 * cm, 1.7 * cm, 2 * cm, 1 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.7 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (7, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 5), 'CENTER'), ('ALIGN', (5, 2), (5, 6), 'CENTER'), ('ALIGN', (6, 3), (7, 6), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -2), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, 6), 1, colors.black), ('GRID', (4, 1), (7, 4), 1, colors.black), ('GRID', (4, 6), (7, 6), 1, colors.black), ('SPAN', (4, 0), (7, 0)), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (4, 3), (5, 3)), ('SPAN', (4, 4), (5, 4)), ('SPAN', (4, 6), (5, 6)), ('SPAN', (6, 3), (7, 3)), ('SPAN', (6, 4), (7, 4)), ('SPAN', (6, 6), (7, 6)), ('SPAN', (1, 6), (2, 6)), ('BACKGROUND', (0, 1), (0, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (7, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 3), (5, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 6), (4, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (6, 2), (6, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)) ])) else: Filas = [ ['', '', '', '', '', ''], [Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h11), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>', h11), ''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '', Paragraph(u'<b>ZONA Nº</b>', h1),'', u'{}'.format(zona),''], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SECCIÓN Nº</b>', h1), '', u'{}'.format(secciones), ''], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', Paragraph(u'<b>A.E. Nº</b>', h1), '', u'{}'.format(aeus), ''], [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', '', '', ''], [Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'{}'.format(catccpp), '', '', Paragraph(u'<b>TOTAL DE VIVIENDAS/ESTABLECIMIENTOS DE LA ZONA</b>', h1), '', '{}'.format(viviendas), ''] ] Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 6.3 * cm, 0.3 * cm, 2 * cm, 1.7 * cm, 2 * cm, 1 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.7 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (7, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 5), 'CENTER'), ('ALIGN', (5, 2), (5, 6), 'CENTER'), ('ALIGN', (6, 2), (7, 6), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -2), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, 6), 1, colors.black), ('GRID', (4, 1), (7, 4), 1, colors.black), ('GRID', (4, 6), (7, 6), 1, colors.black), ('SPAN', (4, 0), (7, 0)), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (7, 1)), ('SPAN', (4, 2), (5, 2)), ('SPAN', (4, 3), (5, 3)), ('SPAN', (4, 4), (5, 4)), ('SPAN', (4, 6), (5, 6)), ('SPAN', (6, 2), (7, 2)), ('SPAN', (6, 3), (7, 3)), ('SPAN', (6, 4), (7, 4)), ('SPAN', (6, 6), (7, 6)), ('SPAN', (1, 6), (2, 6)), ('BACKGROUND', (0, 1), (0, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (7, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 3), (5, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 6), (4, 6), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla) Elementos.append(Spacer(0, 10)) if flag_desastre==0: CabeceraSecundaria = [ [Paragraph(e, h3) for e in [u"<strong> C. INFORMACIÓN DE LA SECCIÓN CENSAL URBANA</strong>", "", "",""]], [Paragraph(e, h3) for e in [u"<strong>SECCIÓN Nº</strong>",u"<strong>A.E.U. Nº</strong>", u"<strong>MANZANA Nº</strong>", u"<strong>Nº DE VIVIENDAS POR A.E.U.</strong>"]] ] else: CabeceraSecundaria = [ [Paragraph(e, h3) for e in [u"<strong> D. INFORMACIÓN DE LA ZONA CENSAL </strong>", "", "", ""]], [Paragraph(e, h3) for e in [u"<strong>SECCIÓN Nº</strong>", u"<strong>A.E. Nº</strong>", u"<strong>MANZANA Nº</strong>", u"<strong>Nº DE VIVIENDAS POR A.E.</strong>"]] ] columnas= [2 * cm, 2 * cm, 10.5 * cm, 3.5 * cm] Tabla1 = Table(CabeceraSecundaria, colWidths=columnas) Tabla1.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, -1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (3, 0)) ] )) Elementos.append(Tabla1) #ListFields=["SECCION","AEU", "CANT_VIV"] #nrows = len([x[0] for x in arcpy.da.SearchCursor(data, ListFields)]) nrows = len(data) p=35 contador_lineas=0 n_hoja=1 if nrows > p: contador_lineas = 1 for x in data: seccion = x[0] aeus = x[1] manzanas=x[2] viviendas_aeu = x[3] Registros = [ [Paragraph(e, h3) for e in [u'{}'.format(seccion), u'{}'.format(aeus), u'{}'.format(manzanas), u'{}'.format(viviendas_aeu)]] ] Tabla2 = Table(Registros, colWidths=columnas) Tabla2.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER') ])) tam_mzs=len(manzanas) lineas=tam_mzs/60.0 cant_lineas=math.ceil(lineas) contador_lineas=cant_lineas+contador_lineas Elementos.append(Tabla2) if n_hoja==1: if contador_lineas>35: n_hoja=n_hoja+1 Elementos.append(PageBreak()) Elementos.append(Tabla1) contador_lineas=1 else: if contador_lineas >47: n_hoja = n_hoja + 1 Elementos.append(PageBreak()) Elementos.append(Tabla1) contador_lineas = 1 #HojaRegistros = contar_registros(nrows, p, 47) #HojaRegistros.append((0, p)) #HojaRegistros.sort(key=lambda n: n[0]) # #for rangos in HojaRegistros: # for x in data[rangos[0]:rangos[1]]: # seccion=x[0] # aeus = x[1] # manzanas=x[2] # viviendas_aeu = x[3] # # Registros = [ # [Paragraph(e, h3) for e in # [u'{}'.format(seccion), u'{}'.format(aeus), u'{}'.format(manzanas), u'{}'.format(viviendas_aeu)]] # ] # # Tabla2 = Table(Registros, colWidths=columnas) # # Tabla2.setStyle(TableStyle([ # ('GRID', (0, 0), (-1, -1), 1, colors.black), # ('FONTSIZE', (0, 0), (-1, -1), 7), # ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # ('ALIGN', (0, 0), (-1, -1), 'CENTER') # ])) # # # Elementos.append(Tabla2) # # Elementos.append(PageBreak()) # Elementos.append(Tabla1) # #cant_reg_ult_pag=HojaRegistros[-1][1]-HojaRegistros[-1][0] #del Elementos[-1] #if cant_reg_ult_pag<43: # del Elementos[-1] else: for x in data: seccion = x[0] aeus = x[1] manzanas = x[2] viviendas_aeu = x[3] registros = [ [Paragraph(e, h3) for e in [u'{}'.format(seccion), u'{}'.format(aeus), u'{}'.format(manzanas), u'{}'.format(viviendas_aeu)]] ] Tabla2 = Table(registros, colWidths=columnas) Tabla2.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER') ])) Elementos.append(Tabla2) if (nrows > 33): Elementos.append(PageBreak()) Elementos.append(Spacer(0, 10)) if flag_desastre==0: FilasPiePagina = [ [Paragraph(u'{}'.format(u"<strong>D. RESUMEN DE LA ZONA</strong>"),h3),''], [Paragraph(u'{}'.format(u"<strong>TOTAL DE SECCIONES</strong>"),h1),u'{}'.format(cant_secc)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE MANZANAS</strong>"),h1), u'{}'.format(cant_mzs)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE AEUS</strong>"),h1), u'{}'.format(cat_aeus)] ] else: FilasPiePagina = [ [Paragraph(u'{}'.format(u"<strong>E. RESUMEN DE LA ZONA</strong>"), h3), ''], [Paragraph(u'{}'.format(u"<strong>TOTAL DE SECCIONES</strong>"), h1),u'{}'.format(cant_secc)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE MANZANAS</strong>"), h1), u'{}'.format(cant_mzs)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE ÁREAS DE EMPADRONAMIENTO</strong>"), h1), u'{}'.format(cat_aeus)] ] Tabla_Pie = Table(FilasPiePagina, colWidths=[6*cm,3.4 * cm], rowHeights=[0.5 * cm,0.5 * cm,0.5 * cm,0.5 * cm]) Tabla_Pie.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (0, 1), (0, 3), 'LEFT'), ('ALIGN', (1, 1), (1, 3), 'RIGHT'), ('ALIGN', (0, 0), (1, 0), 'CENTER'), ('SPAN', (0, 0), (1,0)), ('BACKGROUND', (0, 0), (0, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla_Pie) # SE DETERMINAN LAS CARACTERISTICAS DEL PDF (RUTA DE ALMACENAJE, TAMAÑO DE LA HOJA, ETC) pdf = SimpleDocTemplate(output, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm,) # GENERACION DEL PDF FISICO pdf.build(Elementos) def ListadoDistrito(informacion,output): cab=informacion[0] data=informacion[1] resumen = informacion[2] ubigeo=cab[0] coddep=cab[1] departamento=cab[2] codprov=cab[3] provincia=cab[4] coddist = cab[5] distrito = cab[6] dist_ope=cab[7] cant_zonas=resumen[1] cant_secc = resumen[2] cant_aeus = resumen[3] cant_mzs=resumen[4] cant_viv = resumen[5] Plantilla = getSampleStyleSheet() h_codigo = PS( name='Codigo', fontSize=8, alignment=TA_RIGHT ) h1 = PS( name='Heading1', fontSize=7, leading=8 ) h11 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER ) h111 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_RIGHT ) h3 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=7, leading=10, alignment=TA_LEFT ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) # LISTA QUE CONTIENE LOS ELEMENTOS A GRAFICAR EN EL PDF Elementos = [] # AGREGANDO IMAGENES, TITULOS Y SUBTITULOS print ubigeo barcode = code128.Code128(u'{}'.format(ubigeo)) Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS <br/> III Censo de Comunidades Nativas y I Censo de Comunidades Campesinas', h_sub_tile) SubTitulo = Paragraph(u'<strong>MARCO DE ZONAS, SECCIONES CENSALES, ÁREAS DE EMPADRONAMIENTO URBANO, MANZANAS Y VIVIENDAS DEL DISTRITO/DISTRITO OPERATIVO </strong>',h_sub_tile_2) CabeceraPrincipal = [ [barcode,'',''], [Image(EscudoNacional, width=50, height=50), Titulo, Image(LogoInei, width=55, height=50)], ['', SubTitulo, ''] ] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm] ) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('ALIGN', (0, 0), (2, 0), 'RIGHT'), ('SPAN', (0, 0), (2, 0)), ('SPAN', (0, 1), (0, 2)), ('SPAN', (2, 1), (2, 2)), ('ALIGN', (0, 1), (-1, -1), 'CENTER'), ('VALIGN', (0, 1), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0, 10)) # CREACION DE LAS TABLAS PARA LA ORGANIZACION DEL TEXTO # Se debe cargar la informacion en aquellos espacios donde se encuentra el texto 'R' Filas = [ [Paragraph(u'<b>Doc.CPV.03.159</b>', h111),'','' ,'',''], [Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h11), '', '','',''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento),'',''], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia),'',''], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito),Paragraph(u'<b>DISTRITO OPERATIVO CENSAL</b>', h1), u'{}'.format(dist_ope)], ] # Permite el ajuste del ancho de la tabla Tabla = Table(Filas, colWidths=[3.6 * cm, 1 * cm, 4.5 * cm,5.2 * cm,4.5 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (2, 0), colors.black), ('ALIGN', (0, 0), (4, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 4), 'CENTER'), ('VALIGN', (0, 0), (4, 4), 'MIDDLE'), ('GRID', (0, 1), (4, 4), 1, colors.black), ('SPAN', (0, 0), (4, 0)), ('SPAN', (0, 1), (4, 1)), ('SPAN', (2, 2), (4, 2)), ('SPAN', (2, 3), (4, 3)), ('FONTSIZE', (1, 1), (4, 4), 8), ('BACKGROUND', (0, 1), (0, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (4, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (3, 4), (3,4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla) Elementos.append(Spacer(0, 10)) CabeceraSecundaria = [ [Paragraph(e, h3) for e in [u"<strong> B. INFORMACIÓN DE LA ZONA CENSAL</strong>", "", "","","","",""]], [Paragraph(e, h3) for e in [u"<strong>NOMBRE DEL CENTRO POBLADO</strong>",u"<strong>ZONA Nº</strong>",u"<strong>SUBZONA Nº</strong>",u"<strong>SECCIÓN Nº</strong>",u"<strong>A.E.U. Nº</strong>", u"<strong>MANZANA Nº</strong>",u"<strong>Nº DE VIVIENDAS </strong>"]], [Paragraph(e, h3) for e in [u"<strong>(1)</strong>", u"<strong>(2)</strong>", u"<strong>(3)</strong>",u"<strong>(4)</strong>",u"<strong>(5)</strong>",u"<strong>(6)</strong>",u"<strong>(7)</strong>"]], ] Tabla1 = Table(CabeceraSecundaria, colWidths=[5*cm,1.8*cm,1.8*cm, 1.8*cm, 1.8*cm,4.8*cm,1.8*cm], rowHeights=[0.5 * cm,1 * cm,0.5 * cm]) Tabla1.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, -1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (6, 0)) ] )) Elementos.append(Tabla1) nrows = len(data) # CUERPO QUE CONTIENE LOS LA INFORMACION A MOSTRAR if nrows > 38: ##### funcion contar_registros(cantidad_total_registros, cantidad_registros_pagina inicial,cantidad_registros_paginas_siguientes) HojaRegistros = contar_registros(nrows, 38, 52) HojaRegistros.append((0, 38)) HojaRegistros.sort(key=lambda n: n[0]) for rangos in HojaRegistros: for aeu in ([ (x[0],x[1],x[2],x[3],x[4],x[5],x[6]) for x in data])[rangos[0]:rangos[1]]: nomccpp=aeu[0] zona=aeu[1] subzona=aeu[2] seccion=aeu[3] aeus = aeu[4] manzanas = aeu[5] viviendas_aeu = aeu[6] Registros = [ [u'{}'.format(nomccpp),u'{}'.format(zona),u'{}'.format(subzona),u'{}'.format(seccion),u'{}'.format(aeus), u'{}'.format(manzanas), u'{}'.format(viviendas_aeu)] ] Tabla2 = Table(Registros, colWidths=[5*cm,1.8*cm,1.8*cm, 1.8*cm, 1.8*cm,4.8*cm,1.8*cm], rowHeights=[0.5 * cm]) Tabla2.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER') ])) Elementos.append(Tabla2) Elementos.append(PageBreak()) Elementos.append(Tabla1) cant_reg_ult_pag=HojaRegistros[-1][1]-HojaRegistros[-1][0] del Elementos[-1] if cant_reg_ult_pag<49: del Elementos[-1] else: for aeu in ([(x[0],x[1],x[2],x[3],x[4],x[5],x[6]) for x in data]): nomccpp=aeu[0] zona = aeu[1] subzona = aeu[2] seccion = aeu[3] aeus = aeu[4] manzanas = aeu[5] viviendas_aeu = aeu[6] Registros = [[u'{}'.format(nomccpp),u'{}'.format(zona), u'{}'.format(subzona), u'{}'.format(seccion), u'{}'.format(aeus),u'{}'.format(manzanas), u'{}'.format(viviendas_aeu)]] Tabla2 = Table(Registros, colWidths=[5*cm,1.8*cm,1.8*cm, 1.8*cm, 1.8*cm,4.8*cm,1.8*cm], rowHeights=[0.5 * cm]) Tabla2.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER') ])) Elementos.append(Tabla2) if (nrows > 34): Elementos.append(PageBreak()) Elementos.append(Spacer(0, 10)) FilasPiePagina = [ [Paragraph(u'{}'.format(u"<strong>C. RESUMEN DEL DISTRITO</strong>"),h3),''], [Paragraph(u'{}'.format(u"<strong>TOTAL DE ZONAS / SUBZONAS</strong>"), h1), u'{}'.format(cant_zonas)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE SECCIONES</strong>"),h1),u'{}'.format(cant_secc)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE AEUS</strong>"),h1), u'{}'.format(cant_aeus)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE MANZANAS</strong>"), h1), u'{}'.format(cant_mzs)], [Paragraph(u'{}'.format(u"<strong>TOTAL DE VIVIENDAS</strong>"), h1), u'{}'.format(cant_viv)] ] Tabla_Pie = Table(FilasPiePagina, colWidths=[6*cm,3.4 * cm], rowHeights=6*[0.5 * cm]) Tabla_Pie.setStyle(TableStyle([ ('GRID', (0, 0), (1, 5), 1, colors.black), ('ALIGN', (0, 1), (0, 5), 'LEFT'), ('ALIGN', (1, 1), (1, 5), 'RIGHT'), ('ALIGN', (0, 0), (1, 0), 'CENTER'), ('SPAN', (0, 0), (1,0)), ('BACKGROUND', (0, 0), (0, 5), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (0, 0), (0, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (0, 0), (1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla_Pie) # SE DETERMINAN LAS CARACTERISTICAS DEL PDF (RUTA DE ALMACENAJE, TAMAÑO DE LA HOJA, ETC) pdf = SimpleDocTemplate(output, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm,) # GENERACION DEL PDF FISICO pdf.build(Elementos) def ListadoViviendasDesocupadas(SECCION_fc,VIV_fc,output): coddep = SECCION_fc[0] departamento = SECCION_fc[1] codprov = SECCION_fc[2] provincia = SECCION_fc[3] coddist = SECCION_fc[4] distrito = SECCION_fc[5] #codccpp = SECCION_fc[6] #nomccpp = SECCION_fc[7] #catccpp = SECCION_fc[8] zona = SECCION_fc[9] seccion = SECCION_fc[10] #aeuini = SECCION_fc[11] #aeufin = SECCION_fc[12] #viviendas = SECCION_fc[13] # CREACION DE PLANTILLA Plantilla = getSampleStyleSheet() # CREADO ESTILOS DE TEXTO h1 = PS( name = 'Heading1', fontSize = 7, leading = 8 ) h11 = PS( name = 'Heading1', fontSize = 7, leading = 8, alignment = TA_CENTER ) h3 = PS( name = 'Normal', fontSize = 6.5, leading = 10, alignment = TA_CENTER ) h4 = PS( name = 'Normal', fontSize = 7, leading = 10, alignment = TA_LEFT ) h5 = PS( name='Normal', fontSize=12, leading=10, alignment=TA_CENTER ) h_sub_tile = PS( name = 'Heading1', fontSize = 10, leading = 14, alignment = TA_CENTER ) h_sub_tile_2 = PS( name = 'Heading1', fontSize = 11, leading = 14, alignment = TA_CENTER ) # LISTA QUE CONTIENE LOS ELEMENTOS A GRAFICAR EN EL PDF Elementos = [] # AGREGANDO IMAGENES, TITULOS Y SUBTITULOS Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA<br/>Y III DE COMUNIDADES INDÍGENAS',h_sub_tile) SubTitulo = Paragraph(u'<strong>LISTADO DE VIVIENDAS DESOCUPADAS</strong>', h_sub_tile_2) CabeceraPrincipal = [[Image(EscudoNacional, width=50, height=50), Titulo, Image(LogoInei, width=55, height=50)], ['', SubTitulo, '']] Tabla0 = Table(CabeceraPrincipal, colWidths = [2 * cm, 14 * cm, 2 * cm]) Tabla0.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (0, 1)), ('SPAN', (2, 0), (2, 1)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0,10)) # CREACION DE LAS TABLAS PARA LA ORGANIZACION DEL TEXTO # Se debe cargar la informacion en aquellos espacios donde se encuentra el texto 'R' Filas = [ ['', '', '', '', '', Paragraph('<b>Doc. CPV</b>', h1)], [Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h1), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>', h1), ''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '', Paragraph(u'<b>ZONA Nº</b>', h1),u'{}'.format(zona)], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SECCIÓN Nº</b>', h1), u'{}'.format(seccion )], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', '', ''], #[Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', ''], #[Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'{}'.format(catccpp), '', '', Paragraph(u'<b>TOTAL DE VIVIENDAS<br/>DEL A.E.U.</b>', h1),'{}'.format(viviendas)] ] # Permite el ajuste del ancho de la tabla Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 8.1 * cm, 0.3 * cm, 4.7 * cm, 2 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm ]) # Se cargan los estilos, como bordes, alineaciones, fondos, etc Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (5, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 4), 'CENTER'), ('ALIGN', (5, 2), (5, 4), 'CENTER'), ('VALIGN', (0, 0), (5,4 ), 'MIDDLE'), ('FONTSIZE', (0, 0), (5, 4), 8), ('GRID', (0, 1), (2, 4), 1, colors.black), ('GRID', (4, 1), (5, 4), 1, colors.black), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (5, 1)), ('BACKGROUND', (0, 1), (0, 4), colors.Color(220.0/255,220.0/255,220.0/255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0/255,220.0/255,220.0/255)), ('BACKGROUND', (4, 1), (5, 1), colors.Color(220.0/255,220.0/255,220.0/255)), ('BACKGROUND', (4, 1), (4, 4), colors.Color(220.0/255,220.0/255,220.0/255)), #('BACKGROUND', (0, 1), (0, 4), colors.Color(220.0/255,220.0/255,220.0/255)), #('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0/255,220.0/255,220.0/255)), #('BACKGROUND', (4, 1), (5, 1), colors.Color(220.0/255,220.0/255,220.0/255)), #('BACKGROUND', (4, 1), (4, 4), colors.Color(220.0/255,220.0/255,220.0/255)), ])) # AGREGANDO LAS TABLAS A LA LISTA DE ELEMENTOS DEL PDF Elementos.append(Tabla) Elementos.append(Spacer(0,10)) # AGREGANDO CABECERA N 2 Filas2 = [ [Paragraph(e, h3) for e in [u"<strong>Mz Nº</strong>", u"<strong>Frent N°</strong>", u"<strong>AEU</strong>", u"<strong>Ord Reg</strong>", u"<strong>DIRECCIÓN DE LA VIVIENDA</strong>", "", "", "", "", "", "", "", "", u"<strong>CONDICIÓN</strong>"]], [Paragraph(e, h3) for e in ["", "", "", "", u"<strong>Tipo de Vía</strong>", u"<strong>Nombre de Vía</strong>", u"<strong>Nº de Puerta</strong>", u"<strong>Block</strong>", u"<strong>Mz Nº</strong>", u"<strong>Lote Nº</strong>", u"<strong>Piso Nº</strong>", u"<strong>Int. Nº</strong>", u"<strong>Km. Nº</strong>", ""]], [Paragraph(e, h3) for e in [u"<strong>(1)</strong>", u"<strong>(2)</strong>", u"<strong>(3)</strong>", u"<strong>(4)</strong>", u"<strong>(5)</strong>", "<strong>(6)</strong>", u"<strong>(7)</strong>", u"<strong>(8)</strong>", u"<strong>(9)</strong>", u"<strong>(10)</strong>", u"<strong>(11)</strong>", u"<strong>(12)</strong>", u"<strong>(13)</strong>", u"<strong>(14)</strong>"]] ] Tabla2 = Table(Filas2, colWidths = [0.8 * cm, 0.8 * cm, 0.90 * cm, 1 * cm, 1.2 * cm, 4.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 3.6 * cm]) Tabla2.setStyle(TableStyle([ ('GRID', (1, 1), (-2, -2), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (0, 0), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (4, 0), (12, 0)), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (3, 0), (3, 1)), ('SPAN', (13, 0), (13, 1)), ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (13, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (0, 0), (13, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) Elementos.append(Tabla2) #ListFields = [field.name for field in arcpy.ListFields(VIV_fc)] ListFields = [ "MANZANA", "FRENTE_ORD","AEU" , "ID_REG_OR","P20", "P21", "P22_A", "P22_B", "P23", "P24","P25", "P26", "P27_A", "P28", "P30"] nrows = len([x[0] for x in arcpy.da.SearchCursor(VIV_fc, ["AEU"])]) print nrows if nrows > 20: HojaRegistros = contar_registros(nrows,20,26) HojaRegistros.append((0, 20)) HojaRegistros.sort(key = lambda n:n[0]) for rangos in HojaRegistros: for viv in ([x for x in arcpy.da.SearchCursor(VIV_fc, ListFields)])[rangos[0]:rangos[1]]: vivn = "" if str(viv[0])=="0" else str(viv[0]) mzinei = viv[1] idregord = viv[2] frente = viv[3] tvia = viv[4] nomvia = "{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[8] mzmuni = viv[9] lote = viv[10] piso = viv[11] interior = viv[12] kmn = viv[13] if int(viv[14]) == 3: condicion = u"En alquiler o venta" if int(viv[14]) == 4: condicion = u"En construcción o reparación" if int(viv[14]) == 5: condicion = u"Abandonada o cerrada" if int(viv[14]) == 6: condicion = u"Otra causa" registros = [[vivn, mzinei, idregord, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, kmn, Paragraph(u'{}'.format(condicion), h4)]] RegistrosIngresados = Table(registros, colWidths = [0.8 * cm, 0.8 * cm, 0.90 * cm, 1 * cm, 1.2 * cm, 4.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 3.6 * cm], rowHeights=[1 * cm]) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (12, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) Elementos.append(PageBreak()) Elementos.append(Tabla2) del Elementos[-1] del Elementos[-1] else: for viv in ( [x for x in arcpy.da.SearchCursor(VIV_fc, ListFields)]): #for viv in ([x for x in arcpy.da.SearchCursor(VIV_fc, ListFields, "LLAVE_AEU = '{}'".format(identificador))]): vivn = "" if str(viv[0])=="0" else str(viv[0]) mzinei = viv[1] idregord = viv[2] frente = viv[3] tvia = viv[4] nomvia = "{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[8] mzmuni = viv[9] lote = viv[10] piso = viv[11] interior = viv[12] kmn = viv[13] if int(viv[14])==3: condicion = u"En alquiler o venta" if int(viv[14])==4: condicion = u"En construcción o reparación" if int(viv[14])==5: condicion = u"Abandonada o cerrada" if int(viv[14])==6: condicion = u"Otra causa" registros = [[vivn, mzinei, idregord, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, kmn, Paragraph(u'{}'.format(condicion), h4)]] RegistrosIngresados = Table(registros, colWidths = [0.8 * cm, 0.8 * cm, 0.90 * cm, 1 * cm, 1.2 * cm, 4.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm, 1 * cm, 0.9 * cm, 0.9 * cm, 3.6 * cm], rowHeights=[1 * cm]) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (12, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) if (nrows > 17): Elementos.append(PageBreak()) # SE DETERMINAN LAS CARACTERISTICAS DEL PDF (RUTA DE ALMACENAJE, TAMANIO DE LA HOJA, ETC) #destino = "\\\srv-fileserver\\CPV2017\\list_segm_tab_2\\urbano\\{}\\{}\\{}{}{}{}.pdf".format(aeu[0],zona_cod,aeu[0],zona_cod,seccion,aeus) destino=output pdf = SimpleDocTemplate(destino, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm, ) pdf.build(Elementos) print "Finalizado" def ListadoDeEstudiantes(informacion, output): cab=informacion[0] data=informacion[1] coddep=cab[0] departamento=cab[1] codprov=cab[2] provincia=cab[3] coddist = cab[4] distrito = cab[5] codccpp = cab[6] nomccpp = cab[7] zona = cab[8] subzona=cab[9] if subzona=='0' or subzona==0 : subzona='' else: subzona = '-{}'.format(subzona) Plantilla = getSampleStyleSheet() h1 = PS( name='Heading1', fontSize=7, leading=8 ) h11 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER ) h111 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_RIGHT ) h3 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=7, leading=10, alignment=TA_LEFT ) h5 = PS( name='Normal', fontSize=10, leading=10, alignment=TA_CENTER ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) Elementos = [] Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS<br/>III CENSO DE COMUNIDADES NATIVAS Y I CENSO DE COMUNIDADES CAMPESINAS',h_sub_tile) SubTitulo = Paragraph(u'<strong>DIRECTORIO DE VIVIENDAS CON ESTUDIANTES Y EMPLEADOS PÚBLICOS</strong>', h_sub_tile_2) CabeceraPrincipal = [[Image(EscudoNacional, width=50, height=50), Titulo, Image(LogoInei, width=55, height=50)], ['', SubTitulo, '']] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 24 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (0, 1)), ('SPAN', (2, 0), (2, 1)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0, 10)) Filas = [ ['', '', '', '', Paragraph('<b>Doc.CPV.03.300</b>', h111), ''], [Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h11), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>', h11),''], [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '',Paragraph(u'<b>ZONA CENSAL Nº</b>', h1), u'{}{}'.format(zona,subzona)], [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '','', ''], #Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>SUBZONA</b>', h1), u'{}'.format(subzona)], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '','', ''], [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', ''], ] Tabla = Table(Filas, colWidths=[5 * cm, 2 * cm, 12 * cm, 1 * cm, 5 * cm, 3 * cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm]) Tabla.setStyle(TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('ALIGN', (4, 0), (5, 0), 'RIGHT'), ('ALIGN', (1, 2), (1, 5), 'CENTER'), ('ALIGN', (5, 2), (5, 5), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, 5), 1, colors.black), ('GRID', (4, 1), (5, 2), 1, colors.black), ('SPAN', (4, 0), (5, 0)), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (5, 1)), ('BACKGROUND', (0, 1), (0, 5), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (5, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ])) # AGREGANDO LAS TABLAS A LA LISTA DE ELEMENTOS DEL PDF Elementos.append(Tabla) Elementos.append(Spacer(0, 10)) # AGREGANDO CABECERA N 2 Filas2 = [ [Paragraph(e, h3) for e in [u"<strong>Nº ORDEN</strong>",u"<strong>SECC. CENSAL Nº</strong>" ,u"<strong>MZ CENSAL Nº</strong>", u"<strong>FRENTE Nº</strong>", u"<strong>DIRECCIÓN DE LA VIVIENDA</strong>", "", "", "", "", "", "","", u"<strong>APELLIDOS Y NOMBRES DEL/DE LA<br/>JEFE/A DEL HOGAR</strong>",u"<strong>TOTAL DE PERSONAS QUE:</strong>","",""]], [Paragraph(e, h3) for e in ["", "", "", "",u"<strong>Tipo de Vía</strong>", u"<strong>Nombre de Vía</strong>", u"<strong>Nº de Puerta</strong>", u"<strong>Block</strong>", u"<strong>Mz Nº</strong>", u"<strong>Lote Nº</strong>", u"<strong>Piso Nº</strong>", u"<strong>Int. Nº</strong>", "", #u"<strong>TRABAJAN EN EL SECTOR PÚBLICO</strong>", u"<strong>ESTUDIAN EN LA UNIVERSIDAD O INSTITUTO SUPERIOR</strong>",u"<strong>TRABAJAN Y ESTUDIAN EN LA UNIVERSIDAD O INSTITUTO SUPERIOR</strong>", u"<strong>ESTUDIANTES DEL 5TO DE SECUNDARIA</strong>" u"<strong>TRABAJAN EN EL SECTOR PÚBLICO</strong>", u"<strong>ESTUDIAN EN LA UNIVERSIDAD O INSTITUTO SUPERIOR</strong>", #u"<strong>TRABAJAN Y ESTUDIAN EN LA UNIVERSIDAD O INSTITUTO SUPERIOR</strong>", u"<strong>Egresados de Sec./Estudiantes de 4TO Y 5TO. año de Sec.</strong>" ]], [Paragraph(e, h3) for e in [u"<strong>(1)</strong>", u"<strong>(2)</strong>", u"<strong>(3)</strong>", u"<strong>(4)</strong>", u"<strong>(5)</strong>", u"<strong>(6)</strong>", u"<strong>(7)</strong>", u"<strong>(8)</strong>", u"<strong>(9)</strong>", u"<strong>(10)</strong>", u"<strong>(11)</strong>", u"<strong>(12)</strong>", u"<strong>(13)</strong>",u"<strong>(14)</strong>",u"<strong>(15)</strong>",u"<strong>(16)</strong>" # ,u"<strong>(17)</strong>" ]] ] #Tabla2 = Table(Filas2,colWidths=[1.5*cm,1.25*cm,1.25*cm,1.25*cm,1.25*cm,3.5*cm,1.5 * cm, 1 * cm, 1 * cm, 1 * cm,1*cm, 1*cm, 5* cm,1.75*cm,1.75*cm,1.75*cm,1.75*cm]) Tabla2 = Table(Filas2, colWidths=[1.5 * cm, 1.30 * cm, 1.30 * cm, 1.30 * cm, 1.25 * cm, 3.5 * cm, 1.5 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 5 * cm, 2.28 * cm, 2.28 * cm, 2.29 * cm]) Tabla2.setStyle(TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (3, 0), (3, 1)), ('SPAN', (4, 0), (11, 0)), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('SPAN', (12, 0), (12, 1)), ('SPAN', (13, 0), (15, 0)), #('SPAN', (13, 0), (16, 0)), ])) Elementos.append(Tabla2) nrows = len(data) if nrows > 15: HojaRegistros = contar_registros(nrows, 15, 20) HojaRegistros.append((0, 15)) HojaRegistros.sort(key=lambda n: n[0]) for rangos in HojaRegistros: for viv in (data)[rangos[0]:rangos[1]]: vivn=viv[0] seccion=viv[1] mzinei = viv[2] frente = viv[3] tvia = viv[4] nomvia = u"{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] jefehogar = viv[12] trab_sec_pub =viv[13] est_uni=viv[14] est_5_secund = viv[15] registros = [ [vivn, seccion,mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, Paragraph(u'{}'.format(jefehogar), h4),trab_sec_pub,est_uni,est_5_secund ]] RegistrosIngresados = Table(registros,colWidths=[1.5 * cm, 1.30 * cm, 1.30 * cm, 1.30 * cm, 1.25 * cm, 3.5 * cm, 1.5 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 5 * cm, 2.28 * cm, 2.28 * cm, 2.29 * cm] ) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (15, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) Elementos.append(PageBreak()) Elementos.append(Tabla2) del Elementos[-1] del Elementos[-1] else: for viv in (data): vivn = viv[0] seccion = viv[1] mzinei = viv[2] frente = viv[3] tvia = viv[4] nomvia = u"{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] jefehogar = viv[12] trab_sec_pub = viv[13] est_uni = viv[14] trabajan_o_estudian = '' est_5_secund = viv[15] registros = [ [vivn, seccion, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, block, mzmuni, lote, piso, interior, Paragraph(u'{}'.format(jefehogar), h4), trab_sec_pub, est_uni, est_5_secund]] RegistrosIngresados = Table(registros, colWidths=[1.5 * cm, 1.30 * cm, 1.30 * cm, 1.30 * cm, 1.25 * cm, 3.5 * cm, 1.5 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 5 * cm, 2.28 * cm, 2.28 * cm, 2.29 * cm] ) RegistrosIngresados.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('ALIGN', (6, 0), (15, 0), 'CENTER') ])) Elementos.append(RegistrosIngresados) Elementos.append(Spacer(0, 10)) pdf = SimpleDocTemplate(output, pagesize=(29.7*cm, 21*cm), rightMargin=20, leftMargin=20, topMargin=0.25 * cm, bottomMargin=0.25 * cm, ) pdf.build(Elementos) print "Finalizado" def listado_emp_especial(informacion,nivel,tipo,output): cab = informacion[0] data = informacion[1] coddep = cab[0] departamento = cab[1] codprov = cab[2] provincia = cab[3] coddist = cab[4] distrito = cab[5] if nivel==2: codccpp = cab[6] nomccpp = cab[7] zona = cab[8] subzona=cab[9] viviendas=cab[11] Plantilla = getSampleStyleSheet() h1 = PS( name='Heading1', fontSize=7, leading=8 ) h11 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER ) h111 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_RIGHT ) h3 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=7, leading=10, alignment=TA_LEFT ) h5 = PS( name='Normal', fontSize=5, leading=5, alignment=TA_CENTER ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) Elementos = [] Titulo = Paragraph( u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS<br/>III CENSO DE COMUNIDADES NATIVAS Y I CENSO DE COMUNIDADES CAMPESINAS', h_sub_tile) if tipo==1 and nivel==2: SubTitulo = Paragraph(u'<strong>LISTADO DE VIVIENDAS COLECTIVAS INSTITUCIONALES DE LA ZONA CENSAL</strong>', h_sub_tile_2) elif tipo==2 and nivel==2: SubTitulo = Paragraph(u'<strong>LISTADO DE VIVIENDAS COLECTIVAS NO INSTITUCIONALES DE LA ZONA CENSAL</strong>', h_sub_tile_2) elif tipo==1 and nivel==1: SubTitulo = Paragraph(u'<strong>LISTADO DISTRITAL DE VIVIENDAS COLECTIVAS INSTITUCIONALES</strong>', h_sub_tile_2) elif tipo==2 and nivel==1: SubTitulo = Paragraph(u'<strong>LISTADO DISTRITAL DE VIVIENDAS COLECTIVAS NO INSTITUCIONALES</strong>', h_sub_tile_2) CabeceraPrincipal = [[Image(EscudoNacional, width=50, height=50), Titulo, Image(LogoInei, width=55, height=50)], ['', SubTitulo, '']] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 24 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (0, 1)), ('SPAN', (2, 0), (2, 1)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0, 10)) if nivel==2: if tipo==1: etiq_documento = ['', '', '', '', Paragraph(u'<b>Doc.CPV.34.</b>', h111), ''] else: etiq_documento = ['', '', '', '', Paragraph(u'<b>Doc.CPV.34A</b>', h111), ''] el1=[Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h11), '', '', '', Paragraph(u'<b>B. UBICACIÓN CENSAL</b>', h11),'','',''] el2=[Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '',Paragraph(u'<b>ZONA CENSAL Nº</b>', h1), u'{}'.format(zona),Paragraph(u'<b>SUBZONA</b>', h1), u'{}'.format(subzona)] else: if tipo==1: etiq_documento = ['', '', '', '','','', Paragraph('<b>Doc.CPV.03.33</b>', h111), ''] else: etiq_documento = ['', '', '', '','','', Paragraph('<b>Doc.CPV.03.33A</b>', h111), ''] el1=[Paragraph(u'<b>A. UBICACIÓN GEOGRÁFICA</b>', h11), '', '', '', '','','',''] el2 = [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '','', '','',''] Filas = [ etiq_documento,el1,el2, [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', '', '','',''], [Paragraph(u'<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', '', '','',''], ] tam_filas=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm] if nivel==2: tam_filas =[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm,0.4 * cm, 0.4 * cm] #if nivel==2: Filas.extend([ [Paragraph(u'<b>CENTRO POBLADO</b>', h1), u'{}'.format(codccpp), u'{}'.format(nomccpp), '', '', '', '', ''], [Paragraph(u'<b>CATEGORÍA DEL CENTRO POBLADO</b>', h1), u'CIUDAD', '', '', Paragraph(u'<b>TOTAL DE VIVIENDAS COLECTIVAS DE LA ZONA</b>', h1), '', u'{}'.format(viviendas), ''] ] ) tam_columns=[5 * cm, 2 * cm, 10 * cm, 1 * cm, 5 * cm, 2 * cm,2*cm,1*cm] Tabla = Table(Filas, colWidths=tam_columns, rowHeights=tam_filas #rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm] ) list_estilos=[ ('TEXTCOLOR', (0, 0), (-1, 0), colors.black), ('SPAN', (-2, 0), (-1, 0)), ('ALIGN', (1, 2), (1, 4), 'CENTER'), ('ALIGN', (5, 2), (5, 4), 'CENTER'), ('ALIGN', (0, 1), (-1, 1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 1), (2, -1), 1, colors.black), ('SPAN', (0, 1), (2, 1)), ('BACKGROUND', (0, 1), (0, -1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ] if nivel==2: list_estilos.extend( [ ('GRID', (4, 1), (-1, 2), 1, colors.black), ('GRID', (4, -1), (-1, -1), 1, colors.black), ('BACKGROUND', (4, 1), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 2), (4, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (6, 2), (6, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, -1), (4, -1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (4, 1), (-1, 1)), ('SPAN', (4,-1), (5, -1)), ('SPAN', (6, -1), (7, -1)), ('ALIGN', (4, 0), (5, 0), 'RIGHT'), ] ) Tabla.setStyle( TableStyle(list_estilos) ) Elementos.append(Tabla) Elementos.append(Spacer(0, 10)) ################# AGREGANDO CABECERA A LA TABLA fila2= [Paragraph(e, h3) for e in [u"<strong>Nº ORDEN</strong>", u"<strong>MZ Nº</strong>", u"<strong>FRENTE Nº</strong>", u"<strong>DIRECCIÓN DE LA VIVIENDA COLECTIVA</strong>", "", "", "", "", "", "", "","", u"<strong>NOMBRE<br/> COMERCIAL/RAZÓN SOCIAL </strong>", u"<strong>Nº DE PERSONAS </strong>"]] fila3=[Paragraph(e, h5) for e in ["", "", "", u"<strong>CATEGORIA DE VIA</strong>", u"<strong>NOMBRE DE LA VIA</strong>", u"<strong>Nº PUERTA</strong>",u"<strong>Nº MZ</strong>", u"<strong>Nº LOTE</strong>", u"<strong>INTERIOR</strong>", u"<strong>BLOCK</strong>", u"<strong>Nº PISO</strong>", u"<strong>KM</strong>","","" ]] if nivel==1 : ###distrital fila2.insert(1, Paragraph(u"<strong>ZONA Nº</strong>", h3)) fila3.insert(1, "") fila1=[[Paragraph(e, h3) for e in [u"<strong>B.INFORMACIÓN DE LA VIVIENDA COLECTIVA INSTITUCIONAL</strong>"]]] for el in range(14): fila1.append("") else: #####zonal fila1 = [[Paragraph(e, h3) for e in [u"<strong>C.INFORMACIÓN DE LA VIVIENDA COLECTIVA INSTITUCIONAL</strong>"]]] for el in range(13): fila1.append("") Filas2 = [ fila1,fila2,fila3,] if nivel==1: tam_columns = [0.975 * cm, 0.975 * cm, 0.975 * cm, 0.975 * cm, 1.25 * cm, 5 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm,1 * cm, 1 * cm, 1 * cm, 8.85 * cm, 2 * cm] else: tam_columns = [1.30 * cm, 1.30 * cm, 1.30 * cm, 1.25 * cm, 5 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 8.85 * cm, 2 * cm] Tabla2 = Table(Filas2, colWidths= tam_columns ) list_span=[] if nivel==1: for i in range(4): list_span.append(('SPAN', (i, 1), (i, 2))) for i in range(13,15): list_span.append(('SPAN', (i, 1), (i, 2))) list_span.append(('SPAN', (4, 1), (12, 1))) else: for i in range(3): list_span.append(('SPAN', (i, 1), (i, 2))) for i in range(12, 14): list_span.append(('SPAN', (i, 1), (i, 2))) list_span.append(('SPAN', (3, 1), (11, 1))) estilo_cab_cuerpo_tabla=[ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 0), (-1, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('SPAN', (0, 0), (-1, 0)), ('GRID', (0, 0), (-1, -1), 1, colors.black), ] estilo_cab_cuerpo_tabla.extend(list_span) Tabla2.setStyle(TableStyle(estilo_cab_cuerpo_tabla)) Elementos.append(Tabla2) nrows = len(data) #####################cuerpo tabla############################## estilo_cuerpo_tabla=[ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, -1), (0, -1), 'CENTER'), ] #if nivel==1: # p=22 #else: p = 20 contador_lineas=0 n_hoja=1 if nrows > p: contador_lineas = 1 for viv in data: vivn = viv[0] zona = viv[1] mzinei = viv[2] frente = viv[3] tvia = viv[4] nomvia = viv[5] #nomvia = u"{}{}".format(viv[5][0:24], "..") if len(viv[5]) > 26 else viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] km = viv[12] nom_estab = viv[13] nom_comercial = viv[14] n_personas = viv[15] registros = [ [vivn, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, mzmuni, lote, interior, block, piso, km, Paragraph(u'{}'.format(nom_comercial), h4), n_personas]] if nivel == 1: registros[0].insert(1, zona) RegistrosIngresados = Table(registros, colWidths=tam_columns) RegistrosIngresados.setStyle(estilo_cuerpo_tabla) tam_mzs=len(nom_comercial) lineas=tam_mzs/50.0 cant_lineas=math.ceil(lineas) contador_lineas=cant_lineas+contador_lineas Elementos.append(RegistrosIngresados) if n_hoja==1: if contador_lineas>p: n_hoja=n_hoja+1 Elementos.append(PageBreak()) Elementos.append(Tabla2) contador_lineas=1 else: if contador_lineas >28: n_hoja = n_hoja + 1 Elementos.append(PageBreak()) Elementos.append(Tabla2) contador_lineas = 1 else: for viv in data: vivn = viv[0] zona = viv[1] mzinei = viv[2] frente = viv[3] tvia = viv[4] nomvia=viv[5] npuerta = viv[6] block = viv[7] mzmuni = viv[8] lote = viv[9] piso = viv[10] interior = viv[11] km = viv[12] nom_estab = viv[13] nom_comercial = viv[14] n_personas = viv[15] registros = [ [vivn, mzinei, frente, tvia, Paragraph(u'{}'.format(nomvia), h4), npuerta, mzmuni, lote, interior, block, piso, km, Paragraph(u'{}'.format(nom_comercial), h4), n_personas]] if nivel == 1: registros[0].insert(1, zona) RegistrosIngresados = Table(registros, colWidths=tam_columns) RegistrosIngresados.setStyle(estilo_cuerpo_tabla) Elementos.append(RegistrosIngresados) if (nrows > p): Elementos.append(PageBreak()) Elementos.append(Spacer(0, 10)) pdf = SimpleDocTemplate(output, pagesize=(29.7 * cm, 21 * cm), rightMargin=20, leftMargin=20, topMargin=0.25 * cm, bottomMargin=0.25 * cm, ) pdf.build(Elementos) print "Finalizado" def listado_depart_prov(informacion,nivel,output): cab = informacion[0] data = informacion[1] if nivel == 1: dep = cab[0] subdep = cab[1] if nivel==2: dep = cab[0] prov = cab[1] subprov = cab[2] Plantilla = getSampleStyleSheet() h1 = PS( name='Heading1', fontSize=7, leading=8 ) h11 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER ) h111 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_RIGHT ) h3 = PS( name='Normal', fontSize=6, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=6, leading=5, alignment=TA_LEFT ) h5 = PS( name='Normal', fontSize=5, leading=10, alignment=TA_CENTER ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) Elementos = [] Titulo = Paragraph( u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS<br/>III CENSO DE COMUNIDADES NATIVAS Y I CENSO DE COMUNIDADES CAMPESINAS', h_sub_tile) if nivel==1: SubTitulo = Paragraph(u'<strong>NÚMERO DE ZONAS, SUBZONAS, SECCIONES CENSALES, ÁREAS DE EMPADRONAMIENTO URBANO, MANZANAS Y VIVIENDAS DEL DEPARTAMENTO </strong>', h_sub_tile_2) else: SubTitulo = Paragraph(u'<strong> NÚMERO DE ZONAS, SUBZONAS, SECCIONES CENSALES, ÁREAS DE EMPADRONAMIENTO URBANO, MANZANAS Y VIVIENDAS DE LA PROVINCIA</strong>', h_sub_tile_2) CabeceraPrincipal = [[Image(EscudoNacional, width=50, height=50), Titulo, Image(LogoInei, width=55, height=50)], ['', SubTitulo, '']] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 0), (0, 1)), ('SPAN', (2, 0), (2, 1)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0, 10)) if nivel==1: etiq_documento=['','', '', Paragraph('<b>DOC.CPV.03.161</b>', h111)] el1=[Paragraph(u'<b> UBICACIÓN GEOGRÁFICA</b>', h11), '', '', ''] #el2=[Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(dep), Paragraph(u'<b>SUB DEPARTAMENTO</b>', h1), u'{}'.format(subdep)] el2 = [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(dep), '',''] el3 = ['','','',''] else: etiq_documento = ['','', '', Paragraph('<b>DOC.CPV.03.160</b>', h111)] el1=[Paragraph(u'<b> UBICACIÓN GEOGRÁFICA</b>', h11), '', '', ''] el2 = [Paragraph(u'<b>DEPARTAMENTO</b>', h1), u'{}'.format(dep),'',''] #el3 = [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(prov), Paragraph(u'<b>SUB PROVINCIA</b>', h1), u'{}'.format(subprov)] el3 = [Paragraph(u'<b>PROVINCIA</b>', h1), u'{}'.format(prov), '',''] Filas = [etiq_documento, el1, el2,el3] Tabla = Table(Filas, colWidths=[4*cm,5*cm,4*cm,5*cm], rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm,0.4 * cm]) list_estilos=[ ('TEXTCOLOR', (0, 0), (3, 0), colors.black), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('SPAN', (0, 1), (-1, 1)), ('BACKGROUND', (0, 1), (-1, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ] if nivel==1: list_estilos.extend( [ ('GRID', (0, 1), (-1, 2), 1, colors.black), ('BACKGROUND', (0, 2), (0, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (2, 2), (2, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('ALIGN', (0, 1), (0, 2), 'RIGHT'), ('SPAN', (1, 2), (-1, 2)), ] ) else: list_estilos.extend( [ ('GRID', (0, 1), (-1, 3), 1, colors.black), ('BACKGROUND', (0, 2), (0, 2), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 3), (0, 3), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), #('BACKGROUND', (2, 3), (2, 3), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('ALIGN', (0, 1), (0, 2), 'RIGHT'), ('ALIGN', (2, 1), (2, 2), 'RIGHT'), ('SPAN', (1, 2), (-1, 2)), ('SPAN', (1, 3), (-1, 3)), ] ) Tabla.setStyle( TableStyle(list_estilos) ) Elementos.append(Tabla) Elementos.append(Spacer(0, 10)) fila2= [Paragraph(e, h3) for e in [u"<strong>UBIGEO</strong>",u"<strong>Distrito</strong>", u"<strong>Subdistrito</strong>",]] fila2.extend([Paragraph(e,h5) for e in [u"<strong>Nº de zonas</strong>", u"<strong>Nº de subzonas</strong>", u"<strong>Nº de secciones censales </strong>", u"<strong>Nº de AEUs</strong>", u"<strong>Nº de Mz. Censales </strong>", u"<strong>Nº de viviendas </strong>"]]) if nivel==1 : ###departamental fila2.insert(1, Paragraph(u"<strong>Provincia</strong>", h3)) #fila2.insert(2, Paragraph(u"<strong>Subprovincia</strong>", h3)) Filas2 = [ fila2] if nivel==1: #tam_columns = [2*cm,2 * cm, 2 * cm, 2 * cm, 2 * cm, 1 * cm, 1 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm,1.5 * cm] tam_columns = [2 * cm, 2 * cm, 3 * cm, 3 * cm, 1 * cm, 1.5 * cm, 1.5 * cm, 1 * cm, 1.5 * cm, 1.5 * cm] else: tam_columns = [2*cm,4 * cm, 4 * cm, 1 * cm, 1.5 * cm, 1.5 * cm, 1 * cm, 1.5 * cm,1.5 * cm] #tam_columns = [3 * cm, 3 * cm, 3 * cm, 3 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, # 1 * cm] Tabla2 = Table(Filas2, colWidths= tam_columns ) estilo_cab_cuerpo_tabla=[ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('GRID', (0, 0), (-1, 0), 1, colors.black), ] Tabla2.setStyle(TableStyle(estilo_cab_cuerpo_tabla)) Elementos.append(Tabla2) nrows = len(data) #####################cuerpo tabla############################## estilo_cuerpo_tabla=[ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (-1, 0), (-1, 0), 'CENTER'), ] estilo_primera_fila = [ ('BACKGROUND', (0, 0), (-1, 0), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ] if nivel==1: estilo_primera_fila.append(('ALIGN', (0, 0), (3, 0), 'CENTER')) estilo_primera_fila.append(('SPAN', (0, 0), (3,0))) else: estilo_primera_fila.append(('ALIGN', (0, 0), (1, 0), 'CENTER')) estilo_primera_fila.append(('SPAN', (0, 0), (1, 0))) i=0 p = 32 contador_lineas = 0 n_hoja = 1 if nivel==1: parametro_linea = 15.0 else: parametro_linea=26.0 if nrows > p: contador_lineas = 1 for viv in data: prov = viv[2] subprov = viv[3] distrito = viv[4] subdistrito = viv[5] zonas = viv[6] subzonas = viv[7] secciones = viv[8] aeus = viv[9] manzanas = viv[10] viviendas = viv[11] ubigeo=viv[12] registros = [[Paragraph(u"{}".format(el), h5) for el in [ubigeo,distrito, subdistrito, zonas, subzonas, secciones, aeus, manzanas, viviendas]]] if nivel == 1: registros[0].insert(1, Paragraph(prov, h5)) #registros[0].insert(2, Paragraph(subprov, h5)) if i == 0: registros[0][0] = Paragraph(u"<strong>TOTAL</strong>", h5) # '<strong>TOTAL</strong>' RegistrosIngresados = Table(registros, colWidths=tam_columns) RegistrosIngresados.setStyle(TableStyle(estilo_primera_fila)) else: RegistrosIngresados = Table(registros, colWidths=tam_columns) RegistrosIngresados.setStyle(TableStyle(estilo_cuerpo_tabla)) Elementos.append(RegistrosIngresados) if nivel==1: max_tam_registros=max([ len(u"{}".format(el)) for el in [prov,distrito, subdistrito] ]) else: max_tam_registros = max([len(u"{}".format(el)) for el in [distrito, subdistrito]]) print max_tam_registros lineas = max_tam_registros / parametro_linea cant_lineas = math.ceil(lineas) print 'cant_lineas',cant_lineas contador_lineas = cant_lineas + contador_lineas if n_hoja == 1: if contador_lineas > p: n_hoja = n_hoja + 1 Elementos.append(PageBreak()) Elementos.append(Tabla2) contador_lineas = 1 else: if contador_lineas > 40: n_hoja = n_hoja + 1 if i<nrows-1: Elementos.append(PageBreak()) Elementos.append(Tabla2) contador_lineas = 1 i = i + 1 else: for viv in data: prov = viv[2] subprov = viv[3] distrito = viv[4] subdistrito = viv[5] zonas = viv[6] subzonas = viv[7] secciones = viv[8] aeus = viv[9] manzanas = viv[10] viviendas = viv[11] ubigeo = viv[12] registros = [[Paragraph(u"{}".format(el), h5) for el in [ubigeo,distrito, subdistrito, zonas, subzonas, secciones, aeus, manzanas, viviendas]]] if nivel == 1: registros[0].insert(1, Paragraph(prov, h5)) #registros[0].insert(2, Paragraph(subprov, h5)) if i == 0: registros[0][0] = Paragraph(u"<strong>TOTAL</strong>", h5) RegistrosIngresados = Table(registros, colWidths=tam_columns) RegistrosIngresados.setStyle(TableStyle(estilo_primera_fila)) else: RegistrosIngresados = Table(registros, colWidths=tam_columns) RegistrosIngresados.setStyle(TableStyle(estilo_cuerpo_tabla)) Elementos.append(RegistrosIngresados) i = i + 1 Elementos.append(Spacer(0, 10)) pdf = SimpleDocTemplate(output, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm, ) #pdf = SimpleDocTemplate(output, pagesize=(29.7 * cm, 21 * cm), # rightMargin=20, # leftMargin=20, # topMargin=0.25 * cm, # bottomMargin=0.25 * cm, ) pdf.build(Elementos) print "Finalizado"
Java
UTF-8
327
2.921875
3
[]
no_license
package br.usjt.OO; public class Cilindro extends Tridimensional{ private double volume; public Cilindro(double raio, double altura) { this.volume = (Math.PI * Math.pow(raio, 2)*altura); } public double volume() { return volume; } @Override public String toString() { return "Cilindro"; } }
C++
UTF-8
3,833
2.59375
3
[ "MIT", "MIT-0" ]
permissive
// // tcp.cpp // Luves // // Created by leviathan on 16/5/17. // Copyright © 2016年 leviathan. All rights reserved. // #include "tcpServer.h" namespace luves { // //TCP Server模块 //用于新建TCP服务端 // TcpServer::~TcpServer() { delete listenChannel_; } void TcpServer::Bind() { bzero(&serverAddr_, sizeof(serverAddr_)); serverAddr_.sin_family=AF_INET; serverAddr_.sin_addr.s_addr=inet_addr(addr_.GetIp().c_str()); serverAddr_.sin_port=htons(addr_.GetPort()); Socket::Bind(listenFd_,this->GetServerAddrPointer()); } void TcpServer::Listen() { listenning_=true; Socket::Listen(listenFd_); } void TcpServer::RunServer() { this->Bind(); this->Listen(); listenChannel_->SetEvent(EVFILT_READ); listenChannel_->SetReadCb([this]{HandleAccept();}); listenChannel_->SetIsListen(true); loop_->AddChannel(listenChannel_); } //当有新的连接,epoll被触发时,回调HandleAccept()函数并建立新的连接 void TcpServer::HandleAccept() { struct sockaddr_in client_addr; int accept_fd; while((accept_fd=Socket::Accept(listenChannel_->GetFd(), &client_addr))>=0) { sockaddr_in local,peer; socklen_t len=sizeof(local); int ret; ret=getsockname(accept_fd, (struct sockaddr*)&local, &len); if (ret<0) { ERROR_LOG("get local addr failed! %d %s",errno,strerror(errno)); continue; } ret=getpeername(accept_fd, (sockaddr*)&peer, &len); if (ret<0) { ERROR_LOG("get peer addr failed! %d %s",errno,strerror(errno)); continue; } Ip4Addr local_addr(local),peer_addr(peer); this->NewConnection(accept_fd,local_addr,peer_addr); } } void TcpServer::NewConnection(int accept_fd,Ip4Addr local,Ip4Addr peer) { TcpConnectionPtr connection=TcpConnectionPtr(new TcpConnection(loop_)); if (readcb_) connection->SetReadCb(readcb_); if (writecb_) connection->SetWriteCb(writecb_); if (closecb_) connection->SetCloseCb(closecb_); connection->Register(loop_, accept_fd,local,peer); tcpConnectionFd_[accept_fd]=connection; //添加Tcp连接与accept套接字至映射队列 } // //TCP Client模块 //新建TCP客户端 // void TcpClient::RunClient() { this->Bind(); this->HandleConnect(); client_channel_->SetEvent(EVFILT_READ); loop_->UpdateChannel(client_channel_); TcpConnectionPtr conn=TcpConnectionPtr(new TcpConnection(loop_)); if (readcb_) { conn->SetReadCb(readcb_); } if (writecb_) { conn->SetWriteCb(writecb_); } } void TcpClient::Bind() { struct sockaddr_in client_addr; bzero(&client_addr, sizeof(client_addr)); client_addr.sin_family=AF_INET; client_addr.sin_addr.s_addr=htons(INADDR_ANY); client_addr.sin_port=htons(0); bind(client_fd_, (struct sockaddr *)&client_addr, sizeof(client_addr)); } void TcpClient::HandleConnect() { struct sockaddr_in server_addr; server_addr.sin_family=AF_INET; server_addr.sin_addr.s_addr=inet_addr("127.0.0.1"); server_addr.sin_port=htons(server_addr_.GetPort()); Socket::Bind(client_fd_, &server_addr); connect(client_fd_, (struct sockaddr *)&server_addr, sizeof(server_addr)); } }
Python
UTF-8
7,210
2.859375
3
[]
no_license
#!/usr/bin/env python __date__="May 3 2017" __location__="SEH 7th Floor" __author__="Sanjeev Sariya" long_description=""" Take in genus name Take in FASTA file current_Bacteria_unaligned.fa These seqeunces are to be printed in an output directory These sequences will be merged with previous RDP work Remember to remove duplicates after printing these seqs and taxonomy-- current_Bacteria_unaligned.fa version 11.5 is used to get sequences genus name and species name are case sensitive in input python get_species_seqs.py -g Staphylococcus -s aureus -o ./ -f current_Bacteria_unaligned.fa """ import sys,os, argparse,re from Bio import SeqIO def replace_special_chr(temp_word): #-replace special characters! temp_word=temp_word.replace('T','') #replace Type strain T info with blank temp_word=temp_word.replace("'",'') temp_word=temp_word.replace('"','') temp_word=temp_word.replace('(','') temp_word=temp_word.replace(')','') temp_word=temp_word.replace('.','') temp_word=temp_word.replace('+','') temp_word=temp_word.replace('=','') #replace = return temp_word #-------------------------------------- # #---------------------------------------- def check_taxonomy(temp_array,temp_seqid): """called from parsetaxonomy function to see if any value is None """ for k in range(0,len(temp_array)): if temp_array[k] is None: temp_array[k]="-" print "Issues with ",temp_seqid else: pass #--if ends #for loop ends---->>> return temp_array #return edited or however it was -- #--------------------------------------------- # #------------------------------------------------ def join_species_array(temp_array): """ Called from parse_taxonomy function It returns species name. Join elements by underscore """ temp_name="" for i in range(0,len(temp_array)): if not i==0: if not temp_array[i] == "": temp_name+="_"+temp_array[i] #not null #not first element else: if not temp_array[i] == "": temp_name+=temp_array[i] #if not null #if not first element check #--- #--for loop ends return temp_name #--------------------------------------------------------------- # #--------------------------------------------------------- def parse_taxonomy(temp_desc,temp_file_name,seqid): """ Called from get_seqs function This function will parse taxonomy and print it out in an output file """ temp_desc=replace_special_chr(temp_desc) taxonomy_array=[None]*7 #store ranks in it and use it to print info lineage_indx=temp_desc.index("Lineage") temp_spc_name=temp_desc[:lineage_indx-1] #get info until lineage. it has seqid in it too species_name="" #store species name in this variable if ";" in temp_spc_name: #if semi colon present semi_colon_inx=temp_spc_name.index(";") #get index of semi colon . seq_temp_spc=temp_spc_name[:semi_colon_inx] #get string until first semi colon temp_spc_parse=re.split('\s+',(seq_temp_spc.rstrip())[len(seqid)+1:]) #get pieces of species name species_name=join_species_array(temp_spc_parse) #return joined species name array #species_name=((seq_temp_spc.rstrip())[len(seqid)+1:]).replace(" ","_" ) #strip to remove extra space after (T) replacement else: #if no semi colon present ---- temp_spc_parse=re.split('\s+',(temp_spc_name.rstrip())[len(seqid)+1:]) species_name=join_species_array(temp_spc_parse) #species_name=((temp_spc_name.rstrip())[len(seqid)+1:]).replace(" ","_") #strip to remove extra space after (T) replacement #--got hold of species name #--time to parse other ranks ----- #-----if for ; ends rootrank_index=temp_desc.index("rootrank;") taxonomy_string=temp_desc[rootrank_index+len("rootrank;"):] split_tax_string=re.split(";",taxonomy_string) #--iterate over split taxonomy string index=0 for k in range(0,len(split_tax_string)): #this I should have used ages ago!! if split_tax_string[k]=="domain": taxonomy_array[0]=split_tax_string[k-1] if split_tax_string[k]=="phylum": taxonomy_array[1]=split_tax_string[k-1] if split_tax_string[k]=="class": taxonomy_array[2]=split_tax_string[k-1] if split_tax_string[k]=="order": taxonomy_array[3]=split_tax_string[k-1] if split_tax_string[k]=="family": taxonomy_array[4]=split_tax_string[k-1] if split_tax_string[k]=="genus": taxonomy_array[5]=split_tax_string[k-1] #--for loop ends ----->>>>>>>>>>>>> if species_name == "": #there can be seqids with no species name taxonomy_array[6]="Unknown_"+taxonomy_array[5] else: taxonomy_array[6]=species_name #store species name in the end --- taxonomy_array=check_taxonomy(taxonomy_array,seqid) """ If any of the index in array is None then replaced by - """ with open(temp_file_name,'a')as t_handle: t_handle.write(seqid+"\t"+"\t".join(x for x in taxonomy_array)+"\n") #--with write ends ------>>><<<<<<< # # # def get_seqs(genus, fasta, outputdir): """ This function prints seqs of your genus and species This also calls function to get taxonomy and prints taxonomy """ count=0 #keep count of seqs found seqs_file=outputdir+"/"+genus.lower()+"_seq.fasta" tax_file=outputdir+"/"+genus.lower()+"_tax.txt" for record in SeqIO.parse(fasta,"fasta"): if genus+";genus" in record.description: if genus in record.description: parse_taxonomy(record.description,tax_file,record.id) with open(seqs_file,'a') as w_handle: w_handle.write(">"+record.id+"\n"+str(record.seq)+"\n") #-with print ends count+=1 #check if species name in description #check if genus name is of our interest and is present in the the description #--for loop ends for current file print "Sequences found of your genus and species ",count #------------------------ # #----------------------- if __name__=="__main__": parser=argparse.ArgumentParser("description") parser.add_argument ('-o', '--out', help='location for output',required=True) # store output dir parser.add_argument ('-f', '--fasta', help='location for fasta file',required=True) # store input fasta file parser.add_argument ('-g', '--genus', help='genus name',required=True) # store output direc args_dict = vars(parser.parse_args()) # make them dict.. output_dir=os.path.abspath(args_dict['out']) #output dir fasta_file=os.path.abspath(args_dict['fasta']) #fasta file genus_name=args_dict['genus'] #genus name get_seqs(genus_name,fasta_file,output_dir) print "Check output dir with genus and species name files for sequences and taxonomy!" print "<<--Bye-Bye-->>"
Java
UHC
2,387
4.3125
4
[]
no_license
/* # for(ݺ) - ݺó Ư ʿ ϰ ó ȰǴ . - for( ʱⰪ; ݺ ; Ѱ( );{ ݺ ( -ʱⰪ Ȱ) } - ʱⰪ : int count=1; int idx=0; cnt=100; - ݺ : count < 100();, cnt > 0();, idx < 迭.length; - : count++, cnt--, count+=2, cnt-=5 # 迭 ȿ ȰǴ for 2° - Ϲ primitive data 迭, ü 迭 - String names={"ȣ", "޽", ""}; names[0] : "ȣ" Ͱ ִ ü -- String name=names[0]; for( ü : 迭ü ){ 迭 ü Ȱؼ ó } ex) for(String name : names){ System.out.println("̸"+name); } */ package a04_statement; public class A03_for_0412 { public static void main(String[] args) { // TODO Auto-generated method stub // 15~50 . for(int count=15; count<=50; count++){ System.out.println("ȣ : "+count); } // 5 tab ٹٲ ó for(int count=15; count<=50; count++){ System.out.print(count); // print ٹٲ if(count%5==0){ System.out.println(); // ȣ 5 0̸ ٹٲ }else{ System.out.print("\t"); // ׷ ȣ tab } } // 1~100 ͸ ջϼ int sum=0; for(int cnt=1; cnt<=100; cnt++){ System.out.print(cnt); if(cnt!=100){ System.out.print(" + "); } if(cnt%10==0){ System.out.println(); } sum+=cnt; // ó } System.out.println("= "+sum); /* 迭 ó */ String[] foods={"", "¥", "ġ"}; // 迭 Ÿ[] = {1, 2, 3,...} for(int idx=0; idx<foods.length; idx++){ // 迭.length : 迭 ũ = indexȣ+1 System.out.println((idx+1)+"° : "+foods[idx]); } // for(/ü : 迭ü){ ش 迭ü ü Ҵ} String[] names={"ȣ", "޽", ""}; for(String name : names){ System.out.println("̸ "+name); } } }
Markdown
UTF-8
1,733
2.953125
3
[]
no_license
# Deleting XDCR replications automation Couchbase url_encoded_replication_id API creation and deletion. I was looking a way to create and delete XDCR replications automatically via API but I didn't find any step-by-step doc. First of all , we need to place uuid generate by API XDCR replication creation in a file while generating the replication. If I take the couchbase sample and add output file that we call uuid.json : curl -v -X POST -u Administrator:password1 \ http://10.4.2.4:8091/controller/createReplication \ -d 'fromBucket=beer-sample' \ -d 'toCluster=remote1' \ -d 'toBucket=remote_beer' \ -d 'replicationType=continuous' \ -d 'type=capi' \ -o uuid.json We can see that the file uuid.json contains the following info : { "id": "9eee38236f3bf28406920213d93981a3/beer-sample/remote_beer" } Now , if we want to delete this XDCR replications , we need to install jq so we can easily parse this generated file . Install JQ: wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 -O jq chmod 755 jq sudo mv jq /usr/local/bin/ delete process : As explain in couchbase documentation : Replication ID needs to be URL-encoded before it can be used in the delete replication URL. So : cat uuid.json | jq -r '.id | @uri' command will return url_encoded_replication_id 9eee38236f3bf28406920213d93981a3%2fbeer-sample%2fremote_beer Create a variable that will contain this url_encoded_replication_id from file created uuid=$( cat uuid.json | jq -r '.id | @uri') add it at the end of curl curl -u Administrator:password1 \ http://10.4.2.4:8091/controller/cancelXDCR/ \ $uuid \ -X DELETE The process of creation and deletion is completely automated. a Bientot
C++
UTF-8
2,480
3.8125
4
[]
no_license
/* Carlos Adiel Diaz del Cid Carnet: DD18003 Una empresa comercializadora contrata vendedores a los cuales les paga un salaria que va de acuerdo al total de las ventas realizadas en el mes. realizar un programa en c++ que sistematice este procedimiento y al ingresar las ventas de un empleado inmediatamente muestre el sueldo que le corresponde.*/ //librerias para realizar el programa #include <iostream>//libreria de entrada y salida #include <math.h>//libreria de procesos matematicos #include <iomanip>//libreria del programa //se utiliza lo siguiente para evitar poner std en cada linea de codigo using namespace std; //definicion de variables para el codigo int ventas; float sueldo; float a; //cuerpo del programa de calculo de sueldo para empleados main() { //se agrega un do y un while para evitar los numeros menores a 0 do{ //se presenta al usuario el nombre de la empresa cout<<"INDUSTRIAS LA CONSTANCIA"<<endl; cout<<" "<<endl; // se solicita al usuario que ingrese el total de ventas del usuario realizadas en un mes cout<<"Ingrese el total de ventas del vendedor."<<endl; //se guarda la variable para realizar los procesos nesesarios cin>>ventas; } //el while se agrega para repetir la peticion de ingreso while(ventas<=0); cout<<setprecision(4)<<endl; cout<<fixed<<endl; // se calcula el sueldo con la condicion 1. if (ventas>0 && ventas<=500000) { sueldo=80.000; } // se calcula el sueldo con la condicion 2. else if (ventas>500001 && ventas<=1000000) { sueldo=160.000; } // se calcula el sueldo con la condicion 3. else if (ventas>1000001 && ventas<=1500000) { sueldo=320.000; } // se calcula el sueldo con la condicion 4. else if (ventas>1500001 && ventas<=2500000) { sueldo=450.000; } // se calcula el sueldo con la condicion 5. else if (ventas>2500001 && ventas<=4000000) { sueldo=550.000; } // se calcula el sueldo con la condicion 6. y else if (ventas>4000000) { // se calcula el sueldo del vendedor multiplicando el total de ventas por 20% de las ventas y resulta el salario a=ventas*0.20; sueldo=a; } /* Esta seria la ultima concion de este codigo pero facilmente se le pueden agragar mas condiciones utilizando else if */ // se imprime en pantalla el sueldo del vendedor cout<<"el sueldo del vendedor es: $"<<sueldo<<endl; return 0; } // fin del programa de calculo de sueldo del vendedodr
Markdown
UTF-8
1,538
2.953125
3
[]
no_license
# Mixed Neural Style Transfer ![Image description](https://static.wixstatic.com/media/94d104_d4932d4d0bde443fa6a5ef511762136f~mv2_d_4897_2184_s_2.png) (The image in the center is in the combined style of the images on the left and the right.) ## Description In this project, I use an idea inspired by one of my academic research projects: I designed adaptable materials using oscillatory optimization goals. Here, I'm letting the learner, an algorithm that mimics the style of a painting, repeatedly change its mind about which style it prefers. The learner oscillates between learning how to paint like Van Gogh and learning how to paint like Picasso. After several cycles, the learner ends up painting in a style that has qualities of both! We make use of a technique called Neural Style Transfer to mimic a single style. The code for this subproblem is heavy adapted from the following link: [Neural Transfer using PyTorch](https://pytorch.org/tutorials/advanced/neural_style_tutorial.html). ## Prerequired packages ```bash pip install numpy pip3 install torch torchvision pip install matplotlib ``` ## Usage Following along the jupyter notebook oscillating_using_pytorch-ongithub_final.ipynb ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## Further reading [Let machines help you design your own art style](https://www.hallojiayi.com/post/let-machine-help-you-design-your-own-art-style)
C#
UTF-8
3,068
3.328125
3
[ "MIT", "CC-BY-4.0" ]
permissive
// System.Net.FileWebResponse.GetResponseStream. /* This program demonstrates the 'GetResponseStream' method of the 'FileWebResponse' class. It creates a 'FileWebRequest' object and queries for a response. The response stream obtained is piped to a higher level stream reader. The reader reads 256 characters at a time, writes them into a string and then displays the string onto the console. */ using System; using System.Net; using System.IO; using System.Text; class FileWebResponseSnippet { public static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("\nPlease enter the file name as command line parameter:"); Console.WriteLine("Usage:FileWebResponse_GetResponseStream <systemname>/<sharedfoldername>/<filename> \nExample:FileWebResponse_GetResponseStream microsoft/shared/hello.txt"); } else { GetPage(args[0]); } Console.WriteLine("Press any key to continue..."); Console.ReadLine(); return; } public static void GetPage(String url) { try { // <Snippet1> Uri fileUrl = new Uri("file://"+url); // Create a 'FileWebrequest' object with the specified Uri. FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl); // Send the 'FileWebRequest' object and wait for response. FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse(); // Get the stream object associated with the response object. Stream receiveStream = myFileWebResponse.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); // Pipe the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader( receiveStream, encode ); Console.WriteLine("\r\nResponse stream received"); Char[] read = new Char[256]; // Read 256 characters at a time. int count = readStream.Read( read, 0, 256 ); Console.WriteLine("File Data...\r\n"); while (count > 0) { // Dump the 256 characters on a string and display the string onto the console. String str = new String(read, 0, count); Console.Write(str); count = readStream.Read(read, 0, 256); } Console.WriteLine(""); // Release resources of stream object. readStream.Close(); // Release resources of response object. myFileWebResponse.Close(); // </Snippet1> } catch(WebException e) { Console.WriteLine("\r\nWebException thrown. The Reason for failure is : {0}",e.Status); } catch(Exception e) { Console.WriteLine("\nThe following Exception was raised : {0}",e.Message); } } }
C++
UTF-8
2,156
3.25
3
[]
no_license
// COS30008 - Problem Set 7, 2019 #include "NTree.h" #include "TreeVisitor.h" #include <iostream> #include <string> using namespace std; void testDepthFirstTraversal() { string A("A"); string A1("AA"); string A2("AB"); string A3("AC"); string AA1("AAA"); string AB1("ABA"); string AB2("ABB"); typedef NTree<string, 3> NS3Tree; NS3Tree lTree(A); lTree.attachNTree(0, *(new NS3Tree(A1))); lTree.attachNTree(1, *(new NS3Tree(A2))); lTree.attachNTree(2, *(new NS3Tree(A3))); lTree[0].attachNTree(0, *(new NS3Tree(AA1))); lTree[1].attachNTree(0, *(new NS3Tree(AB1))); lTree[1].attachNTree(1, *(new NS3Tree(AB2))); cout << "Depth-first traversal:" << endl; lTree.traverseDepthFirst(PreOrderVisitor<string>()); cout << endl << "Success." << endl; } void testBreadthFirstTraversal() { string A("A"); string A1("AA"); string A2("AB"); string A3("AC"); string AA1("AAA"); string AB1("ABA"); string AB2("ABB"); typedef NTree<string, 3> NS3Tree; NS3Tree lTree(A); lTree.attachNTree(0, *(new NS3Tree(A1))); lTree.attachNTree(1, *(new NS3Tree(A2))); lTree.attachNTree(2, *(new NS3Tree(A3))); lTree[0].attachNTree(0, *(new NS3Tree(AA1))); lTree[1].attachNTree(0, *(new NS3Tree(AB1))); lTree[1].attachNTree(1, *(new NS3Tree(AB2))); cout << "Breadth-first traversal:" << endl; lTree.traverseBreadthFirst(TreeVisitor<string>()); cout << endl << "Success." << endl; } void testLinearRepresentation() { string A("A"); string A1("AA"); string A2("AB"); string A3("AC"); string AA1("AAA"); string AB1("ABA"); string AB2("ABB"); typedef NTree<string, 3> NS3Tree; NS3Tree lTree(A); lTree.attachNTree(0, *(new NS3Tree(A1))); lTree.attachNTree(1, *(new NS3Tree(A2))); lTree.attachNTree(2, *(new NS3Tree(A3))); lTree[0].attachNTree(0, *(new NS3Tree(AA1))); lTree[1].attachNTree(0, *(new NS3Tree(AB1))); lTree[1].attachNTree(1, *(new NS3Tree(AB2))); cout << "Linear representation:" << endl; lTree.traverseDepthFirst(LeftLinearVisitor<string>()); cout << endl << "Success." << endl; } int main() { testDepthFirstTraversal(); testBreadthFirstTraversal(); testLinearRepresentation(); return 0; }
JavaScript
UTF-8
1,122
3.0625
3
[]
no_license
class Worker { constructor() { console.log('Event listeners being added'); let btn = document.getElementById('_getImages'); btn.addEventListener('click', this.getImages ); } getImages() { console.log('Get images here'); let url = "https://api.github.com/users"; console.log(`Fetch url ${url}`); fetch(url) .then(function(response){ return response.json(); }).then((json)=>{Worker.parseUsers(json)}) .catch(function(error){ console.log(error); }); } parseUsers(users) { users.forEach(function(user){ this.createUserNode(user); }); } createUserNode(user){ let {avatar_url, login} = user; console.log(avatar_url); console.log(login); let content = `<div class="card"> <img class="card-img-top" src="${avatar_url}" alt="Card image cap"> <div class="card-block"> ${login} </div> </div>`; let node = document.createElement('li'); node.innerHTML = content; node.className = "list-group-item"; document.getElementById('userlist').appendChild(node); } } export {Worker};
Java
UTF-8
245
2.140625
2
[]
no_license
package com.example.heuristic; import lombok.Data; import java.util.ArrayList; import java.util.List; @Data public class Car { private double width=1200; private double height=600; private List<Cage> cageList=new ArrayList<>(); }
Markdown
UTF-8
4,252
2.703125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Sub 式 (Visual Basic) ms.date: 07/20/2015 helpviewer_keywords: - lambda expressions [Visual Basic], sub expression - Sub Expression [Visual Basic] - subroutines [Visual Basic], sub expressions ms.assetid: 36b6bfd1-6539-4d8f-a5eb-6541a745ffde ms.openlocfilehash: d284e629ea0b0a4e9b6eb9e098612bb07c38723b ms.sourcegitcommit: 17ee6605e01ef32506f8fdc686954244ba6911de ms.translationtype: MT ms.contentlocale: ja-JP ms.lasthandoff: 11/22/2019 ms.locfileid: "74350899" --- # <a name="sub-expression-visual-basic"></a>Sub 式 (Visual Basic) サブルーチンラムダ式を定義するパラメーターとコードを宣言します。 ## <a name="syntax"></a>構文 ```vb Sub ( [ parameterlist ] ) statement - or - Sub ( [ parameterlist ] ) [ statements ] End Sub ``` ## <a name="parts"></a>指定項目 |用語|Definition| |---|---| |`parameterlist`|省略可。 プロシージャのパラメーターを表すローカル変数名の一覧です。 リストが空の場合でも、かっこは存在する必要があります。 詳細については、「[パラメーター リスト](../../../visual-basic/language-reference/statements/parameter-list.md)」を参照してください。| |`statement`|必須。 1つのステートメント。| |`statements`|必須。 ステートメントの一覧。| ## <a name="remarks"></a>コメント *ラムダ式*は、名前がなく、1つ以上のステートメントを実行するサブルーチンです。 ラムダ式は、デリゲート型を使用できる場所であればどこでも使用できます。ただし、`RemoveHandler`の引数として使用することはできません。 デリゲートの詳細と、デリゲートでのラムダ式の使用については、「[Delegate ステートメント](../../../visual-basic/language-reference/statements/delegate-statement.md)」および「[厳密でないデリゲート変換](../../../visual-basic/programming-guide/language-features/delegates/relaxed-delegate-conversion.md)」を参照してください。 ## <a name="lambda-expression-syntax"></a>ラムダ式の構文 ラムダ式の構文は、標準のサブルーチンの構文に似ています。 相違点は、次のとおりです。 - ラムダ式に名前がありません。 - ラムダ式には、`Overloads` や `Overrides`などの修飾子を含めることはできません。 - 単一行のラムダ式の本体は、式ではなく、ステートメントでなければなりません。 本文は、Sub プロシージャの呼び出しで構成できますが、Function プロシージャを呼び出すことはできません。 - ラムダ式では、すべてのパラメーターのデータ型が指定されているか、すべてのパラメーターが推論される必要があります。 - ラムダ式では、省略可能なパラメーターと `ParamArray` パラメーターは使用できません。 - ラムダ式ではジェネリックパラメーターは使用できません。 ## <a name="example"></a>例 値をコンソールに書き込むラムダ式の例を次に示します。 この例では、サブルーチンの単一行と複数行のラムダ式の構文の両方を示しています。 その他の例については、「[ラムダ式](../../../visual-basic/programming-guide/language-features/procedures/lambda-expressions.md)」を参照してください。 [!code-vb[VbVbalrLambdas#15](~/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbVbalrLambdas/VB/Class1.vb#15)] ## <a name="see-also"></a>参照 - [Sub ステートメント](../../../visual-basic/language-reference/statements/sub-statement.md) - [ラムダ式](../../../visual-basic/programming-guide/language-features/procedures/lambda-expressions.md) - [演算子および式](../../../visual-basic/programming-guide/language-features/operators-and-expressions/index.md) - [ステートメント](../../../visual-basic/programming-guide/language-features/statements.md) - [厳密でないデリゲート変換](../../../visual-basic/programming-guide/language-features/delegates/relaxed-delegate-conversion.md)
PHP
UTF-8
1,235
2.65625
3
[]
no_license
<?php namespace Awz\Note\Models; use Illuminate\Database\Eloquent\Model; class Note extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'notes'; /** * The database primary key value. * * @var string */ protected $primaryKey = 'id'; /** * Attributes that should be mass-assignable. * * @var array */ protected $fillable = [ 'openid' , 'nickname' , 'content' , 'image' , 'width' , 'height' ]; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = [ ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ ]; protected $appends = [ 'abstract' ]; public function getAbstractAttribute () { if ( strlen ( $this->attributes[ 'content' ] ) <= 100 ) { return $this->attributes[ 'content' ]; } return str_limit ( $this->attributes[ 'content' ] , 100 ) . '<a href="' . route ( 'notes.note.view' , $this->attributes[ 'id' ] ) . '" target="_blank">&gt;&gt;&gt;</a>'; } }
C#
UTF-8
1,878
2.671875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// This is a class to save information about the animals on the boat /// </summary> public class VaisseauDataManager : MonoBehaviour { private Dictionary<EtreVivant, int> dataModel = AnimalDataModel.GetDataModel(); void Start() { } // Update is called once per frame void Update() { foreach(var pair in dataModel) { TempsQuiPasse(pair.Key); //Debug.Log(pair.Key.Fatigue); } } /// <summary> /// Update the information about the animals each frame /// </summary> /// <param name="animal"></param> private void TempsQuiPasse( EtreVivant animal) { animal.Chronometre += Time.deltaTime; if (animal.Chronometre >= animal.Chronolimite) { animal.Chronometre = 0f; if (GameManager.Instance.IsSleep == false) { animal.Estomac -= 0.5f; animal.Fatigue -= (0.1f * Time.deltaTime); if (animal.Fatigue < 0) { animal.Fatigue = 0f; } if (animal.Estomac < 0) { animal.Estomac = 0; } //if (UnityEngine.Random.value >= 0.5) //{ // animal.DisplayHumeur(); //} } else { Debug.Log("trueeeeeee"); // problème : ça risque de ne pas se recharger si je quitte l'application ! animal.Fatigue += 0.3f; if (animal.Fatigue > 10f) { animal.Fatigue = 10f; } } } AnimalDataModel.UpdateAnimalInfo(animal); } }