language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
2,928
2.515625
3
[ "CC-BY-3.0" ]
permissive
import { onFrame } from './init.js'; const gamepad = { stick: { x: 0, y: 0 }, camStick: { x: 0, y: 0 }, accelerate: false, brake: false, fire: false }; const heldKeys = new Set(); window.addEventListener('keydown', e => heldKeys.add(e.key.toUpperCase())); window.addEventListener('keyup', e => heldKeys.delete(e.key.toUpperCase())); window.addEventListener('keypress', e => e.preventDefault()); const touches = new Map(), touchControls = { left: false, right: false, gas: false, brake: false }, touchEls = []; document.addEventListener('DOMContentLoaded', e => { const c = document.getElementById('touch-controls'); touchEls.push(document.getElementById('left')); touchEls.push(document.getElementById('right')); touchEls.push(document.getElementById('gas')); touchEls.push(document.getElementById('brake')); c.addEventListener('touchstart', updateTouch); c.addEventListener('touchmove', updateTouch); c.addEventListener('touchend', endTouch); c.addEventListener('touchcancel', endTouch); function updateTouch(e) { for (const t of e.changedTouches) touches.set(t.identifier, t); updateTouchControls(); } function endTouch(e) { for (const t of e.changedTouches) touches.delete(t.identifier); updateTouchControls(); } }); function updateTouchControls() { touchControls.left = false; touchControls.right = false; touchControls.gas = false; touchControls.brake = false; for (const el of touchEls) el.classList.remove('active'); for (const t of touches.values()) { console.log(t) const el = document.elementFromPoint(t.pageX, t.pageY); console.log(el) if (el && touchControls.hasOwnProperty(el.id)) { touchControls[el.id] = true; el.classList.add('active'); } } } let inputs = null; window.addEventListener('gamepadconnected', e => { console.log(e.gamepad.id, 'connected'); if (!inputs) inputs = e.gamepad; }); onFrame(update); const dummyPad = { axes: [0, 0, 0, 0], buttons: [ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} ] }; function update() { const i = inputs ? navigator.getGamepads()[inputs.index] : dummyPad; gamepad.stick.x = (heldKeys.has('A') || touchControls.left) ? -1 : (heldKeys.has('D') || touchControls.right) ? 1 : deadZone(i.axes[0]); // -ve is left here gamepad.stick.y = deadZone(i.axes[1]); // -ve is up here gamepad.camStick.x = deadZone(i.axes[2]); // -ve is left here gamepad.camStick.y = deadZone(i.axes[3]); // -ve is up here gamepad.accelerate = i.buttons[0].pressed || heldKeys.has('SHIFT') || touchControls.gas; gamepad.brake = i.buttons[1].pressed || heldKeys.has('S') || touchControls.brake; gamepad.fire = i.buttons[2].pressed || heldKeys.has(' '); gamepad.y = i.buttons[3].pressed; gamepad.start = i.buttons[9].pressed || i.buttons[0].pressed || heldKeys.has(' ') || touchControls.gas; gamepad.raw = i; } function deadZone(n) { return (Math.abs(n) < 0.05) ? 0 : n; } export default gamepad;
Markdown
UTF-8
4,609
2.9375
3
[]
no_license
16061121 2019年春季 北航《计算机科学前沿讲座》 挑战 ========== # 问题1 >3.1 在一个游戏中,主办方在三个门中任选一个,在门后放了一个奖品,另外两个门之后是空的。选手要在三个门中选择一个抽奖。 当选手选择了一个门,未曾打开门之前,主办方打开了另外两个门中没有奖品的那个门,并向选手说, 他可以改变他的选择,即转为选择剩下一个没有打开的门。 请问,如果选手此时改变选择, 他会提高或降低获奖的可能性么?提高多少?请给出你的分析。 会提高中奖的可能性。原来的中奖概率为1/3,现在转变为2/3,所以中奖概率提高了1/3。 如果没有主办方为选手打开门,选手的中奖概率为1/3。而主办方为选手打开一扇没有奖品的门时,选手的选择只有剩下的两扇门,选手中奖概率为: - 如果选手一开始选的门是有奖的,概率为1/3,在主持人关闭一扇无奖的门后,他不改变选择中奖率为1,改变的中奖率为0 - 如果选手一开始选的门是无奖的,概率为2/3,在主持人关闭一扇无奖的门后,他不改变选择中奖率为0,改变的中奖率为1 - 因此改变选择的中奖率为1/3\*0+2/3\*1=2/3 - 所以选手此时改变选择,他会提高中奖的可能性,由原来的1/3提高到2/3,提高了1/3 # 问题2 >3.2 如何看待 “中文房间” 问题,中文房间有智能么?它有什么样水平的智能?如何才能让它具有人类水平的智能? 我认为中文房间没有智能。 中文房间中的规则书只是罗列了一切可能的中文问题,并给出了相应的中文回答,房间中的人,只是按照规则对应相应的回答,拼凑出相应的中文字符传递出去。这一过程是基于语法的,没有语义的理解和联想,更没有联系上下文的能力,所以我认为中文房间可以完成字符串的转换,但是没有智能。 人类是靠着理解各种事物中建立的错综复杂的联系,而理解就是联想,联想来自各种条件发射。要让中文房间具有人类水平的智能,我认为需要: - 扩充语料库,将日常的交际场景中的语料加入到训练样本中,让中文房间能够理解上下文,根据语境做出正确的反应。 - 以神经网络程序的基因算法为基础,建立与生物建立条件反射的过程基本相同的学习过程,赋予计算机联想解决问题的能力,我们就可以说机器理解了知识,具有人类水平的智能。 # 问题3 >3.3 既然这门课讲了很多计算机前沿,那么学生就可以预计一下这些前沿知识如何能给普通用户或某个行业带来好处。 学生根据讲课的内容和参考文献,用 NABCD 的模板,描述你心目中一个使用了 “人工智能+其他前沿技术” 的创新项目。 这个项目应该是由 7 - 10 名有相关技能的大学生在 4 个月能完成。 - Need: - 大型配电网产值巨大,对工农业的正常运行有着重要的支撑作用 - 而配电网中的变压器是十分重要并且昂贵的设备 - 如果配电不正确,很有可能对变压器造成伤害,并且影响工农业的正常运行。 - Approach: - 变压器中通常会安装测温变压器来监控变压器的油温变化,对油温进行微分方程建模,结合热力学模型我们可以根据油温得到变压器的负载状况 - 使用时序预测模型,连接到电网的变压器中的测温传感器,以历史的油温、功率、天气和地理文职信息,预测之后的一天变压器的油温变化,从而得到变压器的负载变化 - 将模型和数据预处理封装,结合易操作的可视化平台,使得工厂能够通过简单的操作就能直观地看到油温和负载变化 - Benefit: - 配电网根据我们提供的预测信息,可以调整之后的配电计划,如果发现之后变压器可能过载,就可以相应的减少负载,如果发现变压器配电冗余,可以适当的平衡负载来增大的经济效益 - 简洁易操作的网站平台,可以使工厂工人不需要任何的相关知识就可以看到预测的油温和负载变化 - Competitors: - 目前也有很多关于变压器顶层油温预测的模型,企业可以去找定制机器学习模型的企业获得类似模型。 - Delivery: - 实际与工厂洽谈,与工厂达成合作,进行推广 - 也可以与国家电网合作,进行线上使用,进行进一步推广
PHP
UTF-8
204
2.578125
3
[]
no_license
<h1>Добро пожаловать!</h1> <p> </p> <?php foreach($data as $row) { print_r("<br>Name: " . $row['name'] . "<br>Age: " . $row['age'] . "<br>Address: " . $row['address'] . "<br>"); } ?>
SQL
UTF-8
2,606
3.1875
3
[ "MIT" ]
permissive
CREATE DATABASE `db_noticias`; CREATE TABLE `tbl_categoria` ( `idcategoria` int(11) NOT NULL, `nomecategoria` varchar(35) NOT NULL ); INSERT INTO `tbl_categoria` (`idcategoria`, `nomecategoria`) VALUES (2, 'Entretenimento'), (1, 'Esporte'), (17, 'Futebol'), (19, 'Lutas'), (7, 'Música'), (10, 'Teatro'), (21, 'Tecnologias'), (14, 'Telefone'), (20, 'Televisão'), (8, 'TI'), (16, 'TIS'); CREATE TABLE `tbl_noticia` ( `idnoticia` int(11) NOT NULL, `titulonoticia` varchar(50) NOT NULL, `conteudonoticia` varchar(200) NOT NULL, `fk_categoria` int(11) NOT NULL, `imgnoticias` varchar(40) NOT NULL ); INSERT INTO `tbl_noticia` (`idnoticia`, `titulonoticia`, `conteudonoticia`, `fk_categoria`, `imgnoticias`) VALUES (1, 'Lorem Ipsum1', 'Proin quis venenatis ex. Phasellus justo quam, efficitur ultrices tincidunt et, bibendum sit amet dui. Morbi molestie neque laoreet luctus suscipit. Vivamus a risus interdum, consectetur est sit amet,', 1, 'img1.png'), (2, 'Título demonstrando', 'Corpo demonstrando para o meu queridíssimo amigo Gabriel Moura.', 7, '246b87a5e890a7de8f2b6f273a370a7e.png'), (3, 'Título pelo form', 'xorpo', 8, 'f75b01a37bb08ad4c4075cf1f8bac49c.png'), (6304, 'Mais uma notícia', 'Esse é o corpo da notícia, e é aqui que deve ser redigido o texto dela.', 8, '6dbe730cdc33f55504d4dba5fdda56b7.png'), (6305, 'Título pelo formulário', 'Corpo', 16, '48f40196aae810b38708beec5d2c9f9f.png'), (6306, 'Corinthians x Palmeiras', '1 a 1', 1, '8283db157f9090841ec01f8c9e5b6bf5.png'), (6307, '3816971', 'Luta', 19, '10a01367e3da4413898f3e2a62f32297.png'), (6308, 'Título pelo form', 'Corpo', 19, 'db604358d4fd0fb865828ebb8291afdf.png'), (6309, 'Teatro', 'Corpo da noticia, hahahahahaha.', 10, '8283db157f9090841ec01f8c9e5b6bf5.png'); ALTER TABLE `tbl_categoria` ADD PRIMARY KEY (`idcategoria`), ADD UNIQUE KEY `nomecategoria` (`nomecategoria`); -- -- Indexes for table `tbl_noticia` -- ALTER TABLE `tbl_noticia` ADD PRIMARY KEY (`idnoticia`), ADD KEY `fk_categoria` (`fk_categoria`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_categoria` -- ALTER TABLE `tbl_categoria` MODIFY `idcategoria` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; -- -- AUTO_INCREMENT for table `tbl_noticia` -- ALTER TABLE `tbl_noticia` MODIFY `idnoticia` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; -- -- Constraints for dumped tables -- -- -- Constraints for table `tbl_noticia` -- ALTER TABLE `tbl_noticia` ADD CONSTRAINT `tbl_noticia_ibfk_1` FOREIGN KEY (`fk_categoria`) REFERENCES `tbl_categoria` (`idcategoria`);
Java
UTF-8
1,506
2.0625
2
[]
no_license
package dressesPageTest; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import HomePage.basepageReuseMethods; import HomePage.dressesObjects; public class testdressesPage { dressesObjects ds; basepageReuseMethods bp; public testdressesPage() { ds=new dressesObjects(); bp=new basepageReuseMethods(); } @BeforeMethod public void preValidation() { ds.clickDress(); } @Test public void pagenavigateAndDressesSize() { ds.verifytabdresses().click(); Assert.assertTrue(bp.elementFound(ds.verifySizeS()),"Pass:Element Present"); Assert.assertTrue(bp.elementFound(ds.verifySizeM()),"Pass:Element Present"); Assert.assertTrue(bp.elementFound(ds.verifySizeL()),"Pass:Element Present"); } @Test public void verifydressesaddedtoCart() { //ds.clickDress(); ds.addtoCart(); ds.addedtoCart(); ds.Scrolldown(); String s=ds.addedtoCart().getText(); System.out.println(s); String x="Product successfully added to your shopping cart"; System.out.println(x); Assert.assertEquals(s, x); ds.closeCartWindow(); } @Test public void verifydressesCount() { //ds.clickDress(); //ds.closeCartWindow(); int count=ds.getProductcountfromheader(); int productSize=ds.getProduct().size(); Assert.assertTrue(count==productSize); } }
Java
UTF-8
802
2.25
2
[]
no_license
package com.baseserver.file.config; import org.springframework.boot.context.embedded.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; /** * <p> * 文件服务器相关配置 * </p> * * @author shi_yuxi * @version 1.0 */ @Configuration public class FileConfig { /** * 限制上传文件大小40M * * @return MultipartConfigElement */ @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize( 1024 * 40 + "KB"); factory.setMaxRequestSize(1024 * 40 + "KB"); return factory.createMultipartConfig(); } }
JavaScript
UTF-8
354
3.3125
3
[]
no_license
function log(target, name, descriptor){ var origin = descriptor.value; descriptor.value = function(target, name, descriptor){ console.log('Calling ${name} with', arguments); return origin.apply(this, arguments); } return descriptor; } class Sum{ @log add(a, b){ return a + b; } } let x = new Sum(); x.add(1,2);
C#
UTF-8
442
3.0625
3
[]
no_license
namespace PCG3.TestFramework { /// <summary> /// Provides methods to check, if certain conditions in a test method are met. /// If a condition is not met, the methods throw an AssertFailedException. /// </summary> public static class Assert { public static void AreEqual(object expected, object actual) { if (!expected.Equals(actual)) { throw new AssertFailedException(expected, actual); } } } }
Python
UTF-8
414
3.53125
4
[]
no_license
#Name: Karthik and Vivan #Date: 10/2/2019 from random import random n = int(raw_input("Value of n: ")) trials = [] for trial in range(10000): m = 2*n +1 j = n+1 steps = 0 while 1<=j<=m: r = random() if r < 0.5: j+=1 else: j-=1 steps += 1 trials.append(steps) avg = (1.0*sum(trials))/10000 print "The average is ",avg
Java
UTF-8
535
2.546875
3
[]
no_license
package com.estudo.ocp.solucao; public class CalculadoraDePreco { private ServicoDeFrete frete; private TabelaDePreco entrega; public CalculadoraDePreco(ServicoDeFrete frete, TabelaDePreco entrega) { this.frete = frete; this.entrega = entrega; } public double calcula(Produto produto) { var desconto = entrega.calculaDesconto(produto.getValor()); var valorFrete = frete.calculaFrete(produto.getEstado()); return produto.getValor() * (1 - desconto) + valorFrete; } }
JavaScript
UTF-8
374
3.3125
3
[]
no_license
/** * @param {number[]} nums * @return {number[]} */ var findDisappearedNumbers = function(nums) { let map = new Map(); let newArray = []; for(let i = 0; i < nums.length; i++){ map.set(nums[i]); } for(let i = 1 ; i <= nums.length; i++){ if(!map.has(i)){ newArray.push(i); } } return newArray; };
Java
UTF-8
1,176
3.140625
3
[]
no_license
package q028; public class Solution { public static void getNext(String a, int[] next) { int q,k; int m = a.length(); next[0] = 0; for (q = 1,k = 0; q < m; ++q) { while(k > 0 && a.charAt(q) != a.charAt(k)) k = next[k-1]; if (a.charAt(q) == a.charAt(k)) { k++; } next[q] = k; } } public static int strStr(String haystack, String needle) { if (needle.length() > haystack.length()) return -1; if (needle.length() < 1 || haystack.length() < 1) return 0; int next[] = new int[needle.length()]; getNext(needle, next); int q=0; for (int i = 0; i < haystack.length(); i++) { while(q > 0 && needle.charAt(q) != haystack.charAt(i)) q = next[q-1]; if (needle.charAt(q) == haystack.charAt(i)) { q++; } if (q == needle.length()) { return i-needle.length()+1; } } return -1; } // public static void main(String[] args) { // String a = "mississippi"; // String b = "issip"; // // System.out.println(a.indexOf(b)); // System.out.println(strStr(a, b)); // // } }
Java
UTF-8
475
1.859375
2
[]
no_license
package fr.adaming.dao; import java.util.List; import fr.adaming.model.BienImmobilier; import fr.adaming.model.Conseiller; import fr.adaming.model.Proprietaire; public interface IProprietaireDao { public int createProprietaire (Proprietaire prop); public int updateProprietaire (Proprietaire prop); public int deleteProprietaire (int id); public Proprietaire getOnePropbyId (int id); public List<Proprietaire> getAllProprietaires(); }
C++
UTF-8
1,194
3.0625
3
[]
no_license
#ifndef __IOPERAND_HPP__ #define __IOPERAND_HPP__ #include "abstractVM.hpp" class IOperand { private: /* Variable types std::string; int; double; float; bool; */ protected: public: /* Return types std::string; int; double; float; bool; */ //getters // virtual int getPrecision(void) const = 0; // virtual std::string getType(void) const = 0; virtual std::string getValue(void) const = 0; //setters // virtual void setPrecision(int deci) = 0; // virtual void setType(std::string type) = 0; //constructor(s) //default // IOperand(); //copy // IOperand(const IOperand & rhs); //destructor // ~IOperand(); //Overloads //Operator Overloads // virtual IOperand const * operator+(IOperand const & rhs) const = 0; // virtual IOperand const * operator-(IOperand const & rhs) const = 0; // virtual IOperand const * operator*(IOperand const & rhs) const = 0; // virtual IOperand const * operator/(IOperand const & rhs) const = 0; // virtual IOperand const * operator%(IOperand const & rhs) const = 0; //ToString Overload // virtual std::string const & ToString(void) const = 0; }; #endif
Java
UTF-8
857
2.1875
2
[]
no_license
package com.prj.web.entity; public class DramaObject { private int id; private String name; private String src; private String iframe; public DramaObject() { } public DramaObject(int id, String name, String src, String iframe) { super(); this.id = id; this.name = name; this.src = src; this.iframe = iframe; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public String getIframe() { return iframe; } public void setIframe(String iframe) { this.iframe = iframe; } }
JavaScript
UTF-8
569
4.3125
4
[]
no_license
// faster/easier way to access/unpack variable from arrays, objects const fruits = ["orange", "banana", "lemon"]; const friends = ["john", "peter", "bob", "anna", "kelly"]; const fruit1 = fruits[0]; const fruit2 = fruits[1]; const fruit3 = fruits[2]; console.log(fruit1, fruit2, fruit3); // orange, banana, lemon const [friend, , bob, , kelly, susan] = friends; console.log(friend, bob, kelly, susan); // john bob kelly undefined // destructing arrays let first = "bob"; let second = "john"; [second, first] = [first, second]; console.log(first, second); // john bob
Java
UTF-8
6,793
2.0625
2
[]
no_license
package com.gs.spider.dao; import com.gs.spider.utils.StaticValue; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.exists.types.TypesExistsRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.net.InetAddress; /** * ESClient */ @Component @Scope("prototype") public class ESClient { private final static String COMMON_INDEX_CONFIG = "commonIndex.json"; private static final String COMMONS_INDEX_NAME = "commons"; private static final String WEBPAGE_TYPE_NAME = "webpage"; private static final String SPIDER_INFO_TYPE_NAME = "spiderinfo"; private static final String SPIDER_INFO_INDEX_NAME = "spiderinfo"; private Logger logger = LogManager.getLogger(ESClient.class); private Client client; @Autowired private StaticValue staticValue; public boolean checkCommonsIndex() { return checkIndex(COMMONS_INDEX_NAME, COMMON_INDEX_CONFIG); } public boolean checkWebpageType() { return checkType(COMMONS_INDEX_NAME, WEBPAGE_TYPE_NAME, "webpage.json"); } public boolean checkSpiderInfoIndex() { return checkIndex(SPIDER_INFO_INDEX_NAME, COMMON_INDEX_CONFIG); } public boolean checkSpiderInfoType() { return checkType(SPIDER_INFO_INDEX_NAME, SPIDER_INFO_TYPE_NAME, "spiderinfo.json"); } public Client getClient() { if (!staticValue.isNeedEs()) { logger.info("已在配置文件中声明不需要ES,如需要ES,请在配置文件中进行配置"); return null; } if (client != null) return client; logger.info("正在初始化ElasticSearch客户端," + staticValue.getEsHost()); Settings settings = Settings.builder() .put("cluster.name", staticValue.getEsClusterName()).build(); try { client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(staticValue.getEsHost()), staticValue.getEsPort())); final ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth() .setTimeout(TimeValue.timeValueMinutes(1)).execute().actionGet(); if (healthResponse.isTimedOut()) { logger.error("ES客户端初始化失败"); } else { logger.info("ES客户端初始化成功"); } } catch (IOException e) { logger.fatal("构建ElasticSearch客户端失败!"); } return client; } public boolean checkType(String index, String type, String mapping) { if (client == null) return false; if (!client.admin().indices().typesExists(new TypesExistsRequest(new String[]{index}, type)).actionGet().isExists()) { logger.info(type + " type不存在,正在准备创建type"); File mappingFile; try { mappingFile = new File(this.getClass().getClassLoader() .getResource(mapping).getFile()); } catch (Exception e) { logger.fatal("查找ES mapping配置文件出错, " + e.getLocalizedMessage()); return false; } logger.debug(type + " MappingFile:" + mappingFile.getPath()); PutMappingResponse mapPuttingResponse = null; PutMappingRequest putMappingRequest = null; try { putMappingRequest = Requests.putMappingRequest(index).type(type).source(FileUtils.readFileToString(mappingFile)); } catch (IOException e) { logger.error("创建 jvmSample mapping 失败," + e.getLocalizedMessage()); } mapPuttingResponse = client.admin().indices().putMapping(putMappingRequest).actionGet(); if (mapPuttingResponse.isAcknowledged()) logger.info("创建" + type + "type成功"); else { logger.error("创建" + type + "type索引失败"); return false; } } else logger.debug(type + " type 存在"); return true; } public boolean checkIndex(String index, String mapping) { if (client == null) return false; if (!client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet().isExists()) { File indexMappingFile; try { indexMappingFile = new File(this.getClass().getClassLoader() .getResource(mapping).getFile()); } catch (Exception e) { logger.fatal("查找" + index + "index mapping配置文件出错, " + e.getLocalizedMessage()); return false; } logger.debug(index + "index MappingFile:" + indexMappingFile.getPath()); logger.info(index + " index 不存在,正在准备创建index"); CreateIndexResponse createIndexResponse = null; try { createIndexResponse = client.admin().indices() .prepareCreate(index) .setSettings(FileUtils.readFileToString(indexMappingFile)) .execute().actionGet(); } catch (IOException e) { logger.error("创建 " + index + " index 失败"); return false; } if (createIndexResponse.isAcknowledged()) logger.info(index + " index 成功"); else { logger.fatal(index + " index失败"); return false; } } else logger.debug(index + " index 存在"); return true; } public StaticValue getStaticValue() { return staticValue; } public ESClient setStaticValue(StaticValue staticValue) { this.staticValue = staticValue; return this; } }
Markdown
UTF-8
8,997
3.390625
3
[ "MIT" ]
permissive
# Ruby Holidays Gem [![Build Status](https://travis-ci.org/holidays/holidays.svg?branch=master)](https://travis-ci.org/holidays/holidays) Functionality to deal with holidays in Ruby. Extends Ruby's built-in Date and Time classes and supports custom holiday definition lists. ## Installation ``` gem install holidays ``` ## Tested versions This gem is tested with the following ruby versions: * 2.4.5 * 2.5.3 * 2.6.1 * JRuby 9.2.5.0 ## Semver This gem follows [semantic versioning](http://semver.org/). The guarantee specifically covers: * methods in the top-most `Holidays` namespace e.g. `Holidays.<method>` * the [core extensions](#extending-rubys-date-and-time-classes) Please note that we consider definition changes to be 'minor' bumps, meaning they are backwards compatible with your code but might give different holiday results! ## Time zones Time zones are ignored. This library assumes that all dates are within the same time zone. ## Usage This gem offers multiple ways to check for holidays for a variety of scenarios. #### Checking a specific date Get all holidays on April 25, 2008 in Australia: ``` Holidays.on(Date.civil(2008, 4, 25), :au) => [{:name => 'ANZAC Day',...}] ``` You can check multiple regions in a single call: ``` Holidays.on(Date.civil(2008, 1, 1), :us, :fr) => [{:name=>"New Year's Day", :regions=>[:us],...}, {:name=>"Jour de l'an", :regions=>[:fr],...}] ``` You can leave off 'regions' to get holidays for any region in our [definitions](https://github.com/holidays/definitions): ``` Holidays.on(Date.civil(2007, 4, 25)) => [{:name=>"ANZAC Day", :regions=>[:au],...}, {:name=>"Festa della Liberazione", :regions=>[:it],...}, {:name=>"Dia da Liberdade", :regions=>[:pt],...} ... ] ``` #### Checking a date range Get all holidays during the month of July 2008 in Canada and the US: ``` from = Date.civil(2008,7,1) to = Date.civil(2008,7,31) Holidays.between(from, to, :ca, :us) => [{:name => 'Canada Day',...} {:name => 'Independence Day',...}] ``` #### Check for 'informal' holidays You can pass the 'informal' flag to include holidays specified as informal in your results. See [here](https://github.com/holidays/definitions/blob/master/doc/SYNTAX.md#formalinformal) for information on what constitutes 'informal' vs 'formal'. By default this flag is turned off, meaning no informal holidays will be returned. Get Valentine's Day in the US: ``` Holidays.on(Date.new(2018, 2, 14), :us, :informal) => [{:name=>"Valentine's Day",...}] ``` Leaving off 'informal' will mean that Valentine's Day is not returned: ``` Holidays.on(Date.new(2018, 2, 14), :us) => [] ``` Get informal holidays during the month of February 2008 for any region: ``` from = Date.civil(2008,2,1) to = Date.civil(2008,2,15) Holidays.between(from, to, :informal) => [{:name => 'Valentine\'s Day',...}] ``` #### Check for 'observed' holidays You can pass the 'observed' flag to include holidays that are observed on different days than they actually occur. See [here](https://github.com/holidays/definitions/blob/master/doc/SYNTAX.md#observed) for further explanation of 'observed'. By default this flag is turned off, meaning no observed logic will be applied. Get holidays that are observed on Monday July 2, 2007 in British Columbia, Canada: ``` Holidays.on(Date.civil(2007, 7, 2), :ca_bc, :observed) => [{:name => 'Canada Day',...}] ``` Leaving off the 'observed' flag will mean that 'Canada Day' is not returned since it actually falls on Sunday July 1: ``` Holidays.on(Date.civil(2007, 7, 2), :ca_bc) => [] Holidays.on(Date.civil(2007, 7, 1), :ca_bc) => [{:name=>"Canada Day", :regions=>[:ca],...}] ``` Get all observed US Federal holidays between 2018 and 2019: ``` from = Date.civil(2018,1,1) to = Date.civil(2019,12,31) Holidays.between(from, to, :federalreserve, :observed) => [{:name => "New Year's Day"....} {:name => "Birthday of Martin Luther King, Jr"....}] ``` #### Check whether any holidays occur during work week Check if there are any holidays taking place during a specified work week. 'Work week' is defined as the period of Monday through Friday of the week specified by the date. Check whether a holiday falls during first week of the year for any region: ``` Holidays.any_holidays_during_work_week?(Date.civil(2016, 1, 1)) => true ``` You can also pass in `informal` or `observed`: ``` # Returns true since Valentine's Day falls on a Wednesday holidays.any_holidays_during_work_week?(date.civil(2018, 2, 14), :us, :informal) => true # Returns false if you don't specify informal irb(main):006:0> Holidays.any_holidays_during_work_week?(Date.civil(2018, 2, 14), :us) => false # Returns true since Veteran's Day is observed on Monday November 12, 2018 holidays.any_holidays_during_work_week?(date.civil(2018, 11, 12), :us, :observed) => true # Returns false if you don't specify observed since the actual holiday is on Sunday November 11th 2018 irb(main):005:0> Holidays.any_holidays_during_work_week?(Date.civil(2018, 11, 12), :us) => false ``` #### Find the next holiday(s) that will occur from a specific date Get the next holidays occurring from February 23, 2016 for the US: ``` Holidays.next_holidays(3, [:us, :informal], Date.civil(2016, 2, 23)) => [{:name => "St. Patrick's Day",...}, {:name => "Good Friday",...}, {:name => "Easter Sunday",...}] ``` You can specify the number of holidays to return. This method will default to `Date.today` if no date is provided. #### Find all holidays occuring starting from a specific date to the end of the year Get all holidays starting from February 23, 2016 to end of year in the US: ``` Holidays.year_holidays([:ca_on], Date.civil(2016, 2, 23)) => [{:name=>"Good Friday",...}, {name=>"Easter Sunday",...}, {:name=>"Victoria Day",...}, {:name=>"Canada Day",...}, {:name=>"Civic Holiday",...}, {:name=>"Labour Day",...}, {:name=>"Thanksgiving",...}, {:name=>"Remembrance Day",...}, {:name=>"Christmas Day",...}, {:name=>"Boxing Day",...}] ``` This method will default to `Date.today` if no date is provided. #### Return all available regions Return all available regions: ``` Holidays.available_regions => [:ar, :at, ..., :sg] # this will be a big array ``` ## Loading Custom Definitions on the fly In addition to the [provided definitions](https://github.com/holidays/definitions) you can load custom definitions file on the fly and use them immediately. To load custom 'Company Founding' holiday on June 1st: ``` Holidays.load_custom('/home/user/holiday_definitions/custom_holidays.yaml') Holidays.on(Date.civil(2013, 6, 1), :my_custom_region) => [{:name => 'Company Founding',...}] ``` Custom definition files must match the [syntax of the existing definition files](https://github.com/holidays/definitions/blob/master/doc/SYNTAX.md). Multiple files can be loaded at the same time: ``` Holidays.load_custom('/home/user/holidays/custom_holidays1.yaml', '/home/user/holidays/custom_holidays2.yaml') ``` ## Extending Ruby's Date and Time classes ### Date To extend the 'Date' class: ``` require 'holidays/core_extensions/date' class Date include Holidays::CoreExtensions::Date end ``` Now you can check which holidays occur in Iceland on January 1, 2008: ``` d = Date.civil(2008,7,1) d.holidays(:is) => [{:name => 'Nýársdagur'}...] ``` Or lookup Canada Day in different regions: ``` d = Date.civil(2008,7,1) d.holiday?(:ca) # Canada => true d.holiday?(:ca_bc) # British Columbia, Canada => true d.holiday?(:fr) # France => false ``` Or return the new date based on the options: ``` d = Date.civil(2008,7,1) d.change(:year => 2016, :month => 1, :day => 1) => #<Date: 2016-01-01 ((2457389j,0s,0n),+0s,2299161j)> ``` Or you can calculate the day of the month: ``` Date.calculate_mday(2015, 4, :first, 2) => 7 ``` ### Time ``` require 'holidays/core_extensions/time' class Time include Holidays::CoreExtensions::Time end ``` Find end of month for given date: ``` d = Date.civil(2016,8,1) d.end_of_month => #<Date: 2016-08-31 ((2457632j,0s,0n),+0s,2299161j)> ``` ## Caching Holiday Lookups If you are checking holidays regularly you can cache your results for improved performance. Run this before looking up a holiday (e.g. in an initializer): ``` YEAR = 365 * 24 * 60 * 60 Holidays.cache_between(Time.now, Time.now + 2 * YEAR, :ca, :us, :observed) ``` Holidays for the regions specified within the dates specified will be pre-calculated and stored in-memory. Future lookups will be much faster. ## How to contribute See our [contribution guidelines](doc/CONTRIBUTING.md) for information on how to help out! ## Credits and code * Started by [@alexdunae](http://github.com/alexdunae) 2007-2012 * Maintained by [@hahahana](https://github.com/hahahana), 2013 * Maintained by [@ppeble](https://github.com/ppeble), 2014-present * Maintained by [@ttwo32](https://github.com/ttwo32), 2016-present Plus all of these [wonderful contributors!](https://github.com/holidays/holidays/contributors)
TypeScript
UTF-8
2,699
3.296875
3
[ "MIT" ]
permissive
/// <reference path="../typings/jasmine/jasmine.d.ts" /> import { Color } from "../lib/color"; describe("instance", () => { it("should construct from rgb array", () => { new Color([255, 0, 5]); }); it("should construct from css rgb string", () => { new Color("rgb(255, 0, 0)"); }); it("should not construct from less than 3 or more than 4 values", () => { expect(() => { new Color(<any>[0, 1]); }).toThrow(new Color.ValueNumberError); expect(() => { new Color([0, 1, 2, 3, 4]); }).toThrow(new Color.ValueNumberError); }); it("should convert to string", () => { expect(""+Color.RED).toBe("rgb(255, 0, 0)"); expect(Color.RED.toString()).toBe("rgb(255, 0, 0)"); }); it("should mix different colors", () => { expect(Color.RED.mix(Color.BLUE)+"").toBe("rgb(128, 0, 128)"); }); it("should not construct from invalid values", () => { expect(() => { new Color("rgb(255, 0, a)"); }).toThrow(new Color.ValueTypeError); }); it("should clamp values to 0-255", () => { expect(new Color([-10,500,128]).slice()).toEqual([0, 255, 128]); }); it("should add different colors", () => { expect(Color.BLUE.add(Color.RED).slice()).toEqual([255, 0, 255]); expect(Color.RED.add(new Color([0, 32, 0])).slice()).toEqual([255, 32, 0]); }); it("should subtract different colors", () => { expect(Color.RED.subtract(new Color([128, 0, 0])).slice()).toEqual([127, 0, 0]); }); it("should map color values", () => { expect(Color.RED.map(function(x) { return x * 0.5; }).slice()).toEqual([128, 0, 0]); }); }); describe("alpha", () => { it("should handle alpha values", () => { expect(""+new Color([0, 0, 0, 0])).toBe("rgba(0, 0, 0, 0)"); expect(""+new Color([0, 0, 0, 0.5])).toBe("rgba(0, 0, 0, 0.5)"); }); it("should disallow invalid alpha values", () => { expect(() => { new Color([0, 0, 0, 5]); }).toThrow(new Color.InvalidAlphaValue); expect(() => { new Color([0, 0, 0, <any>"foo"]); }).toThrow(new Color.InvalidAlphaValue); expect(() => { new Color([0, 0, 0, -1]); }).toThrow(new Color.InvalidAlphaValue); }); it("should parse alpha colors", () => { expect(""+new Color("rgba(255, 0, 0, 0.1)")).toBe("rgba(255, 0, 0, 0.1)"); }); }); describe("static", () => { it("should clamp values from 0 - 255", () => { expect(Color.clamp(256)).toBe(255); expect(Color.clamp(-1)).toBe(0); expect(Color.clamp(128)).toBe(128); }); it("should parse css rgb() colors", () => { expect(Color.parse("rgb(0,0,0)")).toEqual([0, 0, 0]); }); it("should parse invalid css rgb() colors to NaN", () => { expect(Color.parse("rgb(a,b,c)").every(isNaN)).toBe(true); }); });
Go
UTF-8
4,052
3
3
[ "MIT" ]
permissive
package dga import ( "bytes" "fmt" "io" "time" ) const ( // Star is used to model any predicate or any object in an NQuad. Star = "*" // DateTimeFormat is the format used by Dgraph for facet values of type dateTime. DateTimeFormat = "2006-01-02T15:04:05" // DgraphType is a reserved predicate name to refer to a type definition. DgraphType = "dgraph.type" ) // NQuad represents an RDF S P O pair. type NQuad struct { // Subject is the node for which the predicate must be created/modified. Subject UID // Predicate is a known schema predicate or a Star Predicate string // Object can be a primitive value or a UID or a Star (constant) Object interface{} // StorageType is used to optionally specify the type when storing the object // see https://docs.dgraph.io/mutations/#language-and-rdf-types // Example: dga.RDFString StorageType RDFDatatype // Maps to string, bool, int, float and dateTime. // For int and float, only 32-bit signed integers and 64-bit floats are accepted. Facets map[string]interface{} } // BlankNQuad returns an NQuad value with a Blank UID subject. // Use BlankUID if you want the object also to be a Blank UID from a name. func BlankNQuad(subjectName string, predicate string, object interface{}) NQuad { return NQuad{ Subject: BlankUID(subjectName), Predicate: predicate, Object: object, } } // RDFDatatype is to set the StorageType of an NQuad. type RDFDatatype string // see https://docs.dgraph.io/mutations/#language-and-rdf-types const ( // RDFString is a RDF type RDFString = RDFDatatype("<xs:string>") RDFDateTime = RDFDatatype("<xs:dateTime>") RDFDate = RDFDatatype("<xs:date>") RDFInt = RDFDatatype("<xs:int>") RDFInteger = RDFDatatype("<xs:integer>") RDFBoolean = RDFDatatype("<xs:boolean>") RDFDouble = RDFDatatype("<xs:double>") RDFFloat = RDFDatatype("<xs:float>") ) // WithStorageType returns a copy with its StorageType set. // Use DetectStorageType(any interface{}) func (n NQuad) WithStorageType(t RDFDatatype) NQuad { return NQuad{ Subject: n.Subject, Predicate: n.Predicate, Object: n.Object, StorageType: t, Facets: n.Facets, } } // WithFacet returns a copy with an additional facet (key=value). func (n NQuad) WithFacet(key string, value interface{}) NQuad { f := n.Facets if f == nil { f = map[string]interface{}{} } f[key] = value return NQuad{ Subject: n.Subject, Predicate: n.Predicate, Object: n.Object, StorageType: n.StorageType, Facets: f, } } func bytesFromNQuads(list []NQuad) []byte { var b bytes.Buffer for _, each := range list { // TODO optimize using buffer? (&b).Write(each.Bytes()) io.WriteString(&b, "\n") } return b.Bytes() } // Bytes returns the mutation line. func (n NQuad) Bytes() []byte { b := new(bytes.Buffer) b.WriteString(n.Subject.RDF()) if n.Predicate == Star { fmt.Fprint(b, " * ") } else { fmt.Fprintf(b, " <%s> ", n.Predicate) } if s, ok := n.Object.(string); ok { if s == Star { fmt.Fprint(b, "*") } else { fmt.Fprintf(b, "%q", s) } } else if uid, ok := n.Object.(UID); ok { fmt.Fprintf(b, "%s", uid.RDF()) } else if s, ok := n.Object.(string); ok { fmt.Fprintf(b, "%q", s) } else if i, ok := n.Object.(int); ok { fmt.Fprintf(b, "\"%d\"", i) } else { fmt.Fprintf(b, "%v", n.Object) } if len(n.StorageType) > 0 { fmt.Fprintf(b, "^^%s ", n.StorageType) } else { fmt.Fprintf(b, " ") } if n.Facets != nil && len(n.Facets) > 0 { fmt.Fprintf(b, "(") first := true for k, v := range n.Facets { if !first { fmt.Fprintf(b, ", ") } var s string if t, ok := v.(time.Time); ok { s = t.Format(DateTimeFormat) } else if q, ok := v.(string); ok { s = fmt.Sprintf("%q", q) } else { s = fmt.Sprintf("%v", v) } fmt.Fprintf(b, "%s=%s", k, s) first = false } fmt.Fprintf(b, ") ") } fmt.Fprintf(b, ".") return b.Bytes() } // RDF returns the string version of its Bytes representation. func (n NQuad) RDF() string { return string(n.Bytes()) }
Markdown
UTF-8
1,674
3.8125
4
[]
no_license
#小解OC Categories `Categories`是Objective-C最有用的一个特性。事实上,`Category`可以使你为一个类添加一个方法,而不需要继承这个类甚至不用知道这个类的内部实现的细节。 这是非常有用的因为你可以为内建的对象添加方法。如果你想把在你应用中所有的的NSString实例添加一个方法,那你只加一个`Category`就好了。并不是所有的事情都需要自定义子类的。 比如,如果你想给NSString添加一个方法来判断字符串本身是否是URL,那就会像下面这样: #import <Cocoa/Cocoa.h> @interface NSString (Utilities) - (BOOL)isURL; @end 这很像声明一个类。他们之间的区别是没有超类列表,而且在圆括号中有一个`Category`的名字。这个名字可以是任何你想要的,当然它应该尽量表达出新添加的方法做的是什么。 下面是implementation的代码: #import "NSString-Utilities.h" @implementstion NSString (Utilities) - (BOOL)isURL { if([self hasPrefix:@"http://"]) { return YES; }else { return NO; } } @end 现在任何NSString对象都可以用`isURL`这个方法。看下面的测试代码: NSString* string1=@"http://www.google.com"; NSString* string2=@"google"; if([string1 isURL]) NSLog(@"string1 is a URL"); if([string2 isURL]) NSLog(@"string2 is a URL"); 不像继承,分类不能添加实例变量。当然,你可以用分类技术来重写在类中已经存在的方法,但是你应该非常小心。 记住,当你对一个类使用`Category`技术的时候,它对你应用中所有这个类的实例都有影响。
Markdown
UTF-8
8,498
2.703125
3
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
--- layout: post title: "谈独立思考" date: 2001-02-15 author: 欧远方 from: http://www.yhcqw.com/ tags: [ 炎黄春秋 ] categories: [ 炎黄春秋 ] --- [ 2001年第2期 谈独立思考 欧远方 ] 泗县第一小学举办金秋书画展,要我题字,我赠送他们一个条幅,上书“独立思考”四字。这是有感而发。 前些年,某刊发表一篇湖南人访问胡耀邦的文章。当时胡耀邦已不担任中共中央总书记。在他的谈话中,除反思他个人解放后犯了两个错误外,还谈到党内长期以来强调集中强调纪律而不强调民主,形成党员中产生驯服工具思想和奴隶主义思想,缺少独立思考。联系我个人在十一届三中全会以前,受奴隶主义影响很大。有时也有独立思考,如三反时为王维、杨琪华夫妇冤案上书区党委,不但未被采纳,反说我是思想老虎,受了处分。以后政治运动一个接一个,或因长期干的是省党报总编辑,作为省委机关报,是省委的喉舌,我不但身体力行奴隶主义,而且在报社向干部宣传“驯服工具论”。后来调到省委办公厅、宣传部等单位,对党委同样是驯服工具,组织叫干啥就干啥,多干实事,少发议论。我也曾佩服老部长陆学斌的善于独立思考,他因发表“人人争上游,上游就堵死了”的言论,被打成“右机”,下放劳动。我也曾佩服李凡夫在省委常委会上一再反对林彪的“顶峰论”,他说:“理论还要发展嘛”!但我自律严,言行从不敢越雷池一步,为此我也曾受过表彰,当过“模范党员”,长期不觉悟,直到“文革”结束,学习了邓小平“解放思想、实事求是”讲话,又经过“真理标准”讲座的启发,我才开窍。这时,想到毛主席曾说过:一事当前,要问个为什么,然后决定接受它或是拒绝它。又回想起陆学斌常说的遇事要“左思右想”,我的思想禁锢逐步解除。从这以后写文章、讲话,就有点独立思考了。重新学习马克思理论,又做过一些调查研究,似乎胆子也大了些。 我为什么要给一小学展览会题“独立思考”四字呢?这是我近年来接触教育界、体育界的干部引出的一个认识,必须提倡独立思考,而且还要提倡“个人奋斗”。 有许多文章比较中国和美国、日本等国教育上的不同之处,在于中国学校重视注入式,美国等学校则重视启发式。中国课堂中“先生讲,学生听”,而美、日等国学校教师和学生间关系则是平等关系,教师可以向学生提问题,学生也可以向教师提问题。我上过一年私塾,私塾教学方法是死记硬背,《论语》、《孟子》要背全文,一字不拉,所以世界数理化奥林匹克比赛,中国学生获奖者多。但中国学生和教师的关系是猫鼠关系,创造性和独立性思考相对差一些,这从大中学校考试中可以看出。老师出选择题,有十个答案,尽管其中有三、四个答案都是正确的,但教师只认同其中一个,即所谓标准答案,比八股应制考试还厉害,这就把学生思想搞僵化了。 举个例子:有个小学老师考小学生:“雪化了变成什么?”多数学生回答:“雪化变成水。”标准答案也是“水”。有位学生回答:“雪化了变成了春天。”老师却说“错”。这一声“错”,无形中扼杀了儿童的想象力和创造力。 其实,中国古代教育家、学者,对教育留下很多宝贵遗产,除孔子的“有教无类”、“三人行必有我师”等等之外,他还主张拜“巫医、乐师、百工之人”为师。唐代大文学家韩愈所著《师说》有句名言:“弟子不必不如师,师不必贤于弟子”,并依此引出“教学相长”之说,都是至理名言。当教师的总以为自己样样高于学生,事实上未必。当教师的假如能正确对待这个问题,就不至于在考试时出偏题、难题,难为学生,以至于学生把考试视为畏途。这种教学方法,学生只有死背硬记,导致思想僵化,除学到一些书本知识外,就很难有独立思考的余地,因而创造性也受到限制。 过去以“师道尊严”出名的日本,也改变了教育方法。学生考试不及格,可以回去重新温习功课,第二次再考,考的成绩好了也算数,这样学生就解除了压力。这种生动活泼的教育方式,既密切了师生关系,又培育了更多人才。 有人提出这样的问题:为什么中国学生在世界奥林匹克比赛中常常获奖,而中国学者却未能培养出诺贝尔奖金的获得者?为什么中国学者到了国外,获得诺贝尔奖金的人却不在少数?这不能说人家都是偏见,这和中国教育只注重死记硬背书本而缺少独立思考有关系,这是不无道理的。 不仅学校教育如此,对干部教育也同样如此。我们所需要的干部,应是善于独立思考,敢于创造,甚至敢于冒险突破各种禁区。中国人是聪明的,自古以来发明创造很多很多。如古代四大发明震惊世界,都是独立思考的成果,也是个人奋斗的成果(有的不是一个人,但精神是一样的)。“独立思考”和“个人奋斗”相辅相成,后者创造发明更多。近百年来由于政治腐败而使发明创造受到压制,或有了发明创造而不能转化为生产力,也不能运用于社会发展。解放以后,中国人的创造发明更多,但后来多次打击人才的政治运动,加上我们高度集中的政治制度压抑了人们的创造性,当然一些尖端技术也难脱颖而出。假如给人们以更宽松的环境,发明创造将更多,对生产和社会的发展贡献也会更大。 就淮河流域来说,历史上的发明创造就不少,如哲学上的老、庄、管、孔、孟、墨、杨……这且不说。解放后安徽人为战胜水灾创造了连拱坝等五大水库(连拱坝设计者是水利专家汪胡桢);开掘了淠史杭人工灌溉渠,其效益可以和都江堰媲美。农业“三改”也是一个创造,50年代开花,80、90年代结果,淮河两岸十个县旱田改种水稻已达600万亩以上。在科学技术上,安徽在一穷二白基础上创造出的半导体在全国处于领先地位,可惜安徽未能形成生产力,而为外省引用,且走在前头。淮南市创造的光缆技术,得不到支持,而外省却很快超过我们。现在的光缆技术已在国内普及,对通讯效率的提高是十分巨大的。这证明安徽人善于独立思考,善于发明创造,但往往因得不到起码的支持,因此中途而废。这证明安徽人才并不缺,缺的是爱护使用。 至于安徽人才外流,说来话长。安徽落后,在华东地区不如其它省市。回顾50年代大胆招引人才,使用人才,不拘一格,正如龚自珍诗句所说,做到了“不拘一格降人才”,才使那时的安徽在科学(包括自然科学和社会科学)和技术方面,教育、医疗方面,都建立了基础和框架。但此后,历经政治运动,知识分子受到打击、压制加上安徽的封建气氛特浓,官本位思想也特厚,人才纷纷外流,许多公认的尖子人才,也遭到某些单位逼其外流,因而有“出生入死”之说,即离开安徽人家就重用,留在安徽却没有前途。知识分子耻于走后门、拉关系,而又好发议论,太重视“独立思考”,于是被某些领导人视为“不听话”,“不尊重组织”(其实是不尊重他个人),于是把这类人才晾在一边,形成自找出路的风气。“此处不留爷,自有留爷处,处处不留爷,爷到外省去。”(原话是“爷去投八路”。这个顺口溜是抗战时在敌后讲的,此处借用。)事实就是如此荒唐,哪里是缺少人才技术啊!当然总体来说安徽人才、技术是弱的,问题在于让现有人才、技术运用起来。 政策放宽,营造一个宽松的环境,尊重人家的“独立思考”,人才就涌现了,技术也有了,发明创造也就多了。 出于上述情况,人们就形成了一个观点:应当重视“独立思考”。
Markdown
UTF-8
4,853
2.71875
3
[]
no_license
# Article A931-2-1 I.-Toute demande d'agrément administratif présentée par une institution de prévoyance ou une union d'institutions de prévoyance en application de l'article L. 931-4 doit être produite en double exemplaire et comporter : a) La liste, établie conformément aux dispositions de l'article R. 931-2-1, des branches ou sous-branches que l'institution ou l'union se propose de pratiquer ; b) Le cas échéant, l'indication des pays étrangers où l'institution ou l'union se propose d'opérer ; c) La convention, l'accord collectif ou l'accord ratifié et le récépissé de dépôt mentionnés au I de l'article R. 931-1-9 ou le procès-verbal intégral mentionné au II de ce même article ; d) Un exemplaire des statuts ; e) La liste des membres du conseil d'administration et des directeurs, ainsi que de toute personne appelée à exercer en fait des fonctions équivalentes, avec les noms, prénoms, domicile, nationalité, date et lieu de naissance de chacun d'eux. Si ces personnes ont résidé hors de France pendant la période de cinq ans précédant la demande d'agrément, elles doivent indiquer leur dernière adresse hors de France. Le dossier défini à l'article A 931-2-2 doit être fourni par chacune de ces personnes ; f) Un programme d'activités comprenant les pièces suivantes : 1. Un document précisant la nature des risques que l'institution ou l'union se propose de garantir ou des engagements qu'elle se propose de prendre ; 2. Une note technique exposant le mode d'établissement des tarifs et les bases de calcul des diverses catégories de cotisations ; s'il s'agit d'opérations de la branche mentionnée au 26 de l'article R. 931-2-1, une note technique exposant le mode d'établissement des tarifs, les modalités de détermination des cotisations annuelles ainsi que les indications relatives à la fixation du nombre d'unités de rente correspondant à ces cotisations ; s'il s'agit d'opérations de la branche mentionnée au 24 de l'article précité, le tarif complet des versements ou cotisations, accompagné de tableaux indiquant au moins année par année les provisions mathématiques et les valeurs de rachat correspondantes, ainsi qu'une note technique exposant le mode d'établissement de ces divers éléments ; 3. Les principes directeurs que l'institution ou l'union se propose de suivre en matière de réassurance, la liste des principaux réassureurs pressentis et les éléments de nature à démontrer leur intention de contracter avec l'institution ou l'union ; 4. La description de l'organisation administrative et des structures de développement ainsi que des moyens en personnel et en matériel dont dispose l'institution ou l'union ; les prévisions de frais d'installation des services administratifs et des services de développement, ainsi que les moyens financiers destinés à y faire face ; 5. Pour les cinq premiers exercices comptables d'activité : les comptes de résultat et bilans prévisionnels ainsi que le détail des hypothèses retenues (principes de tarification, nature des garanties, sinistralité, évolution des frais généraux, rendement des placements) ; 6. Pour les mêmes exercices : - les prévisions relatives aux moyens financiers destinés à la couverture des engagements ; - les prévisions relatives à la marge de solvabilité calculée conformément aux dispositions de la section 10 du chapitre Ier du titre III du livre IX et de la présente annexe ; - les prévisions de trésorerie ; 7. La justification des éléments constituant le montant minimal du fonds de garantie que l'institution de prévoyance ou l'union d'institutions de prévoyance doit posséder conformément aux dispositions de la section 10 précitée ; 8. Les liste et certificat relatifs à la constitution du fonds d'établissement visés à l'article R. 931-1-7 et une note détaillant les éléments constitutifs de la marge de solvabilité conformément aux dispositions de la section 10 précitée ; 9. Le nom et l'adresse du ou des principaux établissements bancaires où sont domiciliés les comptes de l'institution ou de l'union. II.-En cas de demande d'extension d'agrément, le dossier à communiquer est le même que celui prévu au I du présent article. **Liens relatifs à cet article** _Modifié par_: - Arrêté 1997-02-25 art. 7 I, II JORF 18 mars 1997 _Codifié par_: - Décret n°85-1353 1985-12-17 _Abrogé par_: - Arrêté du 30 décembre 2015 - art. 1 _Cité par_: - Code de la sécurité sociale. - art. A931-2-2 (Ab) - Code de la sécurité sociale. - art. A951-3-1 (Ab) _Cite_: - Code de la sécurité sociale. - art. L931-4 - Code de la sécurité sociale. - art. R931-1-7 - Code de la sécurité sociale. - art. R931-1-9 - Code de la sécurité sociale. - art. R931-2-1
PHP
WINDOWS-1251
272
2.578125
3
[]
no_license
<!-- : . --> <html><body> <h2> :</h2> <?$f = fopen("../news.txt", "r") ?> <?for ($i=1; !feof($f) && $i<=5; $i++) {?> <li><?=$i?>- : <?=fgets($f, 1024)?> <?}?> </body></html>
Python
UTF-8
9,224
3
3
[]
no_license
'''Debbuging interface for the m5mbridge. All parts of m5mbridge that support debugging must be registered here. Debugging is hierarchical to control the degree of debugging output that is desired. Every part is a direct or indirect child of the debugging class 'all' which enables debugging globally. Children of 'all' are, for example mcpat and m5 which have as children importer and exporter. For example to enable debugging for the mcpat module you use the following path specifier: all.modules.mcpat In general every individual part is separated with a ., similar to a / in filesystem paths. Such a path is call a partref. Debugging for a module is enabled if the debugging flag is set for its partref or for a partref of an ancestor. For example for the mcpat module debugging is enabled if the debugging flag is set for any of the following partrefs: 'all.modules.mcpat', 'all.modules' or 'all'. For more information on the allowed command-line syntax see the docstring of enable_debugging_from_options. ''' import inspect from m5mbridge import bug, warning DEBUGGABLE_PARTS = set([ 'all', 'all.controller', 'all.controller.playback', 'all.controller.recorder', 'all.modules', 'all.modules.m5', 'all.modules.m5.importer', 'all.modules.m5.importer.configparser', 'all.modules.m5.importer.generatecalcparts', 'all.modules.m5.importer.machinefactory', 'all.modules.m5.importer.stats', 'all.modules.m5.importer.translatorfactory', 'all.modules.m5.exporter', 'all.modules.mcpat', 'all.modules.mcpat.importer', 'all.modules.mcpat.importer.lexer', 'all.modules.mcpat.importer.parser', 'all.modules.mcpat.exporter', 'all.modules.mcpat.exporter.prunetree', 'all.modules.mcpat.exporter.tree2mcpat', 'all.modules.mcpat.exporter.tree2xml', ]) # Create a dict with the partrefs as key and a boolean flag as value indicating # whether debugging for that partref is enabled or disabled. DEBUG = dict((part, False) for part in DEBUGGABLE_PARTS) # This is a subset of DEBUGGABLE_PARTS which have debugging currently enabled, # i.e., for those keys in DEBUG which have a True value as value. DEBUGGED_PARTS = set() def enabled(partref): 'Check if debugging for the given partref is enabled.' return partref in DEBUGGED_PARTS def enable(partref): 'Enable debugging for partref and all children.' if DEBUG.has_key(partref): DEBUG[partref] = True else: warning("Attempt to enable debugging for non-existing part '{0}' ignored.".format(partref)) def shortref(partref): '''Return an abbreviated but unique partref. This function returns an abbreviated partref as accepted by enable_debugging_from_options that is still unique among all parts which have have debugging enabled. ''' if not partref in DEBUGGED_PARTS: bug('Cannot find partref {0} in debugged parts {1}.'.format(partref, DEBUGGED_PARTS)) parts = partref.split('.') # Iterate over all possible abbreviations, starting with the shortest (just # the last part name in the partref). The first that is unique is returned. sref = '' for part in reversed(parts): newSref = part + sref if len([p for p in DEBUGGED_PARTS if p.endswith(newSref)]) == 1: return newSref sref = '.' + newSref # No abbreviation possible, need the full name return partref def enable_debugging_from_options(partrefList): '''Parses the argument of the --debug optional argument. Iterate the colon-separated list of partrefs of --debug and enable debugging for all listed parts. To enhance the user experience it is not required that the partrefs are written out in full. Partial partrefs are allowed and if there's more than one part with that partref debugging for all of them is enabled. For example the partref 'importer' would enable debugging for all.modules.mcpat.importer and all.modules.m5.importer, but the partref 'm5.importer' enables debugging just for all.modules.m5.importer. Enabling debugging for a part implicitly enables debugging for all subparts of that part. If that is not wanted the partref can end in a '-' character, which disabled the implicit inclusion of subparts. For example modules.mcpat- enabled debugging only for the part with partref all.modules.mcpat but none of its subparts, e.g., all.modules.mcpat.importer. For even more information about parsing see the docstring of possible_matches. ''' withSubParts = filter(lambda x: not x.endswith('-'), partrefList) withoutSubParts = filter(lambda x: x.endswith('-'), partrefList) # Reset, just in case. global DEBUGGED_PARTS DEBUGGED_PARTS = set() __enable_debugging_from_options(withSubParts) update_debugged_parts(__enabled) # Now that update_debugged_parts() enabled debugging for all sub-parts, we # can set the debug flag for partrefs that should not activate debugging # for their children. We also have to remove the trailing '-' character. __enable_debugging_from_options(map(lambda x: x[:-1], withoutSubParts)) update_debugged_parts(lambda p: DEBUG.get(p, False)) if len(DEBUGGED_PARTS): print "Debugging enabled for", DEBUGGED_PARTS def __enable_debugging_from_options(partrefList): '''Set debug flag for all partrefs that end in an element of the list. This function sets the debug flag in DEBUG for any partref from DEBUGGABLE_PARTS that ends in a suffix from the `partrefList'. ''' for partref in partrefList: possibleParts = possible_matches(partref) if len(possibleParts) > 1: warning("More than one part matches '{0}': {1}".format(partref, possibleParts)) elif len(possibleParts) == 0: warning("Ignoring unknown partref '{0}'".format(partref)) for part in possibleParts: DEBUG[part] = True def possible_matches(partref): '''Returns all partrefs that end in the given shortref/partial partref. If the shortref contains a . it returns all partrefs that end in the given shortref, else the shortref must match the last component of the shortref exactly. This is to avoid, for example matching of 'modules.mcpat' and 'mcpat.exporter.tree2mcpat' with the shortref 'mcpat'. ''' if '.' in partref: f = lambda x: x.endswith(partref) else: f = lambda x: x.split('.')[-1] == partref return [part for part in DEBUGGABLE_PARTS if f(part)] def update_debugged_parts(enabled): global DEBUGGED_PARTS DEBUGGED_PARTS.update(part for part in DEBUGGABLE_PARTS if enabled(part)) def __enabled(partref): 'Check if debugging for the given partref is enabled.' parts = partref.split('.') # Iterate over all ancestors, starting with the most remote ancestor, i.e. # 'all'. ancestor = '' for part in parts: ancestor += part if DEBUG.get(ancestor, False): return True ancestor += '.' # Append a dot for next part name. return False def pp(partref, *args): 'A pretty printer for debug messages.' if not partref in DEBUGGED_PARTS: if not partref in DEBUGGABLE_PARTS: warning('debug.pp called for unknown partref {0}'.format(partref)) return args = map(str, args) # Convert args to strings (required for joining them) s = '\n'.join(args).replace('\n', '\n\t') print "{0}: {1}".format(shortref(partref), s) def caller_name(fully_qualified = True): '''Return name of caller from our caller. This helper uses Python's introspection interface to find the name of the caller from our caller. Using this function makes the intention more clear than an ugly inspect.stack()[1][3] in our caller's code. ''' if fully_qualified: return __caller_name(3) return inspect.stack()[2][3] def __caller_name(skip=2): '''Get a fully qualified name of a caller in the format module.class.method. `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exceed stack height Taken from https://gist.github.com/2151727 (License: public domain). ''' stack = inspect.stack() start = 0 + skip if len(stack) < start + 1: return '' parentframe = stack[start][0] name = [] module = inspect.getmodule(parentframe) # `modname` can be None when frame is executed directly in console # TODO(techtonik): consider using __main__ if module: name.append(module.__name__) # detect classname if 'self' in parentframe.f_locals: # I don't know any way to detect call from the object method # XXX: there seems to be no way to detect static method call - it will # be just a function call name.append(parentframe.f_locals['self'].__class__.__name__) codename = parentframe.f_code.co_name if codename != '<module>': # top level usually name.append( codename ) # function or a method del parentframe return ".".join(name)
Python
UTF-8
1,007
3.25
3
[ "MIT" ]
permissive
# # @lc app=leetcode.cn id=13 lang=python3 # # [13] 罗马数字转整数 # # @lc code=start class Solution: def romanToInt(self, s: str) -> int: map_roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} i = 0 str_len = len(s) str_list = [s[0]] sums = 0 while True: i += 1 if i == str_len: if len(str_list) > 1: sums += map_roman[str_list[1]] - map_roman[str_list[0]] else: sums += map_roman[str_list[0]] break else: if len(str_list) > 1: sums += map_roman[str_list[1]] - map_roman[str_list[0]] str_list.pop() str_list.pop() elif map_roman[str_list[0]] >= map_roman[s[i]]: sums += map_roman[str_list[0]] str_list.pop() str_list.append(s[i]) return sums # @lc code=end
Java
UTF-8
1,363
3.390625
3
[]
no_license
import java.io.*; import java.util.*; class nqueen{ public static void main(String args[])throws IOException{; System.out.println("Enter row and column"); Scanner sc = new Scanner(System.in); int row = sc.nextInt(); int col = sc.nextInt(); int matrix[][] = new int[row][col]; List<List<Cell>> answer = new ArrayList<>(); List<Cell> temp = new ArrayList<>(); int curr_row = 0; int curr_col = 0; solve_nq(row,col,answer,temp,curr_row,curr_col); System.out.println(answer); } public static void solve_nq(int row,int col,List<List<Cell>> answer,List<Cell> temp,int curr_row,int curr_col){ System.out.println(temp); if(curr_row==row){ answer.add(new ArrayList<>(temp)); } else{ for(int i=0;i<col;i++){ temp.add(new Cell(curr_row,i)); if(isSafe(temp,curr_row,i)){ solve_nq(row,col,answer,temp,curr_row+1,curr_col); } temp.remove(temp.size()-1); } } } public static boolean isSafe(List<Cell> temp,int row, int col){ int n = temp.size(); n=n-1; for(int i=0;i<n;i++){ int prev_row = temp.get(i).row; int prev_col = temp.get(i).col; if(Math.abs(prev_col-col)==0) return false; if(Math.abs(prev_row-row)-Math.abs(prev_col-col)==0) return false; } return true; } } class Cell{ int row; int col; Cell(int r,int c){ row = r; col = c; } public String toString(){ return "("+row+"-"+col+")"; } }
C#
UTF-8
1,255
2.703125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using Fungus; namespace Assets.Scripts { [CommandInfo("Custom", "InteractionTrigger", "Modifies Stance and/or Mood by specified number.")] [AddComponentMenu("")] public class InteractionTrigger : Command { [Tooltip("Current Mood enum (Good 0, Neutral 1, Bad 2)")] [VariableProperty(typeof(IntegerVariable))] [SerializeField] protected IntegerVariable mood; [Tooltip("Stance scale from -20 to 20")] [VariableProperty(typeof(IntegerVariable))] [SerializeField] protected IntegerVariable stance; [Tooltip("Amount of stance change from this interaction")] [SerializeField] protected int stanceChangeValue; [SerializeField] protected bool changeMood = false; [Tooltip("Mood to change to: Good(0) Neutral(1) Bad(2)")] [SerializeField] protected int newMood; public override void OnEnter() { if(mood != null && changeMood) { mood.Value = newMood; } if(stance != null) { stance.Value += stanceChangeValue; } Continue(); } } }
Java
UTF-8
973
2.984375
3
[]
no_license
package br.com.renato.ControleDeTurmas; import br.com.renato.utilitarios.io.Console; public class App { public static void main(String[] args) { Instituicao a1 = new Instituicao(); a1.getTurmas(); String ra, nome, codigo, nomeTurma; String opcao; do { Console.escrever("Digite o RA do aluno :"); ra = Console.ler(); Console.escrever("Digite o nome do aluno :"); nome = Console.ler(); Console.escrever("Digite o Código da Turma do aluno :"); codigo = Console.ler(); Console.escrever("Digite o nome da Turma do aluno :"); nomeTurma = Console.ler(); Console.escrever("Deseja continuar:"); opcao = Console.ler(); } while ("1".equals(opcao)); if ("1".equals(opcao)) { } else { Console.escreverln("opcao invalida:"); } } }
Python
UTF-8
1,171
2.828125
3
[]
no_license
import cv2 import matplotlib.pyplot as plt import os from mtcnn import mtcnn import time def detect_face(weights_file, image_file): """ Introduction ------------ 使用mtcnn模型检测人脸 Parameters ---------- weights_file: 模型权重文件 image_file: 检测图片文件 Returns ------- result: 检测结果 """ detector = mtcnn(weights_file) start = time.time() files = os.listdir(image_file) for file in files: print('image_file', image_file + file) image = cv2.imread(image_file + file) result = detector.detect_face(image) print('detect time: {}'.format(time.time() - start)) print(result) if len(result) > 0: for bbox in result: bounding_box = bbox['box'] cv2.rectangle(image, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),(0,155,255), 2) # plt.imshow(image) # plt.show() cv2.imwrite('./result_mtcnn/' + file , image) if __name__ == '__main__': detect_face('./mtcnn_weights.npy', './live_image/')
Java
UTF-8
1,352
2.125
2
[]
no_license
package com.kunyuesoft.dao.mapper; import java.util.List; import com.kunyuesoft.model.domain.SysDictData; /** * 字典数据Mapper接口 * * @author kunyuesoft * @date Fri Aug 13 15:27:32 CST 2021 */ public interface SysDictDataMapper { /** * 查询字典数据 * * @param dictCode 字典数据ID * @return 字典数据 */ public SysDictData selectSysDictDataById(String dictCode); /** * 查询字典数据列表 * * @param sysDictData 字典数据 * @return 字典数据集合 */ public List<SysDictData> selectSysDictDataList(SysDictData sysDictData); /** * 新增字典数据 * * @param sysDictData 字典数据 * @return 执行结果 */ public int insertSysDictData(SysDictData sysDictData); /** * 修改字典数据 * * @param sysDictData 字典数据 * @return 执行结果 */ public int updateSysDictData(SysDictData sysDictData); /** * 删除字典数据 * * @param dictCode 字典数据ID * @return 执行结果 */ public int deleteSysDictDataById(String dictCode); /** * 批量删除字典数据 * * @param dictCodes 需要删除的数据ID * @return 执行结果 */ public int deleteSysDictDataByIds(String[] dictCodes); }
Markdown
UTF-8
3,649
3.359375
3
[]
no_license
[1]: https://raw.githubusercontent.com/Geeksltd/Zebble.Docs/master/assets/automated-ui-testing/1.png ### ABOUT AUTOMATED UI TESTING ![1] User Interface test automation is a tricky practice. UI tests are an essential part of protecting your application's critical paths, and it's easy to start building them in the wrong way. **Graphical user interface testing** is a testing framework that generates user interface events such as keystrokes and mouse clicks, and observes the changes that result in the user interface, to validate that the observable behavior of the program is correct. You are lucky! Zebble framework has a fantastic feature for UI testing. You can add the NuGet package of Zebble.UITesting to your solution. #### UI Automation: Before You Even Start Welcome to the first of two articles on being successful with user interface (UI) automation. The goal of these articles is to help you start asking the right questions to begin building high-value, maintainable automation in place for your projects. Once you’re past the basics, we hope to help you find the right questions on how to evolve your testing over time to continue adding value to your project. You’ll notice we have mentioned “questions” a lot; answers, not so much. UI automation is a difficult domain to work in, and there aren’t any magic “best practices” other than one: use your brain. This short series will hopefully give you some ideas on how to look at your specific environment, and how to create a new (or tailor an existing!) automation strategy. #### Why do UI Automation in the First Place? Your first question about UI automation is one that’s too often missed: why do UI automation at all? Aren’t unit, integration, and manual/exploratory tests enough? We in the software industry don’t ask “Why?” anywhere near as often as we should. UI automation is a significant cost in your overall development cycle. It’s important you understand if it’s worth the cost before jumping in! UI automation ensures you’ve got tripwires around your most critical business value features in your system. Hopefully you’ve got a solid amount of test automation at other levels, but while unit and integration tests are critical to a system’s overall automation approach, by definition they don’t cross all boundaries of a functional slice. Teams should **not** look to UI automation as a replacement for the thousands manual test scripts they have in place. That is a painful path that’s guaranteed to lead to failure. Those manual scripts should be evaluated to understand what critical “Show me the money!” features and use cases they’re guarding. #### Goals for Automation It’s a perfectly valid question, and one your team needs to answer. As part of answering that question, get distinct goals in mind for your automation effort, such as (for example): - Increasing communication about testing across your team - Helping cut down the number of regression bugs that escape to your customers - Helping your team build what your stakeholders actually need - Freeing your testers from rote regression tests so they can do more important testing Note we never once mentioned metrics like “ensure 100% test coverage,” “create 5,000 automated test cases,” or “convert 95% of manual tests to automated.” Those are incredibly awful, horrible, nasty, smelly metrics that in my view have no place in any project. They’re extremely shallow metrics that don’t indicate the value of tests. Make your goals something that’s more effective in helping your team deliver true value to your customers.
C++
UTF-8
3,096
2.5625
3
[]
no_license
// // pixel_layer.hpp // VLImageKit // // Created by chance on 3/30/17. // Copyright © 2017 Bychance. All rights reserved. // #ifndef pixel_layer_hpp #define pixel_layer_hpp #include <stdio.h> #include "common/common.h" #include "common/pixel_layer_defines.h" namespace VLImageKit { /** PixelLayer 作为图像合成抽象图层,不支持多线程 */ class PixelLayer { public: PixelLayer(); ~PixelLayer(); /** Indicates how the content is rotation or flip while rendering. @note The operation order: original -> flip -> roration -> rendering */ void setFlipOpetions(PixelLayerFlipOptions flipOptions); inline PixelLayerFlipOptions getFlipOptions() const { return _flipOptions; } void setRotation(PixelLayerRotation rotation); inline PixelLayerRotation getRotation() const { return _rotation; } /** The frame of current layer while rendering. This property has the same meaning as UIView's frame. Excepted that its unit is PIXEL!!!. @note This property only available while layer composition */ void setFrame(VLRect frame); inline VLRect getFrame() const { return _frame; } /** This property has the same meaning as UIImageView (or View in Android) 's contentMode. It decides how the layer's content is filled while the frame's size is different from the content's size. @note This property only available while layer composition */ void setContentMode(PixelLayerContentMode contentMode); inline PixelLayerContentMode getContentMode() const { return _contentMode; } /** Set OpenGL texture buffer id and texture size (IN PIXEL!!!). */ void setTexture(GLint textureID, VLSize textureSize); inline GLint getTextureID() const { return _textureID; } inline VLSize getTextureSize() const { return _textureSize; } /** Preset framebuffer, used to custom render destination framebfuffer */ void setPresetFramebuffer(GLint framebuffer); inline GLint getPresetFramebuffer() { return _presetFramebuffer; } #pragma mark - For rendering /** Return texture coordinate data for rendering */ GLfloat *textureCoordinates(); /** Return vertex coordinate data for rendering */ GLfloat *vertexCoordinatesWithCanvasSize(VLSize canvasSize); private: GLint _textureID; VLSize _textureSize; GLint _presetFramebuffer; PixelLayerFlipOptions _flipOptions; PixelLayerRotation _rotation; VLRect _frame; PixelLayerContentMode _contentMode; GLfloat _vertexCoordinate[8]; GLfloat _textureCoordinate[8]; bool _hasFrameChanged; bool _shouldUpdateTextureCoordinate; VLSize _lastCanvasSize; /* switch texture coordinate between two points */ void switchTextureCoordinate(GLfloat *textureCoordinate, int fromPoint, int toPoint); }; } #endif /* pixel_layer_hpp */
Markdown
UTF-8
388
2.53125
3
[]
no_license
# Competition-Model-of-Two-Species-in-Population-Biology-Using-pplane This project is to simulate the behavior of 2 species living in the same environment and compete on the same food source. By running this simulation, you can get the equilibria points for the biological system and determine the competition model type whether it is a coexistence model or a survival-extinction model.
C++
UTF-8
2,403
3.625
4
[]
no_license
// SIMPLICITY ( Adding 1 to the number directly instead of convert it to base 10 adding 1 and back to base b). #include <iostream> #include <bits/stdc++.h> using namespace std; int addTwoNumberInGivenBase(int number1 ,int number2, int base){ int carry = 0; int ans = 0; int multiplier = 1; while(number1 >0 || number2 > 0 || carry >0){ int currDigitSum = 0; if(number1 > 0){ currDigitSum += (number1 % 10); number1 /= 10; } if(number2 > 0){ currDigitSum += (number2 % 10); number2 /= 10; } if(carry > 0) { currDigitSum += carry; } carry = currDigitSum / base; int currVal = currDigitSum % base; ans = multiplier * currVal + ans; multiplier *= 10; } return ans; } // function to convert interger number to alien format string convertNumberToAlienFormat(int number, string Base){ string AlienFormat; while(number>0){ int digit = number%10; AlienFormat.insert(AlienFormat.begin(), Base[digit]); number = number/10; } return AlienFormat; } int convertNumberFromAlienFormatToInteger(string num , string Base){ map<char,int> table; // storing the maping of number to symbol from the base string for(int i = 0 ; i < Base.length() ;i++){ table[Base[i]] = i; } //converting string input in AlienFormat to interger value. int NumBaseb = 0 ; for(int i=0 ; i<num.length();i++){ NumBaseb = NumBaseb * 10 + table[num[i]]; } return NumBaseb; } void succ_alien(string num, string Base){ int baseValue = Base.length(); //converting string input in AlienFormat to interger value. int NumBaseb = convertNumberFromAlienFormatToInteger(num,Base) ; cout << num <<" -> "<<NumBaseb <<" -> "; int NextNumBaseB = addTwoNumberInGivenBase( NumBaseb , 1 , baseValue); cout << NextNumBaseB <<" "; // converting this number in base b back to alien format string AnsAlienFormat = convertNumberToAlienFormat(NextNumBaseB , Base); // adding additional zero in the front if present in input. while(AnsAlienFormat.length() < num.length()){ AnsAlienFormat.insert(AnsAlienFormat.begin(),Base[0]); } cout<<AnsAlienFormat; } int main() { succ_alien("!@^&*","!@^&*"); return 0; }
JavaScript
UTF-8
1,021
2.90625
3
[]
no_license
var App_B = (function(){ var forecasts; function getForecast(){ return new Promise(function(resolve, reject){ ServerAPI.fetchForecast(function(data){ console.log('Successfully retrieved weather data', data); forecasts = data.list; resolve(); }, function(error){ console.log('Error retrieving weather data'); reject(); }); }); } function displayForecast(){ getForecast() .then(function(response){ forecasts.forEach(function(weatherObj, i){ var temp = Math.floor((weatherObj.main.temp) * 1.8 - 459.67); $('#days') .append('<div class="day"><div>' + weatherObj.dt_txt + '</div><div>' + weatherObj.weather[0].description + '</div><div>' + temp + ' degrees</div></div>'); }); }) .catch(function(error){ $('#days').append('<div class="day">Please try again later</div>'); }); } return { displayForecast: displayForecast }; })();
C++
UTF-8
606
3.15625
3
[]
no_license
#include <iostream> #include "observer.hpp" struct Foo { void print(int a, int b) { std::cout << "Foo " << a + b << std::endl; } }; struct Bar { void print(int a, int b) { std::cout << "Bar " << a + b << std::endl; } }; int main() { Events<std::function<void (int, int)>> evt; Foo foo; auto key_foo = evt.Connect( [&foo](int a, int b) { foo.print(a, b); }); Bar bar; auto key_bar = evt.Connect( [&bar](int a, int b) { bar.print(a, b); }); int a = 1, b = 2; evt.Notify(a, b); evt.Disconnect(key_foo); evt.Notify(a, b); return 0; }
Java
UTF-8
4,137
1.9375
2
[]
no_license
package com.example.wander; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.Manifest; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; public class MapFragment extends Fragment { private GoogleMap mMap; private FusedLocationProviderClient fusedLocationClient; private Location currentLocation; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_map, container, false); final SharedPreferences sharedPref = this.getActivity().getApplicationContext().getSharedPreferences("gameState", Context.MODE_PRIVATE); final Gson gson = new Gson(); SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); //use SupportMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment mapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext()); // Add a marker at all found locations String response = sharedPref.getString("objectiveList", ""); ArrayList<ObjectiveItem> objectiveItems = gson.fromJson(response, new TypeToken<List<ObjectiveItem>>(){}.getType()); for (ObjectiveItem obj: objectiveItems) { if (obj.getFound()) { LatLng temp = new LatLng(obj.getLat(), obj.getLong()); mMap.addMarker(new MarkerOptions().position(temp).title(obj.getName())); } } // TODO: Focus camera on user location LatLng blueJay = new LatLng(39.331089, -76.619615); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(blueJay,15)); //requestPermissions(FINE_LOCATION_PERMS, 1); if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); fusedLocationClient.getLastLocation() .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { currentLocation = location; //Log.d("myTag", ""+location.getLongitude()); } } }); } //mMap.setMyLocationEnabled(true); } }); return rootView; } }
Markdown
UTF-8
1,009
2.953125
3
[]
no_license
[Title]: # (Assess your risk) [Order]: # (1) ### Understand what could happen before you reveal sensitive information. (Learn about [Security Planning](umbrella://assess-your-risk/security-planning/beginner).) Sharing information that others would prefer to hide comes with potential consequences. These consequences depend on several factors. ## Who is implicated? This could include: * Employers or colleagues; * Criminal groups; * Government, military or intelligence agencies. ## What's at stake? * Will their reputation or assets be threatened as a result of exposure? * Could they try and silence or retaliate against whistleblowers? ## What could happen? Some adversaries have taken action against people who try to expose them. In some contexts, whistleblowers may be: * Fired, discredited, discriminated against, or sued; * Investigated or imprisoned; * Threatened or harmed. (Learn about [Managing Information](umbrella://information/managing-information/beginner).)
C++
GB18030
1,345
3.6875
4
[]
no_license
class MergeSort { public: int* mergeSort(int* A, int n)//տʼĺ { int *p = new int[n]; //һAһСpʱmergeArrayлõ if (!p) return NULL; mergeSort(A, 0, n - 1, p); // delete[] p; return A; } private: void mergeSort(int *A, int begin, int end, int *temp) //ֳ { if (begin<end) { int middle = (begin + end) / 2; //мλ mergeSort(A, begin, middle, temp); mergeSort(A, middle + 1, end, temp); //ֱֿٷ mergeArray(A, begin, end, middle, temp);//ϲ } } void mergeArray(int *A, int begin, int end, int mid, int *temp) { int i = begin; //a[0,10]еa[0,4]a[5,9]ϲһԪ±i,j int j = mid + 1; int end1 = mid; //һԪظֵend1,end2 int end2 = end; int k = 0; while (i <= end1 && j <= end2) //ԪؽбȽϣֵtemp { if (A[i]<A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } while (i <= end1) temp[k++] = A[i++]; //һԪʣ࣬˵ʣµĶǴˣֱӸֵtemp while (j <= end2) temp[k++] = A[j++]; for (i = 0; i<k; i++) A[begin + i] = temp[i];//tempеݸA } };
TypeScript
UTF-8
425
2.78125
3
[]
no_license
export default class Move { row: number; col: number; player: number; pointValue: number; isHighestScoring: boolean; constructor( row: number, col: number, points: number, playerId: number, isHighestScoring: boolean = false ) { this.col = col; this.row = row; this.pointValue = points; this.player = playerId; this.isHighestScoring = isHighestScoring; } }
C
UTF-8
527
3.765625
4
[]
no_license
#include<stdio.h> #define SWAP(x,y,t) ((t) = (x), (x) = (y), (y) = (t)) void permutation(char arr[], int i, int n){ int j, temp; if (i == n){ for(j=0; j<=n; j++) printf("%c", arr[j]); printf("\n"); return; } for(j=i; j<=n; j++){ SWAP(arr[i], arr[j], temp); permutation(arr, i+1, n); SWAP(arr[i], arr[j], temp); } } int main(){ char arr[] = {'a','b','c','d'}; permutation(arr, 0, 3); //arr의 0번째 원소부터 n-1번째 원소까지의 순열 }
Java
UTF-8
2,737
1.976563
2
[]
no_license
package com.example.healthguide; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; public class workout_Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_workout_); ImageView btnArm = (ImageView) findViewById(R.id.btnArm); ImageView btnLeg = (ImageView) findViewById(R.id.btnLeg); ImageView btnChest = (ImageView) findViewById(R.id.btnChest); ImageView btnBody = (ImageView) findViewById(R.id.btnBody); this.setTitle("Workout"); // btnLeg.findViewById(R.id.btnLeg); // btnChest.findViewById(R.id.btnChest); // btnBody.findViewById(R.id.btnBody); // btnArm.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(workout_Activity.this,workoutArm.class); // startActivity(intent); // } // }); // btnLeg.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(workout_Activity.this,workoutleg.class); // startActivity(intent); // } // }); // // btnChest.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(workout_Activity.this,workoutChest.class); // startActivity(intent); // } // }); // // btnBody.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(workout_Activity.this,activityWorkoutFullbody.class); // startActivity(intent); // } // }); } public void goArm(View view) { Intent intent = new Intent(workout_Activity.this, workoutArm.class); startActivity(intent); } public void goLeg(View view) { Intent intent = new Intent(workout_Activity.this, workoutleg.class); startActivity(intent); } public void goChest(View view) { Intent intent = new Intent(workout_Activity.this, workoutChest.class); startActivity(intent); } public void goBody(View view) { Intent intent = new Intent(workout_Activity.this, activityWorkoutFullbody.class); startActivity(intent); } }
Markdown
UTF-8
1,209
2.625
3
[ "MIT" ]
permissive
# MD5 File Hashing ```cs var md5 = System.Security.Cryptography.MD5.Create(); string[] imageFilePaths = System.IO.Directory.GetFiles($"./", "*.png"); foreach (string filePath in imageFilePaths) { string hashString = ""; using (var stream = System.IO.File.OpenRead(filePath)) { byte[] hashBytes = md5.ComputeHash(stream); for (int i = 0; i < hashBytes.Length; i++) hashString += hashBytes[i].ToString("X2"); } Console.WriteLine($"{hashString} {System.IO.Path.GetFileName(filePath)}"); } ``` Output: ``` FB6E91ED7B3A82002E3DE07395CCB698 01_Scatter_Sin.png 826A036491DAA617499D4CEAF562BC86 02_Scatter_Sin_Styled.png 7D4245E66993097B62DA1004F24DFCBF 03_Scatter_XY.png 455055FF41ED8C7CDB0753F0B1208E4C 04_Scatter_XY_Lines_Only.png ACCCAEE3BD1279389A60F8DC36BB7277 05_Scatter_XY_Points_Only.png C5B0652A24CAAC2EDDDB2D6408511AF2 06_Scatter_XY_Styling.png 5E38ED33B32B0BD79A0E900331F35D94 07_Point.png FE4FB28182BC179B7E08B4F804EEDA8B 08_Text.png 5DC04B0CA9E40D82C5114BC91730658E 20_Small_Plot.png 466876D94F76C33F3E95F220FE946CB8 21_Title_and_Axis_Labels.png 75813E0A2F2BE3FD18F88B4B51BE669E 22_Custom_Colors.png 50656DCC277FF318569D27A597A71934 23_Frameless.png ```
Java
UTF-8
1,327
2.765625
3
[]
no_license
package com.app.apprfid.asciiprotocol.enumerations; import java.util.HashMap; public class AlertDuration extends EnumerationBase { public static final AlertDuration LONG = new AlertDuration("lon", "A long duration"); public static final AlertDuration MEDIUM = new AlertDuration("med", "A medium duration "); public static final AlertDuration NOT_SPECIFIED = null; public static final AlertDuration SHORT = new AlertDuration("sho", "A short duration"); public static final AlertDuration[] PRIVATE_VALUES = {NOT_SPECIFIED, SHORT, MEDIUM, LONG}; private static HashMap parameterLookUp; private AlertDuration(String str, String str2) { super(str, str2); if (parameterLookUp == null) { parameterLookUp = new HashMap(); } parameterLookUp.put(str, this); } public static final AlertDuration Parse(String str) { String trim = str.trim(); if (parameterLookUp.containsKey(trim)) { return (AlertDuration) parameterLookUp.get(trim); } throw new IllegalArgumentException(String.format("'%s' is not recognised as a value of %s", new Object[]{str, AlertDuration.class.getName()})); } public static final AlertDuration[] getValues() { return PRIVATE_VALUES; } }
C++
UTF-8
354
3.359375
3
[]
no_license
#include<iostream> using namespace std; int main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number variable cout<<"Address of p variable is \n"<<p; p=p+3; //adding 3 to pointer variable cout<<"\n After adding 3: Address of p variable is \n"<<p; return 0; }
C++
UTF-8
715
3.125
3
[ "MIT" ]
permissive
#include "token.h" namespace libtoken { void token::clear(char new_parts_separator) { parts_separator = new_parts_separator; parts.clear(); } token::Type token::get_type() const { if (parts.size() == 0) // empty token return token::Type::Undefined; if (parts.size() > 1) // token consists of more than one part return token::Type::Multipart; if (parts[0].type == token_part::Type::Text) // token consists of one text part return token::Type::Text; if (parts[0].type == token_part::Type::EOL) // token consists of one part with newline character return token::Type::EOL; return token::Type::Atomic; // single-part token without any special meanings } }
Java
UTF-8
1,386
3.0625
3
[]
no_license
package com.kodilla.good.patterns.challenges.submodule2; import java.util.HashMap; import java.util.stream.Collectors; public class Order { private Customer customer; private HashMap<Product, Integer> productList; private String delivery; private Double toPay; private boolean isPrepared = false; public Order() { } public Order(Customer customer, HashMap<Product, Integer> productList, String delivery) { this.customer = customer; this.productList = productList; this.delivery = delivery; this.toPay = new Payment().calculatePayment(productList, delivery); } public Double getToPay() { return toPay; } public HashMap<Product, Integer> getProductList() { return productList; } public Customer getCustomer() { return customer; } public String getDelivery() { return delivery; } public void setCustomer(Customer customer) { this.customer = customer; } public boolean isPrepared() { return isPrepared; } public void setPrepared(boolean prepared) { isPrepared = prepared; } @Override public String toString() { String mapAsString = productList.entrySet().stream() .map(key -> key + "=" + productList.get(key)) .collect(Collectors.joining(", ", "{", "}")); return "Order{" + "customer=" + customer.toString() + "\n productList=" + mapAsString + "\n delivery='" + delivery + '\'' + "\n toPay=" + toPay + '}'; } }
Java
UTF-8
618
2.5
2
[]
no_license
package fr.arolla.core; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class InMemoryPlayersTest { private InMemoryPlayers players = new InMemoryPlayers(); @Test public void should_reset_score__even_with_username_containing_uppercase_letter() { players.add(new Player("Luigi", "password", "http://somewh.ere")); players.addCash("Luigi", 100.0d); assertThat(players.findByName("Luigi").get().cash()).isEqualTo(100.0d); players.resetScore("Luigi"); assertThat(players.findByName("Luigi").get().cash()).isEqualTo(0.0d); } }
C#
UTF-8
354
3.0625
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace LeetCode.AskGif.Easy.String { public class FindLUSlengthSoln { public int FindLUSlength(string a, string b) { if (a == b) return -1; else return Math.Max(a.Length, b.Length); } } }
C
UTF-8
4,793
3.1875
3
[ "BSD-2-Clause" ]
permissive
/* * Generate a 'good enough' gaussian random variate. * based on central limit thm , this is used if better than * achipolis projection is needed */ double randn() { int i; float s = 0.0; for(i = 0;i<6; i++)s+=((float)rand())/RAND_MAX; return s - 3.0; } /* *print @size values of an integer vector @v */ inline void printVecI(unsigned char* v,int size){ unsigned char i = 0; for(;i<size;i++){ printf("%i",v[i]); if(i<size-1)printf(",",v[i]); } printf("\n"); } /* *print @size values of an float vector @v */ inline void printVecF(float* v,int size){ unsigned char i = 0; for(;i<size;i++){ printf("%.2f",v[i]); if(i<size-1)printf(",",v[i]); } printf("\n"); } /* * print the binary expansion of a long integer. output ct * sets of grsize bits. For golay and hexacode set grsize * to 4 bits, for full leech decoding with parity, set grsize * to 3 bits */ static void print(unsigned long ret,int ct,int grsize){ int i,j,err; for(i=0;i<ct;i++) { for(j=0;j<grsize;j++) { printf("%d",ret&1); //err +=ret&1; ret=ret>>1; } printf(" "); } //if(err%2) printf("error \n");else printf("\n"); } int weight(unsigned long u){ int ret = 0; while(u>0) { if(u&1 == 1)ret++; u = (u>>1); } return ret; } /* * Create a random float vector @r of length @len and * @sparseness */ void genRandomVector(int len,float sparesness,float* r) { while(len>0){ if(((float)rand())/((float)RAND_MAX)< sparesness) r[len-1]=2.0*((float)rand())/RAND_MAX-1.0; else r[len-1]=0.0; len--; } } /* * Lets prove we are not accidentally finding clusters. */ void shuffle(float* M,int dim,int len) { int j,i = 0; for(;i<len;i++) { int r = rand()/RAND_MAX; for(j = 0;j<dim;j++) { float temp = M[r*dim+j]; M[r*dim+j] = M[i*dim+j]; M[i*dim+j] = temp; // xor swap /* M[r*dim+j] ^= M[i*dim+j] ; M[i*dim+j] ^= M[r*dim+j]; M[r*dim+j] ^= M[i*dim+j] ; */ } } } /* * Create a scaled histogram for the counts data * inx and the indexed data iny. b is the number of * buckets, and len is the length of iny and inx. */ float histogram(int b, int len, float* inx,float* iny) { int i,j; float max = -RAND_MAX; float min = RAND_MAX;//big number int* cts = malloc(sizeof(int)*b); float * out =malloc(sizeof(float)*b); //initialize output for (i=0;i<b; i++) { cts[i]=0; out[i]=0; } for (i=0;i<len; i++) { if(inx[i]>max)max =(float) inx[i]; if(inx[i]<min)min =(float) inx[i]; } float wsize = ((float)max-min) /((float) b); for (i=0;i<len; i++) { j = 0; while(j+1<b && inx[i] > min+wsize*j)j++; out[j] += (float)iny[i]; cts[j]++; } //scale averages for (i=0;i<b; i++) if(cts[i]!=0)out[i]=out[i]/((float)cts[i]); printVecF(out,b); for (i=0;i<b; i++)printf("%.0f, ",wsize*i);printf("\n"); return wsize; } int listSearchAndAdd(unsigned long query, unsigned long* list,int len) { list[len]=query; while(--len) if(list[len]==query) return len; return len; } /* * Return the index of the nearest neighbor to vector v */ int NN(float* v, float*M,int dim,int len) { int i,j = 0; float dist = 0.0f; int argmin = 0; float min = 10000.0f; float* q; for(;j<len;j++) { dist =0.0f; q = &M[j*dim]; for (i=0;i<dim;i++) { dist += (v[i]- q[i]) *(v[i]- q[i]) ; } if(dist<min){ min = dist; argmin = j; } } return argmin; } /* * generate random centers */ float * generateRandomCenters(int d,int clu) { int i; float *clusterCenters =(float*) malloc(sizeof(float)*d*clu); for (i=0;i<clu;i++){ genRandomVector(d,1.0,&clusterCenters[i*d]); } return clusterCenters; } /* * Very optimized Gaussian random cluster generator */ float* generateGaussianClusters(int part,int d,int clu,float* clusterCenters){//, float *clusterCenters){//, float *ret){ float *ret = (float*)malloc(sizeof(float*)*d*part*clu); int i,j,k; for (i=0;i<clu;i++){ //must be positive and near 1, around .1 , higher numbers results in data out of range ~(-1:1) float variance = .1;//*((float)rand())/RAND_MAX; float* ct = &clusterCenters[i*d]; //these are the partitions for(j = 0;j<part;j++) { //these are the individual vectors for( k=0;k<d;k++) { float pts = (randn()*4.0); ret[i*part*d +j*d+k]= (pts*variance+ ct[k]); } } } return ret; }
Java
UTF-8
741
3.375
3
[]
no_license
package cn.design.pattern.op; import java.util.ArrayList; import java.util.List; public class Turtle implements Observable { private List<Observer> observerList = new ArrayList<Observer>(); public void hungry() { this.notifyObservers("我饿了!"); } @Override public void addObserver(Observer observer) { observerList.add(observer); } @Override public void removeObserver(Observer observer) { if (observerList != null && observerList.contains(observer)) { observerList.remove(observer); } } @Override public void notifyObservers(String info) { for (Observer observer : observerList) { observer.feed(info); } } }
C++
UTF-8
8,579
2.59375
3
[ "Apache-2.0" ]
permissive
// // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "zetasql/public/numeric_parser.h" #include <cstdint> #include "zetasql/common/multiprecision_int.h" #include "zetasql/public/numeric_constants.h" #include "absl/status/status.h" #include "absl/strings/ascii.h" #include "zetasql/base/status_builder.h" namespace zetasql { #define RETURN_FALSE_IF(x) \ if (ABSL_PREDICT_FALSE(x)) return false struct ENotationParts { bool negative = false; absl::string_view int_part; absl::string_view fract_part; absl::string_view exp_part; }; bool SplitENotationParts(absl::string_view str, ENotationParts* parts) { const char* start = str.data(); const char* end = str.data() + str.size(); // Skip whitespace. for (; start < end && (absl::ascii_isspace(*start)); ++start) { } for (; start < end && absl::ascii_isspace(*(end - 1)); --end) { } // Empty or only spaces RETURN_FALSE_IF(start == end); *parts = ENotationParts(); parts->negative = (*start == '-'); start += (*start == '-' || *start == '+'); for (const char* c = end; --c >= start;) { if (*c == 'e' || *c == 'E') { parts->exp_part = absl::string_view(c + 1, end - c - 1); RETURN_FALSE_IF(parts->exp_part.empty()); end = c; break; } } for (const char* c = start; c < end; ++c) { if (*c == '.') { parts->fract_part = absl::string_view(c + 1, end - c - 1); end = c; break; } } parts->int_part = absl::string_view(start, end - start); return true; } // Parses <exp_part> and add <extra_scale> to the result. // If <exp_part> represents an integer that is below int64min, the result is // int64min. // If <exp_part> represents an integer that is above int64max, the result is // int64max. bool ParseExponent(absl::string_view exp_part, uint extra_scale, int64_t* exp) { *exp = extra_scale; if (!exp_part.empty()) { FixedInt<64, 1> exp_fixed_int; if (ABSL_PREDICT_TRUE(exp_fixed_int.ParseFromStringStrict(exp_part))) { RETURN_FALSE_IF(exp_fixed_int.AddOverflow(*exp)); *exp = exp_fixed_int.number()[0]; } else if (exp_part.size() > 1 && exp_part[0] == '-') { // Still need to check whether exp_part contains only digits after '-'. exp_part.remove_prefix(1); for (char c : exp_part) { RETURN_FALSE_IF(!std::isdigit(c)); } *exp = std::numeric_limits<int64_t>::min(); } else { for (char c : exp_part) { RETURN_FALSE_IF(!std::isdigit(c)); } *exp = std::numeric_limits<int64_t>::max(); } } return true; } // PowersAsc<Word, first_value, base, size>() returns a std::array<Word, size> // {first_value, first_value * base, ..., first_value * pow(base, size - 1)}. template <typename Word, Word first_value, Word base, int size, typename... T> constexpr std::array<Word, size> PowersAsc(T... v) { if constexpr (sizeof...(T) < size) { return PowersAsc<Word, first_value, base, size>(first_value, v * base...); } else { return std::array<Word, size>{v...}; } } // Parses <int_part>.<fract_part>E<exp> to FixedUint. // If <strict> is true, treats the input as invalid if it does not represent // a whole number. If <strict> is false, rounds the input away from zero to a // whole number. Returns true iff the input is valid. template <int n> bool ParseNumber(absl::string_view int_part, absl::string_view fract_part, int64_t exp, bool strict, FixedUint<64, n>* output) { *output = FixedUint<64, n>(); bool round_up = false; if (exp >= 0) { // Promote up to exp fractional digits to the integer part. size_t num_promoted_fract_digits = fract_part.size(); if (exp < fract_part.size()) { round_up = fract_part[exp] >= '5'; num_promoted_fract_digits = exp; } absl::string_view promoted_fract_part(fract_part.data(), num_promoted_fract_digits); fract_part.remove_prefix(num_promoted_fract_digits); if (int_part.empty()) { RETURN_FALSE_IF(!output->ParseFromStringStrict(promoted_fract_part)); } else { RETURN_FALSE_IF( !output->ParseFromStringSegments(int_part, {promoted_fract_part})); int_part = absl::string_view(); } // If output is zero, avoid scaling. if (!output->is_zero()) { // If exp is greater than the number of promoted fractional digits, // scale the result up by pow(10, exp - num_promoted_fract_digits). size_t extra_exp = static_cast<size_t>(exp) - num_promoted_fract_digits; for (; extra_exp >= 19; extra_exp -= 19) { RETURN_FALSE_IF(output->MultiplyOverflow(internal::k1e19)); } if (extra_exp != 0) { static constexpr std::array<uint64_t, 19> kPowers = PowersAsc<uint64_t, 1, 10, 19>(); RETURN_FALSE_IF(output->MultiplyOverflow(kPowers[extra_exp])); } } } else { // exp < 0 RETURN_FALSE_IF(int_part.size() + fract_part.size() == 0); // Demote up to -exp digits from int_part if (exp >= static_cast<int64_t>(-int_part.size())) { size_t int_digits = int_part.size() + exp; round_up = int_part[int_digits] >= '5'; RETURN_FALSE_IF(int_digits != 0 && !output->ParseFromStringStrict( absl::string_view(int_part.data(), int_digits))); int_part.remove_prefix(int_digits); } } // The remaining characters in int_part and fract_part have not been visited. // They represent the fractional digits to be discarded. In strict mode, they // must be zeros; otherwise they must be digits. if (strict) { for (char c : int_part) { RETURN_FALSE_IF(c != '0'); } for (char c : fract_part) { RETURN_FALSE_IF(c != '0'); } } else { for (char c : int_part) { RETURN_FALSE_IF(!std::isdigit(c)); } for (char c : fract_part) { RETURN_FALSE_IF(!std::isdigit(c)); } } RETURN_FALSE_IF(round_up && output->AddOverflow(uint64_t{1})); return true; } #undef RETURN_FALSE_IF template <uint32_t word_count, uint32_t scale, bool strict_parsing> absl::Status ParseNumber(absl::string_view str, FixedPointRepresentation<word_count>& parsed) { ENotationParts parts; int64_t exp; if (ABSL_PREDICT_TRUE(SplitENotationParts(str, &parts)) && ABSL_PREDICT_TRUE(ParseExponent(parts.exp_part, scale, &exp)) && ABSL_PREDICT_TRUE(ParseNumber(parts.int_part, parts.fract_part, exp, strict_parsing, &parsed.output))) { parsed.is_negative = parts.negative; return absl::OkStatus(); } return ::zetasql_base::InvalidArgumentErrorBuilder() << "Failed to parse " << str << " . word_count: " << word_count << " scale: " << scale << " strict_parsing: " << strict_parsing; } template <bool strict_parsing> absl::Status ParseNumeric(absl::string_view str, FixedPointRepresentation<2>& parsed) { return ParseNumber<2, 9, strict_parsing>(str, parsed); } template <bool strict_parsing> absl::Status ParseBigNumeric(absl::string_view str, FixedPointRepresentation<4>& parsed) { return ParseNumber<4, 38, strict_parsing>(str, parsed); } absl::Status ParseJSONNumber(absl::string_view str, FixedPointRepresentation<79>& parsed) { return ParseNumber<79, 1074, true>(str, parsed); } // Explicit template instantiations for NUMERIC template absl::Status ParseNumeric</*strict_parsing=*/true>( absl::string_view str, FixedPointRepresentation<2>& parsed); template absl::Status ParseNumeric</*strict_parsing=*/false>( absl::string_view str, FixedPointRepresentation<2>& parsed); // Explicit template instantiations for BIGNUMERIC template absl::Status ParseBigNumeric</*strict_parsing=*/true>( absl::string_view str, FixedPointRepresentation<4>& parsed); template absl::Status ParseBigNumeric</*strict_parsing=*/false>( absl::string_view str, FixedPointRepresentation<4>& parsed); } // namespace zetasql
C
UTF-8
406
2.828125
3
[]
no_license
#include<stdio.h> #include<stdlib.h> char * command_str; int kernel_enabled = 1; void command_parser(char * x){ if(x == "help"){ printf("%s", "-help: previews this screen..."); } } void commands(){ printf("%s", "<C:/>"); scanf("%s", command_str); command_parser(command_str); } int main(){ while(kernel_enabled == 1) { commands(); } return 0; }
Java
UTF-8
366
2.046875
2
[]
no_license
package kakao.pay.test.invest.interfaces; import java.util.List; /** * 투자정보 조회 서비스. */ public interface InvestProductReceiptService { /** * userId와 일치하는 투자정보들을 리턴합니다. * @param userId 사용자 식별값 * @return 투자정보 목록 */ List<InvestProductReceipt> findAllByUserId(long userId); }
PHP
UTF-8
498
2.703125
3
[]
no_license
<?php session_start(); if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang']; } else { if(!isset($_SESSION['lang'])){ $_SESSION['lang'] = "en-en"; } } switch ($_SESSION['lang']) { case "en-en": include_once('assets/lang/en-en.php'); break; case "de-de": include_once('assets/lang/de-de.php'); break; default: include_once('assets/lang/en-en.php'); break; } function setHtmlLang() { if ($_SESSION['lang']) { echo $_SESSION['lang']; } else { echo "de-de"; } } ?>
Java
UTF-8
833
2.78125
3
[]
no_license
/** * Copyright (C), 2015-2018, XXX有限公司 FileName: Person Author: byron Date: 2018/8/6 14:02 * Description: History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.example.demo.other; public class Person { public String str = "22"; private String name; private Integer age; public Object getSon(){ Son son = new Son(); son.setAge(12); return son; } public String getName() { return name; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
PHP
UTF-8
3,897
2.515625
3
[]
no_license
<?php /** * 主贴评论类,针对ebh_revert表 */ class RevertModel extends CModel{ /** *根据参数条件获取主贴评论评论列表 *@param array $param *@return array */ public function getList($param = array()){ $sql = 'select p.subject,u.username,r.*,c.crname from ebh_revert r left join ebh_classrooms c on r.cid = c.crid left join ebh_posts p on r.postsid = p.postsid left join ebh_users u on r.uid = u.uid '; $whereArr = array(); if(!empty($param['searchkey'])){ $whereArr[]=' r.rcontent like \'%'.$param['searchkey'].'%\' '.' or p.subject like \'%'.$param['searchkey'].'%\' '.' or u.username like \'%'.$param['searchkey'].'%\' '.' or c.crname like \'%'.$param['searchkey'].'%\' '; } if(strlen($param['status'])==1){ $whereArr[]=' r.status = '.intval($param['status']); } if(!empty($param['begintime'])){ $whereArr[]=' r.rtime > '.strtotime($param['begintime']); } if(!empty($param['endtime'])){ $whereArr[]=' r.rtime < '.strtotime($param['endtime']); } if(!empty($whereArr)){ $sql.=' WHERE '.implode(' AND ',$whereArr); } if(!empty($param['order'])){ $sql.=' order by '.$param['order']; } if(!empty($param['limit'])){ $sql.= ' limit '.$param['limit']; } return $this->db->query($sql)->list_array(); } /** *根据参数条件获取主贴评论条数 *@param array $param *@return int */ public function getListCount($param = array()){ $sql = 'select count(*) count from ebh_revert r left join ebh_classrooms c on r.cid = c.crid left join ebh_posts p on r.postsid = p.postsid left join ebh_users u on r.uid = u.uid '; $whereArr = array(); if(!empty($param['searchkey'])){ $whereArr[]=' r.rcontent like \'%'.$param['searchkey'].'%\' '.' or p.subject like \'%'.$param['searchkey'].'%\' '.' or u.username like \'%'.$param['searchkey'].'%\' '.' or c.crname like \'%'.$param['searchkey'].'%\' '; } if(strlen($param['status'])==1){ $whereArr[]=' r.status = '.intval($param['status']); } if(!empty($param['begintime'])){ $whereArr[]=' r.rtime > '.strtotime($param['begintime']); } if(!empty($param['endtime'])){ $whereArr[]=' r.rtime < '.strtotime($param['endtime']); } if(!empty($whereArr)){ $sql.=' WHERE '.implode(' AND ',$whereArr); } $res = $this->db->query($sql)->row_array(); return $res['count']; } /** *编辑单条主贴评论内容 *@param array $param *@param array $where *@return bool *$param为键值对,键对表的字段,值代表该字段将要被修改成的值 *$where为键值对,键表示表的字段,值表示该字段的值 */ public function _update($param=array(),$where=array()){ if(empty($where)){ return false; } if($this->db->update('ebh_revert',$param,$where)!=-1){ return true; }else{ return false; } } /** *删除单条主贴评论记录 *@param array $param *@return bool *$where为键值对,键表示表的字段,值表示该字段的值 */ public function _delete($param = array()){ if(empty($param)){ return false; } $res = $this->db->delete('ebh_revert',$param); if($res==-1){ return fasle; }else{ return true; } } /** *根据传入的revertid获取单条主贴评论记录 *@param int $rid *@return array */ public function getOnerevert($rid=0){ $rid = intval($rid); if($rid==0){ return array(); }else{ $sql = 'select r.*,p.subject,p.content,c.crname,u.username as username, uu.username as teacher from ebh_revert r left join ebh_classrooms c on r.cid = c.crid left join ebh_users u on c.uid = u.uid left join ebh_users uu on c.uid = uu.uid left join ebh_posts p on p.postsid = r.postsid where r.rid = '.$rid.' limit 1 '; return $this->db->query($sql)->row_array(); } } } ?>
Go
UTF-8
428
3.140625
3
[ "MIT" ]
permissive
package validator import "strconv" // Range validator type Range struct { Min int Max int } // Check a param within a range func (r Range) Check(param string) (int, bool) { if isBlank(param) { return 0, true } v, err := strconv.Atoi(param) return v, err == nil && !(v < r.Min) && !(v > r.Max) } // Validate for Validator interface func (r Range) Validate(param string) bool { _, ok := r.Check(param) return ok }
Java
UTF-8
2,820
2.390625
2
[]
no_license
package ch.heigvd.wns.security; import ch.heigvd.wns.security.jwt.JWTAuthenticationFilter; import ch.heigvd.wns.security.jwt.JWTLoginFilter; import ch.heigvd.wns.security.jwt.UserDetailsServiceImp; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * The JWT configuration are inspired by an excellent article: https://dzone.com/articles/securing-spring-boot-with-jwts */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { return new UserDetailsServiceImp(); }; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }; @Override protected void configure(HttpSecurity http) throws Exception { // disable caching http.headers().cacheControl(); http.csrf().disable() // disable csrf for our requests. .authorizeRequests() .antMatchers("/").permitAll() .antMatchers(HttpMethod.POST,"/users/signin").permitAll() .antMatchers(HttpMethod.POST,"/users/signup").permitAll() .antMatchers(HttpMethod.GET, "/books/{\\d+}/pdf").permitAll() .anyRequest().authenticated() .and() // We filter the api/login requests .addFilterBefore(new JWTLoginFilter("/users/signin", authenticationManager()), UsernamePasswordAuthenticationFilter.class) // And filter other requests to check the presence of JWT in header .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception{ auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder()); // Create a default account //auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); /* auth.inMemoryAuthentication() .withUser("admin") .password("password") .roles("ADMIN");*/ } }
Java
UTF-8
256
1.742188
2
[]
no_license
package gov.nist.csd.pm.policy.model.graph.relationships; import gov.nist.csd.pm.policy.exceptions.PMException; public class InvalidAssignmentException extends PMException { public InvalidAssignmentException(String msg) { super(msg); } }
PHP
UTF-8
780
2.78125
3
[]
no_license
<?php error_reporting(E_ALL); ini_set("display_errors", 1); $mysqli = new mysqli("mysql.eecs.ku.edu", "willthomas", "ANahy9ui", "willthomas"); $userId = $_POST["userId"]; if ($mysqli->connect_error) { die("Connect Failed: ". $mysqli->connect_error); } $checkQuery = "select * from Users where user_id = \"$userId\";"; $insertQuery = "INSERT INTO Users (user_id) values (\"$userId\");"; $result = $mysqli->query($checkQuery); echo "<h1>Database Response</h1>"; if ($result->fetch_row()[0]) { // Already in DB echo "<h3>User '". $userId . "' Already in the Database, cannot duplicate users</h3>"; } else { $mysqli->query($insertQuery); echo "<h3>Successfull Inserted '" . $userId . "' into Database</h3>"; } $result->free(); $mysqli->close(); ?>
C++
UTF-8
2,221
3.234375
3
[]
no_license
/* * Item.cpp * * Created on: Dec 7, 2016 * Author: lai61 */ #include "Item.h" #include <iostream> namespace std { Item::Item(rapidxml::xml_node<> *item) { // TODO Auto-generated constructor stub xml_node<>* elements = item->first_node(); turnon_flag = false; while(elements != NULL) { if(string(elements->name()) == "name") { name = string(elements->value()); } if(string(elements->name()) == "status") { status = string(elements->value()); } if(string(elements->name()) == "description") { description = string(elements->value()); } if(string(elements->name()) == "writing") { writing = string(elements->value()); } if(string(elements->name()) == "turnon") { turnon_flag = true; xml_node<>* sub_element = elements->first_node(); while(sub_element!= NULL) { if(string(sub_element->name()) == "print") { turnon.print = string(sub_element->value()); } if(string(sub_element->name()) == "action") { turnon.action = string(sub_element->value()); } sub_element = sub_element->next_sibling(); } } if(string(elements->name()) == "trigger") { Triggers *new_tigger = new Triggers(elements); trigger.push_back(new_tigger); } elements = elements->next_sibling(); } } Item::~Item() { // TODO Auto-generated destructor stub } void Item::print_item() { cout << "item------------------" <<endl; cout << "name:" << name <<endl; cout << "status:" << status <<endl; cout << "description:" << description <<endl; cout << "writing:" << writing <<endl; cout << "Turn on" <<endl; cout << "print:" << turnon.print <<endl; cout << "action:" << turnon.action <<endl; for(unsigned int i = 0; i < trigger.size(); i++) { trigger[i]->print_trigger(); } } string Item::get_name() { return name; } void Item::read_writing() { if(writing.empty()) { cout << "Nothing written" <<endl; } else { cout << writing <<endl; } } bool Item::get_turnon_flag() { return turnon_flag; } Turnon Item::get_turn_on() { return turnon; } void Item::set_status(string new_status) { status = new_status; } string Item::get_status() { return status; } vector<Triggers*> Item::get_trigger() { return trigger; } }
Rust
UTF-8
3,160
3.265625
3
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::cmp::Ordering; use crate::common::math; use cgmath::{InnerSpace, Vector2, Vector3}; // TODO: make this a cvar const SUBDIVIDE_SIZE: f32 = 32.0; /// Subdivide the given polygon on a grid. /// /// The algorithm is described as follows: /// Given a polygon *P*, /// 1. Calculate the extents *P*min, *P*max and the midpoint *P*mid of *P*. /// 1. Calculate the distance vector *D*<sub>i</sub> for each *P*<sub>i</sub>. /// 1. For each axis *A* = [X, Y, Z]: /// 1. If the distance between either *P*min<sub>A</sub> or /// *P*max<sub>A</sub> and *P*mid<sub>A</sub> is less than 8, continue to /// the next axis. /// 1. For each vertex *v*... /// TODO... pub fn subdivide(verts: Vec<Vector3<f32>>) -> Vec<Vector3<f32>> { let mut out = Vec::new(); subdivide_impl(verts, &mut out); out } fn subdivide_impl(mut verts: Vec<Vector3<f32>>, output: &mut Vec<Vector3<f32>>) { let (min, max) = math::bounds(&verts); let mut front = Vec::new(); let mut back = Vec::new(); // subdivide polygon along each axis in order for ax in 0..3 { // find the midpoint of the polygon bounds let mid = { let m = (min[ax] + max[ax]) / 2.0; SUBDIVIDE_SIZE * (m / SUBDIVIDE_SIZE).round() }; if max[ax] - mid < 8.0 || mid - min[ax] < 8.0 { // this component doesn't need to be subdivided further. // if no components need to be subdivided further, this breaks the loop. continue; } // collect the distances of each vertex from the midpoint let mut dist: Vec<f32> = verts.iter().map(|v| (*v)[ax] - mid).collect(); dist.push(dist[0]); // duplicate first vertex verts.push(verts[0]); for (vi, v) in (&verts[..verts.len() - 1]).iter().enumerate() { // sort vertices to front and back of axis let cmp = dist[vi].partial_cmp(&0.0).unwrap(); match cmp { Ordering::Less => { back.push(*v); } Ordering::Equal => { // if this vertex is on the axis, split it in two front.push(*v); back.push(*v); continue; } Ordering::Greater => { front.push(*v); } } if dist[vi + 1] != 0.0 && cmp != dist[vi + 1].partial_cmp(&0.0).unwrap() { // segment crosses the axis, add a vertex at the intercept let ratio = dist[vi] / (dist[vi] - dist[vi + 1]); let intercept = v + ratio * (verts[vi + 1] - v); front.push(intercept); back.push(intercept); } } subdivide_impl(front, output); subdivide_impl(back, output); return; } // polygon is smaller than SUBDIVIDE_SIZE along all three axes assert!(verts.len() >= 3); let v1 = verts[0]; let mut v2 = verts[1]; for v3 in &verts[2..] { output.push(v1); output.push(v2); output.push(*v3); v2 = *v3; } }
Markdown
UTF-8
14,325
3.796875
4
[]
no_license
# REACT with Traversy Media <b>React</b> is a javascript library which is actually seen as a framework by a lot of devs due to the way it is used to handle multiple tasks relevant to the whole dev process. A react app is created on-the-go with some boilerplate code using `npx create-react-app *directory_name*` The main page of the whole website is the index.html by default. There is a div there that has an id of root. This element shall hold all the content of the website. The content is created in react and rendered in the HTML within the index.js file using ReactDOM.render(). ## Components In React, everything on the webpage is represented by a component. So each todo element is a component, just as the container element for all the todos is also a component, just as everything on the page is in a containing component. So first of all, to display something on the webpage, find the index.js file. It controls what is inserted into the index.html file which is rendered as our SPA. The index.html file contains a div with id="root". It is in this div that the components to be rendered are inserted. A component can be created using a class or function definition. For both cases you need to import React and Component from the react module. <br>`import React, {Component} from 'react'`<br> Then, the class way: ``` js /* Could've been class App extends React.Component{} */ class App extends Component { render() { return( // HTML (actually, jsx) to be rendered in browser ); } } ``` The return block contains JSX, which is similar to Jinja (Jinja template engine) for Flask. JSX allows JavaScript code to be written with HTML easily using `{}` to represent the JSX. Class components have methods called `lifecylce methods`. These are called at different stages from the point the component is being loaded to rendering. Among them are `render` and `componentDidMount` which we would see later. ## States *React states* are used to define qualities or properties that can be modified dynamically and used by components to make the application more interactive. To define states in '*classy*' components, we just define variable in the component definition. After defining a state, it can be passed <span style="background-color: rgba(255,255,255,0.2); padding: 1px 2px; border-radius: 10%">down</span> to other components by passing them as `props`. ``` js class Comp extends React.Component{ state = { text: "hello" } render() { return( <div> <ImportedComponent propName={this.state.text}/> </div> ); } } ``` To access the passed on state within the receiving component, it is referenced within the component as `this.props.propName`. For the todo app we create the main App component. Then we create a Todos component which should contain all the todos. Then the TodoItem component represents each todo. A state is defined within the App component to contain the list(Array) of todo items. The state is placed there so that it can be accessed by the Todos and TodoItem components as well. So the App component contains the Todos component which contains the TodoItem component. The todos are passed down from the state of the App component to the Todos component as a prop named `todos`. Then to pass individual todo items from the Todos component to the TodoItem component, we need to loop through the Array of todos. Then we pass each individual todo as a prop, including its key(recommended). ``` js class Todos extends React.Component { render() { const todos = this.props.todos; let arr = []; todos.forEach(todo => { arr.push(<TodoItem key={todo.id} todo={todo} toggleComplete={this.props.toggleComplete}/>); }); return arr } } ``` A much simpler way of doing the same thing is to call the `map` function off the array of todos. `map` is part of some funcitons known as higher-order functions in JS. `Array.map` just takes an array, modifies each element using the callback function passed as an argument, then returns the modified array. ``` js class Todos extends React.Component { render() { return this.props.todos.map((todo) => ( <TodoItem key={todo.id} todo={todo} toggleComplete={this.props.toggleComplete} /> )); } } ``` ## Proptypes PropTypes help identify the props of a component. To define the prototype of a component, we first need to: `import PropTypes from 'prop-types';` Then the actual definition is done outside the component's own definition: ```js /* SYNTAX componentName.propTypes = { propName: PropTypes.propDataType.isRequired } */ // EXAMPLE Todos.propTypes = { todo: PropTypes.Array.isRequired } ``` ## Styling with CSS in React To style within a component's definition you can simply add the style attribute to the HTML element that should be styled, within the render's return method. The value of the style attribute should be enclosed within double curly braces. ```js <div style={{ property1Name: value, property2Name: value }}> </div> ``` Remember its JSX. We can also pass a variable or a function(a method of the component's class) which returns the styles as an Object instead. And in that case, only one set of curly braces is needed since an Object is returned by the function (the Object has its own set of curly braces). ```js // Method Within Component Class Definition myComponentStyles = () => { return { propertyOne: 'value', propertyTwo: 'value', propertyThree: 'value', } } // return value of component's render method render () { return( <div style={ this.myComponentStyles() }> </div> ) } ``` ## Toggling Todo Complete Now, we need to update the state of our todos upon clicking on the checkboxes to toggle them as completed or not. So we add an eventlistener to the checkbox, within the TodoItem component, which calls a function, passed as a prop from our App component where the state is defined. To target the actual todo item which needs its state modified, the toggleComplete funciton has a parameter which represent's the todo item's id. ```js // Doing this will call the toggleComplete function for all todo items immediately the page loads <input type="checkbox" onChange={this.props.toggleComplete(this.props.todo.id)} /> // to fix the problem above, we need to use `bind` <input type="checkbox" onChange={this.props.toggleComplete.bind(this, this.props.todo.id)} /> ``` ### What does bind do? It allows a single function to be defined somewhere, then have its `this` keyword represent the first argument passed in as the first argument to `bind`. So it kind of creates another function out of an already defined function. This new function possesses the same parameters. The difference is that the new function is bound to the object which is passed in as the first argument to `bind`. ```js ``` So to actually change the state, within the toggleComplete method, we use `setState` which is a built in method of components. `setState` modifies the state of the component. state is an object. if the state passed to setState contains an existing state variable, then its value is overridden. But if the state variable passed as an argument to setState is non-existent, then it is added as another state variable to the existing state of the component. ```js // supposing this is a component's state state = { age: 2 } // modifying existing state variable modifyExistingStateVar = () => { this.setState({age: 3}) console.log(this.state) } // adding a new state variable addNewStateVar = () => { this.setState({height: 31}) console.log(this.state) } modifyExistingStateVar() // Output: {age: 3} addNewStateVar() // Output: {age: 2, height: 31} ``` So our toggleComplete function is: ```js toggleComplete = (id) => { this.setState({ todos: this.state.todos.map(todo => { if (id === todo.id) { todo.completed = !todo.completed } return todo }) }) } ``` The setState function is called within toggleComplete to modify an existing state variable - `todos`. What do we do to it? We call `map` off the current todos (`this.state.todos`) to check for the task that matches the `id` argument. If the todo matches, then we toggle its completed value which is a boolean. Remember that a value needs to be returned within the map function's callback. Remember that the map function returns an Array of all the values that are returned within its callback. ## Adding header, todos using a form ### Header so to add the header which wouldn't have any need for state and any functionality, we just use a function-based component to do that. For funtion based components, they just return the required HTML/JSX to be rendered. ```js function Header() { return ( <header style={headerStyle}> <h1>TodoList</h1> </header> ) } export default Header; ``` ### Adding Todos using a form element so as usual, a component is created for the form. #### form fields and state variables Usually, when there are input fields in a component, they should have state variables to hold their values. Then the value in the state variable should be passed as the value of each input field. But if this alone is done, then the input field would be made readonly. This is because as you type in the input field, an onChange event is fired but not handled to update the state variable, so React will just make the field a readonly field. If the field is supposed to be mutable, then the onChange event must be handled. ```js onChangeHandler = (e) => { this.setState({ title: e.target.value }) } ``` But if there is multiple form fields, it would be very tedious to write an event handler for each field. So instead, one event hadler can be used, then we reference the state variable using the name attribute of the form field. ```js onChangeHandler = (e) => { this.setState({ [e.target.name]: e.target.value }) } ``` #### submitting form data - Adding a new todo item To submit the data, we have to add a submit event handler to the form. The `onSubmit` is going to call another function which is responsible for changing the state in which all the todos are found. Then we reset the form by changing the state to its initial default values. ```js onSubmitHandler = e => { // prevent default event trigger action e.preventDefault(); // call function responsible for modifying global state which contains the todos this.props.AddTodoItem(this.state.title); // clear form this.setState({ title: '' }) } ``` ## Routers NB: React fragments are used when no actula HTML tag is intended to contain the remaining elements, but JSX is still used within rendering. Supposing there is an about page which we want to visit when we enter a specific URL. Then we need react to render that page when that URL is entered. This is one reason for routers. So first of all, all the components including the main App component needs to be enclosed within `BrowserRouter` tags. `BrowserRouter` is within the `react-router-dom` module. ```js import {BrowserRouter as Router} from 'react-router-dom'; render() { return ( <Router> <div className="App"> <div className="container"> <ComponentName /> </div> </div> </Router> ); } ``` To render different components depending on the URL path, we need to import `Route` also from `react-router-dom`. Within `Route`, a path is defined to represent the URL path. Then, the components to be rendered when that path is visited are returned in by the `props` callback of the `Route` `render` prop. If multiple components are to be returned, remember to wrap them in a single element. If the multiple components should be rendered excluding the container element then just use `React.Fragment` to wrap them. `React.Fragment` is not actually rendered in the DOM, it is just used for some JSX purposes. So our home route looks like: ```jsx <Router> <div className="App"> <div className="container"> <Header /> {/* HOME ROUTE */} <Route exact path="/" render={props => ( <React.Fragment> <AddTodo addTodoItem={this.addTodoItem} /> <Todos todos={this.state.todos} delTodo={this.delTodo} toggleComplete={this.toggleComplete} /> </React.Fragment> )} /> {/* ABOUT ROUTE */} </div> </div> </Router> ``` Notice the `exact` prop added to the `Route`. It ensures that the path is matched exactly as provided before the components are rendered. To add the about page route which is a single component, we just add another `Route` and this time define a `component` prop. ```jsx {/* ABOUT ROUTE */} <Route path="/about" component={About} /> ``` **NB**<br> `component` is used to render a single component in a `Route` whereas `render` is used to render multiple components in a `Route`. ### Adding Links In React, instead of creating a link using the anchor `<a>` tag, we use `Link`. The attribute that defines the path that the link leads to is called `to`. `Link` is also imported from `react-router-dom` ```jsx <Link to="/path/to/destination"></Link> ``` ## HTTP requests We'll be using axios, just a preference. So we'll fetch data from a resource and then use it to populate the state instead. This is done within a lifecyle method called `componentDidMount`. The `componentDidMount` is >called immediately after a component is mounted. Setting state here will trigger re-rendering. ```jsx componentDidMount() { axios.get('https://jsonplaceholder.typicode.com/todos/?_limit=10') .then(response => this.setState({todos: response.data})) } ```
Markdown
UTF-8
31,248
3.359375
3
[]
no_license
[String / StringBuilder / StringBuffer](https://12bme.tistory.com/42) 1. 풀이 ```java class Solution { public String solution(int n) { String answer = ""; StringBuilder sb = new StringBuilder(); for(int i=0; i < n; i++){ if(i%2 == 0) sb.append("수"); else sb.append("박"); //sb.append(i%2==0 ? "수":"박"); // 위 조건문 대체 가능 } answer = sb.toString(); return answer; } } ``` 2. 다른 사람의 풀이1 ```java public class WaterMelon { public String watermelon(int n){ return new String(new char [n/2+1]).replace("\0", "수박").substring(0,n); //char의 빈 배열은 "\0"로 채워짐 -> "\0"를 "수박"으로 바꾸는 것 } // 실행을 위한 테스트코드입니다. public static void main(String[] args){ WaterMelon wm = new WaterMelon(); System.out.println("n이 3인 경우: " + wm.watermelon(3)); System.out.println("n이 4인 경우: " + wm.watermelon(4)); } } ``` 3. 다른 사람의 풀이2 ```java class Solution { String text = "수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박수박"; public String solution(int n) { String answer = text.substring(0, n); return answer; } } ```
C++
UTF-8
870
2.96875
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#pragma once #include "ContextBase.h" #define GLTEST_DEFAULT_WIDTH 160 #define GLTEST_DEFAULT_HEIGHT 90 #define GLTEST_DEFAULT_DEPTH 4 //Basic interface for OpenGL tests class GLTest { protected: std::shared_ptr<ContextBase> context; int w; int h; int d; int size; int mode; /*Constructor. Set up all necessary objects objects here. */ GLTest(std::shared_ptr<ContextBase> & c, const int width = GLTEST_DEFAULT_WIDTH, const int height = GLTEST_DEFAULT_HEIGHT, const int depth = GLTEST_DEFAULT_DEPTH); public: /*Return the name of the test and the mode set */ virtual std::string name() const; /*Set the mode the test is in. */ virtual void setMode(const int value); virtual int getMode() const; /*Initialize test before drawing. */ virtual bool pre(); /*De-initialize test after drawing. */ virtual bool post(); };
Shell
UTF-8
308
3.046875
3
[]
no_license
# This file is part of elasticsearch restore. #!/bin/sh # URL where elasticsearch is running. OUTPUT=http://localhost:9200 # destination where dump files are located DUMPS=./dumps for FILENAME in "$DUMPS"/* do echo "$FILENAME" elasticdump --input=$FILENAME --output=$OUTPUT/$FILE --type=data done
Java
UTF-8
522
2.390625
2
[]
no_license
package movies.raemacias.com.movieappstage2.api; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class Client { public static final String BASE_URL = "http://api.themoviedb.org/3/movie/"; public Retrofit retrofit; public Retrofit getClient() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit; } }
JavaScript
UTF-8
1,273
2.625
3
[]
no_license
var express = require("express"); var router = express.Router(); // Import the model to use its database functions. var burger = require("../models/burger.js"); router.get("/",function(req,res){ burger.selectAll(function(data){ var burgerObj = { burgers: data }; res.render("index",burgerObj); }); }) router.post("/api/burgers",function(req,res){ burger.insertOne(["burger_name"],[req.body.burger_name],function(result){ if(result.affectedRows !=0){ res.status(200).json({ status:true, id:result.insertId}); } else{ res.status(500).json({ status:false, msg:"insert internal error" }).end(); } }); }) router.put("/api/burgers/:id",function(req,res){ var condition = "id ="+req.params.id; burger.updateOne({devoured:req.body.devoured},condition,function(result){ if (result.changedRows == 0) { return res.status(404).end(); } else { res.status(200).json({ status:true, msg:"updated successfully" }).end(); } }); }) module.exports=router;
Java
UTF-8
10,768
3.375
3
[]
no_license
import java.util.Scanner; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class TuringMachine { static JFrame frame1; static Container pane; static JButton btn1, btn2, btn3; static JLabel prompt; static JTextField input; static Insets insets; public static void main(String args[]) throws Exception{ frame1 = new JFrame ("Turning Machine Application"); frame1.setSize(650,200); pane = frame1.getContentPane(); insets = pane.getInsets(); pane.setLayout(null); prompt = new JLabel("Please chose your language"); input = new JTextField(10); btn1 = new JButton("{ww | w ∈ {0,1}}"); btn2 = new JButton("{w#w#w | w ∈ {0, 1}}"); btn3 = new JButton("{w | w contains an even number of 0s and w ∈ {0} ∗ }"); pane.add(prompt); prompt.setBounds(insets.top + 100, insets.right + 5, prompt.getPreferredSize().width, prompt.getPreferredSize().height); pane.add(btn1); btn1.setBounds (input.getX() + 100 + btn1.getWidth(), insets.top + 30, btn1.getPreferredSize().width, btn1.getPreferredSize().height); btn1.setActionCommand("1"); pane.add(btn2); btn2.setBounds (input.getX() +100 + btn2.getWidth(), insets.top + 60, btn2.getPreferredSize().width, btn2.getPreferredSize().height); btn2.setActionCommand("2"); pane.add(btn3); btn3.setBounds (input.getX() +100 + btn3.getWidth(), insets.top + 90, btn3.getPreferredSize().width, btn3.getPreferredSize().height); btn3.setActionCommand("3"); frame1.setVisible(true); btn1.addActionListener(new ButtonListener()); btn2.addActionListener(new ButtonListener()); btn3.addActionListener(new ButtonListener()); //Set Look and Feel try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (ClassNotFoundException e) {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (UnsupportedLookAndFeelException e) {} }//main }//turning machine class ButtonListener implements ActionListener{ static JFrame frame1; static Container pane; static JLabel prompt, tapeJ, deniedJ; static JTextField input; static Insets insets; static JButton btn; ButtonListener(){ } public void actionPerformed(ActionEvent e){ if("1".equals(e.getActionCommand())){ Machine1_Input(); } if("2".equals(e.getActionCommand())){ Machine2_Input(); } if("3".equals(e.getActionCommand())){ Machine3_Input(); } if("OK1".equals(e.getActionCommand())){ String str = input.getText(); Machine1(str); } if("OK2".equals(e.getActionCommand())){ String str = input.getText(); Machine2(str); } if("OK3".equals(e.getActionCommand())){ String str = input.getText(); Machine3(str); } } public void Machine1_Input(){ //{ww | w ∈ {0,1}} frame1 = new JFrame ("Machine 1"); frame1.setSize(650,200); pane = frame1.getContentPane(); insets = pane.getInsets(); pane.setLayout(null); input = new JTextField(10); prompt = new JLabel("Please enter your string"); btn = new JButton("OK"); pane.add(prompt); prompt.setBounds(insets.top + 100, insets.right + 5, prompt.getPreferredSize().width, prompt.getPreferredSize().height); pane.add(input); input.setBounds(insets.top + 100, insets.top + 25, input.getPreferredSize().width, input.getPreferredSize().height); pane.add(btn); btn.setBounds(insets.top + 100, insets.right + 60, btn.getPreferredSize().width, btn.getPreferredSize().height); btn.setActionCommand("OK1"); frame1.setVisible(true); try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (ClassNotFoundException e) {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (UnsupportedLookAndFeelException e) {} btn.addActionListener(new ButtonListener()); }//Machine1 public void Machine1(String str){ StringBuilder tape = new StringBuilder(str); StringBuilder tape1 = new StringBuilder(tape); tape.append(tape1); for(int i = 0; i < tape.length(); i++){ if(tape.charAt(i) == '0'){ tape.setCharAt(i, 'x'); System.out.println("Step #"+ i + " " + tape + "\tOperation performed: Read 0 at position #" + i + ", wrote x, movement right"); } else if (tape.charAt(i) != '0'){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 1 at position #" + i + ", string denied."); break; } if(tape.charAt(i+1) == '1'){ tape.setCharAt(i+1, 'x'); System.out.println("Step #"+ (i+1) + " " + tape + "\tOperation performed: Read 1 at position #" + (i+1) + ", wrote x, movement right"); } else if (tape.charAt(i+1) != '1'){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 0 at position #" + i + ", string denied."); break; } i++; }//for if(tape.charAt(tape.length()-1) == 'x'){ System.out.println("Accepted!"); } }//machine1 public void Machine2_Input(){ //{w#w#w | w ∈ {0, 1}} frame1 = new JFrame ("Machine 2"); frame1.setSize(650,200); pane = frame1.getContentPane(); insets = pane.getInsets(); pane.setLayout(null); input = new JTextField(10); prompt = new JLabel("Please enter your string"); btn = new JButton("OK"); pane.add(prompt); prompt.setBounds(insets.top + 100, insets.right + 5, prompt.getPreferredSize().width, prompt.getPreferredSize().height); pane.add(input); input.setBounds(insets.top + 100, insets.top + 25, input.getPreferredSize().width, input.getPreferredSize().height); pane.add(btn); btn.setBounds(insets.top + 100, insets.right + 60, btn.getPreferredSize().width, btn.getPreferredSize().height); btn.setActionCommand("OK2"); frame1.setVisible(true); try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (ClassNotFoundException e) {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (UnsupportedLookAndFeelException e) {} btn.addActionListener(new ButtonListener()); } public void Machine2(String str){ //{w#w#w | w ∈ {0, 1}} String h = "#"; StringBuilder tape = new StringBuilder(str); StringBuilder tape1 = new StringBuilder(tape); StringBuilder tape2 = new StringBuilder(tape1); tape.append(h); tape.append(tape1); tape.append(h); tape.append(tape2); try{ for(int i = 0; i < tape.length();i++){ if(tape.charAt(i) == '0'){ tape.setCharAt(i, 'x'); System.out.println("Step #"+ i + " " + tape + "\tOperation performed: Read 0 at position #" + i + ", wrote x, movement right."); } else if (tape.charAt(i) == '1'){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 1 at position #" + i + ", string denied."); break; } if(tape.charAt(i+1) == '1'){ tape.setCharAt(i+1, 'x'); System.out.println("Step #"+ (i+1) + " " + tape + "\tOperation performed: Read 1 at position #" + (i+1) + ", wrote x, movement right."); } else if (tape.charAt(i+1) == '0'){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 0 at position #" + i + ", string denied."); break; } if(tape.charAt(i+2) == '#' ) { tape.setCharAt(i+2, 'x'); System.out.println("Step #"+ (i+2) + " " + tape + "\tOperation performed: Read # at position #" + (i+2) + ", wrote x, movement right."); }else if ((tape.charAt(i+2) == '0') || (tape.charAt(i+2) == '1')){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 1 or 0 at position #" + (i+2) + ", string denied."); break; } i++; i++; }//for } catch (StringIndexOutOfBoundsException e) { } if(tape.charAt(tape.length()-1) == 'x'){ System.out.println("Accepted!"); } }//Machine2 public void Machine3_Input(){ //{w | w contains an even number of 0s and w ∈ {0} ∗ } frame1 = new JFrame ("Machine 3"); frame1.setSize(650,200); pane = frame1.getContentPane(); insets = pane.getInsets(); pane.setLayout(null); input = new JTextField(10); prompt = new JLabel("Please enter your string"); btn = new JButton("OK"); pane.add(prompt); prompt.setBounds(insets.top + 100, insets.right + 5, prompt.getPreferredSize().width, prompt.getPreferredSize().height); pane.add(input); input.setBounds(insets.top + 100, insets.top + 25, input.getPreferredSize().width, input.getPreferredSize().height); pane.add(btn); btn.setBounds(insets.top + 100, insets.right + 60, btn.getPreferredSize().width, btn.getPreferredSize().height); btn.setActionCommand("OK3"); frame1.setVisible(true); try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch (ClassNotFoundException e) {} catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (UnsupportedLookAndFeelException e) {} btn.addActionListener(new ButtonListener()); } public void Machine3(String str){ //{w | w contains an even number of 0s and w ∈ {0} ∗ } boolean odd = false; StringBuilder tape = new StringBuilder(str); try{ for(int i = 0; i < tape.length();i++){ if(tape.charAt(i) == '0'){ tape.setCharAt(i, 'x'); System.out.println("Step #"+ i + " " + tape + "\tOperation performed: Read 0 at position #" + i + ", wrote x, movement right."); } else if (tape.charAt(i) != '0'){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 1 at position #" + i + ", string denied."); break; } if(tape.charAt(i+1) == '0'){ tape.setCharAt(i+1, 'x'); System.out.println("Step #"+ (i+1) + " " + tape + "\tOperation performed: Read 0 at position #" + (i+1) + ", wrote x, movement right."); } else if (tape.charAt(i+1) != '0'){ System.out.println("Denied!"); System.out.println("\t\tOperation performed: Read 1 at position #" + (i+1) + ", string denied."); break; } i++; }//for } catch (StringIndexOutOfBoundsException ei) { System.out.println("Denied!\t\tString is not of even length."); odd = true; } if((tape.charAt(tape.length()-1) == 'x') && (odd == false)){ System.out.println("Accepted!"); } }//Machine3 }
Java
UTF-8
798
3.15625
3
[]
no_license
package Heap; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Collections; import java.util.PriorityQueue; public class Acmicpc_11279_최대힙 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int N = Integer.parseInt(br.readLine()); PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for(int i = 0; i < N; i++) { int x = Integer.parseInt(br.readLine()); if(x == 0) { if(pq.isEmpty()) { sb.append(0).append("\n"); }else { sb.append(pq.poll()).append("\n"); } } else { pq.offer(x); } } sb.setLength(sb.length()-1); System.out.print(sb); } }
Markdown
UTF-8
1,182
2.734375
3
[]
no_license
# redux-server-side-rendering My demo project of React and Redux server side rendering. I used the counter idea from the Redux Docs on [server side rendering](http://redux.js.org/docs/recipes/ServerRendering.html), as well as a very simple and easy to follow [universal-redux-template](https://github.com/mz026/universal-redux-template). The reason for the later was to include Route handling on the client and server. This involves using `match` from [react-router](https://github.com/reactjs/react-router) to get the Route Tree structure without rendering. Then using some helper function I call `renderToString` from react/server to make the `html` constant in server.js. This is passed along with the initialState from the redux Store to the `renderFullPage()` function to use `res.send()` to the client. This helps with SEO and should give me a good demo and reference to start using server side rendering for React in my apps. **Extra** The webpack.server.js file is not needed however going through the react-router tutorial on [server-rendering](https://github.com/reactjs/react-router-tutorial/tree/master/lessons/13-server-rendering) show the use and the why of it.
Python
UTF-8
11,344
3
3
[ "MIT" ]
permissive
import numpy as np import PIL from IPython.display import display def reshape_single_as_picture(input, size): ''' Takes a np array and reshapes it to the specified size. Essentially, a transparent wrapper for np.reshape(input, size) ''' return np.reshape(input, size) def as_single_picture(input, size, outsize=None): ''' Takes a flatten np array (uint8) and its size and returns it as a PIL Image instance, optionally resized to outsize. ''' outsize = outsize if outsize is not None else size input_as_uint8 = input.astype(np.uint8) return PIL.Image.fromarray(reshape_single_as_picture(input_as_uint8, size), 'L').resize(outsize, PIL.Image.NEAREST) import seaborn as sns import matplotlib.pyplot as plt def display_as_single_heatmap(input, size): ''' Displays input np array as a heatmap of specified size. ''' display(sns.heatmap(np.reshape(input, size), center=0.0)) plt.show() def plot_square_w_as_heatmaps(data, data_extractor, plots=(3, 3)): ''' Takes input `data`, runs `data_extractor(data, i)` for max of (each plot (nrows, ncols), data.shape[1]) and then displays a square heatmap for each of the returned `dta`, arranging them in a (nrows, ncols) grid. Useful for displaying set of convolution layer filters. E.g.: weights = hsm.networks[0].layers[0].weights get_data = lambda w, i: get_gaussian(w[:,i], (SIZE_DOWNSAMPLE, SIZE_DOWNSAMPLE)) plot_square_w_as_heatmaps(weights, get_data) ''' nrows, ncols = plots fig, ax = plt.subplots(nrows=nrows, ncols=ncols) fig.set_size_inches(16, 16) for i in range(min(nrows*ncols, data.shape[1])): dta = data_extractor(data, i).flatten() size = int(np.sqrt(dta.shape[0])) dta = np.reshape(dta, (size, size)) sns.heatmap(dta, center=0.0, ax=ax[i//ncols][i%ncols]) plt.show() import math import numpy as np import matplotlib.pyplot as plt def get_metrics_runs(dta, normalize_steps=False, median_mode = False): ''' Get performance metrics (vals_top, vals_bot, vals_mid, vals_bot_sec, steps) for set of runs. Expects pd df{Steps, Run, Value}. - normalize_steps: Normalizes step values to 0-1 range. - median_mode: Use (90th, 10th, 50th, 25th) percentiles instead of (95th, 05th, 75th, 25th). ''' by_step = dta.groupby("Step", as_index=False) steps = by_step.first()["Step"].values if not normalize_steps else by_step.first()["Step"].values / by_step.first()["Step"].max() if median_mode: vals_top = by_step.quantile(0.90)["Value"].values vals_bot = by_step.quantile(0.10)["Value"].values vals_mid = by_step.quantile(0.50)["Value"].values vals_bot_sec = by_step.quantile(0.25)["Value"].values else: vals_top = by_step.quantile(0.95)["Value"].values vals_bot = by_step.quantile(0.05)["Value"].values vals_mid = by_step.quantile(0.75)["Value"].values vals_bot_sec = by_step.quantile(0.25)["Value"].values return (vals_top, vals_bot, vals_mid, vals_bot_sec, steps) def summarize_runs(dta, normalize_steps=False, median_mode = False, **kwargs): ''' Gets fully trained performance metrics (mid_percentile_value, top_percentile_value, bottom_percentile_value) for set of runs, expects pd df{Steps, Run, Value}. - normalize_steps: Normalizes step values to 0-1 range (can be ignored for this method, here due to backwards compatibility reasons). - median_mode: Use (90th, 10th, 50th, 25th) percentiles instead of (95th, 05th, 75th, 25th). ''' (vals_top, vals_bot, vals_mid, _, _) = get_metrics_runs(dta, normalize_steps, median_mode) return (vals_mid[-1], vals_top[-1], vals_bot[-1]) def analyse_runs(dta, fig=None, ax=None, second_level_errbar=False, normalize_steps=False, median_mode = False, figsize=None, ylim=None): ''' Visualizes data for set of runs, expects pd df{Steps, Run, Value}. Draws a single line (mid percentile) with error bars (bottom, top percentiles) on a figure corresponding to a set of runs for one experiment. - second_level_errbar: Draws second set of smaller error boxes for second bottom percentile. - normalize_steps: Normalizes steps to 0-1 range. - median_mode: Use (90th, 10th, 50th, 25th) percentiles instead of (95th, 05th, 75th, 25th). ''' assert (fig is None) == (ax is None) (vals_top, vals_bot, vals_mid, vals_bot_sec, steps) = get_metrics_runs(dta, normalize_steps, median_mode) if figsize is None: figsize = (20, 10) # Allows externally passed fix, ax so that it can be added to existing ax if fig is None: fig, ax = plt.subplots(figsize=figsize) # Ideally computes for the whole set of experiments & is uniform across all of them # ..even if they have different leghts -> too much work. Eyeball cca 50-> errbars fit. err_every = math.ceil(len(vals_mid)/50) # Print data-points for - at most - 500 positions -> otherwise if too many points close in x-axis are far in y-axis they create a thick line vals_top = vals_top[0::math.ceil(len(vals_top)/500)] vals_bot = vals_bot[0::math.ceil(len(vals_bot)/500)] vals_mid = vals_mid[0::math.ceil(len(vals_mid)/500)] vals_bot_sec = vals_bot_sec[0::math.ceil(len(vals_bot_sec)/500)] steps = steps[0::math.ceil(len(steps)/500)] ax.set_yticks(np.arange(0, 1., 0.02)) if ylim: ax.set_ylim(ylim) ax.yaxis.grid(True) f_line = ax.errorbar(steps, vals_mid, yerr=[(vals_mid-vals_bot), (vals_top-vals_mid)], capsize=4, alpha=0.85, elinewidth=1, errorevery=err_every, lw=1)[0] if second_level_errbar: # Draws second set of error boxes at 0.75-0.25 _ = ax.errorbar(steps, vals_mid, yerr=[(vals_mid-vals_bot_sec), (vals_mid-vals_mid)], capsize=2, alpha=0.85, elinewidth=2, errorevery=err_every, c=f_line.get_color(), lw=1) return f_line def analyse_static_data(dta, limit_steps, fig=None, ax=None, second_level_errbar=False, normalize_steps=False, figsize=None, ylim=None, **kwargs): ''' Visualizes piece of static data, expects (val_top, val_bot, val_mid, val_bot_sec, number_of_epochs) as dta. Draws a single line (mid percentile) with error bars (bottom, top percentiles) on a figure corresponding to a set of runs for one experiment. - second_level_errbar: Draws second set of smaller error boxes for second bottom percentile. - normalize_steps: Normalizes steps to 0-1 range. ''' assert (fig is None) == (ax is None) (val_top, val_bot, val_mid, val_bot_sec, epochs) = dta if limit_steps is None: limit_steps = (float("-inf"), float("+inf")) steps = [x for x in range(-1, epochs-1, 100) if x >= 0 and x >= limit_steps[0] and x <= limit_steps[1]] vals_mid = np.array([val_mid for x in steps]) vals_top = np.array([val_top for x in steps]) vals_bot = np.array([val_bot for x in steps]) vals_bot_sec = np.array([val_bot_sec for x in steps]) if normalize_steps: steps = steps / np.max(steps) if figsize is None: figsize = (20, 10) # Allows externally passed fix, ax so that it can be added to existing ax if fig is None: fig, ax = plt.subplots(figsize=figsize) # Ideally computes for the whole set of experiments & is uniform across all of them # ..even if they have different leghts -> too much work. Eyeball cca 50-> errbars fit. err_every = math.ceil(len(vals_mid)/50) ax.set_yticks(np.arange(0, 1., 0.02)) if ylim: ax.set_ylim(ylim) ax.yaxis.grid(True) f_line = ax.errorbar(steps, vals_mid, yerr=[(vals_mid-vals_bot), (vals_top-vals_mid)], capsize=4, alpha=0.85, elinewidth=1, errorevery=err_every, lw=1)[0] if second_level_errbar: # Draws second set of error boxes at 0.75-0.25 _ = ax.errorbar(steps, vals_mid, yerr=[(vals_mid-vals_bot_sec), (vals_mid-vals_mid)], capsize=2, alpha=0.85, elinewidth=2, errorevery=err_every, c=f_line.get_color(), lw=1) return f_line import utils.data as udata def analyse_experiments(experiments, tag, limit_steps=None, experiments_log_in_legend=True, override_legend=None, title=None, enable_legend = True, static_data = [], figsize=(20, 10), **kwargs): ''' Visualizes data for a set of experiments, expects [(experiment_folder, experiment_TB_like_regex), ...]. Returns figure. Draws a single figure with a line for each experiment. For line description see `analyse_runs(...)`. - limit_steps (float, float)|None: Only display data for steps within bounds (expects absolute step numbers / float(inf)) - experiments_log_in_legend bool: Show corresponding entries from ./training_data/experiments.txt log file for each experiment in legend. - static_data: adds a line based on static values, expects (name_on_legend, data) format. For data format, refer to `analyse_static_data` - ...paramaters of `analyse_runs(...)` ''' fig, ax = plt.subplots(figsize=figsize) line_handles = [] legend_names = [] for (name, dta) in static_data: line_handle = analyse_static_data(dta, limit_steps, fig=fig, ax=ax, figsize=figsize, **kwargs) line_handles.append(line_handle) legend_names.append(name) for i, (folder, regex) in enumerate(experiments): dta, logs_num = udata.get_log_data_for_experiment(folder, regex, tag, limit_steps) line_handle = analyse_runs(dta, fig=fig, ax=ax, figsize=figsize, **kwargs) line_handles.append(line_handle) if override_legend is None: legend_exp = udata.get_experiment_entries(folder, regex) if experiments_log_in_legend else [] legend_names.append(f"{regex} ({logs_num} runs) {', '.join(legend_exp)}") else: legend_names.append(override_legend[i]) if enable_legend: ax.legend(line_handles, legend_names) ax.set_xlabel("training epoch") ax.set_ylabel("mean validation set correlation") ax.tick_params(labelleft=True, labelright=True,) if title: ax.set_title(title) fig = plt.gcf() plt.show() return fig def summarize_experiments(experiments, tag, limit_steps=None, experiments_log_in_legend=True, override_legend=None, title=None, **kwargs): ''' Prints trained performance summaries for set of experiments, expects [(experiment_folder, experiment_TB_like_regex), ...]. Prints a single summary for each experiment. For summary description see `summarize_runs(...)`. - limit_steps (float, float)|None: Only shows data for steps within bounds (expects absolute step numbers / float(inf)) - experiments_log_in_legend bool: Show corresponding entries from experiments.txt log file. - ...paramaters of `summarize_runs(...)` ''' for i, (folder, regex) in enumerate(experiments): dta, logs_num = udata.get_log_data_for_experiment(folder, regex, tag, limit_steps) runs_summary = summarize_runs(dta, **kwargs) if override_legend is None: legend_exp = udata.get_experiment_entries(folder, regex) if experiments_log_in_legend else [] legend = f"{regex} ({logs_num} runs) {', '.join(legend_exp)}" else: legend = override_legend[i] print(f"{legend}: {tuple(map(lambda x: round(x, 3), runs_summary))}")
Java
UTF-8
368
1.875
2
[]
no_license
package ru.home.aws.pictures.service; import ru.home.aws.pictures.dto.Picture; public interface PictureService { Iterable<Picture> getPictures(); Picture getPictureById(Long id); Picture getRandom(); Picture getPictureByName(String name); Picture create(Picture picture); Picture update(Long id, Picture picture); void delete(Long id); }
Java
UTF-8
2,722
2.3125
2
[]
no_license
package com.oce.app.service.impl; import com.oce.app.service.TypeServiceService; import com.oce.app.domain.TypeService; import com.oce.app.repository.TypeServiceRepository; import com.oce.app.service.dto.TypeServiceDTO; import com.oce.app.service.mapper.TypeServiceMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * Service Implementation for managing {@link TypeService}. */ @Service @Transactional public class TypeServiceServiceImpl implements TypeServiceService { private final Logger log = LoggerFactory.getLogger(TypeServiceServiceImpl.class); private final TypeServiceRepository typeServiceRepository; private final TypeServiceMapper typeServiceMapper; public TypeServiceServiceImpl(TypeServiceRepository typeServiceRepository, TypeServiceMapper typeServiceMapper) { this.typeServiceRepository = typeServiceRepository; this.typeServiceMapper = typeServiceMapper; } /** * Save a typeService. * * @param typeServiceDTO the entity to save. * @return the persisted entity. */ @Override public TypeServiceDTO save(TypeServiceDTO typeServiceDTO) { log.debug("Request to save TypeService : {}", typeServiceDTO); TypeService typeService = typeServiceMapper.toEntity(typeServiceDTO); typeService = typeServiceRepository.save(typeService); return typeServiceMapper.toDto(typeService); } /** * Get all the typeServices. * * @param pageable the pagination information. * @return the list of entities. */ @Override @Transactional(readOnly = true) public Page<TypeServiceDTO> findAll(Pageable pageable) { log.debug("Request to get all TypeServices"); return typeServiceRepository.findAll(pageable) .map(typeServiceMapper::toDto); } /** * Get one typeService by id. * * @param id the id of the entity. * @return the entity. */ @Override @Transactional(readOnly = true) public Optional<TypeServiceDTO> findOne(Long id) { log.debug("Request to get TypeService : {}", id); return typeServiceRepository.findById(id) .map(typeServiceMapper::toDto); } /** * Delete the typeService by id. * * @param id the id of the entity. */ @Override public void delete(Long id) { log.debug("Request to delete TypeService : {}", id); typeServiceRepository.deleteById(id); } }
Markdown
UTF-8
4,610
3.3125
3
[]
no_license
### Q1) How do I get started? (insert the "Important Notes for New ML Students" here) Familiarize yourself with the Resources menu (see the links on the left side of your browswer) and the Discussion Forums. Questions regarding Machine Learning should be posted on the course Discussion Forums Technical issues/suggestions regarding the videos should either be reported via the small flag icon on the bottom right of the videos, or via the Help Center. Certificate related issues should also be sent to the Help Center. ### Q2) What are the course pre-requisites? You will do best in this course if you have: Experience in at least one programming language. Are not frightened of solving a system of linear equations. ...which is another way of saying... Know how to multiply matrices and vectors. Lacking those skills, you can still complete the course, but it will take considerably more time and study. The course is not heavy in math - linear algebra is a benefit, some statistics is helpful, calculus is not required. If you do not have any programming experience, consider taking an introduction to programming course, such as Mathwork's "MATLAB Onramp". ### Q3) Why does the cost function include multiplying by 1/(2m)? The '1/m' portion is so that the cost is scaled to a per-example basis. Later in the course we will be comparing the cost value J for different sizes of training sets. The '1/2' portion is a calculus trick, so that it will cancel with the '2' which appears in the numerator when we compute the partial derivatives. This saves us a computation in the cost function. ### Q4) In the cost function, why don't we use absolute value instead of the squared error? The absolute value has some bad characteristics for minimization. The gradient is not continuous, because the absolute value function is not differentiable at its minimum point. It does not emphasize the correction of large errors. The abs() function is also not very mathematically efficient. ### Q5) I found an error in one of the video lectures. Should I post about it on the Forum? No. There are lots and lots of errors in the video lectures. We keep a list of them in the Errata sections of the Resources menu. ### Q6) Can I use python or R to do the programming exercises? The short answer is "no". This course is taught using MATLAB or Octave (the open source implementation of the MATLAB language). The grader software is written in MATLAB and tests your code by calling it using MATLAB function calls. Prof Ng explains why he choose MATLAB in the lectures. ### Q7) In the quiz grading, what does "correct response" mean? Be careful about how you interpret the quiz grading. It is grading your responses, not whether the answer choices are true. The "correct response" is for you to mark the true statements, and to not mark the false ones. ### Q8) Why can't I get the correct answers for the Week 1 quizzes? First, read (Q7 above) so you know how the grader provides feedback. Next, be very careful you read the quiz questions and answers in great detail. The quizzes are randomly generated each time you re-take a quiz - you may get a different set of questions, a different set of possible answers, and they will all appear in a random order. The quiz grader doesn't tell you why your answer was wrong - so this can be frustrating especially on those "pick all that apply" questions. The best way to sort out this dilemma is to keep a record of what your quiz attempts have been - both the questions you were asked AND the answers you tried. This will prevent you from overlooking some subtle difference in the questions, and help you avoid re-using the same answers. A last bit of advice. Questions that include the word "always" are (nearly) never the correct answer. After a few attempts at a quiz, you may think that the grader is broken. But the grader is actually correct - but some of the questions are very subtle. ### Q9) What's all this about "regression" vs. "classification"? Lots of problems in Machine Learning can be solved using either linear prediction or classification prediction. They're both forms of regression. Which method to use depends on how you want to use the output values - do you want a real value, or do you want a label? "regression" vs. "classification" is a false distinction. Do not confuse "classification" with "clustering". Clustering is an unsupervised method - we're just sorting examples into different bins depending on their characteristics - maybe size, maybe color, maybe their genes. There is no "output" value to consider.
Python
UTF-8
1,291
2.59375
3
[]
no_license
import cv2 import numpy as np from keras.datasets import mnist from keras.layers import Dense, Flatten from keras.layers.convolutional import Conv2D from keras.models import Sequential from keras.utils import to_categorical import matplotlib.pyplot as plt import datetime as dt print("hora de inicio") print(dt.datetime.now().time()) (X_train, y_train), (X_test, y_test) = mnist.load_data() ## Checking out the shapes involved in dataset X_train = X_train.reshape(60000, 28, 28, 1) X_test = X_test.reshape(10000, 28, 28, 1) y_train = to_categorical(y_train) y_test = to_categorical(y_test) ## Declare the model model = Sequential() ## Declare the layers layer_1 = Conv2D(64, kernel_size=3, activation='relu', input_shape=(28, 28, 1)) layer_2 = Conv2D(64, kernel_size=3, activation='relu') layer_2 = Conv2D(64, kernel_size=3, activation='relu') layer_3 = Flatten() layer_4 = Dense(10, activation='softmax') ## Add the layers to the model model.add(layer_1) model.add(layer_2) model.add(layer_3) model.add(layer_4) model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=4) model.save('num_reader_medium.model') print("hora de fin") print(dt.datetime.now().time())
Java
UTF-8
397
2.78125
3
[]
no_license
package duke.exceptions; //used when delete description is in the wrong format public class DeleteFormatException extends Exception { public final String DELETE_FORMAT_RESPONSE = "Could you rephrase that for Kao ( ̄▽ ̄*)?" + "\nThe following format must be used: delete [index]"; @Override public String getMessage(){ return DELETE_FORMAT_RESPONSE; } }
C++
UTF-8
1,617
2.9375
3
[]
no_license
#include <minpt/math/matrix4.h> #include <minpt/core/exception.h> namespace minpt { Matrix4f& Matrix4f::inverse() { int idxr[4], idxc[4]; bool visited[4] = { false, false, false, false }; for (auto i = 0; i < 4; ++i) { auto row = 0; auto col = 0; auto pivot = 0.0f; for (auto r = 0; r < 4; ++r) { if (visited[r]) continue; for (auto c = 0; c < 4; ++c) { auto abs = std::abs(e[r][c]); if (visited[c] || abs <= pivot) continue; pivot = abs; row = r; col = c; } } if (pivot == 0) throw Exception("Singular matrix!"); visited[col] = true; if (row != col) for (auto c = 0; c < 4; ++c) std::swap(e[row][c], e[col][c]); idxr[i] = row; idxc[i] = col; auto inv = 1 / e[col][col]; e[col][col] = 1; for (auto c = 0; c < 4; ++c) e[col][c] *= inv; for (auto r = 0; r < 4; ++r) { if (r == col) continue; auto tmp = e[r][col]; e[r][col] = 0; for (auto c = 0; c < 4; ++c) e[r][c] -= e[col][c] * tmp; } } for (auto i = 2; i >= 0; --i) { if (idxr[i] == idxc[i]) continue; for (auto r = 0; r < 4; ++r) std::swap(e[r][idxr[i]], e[r][idxc[i]]); } return *this; } Matrix4f& Matrix4f::transpose() { float tmp; tmp = e[0][1]; e[0][1] = e[1][0]; e[1][0] = tmp; tmp = e[0][2]; e[0][2] = e[2][0]; e[2][0] = tmp; tmp = e[0][3]; e[0][3] = e[3][0]; e[3][0] = tmp; tmp = e[1][2]; e[1][2] = e[2][1]; e[2][1] = tmp; tmp = e[1][3]; e[1][3] = e[3][1]; e[3][1] = tmp; tmp = e[2][3]; e[2][3] = e[3][2]; e[3][2] = tmp; return *this; } }
C
UTF-8
843
2.53125
3
[ "BSD-2-Clause" ]
permissive
/* * Copyright 2019 Shannon F. Stewman * * See LICENCE for the full copyright terms. */ #ifndef ADT_MAPPINGSET_H #define ADT_MAPPINGSET_H struct fsm_alloc; struct mapping_set; struct mapping; struct mapping_iter { struct hashset_iter iter; }; struct mapping_set * mapping_set_create(const struct fsm_alloc *a, unsigned long (*hash)(const struct mapping *a), int (*cmp)(const void *a, const void *b)); void mapping_set_free(struct mapping_set *set); struct mapping * mapping_set_add(struct mapping_set *set, struct mapping *item); struct mapping * mapping_set_contains(const struct mapping_set *set, const struct mapping *item); void mapping_set_clear(struct mapping_set *set); struct mapping * mapping_set_first(const struct mapping_set *set, struct mapping_iter *it); struct mapping * mapping_set_next(struct mapping_iter *it); #endif
Markdown
UTF-8
4,229
2.65625
3
[]
no_license
![cabecalho memed desafio](https://user-images.githubusercontent.com/2197005/28128758-3b0a0626-6707-11e7-9583-dac319c8b45b.png) # Desafio do Autocomplete ## Problema: A forma como um médico interage com a tecnologia ao escrever uma prescrição é um dos pontos mais importantes para a Memed. Por dia, um médico realiza em média 40 prescrições, e ter uma ferramenta de prescrição com ótima interface, usabilidade e conteúdo resulta em melhor qualidade de trabalho e mais atenção para o paciente. Uma das formas da Memed auxiliar ferramentas de parceiros no momento da prescrição é extendendo a usabilidade de campos de texto, os quais muitas vezes são utilizados por prontuários web. Extender a usabilidade de um campo de texto significa: - Ajudar o médico a encontrar medicamentos no momento da prescrição - Possibilitar a inserção de textos pré-definidos - Compreender o contexto e reagir a gatilhos de uso ## Solução: Criar uma página com um campos de texto (textarea), e quando o usuário digitar algo, posicionar um autocomplete logo abaixo do cursor (caret), sugerindo medicamentos. Quando um medicamento for clicado, inserir no campo de texto o nome e fabricante do medicamento. ## Proposta: A solução pode ser feita com ou sem frameworks front-end. Fique a vontade para usar algum framework CSS (ex: Bootstrap, Material, Semantic UI). Para enviar seu código, faça um fork deste repositório e nos avise quando concluir o desafio (:white_check_mark: as mensagens dos seus commits também serão analisadas). Lembre-se de alterar o README.md com as instruções para rodar o projeto. Não é necessário realizar uma busca verdadeira, será avaliada a interface (UI) e usabilidade (UX). Abaixo, segue uma lista de medicamentos para serem mostrados no autocomplete, independente do que for escrito pelo usuário: ```javascript [ { fabricante: 'Roche', nome: 'Roacutan 20mg, Cápsula (30un)', precoMax: 22.10, precoMin: 20.99, principioAtivo: 'Isotretinoína 20mg', titularidade: 'Referência' }, { fabricante: 'Sundown Vitaminas', nome: 'Vitamina C, comprimido (100un)', precoMax: 45.15, precoMin: 31.99, principioAtivo: 'Ácido Ascórbico', titularidade: 'Referência' }, { fabricante: 'Sundown Vitaminas', nome: 'Vitamina C, comprimido (180un)', precoMax: 10.00, precoMin: 10.00, principioAtivo: 'Ácido Ascórbico', titularidade: 'Genérico' }, { fabricante: 'EMS Sigma Pharma', nome: 'Itraspor 100mg, Cápsula (15un)', precoMax: 209.00, precoMin: 100.00, principioAtivo: 'Itraconazol 100mg', titularidade: 'Genérico' }, { fabricante: 'EMS Sigma Pharma', nome: 'Itraspor 100mg, Cápsula (28un)', precoMax: 15.00, precoMin: 9.99, principioAtivo: 'Itraconazol 100mg', titularidade: 'Referência' }, { fabricante: 'Abbott', nome: 'Cloridrato de sibutramina 15mg, Cápsula (30un)', precoMax: 40.00, precoMin: 40.00, principioAtivo: 'Cloridrato de sibutramina 15mg', titularidade: 'Genérico' }, { fabricante: 'Abbott', nome: 'Cloridrato de sibutramina 15mg, Cápsula (100un)', precoMax: 200.00, precoMin: 100.00, principioAtivo: 'Cloridrato de sibutramina 15mg', titularidade: 'Referência' } ] ``` Para o visual do autocomplete, você deve seguir a imagem abaixo. ATENÇÃO NOS DETALHES VISUAIS (interface/layout), isso será o ponto principal analisado. A fonte utilizada é a [Open Sans](https://fonts.google.com/specimen/Open+Sans). ![layout](https://user-images.githubusercontent.com/2197005/28479617-94429342-6e33-11e7-9707-00f99a5fb8f8.png) ## Etapas: 1 - O usuário deverá visualizar o autocomplete assim que começar a digitar no campo de texto: ![buscando](https://user-images.githubusercontent.com/2197005/28478284-2cda9b96-6e2e-11e7-8ac6-2e9095835227.gif) 2 - Ao clicar em um medicamento, deverá ser adicionado ao campo de texto o nome e o fabricante: ![clicando](https://user-images.githubusercontent.com/2197005/28478285-2de69f08-6e2e-11e7-93be-9d72a2a7b011.gif) 3 - O autocomplete deverá seguir o cursor (apenas verticalmente): ![trocando-de-linha](https://user-images.githubusercontent.com/2197005/28478286-2f36f88a-6e2e-11e7-8303-1619644f5e1f.gif) Boa sorte _and let’s code_! :m: Equipe Memed
C++
UTF-8
208
2.625
3
[]
no_license
#include <iostream> using namespace std; int main() { int n,c,b; cin >> n; c = 2; b = 1; do { b = b + 1; c = c * 2 ; } while (b < n); cout << c << endl; }
Python
UTF-8
206
3.53125
4
[]
no_license
# 100累加 i = 0 result = 0 while i < 100: i += 1 result += i print(result) j = 0 result2 = 0 while j < 100: j += 1 if (j % 2 == 0): print(j) result2 += j print(result2)
Python
UTF-8
770
4.25
4
[]
no_license
#Exmple for overriding #Base or parent class class Employee: def __init__(self, name, sal): self.name = name self.salary = sal def getName(self): return self.name def getSalary(self): return self.salary #Sub or child class class SalesOfficer(Employee): def __init__(self, name, sal, inc): super().__init__(name,sal) self.incnt = inc #getSalary method is override to calculate incentives def getSalary(self): print("override") return self.salary + self.incnt e1 = Employee("Rajesh", 9000) print("Total salary for {} is Rs {}".format(e1.getName(),e1.getSalary())) s1 = SalesOfficer("Kiran", 10000, 1000) print("Total salary for {} is Rs {}".format(s1.getName(),s1.getSalary()))
Markdown
UTF-8
6,797
2.78125
3
[]
no_license
--- title: '安卓文本居中——关于css,字体和line-box的笔记' date: 2018-12-27 2:30:12 hidden: true slug: zfeub4j94xg categories: [reprint] --- {{< raw >}} <h2 id="articleHeader0">前言</h2> <p>本文主要探索在安卓系统下浏览器中小字号中文居中的实现以及在混排时的对齐处理。本文是受《<a href="http://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align" rel="nofollow noreferrer" target="_blank">Deep dive CSS: font metrics, line-height and vertical-align</a>》(以下简称为《Deep》)所启发,并以此为基础所写,建议先阅读前文,您也可以选择阅读大漠老师或方应杭老师的翻译版。<a href="https://www.w3cplus.com/css/css-font-metrics-line-height-and-vertical-align.html" rel="nofollow noreferrer" target="_blank">大漠版</a> <a href="https://zhuanlan.zhihu.com/p/25808995" rel="nofollow noreferrer" target="_blank">方应杭版</a></p> <p>一直以来前端最简单的文字垂直居中方式就是line-height=height,浏览器会自动将line-height大于font-size的部分平分在文字上下,实现居中效果。但是,当网页中存在中文特别是10-12px的小字号中文时,在部分安卓机器上出现字符上飘,甚至超出容器的情况。<br>对于这种现象,网上流传着多种解决方案,比如tabel-cell法,flex法等。但是这类方法总是时灵时不灵,原因就在于这类方法只解决了将line-box相对外层容器居中的问题,必须要配合line-height:normal实现文字在line-box内居中才能解决问题。下文将对line-height:normal的生效原理和副作用处理进行研究。</p> <h2 id="articleHeader1">神奇的安卓字体</h2> <p>根据《Deep》所述,文字中从小到大可以划出三个区域,分别是em-square,content-area和virtual-area。一般情况下,前一个区域大致居中与后一个区域,而文字本身也大致居中于这个区域。因此无论是采用哪种line-height,文字居中于line-box看起来都是一件理所当然的事。<br>但是,对于部分安卓系统的默认字体而言却不是这样。</p> <p>下图的两个字的font-size和height都是10px,左边一个line-height为1即等于font-size,右边一个则为normal(由于DPR的原因,这里看到的像素点是实际上的三倍)。由于line-height属性不同。左边的line-box大小等于ex-square,右边的line-box大小等于virtual-area=content-area+line-gap<br>下图左侧红框内的淡灰色区域为em-square,高10px,深灰色区域为content-area高11px,右侧红框内的淡灰色区域为virtual-area高14px。可以看出,此时em-square位于content-area底部,字形则位于content-area顶部,所以字形完全没有居中于ex-square。<br>而右侧的行为则与《Deep》所述不同,virtual-area相对content-area多出来的3px大小的line-gap并不是平均分配与上下,而是全部堆在了顶部。因此恰好看起来文字居中于virtual-area。<br><span class="img-wrap"><img data-src="/img/bVXNwQ?w=1120&amp;h=520" src="https://static.alili.tech/img/bVXNwQ?w=1120&amp;h=520" alt="demo1" title="demo1" style="cursor: pointer; display: inline;"></span></p> <h2 id="articleHeader2">应用</h2> <p>综上,line-height:normal可以使文字在那些奇怪的安卓机器上实现垂直居中。当然,这条样式会带来一个问题,即高度line-box的高度不可控,此时就需要前文所说的flex或tabel-cell将line-box<br>相对于外层容器居中,然后在外层容器设置高度即可。</p> <p>下面是使用实例,起作用的样式是display: flex;align-items: center两条。创建一个弹性容器,然后将该容器的子元素居中,这样virtual-area多出来的部分就溢出到边框之外,而不会影响布局了。<br>图中红框内的浅灰色区域为高度12px的容器,深灰色为高度16px的line-box和virtual-area。最终实现了将12px大小的文字居中于12px大小的容器中的目的。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="<span style=&quot;border:1px solid red;height:12px;font-size:12px;color: black;display: flex;align-items: center;&quot;>国</span> " title="" data-original-title="复制"></span> <span type="button" class="saveToNote code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="放进笔记"></span> </div> </div><pre class="hljs xml"><code><span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"border:1px solid red;height:12px;font-size:12px;color: black;display: flex;align-items: center;"</span>&gt;</span>国<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> </code></pre> <p><span class="img-wrap"><img data-src="/img/bVXQAW?w=220&amp;h=200" src="https://static.alili.tech/img/bVXQAW?w=220&amp;h=200" alt="图片描述" title="图片描述" style="cursor: pointer; display: inline;"></span></p> <h2 id="articleHeader3">总结</h2> <p>回顾我们以前的做法。我们通常会为line-height设置一个具体的高度该高度就是line-box的高度。而浏览器会将字体的em-square居中于line-box中。对于大多数正常字体这么操作就可以实现垂直居中。<br>但是,部分安卓机器字体的字形不居中于em-square,却居中于virtual-area。此时通过line-height:normal样式使得virtual-area撑满line-box。从而实现文字居中于line-box。最后通过固定外层容器大小然后居中line-box的方式,消除前面的样式造成的line-box大小不可控的副作用。</p> <p>PS:这种方案应用于多行文本的时,无法手动控制行间距,只能使用字体设计师决定的默认行间距。在需要手动控制行间距时,还是建议放弃此方案,反正对于多行文本,1~2px的偏移对整体视觉展现不会有太大的影响<br>。</p> {{< /raw >}} # 版权声明 本文资源来源互联网,仅供学习研究使用,版权归该资源的合法拥有者所有, 本文仅用于学习、研究和交流目的。转载请注明出处、完整链接以及原作者。 原作者若认为本站侵犯了您的版权,请联系我们,我们会立即删除! ## 原文标题 安卓文本居中——关于css,字体和line-box的笔记 ## 原文链接 [https://segmentfault.com/a/1190000011833307](https://segmentfault.com/a/1190000011833307)
Python
UTF-8
196
3.390625
3
[]
no_license
def sqrt(x): last_guess = x/2.0 while True: guess = (last_guess + x/last_guess)/2 if abs(guess - last_guess) < .000001: return guess last_guess = guess
JavaScript
UTF-8
2,480
3
3
[]
no_license
$(function(){ var loaderPoke = $('.js-loader-pokeball').hide(); var setBackgroundForType = function(type) { var color = null switch(type) { case 'water': color = 'lightblue' break; case 'fire': color = 'red' break; default: color = 'green' } $('.js-pokemon-photo').css({backgroundColor: color}) } var resetDetail = function(){ $('.js-pokemon-name') .empty() $('.js-pokemon-photo') .empty() $('.js-pokemon-type') .empty() } //J'ajoute un pokemon dans la liste var addPokemonToList = function(name, url){ var li = $('<li>').text(name).addClass('pokemon-item js-pokemon-item').attr('data-url', url) $('.js-pokemon-list').append(li) } //J'ajoute un pokemon dans le detail var addPokemonToDetail = function(name, photo, types, weight, height){ var typeFormated = ''; for (var i = 0; i < types.length; i++) { typeFormated += types[i].type.name if (i < types.length-1){ typeFormated+=' and ' } else { typeFormated+='.' } } var pokeName = $('<h4>') .text('Name: '+name) .addClass('poke-name') var img = $('<img>').attr('src', photo) var type = $('<li>') .text('Type(s): '+typeFormated) .addClass('pokemon-attribute') var weight = $('<li>') .text('Weight: '+weight) .addClass('pokemon-attribute') var height = $('<li>') .text('Height: '+height) .addClass('pokemon-attribute') $('.js-pokemon-name') .append(pokeName) $('.js-pokemon-photo') .append(img) $('.js-pokemon-type') .append(type) .append(weight) .append(height) } //Je recupere la liste des pokemons $.ajax('https://pokeapi.co/api/v2/pokemon/?limit=20') .done(function(pokemons){ for (var i = 0; i < pokemons.results.length; i++) { var pokemon = pokemons.results[i] addPokemonToList(pokemon.name, pokemon.url) } }) $('.js-pokemon-list').on('click', '.js-pokemon-item', function(){ var url = $(this).attr('data-url') loaderPoke.show(); resetDetail(); $.ajax(url) .done(function(pokemon){ loaderPoke.hide(); addPokemonToDetail(pokemon.name, pokemon.sprites.front_default, pokemon.types, pokemon.weight, pokemon.height) setBackgroundForType(pokemon.types[0].type.name) console.log(pokemon.types[0].type.name) }) }) });
Java
UTF-8
6,888
1.804688
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sirelab.controller.estructuralaboratorio; import com.sirelab.ayuda.MensajesConstantes; import com.sirelab.bo.interfacebo.planta.GestionarPlantaHojasVidaEquiposBOInterface; import com.sirelab.entidades.HojaVidaEquipo; import com.sirelab.entidades.TipoEvento; import java.io.Serializable; import java.math.BigInteger; import java.text.DateFormat; import java.util.Date; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; /** * * @author ELECTRONICA */ @ManagedBean @SessionScoped public class ControllerDetallesHojaVidaEquipo implements Serializable { @EJB GestionarPlantaHojasVidaEquiposBOInterface gestionarPlantaHojasVidaEquiposBO; private String inputDetalle; private String inputFechaEvento, inputFechaFinEvento, inputFechaRegistro; private String inputObservacion, inputUsuario, inputCosto; private TipoEvento inputTipoEvento; private String mensajeFormulario; private BigInteger idEquipo; private BigInteger idHojaVidaEquipo; private HojaVidaEquipo hojaVidaEquipoDetalle; private Logger logger = Logger.getLogger(getClass().getName()); private String colorMensaje; private boolean fechaDiferidaEvento, fechaDiferidaRegistro; private MensajesConstantes constantes; public ControllerDetallesHojaVidaEquipo() { } @PostConstruct public void init() { constantes = new MensajesConstantes(); BasicConfigurator.configure(); } public void recibirIDHojaVidaEquipo(BigInteger idRegistro) { this.idHojaVidaEquipo = idRegistro; cargarInformacionRegistro(); colorMensaje = "black"; mensajeFormulario = "N/A"; } private void cargarInformacionRegistro() { hojaVidaEquipoDetalle = gestionarPlantaHojasVidaEquiposBO.consultarHojaVidaEquipoPorID(idHojaVidaEquipo); if (null != hojaVidaEquipoDetalle) { inputDetalle = hojaVidaEquipoDetalle.getDetalleevento(); inputObservacion = hojaVidaEquipoDetalle.getObservaciones(); inputUsuario = hojaVidaEquipoDetalle.getUsuariomodificacion(); inputCosto = hojaVidaEquipoDetalle.getCosto(); DateFormat df = DateFormat.getDateInstance(); Date fecha = hojaVidaEquipoDetalle.getFechaevento(); Date fecha2 = hojaVidaEquipoDetalle.getFecharegistro(); Date fecha3 = hojaVidaEquipoDetalle.getFechafinevento(); inputFechaEvento = df.format(fecha); inputFechaRegistro = df.format(fecha2); inputFechaFinEvento = df.format(fecha3); idEquipo = hojaVidaEquipoDetalle.getEquipoelemento().getIdequipoelemento(); inputTipoEvento = hojaVidaEquipoDetalle.getTipoevento(); } } public void cancelarHojaVidaEquipo() { inputDetalle = null; inputCosto = null; inputObservacion = null; inputUsuario = null; inputFechaFinEvento = null; fechaDiferidaEvento = true; fechaDiferidaRegistro = true; inputTipoEvento = null; inputFechaEvento = null; inputFechaRegistro = null; colorMensaje = "black"; mensajeFormulario = "N/A"; } public String cerrarPagina() { cancelarHojaVidaEquipo(); return "hojadevida"; } //GET-SET public String getInputDetalle() { return inputDetalle; } public void setInputDetalle(String inputDetalle) { this.inputDetalle = inputDetalle; } public String getInputFechaEvento() { return inputFechaEvento; } public void setInputFechaEvento(String inputFechaEvento) { this.inputFechaEvento = inputFechaEvento; } public String getInputFechaRegistro() { return inputFechaRegistro; } public void setInputFechaRegistro(String inputFechaRegistro) { this.inputFechaRegistro = inputFechaRegistro; } public String getMensajeFormulario() { return mensajeFormulario; } public void setMensajeFormulario(String mensajeFormulario) { this.mensajeFormulario = mensajeFormulario; } public BigInteger getIdEquipo() { return idEquipo; } public void setIdEquipo(BigInteger idEquipo) { this.idEquipo = idEquipo; } public BigInteger getIdHojaVidaEquipo() { return idHojaVidaEquipo; } public void setIdHojaVidaEquipo(BigInteger idHojaVidaEquipo) { this.idHojaVidaEquipo = idHojaVidaEquipo; } public TipoEvento getInputTipoEvento() { return inputTipoEvento; } public void setInputTipoEvento(TipoEvento inputTipoEvento) { this.inputTipoEvento = inputTipoEvento; } public HojaVidaEquipo getHojaVidaEquipoDetalle() { return hojaVidaEquipoDetalle; } public void setHojaVidaEquipoDetalle(HojaVidaEquipo hojaVidaEquipoDetalle) { this.hojaVidaEquipoDetalle = hojaVidaEquipoDetalle; } public String getColorMensaje() { return colorMensaje; } public void setColorMensaje(String colorMensaje) { this.colorMensaje = colorMensaje; } public boolean isFechaDiferidaEvento() { return fechaDiferidaEvento; } public void setFechaDiferidaEvento(boolean fechaDiferidaEvento) { this.fechaDiferidaEvento = fechaDiferidaEvento; } public boolean isFechaDiferidaRegistro() { return fechaDiferidaRegistro; } public void setFechaDiferidaRegistro(boolean fechaDiferidaRegistro) { this.fechaDiferidaRegistro = fechaDiferidaRegistro; } public String getInputFechaFinEvento() { return inputFechaFinEvento; } public void setInputFechaFinEvento(String inputFechaFinEvento) { this.inputFechaFinEvento = inputFechaFinEvento; } public String getInputObservacion() { return inputObservacion; } public void setInputObservacion(String inputObservacion) { this.inputObservacion = inputObservacion; } public String getInputUsuario() { return inputUsuario; } public void setInputUsuario(String inputUsuario) { this.inputUsuario = inputUsuario; } public String getInputCosto() { return inputCosto; } public void setInputCosto(String inputCosto) { this.inputCosto = inputCosto; } }
JavaScript
UTF-8
3,435
2.53125
3
[]
no_license
// CRUD create read update delete // const mongodb = require('mongodb') // const MongoClient = mongodb.MongoClient // const MongoClient = mongodb.ObjectID const { MongoClient, ObjectID } = require ('mongodb'); const connectionURL = 'mongodb://127.0.0.1:27017' const databaseName = 'aics-test' // const id=new ObjectID(); // console.log(id); MongoClient.connect(connectionURL, { useNewUrlParser: true }, (error, client) => { if (error) { return console.log('Unable to connect to database!') } const db = client.db(databaseName); db.collection('employee').deleteMany({ age: 15 }).then((result) => { console.log(result) }).catch((error) => { console.log(error) }) // const UpdatePromise= db.collection('employee').updateOne({ // _id: new ObjectID("5d7f79e1932b3a29fcfa9aeb") // },{ // $set: { // name: 'Harish', // gender: 'Male', // age: 34, // no: 9876543210, // mailid: 'hari@gmail.com', // } // }) // UpdatePromise.then((result) => { // console.log(result); // }).catch((error)=> { // console.log(error); // }) // read // db.collection('employee').findOne({gender: 'Female' }, (error,user)=>{ // if (error) { // return console.log("Unable to fetch"); // } // console.log(user); // }) // db.collection('employee').find({gender: 'Female' }).count((error,user)=>{ // if (error) { // return console.log("Unable to fetch"); // } // console.log(user); // }) // create // db.collection('employee').insertOne({ // name: 'demo', // age: 15, // gender: 'Female', // no: 1276543210, // mailid: '1212123def@gmail.com' // },(error, result)=>{ // if (error) { // return console.log('Unable to insert records'); // } // console.log(result.ops); // }); ////////////////////////////////////////////////////////////////// // db.collection('employee').insertMany([ // { // name: 'demo7', // age: 35, // gender: 'Female', // no: 45276543210, // mailid: '1212123def@gmail.com' // }, // { // name: 'demo8', // age: 25, // gender: 'Female', // no: 45453210, // mailid: 'ghf@gmail.com' // }, // { // name: 'demo9', // age: 24, // gender: 'Female', // no: 4545543210, // mailid: 'wer@gmail.com' // }, // { // name: 'demo10', // age: 11, // gender: 'Female', // no: 13453210, // mailid: 'rwer@gmail.com' // }, // { // name: 'demo11', // age: 22, // gender: 'Female', // no: 1346543210, // mailid: 'asd@gmail.com' // }, // { // name: 'demo12', // age: 33, // gender: 'Female', // no: 1236543210, // mailid: 'xcvb@gmail.com', // createdate: new Date(), // updatedate:"" // } // ],(error,result) => { // if (error) { // return console.log("unable to insert process"); // } // console.log(result.ops); // }) })
C++
UTF-8
3,805
3.1875
3
[]
no_license
/********************************** ** Program Name: main.cpp ** Author: Miao Pan ** Date: 01/13/2019 ** Description: This is the main function of the Langton's Ant game. **********************************/ #include <iostream> #include <string> #include "menu.cpp" #include "Board.cpp" #include "Ant.cpp" using std::cout; using std::cin; using std::endl; //main function int main(){ State gameState = newGame; while (gameState == newGame or gameState == finished){ int* menuAnswer = menu(gameState); int first = menuAnswer[0]; if (first != 0){ //Print out the user input from menu for (int i= 0; i<5; i++){ cout << "menuAnswer: " << menuAnswer[i] << endl; } cout << "Now making the game board" << endl; //Create the board Board newBoard(menuAnswer[0], menuAnswer[1]); newBoard.printBoard(); //Create the ant Ant ant1(menuAnswer[3], menuAnswer[4], menuAnswer[0], menuAnswer[1]); //Get the cell value of where the ant is sitting on char currentAntValue = newBoard.getValue(ant1.getAntRow(), ant1.getAntCol()); int stepNumber = menuAnswer[2]; if(stepNumber == 0){ newBoard.setValue(ant1.getAntRow(), ant1.getAntCol(), '*'); newBoard.printBoard(); } for(int i = 0; i < stepNumber; i++){ cout << "Iterating instance " << i << endl; if(currentAntValue == ' '){ //cout << ant1.getAntOrient() << endl; //Ant turn right cout << ant1.turnRight() << endl; //Ant change the space from white to black'#' newBoard.setValue(ant1.getAntRow(), ant1.getAntCol(), '#'); //Ant moves forward ant1.moveAnt(); //Update board cell value to * with new ant position, but before updating, get the original cell value currentAntValue = newBoard.getValue(ant1.getAntRow(), ant1.getAntCol()); newBoard.setValue(ant1.getAntRow(), ant1.getAntCol(), '*'); cout << "the cell is now *, but before it was changed, it was " << currentAntValue << endl; }else if(currentAntValue == '#'){ //Turn ant left ant1.turnLeft(); //Ant change the space from black'#' to white' '; newBoard.setValue(ant1.getAntRow(), ant1.getAntCol(), ' '); //Ant moves forward ant1.moveAnt(); //Update board cell value to * with new ant position, but before updating, get the original cell value cout << "before changing to *, this space was " << newBoard.getValue(ant1.getAntRow(), ant1.getAntCol()) << endl; currentAntValue = newBoard.getValue(ant1.getAntRow(), ant1.getAntCol()); newBoard.setValue(ant1.getAntRow(), ant1.getAntCol(), '*'); }else{ cout << "something went rong!!!!" << endl; cout << "this is iteration instance " << i << endl; } //Print the board after each step newBoard.printBoard(); } gameState = finished; } else if(first == 0){ gameState = noMore; } //deallocating menuAnswer array delete[] menuAnswer; menuAnswer = nullptr; } cout << "Thanks for your time! See you next time!" << endl; return 0; }
JavaScript
UTF-8
17,124
2.8125
3
[]
no_license
$(document).ready(function() { /* ============================================================== INITIALISATION ==============================================================*/ var page = 1 var selectedNumber = parseInt($("input[type='radio']:checked").val()) var mode = $("input.mode[type='radio']:checked").val() var auteur = "nobody" //var userId = "noId" //window.userID = "noID" $(".precedent").addClass("disabled") $(".suivant").addClass("disabled") $("#carouselMode").hide() $("#paginationMode").hide() $(".endButtons").hide() // Date picker $("#datePhoto").datepicker(); // Modal $( "#dialog" ).dialog( { autoOpen: false, title: "Informations de l'image", width: 660 }); /* ============================================================== EVENTS / ANONYMOUS FUNCTIONS ==============================================================*/ $("body").on("click", ".swipebox", function() { // Clear the dialog box content $("#dialog").empty() // If the dialog box is already open we close it var isOpen = $("#dialog").dialog("isOpen") if (isOpen) { $("#dialog").dialog( { position: { my: "center", at: "center", of: window } }); } // Some information about the image var link = $(this).attr('href') var id = $(this).attr('id') getImageInformation(id) // Construct the dialog box content $("#dialog").append('<p><b>Titre :</b> <span id="detailTitre"></span></p>') $("#dialog").append('<p><b>Auteur :</b> <span id="detailAuteur"></span></p>') $("#dialog").append('<p><b>Date :</b> <span id="detailDate"></span></p><br><br>') $( "#dialog" ).append('<img src="'+link+'">') // Open the dialog box AFTER all operations $( "#dialog" ).dialog( "open" ) return false; }); // Research button click $("#submit-photos-pagination").on("click", function() { loadContent(); }); // Research by keypress enter event in city input field $("#commune").keypress(function (e) { if (e.which == 13) { $('#submit-photos-pagination').trigger('click'); } }); // Research by keypress enter event in author input field $("#infoAuteur").keypress(function (e) { if (e.which == 13) { $('#submit-photos-pagination').trigger('click'); } }); // Previous button click $(".precedent").on("click", function() { // Always close the dialog box if it's open var isOpen = $("#dialog").dialog("isOpen") if (isOpen) $("#dialog").dialog("close") if (page != 1) page-- watchPreviousButton(page) if (mode == "page") { getDataPaginationPageMode(page) } else { getDataPaginationMode(page) } }); // Next button click $(".suivant").on("click", function() { // Always close the dialog box if it's open var isOpen = $("#dialog").dialog("isOpen") if (isOpen) $("#dialog").dialog("close") page++; watchPreviousButton(page) if (mode == "page") { getDataPaginationPageMode(page) } else { getDataPaginationMode(page) } }); // When a change occurs, update the number of images to display $("input[type='radio']").on("change",function() { selectedNumber = parseInt($("input[type='radio']:checked").val()); }) $("input.mode[type='radio']").on("change",function() { mode = $("input.mode[type='radio']:checked").val() }); /* ============================================================== FUNCTIONS ==============================================================*/ // Function to show gallery or carousel content function loadContent() { page = 1 if( $("#commune").val() == "" && $("#infoAuteur").val() == "") { alert("Vous devez saisir au moins un mot clé") $("#commune").focus() return false } // Select the correct mode if(mode == "page") { getDataPaginationPageMode(page); $("#paginationMode").show() $("#carouselMode").hide() } else if (mode == "regroupement") { getDataPaginationMode(page); $("#paginationMode").show() $("#carouselMode").hide() } else { getDataCarouselMode(page); $("#carouselMode").show() $("#paginationMode").hide() } } // This function change class of previous button relative with page function watchPreviousButton(page) { if (page == 1) $(".precedent").addClass("disabled") else $(".precedent").removeClass("disabled") } // Function to get images data from Flickr API in pagination mode function getDataPaginationMode(atPage) { var username = $("#infoAuteur").val() var userid = (function () { var ajaxResponse; $.ajax( { type: "POST", url: "https://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: "username="+username, success: function (data) { userID = data.user.id; var dataSearch = "tags=" + $("#commune").val()+"&per_page="+selectedNumber+"&page="+atPage if ($("#datePhoto").val() != "A partir de") { date = ($("#datePhoto").val()); date = Date.parse(date)/1000; dataSearch += "&min_upload_date="+date+"&sort=date-posted-asc" } else date = "0"; if ($("#infoAuteur").val() != ''){ dataSearch += "&user_id="+userID } $(".endButtons").show() // Set next button available $(".suivant").removeClass("disabled") // Clear the div of images when a new research is done $("#showImagesPaginationMode").empty(); // Ajax JSON request $.ajax( { type: "POST", dataType: "json", url: "https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: dataSearch, success: function(data) { if (data.photos.photo.length == 0) alert("Aucune données pour cette recherche") $.each(data.photos.photo, function(i, image) { // Show only the good number of images if(i == selectedNumber) return false; // Call getImages function to delegate the responsability getImagesPaginationMode(image); }) }, error : function() { alert("Une erreur dans la récupération des données est survenue.") } }); }, dataType: "json"}); }()); } // Function to get images data from Flickr API in pagination mode function getDataPaginationPageMode(atPage) { var username = $("#infoAuteur").val() var userid = (function () { var ajaxResponse; $.ajax( { type: "POST", url: "https://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: "username="+username, success: function (data) { userID = data.user.id; var dataSearch = "tags=" + $("#commune").val()+"&per_page="+selectedNumber+"&page="+atPage if ($("#datePhoto").val() != "A partir de") { date = ($("#datePhoto").val()); date = Date.parse(date)/1000; dataSearch += "&min_upload_date="+date+"&sort=date-posted-asc" } else date = "0"; if ($("#infoAuteur").val() != ''){ dataSearch += "&user_id="+userID } $(".endButtons").show() // Set next button available $(".suivant").removeClass("disabled") // Clear the div of images when a new research is done $("#showImagesPaginationMode").empty() $("#showImagesPaginationMode").removeClass("justified-gallery") // Ajax JSON request $.ajax( { type: "POST", dataType: "json", url: "https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: dataSearch, success: function(data) { if (data.photos.photo.length == 0) alert("Aucune données pour cette recherche") $.each(data.photos.photo, function(i, image) { // Show only the good number of images if(i == selectedNumber){ return false; } // Call getImages function to delegate the responsability getImagesPaginationPageMode(image); }) }, error : function() { alert("Une erreur dans la récupération des données est survenue.") } }); }, dataType: "json"}); }()); } // Function to get data images for the carosuel mode function getDataCarouselMode(atPage) { var username = $("#infoAuteur").val() var userid = (function () { var ajaxResponse; $.ajax( { type: "POST", url: "https://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: "username="+username, success: function (data) { userID = data.user.id; var dataSearch = "tags=" + $("#commune").val()+"&per_page="+selectedNumber+"&page="+atPage if ($("#datePhoto").val() != "A partir de") { date = ($("#datePhoto").val()); date = Date.parse(date)/1000; dataSearch += "&min_upload_date="+date+"&sort=date-posted-asc" } else date = "0"; if ($("#infoAuteur").val() != '') dataSearch += "&user_id="+userID $.ajax( { type: "POST", dataType: "json", url: "https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: dataSearch, success: function(data) { if (data.photos.photo.length == 0) alert("Aucune données pour cette recherche") $.each(data.photos.photo, function(i, image) { // Show only the good number of images if(i == selectedNumber) return false; // Call getImages function to delegate the responsability getImagesCarouselMode(image); }) }, error : function() { alert("Une erreur dans la récupération des données est survenue.") } }); }, dataType: "json"}); }()); } // Function to get specific information about an image (ex : title, author, date, ...) function getImageInformation(id) { $.ajax( { type: "POST", dataType: "json", url: "https://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=0ec1c8867eeca73bca63ed9b7365ad5b&format=json&jsoncallback=?", data: "photo_id="+id, success: function(data) { var formattedTime = timeConverter(data.photo.dates.posted) if (data.photo.title._content == "") { $("#detailTitre").text("[Photo sans titre...]"); } else { $("#detailTitre").text(data.photo.title._content); } $("#detailAuteur").text(data.photo.owner.username); $("#detailDate").text(formattedTime); } }); } // Function to show image function getImagesPaginationMode(image) { var link = "http://farm"+image.farm+".staticflickr.com/"+image.server+"/"+image.id+"_"+image.secret+"_z.jpg"; var titre = image.title if (titre == "") { titre = "[Photo sans titre....]"; } $("#showImagesPaginationMode").append('<a href="'+link+'" class="swipebox" title="'+image.title+'" id="'+image.id+'"><img src="'+link+'" alt="'+titre+'"></a>') $("#showImagesPaginationMode").justifiedGallery( { lastRow : 'nojustify', rowHeight : 300, margins : 1 }).on('jg.complete', function () { return true; }); } function getImagesPaginationPageMode(image) { var link = "http://farm"+image.farm+".staticflickr.com/"+image.server+"/"+image.id+"_"+image.secret+"_z.jpg"; var titre = image.title if (titre == "") { titre = "[Photo sans titre....]"; } $("#showImagesPaginationMode").append('<div class="col-lg-6 col-md-6 col-xs-6 col-lg-offset-3 col-md-offset-3 col-xs-offset-3"><center><a href="'+link+'" class="swipebox" title="'+image.title+'" id="'+image.id+'"><img id="imagePage" src="'+link+'" alt="'+titre+'"></a></center></div>') } // Function to show image function getImagesCarouselMode(image) { var link = "http://farm"+image.farm+".staticflickr.com/"+image.server+"/"+image.id+"_"+image.secret+"_z.jpg"; $(".jcarousel-list").append('<li><a class="swipebox" href="'+link+'" title="'+image.title+'" id="'+image.id+'"><img src="'+link+'" width="600" height="400" alt=""></a></li>') $('.jcarousel').jcarousel('reload'); } // Function to convert a date (unix time stamp) in a readable format by humans // This function will no longer work on 19 January 2038 :=) function timeConverter(UNIX_timestamp) { var a = new Date(UNIX_timestamp*1000); var months = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre']; var year = a.getFullYear(); var month = months[a.getMonth()]; var date = a.getDate(); var hour = a.getHours(); var min = a.getMinutes(); var sec = a.getSeconds(); var time = date + ' ' + month + ' ' + year + ' - ' + hour + ':' + min + ':' + sec ; return time; } });
Java
UTF-8
1,189
2.359375
2
[]
no_license
package com.lp.sidebar_master.adapter; import android.content.Context; import com.lp.sidebar_master.R; import com.lp.sidebar_master.base.viewholder.CommonAdapter; import com.lp.sidebar_master.base.viewholder.ViewHolder; import com.lp.sidebar_master.presenter.CountryBean; import java.util.List; /** * 俩种adapter封装框架实现 供演示 * File descripition: 选择国家 * * @author lp * @date 2018/8/4 */ public class CountryLvAdapter extends CommonAdapter<CountryBean> { public CountryLvAdapter(Context context, List<CountryBean> datas, int layoutId) { super(context, datas, layoutId); } @Override public void convert(ViewHolder holder, CountryBean countryBean) { holder.setText(R.id.tv_name, countryBean.getName()); holder.setText(R.id.tv_number, countryBean.getCode()); if (countryBean.getLetter()) { holder.setVisible(R.id.tv_letter, true); holder.setVisible(R.id.view, true); holder.setText(R.id.tv_letter, countryBean.getSortLetters()); } else { holder.setVisible(R.id.tv_letter, false); holder.setVisible(R.id.view, false); } } }
Ruby
UTF-8
2,610
2.828125
3
[]
no_license
require 'nokogiri' require 'nori' require_relative 'error' module WSDiscovery # Represents the probe response. class Response attr_accessor :response # @param [String] response Text of the response to a WSDiscovery probe. def initialize(response) @response = response end # Shortcut accessor for the SOAP response body Hash. # # @param [Symbol] key The key to access in the body Hash. # @return [Hash,String] The accessed value. def [](key) body[key] end # Returns the SOAP response header as a Hash. # # @return [Hash] SOAP response header. # @raise [WSDiscovery::Error] If unable to parse response. def header unless hash.has_key? :envelope raise WSDiscovery::Error, "Unable to parse response body '#{to_xml}'" end hash[:envelope][:header] end # Returns the SOAP response body as a Hash. # # @return [Hash] SOAP response body. # @raise [WSDiscovery::Error] If unable to parse response. def body unless hash.has_key? :envelope raise WSDiscovery::Error, "Unable to parse response body '#{to_xml}'" end hash[:envelope][:body] end alias to_hash body # Returns the complete SOAP response XML without normalization. # # @return [Hash] Complete SOAP response Hash. def hash @hash ||= nori.parse(to_xml) end # Returns the SOAP response XML. # # @return [String] Raw SOAP response XML. def to_xml response end # Returns a Nokogiri::XML::Document for the SOAP response XML. # # @return [Nokogiri::XML::Document] Document for the SOAP response. def doc @doc ||= Nokogiri::XML(to_xml) end # Returns an Array of Nokogiri::XML::Node objects retrieved with the given +path+. # Automatically adds all of the document's namespaces unless a +namespaces+ hash is provided. # # @param [String] path XPath to search. # @param [Hash<String>] namespaces Namespaces to append. def xpath(path, namespaces = nil) doc.xpath(path, namespaces || xml_namespaces) end private # XML Namespaces from the Document. # # @return [Hash] Namespaces from the Document. def xml_namespaces @xml_namespaces ||= doc.collect_namespaces end # Returns a Nori parser. # # @return [Nori] Nori parser. def nori return @nori if @nori nori_options = { strip_namespaces: true, convert_tags_to: lambda { |tag| tag.snakecase.to_sym } } @nori = Nori.new(nori_options) end end end
C#
UTF-8
1,257
3.328125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace System.Data.Wrapper { /// <summary> /// Extension methods /// </summary> internal static class Extensions { /// <summary> /// Ensures that a string ends with ".sql" /// </summary> /// <param name="filename">string to check</param> internal static string EnsureSqlFile(this string filename) { if (filename == null || filename.EndsWith(".sql")) return filename; return $"{filename}.sql"; } /// <summary> /// An extension method that throws an <see cref="ArgumentException"/> when <paramref name="instance"/> is null. /// </summary> /// <typeparam name="T">The type of object to be checked for null</typeparam> /// <param name="instance">The object to be checked for null</param> /// <param name="argName">The name to give to the constructor of <see cref="ArgumentException"/></param> internal static T ThrowIfNull<T>(this T instance, string argName) { if (instance == null) throw new ArgumentNullException(argName); return instance; } } }
JavaScript
UTF-8
2,886
2.859375
3
[]
no_license
import React, { Component } from "react"; //Используем готовый компонент infiniteScroll import InfiniteScroll from "react-infinite-scroller"; import ArrayItem from "./ArrayItem"; import ArrayList from "./ArrayList"; //Запрос локального JSON через fetch. const dataLink = `${window.location.href}data.json`; class ItemList extends Component { state = { // Храним наш JSON, количество выводимых элементов, // максимальную длину массива, и проверку на окончание dataStore: [], length: 10, maxLength: null, hasMoreItems: true }; fetchData = (data, numberOfItem, pageNumber) => { //проверяем максимальную длину, вдруг кто-то добавил что-то в json const maxLength = data.length; const currentLength = pageNumber * 10; //обрезаем полученный массив при помощи изменения его длины data.length = numberOfItem; //меняем стейт для текущей страницы this.setState({ dataStore: data, maxLength, length: currentLength }); }; loadMoreData = page => { const length = this.state.length; const maxLength = this.state.maxLength; const numberOfItem = 10 * page; //Мнимая задержка на загрузку, для дебага. setTimeout(() => { //проверка на последний элемент, выводим оставшиеся элементы, не кратные 10 if (length >= maxLength && maxLength != null) { this.setState({ hasMoreItems: false }); } fetch(dataLink) .then(response => response.json()) .then(data => this.fetchData(data, numberOfItem, page)); }, 1000); }; render() { const { dataStore } = this.state; return ( <ArrayList> <InfiniteScroll pageStart={0} loadMore={this.loadMoreData} hasMore={this.state.hasMoreItems} loader={<div className="lds-dual-ring" key={0} />} > {dataStore.map((item, i) => ( <ArrayItem key={i} id={item.id} avatar={item.avatar} firstName={item.first_name} text={item.newsInput} /> ))} </InfiniteScroll> </ArrayList> ); } } export default ItemList;
PHP
UTF-8
777
2.546875
3
[]
no_license
<?php /** @noinspection PhpMissingDocCommentInspection */ declare(strict_types=1); namespace tests\Exporters\Processors; use PHPUnit\Framework\TestCase; use vvvitaly\txs\Core\Export\Data\Transaction; use vvvitaly\txs\Exporters\Processors\AutoIdCounter; final class AutoIdCounterTest extends TestCase { public function testProcess(): void { $tx1 = new Transaction(); $tx2 = new Transaction(); $tx3 = new Transaction(); $processor = new AutoIdCounter('test.', 100); $processor->process($tx1); $processor->process($tx2); $processor->process($tx3); $this->assertEquals('test.100', $tx1->id); $this->assertEquals('test.101', $tx2->id); $this->assertEquals('test.102', $tx3->id); } }
Markdown
UTF-8
3,422
3.4375
3
[]
no_license
# JavaScript All the Way Down ![turtles](http://www.tricycle.com/sites/default/files/images/webexclusives/turtles.jpg) Today, you learned how to allow your client-side JavaScript to talk to your Express server through the magic of AJAX. Tonight, you're going to get some more practice with AJAX and continue working with Express servers. ### Objectives: 1. Pay close attention to the division between client-side and server-side code. What happens where? What order do things happen in? What messages are passed back and forth? 1. Use `bower` to manage & install your client-side dependencies (jQuery, handlebars, etc.) 1. Use `npm` to manage & install your server-side dependencies (express, ejs, etc.) 1. Practice using these new tools to create a Single Page Application, or a single-page website that's updated dynamically as the user interacts with the page (no page refreshes!). ### Resources Now that we're using JavaScript on the client AND the server, it can get more difficult keeping track of what needs to happen and which tools we need to use on the client and on the server. Here's a handy table that lists a few key tools: | | Server-side (Node) | Client-side (browser) | |:----------------------------------|:---------------------:|:--------------------------------:| | **Language** | JavaScript | JavaScript | | **Dependency Management** | npm | bower | | **Parsing/Interacting with HTML** | `cheerio` package | jQuery | | **HTTP Requests** | `request` package | AJAX | | **Templating** | `ejs` package `<% %>` | `handlebars` library {{ }} | ## Part One: [That Heart's Still Going On and On...](https://www.youtube.com/watch?v=WNIPqafd4As) Keep working on the [Titanic prompt](https://github.com/ga-students/wdi-persephone/tree/master/unit_d/w12/d04/classwork/titanic_lab)! Once you've got MVP functionality (everything but the bonus), move on to the simple CRUD app below. If you finish with that, circle back to the Titanic bonus prompts. ## Part Two: What's in YOUR Closet? ![closet](http://www.ecouterre.com/wp-content/uploads/2010/05/clothes-closet.jpg) _Your closet is a total mess. Write a web application to help you keep track of your suits, sweats, and sneakers!_ The overall functionality for this app will be similar to the Burrito Express app you worked on last night - the difference is that this time, you'll be utilizing AJAX to perform CRUD actions instead of refreshing the page. ### Creating the Server - First, write a server using Express that renders a single index page. This page should include a header and a section for - Your server should accept GET, POST, PUT and DELETE requests for `item`s and respond with JSON. - Store your data in an `items.json` file. You can start your file off with a few items already. ### In the Browser - Use AJAX to allow your user to CRUD a single resource. Your application should allow the user to: - Track each clothing item's color, size and clothing_type. - Display an ordered list of clothing items when the user visits the index page. - Allow a user to delete an item. **Bonus:** Allow users to make edits to items without needing to navigate to another page!
PHP
UTF-8
163
3.3125
3
[]
no_license
<?php // Function to find out BMI function BMI($mass,$height){ $BMI = $mass / ($height * $height); echo "Your BMI Is = $BMI <br>"; } BMI(70,6);
C++
UTF-8
370
2.96875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; long sum = 0; string s; cin>>n; while (n-- > 0){ cin>>s; if (s == "Tetrahedron"){ sum += 4; } else if ( s == "Cube"){ sum += 6; } else if (s == "Octahedron"){ sum += 8; } else if (s == "Dodecahedron"){ sum += 12; } else{ sum += 20; } } cout<<sum; return 0; }