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
C#
UTF-8
1,058
2.8125
3
[ "MIT" ]
permissive
using System.IO; namespace BatchAudioFileConverter.Models { public class PathTransformer : IPathTransformer { public string Transform(string inputBasePath , string inputPath , string outputBasePath ) { return Path.Combine(outputBasePath , inputPath .Replace(inputBasePath, string.Empty) .Trim(Path.DirectorySeparatorChar) ); } public string TransformToFlatOutput(string inputBasePath , string inputPath , string outputPath , bool removeExtension ) { var outputFileName = inputPath .Replace(inputBasePath, string.Empty) .Trim('\\') .Replace('\\', '_'); if (removeExtension) { outputFileName = Path.GetFileNameWithoutExtension(outputFileName); } return Path.Combine(outputPath, outputFileName); } } }
Markdown
UTF-8
770
2.96875
3
[ "Apache-2.0" ]
permissive
## Autoplay <!-- {docsify-ignore-all} --> If autoplay with sound is not allowed by the browser, the player will try to mute and play again. Some mobile device does not support autoplay start even player is muted. :warning: Autoplay already handled in **VideoJS 7**, you may not need this plugin <br /> ```html inject <video id="autoplay-video" poster="https://vjs.zencdn.net/v/oceans.png"> <source src="https://vjs.zencdn.net/v/oceans.mp4" /> </video> ``` ### Usage ```js run const player = videojs('autoplay-video', { autoplay: true, // highlight-line aspectRatio: '16:9' }); ``` ### Event ```js player.on('autoplay-success', () => { console.log('autoplay success'); }); player.on('autoplay-failure', () => { console.log('autoplay failure'); }); ```
JavaScript
UTF-8
403
2.75
3
[]
no_license
const electron = require('electron'); const { ipcRenderer } = electron; const taskList = document.querySelector('.task-list ul'); ipcRenderer.on('task:new', (event, task) => { const elem = document.createElement('li'); const text = document.createTextNode(task); elem.appendChild(text); taskList.appendChild(elem); }); ipcRenderer.on('tasks:clear', event => { taskList.innerHTML = ''; });
Python
UTF-8
2,020
2.5625
3
[]
no_license
N=int(input()) sand=[] for i in range(N): a=list(map(int,input().split())) sand.append(a) start=[int((N-1)/2),int((N-1)/2)] import math visited=[ [0]*N for i in range(N)] dr=[0,1,0,-1] dc=[-1,0,1,0] cnt=0 cum=-1 row=start[0] col=start[1] def tornado(x,r,c): y=[x[0]+r,x[1]+c] ratio=[0.02,0.10,0.07,0.01,0.05,0.10,0.07,0.01,0.02] position=[[-2,0],[-1,-1],[-1,0],[-1,1],[0,-2],[1,-1],[1,0],[1,1],[2,0]] if r==dr[1] and c==dc[1]: for i in range(len(position)): temp=position[i][1] position[i][1]=position[i][0] position[i][0]=temp*(-1) elif r==dr[2] and c==dc[2]: for i in range(len(position)): temp=position[i][0] position[i][1]=position[i][1]*(-1) position[i][0]=temp*(-1) elif r==dr[3] and c==dc[3]: for i in range(len(position)): temp=position[i][1] position[i][1]=position[i][0]*(-1) position[i][0]=temp num=0 for i in range(len(position)): if 0<=y[0]+position[i][0]<N and 0<=y[1]+position[i][1]<N: sand[y[0]+position[i][0]][y[1]+position[i][1]]=int(sand[y[0]][y[1]]*ratio[i])+sand[y[0]+position[i][0]][y[1]+position[i][1]] num+=int(sand[y[0]][y[1]]*ratio[i]) if 0<=y[0]+r<N and 0<=y[1]+c<N: sand[y[0]+r][y[1]+c]=sand[y[0]+r][y[1]+c]+sand[y[0]][y[1]]-num sand[y[0]][y[1]]=0 sandcnt=0 for i in range(N): for j in range(N): sandcnt+=sand[i][j] while cnt<N*N: x=[row,col] visited[row][col]=1 if 0<=row+dr[(cum+1)%4]<N and 0<=col+dc[(cum+1)%4]<N and visited[row+dr[int((cum+1)%4)]][col+dc[int((cum+1)%4)]]==0: row=row+dr[int((cum+1)%4)] col=col+dc[int((cum+1)%4)] cum+=1 tornado(x,dr[int((cum)%4)],dc[int((cum)%4)]) else: row=row+dr[int((cum)%4)] col=col+dc[int((cum)%4)] tornado(x,dr[int((cum)%4)],dc[int((cum)%4)]) cnt+=1 for i in range(N): for j in range(N): sandcnt-=sand[i][j] print(sandcnt)
JavaScript
UTF-8
5,794
2.5625
3
[]
no_license
import * as dicomParser from 'dicom-parser' import log from 'loglevel' const decodeLittleEndian = async ( byteArray, { bitsAllocated, bitsStored, pixelRepresentation } ) => { if (bitsAllocated === 8) { return new Uint8Array( byteArray.buffer, byteArray.byteOffset, byteArray.length ) } if (bitsAllocated === 16) { if (pixelRepresentation === 0) { return new Uint16Array( byteArray.buffer, byteArray.byteOffset, byteArray.length / 2 ) } else if (bitsStored === 16) { return new Int16Array( byteArray.buffer, byteArray.byteOffset, byteArray.length / 2 ) } else { throw new Error( 'Signed pixel representation is not fully supported. Please convert the image to unsigned pixel representation.' ) } } else if (bitsAllocated === 32) { return new Float32Array( byteArray.buffer, byteArray.byteOffset, byteArray.length / 4 ) } throw new Error(`Unsupported BitsAllocated tag value ${bitsAllocated}.`) } const decodeJPEGBaseline = (byteArray, { bitsStored, samplesPerPixel }) => new Promise((resolve, reject) => { if (bitsStored === 8) { const image = new Image() const blob = new Blob([byteArray], { type: 'image/jpeg' }) const objectUrl = URL.createObjectURL(blob) image.src = objectUrl image.onload = () => { const canvas = document.createElement('canvas') canvas.width = image.naturalWidth canvas.height = image.naturalHeight const ctx = canvas.getContext('2d') ctx.drawImage(image, 0, 0) URL.revokeObjectURL(objectUrl) const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height) if (samplesPerPixel === 4) { resolve(imageData.data) } else if (samplesPerPixel === 1) { const pixelData = new Uint8Array(imageData.data.length / 4) for (let i = 0; i !== pixelData.length; i++) { pixelData[i] = imageData.data[i * 4] } resolve(pixelData) } else { reject(new Error(`Unspported SamplesPerPixel == ${samplesPerPixel}.`)) } } image.onerror = () => { reject(new Error('Invalid JPEG baseline image data.')) } } else { reject( new Error( `Invalid BitsStored == ${bitsStored} for JPEG Baseline Image.` ) ) } }) const decodeBigEndian = async ( byteArray, { bitsAllocated, bitsStored, pixelRepresentation } ) => { const data = await decodeLittleEndian(byteArray, { bitsAllocated, bitsStored, pixelRepresentation }) // TODO: decode for big endian log.error('do not fully support big endian encode.') return data } const parseImageFrame = dataSet => { const pixelDataElement = dataSet.elements.x7fe00010 if (pixelDataElement === undefined) { throw new Error('No pixel data to decode.') } if (pixelDataElement.encapsulatedPixelData) { // http://dicom.nema.org/dicom/2013/output/chtml/part05/sect_A.4.html if (pixelDataElement.basicOffsetTable.length) { return dicomParser.readEncapsulatedImageFrame( dataSet, pixelDataElement, 0 ) } else if (pixelDataElement.fragments.length === 1) { return dicomParser.readEncapsulatedPixelDataFromFragments( dataSet, dataSet.elements.x7fe00010, 0 ) } else { const basicOffsetTable = dicomParser.createJPEGBasicOffsetTable( dataSet, dataSet.elements.x7fe00010 ) return dicomParser.readEncapsulatedImageFrame( dataSet, dataSet.elements.x7fe00010, 0, basicOffsetTable ) } } else { return new Uint8Array( dataSet.byteArray.buffer, pixelDataElement.dataOffset, pixelDataElement.length ) } } const decodeImageData = async dataSet => { const start = Date.now() const transferSyntax = dataSet.string('x00020010') const bitsAllocated = dataSet.uint16('x00280100') const bitsStored = dataSet.uint16('x00280101') const highBit = dataSet.uint16('x00280102') const pixelRepresentation = dataSet.uint16('x00280103') const samplesPerPixel = dataSet.uint16('x00280002') const pixelDataByteArray = parseImageFrame(dataSet) const makeTexture = pixelData => { const end = Date.now() const decodeTimeInMs = end - start return { transferSyntax, samplesPerPixel, bitsAllocated, bitsStored, highBit, pixelRepresentation, pixelData, decodeTimeInMs } } const pixelConfig = { bitsAllocated, bitsStored, highBit, pixelRepresentation, samplesPerPixel } if (transferSyntax === '1.2.840.10008.1.2') { // Implicit VR Little Endian return makeTexture( await decodeLittleEndian(pixelDataByteArray, pixelConfig) ) } else if (transferSyntax === '1.2.840.10008.1.2.1') { // Explicit VR Little Endian return makeTexture( await decodeLittleEndian(pixelDataByteArray, pixelConfig) ) } else if (transferSyntax === '1.2.840.10008.1.2.1.99') { // Deflate transfer syntax (deflated by dicomParser) return makeTexture( await decodeLittleEndian(pixelDataByteArray, pixelConfig) ) } else if (transferSyntax === '1.2.840.10008.1.2.4.50') { // Lossy JPEG 8-bit Image Compression return makeTexture( await decodeJPEGBaseline(pixelDataByteArray, pixelConfig) ) } else if (transferSyntax === '1.2.840.10008.1.2.2') { // explicit big endian return makeTexture(await decodeBigEndian(pixelDataByteArray, pixelConfig)) } else { throw new Error(`No decoder for transfer syntax ${transferSyntax}`) } } export { decodeImageData }
Java
MacCentralEurope
2,291
2.65625
3
[]
no_license
package br.com.ligaesporteamador.bo; import java.util.Calendar; import org.apache.commons.lang.StringUtils; import br.com.ligaesporteamador.model.Usuario; import br.com.ligaesporteamador.util.ValidaCPF; public class UsuarioBO { public String validaPreenchimento(Usuario usuario) { String message = ""; if (!usuario.isTermoContrato()) { message = "Para se Cadastrar necessario aceitar o termo de contrato."; } else if (StringUtils.isBlank(usuario.getNome())) { message = "Por favor preencher o campo Nome !"; } else if (StringUtils.isBlank(usuario.getSobreNome())) { message = "Por favor preencher o campo Sobre Nome !"; } else if (StringUtils.isBlank(usuario.getDataNasc())) { message = "Por favor preencher o campo Data de Nascimento !"; } else if (StringUtils.isBlank(usuario.getCpf())) { message = "Por favor preencher o campo CPF !"; }else if(!ValidaCPF.isCPF(usuario.getCpf().replace(".", "").replace("-", ""))){ message = "CPF Invalido !"; }else if (StringUtils.isBlank(usuario.getSexo())) { message = "Por favor preencher o campo Sexo !"; } else if (StringUtils.isBlank(usuario.getContato().getEmail())) { message = "Por favor preencher o campo E-mail !"; } else if (usuario.isEnvioSms() && StringUtils.isBlank(usuario.getContato() .getTelefoneCelular())) { message = "Por favor preencher o campo Telefone Celular !"; } else if (StringUtils.isBlank(usuario.getContato() .getTelefoneCelular()) && StringUtils.isBlank(usuario.getContato() .getTelefoneResidencial()) && StringUtils.isBlank(usuario.getContato() .getTelefoneComercial())) { message = "Por favor preencher pelomenos um Telefone !"; } else if (!usuario.getSenha().equals(usuario.getConfirmarSenha())) { message = "Os campos senha e confirmar senha no conferem !"; } else if (StringUtils.isEmpty(usuario.getSenha())) { message = "Por Favor preencher o campo senha !"; } return message; } public Usuario insertDateValidation(Usuario usuario) throws Exception{ usuario.setDataDeCriacao(Calendar.getInstance()); return usuario; } public Usuario updateDateValidation(Usuario usuario) throws Exception{ usuario.setDataDeAtualizacao(Calendar.getInstance()); return usuario; } }
C++
UTF-8
2,492
2.515625
3
[]
no_license
#ifndef CITYSIMULATOR_ENTITY_SERVICE_HPP #define CITYSIMULATOR_ENTITY_SERVICE_HPP #include "base_service.hpp" #include "ecs.hpp" #include "world.hpp" const EntityID MAX_ENTITIES = 1024; typedef std::unordered_map<std::string, ConfigKeyValue> EntityTags; class EntityService : public BaseService { public: virtual void onEnable() override; virtual void onDisable() override; unsigned int getEntityCount() const; EntityID createEntity(); EntityIdentifier *createEntity(EntityType type); void killEntity(EntityID e); bool isAlive(EntityID e) const; EntityID getComponentMask(EntityID e) const; // systems void tickSystems(float delta); void renderSystems(WorldID currentWorld); // component management void removeComponent(EntityID e, ComponentType type); bool hasComponent(EntityID e, ComponentType type) const; BaseComponent *getComponentOfType(EntityID e, ComponentType type); template<class T> T *getComponent(EntityID e, ComponentType type) { return dynamic_cast<T *>(getComponentOfType(e, type)); } void addPhysicsComponent(EntityIdentifier &entity, World *world, const sf::Vector2i &startTilePos, float maxSpeed, float damping); void addRenderComponent(const EntityIdentifier &entity, const std::string &animation, float step, DirectionType initialDirection, bool playing); void addPlayerInputComponent(EntityID e); void addAIInputComponent(EntityID e); /** * @return A new body with new BodyData for the given entity */ b2Body *createBody(b2World *world, EntityIdentifier &entity, const sf::Vector2f &pos); /** * @return A new body with the same BodyData and position as the given body */ b2Body *createBody(b2World *world, b2Body *clone); /** * @return A new body with the same BodyData as the given body, at the given position */ b2Body *createBody(b2World *world, b2Body *clone, const sf::Vector2f &pos); private: EntityID entities[MAX_ENTITIES]; EntityIdentifier identifiers[MAX_ENTITIES]; EntityID entityCount; // loading std::map<EntityType, EntityTags> loadedTags; void loadEntities(ConfigurationFile &config, EntityType entityType, const std::string &sectionName); // components PhysicsComponent physicsComponents[MAX_ENTITIES]; RenderComponent renderComponents[MAX_ENTITIES]; InputComponent inputComponents[MAX_ENTITIES]; // systems std::vector<System *> systems; RenderSystem *renderSystem; // helpers BaseComponent *addComponent(EntityID e, ComponentType type); }; #endif
JavaScript
UTF-8
1,857
2.78125
3
[]
no_license
(function () { $(".register #reg").click(function () { var user=/^\w{4,10}$/g; var phone=/^1[3578]\d{9}/g; var psw=/^\w{6,12}/g; if($(".register #username").val()==""){ alert("请输入用户名"); $(".register #username").focus(); return; } if(user.test($(".register #username").val())!=true){ alert("用户名错误,请输入4~10位的字母、数字、下划线!"); $(".register #username").val("").focus(); return; } if($(".register #password").val()==""){ alert("密码不能为空,请输入密码"); $(".register #password").focus(); return; } if(psw.test($(".register #password").val())!=true){ alert("密码格式错误,请输入6~10位的字母、数字、下划线!"); $(".register #password").val("").focus(); return; } if($(".register #repassword").val()!=$(".register #password").val()) { alert("两次密码不一样,请重新输入"); $(".register #password").val("").focus() $(".register #repassword").val(""); return; } if($(".register #phone").val()==""){ alert("联系电话不能为空,请输入联系电话"); $(".register #phone").focus(); return; } if(phone.test($(".register #phone").val())!=true){ alert("联系电话格式错误请重新输入"); $(".register #phone").focus(); return; } location.href("login.html"); }); })();
Shell
UTF-8
551
3.078125
3
[]
no_license
#!/usr/bin/env bash function install_ansible_ubuntu() { sudo apt-get update sudo apt-get install software-properties-common sudo apt-add-repository ppa:ansible/ansible -y sudo apt-get update sudo apt-get install ansible -y } function install_awx_dependencies(){ for role in geerlingguy.repo-epel geerlingguy.git geerlingguy.ansible geerlingguy.docker geerlingguy.pip geerlingguy.nodejs geerlingguy.awx do sudo ansible-galaxy install ${role} -f done } install_ansible_ubuntu install_awx_dependencies `dirname $0`/awx.yml exit 0
Java
UTF-8
837
3.421875
3
[]
no_license
package me.surendra.leetcode.trees.n_ary_tree; import java.util.ArrayList; import java.util.List; /** * @see <a href="https://leetcode.com/problems/n-ary-tree-postorder-traversal/">N-ary Tree Postorder Traversal</a> */ public class PostOrderTraverser { /* Time Complexity - O(n) Space Complexity - 0(n) */ final List<Integer> returnList = new ArrayList<>(); public List<Integer> postorder(final Node root) { if (root == null) { return returnList; } for (Node children: root.children) { postorder(children); } returnList.add(root.val); return returnList; } public List<Integer> postorderUsingIterative(final Node root) { final List<Integer> returnList = new ArrayList<>(); return returnList; } }
TypeScript
UTF-8
1,514
3.0625
3
[ "MIT" ]
permissive
import Promises from '@promises/core'; import { IOptionalPromise } from '@promises/interfaces'; import forEachRightSeries from '../'; Promises._setOnPrototype('forEachRightSeries', forEachRightSeries); export default Promises; declare module '@promises/core' { interface Promises <T> { /** * @example * * let array: number[] = [3, 7, 1, 5]; * let promises: Promises<number[]> = Promises.resolve(array); * * console.log('before'); * promises.forEachRightSeries((value: number) => { * console.log(`start: ${ value }`); * return timeout((resolve) => { * console.log(`end: ${ value }`); * resolve(); * }, value); * }).then(() => { * console.log('complete'); * }); * console.log('after'); * * // => before * // => after * // => start 5 * // => end 5 * // => start 1 * // => end 1 * // => start 7 * // => end 7 * // => start 3 * // => end 3 * // => complete */ forEachRightSeries(this: Promises<T & ArrayLike<any>>, iteratee?: (value: T[keyof T & number], index: number, array: T) => IOptionalPromise<any>): Promises<T>; forEachRightSeries(this: Promises<T & object>, iteratee?: (value: T[keyof T], key: keyof T, object: T) => IOptionalPromise<any>): Promises<T>; } }
C++
UTF-8
612
2.71875
3
[]
no_license
#ifndef DEF_GUERRIER #define DEF_GUERRIER #include <personnage.h> class Guerrier : public Personnage { private: public: Guerrier(); virtual ~Guerrier(); virtual void action1(Personnage &adversaire); virtual void action2(Personnage *adversaire = nullptr); virtual void action3(Personnage *adversaire = nullptr); virtual void action4(Personnage &adversaire); virtual bool action1availible(); virtual bool action2availible(); virtual bool action3availible(); virtual bool action4availible(); }; #endif // DEF_GUERRIER
C++
UTF-8
4,746
2.625
3
[]
no_license
/* * EventLoopTimer.hpp * * Created on: Aug 3, 2017 * Author: ishan */ #ifndef SRC_TIMERCOMPONENT_EVENTLOOPTIMER_HPP_ #define SRC_TIMERCOMPONENT_EVENTLOOPTIMER_HPP_ #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/asio.hpp> #include <boost/signals2/signal.hpp> #include "../interfaces/IsdkComponent.hpp" #include <boost/date_time/posix_time/posix_time.hpp> class IEventloop:public IsdkComponent{ public: enum class TimerGroup:int{ TWO_HUNDRED_MILLIS, FIVE_HUNDRED_MILLIS, ONE_SECOND, FIVE_SECONDS, ONE_MINUTE, FIVE_MINUTE, ONE_HOUR }; using AsioEventLoop = boost::asio::io_service; // using TimerEvent = void(const TimerGroup&); using TimerEventSignal = boost::signals2::signal<void(const TimerGroup&)>; using TimerEventConnection = boost::signals2::connection; virtual std::shared_ptr<AsioEventLoop> getEventloop()=0; virtual std::shared_ptr<TimerEventSignal> getPeriodicSignal(const TimerGroup& grp)=0; virtual void start()=0; }; class EventLoop : public IEventloop{ private: const size_t two_hundred_millis = 200; const size_t five_hundred_millis = 500; const size_t one_second = five_hundred_millis * 2; const size_t five_seconds = one_second * 5; const size_t one_minute = five_seconds * 12; const size_t five_minute = one_minute * 5; const size_t one_hour = five_minute * 12; struct SignalTimer{ boost::asio::deadline_timer m_timer; TimerGroup m_timergroup; std::size_t m_millis; std::shared_ptr<TimerEventSignal> m_signal; SignalTimer(const std::shared_ptr<AsioEventLoop> el, const TimerGroup group, const size_t interval); ~SignalTimer(); void repeat(); void cancel(); }; public: EventLoop(Idependencymanager &dp); ~EventLoop(); virtual std::shared_ptr<AsioEventLoop> getEventloop() override; virtual std::shared_ptr<TimerEventSignal> getPeriodicSignal(const TimerGroup& grp) override; virtual void start() override; void launch(); private: std::shared_ptr<AsioEventLoop> m_asioeventloop; SignalTimer m_signaltwohundredmillis; SignalTimer m_signalfivehundredmillis; SignalTimer m_signalonesecond; SignalTimer m_signalfiveseconds; SignalTimer m_signaloneminute; SignalTimer m_signalfiveminute; SignalTimer m_signalonehour; std::thread mainloopthread; }; void EventLoop::start(){ mainloopthread = std::thread([this](){m_asioeventloop->run();}); } EventLoop::SignalTimer::SignalTimer(const std::shared_ptr<AsioEventLoop> el,const enum TimerGroup group, const size_t interval): m_timer(*el,boost::posix_time::seconds(0)),m_signal(std::make_shared<TimerEventSignal>()),m_millis(interval),m_timergroup(group){ } void EventLoop::SignalTimer::repeat(){ m_timer.expires_at(m_timer.expires_at() + boost::posix_time::milliseconds(m_millis)); m_timer.async_wait([this](const boost::system::error_code& ec){ if(!ec){ repeat(); (*m_signal)(m_timergroup); } }); } void EventLoop::SignalTimer::cancel(){ m_timer.cancel(); } EventLoop::SignalTimer::~SignalTimer(){ m_timer.cancel(); } EventLoop::~EventLoop(){ if(mainloopthread.joinable()) { mainloopthread.join(); m_asioeventloop->stop(); } } EventLoop::EventLoop(Idependencymanager &dp): m_asioeventloop(std::make_shared<boost::asio::io_service>()), m_signaltwohundredmillis(m_asioeventloop,TimerGroup::TWO_HUNDRED_MILLIS,200), m_signalfivehundredmillis(m_asioeventloop,TimerGroup::FIVE_HUNDRED_MILLIS,500), m_signalonesecond(m_asioeventloop,TimerGroup::ONE_SECOND,1000), m_signalfiveseconds(m_asioeventloop,TimerGroup::FIVE_SECONDS,5000), m_signaloneminute(m_asioeventloop,TimerGroup::ONE_MINUTE,5000*2), m_signalfiveminute(m_asioeventloop,TimerGroup::FIVE_MINUTE,5000*10), m_signalonehour(m_asioeventloop,TimerGroup::ONE_HOUR,5000*10*12) { (void)dp; m_signaltwohundredmillis.repeat(); m_signalfivehundredmillis.repeat(); m_signalonesecond.repeat(); m_signalfiveseconds.repeat(); m_signaloneminute.repeat(); m_signalfiveminute.repeat(); m_signalonehour.repeat(); } std::shared_ptr<IEventloop::AsioEventLoop> EventLoop::getEventloop() { return m_asioeventloop; } std::shared_ptr<IEventloop::TimerEventSignal> EventLoop::getPeriodicSignal(const TimerGroup& grp) { switch(grp){ case TimerGroup::TWO_HUNDRED_MILLIS: return m_signaltwohundredmillis.m_signal; case TimerGroup::FIVE_HUNDRED_MILLIS: return m_signalfivehundredmillis.m_signal; case TimerGroup::ONE_SECOND: return m_signalonesecond.m_signal; case TimerGroup::FIVE_SECONDS: return m_signalfiveseconds.m_signal; case TimerGroup::ONE_MINUTE: return m_signaloneminute.m_signal; case TimerGroup::FIVE_MINUTE: return m_signalfiveminute.m_signal; case TimerGroup::ONE_HOUR: return m_signalonehour.m_signal; } } #endif /* SRC_TIMERCOMPONENT_EVENTLOOPTIMER_HPP_ */
Markdown
UTF-8
9,775
2.90625
3
[]
no_license
--- title: 'Hibernate Tools: Tips for Reverse Engineering at the Command Line' author: mdesjardins categories: - blog tags: - hibernate - java - jpa - programming --- One of the ancillary projects of the Hibernate framework is the [Hibernate Tools][1] toolset. Using Hibernate Tools, you can automatically generate your mapping files (or, if you prefer, JPA annotations), POJOs, and DDL from your database schema. I&#8217;ve been enamored with the &#8220;Convention over Configuration&#8221; web frameworks lately (e.g., Grails, Django), and wondered how hard it&#8217;d be to reproduce some of their magic ORM functionality using Hibernate Tools. I&#8217;ve concluded that I&#8217;ve still got a <font style="font-weight: bold;">long</font> ways to go, but that I might have some worthwhile tips to share in the meantime. My progress has been impeded a bit because the documentation for Hibernate Tools is pretty weak. Hibernate Tools was really generated with Eclipse users in mind. A large portion of the documentation is devoted to explaining how to use the IDE. I&#8217;m not using Eclipse, and I intend to use the tools at the command-line, and command-line use really isn&#8217;t targeted. <font style="font-weight: bold;">0.) Get the tools and dependencies.</font> I&#8217;m still in the dark ages &#8211; I use ant instead of maven for builds, and need to track down jar dependencies the old fashioned way. In addition to the usual Hibernate jars, you&#8217;ll also need [hibernate-tools][2], [freemarker][3], and [jtidy][4]. <font style="font-weight: bold;"><br /> 1.) Setup an Ant task</font> This is pretty straightforward, and it is explained fairly well in the documentation. First, define yourself a Hibernate Tools task. Mine looks like this: ```xml <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"> <classpath> <fileset refid="hibernate.libs"/> <fileset refid="hibernatetools.libs"/> <fileset refid="apps.libs"/> <fileset refid="compile.libs"/> <pathelement path="${build}"/> <pathelement path="${basedir}"/> </classpath> </taskdef> ``` Next, create a task that uses our new definition. We&#8217;re going to be creating the mapping files and POJOs in this example. It will look something like this: ```xml <target name="gen_hibernate" depends="compile"> <delete dir="${genhbm}" /> <mkdir dir="${genhbm}" /> <hibernatetool> <jdbcconfiguration configurationfile="${src}/hibernate-connection.cfg.xml" revengfile="hibernate.reveng.xml" packagename="us.mikedesjardins.data" detectmanytomany="true" detectoptimisticlock="true" /> <hbm2hbmxml destdir="${genhbm}" /> <hbm2java destdir="${genhbm}"> <property key="jdk5" value="true" /> <property key="ejb3" value="false" /> </hbm2java> </hibernatetool> </target> ``` You&#8217;ll note that I&#8217;ve created a hibernate configuration file above which only contains connection information. This is because I ran into problems when I tried to use a hibernate configuration with cache configuration elements in it. You&#8217;ll also note a reference to a file called hibernate.reveng.xml. This file controls various aspects of the reverse engineering process. Mine is very simple &#8211; I&#8217;m working with MS SQL Server, and I don&#8217;t want it to include any of the system tables which begin with the prefix sys: ```xml <hibernate-reverse-engineering> <!-- Eliminate system tables --> <table-filter name="sys.*" exclude="true"> </hibernate-reverse-engineering> ``` That should be all that you need to do to get started. When you run this ant target, your domain object POJOs and Mappings should end up in the ${genhbm} directory. <font style="font-weight: bold;">2.) First Problem &#8211; Table Names</font> Let&#8217;s say you&#8217;re in a company that prefixes most of it&#8217;s tables with something silly, like &#8220;tb_&#8221;. In that case, Hibernate tools will happily create all kinds of POJOs for you named TbAccount, TbAddress, etc. This is probably not what you want. Fortunately, Hibernate tools let you provide your own &#8220;Reverse Engineering Strategy&#8221; class to deal with situations just like this. First, update your build target in Ant to include a reference to your strategy class as an attribute of the jdbcconfiguration element: ```xml <target name="gen_hibernate" depends="compile"> <delete dir="${genhbm}" /> <mkdir dir="${genhbm}" /> <hibernatetool> <jdbcconfiguration configurationfile="${src}/hibernate-connection.cfg.xml" revengfile="hibernate.reveng.xml" packagename="us.mikedesjardins.data" detectmanytomany="true" detectoptimisticlock="true" reversestrategy="us.mikedesjardins.hibernate.CustomReverseEngineeringStrategy"/> <hbm2hbmxml destdir="${genhbm}" /> <hbm2java destdir="${genhbm}"> <property key="jdk5" value="true" /> <property key="ejb3" value="false" /> </hbm2java> </hibernatetool> </target> ``` Next, we&#8217;ll need to create the strategy class. The documentation recommends that you extend the <font style="font-weight: bold;">DelegatingReverseEngineeringStrategy</font> class to do this, like this: ```java package us.mikedesjardins.hibernate; import org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy; import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; public class CustomReverseEngineeringStrategy extends DelegatingReverseEngineeringStrategy { public CustomReverseEngineeringStrategy(ReverseEngineeringStrategy delegate { super(delegate); } } ``` Unfortunately, I was unable to find any JavaDoc documentation for the Hibernate Tools classes, so I had to do a bit of trial-and-error. It turns out there is a method called tableToClassName that can be overridden. This class accepts a TableIdentifier as its input parameter, and returns the class name in a String. Thus, to remove the tb_ from the class, we could do something like this: ```java public String tableToClassName(TableIdentifier tableIdentifier) { String packageName = "us.mikedesjardins.data"; String className = super.tableToClassName(tableIdentifier); if (className.startsWith("Tb")) { className = className.substring(2); } return className; } ``` Compile your CustomReverseEngineeringStrategy class, make sure it&#8217;s on the hibernatetools task definition&#8217;s classpath, and re-run the task. Voila! The Tb&#8217;s are gone! There&#8217;s a similar method for column names named <font style="font-weight: bold;">columnToPropertyName</font> that handles naming your persisted class&#8217;s member variables. In my current project, the primary key columns are named the same as the table name, with &#8220;_id&#8221; appended to the end. However, in the object model, we like to just name the primary key property &#8220;id&#8221; to simplify the creation of generic DAOs. I use the columnToPropertyName method for this. <font style="font-weight: bold;">2.) Next Problem &#8211; The Generated POJOs need tweaking.</font> Perhaps the code that Hibernate generates is not to your liking. Maybe you work with standards-compliance-nazis who want a copyright header at the top of each class file. Or maybe all of your persisted objects implement the same interface for use with generic DAOs. Under the covers, Hibernate uses [freemarker][3] to generate POJOs and mapping files. The templates that it uses can be edited to your liking, but doing it is not very straightforward. First, unzip the hibernate tools jar into a temporary directory. Once unzipped, you&#8217;ll find a directory named pojo. This directory contains all of the templates used for POJO generation. Copy that directory into your build area and name it something like hib_templates. The hbm2java task is actually just an alias for another hibernate tools target called hbmtemplate. With hbmtemplate, you can configure the location of the source templates. So we&#8217;ll remove the hbm2java task from the gen_hibernate target, and replace it with an equivalent hbmtemplate task: ```xml <target name="gen_hibernate" depends="compile"> <delete dir="${genhbm}" /> <mkdir dir="${genhbm}" /> <hibernatetool> <jdbcconfiguration configurationfile="${src}/hibernate-connection.cfg.xml" revengfile="hibernate.reveng.xml" packagename="us.mikedesjardins.data" detectmanytomany="true" detectoptimisticlock="true" reversestrategy="us.mikedesjardins.hibernate.CustomReverseEngineeringStrategy"/> <hbm2hbmxml destdir="${genhbm}" /> <hbmtemplate templateprefix="pojo/" destdir="${genhbm}" template="hib_templates/Pojo.ftl" filepattern="{package-name}/{class-name}.java"> <property key="jdk5" value="true"> <property key="ejb3" value="false"> </hbmtemplate> </hibernatetool> </target> ``` Now that we&#8217;ve told hibernate tools where our template lives, we can edit it to our liking. For example, if we want to add a copyright notice to the top of each generated POJO, we could do so thusly: ``` // // Copyright 2008 Big Amalgamated Mega Global Software Corp. All Rights Reserved. // ${pojo.getPackageDeclaration()} // Generated ${date} by Hibernate Tools ${version} <#assign classbody> <#include "PojoTypeDeclaration.ftl"/>; { . . . (etc) ``` Now that we&#8217;ve done this, we can create more templates that, e.g., generate empty DAO classes, automatically create derived classes, etc. Hope that helps! [1]: http://www.hibernate.org/255.html [2]: http://www.hibernate.org/30.html [3]: http://freemarker.sourceforge.net/ [4]: http://jtidy.sourceforge.net/download.html
JavaScript
UTF-8
488
2.609375
3
[ "MIT" ]
permissive
import Promise from 'bluebird'; export const getImageSizeForSource = source => { const img = document.createElement('img'); img.src = source; return new Promise(resolve => { img.onload = () => resolve({ couldGetSize: true, width: img.naturalWidth, height: img.naturalHeight }); img.onerror = () => resolve({ couldGetSize: false, width: null, height: null }); }); };
Java
UTF-8
6,683
2.078125
2
[ "CC-BY-3.0", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-protobuf", "MIT" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.replication.regionserver; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; import org.apache.yetus.audience.InterfaceAudience; import org.apache.yetus.audience.InterfaceStability; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Class that does enqueueing/dequeuing of wal at one place so that we can update the metrics just at one place. */ @InterfaceAudience.Private @InterfaceStability.Evolving public class ReplicationSourceLogQueue { private static final Logger LOG = LoggerFactory.getLogger(ReplicationSource.class); // Queues of logs to process, entry in format of walGroupId->queue, // each presents a queue for one wal group private Map<String, PriorityBlockingQueue<Path>> queues = new ConcurrentHashMap<>(); private MetricsSource metrics; private Configuration conf; // per group queue size, keep no more than this number of logs in each wal group private int queueSizePerGroup; // WARN threshold for the number of queued logs, defaults to 2 private int logQueueWarnThreshold; private ReplicationSource source; public ReplicationSourceLogQueue(Configuration conf, MetricsSource metrics, ReplicationSource source) { this.conf = conf; this.metrics = metrics; this.source = source; this.queueSizePerGroup = this.conf.getInt("hbase.regionserver.maxlogs", 32); this.logQueueWarnThreshold = this.conf.getInt("replication.source.log.queue.warn", 2); } /** * Enqueue the wal * @param wal wal to be enqueued * @param walGroupId Key for the wal in @queues map * @return boolean whether this is the first time we are seeing this walGroupId. */ public boolean enqueueLog(Path wal, String walGroupId) { boolean exists = false; PriorityBlockingQueue<Path> queue = queues.get(walGroupId); if (queue == null) { queue = new PriorityBlockingQueue<>(queueSizePerGroup, new AbstractFSWALProvider.WALStartTimeComparator()); // make sure that we do not use an empty queue when setting up a ReplicationSource, otherwise // the shipper may quit immediately queue.put(wal); queues.put(walGroupId, queue); } else { exists = true; queue.put(wal); } // Increment size of logQueue this.metrics.incrSizeOfLogQueue(); // Compute oldest wal age this.metrics.setOldestWalAge(getOldestWalAge()); // This will wal a warning for each new wal that gets created above the warn threshold int queueSize = queue.size(); if (queueSize > this.logQueueWarnThreshold) { LOG.warn( "{} WAL group {} queue size: {} exceeds value of " + "replication.source.log.queue.warn {}", source.logPeerId(), walGroupId, queueSize, logQueueWarnThreshold); } return exists; } /** * Get the queue size for the given walGroupId. * @param walGroupId walGroupId */ public int getQueueSize(String walGroupId) { Queue<Path> queue = queues.get(walGroupId); if (queue == null) { return 0; } return queue.size(); } /** * Returns number of queues. */ public int getNumQueues() { return queues.size(); } public Map<String, PriorityBlockingQueue<Path>> getQueues() { return queues; } /** * Return queue for the given walGroupId Please don't add or remove elements from the returned * queue. Use {@link #enqueueLog(Path, String)} and {@link #remove(String)} methods respectively. * @param walGroupId walGroupId */ public PriorityBlockingQueue<Path> getQueue(String walGroupId) { return queues.get(walGroupId); } /** * Remove head from the queue corresponding to given walGroupId. * @param walGroupId walGroupId */ public void remove(String walGroupId) { PriorityBlockingQueue<Path> queue = getQueue(walGroupId); if (queue == null || queue.isEmpty()) { return; } queue.remove(); // Decrease size logQueue. this.metrics.decrSizeOfLogQueue(); // Re-compute age of oldest wal metric. this.metrics.setOldestWalAge(getOldestWalAge()); } /** * Remove all the elements from the queue corresponding to walGroupId * @param walGroupId walGroupId */ public void clear(String walGroupId) { PriorityBlockingQueue<Path> queue = getQueue(walGroupId); while (!queue.isEmpty()) { // Need to iterate since metrics#decrSizeOfLogQueue decrements just by 1. queue.remove(); metrics.decrSizeOfLogQueue(); } this.metrics.setOldestWalAge(getOldestWalAge()); } /* * Returns the age of oldest wal. */ long getOldestWalAge() { long now = EnvironmentEdgeManager.currentTime(); long timestamp = getOldestWalTimestamp(); if (timestamp == Long.MAX_VALUE) { // If there are no wals in the queue then set the oldest wal timestamp to current time // so that the oldest wal age will be 0. timestamp = now; } long age = now - timestamp; return age; } /* * Get the oldest wal timestamp from all the queues. */ private long getOldestWalTimestamp() { long oldestWalTimestamp = Long.MAX_VALUE; for (Map.Entry<String, PriorityBlockingQueue<Path>> entry : queues.entrySet()) { PriorityBlockingQueue<Path> queue = entry.getValue(); Path path = queue.peek(); // Can path ever be null ? if (path != null) { oldestWalTimestamp = Math.min(oldestWalTimestamp, AbstractFSWALProvider.WALStartTimeComparator.getTS(path)); } } return oldestWalTimestamp; } public MetricsSource getMetrics() { return metrics; } }
Markdown
UTF-8
2,929
2.609375
3
[]
no_license
# Project Task ## Tech Stack - Laravel - Mysql ## API Services - GET - POST - PATCH - DELETE ### API Endpoint localhost:8000 ## Functions Example ``` json POST /teams request: { "name":”Platform”, } response: { "id":"b7f32a21-b863-4dd1-bd86-e99e8961ffc6", "name”: “Platform”, } ``` ```json GET /teams/:id response: { "id":"b7f32a21-b863-4dd1-bd86-e99e8961ffc6", "name”: “Platform” } ``` ``` json POST /teams/:id/member request: { "name": "Vv", "email": "venkat.v@razorpay.com" } Response: { "id": "b7f32a21-b863-4dd1-bd86-e99e8961ffc6", "name": "Vv", "email": "venkat.v@razorpay.com" } ``` ```json DELETE /teams/:id/members/:id2 response: HTTP 204 No Content ``` ```json POST /teams/:id/tasks request: { "title": "Deploy app on stage", //mandatory "description" : "We have built a new app which needs to be tested thoroughly", //optional "assignee_id": "some member id from the same team", // optional "status": "todo" } response: { "id": "2a913e52-81ea-4987-874d-820969a62ea6", "title": "Deploy app on stage", //mandatory "description" : "We have built a new app which needs to be tested thoroughly", //optional "assignee_id": "some member id from the same team", // optional "status": "todo" } ``` ``` json GET /teams/:id/tasks/:id2 response: { "id": "2a913e52-81ea-4987-874d-820969a62ea6", "title": "Deploy app on stage", //mandatory "description" : "We have built a new app which needs to be tested thoroughly", //optional "assignee_id": "some member id from the same team", // optional "status": "todo" } ``` ``` json PATCH /teams/:id/tasks/:id2 request: { "title": "Deploy app on preprod",//optional "description":"new description",//optional "assignee_id": "745dbe00-2520-420a-985d-0c3f5d280e57",//optional "status": "done" } response: { "id": "2a913e52-81ea-4987-874d-820969a62ea6", "title": "Deploy app on preprod",//optional "description":"new description",//optional "assignee_id": "745dbe00-2520-420a-985d-0c3f5d280e57", "status": "done" } ``` ``` json GET /teams/:id/tasks/ response: [ { "id": "2a913e52-81ea-4987-874d-820969a62ea6", "title": "Deploy app on preprod",//optional "description":"new description",//optional "assignee_id": "745dbe00-2520-420a-985d-0c3f5d280e57", "status": "todo" }, ] ``` ``` json GET /teams/:id/members/:id2/tasks/ response: [ { "id": "2a913e52-81ea-4987-874d-820969a62ea6", "title": "Deploy app on preprod",//optional "description":"new description",//optional "assignee_id": "745dbe00-2520-420a-985d-0c3f5d280e57", "status": "todo" }, ] ``` ## To Run locally `$ php artisan migrate` `$ php artisan serve` ## To Run on docker `$ docker-compose up --build` ## **Attention**: Before running the API edit the env file, add Database username and password
JavaScript
UTF-8
764
2.609375
3
[]
no_license
import React from 'react'; const SearchBar = ({ searchTerm, setSearchTerm }) => { const handleChange = (event) => { event.preventDefault(); setSearchTerm(event.target.value); }; const handleShowAllClick = (event) => { event.preventDefault(); setSearchTerm(''); }; const ShowAllBtn = () => { if (searchTerm.length >= 3) { return ( <button type="button" onClick={handleShowAllClick}>Show All Questions</button> ); } return ( <div /> ); }; return ( <form> <input type="text" value={searchTerm} onChange={handleChange} placeholder="Have a question? Search for answers…" style={{maxWidth: '50%', width: '50%'}}/> {ShowAllBtn()} </form> ); }; export default SearchBar;
Markdown
UTF-8
3,364
2.90625
3
[]
no_license
# LOGFLOWS Software Engineer Challenge - Frontend - [Overview](#overview) - [Functional Requirements](#functional-requirements) - [Other Requirements](#other-requirements) - [Frameworks and Libraries](#frameworks-and-libraries) - [Using the Mock API](#using-the-mock-api) - [Implementation Notes](#implementation-notes) - [Wireframes](#wireframes) ## Overview the application should allow the user to view, create, update and delete user information and joborders. ## Functional Requirements 1. as a user i need to view user and joborders with embedded map using [Google Maps](https://developers.google.com/maps/) from the list of user information. 2. as a user i need to update a user and add joborder from the list of user information. 3. as a user i need to add a user from the list of user information. 4. as a user i need to delete a user from the list of user information. *NOTE: please do not include your google API key in your submission. Instead use a configurable config file to store the api key.* ## Other Requirements 1. major functionalities should be cover on the test. 2. support for modern browsers. 3. instructions and `readme.md` on how to use the application should be included. 4. use of git. 5. end to end test is strong bonus ## Frameworks and Libraries we mainly use VueJs at LOGFLOWS, however you are free to use whatever framework that you are familiar with (vue/react/angular). ## Using the Mock API The Mock API has been deployed at [https://61f2aba52219930017f5080b.mockapi.io](https://61f2aba52219930017f5080b.mockapi.io) - Method: `GET` - get all users - URL path: `/users` - Method: `GET` - get specific user - URL path: `/users/<:id>` - Method: `POST` - insert user - URL path: `/users` - Sample Request body: ``` { "name": "Peter Parker", "image": "https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/800.jpg", "companyName": "logflows", "email": "spiderman@gmail.com", "remarks": "remarks 1", "jobOrders": [ { "pickup": { "latitude": 22.335538, "longitude": 114.176169, "address": "Kowloon Tong" }, "dropoff": { "latitude": 22.319181, "longitude": 114.170008, "address": "Mong Kok" } } ] } ``` - Method: `PUT` - update user - URL path: `/users/<:id>` - Sample Request body: ``` { "name": "Bruce Wayne" "email": "batman@gmail.com" } ``` - Method: `DELETE` - delete specific user - URL path: `/users/<:id>` ## Implementation Notes - you can work on your own schedule, but a complete solution is expected within 14 days. - your code should be modular. Each module should focus on doing one thing well. - you must be frugal in the use of third-party libraries. (don’t include a 300 KB library just for one helper function) - you can implement any additional features that you think will enhance the user experience. ## Wireframes these wireframes serve as a reference for the UI of your application. You can be creative with UI/UX and additional features. [wireframe](https://xd.adobe.com/spec/a1516e48-56fb-4e40-739e-cf27bcd00d47-d760/) **Questions? Suggestions? Ping us at: [johnpaul@logflows.com](mailto:johnpaul@logflows.com)**
Java
UTF-8
1,085
1.789063
2
[]
no_license
package com.ucpro.feature.video.player.view; import android.view.View; import com.ucpro.feature.video.player.b.v; /* compiled from: ProGuard */ final class ad implements v<Boolean> { final /* synthetic */ af a; ad(af afVar) { this.a = afVar; } public final /* synthetic */ void a(int i, Object obj) { Boolean bool = (Boolean) obj; View findViewById = this.a.a.findViewById(i); if (findViewById != null) { if (i != 44) { findViewById.setVisibility(bool.booleanValue() ? 0 : 4); switch (i) { case 28: af.a(this.a, this.a.b, true); return; case 33: af.a(this.a, this.a.c, false); return; default: return; } } else if (bool.booleanValue()) { this.a.d.b(); this.a.d.d(); } else { this.a.d.e(); } } } }
Python
UTF-8
4,035
2.515625
3
[]
no_license
import time import pandas as pd import numpy as np import networkx as nx import random as rand import csv import ogb.nodeproppred as ogbn from torch_geometric.data import Data import torch_geometric.utils as utils import torch_geometric import torch MAX_NODES = -1 values_dict = {} def choose_node_dataset(): name = 'arxiv' name = 'ogbn-' + name ogb = ogbn.NodePropPredDataset(name=name, root='dataset/') split = 'train' return (ogb, split) def first_split(ogb, split): total_num_nodes = ogb[0][0]['num_nodes'] if(split == 'no-split'): nodes_ini = list(range(0, ogb[0][0]['num_nodes'])) else: split_idx = ogb.get_idx_split() nodes_ini = split_idx[split] edges_ini = ogb[0][0]['edge_index'] print(ogb[0][0]) feature = input('Choose feature: ') node_feat = ogb[0][0][feature] return (total_num_nodes, nodes_ini, edges_ini, node_feat) def second_split_and_shuffle(total_num_nodes, nodes_ini, edges_ini): rand.shuffle(nodes_ini) nodes = nodes_ini[0:MAX_NODES] nodes_tensor = torch.LongTensor([x for x in nodes]) edges_tensor = torch.LongTensor([x for x in edges_ini]) edges, _ = utils.subgraph(nodes_tensor, edges_tensor, num_nodes=total_num_nodes) return (nodes, edges) def get_dict_features(features): dict_features = {} for i in range(len(features)): dict_feature = {str(j): features[i][j] for j in range(0, len(features[i]))} dict_features[i] = dict_feature return dict_features def get_nx_graph(nodes, edges, features): undirected = utils.is_undirected(edges) edge_list = [] for i in range(len(edges[0])): edge_list.append((int(edges[0][i]), int(edges[1][i]))) if undirected: G = nx.Graph() else: G = nx.DiGraph() G.add_nodes_from(nodes) G.add_edges_from(edge_list) dict_features = get_dict_features(features) nx.set_node_attributes(G, dict_features) CC = [G.subgraph(c).copy() for c in sorted(nx.algorithms.components.strongly_connected_components(G), key=len, reverse=True)] print(len(CC)) return (G, undirected) def compute_assortativity(G, num_features): for i in range(num_features): assortativity = nx.attribute_assortativity_coefficient(G, str(i)) value = 'Assortativity_' + str(i+1) values_dict[value] = assortativity def write_csv(i): if i==0: with open('results_OGBN.csv', 'w', newline='') as f: w = csv.DictWriter(f, values_dict.keys()) w.writeheader() w.writerow(values_dict) else: with open('results_OGBN.csv', 'a', newline='') as f: w = csv.DictWriter(f, values_dict.keys()) w.writerow(values_dict) def analysis(ogb, split): total_num_nodes, nodes_ini, edges_ini, node_feat = first_split(ogb, split) for i in range(5): nodes, edges = second_split_and_shuffle(total_num_nodes, nodes_ini, edges_ini) G, undirected = get_nx_graph(nodes, edges, node_feat) values_dict['Directed'] = (not undirected) time_ini = time.time() num_features = len(node_feat[0]) compute_assortativity(G, num_features) time_end = time.time() - time_ini values_dict['Execution time'] = time_end write_csv(i) def main(): ogb, split = choose_node_dataset() global MAX_NODES MAX_NODES = int(input('Choose MAX_NODES: ')) analysis(ogb, split) def test(): nodes = [0,3,5] edge_list = [(0,5), (3,5)] features = [[0.02,0.003], [0.07,0.2], [0.001,0.2], [0.001,0.02], [0.1,0.05], [0.01,0.09]] dict_features = {} for i in range(len(features)): dict_feature = {str(j): features[i][j] for j in range(0, len(features[i]))} dict_features[i] = dict_feature print(dict_features) G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edge_list) nx.set_node_attributes(G,dict_features) R = nx.Graph() R.add_node(4, color=1, dim=2) R.add_node(5, color=67, dim=9) for i in range(2): assortativity = nx.attribute_assortativity_coefficient(G, str(i)) print(assortativity) if __name__ == '__main__': main()
Markdown
UTF-8
709
2.609375
3
[ "Apache-2.0" ]
permissive
--- layout: post title: '[BOJ] 2293 : 동전 1' author: wookje.kwon comments: true date: 2018-03-27 14:23 tags: [boj, dynamic-programming] --- [2293 : 동전 1](https://www.acmicpc.net/problem/2293) ## 풀이 `dp[i] = 동전 i원을 만들 수 있는 방법의 수` `dp[i] = dp[i - coins[]]` ## 코드 ```cpp main() { int N, K, x, i, j; int dp[10001] = { 1, }; scanf("%d %d", &N, &K); for (i = 1; i <= N; i++) { scanf("%d", &x); for (j = 0; j <= K - x; j++) dp[j + x] += dp[j]; } printf("%d", dp[K]); } ``` ### 아무말 백준, 백준 온라인 저지, BOJ, Baekjoon Online Judge, C, C++, 씨, 씨쁠쁠, JAVA, algorithm, 자바, 알고리즘, 자료구조, 문제, 문제 풀이, 풀이
Markdown
UTF-8
19
2.859375
3
[ "MIT" ]
permissive
# udacity-aos-learn
Java
UTF-8
3,230
2.265625
2
[]
no_license
package com.ems.dao; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.SessionFactoryUtils; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.ems.model.SceneLightLevelTemplate; import com.ems.model.SceneTemplate; import com.ems.model.Switch; import com.ems.model.SwitchGroup; import com.ems.server.ServerConstants; import com.ems.utils.ArgumentUtils; @Repository("sceneTemplateDao") @Transactional(propagation = Propagation.REQUIRED) public class SceneTemplateDao extends BaseDaoHibernate { static final Logger logger = Logger.getLogger(SceneTemplateDao.class.getName()); public static final String SWITCH_CONTRACTOR = "Select new SceneTemplate(s.id,"+ "s.name)"; public List<SceneTemplate> loadAllSceneTemlates() { try { List<SceneTemplate> results = null; String hsql = SWITCH_CONTRACTOR + " from SceneTemplate s"; Query q = getSession().createQuery(hsql.toString()); results = q.list(); if (results != null && !results.isEmpty()) { return results; } } catch (HibernateException hbe) { throw SessionFactoryUtils.convertHibernateAccessException(hbe); } return null; } public List<SceneTemplate> getSceneTemplateByName(String name) { try { List<SceneTemplate> results = null; String hsql = "Select new SceneTemplate(s.name) from SceneTemplate s where s.name=?"; Query q = getSession().createQuery(hsql.toString()); q.setParameter(0, name); results = q.list(); if (results != null && !results.isEmpty()) { return results; } } catch (HibernateException hbe) { throw SessionFactoryUtils.convertHibernateAccessException(hbe); } return null; } public SceneTemplate createNewSceneTemplate(SceneTemplate newSceneTemplate) { return (SceneTemplate) saveObject(newSceneTemplate); } public SceneTemplate getSceneTemplateById(Long scenetemplateId) { try { SceneTemplate rs = null; List<SceneTemplate> results = null; String hsql = "from SceneTemplate s where s.id=?"; Query q = getSession().createQuery(hsql.toString()); q.setParameter(0, scenetemplateId); results = q.list(); if (results != null && !results.isEmpty()) { rs = results.get(0); return rs; } } catch (HibernateException hbe) { throw SessionFactoryUtils.convertHibernateAccessException(hbe); } return null; } public int deleteSceneTemplate(Long sceneTemplateId) { int status; try { String hsql = "delete from SceneTemplate sl where sl.id=?"; Query q = getSession().createQuery(hsql.toString()); q.setParameter(0, sceneTemplateId); status = q.executeUpdate(); } catch (HibernateException hbe) { throw SessionFactoryUtils.convertHibernateAccessException(hbe); } return status; } }
JavaScript
UTF-8
4,882
3.28125
3
[]
no_license
class Obstacle { constructor(ctx, canvasSize, speed, canvasWidth, canvasHeight, imgObstSrc) { this.ctx = ctx this.canvasSize = canvasSize this.speed = speed this.canvasWidth = canvasWidth this.canvasHeight = canvasHeight // gap es la diferencia en segundos entre obstaculos, //igual no es necesaria this.obstMaxGap = 4 this.obstMinGap = 2 this.imgObstSrc = imgObstSrc this.imageInstance = new Image() this.imageInstance.src = `./images/${this.imgObstSrc}` //Dentro de este array hay que hacer un push de un nuevo elemento //cada X segundos, siendo X un espectro predefinido this.obstacleArray = [] // this.obstMaxSize = { w: 100, h: 100 } this.obstMinSize = { w: 100, h: 100 } this.obstSize = { vertical: { w: Math.floor(this.obstMinSize.w + Math.random() * (this.obstMaxSize.w)), h: Math.floor(this.obstMinSize.h + Math.random() * (this.obstMaxSize.h)) }, horizontal: { w: Math.floor(this.obstMinSize.w + Math.random() * (this.obstMaxSize.w)), h: Math.floor(this.obstMinSize.h + Math.random() * (this.obstMaxSize.h)) } } this.osbtPosition = { bottom: { x: Math.floor(Math.random() * (this.canvasWidth)), y: this.canvasHeight }, top: { x: Math.floor(Math.random() * (this.canvasWidth)), y: 0 }, left: { x: 0, y: Math.floor(Math.random() * (this.canvasHeight)) }, right: { x: this.canvasWidth, y: Math.floor(Math.random() * (this.canvasHeight)) }, } } // DIBUJAR TODOS LLAMA A DIBUJAR A CADA UNO //ahora mismo se están dibujando en lugares aleatorios pegados al canvas //por fuera, por eso no se ven drawObst() { this.drawObstFromBottom() this.drawObstFromLeft() this.drawObstFromRight() this.drawObstFromTop() } //FUNCIONES DE DIBUJAR DEPENDIENDO DEL ORIGEN drawObstFromBottom() { this.ctx.drawImage(this.imageInstance, this.osbtPosition.bottom.x, this.osbtPosition.bottom.y, this.obstSize.vertical.w / 2, this.obstSize.vertical.h) } drawObstFromTop() { this.ctx.drawImage(this.imageInstance, this.osbtPosition.top.x, (this.osbtPosition.top.y) - (this.obstSize.vertical.h), this.obstSize.vertical.w / 2, this.obstSize.vertical.h) } drawObstFromRight() { this.ctx.drawImage(this.imageInstance, this.osbtPosition.right.x, this.osbtPosition.right.y, this.obstSize.horizontal.w, this.obstSize.horizontal.h / 2) } drawObstFromLeft() { this.ctx.drawImage(this.imageInstance, (this.osbtPosition.left.x) - (this.obstSize.horizontal.w), this.osbtPosition.left.y, this.obstSize.horizontal.w, this.obstSize.horizontal.h / 2) } moveObst() { this.moveFromBottom() this.moveFromTop() this.moveFromRight() this.moveFromLeft() } moveFromBottom() { this.osbtPosition.bottom.y -= this.speed } moveFromTop() { this.osbtPosition.top.y += this.speed } moveFromLeft() { this.osbtPosition.left.x += this.speed } moveFromRight() { this.osbtPosition.right.x -= this.speed } } //FUNCIONES PARA CONTROLAR EL TAMAÑO // setLimitHorizontal() { // this.obstMaxSize.w = 100 // this.obstMaxSize.h = 30 // this.obstMinSize.w = 80 // this.obstMinSize.h = 20 // } // setLimitVertical() { // this.obstMaxSize.w = 30 // this.obstMaxSize.h = 100 // this.obstMinSize.w = 20 // this.obstMinSize.h = 80 // } // setSizeObst(originSide) { // switch (originSide) { // case this.originSide === "right": // setLimitHorizontal(); // //como consecuencia: // // this.obstMaxSize.w = 100 // // this.obstMaxSize.h = 30 // // this.obstMinSize.w = 80 // // this.obstMinSize.h = 20; // break; // case this.originSide === "left": // setLimitHorizontal(); // break; // case this.originSide === "top": // setLimitVertical(); // break; // case this.originSide === "bottom": // setLimitVertical(); // break; // } // }
C
UTF-8
2,455
3.890625
4
[]
no_license
/* * ===================================================================================== * * Filename: angle.c * * Description: Calculate the quadrant based on input angle * Quadrant I: angle between 0 and 90 * Quadrant II: angle between 90 and 180 * Quadrant III: angle between 180 and 270 * Quadrant IV: angle between 270 and 360 * * Version: 1.0 * Created: 01/31/2019 08:35:05 AM * Revision: none * Compiler: gcc * * Author: Keaton Muhlestein (), keatonmuhlestein@mail.weber.edu * Organization: WSU * * ===================================================================================== */ #include <stdio.h> #include <math.h> #include <stdlib.h> // Constants // Function Prototypes // Main Function int main() { int angle; printf("Please enter an angle in degrees: "); scanf("%d", &angle); angle = angle % 360; if (angle < 0) { angle = abs(360 + angle); } if (angle > 0 && angle < 90) { printf("Your angle is in Quadrant I.\n"); } else if (angle > 90 && angle < 180) { printf("Your angle is in Quadrant II.\n"); } else if (angle > 180 && angle < 270) { printf("Your angle is in Quadrant III.\n"); } else if (angle > 270 && angle < 360) { printf("Your angle is in Quadrant IV.\n"); } else if (angle == 0 || angle == 90 || angle == 180 || angle == 270) { switch(angle) { case 0: printf("Your angle is between Quadrant I and Quadrant IV.\n"); printf("Also your angle is on the positive X-axis.\n"); break; case 90: printf("Your angle is between Quadrant I and Quadrant II.\n"); printf("Also your angle is on the positive Y-axis.\n"); break; case 180: printf("Your angle is between Quadrant II and Quadrant III.\n"); printf("Also your angle is on the negative X-axis.\n"); break; case 270: printf("Your angle is between Quadrant III and Quadrant IV.\n"); printf("Also your angle is on the negative Y-axis.\n"); break; } } else { printf("Invalid response\n"); } return 0; } // Function Definitions
Markdown
UTF-8
1,360
2.65625
3
[]
no_license
# 使用 Amazon SageMaker 训练自己的数据 常用的机器学习的DEMO或者演示项目中使用到的基本全是公开已经制作好并经过经验的数据集,而工作中实际运用到生产的数据往往是未经过处理的。这个项目演示了如何从零开始(指手头没有任何数据),收集数据,筛选数据,给数据打标签,并通过有限数量的jpeg图片(3000张图片),生成 MXNet 常用的 RecordIO 数据格式。并利用自定义的小规模数据集,进行迁移学习(transfer learning),在短时间低成本的情况下获取准确率较高的模型。 另外,可以使用上述生成的数据集交给 Amazon SageMaker Ground Truth 快速进行数据打标签的测试。 ## Tranfer learning 迁移学习 `./transfer-learning-setup.sh` 在 Amazon SageMaker 中打开notebook 'Image-classification-transfer-learning-highlevel.ipynb',参照步骤进行迁移学习 训练完成后可以运行 `./transfer-learning-clean.sh` 清空目录下不需要的文件 ## 测试 Amazon SageMaker Ground Truth `./ground-truth-setup.sh` 在 Amazon SageMaker Ground Truth 中按照页面中的步骤创建项目,其中数据的输入文件复制命令行脚本的输出结果。 提交打标签任务后,可以运行`./ground-truth-clean.sh` 清空不必要的文件并删除S3存储桶
SQL
UTF-8
6,943
3.640625
4
[]
no_license
/************************************************************************************************ NPM1: Update to find the molecular information closest to arrival */ DROP TABLE IF EXISTS molecular.cp ; CREATE TABLE molecular.cp SELECT PatientId, PtMRN FROM caisis.vdatasetpatients; DROP TABLE IF EXISTS molecular.range ; CREATE TABLE molecular.range SELECT cp.PtMRN, cp.PatientId, UWID, ArrivalDx, Protocol, ResponseDescription , AMLDxDate , ArrivalDate , TreatmentStartDate , ResponseDate -- Arrival , 'DIAGNOSIS' AS Type , CASE WHEN AMLDxDate IS NULL THEN NULL ELSE date_add(AMLDxDate, INTERVAL -35 DAY) END AS StartDateRange , ArrivalDate AS TargetDate , CASE WHEN TreatmentStartDate IS NULL THEN NULL ELSE TreatmentStartDate END AS EndDateRange FROM amldatabase2.pattreatment LEFT JOIN molecular.cp on cp.PtMRN = pattreatment.UWID WHERE UWID IS NOT NULL GROUP BY UWID, ArrivalDate UNION SELECT cp.PtMRN, cp.PatientId, UWID, ArrivalDx, Protocol, ResponseDescription , AMLDxDate , ArrivalDate , TreatmentStartDate , ResponseDate -- Arrival , 'ARRIVAL' AS Type , CASE WHEN ArrivalDate IS NULL THEN NULL WHEN AMLDxDate > date_add(ArrivalDate, INTERVAL -35 DAY) THEN date_add(AMLDxDate, INTERVAL -5 DAY) -- Since the patient was diagnosed not that long ago, look at dx values as well as arrival values ELSE date_add(ArrivalDate, INTERVAL -35 DAY) END AS StartDateRange , ArrivalDate AS TargetDate , CASE WHEN TreatmentStartDate IS NULL THEN NULL ELSE TreatmentStartDate END AS EndDateRange FROM amldatabase2.pattreatment LEFT JOIN molecular.cp on cp.PtMRN = pattreatment.UWID WHERE UWID IS NOT NULL GROUP BY UWID, ArrivalDate UNION SELECT cp.PtMRN, cp.PatientId, UWID, ArrivalDx, Protocol, ResponseDescription , AMLDxDate , ArrivalDate , TreatmentStartDate , ResponseDate -- Arrival , 'TREATMENT' AS Type , ArrivalDate AS StartDateRange , CASE WHEN TreatmentStartDate IS NULL THEN NULL ELSE date_add(TreatmentStartDate, INTERVAL -1 DAY) END as TargetDate -- try to get labs from the day before treatment starts , CASE WHEN TreatmentStartDate IS NULL THEN NULL ELSE date_add(TreatmentStartDate, INTERVAL +2 DAY) END AS EndDateRange FROM amldatabase2.pattreatment LEFT JOIN molecular.cp on cp.PtMRN = pattreatment.UWID WHERE UWID IS NOT NULL GROUP BY UWID, ArrivalDate UNION SELECT cp.PtMRN, cp.PatientId, UWID, ArrivalDx, Protocol, ResponseDescription , AMLDxDate , ArrivalDate , TreatmentStartDate , ResponseDate -- Arrival , 'RESPONSE' AS Type , CASE WHEN ResponseDate IS NULL THEN NULL ELSE date_add(ResponseDate, INTERVAL -14 DAY) END AS StartDateRange , ResponseDate AS TargetDate , CASE WHEN ResponseDate IS NULL THEN NULL ELSE date_add(ResponseDate, INTERVAL +14 DAY) END AS EndDateRange FROM amldatabase2.pattreatment LEFT JOIN molecular.cp on cp.PtMRN = pattreatment.UWID WHERE UWID IS NOT NULL GROUP BY UWID, ArrivalDate ORDER BY UWID, ArrivalDate, TYPE; ALTER TABLE `molecular`.`range` ADD INDEX `UWID` (`UWID`(10) ASC), ADD INDEX `ArrivalDate` (`ArrivalDate` ASC); ALTER TABLE `molecular`.`range` ADD COLUMN `arrival_id` DOUBLE NULL DEFAULT NULL AFTER `EndDateRange`; UPDATE `molecular`.`range` a, caisis.`arrivalidmapping` b SET a.arrival_id = b.arrival_id WHERE a.Patientid = b.Patientid and a.ArrivalDate = b.ArrivalDate ; DROP TABLE IF EXISTS molecular.cp ; SELECT * FROM molecular.range ; DROP TABLE IF EXISTS molecular.t3 ; CREATE TABLE molecular.t3 SELECT t1.UWID , t2.PtMRN , t2.PatientId , t1.ArrivalDx , t1.Protocol , t1.ResponseDescription , t1.AMLDxDate , t1.ArrivalDate , t1.TreatmentStartDate , t1.ResponseDate , concat(t1.Type,'_','{1}') AS Type , t1.StartDateRange , t1.TargetDate , t1.EndDateRange , abs(timestampdiff(DAY,t1.TargetDate,t2.LabDate)) AS DaysFromTarget , t2.LabTestId , t2.LabDate , t2.LabTest , t2.LabResult , t2.LabUnits , t2.BaseLengthTest , t2.BaseLength , t2.RatioTest , t2.Ratio FROM molecular.range t1 LEFT JOIN caisis.v_npm1mutation as t2 on t1.UWID = t2.PtMRN WHERE t2.LabDate between t1.StartDateRange and t1.EndDateRange AND UPPER(LabResult) NOT RLIKE 'ORDER' AND UPPER(LabResult) NOT RLIKE 'NOT NEEDED' AND UPPER(LabResult) NOT RLIKE 'WRONG' AND UPPER(LabResult) NOT RLIKE 'CORRECTION' AND UPPER(LabResult) NOT RLIKE 'SEE INTERPRETATION' AND UPPER(LabResult) NOT RLIKE 'SPECIMEN RECEIVED' ORDER BY t1.UWID, t1.TargetDate, DaysFromTarget; DROP TABLE IF EXISTS molecular.v_npm1mutation ; CREATE TABLE molecular.v_npm1mutation SELECT UWID, PtMRN, PatientId , ArrivalDate , TargetDate , min(DaysFromTarget) as DaysFromTarget , Type , LabDate , LabResult , LabUnits , BaseLengthTest , BaseLength , RatioTest , Ratio FROM molecular.t3 GROUP BY UWID, TargetDate, type ; ALTER TABLE ADD INDEX `PatientId` (`PatientId` ASC), ADD INDEX `PtMRN` (`PtMRN`(10) ASC), ADD INDEX `UWID` (`UWID`(10) ASC), ADD INDEX `LabDate` (`LabDate` ASC), ADD INDEX `ArrivalDate` (`ArrivalDate` ASC); DROP TABLE IF EXISTS molecular.t3 ; /* select * FROM caisis.playground ; SELECT * FROM caisis.molecularlabs ; SELECT * FROM molecular.range SELECT * FROM molecular.v_npm1mutation; */ /* Have Vasta Global look for date of death for these patients */ DROP TABLE IF EXISTS temp.FindLastContactDate ; CREATE TABLE temp.FindLastContactDate SELECT * FROM temp.allarrivals WHERE PtDeathDate IS NULL AND LastInformationDate < '2017-10-01' AND BackBoneName IS NOT NULL # AND Response LIKE '%cr%' AND YEAR(ArrivalDate) > 2008; SELECT PtMRN, MIN(arrivalDate) AS FirstArrivalDate , PtBirthdate , PtLastName , PtDeathDate , PtDeathType , LastStatusDate , LastStatusType , LastInformationDate FROM temp.FindLastContactDate GROUP BY 1;
Ruby
UTF-8
2,098
2.578125
3
[ "MIT" ]
permissive
module WatcherFactory def self.create(queue_name, config, default_config) watcher_class = config[:name].to_s require "bender/watchers/#{watcher_class}" watcher_class.classify.constantize.new(queue_name, default_config) end end class Watcher def name @name ||= safe_queue_name("#{@queue_name}-#{self.class.to_s.underscore}") end def initialize(queue_name, options) @queue_name = queue_name @options = options load_queue end def start subscribe end def load_queue @queue ||= Bender::Client.sqs.queues.create( self.name, @options[:create_options] ) rescue Exception => ex Bender.logger.error("#{self.class}: #{ex.message}#{ex.backtrace.join("\n")}") end def subscribe while Bender::Client.keep_running? do Bender.logger.info("Polling #{@queue.arn} for #{self.class.to_s}") @queue.poll(@options[:poll_options]) do |received_message| safe_perform(received_message.body) end end rescue Exception => ex Bender.logger.error("#{self.class}: #{ex.message}#{ex.backtrace.join("\n")}") end def publish(message, ack = nil) unless message.is_a?(Hash) message = JSON.parse(message) end message.merge!(ack) if ack @queue.send_message(message.to_json) true rescue Exception => ex Bender.logger.error("#{self.class}: #{ex.message}#{ex.backtrace.join("\n")}") false end private def safe_queue_name(name) name[0..79] end def safe_perform(json) message = JSON.parse(json, :symbolize_names => true) rescue :invalid if message == :invalid Bender.logger.error("#{self.class}: Unable to parse message: #{json}") else # requires an ack ? ack = message.delete(:ack_queue_name) self.perform(message) if ack Bender.logger.info("#{self.class}: Ack'ing on #{ack}") Bender::Client.sqs.queues.named(ack).send_message({:ack => true}.to_json) end end rescue Exception => ex Bender.logger.error("#{self.class}: Perform : #{ex.message}#{ex.backtrace.join("\n")}") end end
Java
UTF-8
5,917
2.125
2
[]
no_license
package com.tapan.flickrsample.adapters; import android.content.Context; import android.graphics.Bitmap; import android.support.annotation.NonNull; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.tapan.flickrsample.R; import com.tapan.flickrsample.listeners.OnClickListener; import com.tapan.flickrsample.objects.FeedObject; import com.tapan.flickrsample.utils.Utils; import java.util.List; public class FeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final int TYPE_INFO = 0; private final int TYPE_DATA = 1; private Context context; private List<FeedObject.Items> feedList; private int selectedPos = -1; private OnClickListener onClickListener; public FeedAdapter(Context context, List<FeedObject.Items> feedList) { onClickListener = (OnClickListener) context; this.context = context; this.feedList = feedList; } @Override public int getItemViewType(int position) { if (selectedPos!= -1){ int infoPos = Utils.getInfoPosition(selectedPos); if(position == infoPos) { return TYPE_INFO; } else { return TYPE_DATA; } } else { return TYPE_DATA; } } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if(viewType == TYPE_DATA) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false); return new DataViewHolder(v); } else { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_info, parent, false); return new InformationViewHolder(v); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) { if(holder instanceof DataViewHolder) { DataViewHolder viewHolder = (DataViewHolder) holder; int feedlistPosition = position; if(selectedPos!=-1) { int infoPos = Utils.getInfoPosition(selectedPos); if(infoPos<=position) { feedlistPosition = feedlistPosition-1; } if(selectedPos == position) { viewHolder.vSelection.setVisibility(View.VISIBLE); viewHolder.vTriangle.setVisibility(View.VISIBLE); } else { viewHolder.vSelection.setVisibility(View.GONE); viewHolder.vTriangle.setVisibility(View.INVISIBLE); } } else { viewHolder.vSelection.setVisibility(View.GONE); viewHolder.vTriangle.setVisibility(View.INVISIBLE); } FeedObject.Items item = feedList.get(feedlistPosition); if (item.getMedia() != null && item.getMedia().getM() != null && item.getMedia().getM().length() > 0) { Glide.with(context) .load(item.getMedia().getM()) .apply(new RequestOptions() .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .placeholder(R.drawable.default_placeholder)) .into(viewHolder.iv); } else { Glide.with(context) .load(R.drawable.default_placeholder) .apply(new RequestOptions() .diskCacheStrategy(DiskCacheStrategy.RESOURCE)) .into(viewHolder.iv); } final int finalFeedlistPosition = feedlistPosition; viewHolder.iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onClickListener != null) { onClickListener.onClick(finalFeedlistPosition); } } }); } else { InformationViewHolder viewHolder = (InformationViewHolder) holder; FeedObject.Items item = feedList.get(selectedPos); viewHolder.tv.setText(Html.fromHtml(item.getDescription())); } } @Override public int getItemCount() { if(selectedPos==-1) { return feedList.size(); } else { return feedList.size()+1; } } public void setData(List<FeedObject.Items> feedList) { this.feedList = feedList; notifyDataSetChanged(); } public static class DataViewHolder extends RecyclerView.ViewHolder { ImageView iv; View vSelection; View vTriangle; public DataViewHolder(View v) { super(v); iv = v.findViewById(R.id.iv); vSelection = v.findViewById(R.id.vSelection); vTriangle = v.findViewById(R.id.vTriangle); } } public static class InformationViewHolder extends RecyclerView.ViewHolder { TextView tv; public InformationViewHolder(View v) { super(v); tv = v.findViewById(R.id.tv); } } public int getSelectedPos() { return selectedPos; } public void setSelectedPos(int selectedPos) { this.selectedPos = selectedPos; } }
Markdown
UTF-8
2,391
2.609375
3
[]
no_license
--- published: true title: Ifai ordena a SAT revele a qué empresas condonó impuestos twitt: "Son montos que deja de recaudar el Estado, por lo que constituye una transferencia negativa de recursos públicos, argumenta comisionada." author: La Jornada location: Nacional category: Principales layout: posts --- ![](http://i.imgur.com/n3PXBIrm.jpg)México, DF. El Servicio de Administración Tributaria (SAT) deberá dar conocer la lista de empresas a las que condonó créditos fiscales en los últimos seis años, por concepto de deudas y atrasos en el pago de impuestos, especificando nombre, fecha y monto, resolvió el Instituto Federal de Acceso a la Información y Protección de Datos (Ifai). Al ser requerida la información, el SAT manifestó que ésta se encuentra reservada por 12 años, en razón de que se trata de datos de contribuyentes protegidos por el secreto fiscal, el cual obliga a los servidores públicos del organismo a guardar absoluta reserva de las declaraciones y datos suministrados por los contribuyentes, o por terceros con ellos relacionados, así como de los obtenidos en el ejercicio de sus facultades de comprobación. El recurso de revisión ante el Ifai fue turnado a la comisionada María Elena Pérez-Jaén, quien celebró una audiencia en la que tuvo acceso a la documentación clasificada. Tras un ejercicio de ponderación de derechos, la comisionada determinó que la reserva de la información invocada por el SAT era improcedente. Advirtió que la condonación es un gasto fiscal que comprende, en términos generales, los montos que deja de recaudar el Estado, por lo que constituye una transferencia de recursos públicos en sentido negativo. Que también es un beneficio a favor del contribuyente, que implica un gasto público y que como tal debe reportarse. Además de que la decisión de condonar un crédito fiscal no involucra únicamente al Servicio de Administración Tributaria y a la persona que se le condona el adeudo, sino a toda la sociedad, en tanto que por disposición constitucional, todos los mexicanos están obligados a contribuir al gasto público de manera proporcional y equitativa. En ese sentido, la difusión de la información solicitada es uno de los mecanismos para que la sociedad evalúe si el SAT está cumpliendo correctamente con su atribución de “recaudar eficientemente” y “evitar la evasión y elusión fiscal”.
Markdown
UTF-8
1,577
3.390625
3
[]
no_license
--- layout: post title: Functional programming in scala image: /assets/img/2012-10-1-scala/scala.jpg readtime: 5 minutes --- Its been a while since i managed to get the time post on my blog, I've been really busy with work and home life, I've recently enrolled in an online course. Functional programming in Scala. I haven't really touched upon much function programming (except for javascript and a bit of F#). I like it! And i can see its uses! It feels a bit weird entering back into the java world, firing up eclipse etc. I guess i have just become reliant on the friendly features of Visual Studio. Anyway, here are the answers to the assignment I just submitted for the Functional Programming in Scala! Pascals Triangle ```scala def pascal(c: Int, r: Int): Int = if (c == 0 || r == c) 1 else (pascal(c - 1, r - 1) + pascal(c, r - 1)); ``` Parentheses Balancing ```scala def balance(chars: List[Char]): Boolean = { def countParenthese(index: Int, list: List[Char]): Boolean = { if (index == 0 && list.isEmpty) true else if (index < 0 || list.isEmpty) false else if (list.head == '(') countParenthese(index + 1, list.tail) else if (list.head == ')') countParenthese(index - 1, list.tail) else countParenthese(index, list.tail) } countParenthese(0, chars) } ``` Change Counting ```scala def countChange(money: Int, coins: List[Int]): Int = if (money == 0) 1 else if (money < 0 || coins.isEmpty) 0 else countChange(money, coins.tail) + countChange(money - coins.head, coins) } ```
Markdown
UTF-8
21,682
3.125
3
[ "MIT" ]
permissive
--- title: "Turning Data into Information" layout: class course: "GIS 520: Advanced Geospatial Analytics" topic: "Geospatial Data Issues" order: 1 esri-course: http://training.esri.com/gateway/index.cfm?fa=catalog.webCourseDetail&CourseID=2017 --- {% include topic-header.html %} [This particular course](http://training.esri.com/gateway/index.cfm?fa=catalog.webCourseDetail&CourseID=2017) provided by ESRI's Virtual Campus introduces GIS users to basic spatial data structures, sources of error, and basic spatial analysis. I'll describe each of the six modules in more detail below. ## Module Navigation: [Basics of Data and Information](#module-i-basics-of-data-and-information) [Cartography, Map Production, and Geovisualization](#module-ii-cartography-map-production-and-geovisualization) [Query and Measurement](#module-iii-query-and-measurement) [Transformations and Descriptive Summaries](#module-iv-transformations-and-descriptive-summaries) [Optimization and Hypothesis Testing](#module-v-optimization-and-hypothesis-testing) [Uncertainty](#module-vi-uncertainty) ## Module I: Basics of Data and Information ### Problem: Conduct an analysis to determine which residential zones fall within the flood zone. ### Analysis Procedures: #### Strategies: This analysis will use ArcGIS's Spatial Analyst extension. I will select only the residential zones from the full land-use raster and find where it intersects with the flood zone raster. The result will show only those residential areas that fall within the flood zone. #### Methods: To complete this analysis I used two input raster layers with the goal of finding all residential areas that fall within the flood zone. The easiest method for completing this analysis is to use raster math. This technique requires reclassifying the input rasters to binary values. The areas that we are interested in (residential zones, the flood zone) will have a value of one, while all other areas have a value of zero. With residential land use pixels and flood zone pixels scored as one, and all other pixels scored zero we simply multiply the two layers. Any land use type other than residential when multiplied will result in a final score of zero. Our final map shows our desired result: residential areas that fall within a flood zone. This information can be used by insurance adjusters to set home/flood insurance rates. ![Flood Zone Diagram]({{ site.baseurl }}/images/gis520/module1-diagram.png "Flood Zone analysis Method Diagram") The image above shows the steps involved in this analysis. ![Residential areas in the Flood zone]({{ site.baseurl }}/images/gis520/floodPlain.png "Residential areas in the Flood zone") The image above shows all residential areas that fall within the flood zone in green. ### Discussion: #### Difficulties: This is a fairly straight-forward exercise. The only difficulty I encountered was due to the fact that I just upgraded to ArcGIS 10.2, and my Spatial Analyst extension was not enabled by default. #### Evaluation: To quickly ensure that my results make sense I used the swipe tool to ensure that all areas deemed to be residential and in the flood zone (the green pixels in the image above) were in fact residential in the original land use raster (yellow pixels in the original). ![Residential areas in the Flood zone]({{ site.baseurl }}/images/gis520/floodPlain.gif "Residential areas in the flood zone were residential in the original raster") The image above compares my final result with the original land use raster to ensure that all areas in my result were originally of the residential category. ### Application &amp; Reflection: This simple raster analysis is a common technique in the world of natural resource management. As an example, if I were interested in finding a rare species I might make a similar model using habitat characteristics including distance to water, distance to roads, soil characteristics, etc. This use-case wouldn't be as cut-and-dry as whether a house falls within a flood zone or not as species can survive in sub-optimal habitat. A particular pixel should not be discarded just because it doesn't meet every single habitat requirement. It this case we might use a habitat quality scale where we aggregate the different layer scores into a raster representing habitat quality. We could then further classify those scores into groups such as Optimal, Marginal, and Poor. With this knowledge we could prioritize surveys for the rare species in the optimal habitat. [Back to top](#top) ## Module II: Cartography, Map Production, and Geovisualization ### Problem: How can we visualize a dataset at different scales using GIS? Why would the scale dictate how, or which layer is drawn on a map? ### Analysis Procedures: #### Strategies: Using a GIS to visualize spatial datasets gives us the ability to explore our data at varying spatial scales. The importance of layers and their detail depends directly on the scale of the map. We can use ArcGIS to simplify features so the detail is coarse for small-scale maps. As we zoom in on a feature we might want all the detail afforded to us by our original dataset. This is usually the case for large-scale maps. #### Methods: ArcGIS provides a cartographic tool for simplifying lines and polygons. For this exercise I will reduce the amount of detail in the original Coastline feature by creating a simplified version. To complete this technique I would display only the simplified features at 1:200,000 and above. When I zoom to larger scale the simplified coastline will turn off, and the more complex coastline will be turned on. ![Scale dependent Features]({{ site.baseurl }}/images/gis520/module2-diagram.png "Scale dependent Features") ### Discussion: #### Difficulties: I didn't experience any difficulties with the simplify geoprocessing tool. The only difficulty one might encounter is making sure to turning the correct layer on and off depending on the map's scale. #### Evaluation: This technique successfully displayed the amount of complexity required to display a coastline at varying scales. The example below keeps both layers on at large-scales to juxtapose the complexity of the two layers. In a production map it would be appropriate to display only one of the two layers at a time. ![Scale dependent features]({{ site.baseurl }}/images/gis520/simplify.gif "Scale dependent detail") In the image above contrasts the two coastline shapefiles showing two levels of detail. You'll also notice that the city points and their labels disappear when you get to a very large scale. ### Application &amp; Reflection: My job as a Regional GIS professional requires that I work at varying spatial scales. My agency has over a dozen field stations in the Southeast that collect and work with data at much larger scales on a daily basis. When aggregating or comparing datasets region-wide it is important to keep scale in mind. I often use the simplify tool in my cartographic products to account for different scales. [Back to top](#top) ## Module III: Query and Measurement ### Problem: Use measurement and queries in a raster analysis to find suitable areas for a new vineyard. ### Analysis Procedures: #### Strategies: In order to locate a new vineyard I need to specify the environmental factors that facilitate good grape growing. A combination of elevation, temperature, and aspect contribute to a successful vineyard. The ability of a vineyard to attract patrons to their location also increases sales so proximity to freeways can increase visitorship. #### Methods: Once again I'll use the raster calculator tool in ArcGIS to query desirable environmental factors to locate my new vineyard. In each case I'll reclassify the continuous value of a given raster layer to either one, which represents a hospitable grape growing environment, or zero, which are areas that I will exclude from consideration. Once I have my environmental factors I'll consider the accessibility of my location to my customers. In this case my input layer is a vector dataset of freeways. I need to convert the vector dataset to a raster so I can compare apples-to-apples using only rasters in my final analysis. The euclidean distance tool will do this for me; I receive an output raster representing each cell as a distance from a freeway. Again I'll enforce a limit on the total distance that I can locate from a freeway to ensure high visitorship. Finally I combine all of these rasters to find only those cells with a value of one for each of the different raster layers. ![Vineyard Siting Analysis]({{ site.baseurl }}/images/gis520/module3-diagram.png "Vineyard Siting Analysis") The diagram above shows the analysis steps used to isolate potential vineyard sites. Geographic features are in blue, geoprocessing tasks are in light red, queries and measurements are in orange, and the final output is in dark red. The intermediate rasters (Good [variable]) have a value of 1 if they meet the query criteria and a value of 0 if they do not. To get the final output these intermediate rasters are multiplied together; any cell that has a value of 0 for will be excluded from the final output. ### Discussion: #### Difficulties: I made a mistake in defining the criteria for the elevation raster calculation. When I tried to re-run the tool with the correct value of 200 I was unable to overwrite the original raster. It would be helpful if ESRI provided an option for overwriting an output when you run a geoprocessing tool rather than forcing you to change environment variables, or manually deleting a dataset. #### Evaluation: ![Potential Land for a Vineyard]({{ site.baseurl }}/images/gis520/vineyardPotential.png "Potential Land for a Vineyard") In the photo above the areas in bright yellow represent land suitable for a new vineyard. These areas fulfill all of our requirements including aspect, slope, elevation, and proximity to a freeway. Most of the factors in this raster analysis were fairly well distributed across the entire area of interest. The limiting factor (the least common factor to meet our criteria) was elevation greater than 200. Based on a visual analysis of the individual input layers and the final output I am confident in my results. ### Application &amp; Reflection: This exercise is similar to the flood zone exercise from module one. The difference here is that we're considering a larger number of layers, and we're combining both raster and vector input layers. The directions for this exercise suggest testing that each individual layer is equal to a value of 1. We could just as easily multiply the separate rasters together. Any layer with a value of zero (unsuitable for growing grapes) would remove that cell from consideration in our final raster, because any number multiplied by zero equals zero. [Back to top](#top) ## Module IV: Transformations and Descriptive Summaries Transformation and descriptive summaries each provide something new. Until now we've simply been asking our data questions. To generate new information we can use tools in GIS and Statistics. ### Problem: How can we use spatial interpolation to create a surface that infers elevation between a series of sample points? ### Analysis Procedures: #### Strategies: Creating an interpolated surface of any variable can be useful in describing a spatial phenomenon in a cost effective way. Rather than surveying every inch of a given area of interest we can survey a representative sample of the whole area and infer values that fall in between our sample sites. This strategy is useful with continuous variables like mercury concentration in soil as opposed to discrete variables like land cover types. In this exercise I'll take an input of sample elevation points and interpolate a surface using ArcGIS's Spatial Analyst toolkit. #### Methods: In the interpolation exercise from this module we were given a feature class of sample locations describing elevation. We used these elevation points as the input for two different interpolation methods: Kriging and Inverse Distance Weighting (IDW). Each method produces a continuous elevation surface by filling in the gaps between sampling points. We then created a hillshade for each surface to as a cartographic technique to exemplify the differences between the two methods. We repeated the process above with the same sample dataset once more for each interpolation method after reducing the number of sample points by 5% then compared the results. ![Comparing Interpolation Methods]({{ site.baseurl }}/images/gis520/module4-diagram.png "Comparing Interpolation Methods") The diagram above shows the first iteration of this exercise. The blue element is our input sample points. The red arrows represent geoprocessing tasks with the purple elements representing the tool inputs. Finally the dark red elements are the final outputs from the exercise. ### Discussion: #### Difficulties: I didn't experience any difficulties completing this exercise, but there are difficulties associated with collecting the data that you would like to interpolate. Choosing sample locations can have a huge impact on the results you get from an interpolation analysis. Whenever possible you should employ a random sampling regime in order to get representative results. Many times sampling is opportunistic focusing on areas that are easy to get to near roads or waterways, which might not be representative of the entire area of interest. It can be difficult to get a representative sample of a given area. Private landowners may not grant you access to sample their land. You may be sampling an area with extremely dense vegetation, which could make it difficult to sample throughout the entire area. #### Evaluation: ![Swipe Tool]({{ site.baseurl }}/images/gis520/KrigIDWSwipe.gif "Swipe Tool: IDW vs. Kriging") The image above shows two different interpolation techniques, IDW vs. Kriging, on the same input dataset. This is also an example of geovisualization using ESRI's built in &#8220;swipe&#8221; tool. The results of both interpolation methods appear to be accurate. The two different techniques employ different methodologies, which explains why the two surfaces had different outputs. The sample points we were given were fairly well distributed. If, instead, there was lots of clustering I would trust the results of Kriging over IDW because Kriging takes clustering into account. ### Application &amp; Reflection: Interpolation techniques are common in natural resource management agencies. This is a great technique for surveying the presence of submerged aquatic vegetation (SAV) in the Chesapeake Bay. Without interpolation SAV surveys would be very difficult and costly and might require divers to visually inspect large swaths of the bay's floor. Instead we can drag an SAV rake from a boat at random sample locations to collect species and density information. Given these points we can use interpolation techniques to create a surface that shows the distribution and density of different SAV species. SAV is an important indicator of ecosystem health so the interpolated surfaces could be used to target restoration work. [Back to top](#top) ## Module V: Optimization and Hypothesis Testing The term optimization is very general and can refer to a number of different analysis techniques. The common denominator is that we're either trying to minimize costs or maximize benefits using a series of spatial datasets. ### Problem: Determine the most cost effective path for the construction of a new power line. ### Analysis Procedures: #### Strategies: We will be using a series of raster datasets to find the least-cost path for the new power line using ArcMap's Spatial Analyst extension. We will assign values to specific attributes that contribute to the overall cost of a construction project. We will then use ArcMap to determine the exact path that minimizes the total cost of construction for the new power line. #### Methods: We will be categorizing the cost of construction based on slope, cost-weighted distance analysis, and land-use through using raster math. Higher grades of slope require additional engineering, which in turn raises costs. As the total distance of the power line increases so does cost. Finally, certain land-cover types are associated with increased costs as well. For example it is much more cost effective to traverse abandoned or vacant land than commercial or residential areas. ![Least Cost Path]({{ site.baseurl }}/images/gis520/module5-diagram.png "Optimization: Least Cost Path") The diagram above shows the analysis steps required to find the least cost path for the new power line connecting the power plant with the Jamula substation. Inputs are in blue, intermediate files are in green, geoprocessing tasks are in light red, and the final output is in dark red. In some cases where back-to-back geoprocessing tasks were required the intermediate file was left out of the diagram for succinctness. The diagram above shows ### Discussion: #### Difficulties: #### Evaluation: ![Least Cost Path]({{ site.baseurl }}/images/gis520/leastCostPath.png "Least Cost Path") The dashed green line in the image above shows the least-cost path for construction of a new power line connecting a power plant with a substation. ### Application &amp; Reflection: With the explosion of natural gas development in the United States development of energy infrastructure is growing rapidly. As a natural resource management agency we are charged with maintaining biodiversity even with increased pressure from development. Pipeline projects that connect natural gas pads with refineries must comply with State and Federal law. Both developers and biologists must consider the same regulations and geographic data when proposing and approving development projects. Pipeline projects would use very similar methods as those completed in this exercise in order to minimize costs not only of construction, but also degradation of wildlife habitat. Often times these types of projects cannot completely avoid wildlife and their habitat, and are thus required to mitigate any damage by restoring other habitat for the benefit of wildlife. [Back to top](#top) ## Module VI: Uncertainty Error is a fact of life when it comes to geographic data. The world is infinitely complex, and therefore impossible to model without some generalization or error. Additionally, the instruments we use to collect geographic data come with inherent error. ### Problem: How can we describe error quantitatively? ### Analysis Procedures: #### Strategies: #### Methods: ### Discussion: #### Difficulties: #### Evaluation: ### Application &amp; Reflection: A Global Positioning Systems (GPS) use a series of satellites orbiting the earth paired with stations on the ground with a known position. The hand-held GPS device you use to take lat/lon positions uses signals from both of these devices in order to record your current position. Many factors effect the quality of the data collected include the GPS module used, the number of satellites you can connect to just to name a few. Generally speaking the error produced by these devices will be similar if you are collecting a series of points all at once. If, instead, you will be collecting data over the course of several days, weeks, months, or years the position and availability of GPS Satellites may be grossly different and can result in different amounts of error. There are different techniques for measuring error depending on the type of data you're working with. For nominal data (categories) we use something called a [confusion matrix](http://en.wikipedia.org/wiki/Confusion_matrix). As an example let's assume we are digitizing land-use types based on aerial imagery. We create polygons of contiguous areas that represent the same land-use type. To test the accuracy of our photo interpretation we ground truth our data most likely using a stratified sample (we're unlikely to be able to ground truth every record). Before we get started we need to create a grid on top of our data so we're selecting random cells rather than inspecting entire polygons. As we ground truth we record instances where our photo interpretation was correct, and in instances where our interpretation was wrong we record the correct value for that cell. The resulting table is called a confusion matrix. We can use our confusion matrix to estimate how likely our photo interpretations are correct, and the likelihood of random errors. [Kappa index]() I often find that consumers of maps assume that the data used is valid and properly applied to a given problem or scenario. I suspect this comes from the fact that any map you review requires a certain amount of personal analysis. Since the reader is coming to their own conclusions they don't hesitate to accept them. At times the reader of a map is unaware that the cartographer has intentionally led them to a certain conclusion. Any GIS practitioner that has read [how to lie with maps](http://www.markmonmonier.com/how_to_lie_with_maps_14880.htm) knows how easy it is to manipulate the impression left on your map's end-user. With that said it is important to not only understand the limitations of a dataset you are prepared to map, but to clearly state the limitations to your readers before you dive into any real analysis. [Back to top](#top)
JavaScript
UTF-8
5,461
4.3125
4
[]
no_license
function addStringToStorage(event) { let number = event.target.innerText //store number in an array numberStorage.push(number) console.log(numberStorage); } // show number in display //[9, 4, 2] would be 942 function renderDisplay() { let numbersDisplayed = numberStorage.join("") answerElement.innerText = numbersDisplayed } function handleNumberOrOperatorClick(event) { addStringToStorage(event) renderDisplay() } let buttonContainer = document.querySelector('.numbers'); let answerElement = document.querySelector('#answer'); buttonContainer.addEventListener('click', handleNumberOrOperatorClick); //empty array for stored numbers let numberStorage = [] //clear button clears the screen function handleClear() { numberStorage = [] renderDisplay() } // let clearButton = document.querySelector('.clear') //next add the eventListener for the click evnet clearButton.addEventListener('click', handleClear) //then call a function that will clear the input let addButton = document.querySelector('.add'); let minusButton = document.querySelector('.minus'); let multiplyButton = document.querySelector('.multiply'); let divideButton = document.querySelector('.divide'); function UseOperator() { if (numberStorage.includes('+')) { addProblem(); numberStorage = [] console.log('it worked'); } else if (numberStorage.includes ('-')) { minusProblem(); numberStorage = [] console.log('does this work'); } else if (numberStorage.includes('x')){ multiplyProblem(); // numberStorage = [] DOES THIS NEED TO BE ADDED } else if (numberStorage.includes('÷')) { divideProblem(); } } addButton.addEventListener('click', handleNumberOrOperatorClick) minusButton.addEventListener('click', handleNumberOrOperatorClick) multiplyButton.addEventListener('click', handleNumberOrOperatorClick) divideButton.addEventListener('click', handleNumberOrOperatorClick) function addProblem() { let numbers = numberStorage.filter(item => item !== '+' ) let solution = parseInt(numbers[0]) + parseInt(numbers[1]) // for var i = -; i < numbers.length; i++) { // solution = solution + parseInt(numbers[i]) // } answerElement.innerText = solution } function minusProblem() { let numbers = numberStorage.filter(item => item !== '-' ) let solution = numbers[0] - numbers[1] //for (var i = 0; i < numbers.length; i++ ) { // solution = solution - parseInt(numbers[i]) // } answerElement.innerText = solution } function multiplyProblem() { let numbers = numberStorage.filter(item => item !== 'x' ) console.log(numbers) let solution = numbers[0] * numbers[1] //for var i = 0; i < numbers.length; i++) { //solution = solution * parseInt(number[i]) //} answerElement.innerText = solution } function divideProblem() { let numbers = numberStorage.filter(item => item !== '÷' ) let solution = numbers[0] / numbers[1] //for var( i = 0; i < numbers.length; i++) { // solution = solution / parseInt(numbers[i]) // } answerElement.innerText = solution } let equalsButton = document.querySelector('#equals') equalsButton.addEventListener('click', UseOperator) //////////////////////////////////////////////////////////////////////////// // //I want to click a number button and make it display in the window // // // /* STEPS // 1. make single number appear in the screen section. // 2. store data typed // myArray = [] // 3.perform match with two single digits // */ // // // function clickedButton(event) { // // console.log("YES"); // // } // // let button = document.querySelectorAll('div.number button'); // // eachButton = addEventListener('click', clickedButton) // // // function showNumber() { // // console.log(button.textContent); //all that changed is this line // screen.textContent = button.textContent; // } // let button = document.querySelector('.numbers button'); // button.addEventListener('click', showNumber); // // let screen = document.querySelector('#answer'); // // let lis = document.querySelectorAll('ul.sizes li'); // for(let i=0; i < lis.length; i++) { // let li = lis[i]; // li.addEventListener('click', msg); // // // // /* // function matchSpanText (){ // let span = li.parentElement.previousElementSibling; // span.textContent = li.textContent; // } // li.addEventListener('click', matchSpanText); // */ // // // // /* // //What I think I need to add // let lis = document.querySelectorAll('ul.sizes li'); // for(let i=0; i < lis.length; i++) { // let li = lis[i]; // li.addEventListener('click', msg); // // */ // // // // /* ANSER FROM WILLIAM // function clickedButton(event){ // let number = event.target.innerText // answerElement.innerText = number // } // let buttonContainer = document.querySelector('.numbers'); // let answerElement = document.querySelector('#answer'); // // buttonContainer.addEventListener('click', clickedButton) // */ // // /*make the operators // /* // function testButtonClick(event){ // let number = event.target.innerText // answerElement.innerText = number // } // let buttonContainer = document.querySelector('.numbers'); // let answerElement = document.querySelector('#answer'); // // buttonContainer.addEventListener('click', testButtonClick) // // //look up const - constant vs var vs let // */ // // /* // function msg() { // console.log('really'); // } // let buttonClicked = document.querySelector('.numbers'); // buttonClicked.addEventListener('click', msg); // */
Shell
UTF-8
311
2.84375
3
[ "MIT" ]
permissive
#!/bin/bash alias git-tree="git log --graph --date=relative --decorate --pretty=\"format:%C(yellow)%h %C(blue)%>(12)%ad %C(green)%<(7)%aN%C(auto)%d %C(reset)%s\"" # rebase to origin/master function grebase { git fetch --all git stash save prebase git rebase ${@-origin/master} git stash pop }
Ruby
UTF-8
603
2.546875
3
[ "MIT" ]
permissive
module ScormCloud class CLI def self.start command = ARGV.shift appid = ENV['SCORM-CLOUD-APPID'] secret = ENV['SCORM-CLOUD-SECRET'] opts = {} while ARGV.length > 0 case ARGV[0] when '--appid' ARGV.shift; appid = ARGV.shift when '--secret' ARGV.shift; secret = ARGV.shift else name = ARGV.shift[2..-1].to_sym value = ARGV.shift opts[name] = value end end sc = ScormCloud.new(appid, secret) puts sc.call(command, opts) end end end
C#
UTF-8
499
2.53125
3
[]
no_license
using NUnit.Framework; using RecreateMe.Sports; namespace TheRealDealTests.DomainTests.Sports { [TestFixture] public class SportTests { private Sport _sport; [SetUp] public void SetUp() { _sport = new Sport(); } [Test] public void HasAName() { const string name = "Volleyball"; _sport.Name = name; Assert.That((object) _sport.Name, Is.EqualTo(name)); } } }
Java
UTF-8
762
1.75
2
[]
no_license
package com.pg.crudOps; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @ComponentScan @EnableJpaRepositories @Import(RepositoryRestMvcAutoConfiguration.class) @EnableAutoConfiguration public class Application { public static void main( String[] args ) { SpringApplication.run(Application.class, args); } }
C++
UTF-8
455
3.171875
3
[]
no_license
class Solution { public: string reverseString(string s) { if (s.length() == 2){ char result = s[1]; s[1] = s[0]; s[0] = result; }else{ for (int i = 0; i < s.length()/2; i++){ cout<<i<<endl; char index = s[i]; cout<<index; s[i] = s[s.length()-i-1]; s[s.length()-i-1] = index; } } return s; } };
C#
UTF-8
5,843
2.984375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; namespace Banzai.Factories { public interface INodeFactory { /// <summary> /// Gets a node by the specified type. /// </summary> /// <typeparam name="TNode">Type of the node to return.</typeparam> /// <returns>The first node matching the TNode type.</returns> TNode GetNode<TNode>(); /// <summary> /// Gets a node by the specified type and registered name. /// </summary> /// <param name="name">Name of the node to return (as registered).</param> /// <typeparam name="TNode">Type of the node to return.</typeparam> /// <returns>The first node matching the TNode type.</returns> TNode GetNode<TNode>(string name); /// <summary> /// Gets all nodes matching the requested type. /// </summary> /// <typeparam name="TNode">Type of the nodes to return.</typeparam> /// <returns>Enumerable of nodes matching the requested type.</returns> IEnumerable<TNode> GetAllNodes<TNode>(); /// <summary> /// Gets a flow matching the specified name and subject type. /// </summary> /// <param name="name">Name of flow to return.</param> /// <returns>Flow matching the requested criteria.</returns> INode<T> GetFlow<T>(string name); /// <summary> /// Builds a flow matching the specified flow component. /// </summary> /// <param name="flowRoot">Definition of the flow to build.</param> /// <returns>Flow matching the requested flow root.</returns> INode<T> BuildFlow<T>(FlowComponent<T> flowRoot); /// <summary> /// Builds a flow matching the specified flow component. /// </summary> /// <param name="serializedFlow">Serialized definition of the flow to build.</param> /// <returns>Flow matching the requested flow root.</returns> INode<T> BuildFlow<T>(string serializedFlow); /// <summary> /// Method overridden to provide a root FlowComponent based on a name. /// </summary> /// <param name="name">Name of the flow root.</param> /// <returns>FlowComponent corresponding to the named root.</returns> FlowComponent<T> GetFlowRoot<T>(string name); } /// <summary> /// Interface for the node factory. Used to create child nodes. /// </summary> /// <typeparam name="T">Type of the underlying node subject.</typeparam> public interface INodeFactory<T> { /// <summary> /// Gets a node by the specified type. /// </summary> /// <typeparam name="TNode">Type of the node to return.</typeparam> /// <returns>The first node matching the TNode type.</returns> TNode GetNode<TNode>() where TNode : INode<T>; /// <summary> /// Gets a node by the specified type and registered name. /// </summary> /// <param name="name">Name of the node to return (as registered).</param> /// <typeparam name="TNode">Type of the node to return.</typeparam> /// <returns>The first node matching the TNode type.</returns> TNode GetNode<TNode>(string name) where TNode : INode<T>; /// <summary> /// Gets a node by the specified type. /// </summary> /// <param name="type">Type of the node to return.</param> /// <returns>The first node matching the TNode type.</returns> INode<T> GetNode(Type type); /// <summary> /// Gets a node by the specified type and registered name. /// </summary> /// <param name="name">Name of the node to return (as registered).</param> /// <param name="type">Type of the node to return.</param> /// <returns>The first node matching the TNode type.</returns> INode<T> GetNode(Type type, string name); /// <summary> /// Gets the default registered node for the specified types. /// </summary> /// <param name="types">Types of the nodes to return.</param> /// <returns>The first node matching each TNode type.</returns> IEnumerable<INode<T>> GetNodes(IEnumerable<Type> types); /// <summary> /// Gets all nodes matching the requested type. /// </summary> /// <typeparam name="TNode">Type of the nodes to return.</typeparam> /// <returns>Enumerable of nodes matching the requested type.</returns> IEnumerable<TNode> GetAllNodes<TNode>() where TNode : INode<T>; /// <summary> /// Gets a flow matching the specified name and subject type. /// </summary> /// <param name="name">Name of flow to return.</param> /// <returns>Flow matching the requested criteria.</returns> INode<T> BuildFlow(string name); /// <summary> /// Builds a flow matching the specified flow component. /// </summary> /// <param name="flowRoot">Definition of the flow to build.</param> /// <returns>Flow matching the requested flow root.</returns> INode<T> BuildFlow(FlowComponent<T> flowRoot); /// <summary> /// Builds a flow matching the specified flow component. /// </summary> /// <param name="serializedFlow">Serialized definition of the flow to build.</param> /// <returns>Flow matching the requested flow root.</returns> INode<T> BuildSerializedFlow(string serializedFlow); /// <summary> /// Method overridden to provide a root FlowComponent based on a name. /// </summary> /// <param name="name">Name of the flow root.</param> /// <returns>FlowComponent corresponding to the named root.</returns> FlowComponent<T> GetFlowRoot(string name); } }
Java
UTF-8
254
3.03125
3
[ "Apache-2.0" ]
permissive
package P02_Shapes; public class Main { public static void main(String[] args) { Shape shape = new Rectangle(4,7); System.out.println(shape.calculateArea()); System.out.println(shape.calculatePerimeter()); } }
C#
UTF-8
374
2.84375
3
[]
no_license
using System; namespace TDDPalindromo { public class Palindromo { public string Frase { get; set; } public Palindromo(string frase) { if (!String.IsNullOrEmpty(frase)) { this.Frase = frase.Replace(" ","").Replace("-","").ToLower(); } } public Palindromo() { } } }
Java
UTF-8
929
2.5
2
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
package gov.cms.bfd.pipeline.bridge.model; import static org.junit.jupiter.api.Assertions.assertEquals; import gov.cms.bfd.model.rif.CarrierClaimColumn; import org.junit.jupiter.api.Test; /** Unit tests for {@link Mcs} class. */ public class McsTest { /** Verifies that all lists of numbered enum names appear in the proper sequence. */ @Test public void testThatNumberedSequenceNamesAreInSequenceOrder() { ModelUtilTest.assertNamesFollowSequence(Mcs.ICD_DGNS_CD, CarrierClaimColumn.ICD_DGNS_CD1); ModelUtilTest.assertNamesFollowSequence( Mcs.ICD_DGNS_VRSN_CD, CarrierClaimColumn.ICD_DGNS_VRSN_CD1); } /** * Pairs of lists are iterated over in the same loop. This test ensures those lists have the same * length to ensure we don't skip any values. */ @Test public void testThatListsOfNamesHaveSameLengths() { assertEquals(Mcs.ICD_DGNS_CD.size(), Mcs.ICD_DGNS_VRSN_CD.size()); } }
Java
UTF-8
946
2.5625
3
[ "MIT" ]
permissive
package net.aholbrook.paseto.data; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import net.aholbrook.paseto.service.Token; import java.util.Objects; @JsonPropertyOrder({"userId", "iss", "sub", "aud", "exp", "nbf", "iat", "jti"}) public class CustomToken extends Token { private Long userId; public Long getUserId() { return userId; } public CustomToken setUserId(Long userId) { this.userId = userId; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; CustomToken that = (CustomToken) o; return Objects.equals(userId, that.userId); } @Override public int hashCode() { return Objects.hash(super.hashCode(), userId); } @Override public String toString() { return "CustomToken{" + "userId=" + userId + ", token='" + super.toString() + '\'' + '}'; } }
Ruby
UTF-8
490
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" class Pokemon attr_accessor :id, :name, :type, :db def initialize(id:, name:, type:, db:) @id = id @name = name @type = type @db = db end def self.save(name, type, db) db.execute("INSERT INTO pokemon (name, type) VALUES ('#{name}', '#{type}')") end def self.find(id, db) array = db.execute("SELECT name, type FROM pokemon WHERE id = #{id}") self.new(id: id, name: array[0][0], type: array[0][1], db: db) end end
C++
UTF-8
1,339
2.53125
3
[]
no_license
#ifndef SHORTEST_LOOP_H #define SHORTEST_LOOP_H #include <vector> #include <iostream> #include <fstream> #include <set> #include <cstring> #include <string> //#define DEBUG 1 const int MAX_NODE_NUM = 51000; struct Edge{ int from,to; int distance; Edge(int _from,int _to,int _weight):from(_from),to(_to),distance(_weight){} Edge(){} }; struct Socket{ int node_id; Edge edge; Socket(int id,const Edge& e){ node_id = id; edge = e; } }; struct queue_node{ int socket_id; int distance; queue_node(int _id,int _dis):socket_id(_id),distance(_dis){} bool operator<(const queue_node& qnode)const{ return distance > qnode.distance; } }; class shortest_loop { public: shortest_loop(); shortest_loop(std::string filename); virtual ~shortest_loop(); void find_loops(std::vector<std::vector<int> >&ans); protected: private: std::vector<Socket>socket_list; void add_edge(int u,int v,int weight); int node_num,edge_num; std::vector<int>node_adj[MAX_NODE_NUM]; bool visit[MAX_NODE_NUM]; bool used[MAX_NODE_NUM]; void Dijsktra(int start,int cut_off,std::vector<int>& ans,int& mini_composite_distance); std::set<int>walk[MAX_NODE_NUM]; }; #endif // SHORTEST_LOOP_H
C++
GB18030
10,192
2.671875
3
[]
no_license
#include "Vayo3dFontManager.h" #include "VayoLog.h" #include "Vayo3dRoot.h" #include "Vayo3dRenderSystem.h" #include "Vayo3dTextureManager.h" NS_VAYO3D_BEGIN //------------------------------------------------------------------------ // bitmap.width λͼ // bitmap.rows λͼ(߶) // bitmap.pitch λͼһռõֽ //------------------------------------------------------------------------ // MONOģʽÿ1ؽ1bit,ֻкںͰ. // 1byteԱ8,1intԱ8*4. static inline void convertMONOToRGBA(FT_Bitmap* source, unsigned char* rgba) { unsigned char *s = source->buffer; unsigned char *t = rgba; for (unsigned int y = source->rows; y > 0; y--) { unsigned char *ss = s; unsigned char *tt = t; for (unsigned int x = source->width >> 3; x > 0; x--) { unsigned int val = *ss; for (unsigned int i = 8; i > 0; i--) { tt[0] = tt[1] = tt[2] = tt[3] = (val & (1 << (i - 1))) ? 0xFF : 0x00; tt += 4; } ss += 1; } unsigned int rem = source->width & 7; if (rem > 0) { unsigned int val = *ss; for (unsigned int x = rem; x > 0; x--) { tt[0] = tt[1] = tt[2] = tt[3] = (val & 0x80) ? 0xFF : 0x00; tt += 4; val <<= 1; } } s += source->pitch; t += source->width * 4; // pitch } } // GRAYģʽ11ֽڱ. static inline void convertGRAYToRGBA(FT_Bitmap* source, unsigned char* rgba) { for (unsigned int y = 0; y < source->rows; y++) { for (unsigned int x = 0; x < source->width; x++) { unsigned char *s = &source->buffer[(y * source->pitch) + x]; unsigned char *t = &rgba[((y * source->pitch) + x) * 4]; t[0] = t[1] = t[2] = 0xFF; t[3] = *s; } } } //------------------------------------------------------------------------ // TrueTypeFont //------------------------------------------------------------------------ FontManager::TrueTypeFont::TrueTypeFont() : _face(NULL) , _rgba(NULL) , _antialias(false) , _bold(false) , _tall(0) { } FontManager::TrueTypeFont::~TrueTypeFont() { release(); } bool FontManager::TrueTypeFont::create(FT_Library library, const char* filename, FT_Long faceIndex, int tall, bool bold, bool italic, bool antialias) { FT_Error err; if (tall > TRUE_TYPE_FONT_TEXTURE_SIZE) { // Bigger than a page size return false; } if ((err = FT_New_Face(library, filename, faceIndex, &_face)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_New_Face() Error %d", err); return false; } if ((err = FT_Set_Pixel_Sizes(_face, 0, tall)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_Set_Pixel_Sizes() Error %d", err); return false; } _rgbaSize = (tall * 2) * tall * 4; _rgba = new unsigned char[_rgbaSize]; if (_rgba == NULL) { return false; } _library = library; _antialias = antialias; _bold = bold; _tall = tall; if (italic) { FT_Matrix m; m.xx = 0x10000L; m.xy = 0.5f * 0x10000L; m.yx = 0; m.yy = 0x10000L; FT_Set_Transform(_face, &m, NULL); } return true; } void FontManager::TrueTypeFont::release() { FT_Error err; if (_face) { if ((err = FT_Done_Face(_face)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_Done_Face() Error %d", err); } _face = NULL; } if (_rgba) { delete[] _rgba; _rgba = NULL; } for (TCharMap::iterator it = _chars.begin(); it != _chars.end(); it++) { delete it->second; it->second = NULL; } _chars.clear(); for (size_t i = 0; i < _pages.size(); i++) { delete _pages[i]; _pages[i] = NULL; } _pages.clear(); } bool FontManager::TrueTypeFont::getCharInfo(int code, tagGlyphMetrics* metrics, TexturePtr& texture, float coords[]) { // fast find it TCharMap::iterator it = _chars.find(code); if (it != _chars.end()) { it->second->getInfo(metrics, texture, coords); return true; } tagGlyphMetrics gm; if (loadChar(code, &gm) == false) { return false; } Char *ch = new Char(); ch->_code = code; ch->setInfo(&gm); for (size_t i = 0; i < _pages.size(); i++) { Page *page = _pages[i]; if (page->append(gm.Width, gm.Height, _rgba, ch->_coords)) { ch->_texture = page->getTexture(); ch->getInfo(metrics, texture, coords); _chars.insert(TCharMap::value_type(code, ch)); return true; } } Page *page = new Page(); if (page->append(gm.Width, gm.Height, _rgba, ch->_coords)) { ch->_texture = page->getTexture(); ch->getInfo(metrics, texture, coords); _chars.insert(TCharMap::value_type(code, ch)); _pages.push_back(page); return true; } delete ch; delete page; return false; } int FontManager::TrueTypeFont::getFontTall() { return _tall; } bool FontManager::TrueTypeFont::loadChar(int code, tagGlyphMetrics* metrics) { FT_Error err; FT_UInt glyph_index = FT_Get_Char_Index(_face, (FT_ULong)code); if (glyph_index > 0) { if ((err = FT_Load_Glyph(_face, glyph_index, FT_LOAD_DEFAULT)) == FT_Err_Ok) { FT_GlyphSlot glyph = _face->glyph; FT_Render_Mode render_mode = _antialias ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO; if (_antialias && _bold) { if ((err = FT_Outline_EmboldenXY(&glyph->outline, 60, 60)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_Outline_EmboldenXY() Error %d", err); } } if ((err = FT_Render_Glyph(glyph, render_mode)) == FT_Err_Ok) { FT_Bitmap* bitmap = &glyph->bitmap; switch (bitmap->pixel_mode) { case FT_PIXEL_MODE_MONO: { if (!_antialias && _bold) { if ((err = FT_Bitmap_Embolden(_library, bitmap, 60, 0)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_Bitmap_Embolden() Error %d", err); } } convertMONOToRGBA(bitmap, _rgba); break; } case FT_PIXEL_MODE_GRAY: { convertGRAYToRGBA(bitmap, _rgba); break; } default: { memset(_rgba, 0xFF, _rgbaSize); break; } } metrics->Width = bitmap->width; metrics->Height = bitmap->rows; metrics->BearingX = glyph->bitmap_left; metrics->BearingY = glyph->bitmap_top; metrics->Advance = glyph->advance.x >> 6; return true; } else { Log::print(ELL_ERROR, "FT_Render_Glyph() Error %d", err); } } else { Log::print(ELL_ERROR, "FT_Load_Glyph() Error %d", err); } } memset(metrics, 0, sizeof(tagGlyphMetrics)); return false; } //------------------------------------------------------------------------ // Char //------------------------------------------------------------------------ void FontManager::TrueTypeFont::Char::setInfo(tagGlyphMetrics* metrics) { memcpy(&_metrics, metrics, sizeof(tagGlyphMetrics)); } void FontManager::TrueTypeFont::Char::getInfo(tagGlyphMetrics* metrics, TexturePtr& texture, float coords[]) { memcpy(metrics, &_metrics, sizeof(tagGlyphMetrics)); texture = _texture; memcpy(coords, _coords, sizeof(float) * 4); } //------------------------------------------------------------------------ // Page //------------------------------------------------------------------------ FontManager::TrueTypeFont::Page::Page() { _wide = _tall = TRUE_TYPE_FONT_TEXTURE_SIZE; _posx = _posy = 0; // In a line, for a max height character _maxCharTall = 0; _texture = Root::getSingleton().getActiveRenderer()->createTexture(L"", NULL, true); } FontManager::TrueTypeFont::Page::~Page() { // free the texture } bool FontManager::TrueTypeFont::Page::append(int wide, int tall, unsigned char* rgba, float coords[]) { if (_posy + tall > _tall) { // not enough line space in this page return false; } // If this line is full ... if (_posx + wide > _wide) { int newLineY = _posy + _maxCharTall; if (newLineY + tall > _tall) { // No more space for new line in this page, should allocate a new one return false; } // Begin in new line _posx = 0; _posy = newLineY; // Reset _maxCharTall = 0; } unsigned char* pData = (unsigned char*)_texture->lock(ECF_RGBA8888, Recti(_posx, _posy, _posx + wide, _posy + tall)); memcpy(pData, rgba, wide*tall*4); _texture->unlock(); coords[0] = _posx / (float)_wide; // left coords[1] = _posy / (float)_tall; // top coords[2] = (_posx + wide) / (float)_wide; // right coords[3] = (_posy + tall) / (float)_tall; // bottom _posx += wide; if (tall > _maxCharTall) { _maxCharTall = tall; } return true; } TexturePtr FontManager::TrueTypeFont::Page::getTexture() { return _texture; } //------------------------------------------------------------------------ // FontManager //------------------------------------------------------------------------ FontManager::FontManager() { _library = NULL; } FontManager::~FontManager() { release(); } bool FontManager::initialize() { FT_Error err; if ((err = FT_Init_FreeType(&_library)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_Init_FreeType() Error %d", err); return false; } return true; } void FontManager::release() { FT_Error err; for (size_t i = 0; i < _fonts.size(); i++) { delete _fonts[i]; _fonts[i] = NULL; } _fonts.clear(); if ((err = FT_Done_FreeType(_library)) != FT_Err_Ok) { Log::print(ELL_ERROR, "FT_Done_FreeType() Error %d", err); } } int FontManager::createFont(const char* filename, int face, int tall, bool bold, bool italic, bool antialias) { TrueTypeFont *font = new TrueTypeFont(); if (!font->create(_library, filename, face, tall, bold, italic, antialias)) { delete font; return -1; } _fonts.push_back(font); return (int)_fonts.size() - 1; } bool FontManager::getCharInfo(int fontIndex, int code, int* wide, int* tall, int* bearingX, int* bearingY, int* advance, TexturePtr& texture, float coords[]) { int i = CONVERT_FONT_INDEX(fontIndex); if (i == -1) return false; TrueTypeFont *font = _fonts[i]; tagGlyphMetrics metrics; if (!font->getCharInfo(code, &metrics, texture, coords)) return false; *wide = metrics.Width; *tall = metrics.Height; *bearingX = metrics.BearingX; *bearingY = metrics.BearingY; *advance = metrics.Advance; return true; } int FontManager::getFontTall(int fontIndex) { int i = CONVERT_FONT_INDEX(fontIndex); if (i == -1) return 0; TrueTypeFont* font = _fonts[i]; return font->getFontTall(); } NS_VAYO3D_END
Python
UTF-8
495
3.875
4
[]
no_license
''' # 가운데 글자 가져오기 단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다. 제한사항 s는 길이가 1 이상, 100이하인 스트링입니다. ''' def solution(s): if len(s) % 2 == 0: answer = s[int(len(s) / 2) - 1 : int(len(s) / 2) + 1] else: answer = s[int(len(s) / 2)] return answer print(solution("abcde")) print(solution("qwer"))
C#
UTF-8
1,639
3.046875
3
[]
no_license
using System; using System.Collections.Generic; using System.Numerics; using System.Text; using System.Linq; using System.Diagnostics; using _calc = MathService.Calculators.Calculator; namespace ProblemService.Problems { public class Problem_271 : Problem { //https://projecteuler.net/problem=271 Published on Saturday, 2nd January 2010, 05:00 am; Solved by 1881; Difficulty rating: 60% // // For a positive number n, define S(n) as the sum of the integers x, for which 1<x<n and // x^3≡1 mod n. // When n= 91, there are 8 possible values for x, namely : 9, 16, 22, 29, 53, 74, 79, 81. // Thus, S(91)= 9 + 16 + 22 + 29 + 53 + 74 + 79 + 81 = 363. // Find S(13,082,761,331,670,030). // //----------------------------------------------------------------------------------- //Notes: // 1. x^3 ends with a 1 so x ends with a 1 // 2. lower bound is 13082761331670030^(1/3) = 235631.3869... // 3. // 4. public override object RunProblem(double x, double y = 0, double z = 0) { var max = 13082761331670030.0; var result = BigInteger.Zero; var found = false; var mult = 1; for(var i = 1; i < max; i++) { var a = Math.Pow(i * max + 1, 1.0 / 3.0); if (a == (int)a && a%10 == 1) { return new { result = a }; } } return new { result }; } } }
Java
UTF-8
1,489
2.359375
2
[]
no_license
package ftn.project.xml.service; import ftn.project.xml.model.TUser; import ftn.project.xml.model.User; import ftn.project.xml.repository.UserRepository; import ftn.project.xml.util.AuthenticationUtilities; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class UserDetailsServiceImpl implements UserDetailsService { private AuthenticationUtilities.ConnectionProperties conn; @Autowired private UserRepository userRepository; @lombok.SneakyThrows @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { TUser tUser = null; User user = null; AuthenticationUtilities.ConnectionProperties conn = null; try { conn = AuthenticationUtilities.loadProperties(); } catch (IOException e) { e.printStackTrace(); } ; try { tUser = userRepository.getUserByEmail(conn, email); if(tUser!=null){ user = new User(tUser); } } catch (Exception e) { e.printStackTrace(); } if (user == null) { throw new UsernameNotFoundException(String.format("No user found with email '%s'.", email)); } else { return user; } } }
Markdown
UTF-8
1,089
2.984375
3
[]
no_license
## Goals Create the home screen of the app. Create a ListView for the Categories. ## Steps Fill out the TODOs in main.dart and category_route.dart using the specs below. If you had customized your category.dart, you can replace our category.dart with yours. Customize your app if desired. Some ideas are listed below. ## Specs The AppBar text should say 'Unit Converter' with a font size of 30.0, and an elevation of 0.0. A list of 8 Categories should be shown on the screen. You should be able to scroll down the list. There should be 8.0 horizontal padding around this list. The AppBar and app body should be the same color. In our example, we use Colors.green[100]. ## Screenshots <p align="left"> <img src="https://github.com/NaagAlgates/Flutter_Route/blob/master/screenshots/1.png" width="350" height="550"/> <img src="https://github.com/NaagAlgates/Flutter_Route/blob/master/screenshots/2.png" width="350" height="550"/> <img src="https://github.com/NaagAlgates/Flutter_Route/blob/master/screenshots/3.png" width="350" height="550"/> </p>
JavaScript
UTF-8
4,847
2.625
3
[]
no_license
export class loginController { constructor() { setTimeout(() => { this.toggleHeader(); }, 100); this.usernameInput = ''; this.password = ''; this.submit = false; dynamicImport("./../../adminpanel/js/database.js").then(db => { this.db = db; mvc.apply(); }); this.enc = []; dynamicImport("./../../adminpanel/js/backend.js").then(enc => { this.enc = enc; }); } /* toggleHeader is a function for show or hide the header by editing the display css proparty @param: none @return: none */ toggleHeader() { const header = document.getElementsByTagName('header')[0]; if(header.style.display!='none') { header.style.display='none'; } } /* Redirect function is used to direct the user to a new page to edit the new selected @param: fullName string @param: username string @param: email string @param: roleId string @param: alg encryption algorithm @param: validityTime session time @param: hashFunction the function that used for hashing @return: Token of the user */ getToken(fullName, username, email, roleId, alg, validityTime, key, hashFunction) { /* username: the username of the user email: the email of the user roleId: the role of the user alg: the hash algorithm that used validityTime: the life time of the token in milliseconds key: the secret that used in signature */ let date = new Date(); let currentDate = date.getTime(); // The current date in milliseconds let expDate = currentDate + validityTime; // the exp data after add the validity time // Generate the token fields let token = { "header": { "alg": alg, "typ": "JWT" }, "data": { "fullName": fullName, "username": username, "email": email, "roleId": roleId, "start": currentDate, "exp": expDate } } // Convert token object to JSON let tokenJson = JSON.stringify(token); // Calculate the Hash for the token data with the key let hash = hashFunction(tokenJson + key); // Add the Hash to the token token["hash"] = hash; // conver the token object after add the hash to json then // encode it to base64 let finalToken = JSON.stringify(token); let finalTokenBased64 = btoa(finalToken); return finalTokenBased64; } /* Make login process when user enter the username and password. It provide messages for each state @return: nothing It redirect the user to dashboard if the login is success. */ login() { if (this.submit) return; this.submit = true; let currentUser = null; createToast("جاري تسجيل الدخول", "", "info", ''); this.db.dbGet("/users", false, this.usernameInput).then(user => { if (user.password != this.password) { createToast("خطأ", "أسم المستخدم أو كلمة المرور خاطئة", "danger", 'times-circle'); return; } else if (user.state == 0) { createToast("ملاحظة", "حسابك معطل راجع أحد المسؤولين", "info", ''); return; } else if (user.password == this.password) { createToast("نجاح", "تم تسجيل الدخول", "success", 'check'); let token = this.getToken(user.firstName + " " + user.lastName, user.username, user.email, user.role, "sha256", 60 * 60 * 1000, this.enc.tokenKey, this.enc.SHA256); user.token = token; let datatoSave = { "token": user.token, "roleID": user.role, "fullName": user.username, "id": user._id, } this.enc.saveData('user', datatoSave); this.toggleHeader(); window.location.href = "#/home"; return; } this.submit = false; }, () => { console.log("Not found"); createToast("خطأ", "أسم المستخدم أو كلمة المرور خاطئة", "danger", 'times-circle'); this.submit = false; }); setTimeout(() => { this.submit = false; }, 1000); } }
Java
UTF-8
14,509
1.898438
2
[]
no_license
package com.example.cauvong.musiconline; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; public class OfflineActivity extends AppCompatActivity implements SongAdapter.InterfAdapter, View.OnClickListener{ private RecyclerView mRecycleView; private List<ItemSong> mListItems; private SongAdapter mSongAdapter; private SeekBar mSeek; private MediaPlayer mPlayer; private Button mBtnPlay, mBtnPause, mBtnshuffer, mBtnShufferOn,mBtnRepeat, mBtnRepeat1, mBtnRepeatAll, mBtnPrev, mBtnNext; private TextView mTvTimeBegin, mTvTimeEnd; private Handler mHandler = new Handler(); private int currentId = 0; private List<String> mLvImage; private RelativeLayout mRelative; private Button mBtnImageOff, mBtnImageOn; private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_offline); findViews(); initComponents(); startService(); } private void startService() { Intent intent = new Intent(); intent.setClass(this,ServiceMedia.class); startService(intent); } private void findViews() { mRecycleView = (RecyclerView) findViewById(R.id.rv_songs); mSeek = (SeekBar) findViewById(R.id.seekbar); mBtnPlay = (Button) findViewById(R.id.btn_play); mBtnPause = (Button) findViewById(R.id.btn_pause); mBtnRepeat = (Button) findViewById(R.id.btn_repeat); mBtnRepeat1 = (Button) findViewById(R.id.btn_repeat_1); mBtnRepeatAll = (Button) findViewById(R.id.btn_repeat_all); mBtnshuffer = (Button) findViewById(R.id.btn_shuffle); mBtnShufferOn = (Button) findViewById(R.id.btn_shuffle_on); mBtnPrev = (Button) findViewById(R.id.btn_prev); mBtnNext = (Button) findViewById(R.id.btn_next); mTvTimeBegin = (TextView) findViewById(R.id.tv_time_run); mTvTimeEnd = (TextView) findViewById(R.id.tv_time_total); mRelative = (RelativeLayout) findViewById(R.id.relative); mBtnImageOff = (Button) findViewById(R.id.btn_image_off); mBtnImageOn = (Button) findViewById(R.id.btn_image_on); mImageView = (ImageView) findViewById(R.id.iv_background); } private void initComponents() { mListItems = new ArrayList<>(); addList(); mSongAdapter = new SongAdapter(this,this); mRecycleView.setAdapter(mSongAdapter); mRecycleView.setOnClickListener(this); LinearLayoutManager manager = new LinearLayoutManager(this); manager.setStackFromEnd(true); mRecycleView.setLayoutManager(manager); mBtnPlay.setOnClickListener(this); mBtnPause.setOnClickListener(this); mBtnRepeat.setOnClickListener(this); mBtnRepeat1.setOnClickListener(this); mBtnRepeatAll.setOnClickListener(this); mBtnshuffer.setOnClickListener(this); mBtnShufferOn.setOnClickListener(this); mBtnPrev.setOnClickListener(this); mBtnNext.setOnClickListener(this); mBtnImageOff.setOnClickListener(this); mBtnImageOn.setOnClickListener(this); mPlayer = new MediaPlayer(); } private void addList() { Uri uri = MediaStore.Files.getContentUri("external"); Cursor cursor = getContentResolver().query(uri, null, null, null,null); mListItems.clear(); int idxPath = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA); int idxSong = cursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE); cursor.moveToFirst(); while (!cursor.isAfterLast()){ String path = cursor.getString(idxPath); if(path.contains("mp3") ){ if (path.contains("_")) { String informSong = cursor.getString(idxSong); String[] name = informSong.split("_"); String nameSong = name[0]; String nameSinger = ""; if (name.length == 2){ nameSinger += name[1]; } mListItems.add(new ItemSong(nameSong, nameSinger, path)); } } cursor.moveToNext(); } cursor.close(); mLvImage = new ArrayList<>(); Uri uri1 = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; Cursor cursor1 = getContentResolver().query(uri1,null, null, null, null); mLvImage.clear(); int indxPathIv = cursor1.getColumnIndex(MediaStore.Images.Media.DATA); cursor1.moveToFirst(); while (!cursor1.isAfterLast()){ String pathIv = cursor1.getString(indxPathIv); mLvImage.add(pathIv); cursor1.moveToNext(); } cursor1.close(); } private void setSeek(int duration) { long minuteEnd = TimeUnit.MILLISECONDS.toMinutes(duration); long secondEnd = TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(minuteEnd); mTvTimeEnd.setText(String.format("%d:%d",minuteEnd,secondEnd)); mSeek.setMax(duration); mSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser){ mPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } @Override public int getCount() { return mListItems.size(); } @Override public ItemSong getItemSong(int position) { return mListItems.get(position); } @Override public void onClick(int position) { currentId = position; play(position); } private void play(int positiion) { mSongAdapter.setCurrentPosition(positiion); mSongAdapter.notifyDataSetChanged(); if (mPlayer.isPlaying()){ mPlayer.stop(); mPlayer.release(); mPlayer = null; // dùng xong xóa,,,, mHandler.removeCallbacks(runnable); } try { mPlayer = new MediaPlayer(); // Mỗi lần dùng mới thì phải tạo lại... mPlayer.setDataSource(mListItems.get(positiion).getmPath()); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { e.printStackTrace(); } if (mBtnImageOn.getVisibility() == View.VISIBLE){ setImageBg(); } else mImageView.setImageResource(R.drawable.bg_login); mBtnPlay.setVisibility(View.INVISIBLE); mBtnPause.setVisibility(View.VISIBLE); setSeek(mPlayer.getDuration()); mHandler.postDelayed(runnable,100); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mBtnPause.setVisibility(View.INVISIBLE); mBtnPlay.setVisibility(View.VISIBLE); } }); } private void setImageBg() { Random random = new Random(); int size = mLvImage.size(); int rand = random.nextInt(size-1) + 0; String path = mLvImage.get(rand); Bitmap bitmap = decodeFile(path,mRelative.getWidth(),mRelative.getHeight()); mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alpha)); mImageView.setImageBitmap(bitmap); } public static Bitmap decodeFile(String f, int WIDTH, int HIGHT){ try { //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(f,o); //The new size we want to scale to final int REQUIRED_WIDTH=WIDTH; final int REQUIRED_HIGHT=HIGHT; //Find the correct scale value. It should be the power of 2. int scale=1; while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT) scale*=2; //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; return BitmapFactory.decodeFile(f, o2); } catch (Exception e) {} return null; } private Runnable runnable = new Runnable() { @Override public void run() { int timeBegin = mPlayer.getCurrentPosition(); long minuteBegin = TimeUnit.MILLISECONDS.toMinutes(timeBegin); long secondBegin = TimeUnit.MILLISECONDS.toSeconds(timeBegin) - TimeUnit.MINUTES.toSeconds(minuteBegin); mTvTimeBegin.setText(String.format("%d:%d",minuteBegin,secondBegin)); mHandler.postDelayed(this,100); mSeek.setProgress(timeBegin); } }; @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_play: playing(); break; case R.id.btn_pause: pauseSong(); break; case R.id.btn_next: playNext(); break; case R.id.btn_prev: playPreveuos(); break; case R.id.btn_shuffle: shuffer(); break; case R.id.btn_shuffle_on: shufferOn(); break; case R.id.btn_repeat: mBtnRepeat.setVisibility(View.INVISIBLE); mBtnRepeat1.setVisibility(View.VISIBLE); repeat1(); break; case R.id.btn_repeat_1: mBtnRepeat1.setVisibility(View.INVISIBLE); mBtnRepeatAll.setVisibility(View.VISIBLE); repeatAll(); break; case R.id.btn_repeat_all: repeat(); break; case R.id.btn_image_off: turnOnImage(); break; case R.id.btn_image_on: turnOffImage(); break; default: break; } } private void turnOnImage() { mBtnImageOff.setVisibility(View.INVISIBLE); mBtnImageOn.setVisibility(View.VISIBLE); setImageBg(); } private void turnOffImage() { mBtnImageOff.setVisibility(View.VISIBLE); mBtnImageOn.setVisibility(View.INVISIBLE); mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alpha)); mImageView.setImageResource(R.drawable.bg_login); } private void pauseSong() { mPlayer.pause(); mBtnPlay.setVisibility(View.VISIBLE); mBtnPause.setVisibility(View.INVISIBLE); } private void playing() { mPlayer.start(); mBtnPlay.setVisibility(View.INVISIBLE); mBtnPause.setVisibility(View.VISIBLE); setSeek(mPlayer.getDuration()); } private void playNext() { if (currentId < mListItems.size() - 1) { play(++currentId); } else { currentId = 0; play(currentId); } } private void playPreveuos() { if (currentId > 0) { play(--currentId); } else { currentId = mListItems.size()-1; play(currentId); } } private void shufferOn() { mBtnShufferOn.setVisibility(View.INVISIBLE); mBtnshuffer.setVisibility(View.VISIBLE); } private void shuffer() { Collections.shuffle(mListItems); mBtnShufferOn.setVisibility(View.VISIBLE); mBtnshuffer.setVisibility(View.INVISIBLE); } private void repeat() { mBtnRepeatAll.setVisibility(View.INVISIBLE); mBtnRepeat.setVisibility(View.VISIBLE); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mBtnPause.setVisibility(View.INVISIBLE); mBtnPlay.setVisibility(View.VISIBLE); } }); } private void repeatAll() { mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if (currentId < mListItems.size() - 1) { play(++currentId); } else { currentId = 0; play(currentId); } if (mBtnRepeatAll.getVisibility() == View.VISIBLE){ repeatAll(); } } }); } private void repeat1() { mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(mListItems.get(currentId).getmPath()); mPlayer.prepare(); mPlayer.start(); if (mBtnRepeat1.getVisibility() == View.VISIBLE) repeat1(); } catch (IOException e) { e.printStackTrace(); } } }); } }
C
UTF-8
2,266
2.84375
3
[ "BSD-3-Clause" ]
permissive
#ifndef __LCD_H__ #define __LCD_H__ // ------------------------------------------------------------------------ #define LCD_WIDTH 160 #define LCD_HEIGHT 80 #define LCD_FRAMEBUFFER_PIXELS (LCD_WIDTH * LCD_HEIGHT) #define LCD_FRAMEBUFFER_BYTES (LCD_WIDTH * LCD_HEIGHT * 2) // ------------------------------------------------------------------------ // Basic functions. All functions are asynchronous, i.e., they return while // bulk of the operation is running using DMA. They all synchronize between // themselves, but lcd_wait() should be called explicitly before accessing // the buffer used by read/write operations. Otherwise there will be race // conditions between DMA and CPU accessing the data. // ------------------------------------------------------------------------ void lcd_init (void); void lcd_clear (unsigned short int color); // All colors are RGB565. void lcd_setpixel (int x, int y, unsigned short int color); void lcd_fill_rect (int x, int y, int w, int h, unsigned short int color); void lcd_rect (int x, int y, int w, int h, unsigned short int color); void lcd_write_u16 (int x, int y, int w, int h, const void* buffer); // Buffer size = w*h*2 bytes. void lcd_write_u24 (int x, int y, int w, int h, const void* buffer); // Buffer size = w*h*3 bytes. void lcd_read_u24 (int x, int y, int w, int h, void* buffer); // Buffer size = w*h*3 bytes. void lcd_wait (void); // Wait until previous operation is complete. // ------------------------------------------------------------------------ // Framebuffer functions. // ------------------------------------------------------------------------ void lcd_fb_setaddr (const void* buffer); // Buffer size = LCD_FRAMEBUFFER_BYTES. Does not enable auto-refresh by itself. void lcd_fb_enable (void); // Automatic framebuffer refresh. When enabled, other functions cannot be used. void lcd_fb_disable (void); // Disable auto-refresh. Waits until last refresh is complete before returning. // ------------------------------------------------------------------------ #endif // __LCD_H__
JavaScript
UTF-8
139
2.953125
3
[]
no_license
"use strict"; function helloWorld(name, val) { console.log(`Hello ${name}! ${val || ''}`); } helloWorld('Joe'); helloWorld('John', 5);
PHP
UTF-8
2,372
2.75
3
[]
no_license
<?php class categorias{ private $name = "llx_categorie"; private $custom; private $arraySubCategorias; private $countSubCategorias = 0; private $rowid; private $fk_parent; private $label; private $description; private $type; public function __constructComplete($rowid, $fk_parent, $label, $description,$type) { $this->rowid = $rowid; $this->fk_parent = $fk_parent; $this->label = $label; $this->description = $description; $this->type = $type; } public function __construct() { } public function getName() { return $this->name; } public function getCustom() { return $this->custom; } public function getArraySubCategorias() { return $this->arraySubCategorias; } public function getCountSubCategorias() { return $this->countSubCategorias; } public function getRowid() { return $this->rowid; } public function getFk_parent() { return $this->fk_parent; } public function getLabel() { return $this->label; } public function getDescription() { return $this->description; } public function gettype() { return $this->type; } public function settype($type) { $this->type = $type; return $this; } public function setName($name) { $this->name = $name; return $this; } public function setCustom($custom) { $this->custom = $custom; return $this; } public function setArraySubCategorias($arraySubCategorias) { $this->arraySubCategorias = $arraySubCategorias; return $this; } public function setCountSubCategorias($countSubCategorias) { $this->countSubCategorias = $countSubCategorias; return $this; } public function setRowid($rowid) { $this->rowid = $rowid; return $this; } public function setFk_parent($fk_parent) { $this->fk_parent = $fk_parent; return $this; } public function setLabel($label) { $this->label = $label; return $this; } public function setDescription($description) { $this->description = $description; return $this; } }
JavaScript
UTF-8
2,424
3.234375
3
[]
no_license
import React, { Component, useState } from 'react'; export default function Form() { const [number1, setNumber1] = useState(""); const [number2, setNumber2] = useState(""); // const [total, setTotal] = useState(number1 + number2); // const [dif, setdif] = useState(number1 - number2); // const [pro, setpro] = useState(number1 * number2); // const [quo, setquo] = useState(number1 / number2); // function add() { // setTotal(number1 + number2); // } // function sub() { // setdif(number1 - number2); // } // function mul() { // setpro(number1 * number2); // } // function div() { // setquo(number1 / number2); // } return ( <> <div className="container my-5"> <h1 className="mb-3 my-3">Enter two Numbers</h1> <div class="mb-3"> <label htmlFor="exampleInputEmail1" class="form-label" >First Number</label> <input type="number" class="form-control" value={number1} aria-describedby="emailHelp" onChange={e => setNumber1(+e.target.value)}/> {/* <div id="emailHelp" class ="form-text">We'll never share your email with anyone else.</div> */} </div> <div class="mb-3"> <label htmlFor="exampleInputPassword1" class="form-label">Second Number</label> <input type="number" class="form-control" value={number2} onChange={e => setNumber2(+e.target.value)}/> </div> {/* <button type="submit" class="btn btn-outline-dark" onClick={add}>Add the numbers</button> <button type="submit" class="btn btn-outline-dark mx-2" onClick={sub}>Subtract the Numbers</button> <button type="submit" class="btn btn-outline-dark mx-2" onClick={mul}>Multiply the Numbers</button> <button type="submit" class="btn btn-outline-dark mx-2" onClick={div}>Divide the Numbers</button> */} <p className='my-5'>Addition: {number1 + number2}</p> <p className='my-5'>Subtraction: {number1 - number2}</p> <p className='my-5'>Multiplication: {number1 * number2}</p> <p className='my-5'>Division: {number1 / number2}</p> <h2>Developer: Ansh Sharma</h2> </div> </> ) }
Java
UTF-8
1,953
4.15625
4
[]
no_license
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { // write your code here startCalculator(); } public static void startCalculator() { Scanner input = new Scanner(System.in); int number1; int number2; int result; String operator = ""; System.out.println("Welcome to the Calculator\n" + "It can do 4 things: Addition, Substraction, Division and Multiplication."); while(true){ int operation; System.out.println("Choose what operator to use: \n" + "1. Addition\n" + "2. Substraction\n" + "3. Division\n" + "4. Multiplication\n"); operation = input.nextInt(); if (operation < 1 || operation > 4){ System.out.println("Please choose one of the operations:"); } System.out.println("Choose your first number."); number1 = input.nextInt(); System.out.println("Choose your second number."); number2 = input.nextInt(); switch (operation) { case 0: result = number1 + number2; operator = "Addition"; break; case 1: result = number1 - number2; operator = "Substraction"; break; case 2: result = number1 / number2; operator = "Division"; break; case 4: result = number1 * number2; operator = "Multiplication"; break; default: result = 0; } System.out.println(operator + " result is: " + result); } } }
Python
UTF-8
150
2.53125
3
[]
no_license
import enum class ButtonType(enum.Enum): """ Enum class with type of buttons """ Start = 0 Records = 1 Quit = 2 Back = 3
Java
UTF-8
599
1.992188
2
[]
no_license
package com.elmagmo3a.java.playstation.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import com.elmagmo3a.java.playstation.entity.User; @Repository public interface UserRepository extends PagingAndSortingRepository<User, Long>, JpaSpecificationExecutor<User> { Optional<User> findByUsernameAndPassword(String username, String password); Optional<User> findByUsername(String username); }
Ruby
UTF-8
3,857
3.765625
4
[]
no_license
# Virus Predictor # I worked on this challenge [by myself, with: ]. # We spent [#] hours on this challenge. # EXPLANATION OF require_relative: links test file to the class file for rspec testing # # require_relative 'state_data' class VirusPredictor # for each new instance of a class, sets the 3 below parameters def initialize(state_of_origin) @state = state_of_origin @population = STATE_DATA[@state][:population] @population_density = STATE_DATA[@state][:population_density] end def virus_effects predicted_deaths speed_of_spread virus_statement end private # define predicted deaths and speed of spread using instance parameters as direct output # outputs the predicted number of deaths for each state due to outbreak using all instance parameters def predicted_deaths # predicted deaths is solely based on population density case @population_density when range_above(200) rate = 0.4 when range_above(150) rate = 0.3 when range_above(100) rate = 0.2 when range_above(50) rate = 0.1 else rate = 0.05 end @number_of_deaths = (@population * rate).floor end def range_above(number) number..Float::INFINITY end # outputs the speed of spread for each state using the population density and state parameters def speed_of_spread #in months # We are still perfecting our formula here. The speed is also affected # by additional factors we haven't added into this functionality. if @population_density >= 200 @speed = 0.5 elsif @population_density >= 150 @speed = 1 elsif @population_density >= 100 @speed = 1.5 elsif @population_density >= 50 @speed = 2 else @speed = 2.5 end end def virus_statement puts "#{@state} will lose #{@number_of_deaths} people in this outbreak and will spread across the state in #{@speed} months." end end #======================================================================= # DRIVER CODE # initialize VirusPredictor for each state #INPUT: STATE_DATA hash #STEPS: # 1. Iterate through the hash 51 times for each state name by using each #OUTPUT: VirusPredicter instance for each state with state name, population density, and population STATE_DATA.each do|state_name,population_data| state_name = VirusPredictor.new(state_name) state_name.virus_effects end #======================================================================= # Reflection Section # # 1. In the state data file, the hash syntax between the state name as key and it's population data hash as value uses a rocket. This is correct since the rocket syntax keeps both objects as they are, string and a hash. Inside the population data hash, they symbol syntax is used. This automatically converts the population density and population keys into symbols with the same id. This helps the program to run more efficiently and makes for a cleaner code. # 2. Require relative links a test file to a class file for rspec testing. Require links a module to a class. # 3. A couple ways to iterate through a hash are to use the .each and .times methods. Each is best used to perform a function once across inputs of an entire hash. Times is better used to perform an operation any set number of times against a hash. # 4. When refactoring virus effects, realizing that calling the instance variables in the predicted deaths and speed of spread variables was unnecessary stood out. I definitely could understand the frame of thinking for calling these variables when writing the code. Only during refactoring the finished code would one realize how repetitive this was. # 5. This challenge, I most definitely solidified refactoring. There were so many things I had not thought about doing when first learning this concept in the challenge last week that my mind was opened up to during the gps this week. Great lesson!
C++
UTF-8
12,343
2.640625
3
[]
no_license
#include <iostream> #include <fstream> #include <cmath> #include "Vector.h" #include "Random64.h" using namespace std; const double A=10., L=100., R=1.; const double K=1e4, Gamma=50, Kcundall=10; const double g=9.8; const int N=27; const double Zeta=0.1786178958448091; const double Lambda=-0.2123418310626054; const double Xi=-0.06626458266981849; class Cuerpo; class Colisionador; //Clase Cuerpo class Cuerpo{ private: vector3D r,rot,a,b,c,V,F,omega,tau; double m,theta,I; public: void Inicie(double x0, double y0, double z0, double phi0, double alpha0, double beta0, double a10, double a20, double a30, double b10, double b20, double b30, double c10, double c20, double c30, double Vx0, double Vy0, double Vz0,double theta0, double omega0, double m0, double I0); void BorreFuerzayTorque(void); void AgregueFuerza(vector3D F0); void AgregueTorque(vector3D tau0); void Mueva_r(double dt, double Constante); void Mueva_V(double dt, double Constante); double Getx(void){return r.x();}; double Gety(void){return r.y();}; double Getz(void){return r.z();}; double Getaz(void){return a.z();}; double Getbz(void){return b.z();}; double Getcz(void){return c.z();}; void Dibujar_esfera(void); void Dibujar_cilindro(void); void Dibujar_plano(void); friend class Colisionador; }; //Clase Colisionador class Colisionador{ private: vector3D ele[N+4][N+4]; bool EstoyEnColision[N+4][N+4]; public: void Inicie(void); void CalculeTodasLasFuerzas(Cuerpo* Grano, double dt); void CalculeLaFuerzaEntre(Cuerpo & Grano1, Cuerpo & Grano2, vector3D & ele, bool & EstoyEnColision, double dt); void CalculeLaFuerzaEntrePlanos(Cuerpo * Grano, vector3D & ele, bool & EstoyEnColision, double dt); }; //Funciones de la clase cuerpo void Cuerpo::Inicie(double x0, double y0, double z0, double phi0, double alpha0, double beta0, double a10, double a20, double a30, double b10, double b20, double b30, double c10, double c20, double c30, double Vx0, double Vy0, double Vz0,double theta0, double omega0, double m0, double I0){ r.cargue(x0,y0,z0); rot.cargue(phi0,alpha0,beta0); a.cargue(a10,a20,a30); b.cargue(b10,b20,b30); c.cargue(c10,c20,c30); V.cargue(Vx0,Vy0,Vz0); theta=theta0; omega.cargue(0,0,omega0); m=m0; I=I0; } void Cuerpo::BorreFuerzayTorque(void){ F.cargue(0,0,0); tau.cargue(0,0,0); } void Cuerpo::AgregueFuerza(vector3D F0){ F+=F0; } void Cuerpo::AgregueTorque(vector3D tau0){ tau+=tau0; } void Cuerpo::Mueva_r(double dt, double Constante){ r+=V*(Constante*dt); a+=V*(Constante*dt); b+=V*(Constante*dt); c+=V*(Constante*dt); theta+=omega.z()*Constante*dt; } void Cuerpo::Mueva_V(double dt, double Constante){ V+=F*(Constante*dt)/m; omega+=tau*Constante*dt/I; } void Cuerpo::Dibujar_esfera(void){ cout<<", "<<r.x()<<"+"<<R<<"*sin(u)*cos(v),"<<r.y()<<"+"<<R<<"*sin(u)*sin(v),"<<r.z()<<"+"<<R<<"*cos(u)"; } void Cuerpo::Dibujar_cilindro(void){ cout<<", "<<r.x()<<"+"<<R<<"*cos(v)*cos("<<rot.x()<<")*cos("<<rot.y()<<")"<<"+t(u)*sin("<<rot.x()<<")*cos("<<rot.y()<<")-"<<R<<"*sin(v)*sin("<<rot.y()<<"),"<<r.y()<<"+"<<R<<"*cos(v)*cos("<<rot.x()<<")*sin("<<rot.y()<<")*cos("<<rot.z()<<")"<<"+t(u)*sin("<<rot.x()<<")*sin("<<rot.y()<<")*cos("<<rot.z()<<")+"<<R<<"*sin(v)*cos("<<rot.y()<<")*cos("<<rot.z()<<")+"<<R<<"*cos(v)*sin("<<rot.x()<<")*sin("<<rot.z()<<")-cos("<<rot.x()<<")*t(u)*sin("<<rot.z()<<"),"<<r.z()<<"+"<<R<<"*cos(v)*cos("<<rot.x()<<")*sin("<<rot.y()<<")*sin("<<rot.z()<<")+sin("<<rot.x()<<")*t(u)*sin("<<rot.y()<<")*sin("<<rot.z()<<")+"<<R<<"*sin(v)*cos("<<rot.y()<<")*sin("<<rot.z()<<")-"<<R<<"*cos(v)*sin("<<rot.x()<<")*cos("<<rot.z()<<")+cos("<<rot.x()<<")*t(u)*cos("<<rot.z()<<")"; } void Cuerpo::Dibujar_plano(void){ cout<<", "<<a.x()<<"+m(u)*("<<b.x()<<"-"<<a.x()<<")+n(v)*("<<c.x()<<"-"<<a.x()<<"),"<<a.y()<<"+m(u)*("<<b.y()<<"-"<<a.y()<<")+n(v)*("<<c.y()<<"-"<<a.y()<<"),"<<a.z()<<"+m(u)*("<<b.z()<<"-"<<a.z()<<")+n(v)*("<<c.z()<<"-"<<a.z()<<")"; } //Funciones de la clase colisionador void Colisionador::Inicie(void){ int i,j; for(i=0;i<N;i++){ for(j=i+1;j<N+4;j++){ ele[i][j].cargue(0,0,0); EstoyEnColision[i][j]=false; } } } void Colisionador::CalculeTodasLasFuerzas(Cuerpo* Grano, double dt){ int i,j; vector3D g_vector; g_vector.cargue(0,0,g); for(i=0;i<N;i++){ Grano[i].BorreFuerzayTorque(); } //Agregue la fuerza de la gravedad for(i=0;i<N-1;i++){ Grano[i].AgregueFuerza(-(Grano[i].m)*g_vector); } //Calcular todas las fuerzas entre parejas de planetas /*for(i=0;i<N;i++){ for(j=i+1;j<N+4;j++){ CalculeLaFuerzaEntre(Grano[i], Grano[j], ele[i][j], EstoyEnColision[i][j], dt); } }*/ CalculeLaFuerzaEntrePlanos(Grano, ele[21][26], EstoyEnColision[21][26], dt); } /* void Colisionador::CalculeLaFuerzaEntre(Cuerpo & Grano1, Cuerpo & Grano2, vector3D & ele, bool & EstoyEnColision, double dt){ vector3D F2,Fn,Ft,runitario,n,Vc,Vcn,Vct,t,r21 = Grano2.r-Grano1.r; double s,m1,m2,R1,R2,m12,componenteVcn,normaVct,componenteFn,normaFt,Ftmax; double ERFF=1e-8,d21=norma(r21); s=Grano1.R+Grano2.R-d21; if(s>0){ //SI SE CHOCAN //Geometria y dinamica del contacto m1=Grano1.m; m2=Grano2.m; m12=(m1*m2)/(m1+m2); R1=Grano1.R; R2=Grano2.R; n=r21/d21; //Calcular velocidad de contacto y el vector tangente Vc=(Grano2.V-Grano1.V)-(Grano2.omega^n)*R2-(Grano1.omega^n)*R1; // ^ = prod cruz //velocidad del punto de contacto // -> dividimos en componentes normal y tangencial componenteVcn=Vc*n;Vcn=n*componenteVcn; Vct=Vc-Vcn; normaVct=norma(Vct); if(normaVct<ERFF) t.cargue(0,0,0); else t=Vct/normaVct; //FUERZAS NORMALES //Fuerza de Hertz componenteFn=K*pow(s,1.5); //Disipación Plástica componenteFn-=m12*sqrt(s)*Gamma*componenteVcn; if(componenteFn<0) componenteFn=0; Fn=n*componenteFn; //FUERZAS TANGENCIALES //Fuerza estática ele+=(Vct*dt); Ft=ele*(-Kcundall); //Fuerza cinética Ftmax=MU*componenteFn; normaFt=norma(Ft); if(normaFt>Ftmax) Ft=ele*(-Ftmax/norma(ele)); F2=Fn+Ft; Grano1.AgregueFuerza(F2*(-1)); Grano2.AgregueFuerza(F2); Grano1.AgregueTorque((n*(-R2))^Ft); Grano2.AgregueTorque((n*R1)^(Ft*(-1))); EstoyEnColision=true; } else if(EstoyEnColision==true){ ele.cargue(0,0,0); EstoyEnColision=false; } }*/ void Colisionador::CalculeLaFuerzaEntrePlanos(Cuerpo * Grano, vector3D & ele, bool & EstoyEnColision, double dt){ vector3D F2,Fn,runitario,n,Vc,Vcn; double m1,m2,m12,componenteVcn,componenteFn; double ERFF=1e-8, s=-Grano[21].Getaz()-L/2; if(Grano[21].Getaz()<-L/2 and Grano[21].Getbz()<-L/2 and Grano[21].Getcz()<-L/2){ //SI SE CHOCAN //Geometria y dinamica del contacto n.cargue(0,0,-1); //Calcular velocidad de contacto Vc=Grano[21].V; componenteVcn=Vc*n;Vcn=n*componenteVcn; //FUERZAS NORMALES //Fuerza de Hertz componenteFn=K*pow(s,1.5); //Disipación Plástica //componenteFn-=m12*sqrt(s)*Gamma*componenteVcn; if(componenteFn<0) componenteFn=0; Fn=n*componenteFn; F2=Fn; int i; for(i=0;i<N-1;i++){ Grano[i].AgregueFuerza(F2*(-1)); } EstoyEnColision=true; } } void InicieAnimacion(void){ cout<<"set terminal gif animate"<<endl; cout<<"set output '2cubo.gif'"<<endl; cout<<"unset key"<<endl; cout<<"set xrange [-60:60]"<<endl; cout<<"set yrange [-60:60]"<<endl; cout<<"set zrange [-60:12]"<<endl; //cout<<"set term gif size 900,700"<<endl; cout<<"set size 1.1,1.1"<<endl; cout<<"set size ratio -1"<<endl; cout<<"set view equal xyz"<<endl; cout<<"set hidden3d front"<<endl; cout<<"set parametric"<<endl; cout<<"set urange [0:pi]"<<endl; cout<<"set vrange [0:2*pi]"<<endl; cout<<"t(u)=10*u/pi"<<endl; cout<<"m(u)=u/pi"<<endl; cout<<"n(v)=v/(2*pi)"<<endl; cout<<"set isosamples 8"<<endl; } void InicieCuadro(void){ cout<<"splot 0,0,0 "; } void TermineCuadro(void){ cout<<endl; } int main(void){ double t, dt=1e-2, tmax=12; int Ndibujos; double tdibujo; Cuerpo parte[N]; Colisionador Newton; Crandom ran64(1); double me=1,mc=1,mp=1,mp_grande=1000; double Ie=2/5.*me*R*R, Ic=1/2.*mc*R*R, Ip=1/6.*mp*A*A, Ip_grande=1/6.*mp_grande*L*L; double V=0, Vy=0, theta0=M_PI, omega0=10; Ndibujos=300; InicieAnimacion(); //Inicio de cuerpos //x0, y0, z0, phi0, alpha0, beta0, //a10, a20, a30, b10, b20, b30, c10, c20, c30, //Vx0, Vy0, Vz0, theta0, omega0, m0, I //ESFERAS parte[0].Inicie(0,0,0, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[1].Inicie(A,0,0, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[2].Inicie(0,A,0, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[3].Inicie(0,0,A, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[4].Inicie(0,A,A, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[5].Inicie(A,0,A, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[6].Inicie(A,A,0, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); parte[7].Inicie(A,A,A, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,me,Ie); //CILINDROS parte[8].Inicie( 0,0,0, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[9].Inicie( 0,0,0, M_PI/2,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[10].Inicie(0,0,0, 0,0,-M_PI/2, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[11].Inicie(0,A,0, M_PI/2,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[12].Inicie(0,A,0, 0,M_PI/2,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[13].Inicie(A,0,0, 0,0,-M_PI/2, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[14].Inicie(A,0,0, 0,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[15].Inicie(0,0,A, M_PI/2,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[16].Inicie(0,0,A, 0,0,-M_PI/2, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[17].Inicie(A,A,0, 0,M_PI/2,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[18].Inicie(0,A,A, M_PI/2,0,0, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); parte[19].Inicie(A,0,A, 0,0,-M_PI/2, 0,0,0,0,0,0,0,0,0, V,Vy,0,theta0,omega0,mc,Ic); //PLANOS parte[20].Inicie(0,0,0,0,0,0, -R,0,0, -R,A,0, -R,0,A, V,Vy,0,theta0,omega0,mp,Ip); parte[21].Inicie(0,0,0,0,0,0, 0,0,-R, 0,A,-R, A,0,-R, V,Vy,0,theta0,omega0,mp,Ip); parte[22].Inicie(0,0,0,0,0,0, 0,-R,0, A,-R,0, 0,-R,A, V,Vy,0,theta0,omega0,mp,Ip); parte[23].Inicie(0,0,0,0,0,0, 0,0,A+R, A,0,A+R, 0,A,A+R, V,Vy,0,theta0,omega0,mp,Ip); parte[24].Inicie(0,0,0,0,0,0, A+R,0,0, A+R,0,A, A+R,A,0, V,Vy,0,theta0,omega0,mp,Ip); parte[25].Inicie(0,0,0,0,0,0, 0,A+R,0, A,A+R,0, 0,A+R,A, V,Vy,0,theta0,omega0,mp,Ip); parte[26].Inicie(0,0,0,0,0,0, -L/2,-L/2,-L/2, -L/2,L/2,-L/2, L/2,-L/2,-L/2, 0,0,0,0,0,mp_grande,Ip_grande); int i; //Dibuja cubo y plano for (t=tdibujo=0;t<tmax;t+=dt,tdibujo+=dt){ if (tdibujo>tmax/Ndibujos){ InicieCuadro(); for(i=0;i<8;i++) parte[i].Dibujar_esfera(); for(i=8;i<20;i++) parte[i].Dibujar_cilindro(); for(i=20;i<N;i++) parte[i].Dibujar_plano(); TermineCuadro(); tdibujo=0; }//cout<<parte[21].Getx()<<" "<<parte[21].Gety()<<" "<<parte[21].Getz()<<" "<<parte[21].Getaz()<<" "<<parte[21].Getbz()<<" "<<parte[21].Getcz()<<endl; //Muevase con Omelyan FR. for(i=0;i<N;i++){ parte[i].Mueva_r(dt, Zeta); } Newton.CalculeTodasLasFuerzas(parte, dt); for(i=0;i<N;i++){ parte[i].Mueva_V(dt, (1-2*Lambda)/2); } for(i=0;i<N;i++){ parte[i].Mueva_r(dt, Xi); } Newton.CalculeTodasLasFuerzas(parte, dt); for(i=0;i<N;i++){ parte[i].Mueva_V(dt, Lambda); } for(i=0;i<N;i++){ parte[i].Mueva_r(dt, 1-2*(Xi+Zeta)); } Newton.CalculeTodasLasFuerzas(parte, dt); for(i=0;i<N;i++){ parte[i].Mueva_V(dt, Lambda); } for(i=0;i<N;i++){ parte[i].Mueva_r(dt, Xi); } Newton.CalculeTodasLasFuerzas(parte, dt); for(i=0;i<N;i++){ parte[i].Mueva_V(dt, (1-2*Lambda)/2); } for(i=0;i<N;i++){ parte[i].Mueva_r(dt, Zeta); } } return 0; }
C
UTF-8
126
2.671875
3
[]
no_license
#include <stdio.h> int main() { int var = 10; int int_ptr = &var; printf("%d\n", int_ptr); return 0; }
JavaScript
UTF-8
647
2.8125
3
[]
no_license
//importando request var request = require('request'); ///Pegando arquivos function get_img(url, tipo) { request(url, (response, body) => { if (response.statusCode == 200) { const https = body //BUSCA PELO INDICE const types = https.indexOf(tipo) //htttps pegar de trás para frente o primeiro https const httpsv = https.lastIndexOf('https:', types) //resultado url var resultado = https.slice(httpsv,types+4); console.log(resultado) } }); } //Exportar img para importar em outro lugar exports.get_img = get_img
C++
UTF-8
2,049
3.515625
4
[]
no_license
#include<iostream> #include <vector> #include <stdexcept> #include <cmath> #include <string> #include <map> #include <algorithm> #include <stack> #include <unordered_map> #include <queue> using namespace std; class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers); // int Partition(vector<int>& arg1, int begin, int end); }; int Solution::MoreThanHalfNum_Solution(vector<int> numbers) { int num(numbers[0]), times(1); for (int i(1); i < numbers.size(); i++) { if (times == 0) { num = numbers[i]; times = 1; } if (num != numbers[i]) times--; else if (num == numbers[i]) times++; } int count(0); for (int i(0); i < numbers.size(); i++) { if (numbers[i] == num) count++; } if (count <= numbers.size() / 2) return 0; else return num; } //int Solution::MoreThanHalfNum_Solution(vector<int> numbers) //{ // if (numbers.size() == 0) // return 0; // // int middle=Partition(numbers, 0, numbers.size()-1); // int left(0), right(numbers.size() - 1); // // while (middle != numbers.size() / 2) // { // if (middle > numbers.size() / 2) // { // right = middle-1; // middle = Partition(numbers, left, right); // } // // if (middle < numbers.size() / 2) // { // left = middle+1; // middle = Partition(numbers, left, right); // } // } // // int result = numbers[middle]; // int count(0); // for (int i(0); i < numbers.size(); i++) // { // if (numbers[i] == result) // count++; // } // if (count <= numbers.size() / 2) // return 0; // else // return result; //} //int Solution::Partition(vector<int>& arg1, int begin, int end) //{ // int i(begin - 1), j(begin); // while (j <= end - 1) // { // if (arg1[j] <= arg1[end]) // { // i++; // int temp = arg1[i]; // arg1[i] = arg1[j]; // arg1[j] = temp; // } // j++; // } // int temp = arg1[i+1]; // arg1[i+1] = arg1[end]; // arg1[end] = temp; // return i + 1; //} int main(int argc, char *argv[]) { Solution Sol; vector<int> vec{ 1,2,3,2,4,2,5,2,3 }; cout<<Sol.MoreThanHalfNum_Solution(vec); return 0; }
Java
UTF-8
4,351
2.1875
2
[]
no_license
package com.wzcsoft.dzpjdy.util; import com.alibaba.fastjson.JSON; import com.wzcsoft.dzpjdy.domain.User; import org.json.JSONArray; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author lyj * @date 2019/7/26 1:12 */ public class JsonUtil { public static String getAccessToken(String str){ com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str); String access_token = jsonObject.getString("access_token"); return access_token; } public static Map<String, Object> getBody(String str) { //todo String s1=null; try { byte[] bytes = str.getBytes("UTF-8"); s1 = new String(bytes, "UTF-8"); System.out.println("解码后的UTF-8"+s1); }catch (Exception e){ System.out.println("解析编码格式失败"+e.getMessage()); } Map<String, Object> rempmap = new HashMap<>(); System.out.println("获取病人基本信息"+str); try { org.json.JSONObject jsonResult = new org.json.JSONObject(s1); Object responseTime1 = jsonResult.get("responseTime"); String s = String.valueOf(responseTime1); Object status_1 = jsonResult.get("status"); String status = String.valueOf(status_1); //todo Object msgCode_1 = jsonResult.get("msgCode"); String msgCode = String.valueOf(msgCode_1); Object msg_1 = jsonResult.get("msg"); String msg = String.valueOf(msg_1); Object inParamSize_1 = jsonResult.get("inParamSize"); String inParamSize = String.valueOf(inParamSize_1); Object transId_1 = jsonResult.get("transId"); String transId = String.valueOf(transId_1); rempmap.put("status", status); rempmap.put("msg", msg); rempmap.put("inParamSize", inParamSize); rempmap.put("transId", transId); rempmap.put("responseTime", s); org.json.JSONObject result1 = jsonResult.getJSONObject("result"); String result = result1.toString(); com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result); String pageNo = jsonObject.getString("pageNo"); String pageSize = jsonObject.getString("pageSize"); String total = jsonObject.getString("total"); String totalPage = jsonObject.getString("totalPage"); rempmap.put("pageNo", pageNo); rempmap.put("pageSize", pageSize); rempmap.put("total", total); rempmap.put("totalPage", totalPage); String content = jsonObject.getString("content"); rempmap.put("content", content); rempmap.put("msgCode", msgCode); // List<User> list = com.alibaba.fastjson.JSONObject.parseObject(content, List.class); // for (int i = 0; i < list.size(); i++) { // User user = com.alibaba.fastjson.JSONObject.parseObject( com.alibaba.fastjson.JSONObject.toJSONString(list.get(i)), User.class); // String caseNo = user.getCaseNo(); // String certId = user.getCertId(); // String patSex = user.getPatSex(); // System.out.println(patSex); // if(patSex.equals("1")){ // patSex="男"; // }else if(patSex.equals("2")) { // patSex="女"; // }else { // patSex="未说明性别"; // } // String patId = user.getPatId(); // String patName = user.getPatName(); // rempmap.put("caseNo", caseNo); // rempmap.put("certId", certId); // rempmap.put("patSex", patSex); // rempmap.put("patId", patId); // rempmap.put("patName", patName); // } return rempmap; } catch (Exception e) { System.out.println(e.getMessage()); rempmap.put("msg", "解析异常"); } return rempmap; } }
C++
UTF-8
3,260
2.578125
3
[]
no_license
#include "Skybox.h" Skybox::Skybox(int scale, Scene *scene) { for (int i = 0; i < 108; i++) { skyboxVertices[i] *= scale; } glGenVertexArrays(1, &skyboxVAO); glGenBuffers(1, &skyboxVBO); glBindVertexArray(skyboxVAO); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid *)0); glBindVertexArray(0); std::vector<const GLchar*> faces; faces.push_back("res/textures/skybox/bluecloud_rt.jpg"); faces.push_back("res/textures/skybox/bluecloud_lf.jpg"); faces.push_back("res/textures/skybox/bluecloud_up.jpg"); faces.push_back("res/textures/skybox/bluecloud_dn.jpg"); faces.push_back("res/textures/skybox/bluecloud_bk.jpg"); faces.push_back("res/textures/skybox/bluecloud_ft.jpg"); cubemapTexture = loadCubemap(faces); this->scene = scene; shader = new ShaderProgram("res/shaders/skyboxVertex.glsl", "res/shaders/skyboxFragment.glsl"); } void Skybox::draw() { glDepthFunc(GL_LEQUAL); shader->start(); shader->loadMatrix(glGetUniformLocation(shader->getProgramID(), "view"), scene->camera->getViewMatrix()); shader->loadMatrix(glGetUniformLocation(shader->getProgramID(), "projection"), scene->camera->getProjectionMatrix()); glBindVertexArray(skyboxVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glDepthFunc(GL_LESS); shader->stop(); } GLuint Skybox::loadTexture(GLchar *path) { GLuint textureID; glGenTextures(1, &textureID); int imageWidth, imageHeight; unsigned char *image = SOIL_load_image(path, &imageWidth, &imageHeight, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); SOIL_free_image_data(image); return textureID; } GLuint Skybox::loadCubemap(std::vector<const GLchar * > faces) { GLuint textureID; glGenTextures(1, &textureID); int imageWidth, imageHeight; unsigned char *image; glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); for (GLuint i = 0; i < faces.size(); i++) { image = SOIL_load_image(faces[i], &imageWidth, &imageHeight, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); SOIL_free_image_data(image); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); return textureID; }
PHP
UTF-8
1,840
2.859375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: hocvt * Date: 7/25/16 * Time: 09:40 */ namespace App\Traits; trait FileUtils { private $tmp_files = []; /** * Tạo 1 file tạm tự động xóa * * @param null|string|resource $input * * @param bool $is_content xác định input là content hay path * * @param string $wm * * @return string */ protected function newTmp($input = null,$id_post = null, $is_content = true, $wm = 'w+'){ if($id_post !== null){ $filename = tempnam(storage_path("media/".$id_post), 'Chv'); }else{ $filename = tempnam(storage_path("media"), 'Chv'); } $this->tmp_files[] = $filename; if($input != null){ if(is_resource($input)){ $ft = fopen($filename, $wm); while($block = fread($input, 4096)){ fwrite($ft, $block); } fclose($ft); }elseif($is_content){ file_put_contents($filename, $input); }else{ $fi = fopen($input, 'rb'); $ft = fopen($filename, 'wb'); while($block = fread($fi, 4096)){ fwrite($ft, $block); } fclose($fi); fclose($ft); } } return $filename; } /** * @return string * @throws \Exception */ private function newTmpFolder($name = 'GldocConverter'){ $filename = tempnam(storage_path('tmp'), $name); if (file_exists($filename)) { \File::delete($filename); } $filename = dirname($filename) . DIRECTORY_SEPARATOR . preg_replace('/\./', '_', basename($filename)); if(\File::makeDirectory($filename, 0777, true) === false){ mkdir($filename, '0777', true); } if (!is_dir($filename)) { throw new \Exception("Can not create tmp folder"); } $this->tmp_files[] = $filename; return $filename; } /** * Danh sách file tạm đã tạo * @return array */ private function listTmp(){ return $this->tmp_files; } }
Markdown
UTF-8
4,256
3.109375
3
[ "MIT" ]
permissive
--- layout: item title: "Wand of Wonder" sources: [DMG.212] tags: [focus, wand, rare, attunement] category: "Wand" rarity: "Rare (requires attunement by a spellcaster)" --- This wand has 7 charges. While holding it, you can use an action to expend 1 of its charges and choose a target within 120 feet of you. The target can be a creature, an object, or a point in space. Roll d100 and consult the following table to discover what happens. If the effect causes you to cast a spell from the wand, the spell’s save DC is 15. If the spell normally has a range expressed in feet, its range becomes 120 feet if it isn’t already. If an effect covers an area, you must center the spell on and include the target. If an effect has multiple possible subjects, the DM randomly determines which ones are affected. The wand regains 1d6 + 1 expended charges daily at dawn. If you expend the wand’s last charge, roll a d20. On a 1, the wand crumbles into dust and is destroyed. d100 Result | Effect ------------|------- 01-05 | You cast slow. 06-10 | You cast faerie fire. 11-15 | You are stunned until the start of your next turn, believing something awesome just happened. 16-20 | You cast gust of wind. 21-25 | You cast detect thoughts on the target you chose. If you didn’t target a creature, you instead take 1d6 psychic damage. 26-30 | You cast stinking cloud. 31-33 | Heavy rain falls in a 60-foot radius centered on the target. The area becomes lightly obscured. The rain falls until the start of your next turn. 34-36 | An animal appears in the unoccupied space nearest the target. The animal isn’t under your control and acts as it normally would. Roll a d100 to determine which animal appears. On a 01–25, a rhinoceros appears; on a 26–50, an elephant appears; and on a 51–100, a rat appears. 37-46 | You cast lightning bolt. 47-49 | A cloud of 600 oversized butterflies fills a 30-foot radius centered on the target. The area becomes heavily obscured. The butterflies remain for 10 minutes. 50-53 | You enlarge the target as if you had cast enlarge/reduce. If the target can’t be affected by that spell, or if you didn’t target a creature, you become the target. 54-58 | You cast darkness. 59-62 | Grass grows on the ground in a 60-foot radius centered on the target. If grass is already there, it grows to ten times its normal size and remains overgrown for 1 minute. 63-65 | An object of the GM’s choice disappears into the Ethereal Plane. The object must be neither worn nor carried, within 120 feet of the target, and no larger than 10 feet in any dimension. 66-69 | You shrink yourself as if you had cast enlarge/reduce on yourself. 70-79 | You cast fireball. 80-84 | You cast invisibility on yourself. 85-87 | Leaves grow from the target. If you chose a point in space as the target, leaves sprout from the creature nearest to that point. Unless they are picked off, the leaves turn brown and fall off after 24 hours. 88-90 | A stream of 1d4 × 10 gems, each worth 1 gp, shoots from the wand’s tip in a line 30 feet long and 5 feet wide. Each gem deals 1 bludgeoning damage, and the total damage of the gems is divided equally among all creatures in the line. 91-95 | A burst of colorful shimmering light extends from you in a 30-­‐foot radius. You and each creature in the area that can see must succeed on a DC 15 Constitution saving throw or become blinded for 1 minute. A creature can repeat the saving throw at the end of each of its turns, ending the effect on itself on a success. 96-97 | The target's skin turns bright blue for 1d10 days. If you chose a point in space, the creature nearest to that point is affected. 98-00 | If you targeted a creature, it must make a DC 15 Constitution saving throw. If you didn’t target a creature, you become the target and must make the saving throw. If the saving throw fails by 5 or more, the target is instantly petrified. On any other failed save, the target is restrained and begins to turn to stone. While restrained in this way, the target must repeat the saving throw at the end of its next turn, becoming petrified on a failure or ending the effect on a success. The petrification lasts until the target is freed by the greater restoration spell or similar magic.
C++
UTF-8
1,487
2.859375
3
[]
no_license
class Solution { public: int leastInterval(vector<char>& tasks, int n) { vector<int> freq(26); // frequency of each task for (const char& ch: tasks) { freq[ch - 'A']++; } // Find the maximum frequency int maxTask = *max_element(begin(freq), end(freq)); // number of tasks which have the max frequency int countMaxTasks = count(begin(freq), end(freq), maxTask); return max((int) tasks.size(), (n + 1) * (maxTask - 1) + countMaxTasks); } int leastInterval1(vector<char>& tasks, int n) { int ans = 0; vector<int> freqs(26); priority_queue<int> pq; for (const char& ch: tasks) { freqs[ch - 'A']++; } for (const int& freq: freqs) { if (freq) { pq.push(freq); } } while (not pq.empty()) { int cycle = n + 1; vector<int> tmp; for (int i = 0; i < cycle; i++) { if (not pq.empty()) { tmp.push_back(pq.top()); pq.pop(); } } for (int& duration: tmp) { if (--duration) { pq.push(duration); } } ans += pq.empty() ? tmp.size() : cycle; } return ans; } };
Markdown
UTF-8
2,849
2.984375
3
[]
no_license
# Predicting a book's literary success using specific books features ## Table of Contents 1. [Introduction and Overview](#introduction) 2. [Technologies](#technologies) 3. [Installation](#installation) 4. [References](#references) ### Introduction and Overview The purpose of this project is to analyze and predict book's overall rating success using various machine learning models. For the analysis, I have utilized datasets collected in 2017 provided by Goodreads which contains specific feature information such as the authors, publishers/publication companies, books average ratings, reviews, publication years, length of books (by pages), languages, genre, fiction/nonfiction classification, authors average ratings, books and authors ratings counts. The Goodreads dataset is structured data that contains information on 2.36M books with approximately 39 feature variables. After collecting the data, and proceeding to explore and clean the dataset as much as possible, I wanted to analyze further the possible research questions: 1. Would a nonfiction or fiction book prove to be more successful? Sucess being measured by the book's overall rating. 2. Does author's historical ratings contribute to the success of the next book he/she would publish? 3. Does the length of a book affect a book's literary success? 4. Are books part of a series more successful than a book not part of a series? ### Technologies Python3 required import packages specified in notebooks #### Please note: goodreads_books_series json file can not be uploaded into github. Please access the below link to download the book_series json file (Json file is located "Detailed Information on Book Series" section) : ##### https://sites.google.com/eng.ucsd.edu/ucsdbookgraph/books?authuser=0 ### Installation There are seperate notebooks for the EDA portion of the analysis and the various Machine Learning models I utilized to achieve the best accuracy result. 1. EDA_final.ipynb: - Loading in json files: goodreads books, goodreads authors, goodreads genre, and goodreads series - Cleaning and creating feature variables - Plots and visualizations- patterns and trends found - exporting clean dataframe into a csv file to run in Models.ipynb notebooks. (Code to save exported CSV file to drive is included in EDA notebook) 2. Modeling 1.ipynb- Decision Tree Classification 3. Modeling 2.ipynb- Support Vector Machine 4. Modeling 3.ipynb - K-nearest Neighbors ### References: ##### https://sites.google.com/eng.ucsd.edu/ucsdbookgraph/home ##### https://github.com/MengtingWan/goodreads/blob/master/README.md - Citations: - Mengting Wan, Julian McAuley, "Item Recommendation on Monotonic Behavior Chains", in RecSys'18. [bibtex] - Mengting Wan, Rishabh Misra, Ndapa Nakashole, Julian McAuley, "Fine-Grained Spoiler Detection from Large-Scale Review Corpora", in ACL'19. [bibtex]
Python
UTF-8
567
3.921875
4
[]
no_license
''' You are given a string S. Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order. Input Format A single line containing the string S and integer value k separated by a space. ''' # Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import combinations if __name__ == "__main__": (s, r) = tuple(input().split()) r = int(r) s = sorted(s) for i in range(1, r+1): result = combinations(s, i) for item in result: print(("".join(item)))
C++
UTF-8
544
2.640625
3
[]
no_license
#include <iostream> #include <chrono> #include <thread> void StatusLoop(); int main(int argc, char* argv[]){ if(argc == 1){ system("cat HSSTool.txt"); return 0; } char StatusArg {'s'}; char* pStatusArg = &StatusArg; if(*argv[1] == *pStatusArg){ std::cout<<"Success.\n"; StatusLoop(); } return 0; } void StatusLoop(){ while(true){ system("clear"); system("hotspotshield status"); std::this_thread::sleep_for(std::chrono::seconds(1)); } }
Python
UTF-8
1,622
2.796875
3
[]
no_license
#!/bin/python2 ### This ncfile is set up to compare the Mass Extinction Coefficients with ### internal vs. external mixing from netCDF4 import Dataset import numpy as np import sys as sys import itertools ### Read data files # Open netCDF file ncfile_bc = 'bc_size.nc' ncfile_su = 'sulfate_size.nc' fh_bc = Dataset(ncfile_bc, 'r') fh_su = Dataset(ncfile_su, 'r') # Read in coordinates wl_orig = fh_bc.variables['wl'][:] rm_orig = fh_bc.variables['RadMean'][:] rh_orig = fh_bc.variables['RH'][:] wlpkd = 0.55 # choose the wavelength at 550nm to represent shortwave radiation wlpkdind = np.where((wl_orig >= wlpkd-0.02) & (wl_orig <= wlpkd+0.02))[0].item() print wlpkdind # Read in data mac_bc_orig = fh_bc.variables['beta_e'][:][:][:] * (1. - np.array(fh_bc.variables['ssa'][:][:][:])) ssa_bc_orig = fh_bc.variables['ssa'][:][:][:] mec_su_orig = fh_su.variables['beta_e'][:][:][:] ssa_su_orig = fh_su.variables['ssa'][:][:][:] # Assign picked values wl = wlpkd mac_bc = mac_bc_orig[wlpkdind,:,:] ssa_bc = ssa_bc_orig[wlpkdind,:,:] mec_su = mec_su_orig[wlpkdind,:,:] ssa_su = ssa_su_orig[wlpkdind,:,:] print 'shape = '+str(mac_bc.shape) units = fh_bc.variables['beta_e'].units for i in range(len(rm_orig)): print 'Mean Radius = '+str(rm_orig[i]) print 'Pure BC MAC = '+str(mac_bc[i][0])+' '+units print 'Pure BC SSA = '+str(ssa_bc[i][0]) for i,j in itertools.product(range(len(rm_orig)),range(len(rh_orig))): print 'RH = '+str(rh_orig[j])+'%' print 'Pure Sulfate MEC = '+str(mec_su[i][j])+' '+units print 'Pure Sulfate SSA = '+str(ssa_su[i][j]) fh_bc.close() fh_su.close()
C#
UTF-8
1,042
2.984375
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using WeekdayFinder.Models; namespace WeekdayFinder.Controllers { public class HomeController : Controller { [Route("/hello")] public string Hello() { return "Hello friend!"; } [Route("/goodbye")] public string Goodbye() { return "Goodbye friend."; } [Route("/form")] public ActionResult Form() { // Weekday dates = new Weekday(result, result2, result3); // dates.Result = result; // Console.WriteLine("Input a month with two digits: Ex: 01 = January, 02 = February, etc."); // int result = int.Parse(Console.ReadLine()); // Console.WriteLine("Input a day with two digits: "); // int result2 = int.Parse(Console.ReadLine()); // Console.WriteLine("Input a year with four digits: "); // int result3 = int.Parse(Console.ReadLine()); // DateTime dateValue = new DateTime(W); // Console.WriteLine("-------------------"); // Console.WriteLine(dateValue.ToString("dddddddd")); return View(); } } }
PHP
UTF-8
2,810
2.59375
3
[ "MIT" ]
permissive
<?php /* * This file is part of Yrgo. * * (c) Yrgo, högre yrkesutbildning. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); require __DIR__.'/../autoload.php'; $id = $_SESSION['userid']; $getData = $pdo->prepare('SELECT * FROM users WHERE id=:id'); $getData->bindParam(':id', $id); $getData->execute(); $data = $getData->fetch(PDO::FETCH_ASSOC); if (strlen($_POST['email']) > 0 && $_POST['email'] != $data['email']) { $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $updateEmail = $pdo->prepare('UPDATE users SET email=:email WHERE id=:id'); $updateEmail->bindParam(':email', $email); $updateEmail->bindParam(':id', $id); $updateEmail->execute(); } if (strlen($_POST['bio']) > 0 && $_POST['bio'] != $data['bio']) { $bio = filter_var($_POST['bio'], FILTER_SANITIZE_STRING); $updateBio = $pdo->prepare('UPDATE users SET bio=:bio WHERE id=:id'); $updateBio->bindParam(':bio', $bio); $updateBio->bindParam(':id', $id); $updateBio->execute(); } if (isset($_POST['urlcheck']) && $_POST['urlcheck'] && strlen($_POST['avatar']) > 0) { $updateAvatar = $pdo->prepare('UPDATE users SET avatar_url=:avatar WHERE id=:id'); $url = filter_var($_POST['avatar'], FILTER_SANITIZE_URL); $updateAvatar->bindParam(':avatar', $url); $updateAvatar->bindParam(':id', $id); $updateAvatar->execute(); } if (isset($_FILES['avatar']) && !empty($_FILES['avatar'])) { $target_dir = 'users/'.$data['nickname'].'/'; $target_file = $target_dir.'profileImage.png'; if (!mkdir('../../'.$target_dir, 0777, true)) { echo 'Folder already exists'; } if (move_uploaded_file($_FILES['avatar']['tmp_name'], '../../'.$target_file)) { $updateAvatar = $pdo->prepare('UPDATE users SET avatar_url=:avatar WHERE id=:id'); $updateAvatar->bindParam(':avatar', $target_file); $updateAvatar->bindParam(':id', $id); $updateAvatar->execute(); echo 'The file '.basename($_FILES['avatar']['name']).' has been uploaded.'; } else { echo 'Sorry, there was an error uploading your file.'; } } if (isset($_POST['passwNew']) && strlen($_POST['passwNew']) > 0 && $_POST['passwNew'] == $_POST['passwRepeat'] && password_verify($_POST['passwOld'], $data['passw'])) { $updateData = $pdo->prepare('UPDATE users SET passw=:pass WHERE id=:id'); $pass = password_hash($_POST['passwNew'], PASSWORD_DEFAULT); $updateData->bindParam(':pass', $pass); $updateData->bindParam(':id', $_SESSION['userid']); if (!$updateData->execute()) { redirect('../../profile.php?passchange=false'); die; } redirect('../../profile.php?passchange=true'); die; } redirect('../../profile.php');
Python
UTF-8
1,439
2.65625
3
[]
no_license
from datetime import datetime from ...extensions import db # -------------------------------- Driver Model ------------------------------- # class Driver(db.Model): """ Driver Model: The driver is the one who produce data records. """ __tablename__ = 'drivers' id = db.Column(db.Integer, primary_key=True) gender = db.Column(db.SmallInteger, default=0) fullname = db.Column(db.String(255), default='Anonyme') avatar = db.Column(db.String(255), nullable=True) city = db.Column(db.String(255), nullable=True) status_id = db.Column(db.SmallInteger, db.ForeignKey('status.id')) status = db.relationship('Status') user_id = db.Column(db.Integer, db.ForeignKey('users.id')) user = db.relationship('User', backref=db.backref('drivers', lazy='dynamic')) country_id = db.Column(db.Integer, db.ForeignKey('countries.id')) country = db.relationship('Country') created = db.Column(db.DateTime(), default=datetime.utcnow()) def __init__(self, user_id, country_id, **kwargs): self.vars = kwargs self.gender = kwargs.get('gender', 3) self.fullname = kwargs.get('fullname', 'Anonymous driver') self.user_id = user_id self.country_id = country_id self.avatar = kwargs.get('avatar') self.status_id = kwargs.get('status_id', 1) self.city = kwargs.get('city') def __repr__(self): return self.fullname
Java
UTF-8
207
1.859375
2
[]
no_license
package com.generactive.util.namegenerator; public class Nouns { public static final String[] VALUES = new String[]{ "n_name1", "n_name2" }; private Nouns() { } }
Java
UTF-8
331
2.453125
2
[]
no_license
package com.wangby.ztest; public class RunB implements Runnable { private Object lock; public RunB(Object lock) { this.lock = lock; } @Override public void run() { synchronized (lock) { System.out.println("RunB start"); while (true) { } } } }
Java
UTF-8
1,186
2.390625
2
[]
no_license
package org; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.statemachine.abstractfactory.StateAbstractFactory; import org.statemachine.interfaces.IContext; import org.statemachine.interfaces.IGameState; public class Main { public static void main(String[] args) { String log4jConfigPath = "src/main/conf/log4j.properties"; PropertyConfigurator.configure(log4jConfigPath); Logger logger = Logger.getLogger(Main.class.getName()); logger.info("Application started."); GlobalExceptionHandler globalExceptionHandler = new GlobalExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); StateAbstractFactory stateFactory = StateAbstractFactory.instance(); IContext gameContext = stateFactory.createGameContext(); if (args.length == 1) { IGameState importState = stateFactory.createImportState(gameContext, args); gameContext.stateMachine(importState); } else { IGameState loadState = stateFactory.createLoadTeamState(gameContext); gameContext.stateMachine(loadState); } } }
Go
UTF-8
1,232
3.46875
3
[]
no_license
package logger import ( "os" "io" ) var stdlog *Loggie func init() { stdlog = NewLoggie("Loggie", os.Stdout) stdlog.SetLogLevel(STDLVL) } //Returns the loggies level as an int func GetCurrentLogLevel() loglevel { return stdlog.loglvl } //Sets to loggies loglevel func SetLogLevel(level loglevel) { stdlog.SetLogLevel(level) } //Makes loggie write to the new writer aswell. func AddDestination(w io.Writer) { stdlog.AddDestination(w) } //Prints a log message if the level is below the current Loglevel. //Messege is printed in format "Log <level>: <message>" and //ends with a new line. func Log(level loglevel, message string) { stdlog.Log(level, message) } //Log function using the Printf function of log rather than Print. //Ends with a newline func Logf(level loglevel, message string, params ...interface{}) { stdlog.Logf(level, message, params...) } func Printf(message string, params ...interface{}) { stdlog.Printf(message, params...) } func Println(message string) { stdlog.Println(message) } func Nl() { stdlog.Nl() } func Panic(message string, params ...interface{}) { stdlog.Panic(message, params...) } func Error(message string, params ...interface{}) { stdlog.Error(message, params...) }
JavaScript
UTF-8
458
2.703125
3
[]
no_license
// @ts-check /* import { resolve } from 'url'; const apiUrl = 'http://localhost:8080/api/v2/'; */ // BEGIN (write your solution here) /* class WeatherService { constructor(client) { this.client = client; } async find(cityName) { const url = resolve(apiUrl, `cities/${cityName}`); const response = await this.client.get(url); const result = JSON.parse(response.data) return result; } } export default WeatherService; // END */
Markdown
UTF-8
14,918
3.21875
3
[]
no_license
# Formulaires Il y a 2 types de formulaires : * `FormsModule` \(en HTML\) * `ReactiveFormModule` \(en TypeScript\) ## Template-driven \(`FormsModule`\) Inspirée du "two-way binding", cette approche a de quelques limitations et s'avère peu extensible. A réserver pour des formulaires simples. Comme son nom l'indique, tout s'écrit dans le template. {% hint style="warning" %} Pour utiliser les formulaires template-driven, importer`FormsModule` est requis. {% endhint %} {% hint style="success" %} **Mise en pratique** Créons un module et un composant login. Ajouter _`LoginModule`_dans l'imports de `AppModule.` Ajouter la balise `<app-login>` dans `AppComponent`. Ajouter _`FormsModule`_ dans l'imports de `LoginModule.` {% code title="login.component.html" %} ```markup <form> Email <input type="text"> Password <input type="password"> <button>Valider</button> </form> ``` {% endcode %} ```markup <form (ngSubmit)="login()"> ``` ```markup <form (ngSubmit)="login(myForm)" #myForm="ngForm"> ``` Ajoutons le attributs `name` aux `input`. {% code title="src\\app\\login\\login.component.html" %} ```markup <form (ngSubmit)="login(myForm)" #myForm="ngForm"> Email <input type="text" name="email" ngModel> Password <input type="text" name="password" ngModel> <button>Valider</button> </form> ``` {% endcode %} {% code title="src\\app\\login\\login.component.ts" %} ```typescript login(myForm: NgForm): void { console.log(myForm) } ``` {% endcode %} A présent, le `console.log` affiche un objet qui donne des infos sur le formulaire : valid / invalid / submitted / pristine / dirty / touched / untouched... Le `console.log(myform.value)` affiche le contenu des champs. {% endhint %} `ngModel` a 2 rôles : * gérer les valeurs des champs * relier les éléments HTML avec `ngForm` ### Validateurs Pour rendre les champs obligatoires on ajoute _`required`_ aux balises. Si on veut afficher "formulaire invalide" seulement après la soumission : ```markup <div *ngIf="myForm.dirty && myForm.invalid"> Formulaire invalide </div> ``` Pour gérer séparément les erreurs pour chaque champs : ```markup <div *ngIf="myForm.dirty"> <div *ngIf="myForm.invalid"> Formulaire invalide </div> <div *ngIf="myForm.controls.email?.hasError('required')"> Email requis </div> </div> ``` ```markup Email <input type="text" name="email" ngModel required minlength="3"> Password <input type="text" name="password" ngModel required minlength="6"> ``` {% hint style="success" %} **Mise en pratique** Complétez la gestion de l'affichage de l'erreur : * validateurs `minlength`et `email` pour le champ `email`. * validateurs `minlength="6"`et `required` pour le champ`password`. {% endhint %} {% hint style="info" %} Liste des validateurs disponibles : [https://angular.io/api/forms/Validators](https://angular.io/api/forms/Validators) {% endhint %} ## Reactive \(`ReactiveFormModule`\) ### Avantages des "Reactive Forms" Pour remédier aux différentes limitations des Template-driven Forms, Angular offre une approche originale et efficace nommée "Reactive Forms" présentant les avantages suivants : * La logique des formulaires **se fait dans le code TypeScript**. Le formulaire devient alors plus facile à **tester** et à **générer dynamiquement**. * Les "Reactive Forms" utilisent des **`Observable`**s pour faciliter et encourager le "**Reactive Programming**". ### Les outils des reactives forms #### `FormControl` La classe **`FormControl`** **permet de piloter et d'accéder à l'état** des "controls" de la vue _\(ex:_ _`<input>`\)_. `FormControl` fournit 3 méthodes :**`reset`**, **`setValue`** et **`patchValue`** pour modifier l'état et la valeur du "control", ainsi que les propriétés : | Propriété | Description | | :--- | :--- | | valid | true si la valeur est correcte | | errors | liste des erreurs \(objet\) | | dirty | true si l'utilisateur modifie le champ | | pristine | false si l'utilisateur modifie le champ | | touched | true si l'utilisateur atteint le champ | | untouched | false si l'utilisateur atteint le champ | | value | valeur du champ | | valueChanges | Observable pour les changements de valeur | #### `FormGroup` `FormGroup` permet de **regrouper des "controls"** afin de faciliter l'implémentation, récupérer la valeur groupée des "controls" ou encore appliquer des validateurs au groupe. | Propriété | Description | | :--- | :--- | | valid | true si tous les champs ont des valeurs correctes | | errors | objet avec toutes les erreurs des champs sinon null | | dirty | true si l'utilisateur modifie un des champ | | pristine | false si l'utilisateur modifie un des champ | | touched | true si l'utilisateur atteint un des champ | | untouched | false si l'utilisateur atteint un des champ | | values | liste des champs et de leurs valeurs | | valueChanges | Observable sur les changements des champs | #### `FormArray` `FormArray` héritant également de la classe abstraite `AbstractControl`, **permet de créer un "control" contenant une liste de "controls"** _\(e.g. `FormControl` ou `FormGroup`\)_ **ordonnés** _\(contrairement à `FormGroup` qui permet de créer un groupe de "controls" accessibles avec des clés sur un "plain object"\)._ La valeur contenu dans le `FormArray` est de type `Array`. #### `FormBuilder` Le module `ReactiveFormsModule` implémente également un service `FormBuilder` qui permet de **simplifier la création des `FormGroup`, `FormArray` ou `FormControl`**. ### Implémentation {% hint style="info" %} Les Reactive Forms n'utilisent pas `FormsModule` mais `ReactiveFormsModule`. {% endhint %} {% hint style="success" %} **Codons ensemble** Remplaçons la précédente importation de `FormsModule` par `ReactiveFormsModule`. Simplifions le template : {% code title="src\\app\\login\\login.component.html" %} ```markup <form (ngSubmit)="login()" [formGroup]="myForm"> Email <input type="text" [formControl]="email"> Password <input type="text" [formControl]="password"> <button>Valider</button> </form> ``` {% endcode %} Ajoutons la gestion du formulaire dans la classe : {% code title="src\\app\\login\\login.component.ts" %} ```typescript import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { myForm: FormGroup; email: FormControl; password: FormControl; constructor(private builder: FormBuilder) { this.email = new FormControl(); this.password = new FormControl(); this.myForm = this.builder.group({ email: this.email, password: this.password }); } ngOnInit(): void {} login() { console.info(this.myForm); } } ``` {% endcode %} A ce stade, on doit avoir un formulaire fonctionnel. Ajoutons un validateur {% code title="src\\app\\login\\login.component.ts" %} ```typescript import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { myForm: FormGroup; email: FormControl; password: FormControl; constructor(private builder: FormBuilder) { this.email = new FormControl('', [Validators.required]); this.password = new FormControl(); this.myForm = this.builder.group({ email: this.email, password: this.password }); } ngOnInit(): void {} login() { console.info(this.myForm); } } ``` {% endcode %} Affichage des erreurs {% code title="src\\app\\login\\login.component.html" %} ```markup <form (ngSubmit)="login()" [formGroup]="myForm"> <div *ngIf="email.hasError('required')"> Email requis </div> Email <input type="text" [formControl]="email"> Password <input type="password" [formControl]="password"> <button>Valider</button> </form> ``` {% endcode %} {% endhint %} {% hint style="success" %} **Amélioration** ```markup <form (ngSubmit)="login()" [formGroup]="myForm"> <div *ngIf="myForm.dirty"> <div *ngIf="email.hasError('required')"> Email requis </div> </div> Email <input type="text" [formControl]="email"> Password <input type="password" [formControl]="password"> <button>Valider</button> </form> ``` {% endhint %} ### Mise en pratique {% hint style="success" %} Complétez la gestion de l'affichage de l'erreur : * validateurs `required`et `email` pour le champ `email`. * validateurs `required` et `minlength(6)`pour le champ`password`. {% endhint %} {% hint style="success" %} **Solution** ```typescript import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { submitted = false; myForm: FormGroup; email: FormControl; password: FormControl; constructor(private builder: FormBuilder) { this.email = new FormControl('', [ Validators.required, Validators.email ]); this.password = new FormControl('', [ Validators.required, Validators.minLength(6) ]); this.myForm = this.builder.group({ email: this.email, password: this.password }); } ngOnInit(): void { } login() { console.info(this.myForm); this.submitted = true; } } ``` ```markup <form (ngSubmit)="login()" [formGroup]="myForm"> <div *ngIf="submitted"> <div *ngIf="email.hasError('required')"> Email requis </div> <div *ngIf="email.hasError('email')"> Email invalide </div> <div *ngIf="password.hasError('required')"> Mot de passe requis </div> <div *ngIf="password.hasError('minlength')"> Mot de passe trop court </div> </div> Email <input type="text" [formControl]="email"> Password <input type="password" [formControl]="password"> <button>Valider</button> </form> ``` {% endhint %} ### Validateurs personnalisés {% code title="src\\app\\shared\\validators\\forbiddenChar.validator.ts" %} ```typescript import {FormControl, ValidationErrors} from '@angular/forms'; export function forbiddenChar(input: FormControl): ValidationErrors | null { return input.value.includes('#') ? {forbiddenChar: true} : null; } ``` {% endcode %} Pour l'utiliser {% code title="src\\app\\login\\login.component.ts" %} ```typescript import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {forbiddenChar} from '../shared/validators/forbiddenChar.validator'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { submitted = false; myForm: FormGroup; email: FormControl; password: FormControl; constructor(private builder: FormBuilder) { this.email = new FormControl('', [ Validators.required, Validators.email, forbiddenChar, ]); this.password = new FormControl('', [ Validators.required, Validators.minLength(6) ]); this.myForm = this.builder.group({ email: this.email, password: this.password }); } ngOnInit(): void { } login() { console.info(this.myForm); this.submitted = true; } } ``` {% endcode %} ```markup <form (ngSubmit)="login()" [formGroup]="myForm"> <div *ngIf="submitted"> <div *ngIf="email.hasError('required')"> Email requis </div> <div *ngIf="email.hasError('email')"> Email invalide </div> <div *ngIf="email.hasError('forbiddenChar')"> Caractère invalide </div> <div *ngIf="password.hasError('required')"> Mot de passe requis </div> <div *ngIf="password.hasError('minlength')"> Mot de passe trop court </div> </div> Email <input type="text" [formControl]="email"> Password <input type="password" [formControl]="password"> <button>Valider</button> </form> ``` Comment ajouter un paramètre à notre fonction `emailValidator` ? `Validators.minLength(3)` retourne une fonction qu’exécutera le validateur. Car le 2ème argument du validateur est un tableau de fonctions. ```typescript this.email= new FormControl('', [ Validators.required, forbiddenChar('#') ]) ``` ```typescript import { FormControl } from '@angular/forms'; export function forbiddenChar(letter: string) { return function validator(input: FormControl): ValidationErrors | null { return input.value.includes(letter) ? { forbiddenChar: true } : null } } ``` Pour afficher quelle est la lettre invalide : ```typescript import { FormControl } from '@angular/forms'; export function forbiddenChar(letter: string) { return function validator(input: FormControl): ValidationErrors | null { return input.value.includes(letter) ? { forbiddenChar: letter } : null; }; } ``` ```markup <div *ngIf="email.hasError('forbiddenChar')"> Caractère invalide : {{ email.errors.forbiddenChar}} </div> ``` ### Validateurs asynchrones Ex : Est-ce que cet email existe déjà dans la BDD ? -&gt; promesse ou observable. Utilisons `HttpClient` via un service. {% code title="src\\app\\core\\user.service.ts" %} ```typescript url = 'https://jsonplaceholder.typicode.com/users'; // Promise style checkEmail(input: FormControl): Promise<ValidationErrors | null> { return this.http .get(this.url + '/1') .toPromise() .then((user: User) => { return user.email === input.value ? { emailExists: true } : null }) } // Observable style checkEmail$(input: FormControl): Observable<ValidationErrors | null> { return this.http .get(this.url + '/1') .pipe( map((user: User) => { return user.email === input.value ? { emailExists: true } : null }) ) } ``` {% endcode %} {% code title="src\\app\\login\\login.component.ts" %} ```typescript constructor(private builder: FormBuilder, private usersService: UsersService) { this.email = new FormControl('', [ Validators.required, Validators.email, ], [this.userService._checkEmail.bind(this.usersService)]); this.password = new FormControl('', [ Validators.required, Validators.minLength(6) ]); this.myForm = this.builder.group({ email: this.email, password: this.password }); } ``` {% endcode %} On doit `bind` le contexte \(ou encapsuler dans une fonction pour garder `this.userService`\) car Angular exécute dans un autre contexte.
Java
UTF-8
816
2.46875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-unknown" ]
permissive
package com.rfacad.joystick; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.rfacad.buttons.interfaces.BState; import com.rfacad.buttons.ButtonCommand; @com.rfacad.Copyright("Copyright (c) 2018 Gerald Reno, Jr. All rights reserved. Licensed under Apache License 2.0") public class CmdExitJoystickDriver implements ButtonCommand { private static final Logger log = LogManager.getLogger(CmdExitJoystickDriver.class); RidiculouslySimpleJoystickDriver joystickDriver; public CmdExitJoystickDriver(RidiculouslySimpleJoystickDriver jd) { joystickDriver=jd; } public boolean button(BState state) { log.info("Shutting down."); if (joystickDriver!=null) { log.info("Shutting down joystick driver thread"); joystickDriver.shutdown(); } return true; } }
C#
UTF-8
4,071
3.171875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Polynomial; namespace PolynomialNUnitTests { [TestFixture] public class PolynomialTests { #region Plus public IEnumerable<TestCaseData> TestPlusData { get { yield return new TestCaseData(new Polynomial.Polynomial(0, 1), null).Throws(typeof(ArgumentNullException)); yield return new TestCaseData(new Polynomial.Polynomial(1, 2, 3), new Polynomial.Polynomial(2, 3, 4)).Returns(new Polynomial.Polynomial(3, 5, 7)); yield return new TestCaseData(new Polynomial.Polynomial(-4, -2, 0), new Polynomial.Polynomial(2, 3, 4, 5)).Returns(new Polynomial.Polynomial(-2, 1, 4, 5)); } } [Test, TestCaseSource(nameof(TestPlusData))] public Polynomial.Polynomial PlusOperator_AddTwoPolynomialsWithYield(Polynomial.Polynomial pol1, Polynomial.Polynomial pol2) { return pol1 + pol2; } #endregion #region Multiplication public IEnumerable<TestCaseData> TestMultiplyData { get { yield return new TestCaseData(new Polynomial.Polynomial(0, 1), null).Throws(typeof(ArgumentNullException)); yield return new TestCaseData(new Polynomial.Polynomial(1, 2), new Polynomial.Polynomial(1)).Returns(new Polynomial.Polynomial(1, 2)); yield return new TestCaseData(new Polynomial.Polynomial(-4, -2, 0), new Polynomial.Polynomial(2, 3, 4, 5)).Returns(new Polynomial.Polynomial(-8, -16, -22, -28, -10)); } } [Test, TestCaseSource(nameof(TestMultiplyData))] public Polynomial.Polynomial MultiplyOperator_MultiplyPolynomailsWithYield(Polynomial.Polynomial pol1, Polynomial.Polynomial pol2) { return pol1 * pol2; } public IEnumerable<TestCaseData> TestMultiplyOnDoubleData { get { yield return new TestCaseData(null, 2).Throws(typeof(ArgumentNullException)); yield return new TestCaseData(new Polynomial.Polynomial(1, 2), 2).Returns(new Polynomial.Polynomial(2, 4)); yield return new TestCaseData(new Polynomial.Polynomial(-4, -2, 3, 0), -2).Returns(new Polynomial.Polynomial(8, 4, -6)); } } [Test, TestCaseSource(nameof(TestMultiplyOnDoubleData))] public Polynomial.Polynomial MultiplyOperator_MultiplyPolynomailOnDoubleWithYield(Polynomial.Polynomial pol, double x) { return pol*x; } #endregion #region Equals public IEnumerable<TestCaseData> TestEqualsData { get { yield return new TestCaseData(new Polynomial.Polynomial(1, 2, 3)).Returns(true); yield return new TestCaseData(new Polynomial.Polynomial(1, 2, 3, 0, 0, 0)).Returns(true); yield return new TestCaseData(new Polynomial.Polynomial(1, 2)).Returns(false); yield return new TestCaseData(null).Returns(false); } } [Test, TestCaseSource(nameof(TestEqualsData))] public bool Equals_CompareTwoPolynomialsWithYield(Polynomial.Polynomial pol) { Polynomial.Polynomial pol1 = new Polynomial.Polynomial(1, 2, 3); return pol1.Equals(pol); } #endregion #region ToString public IEnumerable<TestCaseData> TestToStringData { get { yield return new TestCaseData().Returns("1 + 2 x^1 + 3 x^2 = 0"); } } [Test, TestCaseSource(nameof(TestToStringData))] public string ToString_ReturnStringWithYield() { Polynomial.Polynomial pol = new Polynomial.Polynomial(1, 2, 3); return pol.ToString(); } #endregion } }
JavaScript
UTF-8
4,784
3.59375
4
[]
no_license
//task 1 document.writeln("task 1 \n"); var qualifications = ["SSC","HSC","BCS","BS","BCOM","MS", "M. Phil.","PhD"]; document.writeln("<h1>Qualifications: </h1> \n"); for(i=0; i<qualifications.length;i++){ document.writeln(i+1 + ") " + qualifications[i]); } document.writeln(""); //task 2 document.writeln("task 2 \n"); var students = ["Ali", "Haris", "Furqan"]; var scores = [320, 230, 480]; var totalScore = 500; var percentages = [(320/500) *100 , (230/500) *100 , (480/500) * 100]; for(i=0; i< percentages.length; i++){ document.writeln("Score of " + students[i] + " is " + scores[i] + ". Percentage: " + percentages[i] + "%"); } document.writeln(""); //task 3 document.writeln("task 3 \n"); var colors = ["purple", "orange", "magenta"]; document.writeln( "Initial colors list : " + colors + "\n"); colors.unshift(prompt("Enter the color you want to add in the beginning")); document.writeln("After adding the color in the beginning of list : " + colors + "\n"); colors.push(prompt("Enter the color you want to add at the end")); document.writeln("After adding the color at the end of list : " + colors + "\n"); colors.unshift( "pink", "cyan"); document.writeln("After adding two colors in the beginning of list : " + colors + "\n"); colors.shift(); document.writeln("After deleting the color in the beginning of list : " + colors + "\n"); colors.pop(); document.writeln("After deleting the color at the end of list : " + colors + "\n"); var index = parseInt(prompt("Enter the index where you want to insert the color")); var color = prompt("Enter the color you want to add to the specified index"); colors.splice(index, 0 , color); document.writeln("After inserting the " + color + " at "+ index + " of list : " + colors + "\n"); var indexToDelete = parseInt(prompt("Enter the index where you want to start deleting the colors")); var colorsToDelete = prompt("Enter the no. of colors to delete"); colors.splice(indexToDelete, colorsToDelete); document.writeln("After deleting " + colorsToDelete + " elements from "+ indexToDelete + " of list : " + colors + "\n"); // //task 4 document.writeln("task 4 \n"); var cities = ["Karachi", "Lahore" , "Islamabad", "Quetta", "Peshawar"]; var selectedCities = cities.slice(2,5); document.writeln("<h1>Cities list :</h1> \n"); document.writeln(cities + " \n"); document.writeln("<h1>Selected cities list : </h1> \n"); document.writeln(selectedCities + " \n"); //task 5 document.writeln("task 5 \n"); var arr = [3,"a","a","a",2,3,"a",3,"a",2,4,9,30]; var uniqueArray = []; for (var i = 0; i < arr.length; i++){ if (!uniqueArray.includes(arr[i])){ uniqueArray.push(arr[i]); } } document.writeln("Initial array is : " + arr ); document.writeln("After removing repeating elements : " + uniqueArray +"\n" ); //task 6 document.writeln("task 6 \n"); var aCities = ["Karachi", "lahore", "Islamabad","Faisalabad"]; var o = ["th","st","nd","rd"]; for (var i = 0; i < aCities.length - 1 ; i++) { for (var j = 1; j < o.length; j++) { document.writeln(i+1 + o[i+1] + " choice is " + aCities[i]); break; } } document.writeln(""); //task 7 document.writeln("task 7 \n"); var a = [10,20,4,40,60,70]; var b = [1,2,3,4,5,6,7,8,9,10]; var uniqueArray = []; for (var i = 0; i < b.length; i++){ if (!uniqueArray.includes(b[i]) ){ uniqueArray.push(b[i]); } } for (var j = 0; j < a.length; j++){ if (!uniqueArray.includes(a[j]) ){ uniqueArray.push(a[j]); } } document.writeln("a= "+ a); document.writeln("b= "+ b); document.writeln("After merging a & b and removing all duplicates: " + uniqueArray + "\n"); // task 8 document.writeln("task 8"); document.writeln("<h1>Counting</h1>"); for (a =1 ; a<=15; a++){ document.write( a, "," ); } document.writeln("<h1>Reverse</h1>"); for (b=10 ; b>=1; b--){ document.write( b, "," ); } document.writeln("<h1>Even</h1>"); for (c=0 ; c<=20; c++){ if(c%2 ==0){ document.write( c, "," ); } } document.writeln("<h1>Odd</h1>"); for (d=0 ; d<=20; d++){ if(d % 2 ==1){ document.write( d, "," ); } } document.writeln("<h1>Series</h1>"); for (e=1 ; e<=10; e++){ document.write( e*2000, "," ); } document.writeln("\n"); // task 9 document.writeln("task 9"); var array = [24, 53, 78, 91, 12]; var largest= 0; for (i=0; i<=array.length;i++){ if (array[i]>largest) { var largest=array[i]; } } document.writeln("Array items "+array); document.writeln("The largest number is "+largest + "\n"); // task 10 document.writeln("task 10"); var array = [20,53,78,4,91,12]; var A = new Uint32Array([20,53,78,4,91,12]); A = A.sort(); document.writeln("Initial array is A= " + array); document.writeln("After sorting an array A= "+ A);
TypeScript
UTF-8
510
2.515625
3
[]
no_license
input.onButtonPressed(Button.A, function () { direction = 1 }) input.onButtonPressed(Button.AB, function () { direction = 0 servos.P0.stop() }) input.onButtonPressed(Button.B, function () { direction = -1 }) let speed = 0 let direction = 0 direction = 1 basic.forever(function () { if (direction != 0) { for (let indeks = 0; indeks <= 9; indeks++) { speed = indeks * 10 * direction servos.P0.run(speed) basic.showNumber(speed) } } })
Go
UTF-8
753
2.828125
3
[ "BSD-3-Clause" ]
permissive
package tools import ( "encoding/json" "html/template" "io/ioutil" "net/http" "github.com/gin-gonic/gin" "github.com/google/uuid" ) func NewUUID() uuid.UUID { uuid, _ := uuid.NewRandom() return uuid } func Redirect(code int, url string, c *gin.Context) { c.Redirect(code, url) c.Abort() } func CURL(r *http.Request, interfaces interface{}) error { r.Header.Add("Content-Type", "application/json") client := &http.Client{} response, err := client.Do(r) if err != nil { return err } defer response.Body.Close() if body, err := ioutil.ReadAll(response.Body); err == nil { bytes := []byte(body) return json.Unmarshal(bytes, interfaces) } else { return err } } func Unescaped(x string) interface{} { return template.HTML(x) }
Java
UTF-8
981
2.046875
2
[]
no_license
package com.example.ashtech.kilbil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * A simple {@link Fragment} subclass. */ public class ExtendedFragment extends Fragment { private View view; private TextView txtContent; public ExtendedFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_extended, container, false); txtContent= (TextView) view.findViewById(R.id.txt_diary_content_detail); int id = getArguments().getInt("resId"); txtContent.setText(getActivity().getResources().getString(id)); return view; } }
Markdown
UTF-8
3,687
3.359375
3
[ "Apache-2.0" ]
permissive
# 几何参数化 在计算设计中,曲线和曲面经常用作基础脚手架,用于构建后续几何体。为了使早期几何体用作以后几何体的基础,脚本必须能够提取诸如整个对象区域的位置和方向等特性。曲线和曲面均支持此提取,并且称为参数化。 曲线上的所有点可以看作具有从 0 到 1 的唯一参数。如果基于多个控制点或插值点创建 NurbsCurve,则第一个点将具有参数 0,而最后一个点将具有参数 1。不可能提前知道什么是精确参数以及什么是中间点,这听起来像是严重限制,但这可通过一系列实用程序函数来减轻。虽然使用两个参数而不是一个参数(称为 u 和 v),但曲面的参数化与曲线相似。如果我们要使用以下点创建一个曲面: ```js pts = [ [p1, p2, p3], [p4, p5, p6], [p7, p8, p9] ]; ``` p1 将具有参数 u = 0 v = 0,而 p9 将具有参数 u = 1 v = 1。 在确定用于生成曲线的点时,参数化并非特别有用,其主要用途是确定 NurbsCurve 和 NurbsSurface 构造函数生成中间点时的位置。 曲线具有 *PointAtParameter* 方法,该方法采用 0 到 1 之间的单个双精度参数,并返回该参数处的“点”对象。例如,此脚本会在参数 0、.1、.2、.3、.4、.5、.6、.7、.8、.9 和 1 处查找点: ![](images/12-7/GeometricParameterization_01.png) ```js pts = {}; pts[0] = Point.ByCoordinates(4, 0, 0); pts[1] = Point.ByCoordinates(6, 0, 1); pts[2] = Point.ByCoordinates(4, 0, 2); pts[3] = Point.ByCoordinates(4, 0, 3); pts[4] = Point.ByCoordinates(4, 0, 4); pts[5] = Point.ByCoordinates(3, 0, 5); pts[6] = Point.ByCoordinates(4, 0, 6); crv = NurbsCurve.ByPoints(pts); pts_at_param = crv.PointAtParameter(0..1..#11); // draw Lines to help visualize the points lines = Line.ByStartPointEndPoint(pts_at_param, Point.ByCoordinates(4, 6, 0)); ``` 同样,曲面具有 *PointAtParameter* 方法,该方法采用两个参数,即生成点的 u 和 v 参数。 尽管提取曲线和曲面上的各个点非常有用,但脚本通常需要了解参数处的特定几何特征,例如曲线或曲面面对的方向。*CoordinateSystemAtParameter* 方法不仅可以查找位置,还能查找位于曲线或曲面参数处的定向 CoordinateSystem。例如,以下脚本沿旋转曲面提取定向 CoordinateSystems,并使用 CoordinateSystems 的方向生成将法线粘滞到曲面的线: ![](images/12-7/GeometricParameterization_02.png) ```js pts = {}; pts[0] = Point.ByCoordinates(4, 0, 0); pts[1] = Point.ByCoordinates(3, 0, 1); pts[2] = Point.ByCoordinates(4, 0, 2); pts[3] = Point.ByCoordinates(4, 0, 3); pts[4] = Point.ByCoordinates(4, 0, 4); pts[5] = Point.ByCoordinates(5, 0, 5); pts[6] = Point.ByCoordinates(4, 0, 6); pts[7] = Point.ByCoordinates(4, 0, 7); crv = NurbsCurve.ByPoints(pts); axis_origin = Point.ByCoordinates(0, 0, 0); axis = Vector.ByCoordinates(0, 0, 1); surf = Surface.ByRevolve(crv, axis_origin, axis, 90, 140); cs_array = surf.CoordinateSystemAtParameter( (0..1..#7)<1>, (0..1..#7)<2>); def make_line(cs : CoordinateSystem) { lines_start = cs.Origin; lines_end = cs.Origin.Translate(cs.ZAxis, -0.75); return = Line.ByStartPointEndPoint(lines_start, lines_end); } lines = make_line(Flatten(cs_array)); ``` 如前所述,参数化在曲线或曲面的长度上并非始终统一,这意味着参数 0.5 并不始终与中点对应,0.25 并不始终对应于曲线或曲面上的 1/4 点。为了解决此限制,曲线还有一组附加的参数化命令,使您可以沿曲线找到特定长度处的点。
C++
UTF-8
2,348
3.671875
4
[]
no_license
//34. 在排序数组中查找元素的第一个和最后一个位置 //给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 // //如果数组中不存在目标值 target,返回[-1, -1]。 // //进阶: // //你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗? // // //示例 1: // //输入:nums = [5, 7, 7, 8, 8, 10], target = 8 //输出:[3, 4] //示例 2: // //输入:nums = [5, 7, 7, 8, 8, 10], target = 6 //输出:[-1, -1] //示例 3: // //输入:nums = [], target = 0 //输出:[-1, -1] // // //提示: // //0 <= nums.length <= 105 //- 109 <= nums[i] <= 109 //nums 是一个非递减数组 //- 109 <= target <= 109 //来源:力扣(LeetCode) //链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ //著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。// #include<stdio.h> #include<Windows.h> /** * Note: The returned array must be malloced, assume caller calls free(). */ int* searchRange(int* nums, int numsSize, int target, int* returnSize){ int* retarr = (int*)malloc(8); retarr[0] = -1; retarr[1] = -1; *returnSize = 2; //方法一:暴力遍历 // for(int i=0;i<numsSize;i++) // { // if(nums[i]!=target) // { // continue; // } // else if(retarr[0]==-1) // { // retarr[0]=i; // retarr[1]=i; // } // else // { // retarr[1]=i; // } // } // return retarr; //方法二:二分查找出其中一个,然后再分别向前,向后求证 int left = 0, right = numsSize - 1; while (left <= right) { int mid = (left + right) / 2; if (target<nums[mid]) { right = mid - 1; } else if (nums[mid]<target) { left = mid + 1; } else { retarr[0] = mid; retarr[1] = mid; int midcopy = mid; //--------非二分查找--------- while (target == nums[mid]) { retarr[0] = mid; mid--; if (mid == left - 1) { break; } } mid = midcopy; while (target == nums[mid]) { retarr[1] = mid; mid++; if (mid == right + 1) { break; } } //------非二分查找内容-------- //return mid; } } return retarr; }
PHP
UTF-8
8,253
2.515625
3
[]
no_license
<?php namespace app\components; use Yii; use yii\web\Response; /** * Class YandexMerchant * * @property array $paymentTypes * @property string $paymentUrl */ class YandexMerchant extends \yii\base\Component { public $shopId; public $scId; public $shopPassword; public $securityType = 'MD5'; public $modelClass = 'app\models\Order'; public $allowedPaymentTypes = array(); public $demo = false; public $enabled = true; private $action; public function init() { if (empty($this->allowedPaymentTypes)) $this->allowedPaymentTypes = array_keys($this->getPaymentTypes()); } public function getPaymentTypes() { return array( 'PC' => "Оплата из кошелька в Яндекс.Деньгах", 'AC' => "Оплата с произвольной банковской карты", 'MC' => "Платеж со счета мобильного телефона", 'GP' => "Оплата наличными через кассы и терминалы", 'WM' => "Оплата из кошелька в системе WebMoney", 'SB' => "Оплата через Сбербанк Онлайн", 'MP' => "Оплата через мобильный терминал (mPOS)", 'AB' => "Оплата через Альфа-Клик", 'MA' => "Оплата через MasterPass", 'PB' => "Оплата через Промсвязьбанк", 'QW' => "Оплата через QIWI Wallet", 'KV' => "Оплата через КупиВкредит (Тинькофф Банк)", 'QP' => "Оплата через Доверительный платеж («Куппи.ру»)", ); } public function getPaymentUrl() { return 'https://' . ($this->demo ? 'demo' : '') . 'money.yandex.ru/eshop.xml'; } public function getAllowedPaymentTypes() { return array_intersect_key($this->getPaymentTypes(), array_fill_keys($this->allowedPaymentTypes, '')); } /** * @param $name * @return mixed */ public function action($name) { Yii::$app->response->format = Response::FORMAT_RAW; $this->action = isset($this->requestData['action']) ? $this->requestData['action'] : $name; switch ($this->action): case 'index': return Yii::$app->controller->render('//pay/yandex', ['merchant'=>$this, 'model'=>$this->model(Yii::$app->request->get('id'))]); default: return $this->processRequest($this->requestData); endswitch; } /** * Handles "checkOrder" and "paymentAviso" requests. * @param array $request payment parameters */ public function processRequest($request) { Yii::trace("Start " . $this->action); Yii::trace("Security type " . $this->securityType); // if ($this->securityType == "MD5") { Yii::trace("Request: " . print_r($request, true)); // If the MD5 checking fails, respond with "1" error code if (!$this->checkMD5($request)) { $response = $this->buildResponse($this->action, $request['invoiceId'], 1); return $this->sendResponse($response); } /*} else if ($this->securityType == "PKCS7") { // Checking for a certificate sign. If the checking fails, respond with "200" error code. if (($request = $this->verifySign()) == null) { $response = $this->buildResponse($this->action, null, 200); $this->sendResponse($response); } Yii::trace("Request: " . print_r($request, true)); }*/ $response = null; if ($this->action == 'checkOrder') { $response = $this->checkOrder($request); } else { $response = $this->paymentAviso($request); } return $this->sendResponse($response); } /** * Checking the MD5 sign. * @param array $request payment parameters * @return bool true if MD5 hash is correct */ private function checkMD5($request) { $str = $request['action'] . ";" . $request['orderSumAmount'] . ";" . $request['orderSumCurrencyPaycash'] . ";" . $request['orderSumBankPaycash'] . ";" . $request['shopId'] . ";" . $request['invoiceId'] . ";" . $request['customerNumber'] . ";" . $this->shopPassword; Yii::trace("String to md5: " . $str); $md5 = strtoupper(md5($str)); if ($md5 != strtoupper($request['md5'])) { Yii::error("Wait for md5:" . $md5 . ", recieved md5: " . $request['md5']); return false; } return true; } /** * Building XML response. * @param string $functionName "checkOrder" or "paymentAviso" string * @param string $invoiceId transaction number * @param string $result_code result code * @param string $message error message. May be null. * @return string prepared XML response */ private function buildResponse($functionName, $invoiceId, $result_code, $message = null) { if($result_code) Yii::error($message); try { $performedDatetime = date('c'); $response = '<?xml version="1.0" encoding="UTF-8"?><' . $functionName . 'Response performedDatetime="' . $performedDatetime . '" code="' . $result_code . '" ' . ($message != null ? 'message="' . $message . '"' : "") . ' invoiceId="' . $invoiceId . '" shopId="' . $this->shopId . '"/>'; return $response; } catch (\Exception $e) { Yii::error($e); } return null; } public function sendResponse($response) { return $response; } /** * CheckOrder request processing. We suppose there are no item with price less * than 100 rubles in the shop. * @param array $request payment parameters * @return string prepared XML response */ private function checkOrder($request) { $response = null; $model = $this->model($request['orderNumber']); if (!$model) { $response = $this->buildResponse($this->action, $request['invoiceId'], 100, "The order is not fount"); } elseif (!($model instanceof IPayable)) { $response = $this->buildResponse($this->action, $request['invoiceId'], 100, "Order class do not use PayableInterface"); } elseif (!$model->getCanPay()) { $response = $this->buildResponse($this->action, $request['invoiceId'], 100, "Order is not for pay"); } elseif ((float)$model->getTotal() != (float)$request['orderSumAmount']) { $response = $this->buildResponse($this->action, $request['invoiceId'], 100, "The order sum is invalid"); } else { $response = $this->buildResponse($this->action, $request['invoiceId'], 0); } return $response; } public function model($id) { /** @var \ra\admin\models\Order $model */ $model = (new $this->modelClass); /** @var \ra\admin\models\Order|IPayable $model */ $model = $model::findOne($id); return $model; } /** * PaymentAviso request processing. * @param array $request payment parameters * @return string prepared response in XML format */ private function paymentAviso($request) { $model = $this->model($request['orderNumber']); $model->onPay(); return $this->buildResponse($this->action, $request['invoiceId'], 0); } public function getRequestData() { $inputAttributes = ['requestDatetime', 'action', 'md5', 'shopId', 'shopArticleId', 'invoiceId', 'orderNumber', 'customerNumber', 'orderCreatedDatetime', 'orderSumAmount', 'orderSumCurrencyPaycash', 'orderSumBankPaycash', 'paymentPayerCode', 'paymentType',]; $attributes = array(); foreach ($inputAttributes as $attribute) { if (isset($_REQUEST[$attribute])) $attributes[$attribute] = $_REQUEST[$attribute]; } return $attributes; } }
Java
UTF-8
2,425
4.3125
4
[]
no_license
package hard; /* 19.12.2020 * * Convert a Roman numeral to an integer * Assume only positive integer (1 to 3,999) should be entered */ public class RomanToInteger { public static void main(String[] args) { String roman = "MMDCLXXIV"; System.out.println("The value for " + roman + " is " + romanToInt(roman)); } public static int romanToInt(String roman) { int result = 0; int temp = 1000; // check the Roman input string one char by one char for (int i = 0; i < roman.length(); i++) { switch (roman.charAt(i)) { case 'M': // checking the previous value if (temp < 1000) { // DM = 900, we already have D = 500, in front // 900 - 500 = 400 result += 400; // record newly inserted position/value temp = 1000; break; } // if no position/value is inserted in front result += 1000; temp = 1000; break; case 'D': if (temp < 500) { // CD = 400, we already have C = 100 // 400 - 100 = 300 result += 300; temp = 500; break; } // if no position/value is inserted in front result += 500; temp = 500; break; case 'C': if (temp < 100) { // LC = 90, we already have L = 50 // 90 - 50 = 40 result += 40; temp = 100; break; } // if no position/value is inserted in front result += 100; // record newly inserted position/value temp = 100; break; case 'L': if (temp < 50) { // XL = 40, we already have X = 10 // 40 - 10 = 30 result += 30; temp = 50; break; } // if no position/value is inserted in front result += 50; temp = 50; break; case 'X': if (temp < 10) { // XI = 9, we already have I = 1 // 9 - 1 = 8 result += 8; // record newly inserted position/value temp = 10; break; } // if no position/value is inserted in front result += 10; temp = 10; break; case 'V': if (temp < 5) { // IV = 4, we already have I = 1 // 4 - 1 = 3 result += 3; temp = 5; break; } // if no position/value is inserted in front result += 5; temp = 5; break; case 'I': result += 1; // record newly inserted position/value temp = 1; break; } } return result; } }
Java
UTF-8
2,270
3.078125
3
[]
no_license
package com.ldm.basic.bean; import java.io.Serializable; /** * Created by ldm on 12-12-13. * 客户端私有分页Bean */ public class BasicPagerBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; /** * 默认1 */ private int page = 1; /** * 默认15条 */ private int limit = 15; /** * 总跳数 */ private int totalCount = 0; private BasicPagerBean(){ } /** * 实例化一个MPager对象 * @return BasicPagerBean */ public static BasicPagerBean newInstance(){ return new BasicPagerBean(); } /** * 获取第一页数据,当指针需要重新开始时调用该方法(有reset效果) * @return [0]页数, [1]条数 */ public int[] getFirstPage() { return new int[] { page = 1, limit }; } /** * 根据当前MPager的状态继续获取下一页数据 * @return [0]页数, [1]条数 */ public int[] getNextPage() { return new int[] { ++page, limit }; } /** * 获取当前页信息 * @return [0]页数, [1]条数 */ public int[] getNowPage() { return new int[] { page, limit }; } /** * 这个方法返回数组共有三个属性 * @return [0]页数, [1]条数 [2]总页数(如果没有第一次返回0) */ public int[] getNowPageTwo() { return new int[] { page, limit, totalCount }; } /** * 是否存在下一页数据 * @param totalCount 总记录条数 * @return true = 存在 */ public boolean isNextPage(final int totalCount) { return totalCount > page * limit; } /** * 是否存在下一页数据,使用内部总条数计算 * @return true = 存在 */ public boolean isNextPage() { return totalCount > page * limit; } /** * 设置每页多少条 * @param limit 条数 */ public void setLimit(int limit) { this.limit = limit; } /** * 获取每页条数 * @return 条数 */ public int getLimit(){ return limit; } /** * 获取总条数 * @return 条数 */ public int getTotalCount() { return totalCount; } /** * 设置总条数 * @param totalCount n */ public void setTotalCount(int totalCount) { this.totalCount = totalCount; } }
C#
UTF-8
2,154
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using android_test.ActivityElement; using NUnit.Framework; namespace android_test.ActivityRepo { class ArchiveActivity { static string ActivityName = "Flow Archive Activity"; public static AndroidList DeletedList { get { string id = "deletedList"; string name = "Delete List"; return new AndroidList(id, name, ActivityName); } } public static void VerifyFlowInListAtPosition(int row, string flowName) { try { string currFlowName = DeletedList.GetInternalElement().FindElementsById("deletedRow")[row].FindElementById("record_name") .Text; Assert.AreEqual(flowName, currFlowName, String.Format("Current flow name: {0} at position: {1} not equal to expected name: {2}", currFlowName, row, flowName)); ConsoleMessage.Pass(String.Format("{0}. Find flow name: {1} at position: {2}", ActivityName, currFlowName, row)); } catch (Exception ex) { ConsoleMessage.Fail(String.Format("{0}. Can't find flow name: {1} at position: {2}", ActivityName, flowName, row), ex); throw; } } public static void RestoreAtPosition(int row) { try { DeletedList.GetInternalElement().FindElementsById("deletedRow")[row].FindElementById("restore_button") .Click(); ConsoleMessage.Pass(String.Format("{0}. Click restore button on #row: {1}", ActivityName, row)); } catch (Exception ex) { ConsoleMessage.Fail(String.Format("{0}. Can't click restore button on #row: {1}", ActivityName, row), ex); throw; } } } }
C++
UTF-8
1,017
3.734375
4
[]
no_license
#pragma once #include <iostream> #include <string> using namespace std; class Enemy { private: int health; int attack; int defence; string weapon; public: //getters int getEnemyHealth() { return health; } int getEnemyAttack() { return attack; } int getEnemyDefence() { return defence; } string getEnemyWeapon() { return weapon; } Enemy(int, int, int, string); void abilities(){ cout<<"- Execute \n- Charge \n- Reflect "<<endl; } void toEnemyString() { cout << "Health: " << this->getEnemyHealth() << endl; cout << "Attack: " << this->getEnemyAttack() << endl; cout << "Defence: " << this->getEnemyDefence() << endl; cout << "Weapon: " << this->getEnemyWeapon() << endl; } }; // A constructor is called when an object is created Enemy::Enemy(int health, int attack, int defence, string weapon) { // This is used to refer to an object created of this class type this->health = health; this->attack = attack; this->defence = defence; this->weapon = weapon; }
Markdown
UTF-8
21,575
2.515625
3
[ "Apache-2.0" ]
permissive
# 步骤12 探索不同ServiceExpose类型下Pod到Service的通信以及VPCPeering的支持 - [Service expose 类型 官方文档](https://kubernetes.io/docs/tutorials/services/source-ip/) - [External SNAT 官方文档](https://docs.aws.amazon.com/eks/latest/userguide/external-snat.html/) - [AWS-VPC-CNI 插件官方文档](https://github.com/aws/amazon-vpc-cni-k8s) > 本节目的 1. 探索 Service expose 类型 ClusterIP, NodePort, LoadBalancer 访问的source ip 2. 学习EKS集群如何进行VPC Peering (类似方法同样适用于通过Direct Connect连接数据中心或者其他AWS Region) # 12.1 创建 Worker Node 在Private Subnet的集群 复用已经创建的VPC (172.16.0.0/16),创建Worker Node 位于Private Subnet的集群 注意:如果要创建面向公网的ELB,则群集中必须具有私有子网和公用子网。 如果只有私有子网,则必须通过注释声明您的 ELB 是内部的:service.beta.kubernetes.io/aws-load-balancer-internal: "true" 。 否则,您将遇到错误: CreatingLoadBalancerFailed service/{Service_NAME} Error creating load balancer (will retry): failed to ensure load balancer for service {Service_NAME}: could not find any suitable subnets for creating the ELB [参考eksctl文档](https://eksctl.io/usage/vpc-networking/) ## 创建集群 ```bash # 参考 resource/private-cluster.yaml, 修改subnets eksctl create cluster -f resource/private-cluster.yaml # 多个EKS集群进行上下文切换, 确保位于gcr-eksworkshop-private kubectl config get-contexts kubectl config use-context <YOUR_TARGET_CONTEXT> # 集群创建完毕后,查看EKS集群工作节点,由于位于 Private Subent 未分配EXTERNAL-IP kubectl get nodes -o jsonpath='{range .items[*]}{"NAME: "}{@.metadata.name}{" INTERNAL-IP: "}{@.status.addresses[?(@.type=="InternalIP")].address}{" EXTERNAL-IP: "}{@.status.addresses[?(@.type=="ExternalIP")].address}{"\n"}{end}' # 输出 NAME: ip-172-16-150-17.cn-northwest-1.compute.internal INTERNAL-IP: 172.16.150.17 EXTERNAL-IP: NAME: ip-172-16-167-227.cn-northwest-1.compute.internal INTERNAL-IP: 172.16.167.227 EXTERNAL-IP: NAME: ip-172-16-212-54.cn-northwest-1.compute.internal INTERNAL-IP: 172.16.212.54 EXTERNAL-IP: # 部署测试 nginx, pod 位于私有子网, Service 暴露为 Type=LoadBalancer,位于公有子网 kubectl apply -f resource/nginx-app/nginx-nlb.yaml ## Check deployment status kubectl get pods ## Get the external access 确保 EXTERNAL-IP是一个有效的AWS Network Load Balancer的地址 NLB=$(kubectl get service service-nginx -o json | jq -r '.status.loadBalancer.ingress[].hostname') curl -m3 -v $NLB ## 清理 kubectl delete -f resource/nginx-app/nginx-nlb.yaml ``` # 12.2 探索 不同 Service Type 情况下 Pod 到 Service 访问的连通性和源IP 1. 部署示例应用程序,程序回显接收到请求的源IP ```bash kubectl create deployment source-ip-app --image=k8s.gcr.io/echoserver:1.4 SOURCE_IP_APP=$(kubectl get pods | egrep -o "source-ip-app[a-zA-Z0-9-]+") kubectl get pod ${SOURCE_IP_APP} -o json | jq -r '.status | "HOST IP: " + .hostIP + " , POD IP: " + .podIP' # 样例输出为 HOST IP: 172.16.150.17 , POD IP: 172.16.131.88 # 设置变量 SOURCE_IP_APP_HOSTIP=172.16.150.17 SOURCE_IP_APP_PODIP=172.16.131.88 ``` 2. 在同一个 EKS 集群启动一个 busybox 容器,测试 Pod 到 Pod 私有地址访问 ```bash # 检查看是否存在一个 busybox 容器 BUSY_BOX=$(kubectl get pods | egrep -o "busybox[a-zA-Z0-9-]+") echo ${BUSY_BOX} # 如果 ${BUSY_BOX} 不为空,进入已有的 busybox 容器的交互式模式 kubectl attach ${BUSY_BOX} -c busybox -it # 如果 ${BUSY_BOX} 为空,重新创建一个 busybox kubectl run busybox -it --image=busybox -- /bin/sh # 在另一个命令行窗口获取 busybox 的 IP 地址 kubectl get pod ${BUSY_BOX} -o json | jq -r '.status | "HOST IP: " + .hostIP + " , POD IP: " + .podIP' # 样例输出为 HOST IP: 172.16.212.54 , POD IP: 172.16.205.58 # 设置变量 BUSY_BOX_HOSTIP=172.16.212.54 BUSY_BOX_PODIP=172.16.205.58 ``` ## 12.2.1 Client Pod 到 Service 私有地址访问 ### 发布服务为 Type=ClusterIP ![pod2pod-ClusterIP.png](media/pod2pod-ClusterIP.png) 1. 为 source-ip-app 发布一个 Type=ClusterIP 的服务 ```bash kubectl expose deployment source-ip-app --name=clusterip --port=80 --target-port=8080 TestClusterIP=$(kubectl get svc clusterip -o json | jq -r '.spec.clusterIP') echo ${TestClusterIP} ``` 2. 进入 busybox 访问 source-ip-app 发现 source-ip-app 输出 - client_address={BUSY_BOX_PODIP} - request_uri=http://{SOURCE_IP_APP_PODIP}:8080/ - host={SOURCE_IP_APP_PODIP}:8080 ```bash # 直接访问 source-ip-app Pod,替换 {SOURCE_IP_APP_PODIP} 为之前的变量 SOURCE_IP_APP_PODIP wget -qO - {SOURCE_IP_APP_PODIP}:8080 | egrep -i 'client_address|host|request_uri' ``` 3. 进入 busybox 访问 source-ip-app 暴露的服务, 发现 source-ip-app 输出 - client_address={BUSY_BOX_PODIP} - request_uri=http://{TestClusterIP}:8080/ - host={TestClusterIP} ```bash # 访问source-ip-app 暴露的服务,替换 {TestClusterIP} 为之前的变量 TestClusterIP wget -qO - {TestClusterIP} | egrep -i 'client_address|host|request_uri' ``` ### 发布服务为 Type=NodePort ![pod2pod-NodePort.png](media/pod2pod-NodePort.png) 1. 发布服务为 Type=NodePort, 设置 Pod 所在的 Node 的安全组的入站规则允许 {NodePort} 访问 ```bash kubectl expose deployment source-ip-app --name=nodeport --port=80 --target-port=8080 --type=NodePort # 获取 Node IP and Node Port, 设置安全组入站规则 NODEPORT=$(kubectl get -o jsonpath="{.spec.ports[0].nodePort}" services nodeport) echo ${NODEPORT} NODES_INTERNAL_IP=$(kubectl get nodes -o jsonpath='{ $.items[*].status.addresses[?(@.type=="InternalIP")].address }') echo ${NODES_INTERNAL_IP} VPC_ID=$(aws eks describe-cluster --name ${CLUSTER_NAME} --region ${AWS_REGION} --query "cluster.resourcesVpcConfig.vpcId" --output text) VPC_CIDR=$(aws ec2 describe-vpcs --vpc-ids ${VPC_ID} --query "Vpcs[].CidrBlock" --region ${AWS_REGION} --output text) STACK_NAME=$(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region=${AWS_REGION} -o json | jq -r '.[].StackName') SGGroupID=$(aws ec2 describe-security-groups --filters Name=tag:Name,Values=${STACK_NAME}\* Name=tag:aws:cloudformation:stack-name,Values=${STACK_NAME} --query "SecurityGroups[*].{SGGroupID:GroupId}" --region=${AWS_REGION} --output text) aws ec2 authorize-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port ${NODEPORT} --cidr ${VPC_CIDR} --region=${AWS_REGION} ``` 2. 进入 busybox 访问 source-ip-app 发现 source-ip-app 输出 - client_address={NodeIP} - request_uri=http://{NodeIP}:8080/ - host={NodeIP}:{NODEPORT} ```bash # 访问 source-ip-app Type=NodePort 的服务, 替换 {NODES_INTERNAL_IP} 为之前的变量 NODES_INTERNAL_IP 数组 以及 {NODEPORT} 为之前的变量 NODEPORT for node in {NODES_INTERNAL_IP}; do wget -qO - $node:{NODEPORT} | egrep -i 'client_address|host|request_uri'; done # 示例: for node in 172.16.150.17 172.16.167.227 172.16.212.54; do wget -qO - $node:32227 | egrep -i 'client_address|host|request_uri'; done ``` 3. 测试完毕,取消安全组入站规则 ```bash aws ec2 revoke-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port ${NODEPORT} --cidr ${VPC_CIDR} --region=${AWS_REGION} ``` ### 发布服务为 Type=LoadBalancer ![pod2pod-LoadBalancer.png](media/pod2pod-LoadBalancer.png) 1. 发布服务为 Type=LoadBalancer ```bash kubectl expose deployment source-ip-app --name=loadbalancer --port=80 --target-port=8080 --type=LoadBalancer SOURCE_IP_ELB=$(kubectl get service loadbalancer -o json | jq -r '.status.loadBalancer.ingress[].hostname') echo ${SOURCE_IP_ELB} ``` 2. 进入 busybox 访问 source-ip-app 访问 source-ip-app 输出: - client_address={NODES_INTERNAL_IP} 数组 - request_uri=http://{SOURCE_IP_ELB}:8080/ - host={SOURCE_IP_ELB} ```bash # 访问 source-ip-app Type=LoadBalancer 的服务, 替换 {SOURCE_IP_ELB} 为之前的变量 SOURCE_IP_ELB wget -qO - <SOURCE_IP_ELB> | egrep -i 'client_address|host|request_uri' ``` ### 发布服务为 内部 AWS NLB ![pod2pod-LoadBalancer-Internal-NLB](media/pod2pod-LoadBalancer-Internal-NLB.png) 1. 发布服务为 内部 AWS NLB ```bash kubectl apply -f resource/pod2service/source-ip-app-internal-nlb.yaml INTERNAL_NLB=$(kubectl get service source-ip-app-internal-nlb -o json | jq -r '.status.loadBalancer.ingress[].hostname') echo ${INTERNAL_NLB} ``` 2. 进入 busybox 访问 source-ip-app 访问 source-ip-app 输出: - client_address={NODES_INTERNAL_IP} 数组 - request_uri=http://{INTERNAL_NLB}:8080/ - host={INTERNAL_NLB} ```bash # 访问 source-ip-app Type=LoadBalancer 的服务, 替换 {INTERNAL_NLB} 为之前的变量 INTERNAL_NLB wget -qO - <INTERNAL_NLB> | egrep -i 'client_address|host|request_uri' ``` # 12.3 探索 不同 Service Type 情况下 Pod 与 VPC Peering 的对端节点互访 ## 12.3.1 Pod 访问 VPC Peering 对端 EC2 节点 ### 准备活动 1. 本实验创建的 EKS 集群 gcr-eksworkshop-private 所在 VPC1 (172.16.0.0/16),VPC Peering 的对方 VPC2 (192.168.0.0/16) 2. 创建好 VPC1 (172.16.0.0/16) 与 VPC2 (192.168.0.0/16) 的 VPC Peering 以及 配置好子网的路由表。[VPC Peering 官方文档](https://docs.aws.amazon.com/vpc/latest/peering/working-with-vpc-peering.html) 3. 在 VPC2 (192.168.0.0/16) 中启动一台 运行 Amazon Linux 2 的 EC2,并且运行一个简单的web 程序 ```bash sudo yum -y install httpd sudo mkdir -p /var/www/html/ hostname=$(curl http://169.254.169.254/latest/meta-data/hostname) sudo sh -c "echo '<html><h1>Hello From Your Web Server on ${hostname}</h1></html>' > /var/www/html/index.html" sudo chkconfig httpd on sudo systemctl start httpd ``` 5. 在 VPC2 (192.168.0.0/16) 中 同时运行着 EKS 集群 gcr-zhy-eksworkshop ### 在 VPC1 (172.16.0.0/16) 的 EKS 集群 gcr-eksworkshop-private 的 busybox 访问 VPC2 (192.168.0.0/16) 的 EC2 的 web 服务 ![VPCPeering-Pod-EC2.png](media/VPCPeering-Pod-EC2.png) 进入 busybox 访问 EC2 的 web 服务,**可以访问成功** ```bash # 访问 EC2 公网IP,可以正确输出响应 / # wget -qO - <EC2_PUBLIC_IP> # 访问 EC2 私网IP,可以正确输出响应 / # wget -qO - <EC2_PRIVATE_IP> ``` ## 12.3.2 VPC Peering 对端 EC2 节点访问 Pod 1. 设置安全组入站规则允许 VPC Peering 对端 EC2 访问 {NODEPORT}, 80, 8080, 443 端口 ```bash # Service Type=NodePort NODEPORT=$(kubectl get -o jsonpath="{.spec.ports[0].nodePort}" services nodeport) echo ${NODEPORT} PEERING_VPC_CIDR=192.168.0.0/16 STACK_NAME=$(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region=${AWS_REGION} -o json | jq -r '.[].StackName') SGGroupID=$(aws ec2 describe-security-groups --filters Name=tag:Name,Values=${STACK_NAME}\* Name=tag:aws:cloudformation:stack-name,Values=${STACK_NAME} --query "SecurityGroups[*].{SGGroupID:GroupId}" --region=${AWS_REGION} --output text) aws ec2 authorize-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port ${NODEPORT} --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} aws ec2 authorize-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port 80 --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} aws ec2 authorize-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port 8080 --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} aws ec2 authorize-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port 443 --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} ``` 2. 登录 VPC2 (192.168.0.0/16) 中一台EC2,访问 12.2.1 创建的 Type=ClusterIP 服务,验证能否访问成功 ```bash # 直接访问 source-ip-app Pod,替换 {SOURCE_IP_APP_PODIP} 为之前的变量 SOURCE_IP_APP_PODIP wget -qO - {SOURCE_IP_APP_PODIP}:8080 | egrep -i 'client_address|host|request_uri' 输出: - client_address={EC2_IP} - request_uri=http://{SOURCE_IP_APP_PODIP}:8080/ - host={SOURCE_IP_APP_PODIP}:8080 # 访问source-ip-app 暴露的服务,替换 {TestClusterIP} 为之前的变量 TestClusterIP wget -qO - {TestClusterIP} | egrep -i 'client_address|host|request_uri' 输出: 网络不通, ClusterIP 仅为Cluster内部通信 ``` 3. 登录 VPC2 (192.168.0.0/16) 中一台EC2,访问 12.2.1 创建的 Type=NodePort 服务,验证访问成功 ```bash # 访问 source-ip-app Type=NodePort 的服务, 替换 {NODES_INTERNAL_IP} 为之前的变量 NODES_INTERNAL_IP 数组 以及 {NODEPORT} 为之前的变量 NODEPORT for node in {NODES_INTERNAL_IP}; do wget -qO - $node:{NODEPORT} | egrep -i 'client_address|host|request_uri'; done 输出: client_address={node} request_uri=http://{node}:8080/ host={node}:{NODEPORT} ``` 4. 登录 VPC2 (192.168.0.0/16) 中一台EC2,访问 12.2.1 创建的 Type=LoadBalancer 服务,验证能否访问成功 ```bash # 访问 source-ip-app Type=LoadBalancer 的服务, 替换 {SOURCE_IP_ELB} 为之前的变量 SOURCE_IP_ELB wget -qO - {SOURCE_IP_ELB} | egrep -i 'client_address|host|request_uri' 输出: client_address={EC2_IP} request_uri=http://{SOURCE_IP_ELB}:8080/ host={SOURCE_IP_ELB} # 访问 source-ip-app Type=LoadBalancer 的服务, 替换 {INTERNAL_NLB} 为之前的变量 INTERNAL_NLB wget -qO - {INTERNAL_NLB} | egrep -i 'client_address|host|request_uri' 输出: client_address={EC2_IP} request_uri=http://{INTERNAL_NLB}:8080/ host={INTERNAL_NLB} ``` ## 12.3.3 VPC Peering 对端 EKS cluster Pod 节点访问 本地 EKS cluster Pod 1. 在 VPC2 (192.168.0.0/16) 中的 EKS 集群 gcr-zhy-eksworkshop 启动一个 busybox ```bash # 创建一个 busybox kubectl run busybox -it --image=busybox -- /bin/sh # 在另一个命令行窗口获取 busybox 的 IP 地址 BUSY_BOX=$(kubectl get pods | egrep -o "busybox[a-zA-Z0-9-]+") kubectl get pod ${BUSY_BOX} -o json | jq -r '.status | "HOST IP: " + .hostIP + " , POD IP: " + .podIP' # 样例输出为 HOST IP: 192.168.40.132 , POD IP: 192.168.54.243 # 设置变量 BUSY_BOX_HOSTIP=192.168.40.132 BUSY_BOX_PODIP=192.168.54.243 ``` 2. 在 VPC2 (192.168.0.0/16) busybox 访问 12.2.1 创建的 Type=ClusterIP 服务,验证能否访问成功 ```bash # 直接访问 source-ip-app Pod,替换 {SOURCE_IP_APP_PODIP} 为之前的变量 SOURCE_IP_APP_PODIP wget -qO - {SOURCE_IP_APP_PODIP}:8080 | egrep -i 'client_address|host|request_uri' 输出: - client_address={BUSY_BOX_HOSTIP} - request_uri=http://{SOURCE_IP_APP_PODIP}:8080/ - host={SOURCE_IP_APP_PODIP}:8080 # 访问source-ip-app 暴露的服务,替换 {TestClusterIP} 为之前的变量 TestClusterIP wget -qO - {TestClusterIP} | egrep -i 'client_address|host|request_uri' 输出: 网络不通, ClusterIP 仅为Cluster内部通信 ``` 3. 在 VPC2 (192.168.0.0/16) busybox 访问 12.2.1 创建的 Type=NodePort 服务,验证访问成功 ```bash # 访问 source-ip-app Type=NodePort 的服务, 替换 {NODES_INTERNAL_IP} 为之前的变量 NODES_INTERNAL_IP 数组 以及 {NODEPORT} 为之前的变量 NODEPORT for node in {NODES_INTERNAL_IP}; do wget -qO - $node:{NODEPORT} | egrep -i 'client_address|host|request_uri'; done 输出: client_address={node} request_uri=http://{node}:8080/ host={node}:{NODEPORT} ``` 4. 在 VPC2 (192.168.0.0/16) busybox 访问 12.2.1 创建的 Type=LoadBalancer 服务,验证能否访问成功 ```bash # 访问 source-ip-app Type=LoadBalancer 的服务, 替换 {SOURCE_IP_ELB} 为之前的变量 SOURCE_IP_ELB wget -qO - {SOURCE_IP_ELB} | egrep -i 'client_address|host|request_uri' 输出: client_address={BUSY_BOX_HOSTIP} request_uri=http://{SOURCE_IP_ELB}:8080/ host={SOURCE_IP_ELB} # 访问 source-ip-app Type=LoadBalancer 的服务, 替换 {INTERNAL_NLB} 为之前的变量 INTERNAL_NLB wget -qO - {INTERNAL_NLB} | egrep -i 'client_address|host|request_uri' 输出: client_address={BUSY_BOX_HOSTIP} request_uri=http://{INTERNAL_NLB}:8080/ host={INTERNAL_NLB} ``` # 12.4 headless-services 服务 与 VPC Peering 的对端节点互访 [headless-services 官方文档](https://kubernetes.io/docs/concepts/services-networking/service/) 1. 在 VPC1 (172.16.0.0/16) 的 EKS 集群中 为source-ip-app 部署一个 headless-services ```bash kubectl expose deployment source-ip-app --name source-ip-app-headless --cluster-ip=None #kubectl apply -f resource/pod2service/source-ip-app-headless-service.yaml kubectl get svc -l app=source-ip-app NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE clusterip ClusterIP 10.100.93.33 <none> 80/TCP 15h loadbalancer LoadBalancer 10.100.254.8 a068ae19572a411eaa5bc0668f12362a-514105420.cn-northwest-1.elb.amazonaws.com.cn 80:32497/TCP 13h nodeport NodePort 10.100.14.156 <none> 80:32227/TCP 15h source-ip-app-headless ClusterIP None <none> <none> 3s ``` 2. 在 VPC1 (172.16.0.0/16) 的 busybox 中获取该 source-ip-app-headless 对应的IP 发现 nslookup source-ip-app-headless 返回 source-ip-app Pods IP ```bash nslookup source-ip-app-headless Server: 10.100.0.10 Address: 10.100.0.10:53 Name: source-ip-app-headless.default.svc.cluster.local Address: 172.16.131.88 wget -qO - source-ip-app-headless:8080 | egrep -i 'client_address|host|request_uri' # 返回 client_address={BUSY_BOX_HOSTIP} request_uri=http://source-ip-app-headless:8080/ host=source-ip-app-headless:8080 ``` 3. 在 VPC2 (192.168.0.0/16) busybox 中 访问 source-ip-app-headless 服务 请将 {source-ip-app-headless} 替换为对应的IP ```bash wget -qO - {source-ip-app-headless}:8080 | egrep -i 'client_address|host|request_uri' # 返回 client_address={BUSY_BOX_HOSTIP} request_uri=http://{source-ip-app-headless}:8080/ host={source-ip-app-headless}:8080 ``` # 12.5 取消安全组入站规则 ```bash aws ec2 revoke-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port ${NODEPORT} --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} aws ec2 revoke-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port 80 --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} aws ec2 revoke-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port 8080 --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} aws ec2 revoke-security-group-ingress --group-id ${SGGroupID} --protocol tcp --port 443 --cidr ${PEERING_VPC_CIDR} --region=${AWS_REGION} ``` # 12.6 如何利用 amazon-vpc-cni-k8s 支持 VPC Peering 在自建 k8s 集群,可能存在 如何解决 12.4 中 headless-services 访问不通的问题 ## SNAT 原理 VPC中的通信(例如 Pod 到 Pod )直接在私有 IP 地址之间进行,不需要 SNAT。 当流量发往 VPC 之外的地址时,Amazon VPC CNI Kubernetes 网络插件会将每个 Pod 的私有 IP 地址转换为一个 primary 私有 IP 地址。该地址默认情况下分配给该 Pod 所在的 Worker Node 的 EC2 主弹性网络接口(Primary ENI)。 SNAT的主要作用: 1. 使Pod可以与Internet双向通信。 Worker Node 必须位于公共子网中,并且已向其 Primary ENI 的 primary 私有 IP 地址分配一个公有或弹性 IP 地址。SNAT 是必需的,因为 Internet 网关只知道如何在 primary private IP与公有或弹性 IP 地址之间进行转换(这些地址已分配给 Pod 所在的 Worker Node 的 EC2 primary ENI 2. 防止其他私有IP地址空间,例如VPC Peering,Transit VPC或Direct Connect直接与如下Pod通信: 未向此 Pod 分配 EC2 Worker Node的 primary ENI 的 primary private IP。 地址转换如图所示: ![SNAT-enabled](media/SNAT-enabled.jpg) 那么如果Pod需要与其他私有IP地址空间(例如VPC Peering,Transit VPC或Direct Connect)中的设备通信,那么: 1. Worker Node必须部署在私有子网中,该私有子网具有到公用子网中NAT设备或者NAT网关的路由。 2. 需要在VPC CNI插件 aws-node DaemonSet中启用外部SNAT 启用外部SNAT后,当流量发送的目标为 VPC 外部地址时,CNI插件不会将Pod的 private IP地址转换为 primary private IP 此地址分配给 Pod 正在其上运行的 EC2 Worker Node的 primary ENI)。在VPC之外。从Pod到Internet的流量在外部与NAT设备的公共IP地址进行双向转换,并通过Internet网关路由到Internet和从Internet路由,如下图所示。 ![SNAT-disabled](media/SNAT-disabled.jpg) ## 利用amazon-vpc-cni-k8s的环境变量,实现VPC Peering 1. 方法1:AWS_VPC_K8S_CNI_EXTERNALSNAT [AWS-VPC-CNI 插件官方文档](https://github.com/aws/amazon-vpc-cni-k8s) 指定是否需要外部 NAT gateway 提供 SNAT ```bash kubectl set env daemonset -n kube-system aws-node AWS_VPC_K8S_CNI_EXTERNALSNAT=true ``` 2. 方法2: AWS_VPC_K8S_CNI_EXCLUDE_SNAT_CIDRS (Since v1.6.0) [AWS_VPC_K8S_CNI_EXCLUDE_SNAT_CIDRS发布说明](https://aws.amazon.com/cn/about-aws/whats-new/2020/02/amazon-eks-announces-release-of-vpc-cni-version-1-6/) [AWS-VPC-CNI 插件官方文档](https://github.com/aws/amazon-vpc-cni-k8s) 指定一个逗号分隔的IPv4 CIDR列表,以将其排除在 CNI 插件的 SNAT 外。 使用该环境变量时,需要设置 AWS_VPC_K8S_CNI_EXTERNALSNAT=false. # 12.3. cleanup ```bash 1. 终止 VPC2 的 EC2 2. 清除 VPC Peering 4. kubectl delete svc -l app=source-ip-app 5. kubectl delete deployment source-ip-app 6. kubectl delete deployment busybox 7. eksctl delete cluster -f resource/private-cluster.yaml ```
Java
UTF-8
1,100
3.640625
4
[]
no_license
package level2; public class Valid_Palindrome { public static void main(String[] args) { System.out.println(isPalindrome2("1a2")); } public static boolean isPalindrome(String s) { if (s.isEmpty()) return true; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c >= '0' && c <= '9') { sb.append(s.charAt(i)); } } String str = sb.toString().toLowerCase(); int len = str.length(); for (int i = 0, j = len - 1; i <= j; i++, j--) { if (str.charAt(i) != str.charAt(j)) { return false; } } return true; } public static boolean isPalindrome2(String s) {//Accepted if (s.isEmpty()) return true; String str = s.toLowerCase(); for (int i = 0, j = str.length() - 1; i < j;i++,j--) { while (i<j&&!Character.isLetterOrDigit(str.charAt(i))) i++; while (i<j&&!Character.isLetterOrDigit(str.charAt(j))) j--; if (str.charAt(i) != str.charAt(j)) return false; } return true; } }
Java
UTF-8
376
2.09375
2
[ "MIT" ]
permissive
package com.knifed.makemefat.daos; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import com.knifed.makemefat.entities.Sleep; import com.knifed.makemefat.entities.Water; import java.util.List; @Dao public interface SleepDao { @Query("SELECT * FROM sleep") List<Sleep> getAll(); @Insert void insertSleep(Sleep sleep); }
C#
UTF-8
2,524
2.8125
3
[ "MIT" ]
permissive
using System.IO; using Xunit; using Xunit.Abstractions; namespace AdventOfCode.Tests { public class Day10Tests { private readonly ITestOutputHelper output; private readonly Day10 solver; public Day10Tests(ITestOutputHelper output) { this.output = output; this.solver = new Day10(); } private static string[] GetRealInput() { string[] input = File.ReadAllLines("inputs/day10.txt"); return input; } private static string[] GetSampleInput() { return new string[] { ".#..##.###...#######", "##.############..##.", ".#.######.########.#", ".###.#######.####.#.", "#####.##.#.##.###.##", "..#####..#.#########", "####################", "#.####....###.#.#.##", "##.#################", "#####.##.###..####..", "..######..##.#######", "####.##.####...##..#", ".#####..#.######.###", "##...#.##########...", "#.##########.#######", ".####.#.###.###.#.##", "....##.##.###..#####", ".#.#.###########.###", "#.#.#.#####.####.###", "###.##.####.##.#..##", }; } [Fact] public void Part1_SampleInput_ProducesCorrectResponse() { var expected = 210; var result = solver.Part1(GetSampleInput()); Assert.Equal(expected, result); } [Fact] public void Part1_RealInput_ProducesCorrectResponse() { var expected = 280; var result = solver.Part1(GetRealInput()); output.WriteLine($"Day 10 - Part 1 - {result}"); Assert.Equal(expected, result); } [Fact] public void Part2_SampleInput_ProducesCorrectResponse() { var expected = 802; var result = solver.Part2(GetSampleInput(), 11, 13); Assert.Equal(expected, result); } [Fact] public void Part2_RealInput_ProducesCorrectResponse() { var expected = 706; var result = solver.Part2(GetRealInput()); output.WriteLine($"Day 10 - Part 2 - {result}"); Assert.Equal(expected, result); } } }