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
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 87
| 2.796875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
# python 3
d = """this
will be printed
in 3 lines"""
print(d)
|
Java
|
UTF-8
| 425
| 2.65625
| 3
|
[] |
no_license
|
package br.edu.fapi.roda;
public class Roda {
private double aro;
private String material;
public Roda ( double aro, String material) {
this.aro = aro;
this.material = material;
}
public double getAro() {
return aro;
}
public void setAro(double aro) {
this.aro = aro;
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
}
|
Java
|
UTF-8
| 725
| 2.1875
| 2
|
[] |
no_license
|
package pl.volanto.contacts.model;
import org.springframework.stereotype.Component;
import pl.volanto.domain.contact.Contact;
import pl.volanto.domain.contact.ContactBuilder;
import pl.volanto.domain.user.UserDTO;
@Component
public class ContactMapper {
public Contact mapToContact(ContactRest contactRest, UserDTO userDTO) {
return new ContactBuilder()
.withFirstName(contactRest.getFirstName())
.withLastName(contactRest.getLastName())
.withFirmName(contactRest.getFirmName())
.withEmail(contactRest.getEmail())
.withPhoneNumber(contactRest.getPhoneNumber())
.withUser(userDTO)
.build();
}
}
|
JavaScript
|
UTF-8
| 4,546
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//window.onload=function(){//页面加载完成后
slideLlx("slide");//参数为字符串是外层容器的id,可以多次调用
// slideLlx("slide_two");
//方法
function slideLlx(slideID){
var slide=document.getElementById(slideID);//容器
var slideLis=slide.getElementsByTagName('li');
var conut=slideLis.length;//实际图片数量
if(conut<2){
return false;//如果图片数量少于2就不开启轮播节约资源
}
var imgs=slide.getElementsByTagName("img");
var firstSrc=imgs[0].getAttribute("src");//第一张图的路径
var lastSrc=imgs[imgs.length-1].getAttribute("src");//最后一张图的路径
var offset=slide.clientWidth;//每次滚动的距离
var index=1;//当前是第一张图
var slideUl=slide.getElementsByTagName("ul")[0];//Ul
var Timer;//自动轮播定时器对象
//开头插入最后一张图
var firstLi=document.createElement("li");
var firstIMG=document.createElement("img");
firstIMG.setAttribute("src",lastSrc);
firstLi.appendChild(firstIMG);
slideUl.insertBefore(firstLi,slideUl.firstChild);//创建li并插入最后一张图的路径添加第一张图之前
slideUl.style.transform="translateX("+(-offset)+"px)";//UL滚动到第一张图的位置
//末尾插入第一张图
var lastLi=document.createElement("li");
var lastIMG=document.createElement("img");
lastIMG.setAttribute("src",firstSrc);
lastLi.appendChild(lastIMG);
slideUl.appendChild(lastLi);
//创建圆点控制按钮
var circle_btn=document.createElement("div");
circle_btn.setAttribute("class","circle_btn");
for(var i=0;i<conut;i++){ //创建等同于图片数的按钮
var cbtn=document.createElement("button");
circle_btn.appendChild(cbtn);
}
slide.appendChild(circle_btn);
//圆点绑定点击事件
var circles=Array.prototype.slice.call(circle_btn.getElementsByTagName("button"));
circles[0].setAttribute("class","active");//第一个圆点高亮
circles.forEach(function(e,i){
e.onclick=function(){
closeAutoSlide();
openTransition();
index=i+1;
goslide();
beActive(this);
}
});
//创建上一个按钮,并且绑定点击事件
var btn_prev=slide.getElementsByClassName("prev_btn")[0];
btn_prev.onclick=function(){
closeAutoSlide();
openTransition();//开启过渡
index--;
goslide();
if(index<1){
index=conut;
beActive(circles[index-1]);
setTimeout(function(){
closeTransition();
goslide();
},600)
}else{
beActive(circles[index-1]);
}
}
//创建下一个按钮,并绑定点击事件
var btn_next=slide.getElementsByClassName("next_btn")[0];
btn_next.onclick=function(){
openTransition();//开启过渡
index++;
goslide();
if(index>conut){
index=1;
beActive(circles[index-1]);
setTimeout(function(){
closeTransition();
goslide();
},600)
}else{
beActive(circles[index-1]);
}
}
//定时器自动轮播
openAutoSlide();//默认开启自动轮播
function openAutoSlide(){
if(Timer){
window.clearInterval(Timer);
}
Timer=setInterval(function(){
beActive(circles[index-1]);
btn_next.onclick();
},3000)//轮播间隔时间
}
//暂停自动轮播,并且在6秒后再次开始轮播
function closeAutoSlide(){
window.clearInterval(Timer);
setTimeout(function(){
openAutoSlide();
},6000);//暂停后再次开始的时间
}
//用户操作时暂停自动
btn_next.onmousedown=function(){
closeAutoSlide();
}
btn_prev.onmousedown=function(){
closeAutoSlide();
}
//为圆点添加高亮,高亮效果可以去修改对应的css
function beActive(btn){
circle_btn.getElementsByClassName("active")[0].setAttribute("class","");
btn.setAttribute("class","active");
}
//打开过渡效果
function openTransition(){
slideUl.style.transition="all .6s";//完成动画的时间为600毫秒如果更改这里请把上面的600也相应的修改
}
//关闭过渡效果
function closeTransition(){
slideUl.style.transition="none";
}
//滚动到index相应的位置
function goslide(){
slideUl.style.transform="translateX(-"+index*offset+"px)";
}
//响应式,根据浏览器窗口变化
slideUl.style.width=slideLis.length*100+"%";
var liWidth=100/slideLis.length+"%";
for(var i=0;i<slideLis.length;i++){
slideLis[i].style.width=liWidth;
}
window.onresize=function(){
closeTransition();//关闭动画
offset=slide.clientWidth;
goslide();//重置UL的位置
}
}
//}
|
PHP
|
UTF-8
| 4,824
| 2.734375
| 3
|
[] |
no_license
|
<?php
/*
* [The "BSD licence"]
* Copyright (c) 2003-2005 Terence Parr, 2010 Yauhen Yakimovich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Antlr
* @package Antlr_StringTemplate
* @author Terence Parr
* @author Yauhen Yakimovich
* @copyright 2003-2005 Terence Parr, 2010 Yauhen Yakimovich
* @license http://www.opensource.org/licenses/bsd-license.php The BSD License
* @link http://www.stringtemplate.org/
*/
namespace Antlr\StringTemplate\Language;
use Antlr\StringTemplate\StringTemplate;
/** Represents the name of a formal argument
* defined in a template:
*
* group test;
* test(a,b) : "$a$ $b$"
* t() : "blort"
*
* Each template has a set of these formal arguments or uses
* a placeholder object: UNKNOWN (indicating that no arguments
* were specified such as when a template is loaded from a file.st).
*
* Note: originally, I tracked cardinality as well as the name of an
* attribute. I'm leaving the code here as I suspect something may come
* of it later. Currently, though, cardinality is not used.
*
* @category Antlr
* @package Antlr_StringTemplate
* @author Terence Parr
* @author Yauhen Yakimovich
* @copyright 2003-2005 Terence Parr, 2010 Yauhen Yakimovich
* @license http://www.opensource.org/licenses/bsd-license.php The BSD License
* @link http://www.stringtemplate.org/
*/
class FormalArgument {
// the following represent bit positions emulating a cardinality bitset.
const OPTIONAL = 1; // a?
const REQUIRED = 2; // a
const ZERO_OR_MORE = 4; // a*
const ONE_OR_MORE = 8; // a+
static public $suffixes = array(
null,
"?",
"",
null,
"*",
null,
null,
null,
"+"
);
/** When template arguments are not available such as when the user
* uses "new StringTemplate(...)", then the list of formal arguments
* must be distinguished from the case where a template can specify
* args and there just aren't any such as the t() template above.
*/
//static public $UNKNOWN = array();
const UNKNOWN = 16;
/**
* @var string
*/
public $name;
//protected int cardinality = REQUIRED;
/** If they specified name="value", store the template here
* @var StringTemplate
*/
public $defaultValueST;
public function FormalArgument($name, $defaultValueST = null) {
$this->name = $name;
if ($defaultValueST) {
$this->defaultValueST = $defaultValueST;
}
}
public static function getCardinalityName($cardinality) {
switch (cardinality) {
case self::OPTIONAL : return "optional";
case self::REQUIRED : return "exactly one";
case self::ZERO_OR_MORE : return "zero-or-more";
case self::ONE_OR_MORE : return "one-or-more";
default : return "unknown";
}
}
public function equals($object) {
if ( $object==null || !($object instanceof FormalArgument) ) {
return false;
}
if ( !$this->name->equals($object->name) ) {
return false;
}
// only check if there is a default value; that's all
if ( ($this->defaultValueST!=null && $object->defaultValueST==null) ||
($this->defaultValueST==null && $object->defaultValueST!=null) ) {
return false;
}
return true;
}
public function toString() {
if ( $this->defaultValueST!=null ) {
return $this->name . "=" . $this->defaultValueST;
}
return $this->name;
}
}
|
Java
|
UTF-8
| 1,120
| 2.453125
| 2
|
[] |
no_license
|
package org.example.helloandroid;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
LoadGetResponse loader = new LoadGetResponse();
loader.execute("start");
}
public class LoadGetResponse extends AsyncTask<String,Integer,String>{
protected void onPreExecute(String s){
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
GetMethodEx test = new GetMethodEx();
String returned = null;
try{
returned = test.getInternetData();
}
catch(Exception e){
e.printStackTrace();
}
return returned;
}
protected void onProgressUpdated(Integer...progress){
}
protected void onPostExecute(String result){
httpStuff.setText(result);
}
}
}
|
Java
|
UTF-8
| 1,003
| 2.140625
| 2
|
[] |
no_license
|
package com.example.vishambar.webserviceusingretrofit.advanced.activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.vishambar.webserviceusingretrofit.R;
import com.example.vishambar.webserviceusingretrofit.advanced.MyApplication;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (MyApplication.isLogin()) {
startActivity(new Intent(SplashActivity.this, ItemsActivity.class));
}else{
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
}
finish();
}
}, 5000);
}
}
|
Ruby
|
UTF-8
| 487
| 3.171875
| 3
|
[] |
no_license
|
def price(item:, size:)
items = {"コーヒー" => 300 , "モカ" => 400}
sizes = {"ショート" => 0, "トール" => 50, "ベンティ" => 100}
items[item] + sizes[size]
end
puts price(item:"コーヒー", size:"ショート")
puts price(item:"コーヒー", size:"トール")
puts price(item:"コーヒー", size:"ベンティ")
puts price(item:"モカ", size:"ショート")
puts price(item:"モカ", size:"トール")
puts price(item:"モカ", size:"ベンティ")
|
Java
|
UTF-8
| 693
| 2.140625
| 2
|
[] |
no_license
|
package com.example.multipledatabasespringboot.service;
import com.example.multipledatabasespringboot.model.request.CustomerRequest;
import com.example.multipledatabasespringboot.model.response.CustomerResponse;
import com.example.multipledatabasespringboot.model.response.PaginateResponse;
/**
* Project title: multiple-database-spring-boot
*
* @author johnadeshola
* Date: 9/9/21
* Time: 8:42 AM
*/
public interface CustomerService {
CustomerResponse createCustomer(CustomerRequest request);
CustomerResponse fetchCustomer(Long id);
CustomerResponse fetchCustomer(String username);
public PaginateResponse<CustomerResponse> fetchCustomers(int start, int limit);
}
|
Java
|
UTF-8
| 1,043
| 2.6875
| 3
|
[] |
no_license
|
package nwpu.sherman.bean;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.util.StringValueResolver;
/**
* 演示Aware接口
*
* @author sherman
*/
public class FooAware implements ApplicationContextAware, EmbeddedValueResolverAware {
/**
* 该方法的入参applicationContext即为Spring容器底层的组件,能够直接拿到
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println(applicationContext);
}
/**
* 该方法的入参stringValueResolver即为Spring容器底层的组件,能够直接拿到
*/
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
System.out.println(resolver.resolveStringValue("hello: ${os.name}" + ", I am #{2571 * 2}"));
}
}
|
PHP
|
UTF-8
| 1,618
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Template Selector plugin for Craft CMS 3.x
*
* A fieldtype that allows you to select a template from a dropdown.
*
* @link https://swishdigital.co
* @copyright Copyright (c) 2022 Swish Digital
*/
namespace swishdigital\templateselector\services;
use swishdigital\templateselector\TemplateSelector;
use Craft;
use craft\base\Component;
use craft\helpers\App;
/**
* TemplateSelectorService Service
*
* All of your plugin’s business logic should go in services, including saving data,
* retrieving data, etc. They provide APIs that your controllers, template variables,
* and other plugins can interact with.
*
* https://craftcms.com/docs/plugins/services
*
* @author Swish Digital
* @package TemplateSelector
* @since 1.0.0
*/
class TemplateSelectorService extends Component
{
// Public Methods
// =========================================================================
/**
* This function can literally be anything you want, and you can have as many service
* functions as you want
*
* From any other plugin file, call it like this:
*
* TemplateSelector::$plugin->templateSelectorService->getSubfolder($fieldHandle)
*
* @param null $fieldHandle
* @return mixed
*/
public function getSubfolder($fieldHandle = null)
{
if(!$fieldHandle) return null;
$field = Craft::$app->getFields()->getFieldByHandle($fieldHandle) ?? null;
if(!$field) return null;
$fieldSettings = $field->getSettings();
return App::parseEnv($fieldSettings['limitToSubfolder']);
}
}
|
Java
|
UTF-8
| 1,578
| 2
| 2
|
[] |
no_license
|
/**
*
*/
package com.turkmen.mongodb.MongoDbIntegrationWithSpringBoot.configuration;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.MongoClient;
import cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodStarter;
/**
* @author TTTDEMIRCI
*
*/
@Configuration
public class MongoDbConfiguration {
private static final Logger logger=LoggerFactory.getLogger(MongoDbConfiguration.class);
@Value("${spring.data.mongodb.host}")
private String mongoUrl;
@Value("${spring.data.mongodb.database}")
private String mongoDbName;
@Value("${spring.data.mongodb.port}")
private int mongoPort;
MongodStarter starter = MongodStarter.getDefaultInstance();
MongodExecutable mongodExecutable;
@Bean
public MongoTemplate mongoTemplate() throws IOException {
logger.info("Starting embeded mongo db.................................");
EmbeddedMongoFactoryBean mongoFactoryBean = new EmbeddedMongoFactoryBean();
mongoFactoryBean.setBindIp(mongoUrl);
MongoClient mongoClient = mongoFactoryBean.getObject();
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, mongoDbName);
return mongoTemplate;
}
}
|
Markdown
|
UTF-8
| 4,542
| 3
| 3
|
[
"MIT"
] |
permissive
|
---
title: មនុស្សក៏ត្រឡប់ជាមានព្រលឹងរស់ឡើង
date: 08/10/2022
---
### អំណានព្រះគម្ពីរសម្រាប់មេរៀនប្រចាំសប្តាហ៍នេះ៖
លោកុប្បត្តិ 2៖7, 19; អេសេគាល 18៖4, 20; សាស្តា 12៖1-7; សាស្តា 9៖5; ពង្សាវតាក្សត្រទី1 2៖10។
> <p>ខចងចាំ</p>
> «ព្រះយេហូវ៉ាដ៏ជាព្រះទ្រង់យកធូលីដីមកសូនធ្វើជាមនុស្ស ទ្រង់ផ្លុំខ្យល់ដង្ហើមជីវិតបញ្ចូល ទៅក្នុងរន្ធច្រមុះ នោះក៏ត្រឡប់ជាមានព្រលឹងរស់ឡើង» (លោកុប្បត្តិ 2៖7)។
ព្រះបានព្រមានលោកអ័ដាម និងនាងអេវ៉ានៅក្នុងសួនច្បារអេដែនថា «អ្នកទាំងពីរនឹងស្លាប់ ជាមិនខាន» (លោកុប្បត្តិ 3៖3, 4, គខប)។ ប៉ុន្តែ សាតាំងបានសន្យានឹងពួកគេថា «ទេ! អ្នកទាំងពីរ នឹងមិនស្លាប់ទេ» (លោកុប្បត្តិ 3៖3, 4, គខប)។ ការព្រមានរបស់ព្រះ និងការសន្យារបស់សាតាំងបានបង្ហាញយើងនូវទស្សនៈ2ខុសគ្នា អំពីសេចក្តីស្លាប់ និងការហៀបនឹងស្លាប់។ គោលគំនិតទាំងនេះ បានបន្តមកដល់សព្វថ្ងៃនេះ។
មនុស្សខ្លះបាននិយាយថា ការសន្យារបស់សាតាំងក៏ដូចគ្នាទៅនឹងការព្រមានរបស់ព្រះដែរ។ ពួកគេបាននិយាយថា ការព្រមានថា «អ្នកទាំងពីរនឹងស្លាប់ជាមិនខាន» នោះ គឺសំដៅទៅលើរូបកាយ ដែលអាចស្លាប់បាន។ មនុស្សទាំងនេះក៏បាននិយាយទៀត ការសន្យារបស់សាតាំងថា «ទេ! អ្នក ទាំងពីរនឹងមិនស្លាប់ទេ» នោះ គឺសំដៅទៅលើវិញ្ញាណ ដែលពួកគេគិតថា រស់នៅជារៀងរហូតនេះ ហើយ។
ប៉ុន្តែ គោលគំនិតនេះមិនត្រឹមត្រូវឡើយ។ តើព្រះបន្ទូលរបស់ព្រះ និងការកុហករបស់សាតាំង មានអត្ថន័យដូចគ្នាដែរឬទេ? តើយើងមានវិញ្ញាណមួយ ដែលអាចរស់នៅ បន្ទាប់ពីយើងស្លាប់ទៅបាន ដែរឬទេ? អ្នកប្រាជ្ញ និងអ្នកវិទ្យាសាស្ត្រជាច្រើនបានព្យាយាមឆ្លើយទៅនឹងសំណួរនេះ។ ប៉ុន្តែ ក្នុងនាម ជាអ្នកគ្រីស្ទានដែលជឿទៅលើព្រះគម្ពីរនោះ យើងត្រូវតែដឹងថា ព្រះអាទិកររបស់យើងទ្រង់បានជ្រាប អំពីយើងគ្រប់យ៉ាង (សូមអានបទគម្ពីរទំនុកដំកើង 139)។ ដូច្នេះ ប្រសិនបើយើងចង់បានចម្លើយ នោះ យើងត្រូវតែក្រឡេកមើលព្រះគម្ពីរតែមួយគត់។
**សប្តាហ៍នេ**
យើងនឹងសិក្សាថា គម្ពីរសញ្ញាចាស់បានចែងយ៉ាងដូចម្តេច អំពីរបៀបដែលព្រះ បានបង្កើតមនុស្សលោក និងអ្វីដែលនឹងត្រូវកើតឡើង នៅពេលដែលយើងស្លាប់ទៅ។
|
Java
|
UTF-8
| 806
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.ywl5320.wlmedia.enums;
/**
* Created by ywl5320 on 2018/12/31
*/
public enum WlBufferType {
BUFFER_QUEUE_SIZE("BUFFER_QUEUE_SIZE", 0), // 设置底层buffer 队列大小(所有流)
BUFFER_MEMORY_SIZE("BUFFER_MEMORY_SIZE", 1), // 设置底层buffer 内存大小(单位:M)
BUFFER_TIME("BUFFER_TIME", 2); // 设置底层buffer 时间大小(单位:s)
private String type;
private int value;
WlBufferType(String type, int value)
{
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
|
PHP
|
UTF-8
| 1,063
| 2.9375
| 3
|
[] |
no_license
|
<html>
<head>
<title>
RETRIVE DATABASE
</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$data_base = "sms";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $data_base);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
echo "<br>";
$query = "SELECT * FROM user";
$data = mysqli_query($conn, $query);
if($data)
{
echo "Database queried successfully";
}
else
{
echo "Error quering database".mysql_error();
}
?>
<br>
<table>
<tr>
<th>
ID
</th>
<th>
EMAIL
</th>
<th>
PASSWORD
</th>
<th>
TELEPHONE
</th>
<th>
MESSAGE
</th>
</tr>
<?php
while($info = mysqli_fetch_array($data))
{
print "<tr>";
print "<td>".$info[0]."</td>";
print "<td>".$info[1]."</td>";
print "<td>".$info[2]."</td>";
print "<td>".$info[3]."</td>";
print "<td>".$info[4]."</td>";
print "</tr>";
}
?>
</table>
<?php
mysqli_close($conn);
?>
</body>
</html>
|
PHP
|
UTF-8
| 800
| 2.609375
| 3
|
[] |
no_license
|
<?php
/* Copyright 2014, Charlie Fyvie-Gauld (Carrotsrg.org)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
class Managers
{
private static $resourceManager = null;
private static $appConfig = null;
public static function setResourceManager($resman)
{
if(self::$resourceManager != null)
return;
self::$resourceManager = $resman;
}
public static function ResourceManager()
{
return self::$resourceManager;
}
public static function setAppConfig($config)
{
if(self::$appConfig != null)
return;
self::$appConfig = $config;
}
public static function AppConfig()
{
return self::$appConfig;
}
}
?>
|
C#
|
UTF-8
| 5,574
| 2.734375
| 3
|
[] |
no_license
|
using Microsoft.Extensions.Logging;
using WEBAPI.DAL.Repository;
using WEBAPI.DAL.Entities;
using System.Collections.Generic;
using System.Linq;
namespace WEBAPI.BL
{
public class FillDatabase
{
IEducationRepository _educationRepository;
private ILogger _logger;
public FillDatabase(IEducationRepository educationRepository)
{
_educationRepository = educationRepository;
}
public FillDatabase(IEducationRepository educationRepository, ILogger logger) : this(educationRepository)
{
_logger = logger;
}
public void FillDatabaseTestData()
{
_educationRepository.EnsureDeleted();
_educationRepository.EnsureCreated();
List<Student> students = new List<Student>() {
new Student() { FullName = "Ivan Ivanov", EMail="Foo@Bar.baz", Phone = "123456" },
new Student() { FullName = "Nikolai Ivanov", EMail="Nikolai@Bar.baz", Phone = "123456" },
new Student() { FullName = "Serdei Ivanov", EMail="Serdei@Bar.baz", Phone = "123456" },
new Student() { FullName = "Petr Ivanov", EMail="Petr@Bar.baz", Phone = "123456" }
};
IStudentRepository studentRepository = _educationRepository.GetStudentRepository();
students.ForEach(s => studentRepository.InsertStudent(s));
studentRepository.Save();
List<Lecturer> lecturers = new List<Lecturer>() { new Lecturer() { FullName = "Sergei Petrov" }, new Lecturer() { FullName = "Nick Petrov" } };
ILecturerRepository lecturerRepository = _educationRepository.GetLecturerRepository();
lecturers.ForEach(l => lecturerRepository.InsertLecturer(l));
lecturerRepository.Save();
List<Lecture> lectures = new List<Lecture> {
new Lecture() { Title = "Jamping", Lecturer = lecturerRepository.GetLecturers().First() },
new Lecture() { Title = "Riding", Lecturer = lecturerRepository.GetLecturers().First() },
new Lecture() { Title = "Joging", Lecturer = lecturerRepository.GetLecturers().First() },
new Lecture() { Title = "Climbing", Lecturer = lecturerRepository.GetLecturers().Last() }
};
ILectureRepository lectureRepository = _educationRepository.GetLectureRepository();
lectures.ForEach(l => lectureRepository.InsertLecture(l));
lectureRepository.Save();
List<AttendingLecture> attendingLectures = new List<AttendingLecture> {
new AttendingLecture() { Atended = false, Lecture = lectureRepository.GetLectures().ToList()[0], Student = studentRepository.GetStudents().ToList()[0] },
new AttendingLecture() { Atended = false, Lecture = lectureRepository.GetLectures().ToList()[1], Student = studentRepository.GetStudents().ToList()[0]},
new AttendingLecture() { Atended = false, Lecture = lectureRepository.GetLectures().ToList()[2], Student = studentRepository.GetStudents().ToList()[0]},
new AttendingLecture() { Atended = false, Lecture = lectureRepository.GetLectures().ToList()[3], Student = studentRepository.GetStudents().ToList()[0]},
new AttendingLecture() { Atended = true, Lecture = lectureRepository.GetLectures().ToList()[0], Student = studentRepository.GetStudents().ToList()[1] },
new AttendingLecture() { Atended = true, Lecture = lectureRepository.GetLectures().ToList()[1], Student = studentRepository.GetStudents().ToList()[1]},
new AttendingLecture() { Atended = true, Lecture = lectureRepository.GetLectures().ToList()[2], Student = studentRepository.GetStudents().ToList()[1]},
new AttendingLecture() { Atended = false, Lecture = lectureRepository.GetLectures().ToList()[3], Student = studentRepository.GetStudents().ToList()[1]},
new AttendingLecture() { Atended = false, Lecture = lectureRepository.GetLectures().Last(), Student = studentRepository.GetStudents().Last() }
};
IAttendingLectureRepository attendingLectureRepository = _educationRepository.GetAttendingLectureRepository();
attendingLectures.ForEach(a => attendingLectureRepository.InsertAttendingLecture(a));
attendingLectureRepository.Save();
attendingLectures = attendingLectureRepository.GetAttendingLectures().ToList();
List<HomeWork> homeWorks = new List<HomeWork> {
new HomeWork() { AttendingLecture = attendingLectures[0], CourseGrade = 0 },
new HomeWork() { AttendingLecture = attendingLectures[1], CourseGrade = 1 },
new HomeWork() { AttendingLecture = attendingLectures[2], CourseGrade = 2 },
new HomeWork() { AttendingLecture = attendingLectures[3], CourseGrade = 3 },
new HomeWork() { AttendingLecture = attendingLectures[4], CourseGrade = 4 } ,
new HomeWork() { AttendingLecture = attendingLectures[5], CourseGrade =4 },
new HomeWork() { AttendingLecture = attendingLectures[6], CourseGrade = 4 },
new HomeWork() { AttendingLecture = attendingLectures[7], CourseGrade = 4 },
new HomeWork() { AttendingLecture = attendingLectures[8], CourseGrade = 1},
};
IHomeWorkRepository homeWorkRepository = _educationRepository.GetHomeWorkRepository();
homeWorks.ForEach(h => homeWorkRepository.InsertHomeWork(h));
homeWorkRepository.Save();
}
}
}
|
Python
|
UTF-8
| 2,059
| 2.59375
| 3
|
[] |
no_license
|
from django.core.management.base import BaseCommand, CommandError
from sklearn.feature_extraction.text import TfidfVectorizer
from explore.models import Article, ArticleTFIDF
from explore.utils import *
class Command(BaseCommand) :
args = 'no arguments'
help = '(re)builds the ArticleTFIDF table'
def handle(self, *args, **options) :
# delete previous
tfidfs = ArticleTFIDF.objects.all()
if len(tfidfs) :
self.stdout.write("Deleting ArticleTFIDF table... ", ending='')
self.stdout.flush()
tfidfs.delete()
self.stdout.write("deleted!\n")
articles = Article.objects.all()
# run tfidf
v = TfidfVectorizer(min_df=1, stop_words=get_stop_words())
self.stdout.write("Running TFIDF on %d articles... " % \
len(articles), ending='')
self.stdout.flush()
m = v.fit_transform(build_corpus())
self.stdout.write("done!\n")
# build ArticleTFIDF table
features = v.get_feature_names()
progress_divisor = float(len(articles)) / 100.0
progress_string = "Writing ArticleTFIDF table (%d documents, %d features)... " % \
(len(articles), len(features))
self.stdout.write(progress_string + "0.00%%", ending='')
self.stdout.flush()
for aindex,article in enumerate(articles) :
tfidfs = []
for findex,feature in enumerate(features) :
value = m[aindex,findex]
if value :
tfidf = ArticleTFIDF()
tfidf.article = article
tfidf.term = feature
tfidf.value = value
tfidfs.append(tfidf)
ArticleTFIDF.objects.bulk_create(tfidfs)
self.stdout.write("\r" + progress_string + ("%.2f%%" % ((aindex+1) / progress_divisor)), ending='')
self.stdout.flush()
self.stdout.write("\r" + progress_string + "done! \n")
|
Go
|
UTF-8
| 2,646
| 2.953125
| 3
|
[
"ISC"
] |
permissive
|
package main
type status int
const (
StatusExhausted status = iota
StatusSwift
StatusLignification
StatusConfusion
StatusNausea
StatusFlames // fake status
StatusHidden
StatusUnhidden
StatusLight
StatusDig
StatusLevitation
StatusShadows
StatusIlluminated
StatusTransparent
StatusDisguised
StatusDelay
StatusDispersal
)
func (st status) Flag() bool {
switch st {
case StatusFlames, StatusHidden, StatusUnhidden, StatusLight:
return true
default:
return false
}
}
func (st status) Clean() bool {
switch st {
case StatusDelay:
return true
default:
return false
}
}
func (st status) Info() bool {
switch st {
case StatusFlames, StatusHidden, StatusUnhidden, StatusLight, StatusDelay:
return true
}
return false
}
func (st status) Good() bool {
switch st {
case StatusSwift, StatusDig, StatusHidden, StatusLevitation, StatusShadows, StatusTransparent, StatusDisguised, StatusDispersal:
return true
default:
return false
}
}
func (st status) Bad() bool {
switch st {
case StatusConfusion, StatusNausea, StatusUnhidden, StatusIlluminated:
return true
default:
return false
}
}
func (st status) String() string {
switch st {
case StatusExhausted:
return "Exhausted"
case StatusSwift:
return "Swift"
case StatusLignification:
return "Lignified"
case StatusConfusion:
return "Confused"
case StatusNausea:
return "Nausea"
case StatusFlames:
return "Flames"
case StatusHidden:
return "Hidden"
case StatusUnhidden:
return "Unhidden"
case StatusDig:
return "Dig"
case StatusLight:
return "Light"
case StatusLevitation:
return "Levitating"
case StatusShadows:
return "Shadows"
case StatusIlluminated:
return "Illuminated"
case StatusTransparent:
return "Transparent"
case StatusDisguised:
return "Disguised"
case StatusDelay:
return "Delay"
case StatusDispersal:
return "Dispersal"
default:
// should not happen
return "unknown"
}
}
func (st status) Short() string {
switch st {
case StatusExhausted:
return "Ex"
case StatusSwift:
return "Sw"
case StatusLignification:
return "Lg"
case StatusConfusion:
return "Co"
case StatusNausea:
return "Na"
case StatusFlames:
return "Fl"
case StatusHidden:
return "H+"
case StatusUnhidden:
return "H-"
case StatusDig:
return "Di"
case StatusLight:
return "Li"
case StatusLevitation:
return "Le"
case StatusShadows:
return "Sh"
case StatusIlluminated:
return "Il"
case StatusTransparent:
return "Tr"
case StatusDisguised:
return "Dg"
case StatusDelay:
return "De"
case StatusDispersal:
return "Dp"
default:
// should not happen
return "?"
}
}
|
Java
|
UTF-8
| 4,199
| 3.515625
| 4
|
[] |
no_license
|
package StringMatching;
/**
* Created by Ethan on 15/11/27.
* The Rabin-Karp algorithm on two-dimensional array.
* Reference: CLRS, Exercises 32.2-3
*/
public class RabinKarpMatcher2D {
private static int[] horizontalInitialization(String[] T, int m2, int d, int q, int base) {
// T = n1*n2
int n1 = T.length;
int[] horizontalMatrix = new int[n1];
// Initializing
for (int i = 0; i < n1; i++) {
int tmp = 0;
for (int j = 0; j < m2; j++) {
tmp = (d * tmp + T[i].charAt(j) - base) % q;
}
horizontalMatrix[i] = tmp;
}
return horizontalMatrix;
}
private static int[][] verticalRollingHash(String[] T, int m1, int q, int base) {
// T = n1*n2
int n1 = T.length;
int n2 = T[0].length();
int[][] verticalMatrix = new int[n1 - m1 + 1][n2];
// Initializing
for (int j = 0; j < n2; j++) {
int tmp = 0;
for (int i = 0; i < m1; i++) {
tmp += (T[i].charAt(j) - base);
}
verticalMatrix[0][j] = tmp % q;
}
// Vertical rolling hash
for (int j = 0; j < n2; j++) {
for (int i = 0; i < n1 - m1; i++) {
verticalMatrix[i + 1][j] = (verticalMatrix[i][j] + (T[i + m1].charAt(j) - base) - (T[i].charAt(j) - base)) % q;
}
}
return verticalMatrix;
}
public static void rabinKarpMatcher2D(String[] T, String[] P) {
rabinKarpMatcher2D(T, P, 26, 29, 'a');
}
/**
* For String P, compute the hash value of m numbers in every line first and hash these mh numbers next.
*
* @param T text
* @param P pattern
* @param d radix
* @param q prime
*/
public static void rabinKarpMatcher2D(String[] T, String[] P, int d, int q, char base) {
// T = n1*n2
int n1 = T.length;
int n2 = T[0].length();
// P = m1*m2
int m1 = P.length;
int m2 = P[0].length();
int h = (int) Math.pow(d, m2 - 1) % q;
int p = 0; // corresponding decimal value of P
int t = 0; // corresponding decimal value of S
int[][] tArr = new int[n1 - m1 + 1][n2 - m2 + 1];
int[] horizontalMatrix = horizontalInitialization(T, m2, d, q, base);
int[][] verticalMatrix = verticalRollingHash(T, m1, q, base);
// Preprocessing p and t
int[] pTmp = new int[m1]; // temporary array for computing p
for (int i = 0; i < m1; i++) {
for (int j = 0; j < m2; j++) {
pTmp[i] = (d * pTmp[i] + P[i].charAt(j) - base) % q;
}
}
for (int i = 0; i < m1; i++) {
p = (p + pTmp[i]) % q;
}
for (int i = 0; i < m1; i++) {
t = (t + horizontalMatrix[i]) % q;
}
tArr[0][0] = t;
// Matching
for (int i = 0; i <= n1 - m1; i++) { // vertical shift
for (int s = 0; s <= n2 - m2; s++) { // horizontal shift
if (p == tArr[i][s]) {
boolean isEquivalent = true;
for (int j = 0; j < m1; j++) {
if (!P[j].equals(T[i + j].substring(s, s + m2))) {
isEquivalent = false;
}
}
if (isEquivalent) {
System.out.println("Pattern occurs with horizontal shift " + s + " and vertical shift " + i);
}
}
if (s < n2 - m2) {
// Horizontal rolling hash
tArr[i][s + 1] = (d * ((tArr[i][s] - verticalMatrix[i][s] * h) % q + q) + verticalMatrix[i][s + m2]) % q;
}
}
if (i < n1 - m1) {
tArr[i + 1][0] = (tArr[i][0] + (horizontalMatrix[i + m1] - horizontalMatrix[i]) % q + q) % q;
}
}
}
public static void main(String[] args) {
String[] T = {"abcdefgh", "ijklmnop", "qrstuvwx", "yzabcdef", "ghijklmn"};
String[] P = {"def", "lmn"};
rabinKarpMatcher2D(T, P); // 3,0; 5,3
}
}
|
JavaScript
|
UTF-8
| 587
| 2.578125
| 3
|
[] |
no_license
|
import * as React from 'react';
function genItems(size) {
const items = [];
for (let i = 1; i <= size; i++) {
items.push(<div className="sl-item" key={i}>{`item${i}`}</div>);
}
return items;
}
export function genData(dataSize) {
const data = [];
for (let i = 1; i <= dataSize; i++) {
data.push({
key: i,
header: `header${i}`,
items: genItems(10)
})
}
data.unshift({
key: 'logo',
header: `React sticky header component`,
items: <div>
<h1 style={{ textAlign: 'center' }}>StickyList</h1>
</div>
})
return data;
}
|
Java
|
UTF-8
| 2,060
| 2.921875
| 3
|
[] |
no_license
|
package ST200110_undo1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main_17130_토끼가정보섬에올라온이유 {
static boolean end = false;
static String[] map;
static int[][] dp;
static boolean[][] check;
static int[] dr = {-1, 0, 1};
static int N, M, Ans = 0;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int row_up = -1, row_down = -1, col = -1;
map = new String[N];
dp = new int[N][M];
check = new boolean[N][M];
for (int i = 0; i < N; i++) {
map[i] = br.readLine();
for (int j = 0; j < M; j++) {
if(map[i].charAt(j) =='R') {
row_up = i;
row_down = i + 1;
col = j;
check[i][j] = true;
}
}
}
while(col != M - 1) {
for (int row = row_up; row < row_down; row++) {
int now = dp[row][col];
int next_col = col + 1;
if(map[row].charAt(col) == '#' || !check[row][col]) continue;
for (int d = 0; d < 3; d++) {
dp_calc(row, col, row + dr[d], col + 1);
}
}
if(row_up > 0) --row_up;
if(row_down < N) ++row_down;
++col;
}
if(end) System.out.println(Ans);
else System.out.println(-1);
}
private static void dp_calc(int row, int col, int next_row, int next_col) {
if(next_row < 0 || next_row == N || map[next_row].charAt(next_col) == '#') return;
int now_dp = dp[row][col];
check[next_row][next_col] = true;
if(map[next_row].charAt(next_col) == '.') {
dp[next_row][next_col] = Math.max(dp[next_row][next_col], now_dp);
}
else if(map[next_row].charAt(next_col) == 'O') {
dp[next_row][next_col] = Math.max(dp[next_row][next_col], now_dp);
Ans = Math.max(Ans, dp[next_row][next_col]);
end = true;
}
else if(map[next_row].charAt(next_col) == 'C') {
dp[next_row][next_col] = Math.max(dp[next_row][next_col], now_dp + 1);
}
}
}
|
Java
|
UTF-8
| 756
| 2.703125
| 3
|
[] |
no_license
|
package it.openly.core.exceptions;
import lombok.Getter;
/**
* A specialised runtime exception that allow passing arguments.<br/>
* The arguments are meant to be the arguments of the function that raised the exception or other information useful
* to return meaningful error messages.
*
* @author filippo.possenti
*/
public class AppRuntimeException extends RuntimeException {
@Getter
private final transient Object[] arguments;
public AppRuntimeException(String message, Object... arguments) {
super(String.format(message, arguments));
this.arguments = arguments;
}
public AppRuntimeException(String message, Throwable cause, Object... arguments) {
super(String.format(message, arguments), cause);
this.arguments = arguments;
}
}
|
JavaScript
|
UTF-8
| 1,723
| 3.515625
| 4
|
[] |
no_license
|
/**
* Created by anubhavshrimal on 23/7/16.
*/
var async = require('async');
var delayedOutput = function (a, b, cb) {
setTimeout(function () {
console.log("output1", (a+b));
// arguments (err, result)
cb(null, a+b);
}, 3000);
};
var delayedOutput2 = function (sum, cb) {
setTimeout(function () {
console.log("output2", sum * 2);
// arguments (err, result)
cb(null, "output2");
}, 3000);
};
var nonDelayedOutput = function (cb) {
console.log("output3");
// arguments (err, result)
cb(null, "output3");
};
// delayedOutput();
// delayedOutput2();
// nonDelayedOutput();
// async series passes a callback as the last argument in the asynchronous function which is then called to execute
// the next function in series array
/*
async.series(
[
function(cb){delayedOutput(5, 2, cb);},
function(cb){delayedOutput2(7, cb);},
nonDelayedOutput],
function(err, results){
console.log("over");
console.log(results);
}
);
*/
/*
async.parallel(
[
delayedOutput,
delayedOutput2,
nonDelayedOutput],
function(err, results){
console.log("over");
console.log(results);
}
);*/
// passes the return of the previous function in the next function
// eg. delayedOutput's o/p can be passed in delayedOutput2
async.waterfall(
[
function(cb){delayedOutput(5, 2, cb);},
function(resultOfOutput1, cb){delayedOutput2(resultOfOutput1, cb);},
function(resultOfOutput2, cb){nonDelayedOutput(cb);}
],
function(err, resultOfNonDelayed){
console.log("over");
console.log(resultOfNonDelayed);
}
);
|
Python
|
UTF-8
| 835
| 2.546875
| 3
|
[] |
no_license
|
import ctypes
nums = [0xc8f9a829, 0xec83260e, 0xaf93c6f4, 0x5a1b89d9, 0x31e68d0d, 0xc38ce7e7, 0xc8f9a829, 0x4aee907b, 0xe0138a5f, 0x31e68d0d, 0x09975e45, 0xd129ea43, 0xc6830a2f, 0xc8f9a829, 0xec83260e, 0xec83260e, 0x13bf2b7f, 0xe0138a5f, 0xe419b183, 0xb2f1ddbb, 0xc38ce7e7, 0xc38ce7e7, 0x91639414, 0x5a1b89d9, 0x31e68d0d, 0x8c45c2b1, 0x0c76c360, 0x0876805b, 0x8d67dd2c, 0xc212d77c, 0xec83260e, 0x5a1b89d9, 0xe59d8403, 0x77244701, 0x1499761a, 0xeb6552fe]
pos = [0x0f, 0x20, 0x01, 0x1d, 0x17, 0x12, 0x0e, 0x1f, 0x1a, 0x08, 0x1b, 0x02, 0x10, 0x14, 0x15, 0x22, 0x13, 0x1c, 0x18, 0x16, 0x05, 0x07, 0x03, 0x19, 0x06, 0x00, 0x0d, 0x0c, 0x1e, 0x0b, 0x21, 0x09, 0x23, 0x0a, 0x11, 0x04]
prime = 0xfbc56a93
flag_len = 36
string = bytearray(flag_len)
for i in range(flag_len):
n = pow(nums[i], -1, prime)
string[pos[i]] = n
print(string)
|
Shell
|
UTF-8
| 1,183
| 3.875
| 4
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
#! /bin/sh
## AUTHOR: Robert Twyman
## Script used to automatically gather GATE x,y,z attenuation translation for STIR images.
## Script echo (returns) x y z variables.
ImageFilename=$1
if [ $# -ne 1 ]; then
echo "Usage:"$0 "ImageFilename" 1>&2
exit 1
fi
set -e # exit on error
trap "echo ERROR in $0" ERR
## Get first and last edge positions
FirstEdges=`list_image_info $ImageFilename| awk -F: '/Physical coordinate of first edge in mm/ {print $2}'|tr -d '{}'|awk -F, '{print $3, $2, $1}'` 1>&2
LastEdges=`list_image_info $ImageFilename| awk -F: '/Physical coordinate of last edge in mm/ {print $2}'|tr -d '{}'|awk -F, '{print $3, $2, $1}'` 1>&2
## Extract x,y first and last edges
FirstEdgeX=$(echo "$FirstEdges" | awk '{print $1}')
LastEdgeX=$(echo "$LastEdges" | awk '{print $1}')
FirstEdgeY=$(echo "$FirstEdges" | awk '{print $2}')
LastEdgeY=$(echo "$LastEdges" | awk '{print $2}')
## Compute Translation
TranslationX=$(echo "$FirstEdgeX $LastEdgeX" | awk '{print ($1+$2)/2}')
TranslationY=$(echo "$FirstEdgeY $LastEdgeY" | awk '{print ($1+$2)/2}')
TranslationZ=0. ## Z translation should be zero.
## Used for return.
echo $TranslationX $TranslationY $TranslationZ
exit 0
|
Markdown
|
UTF-8
| 3,089
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
_1강에서 다룬 내용은 pdf ppt슬라이드에 모두 있습니다._
_복습이라고 생각하시고 책읽듯이 읽어주세요_
# JSX
JSX는 리액트에서 return문에 사용하는 문법이다.
얼핏보면 HTML같지만, 실제로는 자바스크립트입니다.
```jsx
return (
<div className="App">
<h1>Hello React</h1>
</div>
);
```
이렇게 컴포넌트에서 JSX를 작성하면 바벨 트렌스파일러가 자동으로 자바스크립트로 변환을 해줍니다.
JSX에는 여러 규칙들이 있습니다
#### 꼭 닫혀야 하는 태그
```jsx
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
<input type="text" />
</div>
);
}
}
export default App;
```
input 같은 태그도 반드시 닫아주세요.
#### 감싸져 있는 엘리먼트
```jsx
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
<div>
Hello
</div>
<div>
Bye
</div>
</div>
);
}
}
export default App;
```
태그들은 반드시 감싸줍니다. div말고 Fragement를 사용해도된다고 했었죠!
#### JSX안에 자바스크립트 값 사용하기
```jsx
import React, { Component } from 'react';
class App extends Component {
render() {
const name = 'react'
return (
<div>
hello {name}!
</div>
);
}
}
export default App;
```
자바스크립트 값을 사용할때는 {}를 사용합니다.
#### 조건부렌더링
```jsx
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
{
true
? console.log('correct')
: console.log('incorrect')
}
</div>
);
}
}
export default App;
```
바벨은 if~else를 transpile하지 못합니다.
3항연산자 또는 && operator를 사용해주세요
#### 스타일은 항상 객체형식으로
```jsx
import React, { Component } from 'react';
class App extends Component {
render() {
const style = {
backgroundColor: 'red',
};
return <div style={style}>react</div>;
}
}
export default App;
```
스타일은 항상 객체형식으로 작성해야합니다.
#### 컴포넌트에 style을 적용할때는 className
```jsx
import React, { Component } from 'react';
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
react
</div>
);
}
}
export default App;
```
스타일을 적용할때는 class가 아닌 className을 써주세요.
class로 해도되지만 warning이 뜨고 class키워드는 이미 자바스크립트에서 사용중이기때문에 가급적 피합니다.
#### 주석
```jsx
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
{/* 주석은 이렇게 */}
<h1>react</h1>
</div>
);
}
}
export default App;
```
주석은 {/\* \*/}형식을 사용합니다.
|
Java
|
UTF-8
| 1,900
| 2.203125
| 2
|
[] |
no_license
|
package com.pabei.backend.controller.response;
import org.springframework.beans.BeanUtils;
import com.pabei.backend.domain.Orders;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Created by PPYX on 2016/12/1. 响应出场凭证的bean
*/
@ApiModel
public class ExitVoucherResponseBean {
/**
* 车牌号码
*/
@ApiModelProperty(value = "车牌号码")
private String plateNo;
/**
* 订单开始时间
*/
@ApiModelProperty(value = "订单开始时间")
private String beginTime;
/**
* 订单结束时间
*/
@ApiModelProperty(value = "订单结束时间")
private String endTime;
/**
* 实际支付金额
*/
@ApiModelProperty(value = "实际支付金额")
private Double actualAmount;
/**
* 停车时间
*/
@ApiModelProperty(value = "停车时间")
private String parkTimeString;
public static ExitVoucherResponseBean clone(Orders orders) {
if (orders == null) {
return null;
}
ExitVoucherResponseBean bean = new ExitVoucherResponseBean();
BeanUtils.copyProperties(orders, bean);
return bean;
}
public String getPlateNo() {
return plateNo;
}
public void setPlateNo(String plateNo) {
this.plateNo = plateNo;
}
public Double getActualAmount() {
return actualAmount;
}
public void setActualAmount(Double actualAmount) {
this.actualAmount = actualAmount;
}
public String getParkTimeString() {
return parkTimeString;
}
public void setParkTimeString(String parkTimeString) {
this.parkTimeString = parkTimeString;
}
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
}
|
C#
|
UTF-8
| 1,389
| 2.65625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace TabbedApp
{
class DoctorListAdapter : BaseAdapter<Doctor>
{
private readonly Activity mcontext;
private readonly List<Doctor> mDoctor;
public DoctorListAdapter(Activity context, List<Doctor> mDoctor)
{
this.mcontext = context;
this.mDoctor = mDoctor;
}
public override Doctor this[int position]
{
get
{
return mDoctor[position];
}
}
public override int Count
{
get
{
return mDoctor.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
{
view = mcontext.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem2, null);
}
view.FindViewById<TextView>(Android.Resource.Id.Text2).Text = mDoctor[position].Name;
return view;
}
}
}
|
JavaScript
|
UTF-8
| 329
| 3.125
| 3
|
[] |
no_license
|
function objectToQueryString(object)
{
return Object.keys(object).map( function(item){
return item + '=' + object[item];
}).join('&');
}
//var obj = {user: 'Dmitry'};
// var obj = {user: 'Dmitry', password: 'pass'};
var obj = {user: 'Dmitry', password: 'pass', id:1};
console.log(objectToQueryString(obj));
|
JavaScript
|
UTF-8
| 644
| 2.53125
| 3
|
[] |
no_license
|
import React, { Component } from 'react'
class Instructions extends Component {
render() {
return (
<div className="instructions">
<h5>How It Works</h5>
<div>
<p>Each card is a multiple choice question. Click on the answer you think is correct!</p>
<p>If you get the answer incorrect, it will be added to your Study List to continue practicing.</p>
<p>If you want to view the questions you missed, choose Study List Only from the dropdown!</p>
</div>
<button onClick={this.props.toggleInstructions}>Got it!</button>
</div>
)
}
}
export default Instructions;
|
Java
|
UTF-8
| 1,652
| 2.75
| 3
|
[] |
no_license
|
package sudoku;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Stack;
/**Класс, описывающий сохраненную игру*/
public class SavedGame implements Serializable{
private final Stack <Move> moves;
private final LinkedList<SudokuLabel> gameField;
private final long time;
private final int checkResultsCounter, selectedLabel;
private final boolean playerWasCheating, cheats, auxMode;
public SavedGame(LinkedList<SudokuLabel> gameField, long time, int checkResultsCounter,
boolean cheats, boolean playerWasCheating, boolean auxMode, int selectedLabel, Stack moves) {
this.gameField = gameField;
this.time = time;
this.checkResultsCounter = checkResultsCounter;
this.playerWasCheating = playerWasCheating;
this.cheats = cheats;
this.auxMode = auxMode;
this.selectedLabel = selectedLabel;
this.moves = moves;
}
public LinkedList<SudokuLabel> getGameField() { return gameField; }
public long getTime() { return time; }
public int getCheckResultsCounter() { return checkResultsCounter;}
public boolean isPlayerWasCheating() { return playerWasCheating; }
public boolean cheats() { return cheats; }
public boolean isAuxMode() { return auxMode; }
public int getSelectedLabel() { return selectedLabel; }
public Stack<Move> getMoves() { return moves; }
}
|
C#
|
UTF-8
| 2,109
| 2.703125
| 3
|
[] |
no_license
|
using QRCoder;
using System;
using System.Drawing.Imaging;
using System.IO;
namespace BarBuddy.DTOs.Helper
{
public static class QRCodeHelper
{
public static string CreateQrCodeForDoor(string qrCodeSalt)
{
try
{
if (string.IsNullOrWhiteSpace(qrCodeSalt))
{
return null;
}
using (MemoryStream ms = new MemoryStream())
{
QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
QRCodeData data = qrCodeGenerator.CreateQrCode(qrCodeSalt, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(data);
using (var bitmap = qrCode.GetGraphic(20))
{
bitmap.Save(ms, ImageFormat.Png);
return "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
}
}
catch (Exception ex)
{
return null;
}
}
public static string CreateQrCodeForSpot(string qrCodeSalt, long spotId)
{
try
{
if (string.IsNullOrWhiteSpace(qrCodeSalt) || spotId <= 0)
{
return null;
}
using (MemoryStream ms = new MemoryStream())
{
QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
QRCodeData data = qrCodeGenerator.CreateQrCode(qrCodeSalt + "#SPOT:" + spotId, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(data);
using (var bitmap = qrCode.GetGraphic(20))
{
bitmap.Save(ms, ImageFormat.Png);
return "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
}
}
catch (Exception ex)
{
return null;
}
}
}
}
|
Markdown
|
UTF-8
| 5,786
| 2.6875
| 3
|
[] |
no_license
|
```yaml
area: Nottinghamshire
og:
description: Car cruisers who ignore pleas to stop illegal gatherings have been warned police are prepared to step up fines.
image: https://www.nottinghamshire.police.uk/_npt_customisations/images/socialmedia-crest-2018.jpg
site:
name: Nottinghamshire Police
title: Seven fixed penalty notices issued following illegal car meet
type: article
url: https://www.nottinghamshire.police.uk/news-article/seven-fixed-penalty-notices-issued-following-illegal-car-meet
title: Seven fixed penalty notices issued following illegal car meet | Nottinghamshire Police
url: https://www.nottinghamshire.police.uk/news-article/seven-fixed-penalty-notices-issued-following-illegal-car-meet
```
December 8, 2020
Share by email
Car cruisers who ignore pleas to stop illegal gatherings have been warned police are prepared to step up fines.
It comes after repeated attempts by Nottinghamshire Police to engage with people and appeal to put the brakes on the dangerous and anti-social meetings.
Officers issued seven further fixed penalty notices last night following an illegal car meet and warned anyone who continues to ignore the appeal they will have to stump up £100.
Officers were called to Hucknall, close to the tram stop next to Tesco in Ashgate Road on Sunday evening, where it was reported there was a large gathering of car cruisers.
They then travelled up to Junction 27 of the M1, which is within a Public Space Protection Order zone.
Officers met them and began issuing tickets which deterred others from remaining in the area.
Participants and spectators at a regular car cruising event were handed fines worth a total of £700 – as the force continued to issue a clear warning about future gatherings.
Officers have been concerned for some time about regular Sunday evening gatherings off Junction 27, where large numbers of modified and high performance vehicles are parked up and driven recklessly around the area.
In response to complaints of anti-social behaviour and dangerous driving a PSPO has been in place in the area since 2018 – allowing officers to fine drivers, passengers and spectators who gather in the area.
After many weeks of visits to the site where warnings were given, officers returned on Sunday (6 December) and issued £100 fixed penalty notices to seven different people.
Sergeant James Flint said: “We have been very patient at this site for many months now and have spent considerable time engaging with people and explaining the restrictions to them.
“Frankly we could have issued dozens of fines in this time, but our focus here isn’t about issuing tickets or making money – it is about public safety and anti-social behaviour.
“Too many of the people who attend these gatherings end up driving in a dangerous, reckless or antisocial manner which poses a hazard to other road users and a noise nuisance to anyone else in the area.
“We have tried very hard in recent weeks to engage with them and to explain what will happen if they continue to congregate at the site.
“As many of them clearly haven’t listened we took firm action on Sunday and make issue the fines.
“We understand that many people are very proud of their vehicles, but these gatherings are a very clear driver of dangerous and reckless driving. As such we are now taking very firm steps to dissuade people from taking part or even standing and watching it.”Sgt Flint said officers will be monitoring the area regularly and will not hesitate to take similar action again, or to enforce government regulations.
He added: "The very last thing we want to be doing as police officers is to be punishing people for gathering together and having fun. However, the current national restrictions are in place to protect the wider public from harm and we will keep enforcing them for as long as we need to.
“Whilst it is heartening that the vast majority of people clearly understand and are obeying the current restrictions, it is deeply disappointing that so many others needed such an expensive reminder that the rules apply equally to everyone.
“We understand that this is a difficult time but there really are no excuses for this kind of behaviour where people are blatantly ignoring the restrictions in such large numbers.”
Although most of the problem activity occurs in twin laybys, the Public Spaces Protection Order covers a larger area in and around Junction 27, taking in the length of Mansfield Road from the west side of the M1 to the Annersley traffic lights and Badger Box pub. It also includes the entirety of the Sherwood Business Park and both the north and southbound carriageways on the A611.
The order prohibits driving at excessive speed, aggressive acceleration, stunts such as drifting or wheel spins, the playing of load music, driving in convoy, sounding horns and congregating to spectate.
People found to be in breach of the order by Nottinghamshire Police are given Fixed Penalty Notices (FPNs) on behalf of Ashfield District Council that may lead to a summary conviction if they are not paid.
Cllr Helen-Ann Smith, Cabinet Member for Community Safety said “Ashfield District Council has been working closely with the police to tackle the ongoing issues at Junction 27. Car cruising is dangerous, not just for those involved but members of the public using the roads safely.
“The PSPO in place needs to act as a warning to those that think its ok to act in this anti-social way, we will not tolerate lives being put at risk and fixed penalty notices will be issued to those caught.
“The Council and police are committed to ensuring that car cruising does not become an issue within the District.
"We welcome the police action as this behaviour disturbs our local residents."
|
Python
|
UTF-8
| 5,983
| 2.5625
| 3
|
[] |
no_license
|
from collections import OrderedDict
import matplotlib.pyplot as plt
import os
import sys
sys.path.append(os.pardir)
from common.layers import *
from common.utils import *
from common.optimizer import *
class ConvolutionalNeuralNet:
def __init__(self, input_shape, hidden_size, output_size, conv_params):
filter_num = conv_params['filter_num']
filter_size = conv_params['filter_size']
filter_stride = conv_params['filter_stride']
filter_padding = conv_params['filter_padding']
pool_size = conv_params['pool_size']
pool_stride = conv_params['pool_stride']
pool_padding = conv_params['pool_padding']
channel_num = input_shape[0]
conv_output_size = (input_shape[2] + 2 * filter_padding - filter_size) // filter_stride + 1
pool_output_num = filter_num * ((conv_output_size + 2 * pool_padding - pool_size) // pool_stride + 1) ** 2
self.params = {
'w1': np.random.randn(filter_num, channel_num, filter_size, filter_size),
'b1': np.random.randn(filter_num),
'w2': random_array_generator_normal(pool_output_num, hidden_size)[0],
'b2': random_array_generator_normal(pool_output_num, hidden_size)[1],
'w3': random_array_generator_normal(hidden_size, output_size)[0],
'b3': random_array_generator_normal(hidden_size, output_size)[1],
}
self.layers = OrderedDict()
self.layers['convolution'] = Convolution(w=self.params['w1'], b=self.params['b1'],
stride=filter_stride, padding=filter_padding)
self.layers['relu1'] = ReLU()
self.layers['pooling'] = Pooling(pool_h=pool_size, pool_w=pool_size, stride=pool_stride, padding=pool_padding)
self.layers['affine1'] = Affine(w=self.params['w2'], b=self.params['b2'])
self.layers['relu2'] = ReLU()
self.layers['dropout'] = Dropout(drop_rate=0.3, is_test=False)
self.layers['affine2'] = Affine(w=self.params['w3'], b=self.params['b3'])
self.lastLayer = SoftMaxWithLoss()
def predict(self, x):
for layer in self.layers.values():
x = layer.forward(x)
return x
def loss(self, x, t):
y = self.predict(x)
return self.lastLayer.forward(y, t)
def accuracy(self, x, t):
y = self.predict(x)
ans = np.argmax(y, axis=1)
if t.ndim != 1:
t = np.argmax(t, axis=1)
accuracy = np.sum(ans == t) / float(x.shape[0])
return accuracy
def gradient(self, x, t):
self.loss(x, t)
dout = 1
dout = self.lastLayer.backward(dout)
layers = list(self.layers.values())
layers.reverse()
for layer in layers:
dout = layer.backward(dout)
gradients = {}
gradients['w1'] = self.layers['convolution1'].dw
gradients['b1'] = self.layers['convolution1'].db
gradients['w2'] = self.layers['affine1'].dw
gradients['b2'] = self.layers['affine1'].db
gradients['w3'] = self.layers['affine2'].dw
gradients['b3'] = self.layers['affine2'].db
return gradients
def main():
np.random.seed(1)
iteration = 10000
batch_size = 100
hidden_size = 100
output_size = 10
sifar_img_num = 10000
sifar_channel_num = 3
sifar_img_size = 32
epoch_size = sifar_img_num / batch_size
train_losses = []
train_accs = []
test_accs = []
pickle = '../data/cifar-10-batches-py/'
train_x, train_y = unpickle(pickle + 'data_batch_1')
test_x, test_y = unpickle(pickle + 'test_batch')
train_x = normalization(train_x)
test_x = normalization(test_x)
train_x = train_x.reshape(sifar_img_num, sifar_channel_num, sifar_img_size, sifar_img_size)
test_x = test_x.reshape(sifar_img_num, sifar_channel_num, sifar_img_size, sifar_img_size)
# img_size + padding*2 - filter_size が filter_stride の倍数になるようにパラメータを設定する
conv_params = {
'filter_num': 10,
'filter_size': 5,
'filter_stride': 2,
'filter_padding': 1,
'pool_size': 5,
'pool_stride': 1,
'pool_padding': 0,
}
CNN = ConvolutionalNeuralNet((sifar_channel_num, sifar_img_size, sifar_img_size),
hidden_size, output_size, conv_params)
for i in range(iteration):
batch_idxes = np.random.choice(sifar_img_num, batch_size)
train_x_batch = train_x[batch_idxes]
train_y_batch = train_y[batch_idxes]
train_y_batch = to_one_hot_vector_batch(train_y_batch, output_size)
gradients = CNN.gradient(train_x_batch, train_y_batch)
### select optimizer for comparison
# optimizer = SGD(lr=0.01)
# optimizer = Momentum(alpha=0.9, lr=0.01)
# optimizer = AdaGrad(lr=0.001, delta=1e-8)
# optimizer = RMSProp(lr=0.001, law=0.9, delta=1e-8)
# optimizer = AdaDelta(law=0.95, delta=1e-6)
optimizer = Adam(alpha=0.001, beta_1=0.9, beta_2=0.999, delta=1e-8)
optimizer.update(CNN.params, gradients)
loss = CNN.loss(train_x_batch, train_y_batch)
print("loss: {}".format(loss))
if i % epoch_size == 0:
train_acc = CNN.accuracy(train_x, train_y)
test_acc = CNN.accuracy(test_x, test_y)
train_accs.append(train_acc)
test_accs.append(test_acc)
train_losses.append(loss)
print("----- epoch{} -----".format(i / epoch_size))
print("train accuracy: {}%".format(train_acc * 100))
print("test accuracy: {}%".format(test_acc * 100))
epochs = range(len(train_accs))
plt.plot(epochs, train_accs, 'b', label='train_acc')
plt.plot(epochs, test_accs, 'r', label='test_acc')
plt.title('train and test accuracy')
plt.legend(bbox_to_anchor=(1, 0), loc='lower right')
plt.show()
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 1,449
| 2.671875
| 3
|
[] |
no_license
|
#pragma once
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Level
{
private:
World* physicsWorld;
LevelLoader* levelLoader;
Spawner* spawner;
string levelName;
string levelPath;
/* all objects in the level */
map < string, PhysicsObject* > physicsObjects;
vector < Player* > players;
public:
Level(World* physicsWorld);
void loadLevel(string level);
void updateLevel();
void addPhysicsObject(PhysicsObject* physicsObject);
PhysicsObject* getPhysicsObject(string name) const;
void removePhysicsObject(PhysicsObject* physicsObject);
void removePhysicsObject(string name);
void spawn(int client);
void update();
void deSpawn(int client);
void clearNoPlayersAndTheirWeaponsOwner(int owner);
map < string, PhysicsObject* > getPhysicsObjects() const;
map < string, PhysicsObject* > getNoPlayersPhysicsObjects() const;
map < string, PhysicsObject* > getNoPlayersAndTheirWeaponsPhysicsObjects() const;
Player* getPlayer(int id) const;
vector < Player* > getPlayers() const;
vector < Player* > getPlayersExcept(int id) const;
string getLevelName() const;
string getLevelPath() const;
~Level();
};
|
Swift
|
UTF-8
| 953
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// HiPayWxOrder.swift
// HiPay
//
// Created by Jason on 16/6/17.
// Copyright © 2016年 wuyingminhui@gmail.com. All rights reserved.
//
// 微信支付订单
import Foundation
/**
* 微信订单
*/
public struct HiPayWxOrder {
/// 商家appid
public var appid: String
/// 商家id
public var partnerId: String
/// 订单id
public var prepayid: String
/// 随机字符串
public var nonceStr: String
/// 时间戳
public var timeStamp: UInt32
/// 扩展字段
public var package: String
/// 签名
public var sign: String
public init(appid: String, partnerId: String, prepayid: String, nonceStr: String, timeStamp: UInt32, package: String, sign: String) {
self.appid = appid
self.partnerId = partnerId
self.prepayid = prepayid
self.nonceStr = nonceStr
self.timeStamp = timeStamp
self.package = package
self.sign = sign
}
}
|
C#
|
UTF-8
| 1,740
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//-----------------------------------------------------------------------
// <copyright file="ITimeOfDayState.cs" company="Sully">
// Copyright (c) Johnathon Sullinger. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Mud.Engine.Shared.Environment
{
using System;
/// <summary>
/// Allows a specific time of day to be given a state.
/// </summary>
public interface ITimeOfDayState
{
/// <summary>
/// Occurs when the state's time is changed.
/// </summary>
event EventHandler<ITimeOfDay> TimeUpdated;
/// <summary>
/// Gets the name of this state.
/// </summary>
/// <value>
/// The name.
/// </value>
string Name { get; }
/// <summary>
/// Gets the current time.
/// </summary>
/// <value>
/// The current time.
/// </value>
ITimeOfDay CurrentTime { get; }
/// <summary>
/// Gets or sets the time of day in the game that this state begins.
/// </summary>
/// <value>
/// The state start time.
/// </value>
ITimeOfDay StateStartTime { get; set; }
/// <summary>
/// Initializes the time of day state with the supplied in-game to real-world hours factor.
/// </summary>
/// <param name="worldTimeFactor">The world time factor.</param>
/// <param name="hoursPerDay">The hours per day.</param>
void Initialize(double worldTimeFactor, int hoursPerDay);
/// <summary>
/// Resets this instance current time to that if its start time.
/// </summary>
void Reset();
}
}
|
C++
|
UTF-8
| 1,679
| 2.90625
| 3
|
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int mod = 998244353;
struct mint {
ll x;
mint(ll x = 0) : x((x % mod + mod) % mod) {}
mint operator-() const { return mint(-x); }
mint &operator+=(const mint a) {
if ((x += a.x) >= mod) x -= mod;
return *this;
}
mint &operator-=(const mint a) {
if ((x += mod - a.x) >= mod) x -= mod;
return *this;
}
mint &operator*=(const mint a) {
(x *= a.x) %= mod;
return *this;
}
mint operator+(const mint a) const {
mint res(*this);
return res += a;
}
mint operator-(const mint a) const {
mint res(*this);
return res -= a;
}
mint operator*(const mint a) const {
mint res(*this);
return res *= a;
}
mint pow(ll t) const {
if (!t) return 1;
mint a = pow(t >> 1);
a *= a;
if (t & 1) a *= *this;
return a;
}
mint inv() const {
return pow(mod - 2);
}
mint &operator/=(const mint a) {
return (*this) *= a.inv();
}
mint operator/(const mint a) const {
mint res(*this);
return res /= a;
}
};
mint table[200020];
void init() {
table[0] = table[1] = 1;
for (int i = 2; i < 200020; i++) {
table[i] = table[i - 1] * i;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll n, m, k;
cin >> n >> m >> k;
init();
mint ans = 0;
for (ll d = n - k - 1; d <= n - 1; d++) {
mint comb = table[n - 1] / table[n - 1 - d] / table[d];
mint p = mint(m - 1).pow(d);
p *= m;
mint tmp = comb * p;
ans += tmp;
}
cout << ans.x << endl;
return 0;
}
|
Java
|
UTF-8
| 2,825
| 3.421875
| 3
|
[] |
no_license
|
package datageneration;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Abstract class templates each of the different forms of data the system will extract from the
* database.
*
* @author Jordan & Michael
*/
public abstract class CreateDocuments extends Documents {
/**
* Extract, analyse and export data from database. This constructor functions more as a main
* method (calling methods in order) than a typical object constructor which initialises fields.
*
* @param target What type of documents need to be created
* @param con Connection to the db
* @throws IOException
* @throws SQLException
*/
public CreateDocuments(String target, CapstoneDBConnection con) throws IOException, SQLException {
super(target, con);
}
/**
* Creates the documents for each user for the given target data. Each document consists of all
* a user's artifacts in a random order
*
* @param target The type of documents to be generated
* @throws IOException
* @throws java.sql.SQLException
*/
@Override
protected void makeDocuments(String target) throws IOException, SQLException {
// Create the directory in which to place the files
createDirectory(target);
// create local copy of user ids
ResultSet userIds = getUserIds();
// Iterate over all user IDs and generate their document
while (userIds.next()) {
int currentUserId = userIds.getInt("USER_ID");
createUserDocument(currentUserId, getUserArtifacts(currentUserId));
}
}
/**
* Creates the directory for user tag documents if it does not already exist
*
* @param target What type of documents need to be created
*/
@Override
protected void createDirectory(String target) {
// Depending on the target data, name the folder differently
if (target.equals("cat") || target.equals("all")) {
super.createDirectory("userTags");
}
if (target.equals("tag") || target.equals("all")) {
super.createDirectory("userCats");
}
}
/**
* Query the database for data about each user and return a set of results
*
* @param uID The user's ID
* @return A ResultSet object of query results
* @throws SQLException
*/
abstract ResultSet getUserArtifacts(int uID) throws SQLException;
/**
* Generate, populate and store the document for each user
*
* @param uID The user's ID
* @param result A ResultSet object of query results
* @throws IOException
* @throws SQLException
*/
abstract void createUserDocument(int uID, ResultSet result) throws IOException, SQLException;
}
|
Python
|
UTF-8
| 17,056
| 2.8125
| 3
|
[] |
no_license
|
#################################################################
# Title: Final Report
# Author: Sam Cohen
# Date Created: 4/25
# Date Modified:
##################################################################
# Packages
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from scipy import signal
from scipy.stats import chi2
import functions_st_louis
import seaborn as sns
import pandas as pd
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.model_selection import train_test_split
import matplotlib.dates as mdates
import datetime
from pandas.plotting import register_matplotlib_converters
from statsmodels.tsa.seasonal import STL
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
register_matplotlib_converters()
from sklearn.decomposition import PCA
# Formats
years_15 = mdates.YearLocator(15) # every 15 years
years_1 = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
years_fmt = mdates.DateFormatter('%Y')
month_fmt = mdates.DateFormatter('%m')
time_delta_large = datetime.timedelta(days = 700)
time_delta_small = datetime.timedelta(days = 7)
# Read in data and perform simple conversions
df = pd.read_csv("./data/st_louis_preprocessed.csv", header=0, index_col=0, infer_datetime_format=True)
#df = df.rename(columns={"Unnamed: 0":"Index"})
#df.reset_index(inplace=True)
#df.rename(columns={"index:":"Date"})
df["revised_date"] = df["Date"].str.slice(start=-5)
df = df[df["revised_date"] != "02-29"]
df = df.reset_index()
df["Date"] = pd.to_datetime(df["Date"], format="%Y-%m-%d")
df = df.set_index(["Date"])
df = df.resample('1W').mean()
date = df.index.to_series()
#date = [datetime.datetime.strptime(w, "%Y-%m-%d").date() for d in df.index.to_series().to_string()]
flow = df['Flow']
#===================================================================================
# Description of the Dataset
# a. Plot of the dependent variable versus time.
# b. ACF/PACF of the dependent variable.
# c. Correlation Matrix with seaborn heatmap and Pearson’s correlation coefficient.
# d. Preprocessing procedures (if applicable): Clean the dataset (no missing data or NAN)
# e. Split the dataset into train set (80%) and test set (20%).
#===================================================================================
# Plot Flow for all years
fig, ax = plt.subplots()
ax.set_title("Historical Discharge at the St. Louis - Mississippi River USGS Gage")
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_major_locator(years_15)
ax.plot(date, flow, label="River Flow")
ax.set_ylabel("River Flow (ft3/s)")
ax.set_xlabel("Date")
ax.set_xlim(min(date) - time_delta_large, max(date) + time_delta_large)
ax.legend()
fig.autofmt_xdate()
plt.show()
# Plot Flow for the past 15 years
# 5,340 days ~= 15 years
fig, ax = plt.subplots()
ax.set_title("2019-2021 Discharge at the St. Louis - Mississippi River USGS Gage")
#ax.xaxis.set_major_formatter(years_fmt)
#ax.xaxis.set_major_locator(years_1)
ax.xaxis.set_major_formatter(month_fmt)
ax.xaxis.set_major_locator(months)
ax.plot(date[-104:], flow[-104:], label="River Flow")
ax.set_ylabel("River Flow (ft3/s)")
ax.set_xlabel("Date")
ax.set_xlim(min(date[-104:]) - time_delta_small, max(date[-104:]) + time_delta_small)
ax.legend()
fig.autofmt_xdate()
plt.show()
# df = df[:][-3650:]
# df = df.reset_index()
# ACF and PACF Plots of Flow
lags = 300
acf, pacf = functions_st_louis.acf_pacf_plot(df["Flow"], lags)
# Correlation Matrix
functions_st_louis.correlation_matrix(df)
#functions_st_louis.correlation_matrix(df.drop("Index", 1))
# Pre-processing
# Any misisng values?
print("Number of data points:", len(df))
print()
print("Number of NA values by variables:\n",df.isnull().sum())
print()
print("Decsriptive statistics of the variables:\n", df.describe())
print()
# Very few missing values. We will fill the SNOW and PRCP variable with mode imputation (as 0 is certainly most
# common) and the other missing values (TMIN) with mean imputation
df["PRCP"] = df["PRCP"].fillna(df["PRCP"].mode()[0])
df["SNOW"] = df["SNOW"].fillna(df["SNOW"].mode()[0])
df["TMIN"] = df["TMIN"].fillna(df["TMIN"].mean())
# Verify everything has been filled
print("Number of NA values by variables:\n",df.isnull().sum())
print()
df = sm.add_constant(df)
# Train - Test - Split
x_train, x_test, y_train, y_test = train_test_split(df[["PRCP", "SNOW", "TMAX", "TMIN"]], df["Flow"], shuffle=False, train_size=.8, test_size=.2)
#===================================================================================
# Stationarity
# Check for a need to make the dependent variable stationary. If the dependent
# variable is not stationary, you need to use the techniques discussed in class to make it stationary.
# Perform ACF/PACF analysis for stationarity. You may also perform ADF-test.
#===================================================================================
# Checks for stationarity include ACF and PACF plots, rolling mean and variances, and ADF test
# Rolling mean and variances
functions_st_louis.rolling_mean_var(df["Flow"])
#
# ADF test
# functions_st_louis.ADF_Cal(df["Flow"])
#
# # Make the dataset stationary
# # Log transform
#flow_log = np.log(flow[-1040:-156])
#
# # First differencing
#flow1 = functions_st_louis.difference(flow_log, 1)
flow3 = functions_st_louis.difference(y_train.values, 52)
#flow3 = functions_st_louis.difference(flow1, 1)
#flow3 = functions_st_louis.difference(flow2, 1)
flow3 = pd.Series(np.array(flow3))
acf, pacf = functions_st_louis.acf_pacf_plot(flow3, lags)
functions_st_louis.rolling_mean_var(flow3)
# ADF test
functions_st_louis.ADF_Cal(flow3)
# GPAC
#functions_st_louis.calc_gpac(14, 14, acf)
# This dataset looks stationary. It is hard to tell if I've got the right seasonality and there are probably a few
# different seasonalities, but here is an attempt. The ADF test, rolling mean and average, and ACF/PACF plots look
# good. The ACF plot implies a AR model of order 2, although I don't see that in the GPAC table
#===================================================================================
# Time Series Decomposition
# Approximate the trend and the seasonality and plot the detrended
# and the seasonally adjusted data set. Find the out the strength of the trend and seasonality. Refer
# to the lecture notes for different type of time series decomposition techniques.
#===================================================================================
functions_st_louis.plot_strength_seasonality_trend(df["Flow"])
# #===================================================================================
# # Holt-Winters Method
# # Using the Holt-Winters method try to find the best fit using the train
# # dataset and make a prediction using the test set.
# #===================================================================================
#
errors = functions_st_louis.holt_winters(y_train, y_test)
print("MSE of Holt-Winters:", np.mean(np.array(errors)**2))
# #===================================================================================
# # Feature Seleciton
# # You need to have a section in your report that explains how the feature
# # selection was performed and whether the collinearity exits not not. Backward stepwise regression
# # along with SVD and condition number is needed. You must explain that which feature(s) need to
# # be eliminated and why. You are welcome to use other methods like PCA or random forest for
# # feature elimination.
# #===================================================================================
df = df.drop("index", 1)
functions_st_louis.colinearity_detection(df)
functions_st_louis.condition_number(x_train.values)
coeffs = functions_st_louis.regression_coeffs(x_train[["PRCP", "SNOW", "TMAX", "TMIN"]], y_train)
model = sm.OLS(y_train, x_train).fit()
print(model.summary())
# drop snow
x_train1 = x_train.drop("SNOW", 1)
functions_st_louis.colinearity_detection(x_train1)
functions_st_louis.condition_number(x_train1.values)
coeffs = functions_st_louis.regression_coeffs(x_train1[["PRCP", "TMAX", "TMIN"]], y_train)
model = sm.OLS(y_train, x_train1).fit()
print(model.summary())
# PCA 2 components
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x_train)
principalDf = pd.DataFrame(data = principalComponents
, columns = ['principal component 1', 'principal component 2'])
print("Explained Variance of Each Feature:", pca.explained_variance_ratio_)
print("Total Explained Variance:", pca.explained_variance_ratio_.sum())
functions_st_louis.colinearity_detection(principalDf)
functions_st_louis.condition_number(principalDf.values)
coeffs = functions_st_louis.regression_coeffs(principalDf[["principal component 1", 'principal component 2']], y_train)
model = sm.OLS(list(y_train), principalDf[["principal component 1", 'principal component 2']]).fit()
print(model.summary())
# PCA 1 component
pca = PCA(n_components=1)
principalComponents = pca.fit_transform(x_train)
principalDf = pd.DataFrame(data = principalComponents
, columns = ['principal component 1'])
print("Explained Variance of Each Feature:", pca.explained_variance_ratio_)
print("Total Explained Variance:", pca.explained_variance_ratio_.sum())
functions_st_louis.colinearity_detection(principalDf)
functions_st_louis.condition_number(principalDf.values)
coeffs = functions_st_louis.regression_coeffs(principalDf[["principal component 1"]], y_train)
model = sm.OLS(list(y_train), principalDf[["principal component 1"]]).fit()
print(model.summary())
# #===================================================================================
# # Multiple Linear Regression
# # a. You need to include the complete regression analysis into your report. Perform one-step
# # ahead prediction and compare the performance versus the test set.
# # b. Hypothesis tests analysis: F-test, t-test.
# # c. AIC, BIC, RMSE, R-squared and Adjusted R-squared
# # d. ACF of residuals.
# # e. Q-value
# # f. Variance and mean of the residuals.
# #===================================================================================
model = sm.OLS(y_train, x_train1).fit()
print(model.summary())
x_test1 = x_test.drop("SNOW", 1)
# one step
predictions = model.predict(x_train1.values)
fig, ax = plt.subplots()
ax.plot(range(0, len(y_train)), y_train,label= "Train Data")
ax.plot(range(0, len(y_train)), predictions,label= "Predictions")
plt.legend(loc='upper left')
plt.title('Reduced Feature Space Linear Regression Model One Step Pred')
plt.xlabel('Time')
plt.ylabel('Flow')
plt.show()
# predictions
predictions = model.predict(x_test1.values)
fig, ax = plt.subplots()
ax.plot(range(0, len(y_train)), y_train,label= "Train Data")
ax.plot(range(len(y_train), len(y_train)+len(y_test)), y_test,label= "Test Data")
ax.plot(range(len(y_train), len(y_train)+len(y_test)), predictions,label= "Predictions")
plt.legend(loc='upper left')
plt.title('Reduced Feature Space Linear Regression Model Train/Test vs. Pred')
plt.xlabel('Time')
plt.ylabel('Flow')
plt.show()
# ACF of residuals
pred_errors = np.subtract(y_train, model.predict(x_train1.values))
functions_st_louis.plot_autocorr(pred_errors, lags=20, title="ACF for residuals errors")
# Q-Value
q = functions_st_louis.q_value(pred_errors, lags=250)
# Var and mean of residuals
print("Mean of the Residuals:", np.mean(pred_errors))
print("Variance of the Residuals:", functions_st_louis.error_var(pred_errors))
# MSE of final predictions
error = y_test - predictions
print("MSE of linear regression:", np.mean(np.square(np.array(error))))
# #===================================================================================
# # ARMA, ARIMA, and SARIMA Model
# # Develop an ARMA, ARIMA and SARIMA model that represent the dataset.
# # a. Preliminary model development procedures and results. (ARMA model order
# # determination). Pick at least two orders using GPAC table.
# # b. Should include discussion of the autocorrelation function and the GPAC. Include a plot of
# # the autocorrelation function and the GPAC table within this section).
# # c. Include the GPAC table in your report and highlight the estimated order.
# #===================================================================================
#
functions_st_louis.calc_gpac(10, 10, acf)
#
#
# #===================================================================================
# # Levenberg - Marquardt Algorithm
# # Display the parameter estimates, the standard deviation of the parameter estimates
# # and confidence intervals.
# #===================================================================================
# Based on the ACF and PACF, the order is ARMA(3,0,0) X ARIMA(0,0,1)365
ar_order = 1
ma_order = 1
coeffs, sigma_squared, cov, sse_array = functions_st_louis.levenberg_marquadt(flow3, ar_order, ma_order)
# coeffs = SARIMAX(y_train, order=(0,0,1), seasonal_order=(0,0,1,365)).fit()
print(coeffs)
#
# # Confidence intervals
uppers = []
lowers = []
for i in coeffs:
upper = i + 2*np.sqrt(np.linalg.det(cov))
lower = i - 2*np.sqrt(np.linalg.det(cov))
uppers.append(upper)
lowers.append(lower)
print("Upper Confidence Interval:", uppers)
print("Lower Confidence Interval:", lowers)
# Plot SSE vs. number of iterations
plt.title("SSE vs. Number of Iterations")
x = np.arange(0, len(sse_array))
plt.plot(x, sse_array, label = "Sum of Squared Error")
plt.legend()
plt.xlabel("Iterations")
plt.ylabel("SSE")
plt.show()
#===================================================================================
# Diagnostic Analysis
# a. Diagnostic tests (confidence intervals, zero/pole cancellation, chi-square test).
# b. Display the estimated variance of the error and the estimated covariance of the estimated
# parameters.
# c. Is the derived model biased or this is an unbiased estimator?
# d. Check the variance of the residual errors versus the variance of the forecast errors.
# e. If you find out that the ARIMA or SARIMA model may better represents the dataset, then
# you can find the model accordingly. You are not constraint only to use of ARMA model.
# Finding an ARMA model is a minimum requirement and making the model better is always
# welcomed.
#===================================================================================
# One step predicitons to get error
preds = functions_st_louis.one_step_forecast(y_train, coeffs, ar_order, ma_order)
var_ratio = np.var(y_train) / np.var(preds)
print("Ratio of the variance of the train set over the predicted set:", var_ratio)
plt.title("Predicted Values vs. Train Set")
x = np.arange(0, len(y_train))
plt.plot(x, y_train, label = "Train Data")
plt.plot(x, preds, label = "Predictions")
plt.legend()
plt.xlabel("Steps")
plt.ylabel("Y")
plt.show()
# Chi square whiteness test of residuals
pred_error = y_train - preds
lags=200
q = functions_st_louis.q_value(pred_error, lags)
functions_st_louis.plot_autocorr(pred_error, lags=20, title="ACF for residuals errors")
DOF = lags - ar_order - ma_order
alpha = .05
chi_crit = chi2.ppf(1-alpha, DOF)
print("Chi critical value:", chi_crit)
if q < chi_crit:
print("The residual is white")
else:
print("The residual is not white")
# Zero Pole Cancellation
print("Roots of AR:", np.roots(np.r_[1, coeffs[:ar_order]]))
print("Roots of MA:", np.roots(np.r_[1, coeffs[ar_order:]]))
# # H-Step forecast
forecast = functions_st_louis.h_step_forecast(df["Flow"], coeffs, ar_order, ma_order, y_test)
#forecast = functions_st_louis.h_step_forecast(df["Flow"], len(y_train)+1,coeffs, other=preds[:-1] ,step=len(y_test))
var_ratio = np.var(y_test) / np.var(forecast)
print("Ratio of the variance of the test set over the forecasted set:", var_ratio)
plt.title("Forecasts - St. Louis")
x = np.arange(0, len(y_test))
plt.plot(x, y_test, label = "Test Data")
plt.plot(x, forecast, label = "Forecasts")
plt.legend()
plt.xlabel("Steps")
plt.ylabel("Y")
plt.show()
forecast_error = y_test - forecast
# Comaprison of residual errors and forecast errors
var_ratio = np.var(pred_error) / np.var(forecast_error)
print("Ratio of the variance of the residual errors over the forecasted errors:", var_ratio)
#===================================================================================
# Base-models:
# average, naïve, drift, simple and exponential smoothing.
#===================================================================================
average_preds = functions_st_louis.average_forecast(y_train, y_test)
functions_st_louis.plot_preds(y_train, y_test, average_preds, "Average Forecast vs. Y-Test")
naive_preds = functions_st_louis.naive_forecast(y_train, y_test)
functions_st_louis.plot_preds(y_train, y_test, naive_preds, "Naive Forecast vs. Y-Test")
drift_preds = functions_st_louis.drift_forecast(y_train, y_test)
functions_st_louis.plot_preds(y_train, y_test, drift_preds, "Drift Forecast vs. Y-Test")
ses_preds = functions_st_louis.ses(y_train, y_test)
functions_st_louis.plot_preds(y_train, y_test, ses_preds, "SES Forecast vs. Y-Test")
|
Python
|
UTF-8
| 1,811
| 2.875
| 3
|
[] |
no_license
|
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpngw import AnimatedPNGWriter
# Import the wave function
from Psi import *
cn = 1/np.sqrt(2)*np.array([1, 1])
x = np.linspace(0, 1, 256)
t = np.linspace(0, 4/(np.pi), 256)
# Check normalization
f = np.abs(Psi(cn, x, t[0]))**2
integral = np.trapz(f, x = x)
if integral == 1:
print("Wave function is normalized")
else:
print("Wave function is not normalized. Integral is " + str(integral))
# Compute <x> and <x^2>
Ex = np.zeros(t.shape)
Ex2 = np.zeros(t.shape)
for i in range(0, len(t)):
Ex[i] = np.trapz(x*(np.abs(Psi(cn, x, t[i]))**2), x = x)
Ex2[i] = np.trapz(x**2*np.abs(Psi(cn, x, t[i]))**2, x = x)
STDx = np.sqrt(Ex2 - Ex**2)
# Compute <p> and <p^2>
Ep = np.zeros(t.shape)
Ep2 = np.zeros(t.shape)
dx = x[1] - x[0]
for i in range(0, len(t)):
Ep[i] = np.trapz(np.conjugate(Psi(cn, x, t[i]))*(-1j)*np.gradient(Psi(cn, x, t[i]), dx), x = x)
Ep2[i] = -np.trapz(np.conjugate(Psi(cn, x, t[i]))*np.gradient(np.gradient(Psi(cn, x, t[i]), dx), dx), x = x)
STDp = np.sqrt(Ep2 - Ep**2)
print("Uncertainty principle holds: " + str((STDx*STDp > 0.5).all()))
def animate(i):
line.set_data(x, np.abs(Psi(cn, x, t[i])))
annotation.xy = (Ex[i], -1)
annotation.set_position((Ex[i], -0.7))
return line, annotation
fig = plt.figure()
ax = plt.axes(xlim = (0, 1), ylim = (-1, 2))
line, = plt.plot([], [], lw = 2)
annotation = ax.annotate(r"$\langle x \rangle$", xy = (Ex[0], -1), xytext = (Ex[0], -0.7), arrowprops = dict(facecolor = "black", shrink = 0.05), )
anim = animation.FuncAnimation(fig, animate, frames = 256, interval = 20, blit = True)
plt.show()
#writer = AnimatedPNGWriter(fps=30)
#anim.save("nonStationaryModulus.png", dpi = 100, writer=writer)
|
C++
|
UTF-8
| 1,980
| 3.015625
| 3
|
[] |
no_license
|
#include "TextureLoader.h"
CTextureLoader::CTextureLoader(void)
{
}
CTextureLoader::~CTextureLoader(void)
{
}
///returns texture, make it equal to unsigned int
GLuint CTextureLoader::load_texture(const char* file)
{
glEnable(GL_TEXTURE_2D);
GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;
SDL_Surface *surface; // this surface will tell us the details of the image
if ( (surface = IMG_Load(file)) ) {
// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}
// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}
//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;
//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}
// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );
// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );
// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load PNG: %s\n", SDL_GetError());
return 1;
}
glDisable(GL_TEXTURE_2D);
TextureHeight = surface->h;
TextureWidth = surface->w;
SDL_FreeSurface(surface);
return texture;
}
|
C#
|
UTF-8
| 1,793
| 2.734375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
namespace simplePerformanceTest.WebApi.Net47.Controllers
{
public class RandomStringController : ApiController
{
private static readonly Random Random = new Random();
// GET api/values
[HttpGet]
[Route("baseline")]
public IHttpActionResult GetBaseline()
{
return Ok();
}
// GET api/values
[HttpGet]
[Route("randomString")]
public string Get()
{
string base64EncodedString = GenerateRandomHashedString();
return base64EncodedString;
}
// GET api/values
[HttpGet]
[Route("randomStringx20")]
public IEnumerable<string> GetStrings()
{
List<string> strings = new List<string>();
for (int counter = 0; counter < 20; counter++)
{
string base64EncodedString = GenerateRandomHashedString();
strings.Add(base64EncodedString);
}
return strings;
}
private static string GenerateRandomHashedString()
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string randomString = new string(Enumerable.Repeat(chars, 128).Select(s => s[Random.Next(s.Length)]).ToArray());
byte[] bytes = Encoding.UTF8.GetBytes(randomString);
SHA256Managed sha256Managed = new SHA256Managed();
byte[] hash = sha256Managed.ComputeHash(bytes);
string base64EncodedString = Convert.ToBase64String(hash);
return base64EncodedString;
}
}
}
|
JavaScript
|
UTF-8
| 3,367
| 2.59375
| 3
|
[] |
no_license
|
import React, {useState, useEffect} from 'react'
import initPexel from './initPexel';
import SearchBar from './SearchBar';
import ImageList from './ImageList';
import './SearchBar.css';
import {Row, Col} from "react-bootstrap" //replaced
import {FaArrowAltCircleRight, FaArrowAltCircleLeft} from "react-icons/fa"
import {AiOutlineSearch} from "react-icons/ai"
export const Pexels = (params) => {
const [images, setImages] = useState(false);
const [searchText, setSearchText] = useState(false);
const setImageUrl = params.setDbImage;
const [nextPage, setNextPage] = useState(false)
const [previousPage, setPreviousPage] = useState(false)
const getPhotos = (data) => {
setNextPage(data.next_page)
setPreviousPage(data.prev_page)
setImages({photos: data.photos})
}
const onSearchSubmit = async () => {
const response = await initPexel.get(`/v1/search`, {
params: {
query: searchText,
per_page: 15,
page: 1
}
});
getPhotos(response.data)
}
const handleKeyPress = (e) => {
if (e.key === 'Enter'){
document.getElementById("pexelUrl").value = searchText;
onSearchSubmit()
}
}
const getNext = async() => {
const response = await initPexel.get(nextPage);
getPhotos(response.data)
}
const getPrevious = async() => {
const response = await initPexel.get(previousPage);
getPhotos(response.data)
}
return (
<div className="pexels-container">
<span style={{display: 'flex'}}>
<span className="pexel-search-field">
<input type="text"
placeholder="Search for photos on Pexels..."
id="pexelUrl"
className="pexel-search-input"
onKeyPress={handleKeyPress}
onChange={(e) =>{
setSearchText(e.target.value)
}}/>
</span>
<span className="pexels-controls" onClick={onSearchSubmit} title="Search Pexels for pictures">
<AiOutlineSearch/>
</span>
</span>
<Row>
<div className="pexels-control">
{nextPage && <span onClick={getNext} className="pexels-controls" title="Next">
<FaArrowAltCircleRight/>
</span>}
{previousPage && <span onClick={getPrevious} className="pexels-controls" title="Previous">
<FaArrowAltCircleLeft/>
</span>}
</div>
</Row>
<ImageList images={images.photos} setImageUrl={setImageUrl}/>
</div>
);
}
/*
class App extends React.Component {
state = { photos: [] };
onSearchSubmit = async (term) => {
const response = await pexels.get(`/v1/search`, {
params: {
query: term,
per_page: 10,
page: 3
}
});
this.setState({ photos: response.data.photos });
}
render() {
return (
<div className="container" style={{marginTop: '10px'}}>
<SearchBar onSubmit={this.onSearchSubmit}/>
<ImageList images={this.state.photos} />
</div>
);
};
}
export default App;*/
|
PHP
|
UTF-8
| 3,597
| 2.59375
| 3
|
[] |
no_license
|
<?php
/*
* This file is part of the Mall Digital Ecosystem (MDE) project.
*
* (c) <SCCD> <office@sccd.lu>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Scc\Cdn\Builder;
use Scc\Cdn\Tests\Helper\Traits\ReflectionTrait;
/**
* Class UrlBuilderTest
*
* Test class for UrlBuilder::class
*
* @author Jason Benedetti <jason.benedetti@sccd.lu>
*/
class UrlBuilderTest extends \PHPUnit_Framework_TestCase
{
use ReflectionTrait;
const PATH = 'my/path/to/test';
/**
* @var UrlBuilder
*/
protected $instance;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->instance = new UrlBuilder(self::PATH);
}
/**
* Test the UrlBuilder::__construct class
*/
public function testConstruct()
{
$this->assertSame(self::PATH, $this->getProperty($this->instance, 'basePath'));
}
/**
* Provide test cases for url parts add
*
* @return array
*/
public function provideUrlParts()
{
return [
[['part1', 'part2'], ''],
[['part1', 'part2'], \RuntimeException::class],
];
}
/**
* Test the UrlBuilder::addUrlParts method
*
* @param array $parts
* @param string $exception
*
* @dataProvider provideUrlParts
*/
public function testAddUrlPart(array $parts, $exception)
{
if (!empty($exception)) {
$this->expectException($exception);
foreach ($parts as $part) {
$this->instance->addUrlPart(0, $part);
}
} else {
foreach ($parts as $position => $part) {
$this->assertSame($this->instance, $this->instance->addUrlPart($position, $part));
}
$this->assertSame($parts, $this->getProperty($this->instance, 'urlParts'));
}
}
/**
* Test the UrlBuilder::replaceUrlPart method
*/
public function testReplaceUrlPart()
{
$reflectedProp = $this->setProperty($this->instance, 'urlParts', ['test_value_1', 'test_value_2']);
$this->assertSame($this->instance, $this->instance->replaceUrlPart(0, 'test_replacement_value'));
$this->assertSame(['test_replacement_value', 'test_value_2'], $reflectedProp->getValue($this->instance));
}
/**
* Test the UrlBuilder::getBasePath method
*/
public function testGetBasePath()
{
$this->assertSame(self::PATH, $this->instance->getBasePath());
}
/**
* Test the UrlBuilder::setBasePath method
*/
public function testSetBasePath()
{
$this->assertSame($this->instance, $this->instance->setBasePath('replace/path'));
$this->assertSame('replace/path', $this->getProperty($this->instance, 'basePath'));
}
/**
* Test the UrlBuilder::build method
*/
public function testBuild()
{
$this->setProperty($this->instance, 'urlParts', ['test_value_1', 'test_value_2']);
$this->assertSame('test_value_1/test_value_2', $this->instance->build());
}
/**
* Test the UrlBuilder class constants
*/
public function testConstants()
{
if (!defined(get_class($this->instance) . '::PATH_TYPE_REMOTE')) {
$this->fail(sprintf('The %s constant have to be defined', 'PATH_TYPE_REMOTE'));
}
if (!defined(get_class($this->instance) . '::PATH_TYPE_UPLOAD')) {
$this->fail(sprintf('The %s constant have to be defined', 'PATH_TYPE_UPLOAD'));
}
}
}
|
C#
|
UTF-8
| 2,021
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DailyChallenge
{
public class DailyChallenge6
{
/*
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
*/
public int Proceed(string text)
{
if (string.IsNullOrWhiteSpace(text))
{
return 0;
}
return ProceedInternal(text);
}
private int ProceedInternal(string text)
{
if (text.Length < 3)
{
return ProceedOneOrTwoChars(text);
}
// At least 3
int parsedOne = int.Parse(text[0].ToString());
int parsedTwo = int.Parse(string.Concat(text.Take(2)));
int result = 0;
if (InRange(parsedOne))
{
result += ProceedInternal(string.Concat(text.Skip(1)));
}
if (InRange(parsedTwo))
{
result += ProceedInternal(string.Concat(text.Skip(2)));
}
return result;
}
private int ProceedOneOrTwoChars(string text)
{
if (text.Length == 1)
{
int parsed = int.Parse(text);
return InRange(parsed) ? 1 : 0;
}
int parsedTwo = int.Parse(text);
int result = InRange(parsedTwo) ? 1 : 0;
// Add "twoChar" to "two separate chars" (if one is not parseable then 0)
return result + ProceedOneOrTwoChars(string.Concat(text[0])) * ProceedOneOrTwoChars(string.Concat(text[1]));
}
private bool InRange(int number)
{
return number > 0 && number <= 26;
}
}
}
|
PHP
|
UTF-8
| 4,103
| 3
| 3
|
[] |
no_license
|
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$modules_code = $modules_name = "";
$modules_code_err = $modules_name_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate modules ID
$input_modules_code = trim($_POST["modules_code"]);
if(empty($input_modules_code)){
$modules_code_err = "Please enter the modules code.";
} elseif(!filter_var($input_modules_code, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z]/")))){
$modules_code_err = "Please enter a valid modules code.";
} else{
$modules_code = $input_modules_code;
}
// Validate modules Name
$input_modules_name = trim($_POST["modules_name"]);
if(empty($input_modules_name)){
$modules_name_err = "Please enter modules name.";
} elseif(!filter_var($input_modules_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z]/")))){
$modules_name_err = "Please enter a valid name.";
} else{
$modules_name = $input_modules_name;
}
// Check input errors before inserting in database
if(empty($modules_code_err) && empty($modules_name_err)){
// Prepare an insert statement
$sql = "INSERT INTO modules (modules_code, modules_name) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_modules_code, $param_modules_name);
// Set parameters
$param_modules_code = $modules_code;
$param_modules_name = $modules_name;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
header("location: module.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Create Record</h2>
</div>
<p>Please fill this form and submit to add new module record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($modules_code_err)) ? 'has-error' : ''; ?>">
<label>Module Code</label>
<input type="text" name="modules_code" class="form-control" value="<?php echo $modules_code; ?>">
<span class="help-block"><?php echo $modules_code_err;?></span>
</div>
<div class="form-group <?php echo (!empty($modules_name_err)) ? 'has-error' : ''; ?>">
<label>Module Name</label>
<input type="text" name="modules_name" class="form-control" value="<?php echo $modules_name; ?>">
<span class="help-block"><?php echo $modules_name_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<a href="module.php" class="btn btn-default">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
|
Java
|
UTF-8
| 1,098
| 2.40625
| 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.mycompany.bankproject;
//
//import javax.persistence.EntityManager;
//import javax.persistence.EntityManagerFactory;
//import javax.persistence.Persistence;
//
///**
// *
// * @author suren
// */
//public class UpdateCustomer {
// public static void main( String[ ] args ) {
// EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
//
// EntityManager entitymanager = emfactory.createEntityManager( );
// entitymanager.getTransaction( ).begin( );
// Employee employee = entitymanager.find( Employee.class, 1201 );
//
// //before update
// System.out.println( employee );
// employee.setSalary( 46000 );
// entitymanager.getTransaction( ).commit( );
//
// //after update
// System.out.println( employee );
// entitymanager.close();
// emfactory.close();
// }
//}
//}
|
JavaScript
|
UTF-8
| 1,322
| 2.90625
| 3
|
[] |
no_license
|
function exibeClientes(clientes) {
for (var i = 0; i < clientes.length; i++) {
var cliente = clientes[i];
var dadosCliente = '<div id="' + cliente.id + '">' +
'ID: ' + cliente.id +
'<br>Nome: ' + cliente.nome +
'<br>Endereço: ' + cliente.endereco +
'<br>Telefone: ' + cliente.telefone +
'<br>Email: ' + cliente.email +
'<br><a href="#" onClick="deletaCliente(' + cliente.id +')"> EXCLUIR </a>' +
'</div>';
document.getElementById('result').innerHTML += dadosCliente + '<br><br>';
}
}
function deletaCliente(id){
$.ajax({
url: '/cliente/deleta?id=' + id,
dataType: 'json',
type: 'post',
error: function (dados) {
alert('Erro: ' + dados.data);
},
success: function (dados) {
if (dados.status === 'ERRO')
alert('Erro: ' + dados.data);
else{
alert(dados.data);
var divResult = document.getElementById('result');
divResult.removeChild(document.getElementById(id));
}
}
});
}
|
Java
|
UTF-8
| 1,068
| 3.078125
| 3
|
[] |
no_license
|
package day47_blocks;
import static java.lang.Math.*;
import static java.lang.Character.*;
import static java.util.Arrays.sort;
import java.util.Arrays.*;
import static java.time.LocalDateTime.now;
import java.util.Arrays;
public class StaticImports {
public static void main(String[] args) {
System.out.println(PI); // 3.14
System.out.println(max(10, 5));
System.out.println(max(10, 10));
System.out.println(min(2, 10));
System.out.println(floor(3.45));
System.out.println(round(45.99));
System.out.println(round(15.4999));
System.out.println(abs(-10));
System.out.println(pow(10.3, 2));
System.out.println(sqrt(5));
System.out.println(random() * 10);
//========================================================
System.out.println(isDigit('4'));
System.out.println(isAlphabetic('a'));
//========================================================
int[] nums = { 31, 34, 45, 6, 7, 234 };
sort(nums);
System.out.println(Arrays.toString(nums));
//========================================================
System.out.println(now());
}
}
|
Java
|
UTF-8
| 2,854
| 2.703125
| 3
|
[] |
no_license
|
package jl.playground.xml.sax;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class SAXLocalNameCount extends DefaultHandler {
private Hashtable<String, Integer> tags;
@Override
public void startDocument() throws SAXException {
tags = new Hashtable<>();
}
private static String convertToFileURL(String filename) {
String path = new File(filename).getAbsolutePath();
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
if (!path.startsWith("/")) {
path = "/" + path;
}
return "file:" + path;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
String key = localName;
Integer value = tags.get(key);
System.out.printf(
"parsing: URI %s, LOCALNAME %s, QNAME %s, ATTRIBUTES %s\n",
uri, localName, qName, attributes);
System.out.println("qname index: " +attributes.getIndex(qName));
System.out.println(attributes.getValue(localName));
if (value == null) {
tags.put(key, 1);
} else {
tags.put(key, ++value);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.print("SAX Event: CHARACTERS[ ");
try {
OutputStreamWriter outw = new OutputStreamWriter(System.out);
outw.write(ch, start, length);
outw.flush();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(" ]");
}
@Override
public void endDocument() throws SAXException {
Enumeration<String> e = tags.keys();
while (e.hasMoreElements()) {
String tag = e.nextElement();
int count = tags.get(tag);
System.out.println("Local Name \"" + tag + "\" occurs " + count
+ " times");
}
}
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
String filename = null;
for (int i = 0; i < args.length; i++) {
filename = args[i];
if (i != args.length - 1) {
usage();
}
if (filename == null) {
usage();
}
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new SAXLocalNameCount());
xmlReader.parse(convertToFileURL(filename));
}
}
private static void usage() {
System.err.println("Usage: SAXLocalNameCount <file.xml>");
System.err.println(" -usage or -help = this message");
System.exit(1);
}
}
|
Java
|
UTF-8
| 1,295
| 3.171875
| 3
|
[] |
no_license
|
package com.neustar.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class GenerateJSon {
private static final String FILENAME = "src\\test\\resources\\testdata\\SampleJson.json";
public static void main(String[] args) throws IOException {
GenerateJSon GJ = new GenerateJSon();
String content = GJ.readJsonFile(FILENAME);
content = GJ.replaceJsonVariable(content, "age", 20);
content = GJ.replaceJsonVariable(content, "name", "ABCDEF");
System.out.println(content);
}
public String readJsonFile(String file) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String replaceJsonVariable(String str, String replaceVariable, Object value) {
return str.replaceAll("\\$\\{" + replaceVariable + "\\}", value.toString());
}
}
|
Markdown
|
UTF-8
| 107,339
| 2.859375
| 3
|
[] |
no_license
|
---
layout: wiki
title: makho's Backlight Mod Notes
category: Wiki
---
## **The best backlight kit is the one you already have.** Enjoy it. A new kit does not invalidate your prior build.
I, /u/Admiral_Butter_Crust or makho on discord or youtube, own *nearly* every backlight kit on the market right now for pretty much every console. I feel like that gives me a rather unique perspective on these things. I did actually end up making a video on just the GBC portion of this but it's pretty old and obsolete now. I also ramble quite a bit so I figure that limiting myself to just text and a few pictures here and there will let me try and *succinctify* myself a bit. If you're new to the hobby and just looking for a recommendation on what you should get and find that this document is information overload, just pick your console (new there too? Look at a [GBA](#agb) or [GBA SP](#ags)) and just stick with the summary at the top of the section.
Each system section has a summary with my recommended kit listed there. I also added a chart to be used a quick summary for the kits. You should check out the notes below or the full video for more information but it should be pretty easy to understand. Any field that has "recommended" in it should be interpreted as "yes" if you want the full experience with all features. For some kits this means full brightness control or hiding the edges of the LCD panel with a new lens but for core functionality, soldering is (usually) not required.
Finally, if you're using this list as a vector for picking "the best" \<x\>, you should understand that the "the best" console or kit or whatever will always be the one you already have. Sure, the new kit from funnyplaying may have this cool new feature but it does NOT invalidate your existing build. If you find yourself building a new Game Boy for every new kit, you're probably not in it for the games, are you? The purpose of this page is to document the different offerings and the primary differences between each item, not to create a hierarchy of options to dismiss the inferior kits. The order of options within each section is largely arbitrary. Newer options tend to be closer to the bottom with similar options grouped together for ease of comparison.
# Foreword on Display Types
There are several different types of LCDs used in Game Boys and these mod kits. I would like to spend a quick few minutes discussing them, if nothing else, to give you proper terms to go research. Do an internet serach of the **bolded** terms for more information.
Except for the Game Boy Light, all Game Boy consoles before the Game Boy Advance SP (and even technically including the earlier model) use **passive** **reflective** displays. This means that behind the screen is a reflector that is used to reflect natural light back into your eyes for the purpose of illuminating the screen. Starting with the Game Boy Advance SP, Nintendo started including internal lighting in the screens. The first SP model, the AGS-001, is a **frontlit** **reflective** display because there is a light panel *in front* of the screen that provides light to the **reflective** display. The second model of Game Boy Advance SP, the AGS-101, uses a **backlit** **transmissive** display because it no longer reflects natural lighting but allows light to pass through it from the light panel behind the LCD. Except for the original model DS (NTR, not USG), all Nintendo consoles made after the AGS-001 use **backlit** **transmissive** displays. All the displays I've mentioned so far are extremely common throughout the vast majority of electronics out there. There are other display types like CRT (for which is the only display that has **scanlines**), plasma, DLP, OLED, etc, but those are not too relevant for this discussion. I may circle back to CRT later but for now we'll continue on about Game Boys.
Let's circle back to the two consoles I mentioned and excluded, the original DS model and Game Boy Light. Both of these consoles use the same type of display, a **transflective** **backlit** LCD ([yes, really, the DS is backlit, not frontlit](https://www.youtube.com/watch?v=84H5SJFJRlU)). The word "transflective" is a portmanteau of "transmissive" and "reflective" and is functionally similar a "one-way" mirror. These screens are built as a reflective display but instead of a reflector, they have a layer applied that will reflect light from the front or allow transmission of light from the back. These screens also have a backlight so when the backlight is off, the screen works much like a passive reflective display but when the backlight is on, the screen works much like a backlit transmissive display. Hence the word transflective. Good reflectors can be expensive and at best diminish color quality and black levels so most people usually opt for sunlight readibility compensation with an absurdly bright backlight instead.
Next, I want to talk about the specific technologies used to make these displays. All of the LCDs used in Game Boy consoles are made with **thin-film transistor** (TFT) technology. TFT displays can be further broken down into **twisted-nematic** (TN) or **in-plane switching** (IPS) displays (but not limited to). TN type displays were used primarily due to their cost (cheap) and power efficiency. This made them ideal for use within an inexpensive portable device. IPS type screens were around at the time but the technology wasn't quite mature at the time (arguably, neither was TN but TN was a lot more mature at the time) and not quite suitable for Game Boys. Benefits of an IPS type display over a TN display usually include more accurate color reproduction and much wider viewing angles. IPS type screens are often used in mod kits.
Last, if you see any mention of "Q5", "9380", or "690" LCDs or backlight kits, that is a reference to the screen itself that is packed with the kit. The kits that use these screens are designed to repurpose salvaged LCDs ($) instead of having something new manufactured from scratch ($$$). Most kits are using new old stock LCDs rather than LCDs directly pulled from phones but for replacement purposes, cheap display assemblies may be sourced and the LCD extracted manually. If the screen isn't mentioned, it is unknown where the LCD is salvaged from, if it's salvaged at all. "690" LCDs (DMG, MGB, CGB) are from the [Palm Centro 690](https://www.phonescoop.com/phones/phone.php?p=1363) and are available with a digitizer attached. The digitizer is held on to the edges of the LCD (NOT laminated) with double sided tape and must be removed to use in a GB. "9380" LCDs (CGB, AGB, AGS) are from the [BlackBerry Curve 9380](https://www.gsmarena.com/blackberry_curve_9380-4331.php) and are available as bare LCDs from most GB kit resellers or as display assemblies from phone parts resellers. The LCD must be extracted from a phone assembly if applicable to use in a GB. "Q5" LCDs (DMG, MGB, CGB) are from the [BlackBerry Q5](https://www.gsmarena.com/blackberry_q5-5452.php) and are available as bare LCDs from most GB kit resellers or as display assemblies from phone parts resellers. The LCD must be extracted from a phone assembly if applicable to use in a GB. Looks like some of these LCDs can be grabbed from [cloud game store on aliexpress.](https://www.aliexpress.com/item/1005002097273361.html)
# Laminated LCDs
A new trend with some backlight kits is to have the glass lens **laminated** to the LCD, much like how modern smartphones and tablets are constructed. Traditionally, Game Boys are made with an air gap between the plastic lens on the outside and the surface of the LCD on the inside. This results in a highly durable and modular build. Scratch the lens? Just pop it off and replace it. Want a custom lens? Just order one and replace it. However, some of the newer kits are bonding the LCD to the lens and shipping them as one unit (for example, the [newest Funnyplaying Game Boy Color kit](https://funnyplaying.com/collections/product/products/gbc-retro-pixel-ips-lcd-kit-1)). This cuts down on the space between the lens and LCD and results in a much better looking final install, greatly improved picture quality, and completely eliminates the possibilty of dust or fingerprints under the lens. This is not without downsides, however. The primary issue is that lens customization is much more expensive/difficult, especially if you want to retain the lamination since the cost of replacing a lens OR LCD now includes BOTH a custom lens and LCD. Another issue particular to Game Boys is that you either have to use a custom shell designed for the laminated display OR you have to significantly modify your existing shell to fit the laminated display assembly. Please see [this article](https://essentialpicks.com/laminated-vs-non-laminated-display-tablet/) for more information on LCD lamination and some good visuals.
# Contents
* [Original Game Boy (DMG)](#dmg)
* [Game Boy Pocket (MGB)](#mgb)
* [Game Boy Color (CGB)](#cgb)
* [Game Boy Advance (AGB)](#agb)
* [Game Boy Advance SP (AGS)](#ags)
# DMG
## Original Game Boy
I actually own most of the DMG kits now. I have three different recommendations for "best" kit as each kit seems to have different strengths or weaknesses. Overall cheapest would be an inexpensive LED panel for modifying the OEM LCD (item #1). This is certainly a good option if you like the OEM style screen but is not an option if your LCD is missing or damaged (cracked, screen rot, horizontal lines, etc). You can go a long way in improving the contrast but the original screens are still pretty low quality and have severe ghosting issues or other display artifacts. Alternatively, a total replacement kit is also (finally) an option. My pick for ease of install, performance, and function is definitely the taobao Moon Screen (item #6). This kit gives you more features than every other kit in this list and requires absolutely zero permanent modification to your DMG. No shell modding, no permanent adhesive (to the DMG), and, aside from adding a speaker, no soldering required. Since that kit can be a bit hard to get outside China though, the One Chip IPS "DMG Backlight OSD" kit (item #11) is also a fantastic option. While the install is a bit more involved, the actual display image itself is bigger (slightly larger than OEM which requires shell modification) and looks proportionally better than the Moon Screen kit when installed on the DMG. Additionally, this kit does implement a very similar OSD that allows customizable palettes and even display image positioning if your LCD is not perfectly aligned with your lens.
|DMG|Full Size|Custom Lens|Soldering|Cutting|Integer Scaling|Pixel Grid|Color Palettes|Adjustable Brightness|Stuttering or Tearing|
:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|
|1. Traditional backlighting methods|Yes|No|Required|No|1x|Yes|No|No|No|
|2. BennVenn 3.0" LCD kit|Much Larger|Required|Speaker Only|Required|1x|Yes|No|No|No|
|3. HiVision 690 TFT kit (AIO)|Much Smaller|Recommended|Required|No|2x|No|Button or Touch|Button or Touch|Frame Drops|
|4. One Chip 690 TFT kit (AIO)|Much Smaller|Recommended|Required|No|2x|No|Button or Touch|Button or Touch|No|
|5. Taobao IPS Backlight (v1 - "Rainbow Screen")|Yes|No|Required|No|3x|No|Yes|Yes|No|
|6. Taobao IPS Backlight (v2 - "Moon Screen")|Smaller|No|Speaker Only|No|3x|Emulation|Contrast Wheel|Contrast Wheel|No|
|7. Funnyplaying Q5 IPS "Retro Pixel" Backlight|Larger|Required|Speaker Only|Required|4x|Emulation|Contrast Wheel|Contrast Wheel|No|
|8. One Chip IPS Backlight kit ("RIPS v1")|Yes|No|Speaker Only|Required|2x|No|Contrast Wheel|Contrast Wheel|No|
|9. One Chip IPS Backlight kit ("RIPS v2")|Yes|No|Speaker Only|Required|2x|No|Contrast Wheel|Contrast Wheel|No|
|10. One Chip IPS Backlight kit ("RIPS v3")|Yes|No|Speaker Only|Required|2x|No|Contrast Wheel|Contrast Wheel|No|
|11. One Chip Q5 IPS "DMG Backlight OSD"|Larger|Required|Speaker Only|Required|4x|Emulation|Contrast Wheel|Contrast Wheel|No|
|12. Freckleshack v2.5 "Aioli" TFT kit|Much Smaller|Recommended|Required|No|2x|No|No|Button|No|
1. Traditional backlighting methods ([console](https://i.ebayimg.com/images/g/E0oAAOSwBgxdm35A/s-l1600.jpg) and [kit](https://cdn.discordapp.com/attachments/666796555835015169/713844571284570255/image0.jpg)) -- you can backlight the original LCD by removing the reflective layer and adding a small LED panel. Results are surprisingly decent for the cost but the effort involved to get a good result can be a bit high and, even then, you still have to deal with all of the cons of the original screen. Which means poor contrast and ghosting. There are methods to improve the contrast (biverting) and this will help significantly. The LED panels themselves can also be a bit low quality and have LED "hot spots" but there are some high quality panels available. If the hot spots really bug you and you can't salvage a good panel, you can use an electro-luminescent (EL) panel but those are generally more costly and not as bright (also come in limited colors). Image shamelessly stolen from u/MrCrono666. I have one of these built by the afore mentioned user and it is absolutely wonderful looking. Still, I prefer one of the IPS kits but my opinion on how good these mods can look has definitely been changed.
2. BennVenn 3.0" LCD kit ([console](https://cdn.shopify.com/s/files/1/0804/0095/files/3in1_540x.jpg?v=1552016880) and [kit](https://cdn.shopify.com/s/files/1/0804/0095/products/IMG20181026191251_360x.jpg?v=1540698675)) -- this is a replacement front PCB with a new, larger LCD on it. Other than installing a speaker and cutting the shell to reduce the bezel size, the install is relatively drop-in. The new screen is bigger but it is the correct resolution. It also still has the same (or even worse in some cases) ghosting issues and the contrast can still be inadequate. It's a decent option when in stock but other than the size, it's not considered an improvement by most. (I don't have one of these)
3. HiVision 690 TFT kit (AIO) ([console](https://ae01.alicdn.com/kf/Ha1919a69ce024edbad12a9c6e588fb0cw/High-brightness-LCD-retrofit-kit-for-Gameboy-DMG-GB-DMG-GB-backlit-LCD.jpg) and [kit](https://cdn.discordapp.com/attachments/246604458744610816/658732946282512394/unknown.png)) -- I don't have this kit in a DMG but I do have one in a MGB. There are two different versions and this one is the version that drops frames. Last I checked, this was also the only kit that actually came with the proper wiring. This kit significantly improves on the ghosting and contrast issues of the previous methods but the viewing angles are not that great and the LCD size itself is a big down-grade. On the plus size, the install does not require any irreversible modification. You do need to desolder the original LCD from the front board and solder the new one in place. I can't vouch for the ease of install but it doesn't look too bad as long as you don't mind soldering directly to a ribbon cable. Due to the smaller LCD, the bezels are huge. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. (I technically don't have one of these)
4. One Chip 690 TFT kit (AIO) ([console](https://ae01.alicdn.com/kf/Ha1919a69ce024edbad12a9c6e588fb0cw/High-brightness-LCD-retrofit-kit-for-Gameboy-DMG-GB-DMG-GB-backlit-LCD.jpg) and [kit](https://i.imgur.com/xDwyPaM.jpg)) -- I don't have this kit in a DMG but I do have one in a MGB. There are two different versions and currently only one works in a DMG and that one is the version that does not drop frames. Last I checked, this kit did not come with the wiring you needed to easily install this. You can use the ribbon cable adapter from the above kit to install this kit or you can wire it manually with the MGB ribbon cable. This kit significantly improves on the ghosting and contrast issues of the previous methods but the viewing angles are not that great and the LCD size itself is a big down-grade. On the plus size, the install does not require any irreversible modification. You do need to desolder the original LCD from the front board and solder the new one in place. I can't vouch for the ease of install but it doesn't look too bad as long as you don't mind soldering directly to a ribbon cable. Due to the smaller LCD, the bezels are huge. Presumably, [the custom color palettes that the new kit supports](https://i.imgur.com/lPubcjc.png) will work on this console too. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. (I technically don't have one of these)
5. Taobao IPS Backlight (v1 - "Rainbow Screen") ([console](https://i.redd.it/mwzcgrlso3t21.jpg) and [kit](https://i.imgur.com/wkedAcF.jpg)) -- The kit looks amazing in the pictures and videos I've seen but it's difficult to get outside of China. My understanding is that this kit has been discontinued in favor of the v2 version coming soon^^^tm (which I will be getting). The v1 version is not a full front PCB replacement as it appears you have to solder it to the front board like the AIO kit above but it does fix all of the issues of all of the previous kits. The screen size is the same as stock (so it works with OEM lenses), the brightness is great, the viewing angles are incredible, the frame rate looks good, the ghosting is way better than stock (but still not perfect as it's an IPS LCD). I'm pretty stoked for my v2. Per funnyplaying, it should be ["soon"](https://www.instagram.com/p/Byy_iyBHk5l/?utm_source=ig_web_copy_link) but it's still unclear if that's a new kit or if that's the "v2" version of this kit. Images taken from [the thread](https://www.reddit.com/r/Gameboy/comments/bert1n/new_backlit_ips_screen_mod_kit_for_gameboy_dmg/) made by u/TheChineseGuy2019
6. Taobao IPS Backlight (v2 - "Moon Screen") ([console and kit](https://imgur.com/a/UGv4IL6)) -- This kit is basically the Rainbow Screen kit but more refined. Installation is significantly easier than the previous iteration and aside from having to transfer your speaker over, the kit is actually 100% drop in with no modding required. You do not need to cut up your shell and the only soldering is for the speaker. Unlike the Funnyplaying kit or the One Chip kits which use 4x and 2x scaling respectively, this kit uses 3x scaling so the image is not going to be as sharp as the funnyplaying kit but it is sharp enough to have the pixel grid enabled like the funnyplaying kit. Personally, I don't like that option but at least it is exactly that; an option. Everything on this kit is configurable, even each color of every pixel from the line grid to the DMG "color" palettes and you can save your configurations to one of eight presets. A side effect of the kit being completely drop in with no modding required is that the LCD itself is a bit smaller and is visible from the outside with a normal sized lens and the display image itself is a bit smaller. This kit has the image displayed on the LCD measuring in at 43mm wide by 38.75mm tall whereas the OC V3 IPS kit measures in at 44.5mm wide by 40.35 tall. The Funnyplaying kit will be bigger than both of these kits and I'll add the measurements as soon as I get my hands on one. All in all, I think this is the best kit yet. I'm eager to get my hands on the funnyplaying version (which as it turns out, *is* a completely different kit) but due to the trimming required for install and what we already know about the built-in configurations I'm not sure if it will be better. (see [my install here](https://www.youtube.com/watch?v=zqmTNd748lU))
7. Funnyplaying Q5 IPS "Retro Pixel" Backlight ([console](https://i.imgur.com/hLTnbDB.jpg) and [kit](https://cdn.shopify.com/s/files/1/2481/6766/products/GBKIT1200_2000x.jpg?v=1591593968)) -- this is basically their MGB IPS kit but with an additional replacement front board for the DMG. I'm extremely pleased with it so far. Quick tap the contrast wheel and then up or down to cycle through the palettes and long tap to toggle the pixel grid emulation on and off. The contrast wheel controls the brightness up or down when not in palette select mode (quick tap to toggle modes). The screen looks absolutely amazing and the trim required to install it is actually pretty easy. I didn't notice any egregious screen issues like dropped frames or tearing that some other kits seem to exhibit. I HIGHLY recommend using a bracket or a spacer to line it up though. The included adhesive is permanent so if you mess it up [(like I did on the MGB install),](https://youtu.be/oCpjxyfpCPw) you're stuck with it unless you want to purchase a new LCD [(less than $7 from funnyplaying).](https://funnyplaying.com/collections/product/products/dmg-gbp-after-sales-ips-lcd) You can use a stock sized lens (and that's what it comes with) but the actual display image is slightly larger than stock and might be best with the custom lens included in the kit. Part of the install is making the LCD window bigger to work with the new lens. Biggest downside is the battery life with an estimated 25~50% runtime after the install, depending on your brightness level. The only better kit than this one is the One Chip IPS "DMG Backlight OSD" kit (item #11). (see [my install here](https://youtu.be/ZogFkhIbBq8))
8. One Chip IPS Backlight kit ("RIPS v1") ([console](https://i.imgur.com/te9Yidf.jpg) and [kit](https://i.imgur.com/GGEMw1S.png)) -- I actually got a couple of these kits to install. The v1 kits do have a pretty large flaw in that the grays are swapped but it's really easy to fix if you don't mind cutting a couple traces on the DMG or the replacement front board. For example, the console on the left is as they are shipped but the kit on the right is the one I fixed. Both kits are the same kit otherwise. This kit is a full front board replacement and the only soldering required is for attaching a speaker (and fixing the palette swap). The trimming required is very easy to do with just flush cutters and takes all of 30 seconds. The screen size is the same as stock (so it works with OEM lenses), the brightness is great, the viewing angles are incredible, the frame rate looks good, the ghosting is way better than stock (but still not perfect as it's an IPS LCD). See this [imgur album](https://imgur.com/a/DDlowE5) I made that documents the issue, the fix, and several before and after images with all the color palettes. New batch kits (look for the black PCB and a v3 mark or a green pcb and a v2 mark on the front board) will not require the palette fix. It should have better contrast on the gray palette too ([left is v1 kit, right is v2 kit](https://cdn.discordapp.com/attachments/332487777986019337/674133183993741323/unknown.png)). (see [my install here](https://www.youtube.com/watch?v=GARDelCYnEs))
9. One Chip IPS Backlight kit ("RIPS v2") -- The install is identical to v1 EXCEPT that you do not have to swap the LCD data lines. The performance is pretty much identical as well except that the grays are correctly assigned in all palettes (instead of JUST the yellow/pink palette) and the contrast on the "gray" palette is even better. I really like this kit but the funnyplaying kit looks as though it may be even more promising if the v2 version keeps the custom palette options from v1. [Left is v1 kit, right is v2 kit.](https://cdn.discordapp.com/attachments/332487777986019337/674133183993741323/unknown.png) (see [my install here](https://www.youtube.com/watch?v=_DqzA0DJ3bQ))
10. One Chip IPS Backlight kit ("RIPS v3") -- Very similar to the above two kits but they are now using black soldermask on the PCBs and the PCBs should be marked with "RIPS V3" as well. These kits use a new LCD that is slightly different shape (wider but shorter) so positioning brackets made for V1 or V2 will not work but otherwise everything else should be similar. The new LCD is much easier to connect to the daughterboard PCB as it uses a snap connector similar to the Funnyplaying IPS kits (but not the same, it's actually a lot bigger on this kit). The V3 PCBs also reportedly fix some button contact issues as the buttons have been moved slightly on the PCB ([v2](https://cdn.discordapp.com/attachments/246604458744610816/714747359166332999/image0.jpg) vs [v3](https://cdn.discordapp.com/attachments/246604458744610816/714747367890354189/image1.jpg)). Performance of V2 vs V3 seems pretty much identical otherwise. Compare V2 (top) with V3 (bottom): [https://i.imgur.com/ylFQC3u.jpg](https://i.imgur.com/ylFQC3u.jpg) (see [my install here](https://www.youtube.com/watch?v=U7fdn3bf8GM))
11. One Chip Q5 IPS "DMG Backlight OSD" ([kit](https://cdn.shopify.com/s/files/1/0266/1862/6122/products/Clipped_6456_2048x2048.jpg?v=1600844126)) -- Uses the same LCD as the Funnyplaying "Retro Pixel" kit (Q5) but with an OSD similar to the "Moon Screen" kit. This kit has user programmable color palettes and you can overwrite the presets with these settings. Each of the four colors (white, light gray, dark gray, black) are fully programmable with RGB values. Testing revealed no noticeable defects or other frame rate issues. Kit also feature programmable vertical and horizontal positions as well to fine tune the kit if the LCD is not aligned perfectly with the lens. For the money, this the best kit for the DMG right now. (see [my install here](https://youtu.be/_qVffKBdELI))
12. [Freckleshack v2.5 "Aioli" 690 TFT kit](https://www.facebook.com/BennVennElectronics/posts/2606963102750460) -- this kit should be pretty similar to the AIO kit above in both performance and install but should be a lot better on power usage and will actually have the proper framerate. It's hard to say anything else until people start getting these kits in hand with DMG ribbons. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs.
# MGB
## Game Boy Pocket
Like the DMG section, I have three different recommendations for "best" kit as each kit seems to have different strengths or weaknesses. Overall cheapest would be an inexpensive LED panel for modifying the OEM LCD (item #1). This is certainly a good option if you like the OEM style screen but is not an option if your LCD is missing or damaged (cracked, screen rot, vertical lines etc). You can go a long way in improving the contrast but the original screens are still pretty low quality and have severe ghosting issues or other display artifacts. Alternatively, a total replacement kit is also an option. My pick for ease of install, performance, and function is definitely the 'One Chip' version of the AIO TFT kit (item #3). This kit is pretty light on features but requires absolutely zero permanent modification to your MGB and is one of the cheapest in the list (of total replacement kits). It requires no shell modding and no permanent adhesive. A step up from this kit is the AIO XL kit (item #8) if you don't mind a little bit of modification. Feature set is mostly the same but you at least get a stock sized LCD. If you're fine with cutting up your shell, the 'One Chip' Q5 OSD IPS kit (item #6) is also a fantastic option. While the install is a bit more involved, the actual display image itself is bigger (slightly larger than OEM) and looks proportionally better on the MGB with the thin bezels and huge LCD. This kit has the most features and is competetively priced with the rest. Performance differences are mostly negligible but battery life is not great. With the new IPS ready aftermarket shells, these larger Q5 IPS kits may soon be a "drop in" experience as far as cutting goes. Expect less than four hours on average with one of these (even less with a flash cart too).
|MGB|Full Size|Custom Lens|Soldering|Cutting|Integer Scaling|Pixel Grid|Color Palettes|Adjustable Brightness|Stuttering or Tearing|
:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|
|1. Traditional backlighting methods|Yes|No|Required|No|1x|Yes|No|No|No|
|2. HiVision 690 TFT kit (AIO)|Much Smaller|Recommended|Recommended|No|2x|No|Button or Touch|Button or Touch|Frame Drops|
|3. One Chip 690 TFT kit (AIO)|Much Smaller|Recommended|Recommended|No|2x|No|Button or Touch|Button or Touch|No|
|4. Funnyplaying Q5 IPS "Retro Pixel" Backlight|Larger|No|Required|Required|4x|Emulation|Touch|Contrast Wheel|No|
|6. One Chip OSD IPS Backlight Kit Q5 Version|Larger|No|Recommended|Required|4x|Emulation|Button or Touch|Button or Touch|No|
|8. HiVision "AIO XL" TFT Kit|Yes|No|Recommended|Yes|2x|No|Button or Touch|Button or Touch|No|
|9. Freckleshack v2.5 "Aioli" 690 TFT kit|Much Smaller|Recommended|Required|No|2x|No|No|Button|No|
1. Traditional backlighting methods ([console](https://cdn.discordapp.com/attachments/706006735252488224/711017849098862692/20200515_175038.jpg) and [kit](https://cdn.discordapp.com/attachments/666796555835015169/713844571284570255/image0.jpg)) -- exactly the same as DMG except that out of the box the contrast is better. You can still bivert for marginal improvements though. Biverting a MGB does not result in as big an improvement as biverting a DMG. (image are my consoles) (see [my install here](https://www.youtube.com/watch?v=EMuF9yr7r1s))
2. HiVision 690 TFT kit (AIO) ([console](https://cdn.discordapp.com/attachments/332487777986019337/646612048460906496/DSC_0175.JPG) and [kit](https://i.imgur.com/OdLacj2.png)) -- Exactly the same as DMG again. There are two different versions and both should work on this console. This is the version that drops frames. Unlike the DMG, you do not need to solder except for one wire to the power switch. New versions of this kit come with a wire preinstalled on the ribbon that you can just wrap around the battery terminal. Soldering is no longer required but still highly recommended. Install is otherwise drop in with no other mods required. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. (see [my install here](https://www.youtube.com/watch?v=6bIAvfHBlpo))
3. One Chip 690 TFT kit (AIO) ([console](https://cdn.discordapp.com/attachments/332487777986019337/646612048460906496/DSC_0175.JPG) and [kit](https://i.imgur.com/xDwyPaM.jpg)) -- Exactly the same as DMG again. There are two different versions and both should work on this console. This is the version that does not drop frames. Unlike the DMG, you do not need to solder except for one wire to the power switch. New versions of this kit come with a wire preinstalled on the ribbon that you can just wrap around the battery terminal. Soldering is no longer required but still highly recommended. Install is otherwise drop in with no other mods required. Presumably, [the custom color palettes that the new kit supports](https://i.imgur.com/lPubcjc.png) will work on this console too. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. (see [my install here](https://www.youtube.com/watch?v=j9FUfmG97KU))
4. [Funnyplaying 'Retro Pixel' Q5 IPS kit](https://www.instagram.com/p/B9mKUbqBT7F/) ([kit](https://i.imgur.com/GUp7rJe.jpg)) -- this is the mostly the same as their DMG IPS kit. I finally got my kit and got it installed. I'm extremely pleased with it so far. Quick tap the touch sensor to cycle through the palettes, medium tap to cycle through the palettes backwards, and long tap to toggle the pixel grid emulation on and off. The contrast wheel controls the brightness. The screen looks absolutely amazing and the trim required to install it is actually pretty easy. I HIGHLY recommend using a bracket or a spacer to line it up though. The included adhesive is permanent so if you mess it up [(like I did),](https://youtu.be/oCpjxyfpCPw) you're stuck with it unless you want to purchase a new LCD [(less than $7 from funnyplaying).](https://funnyplaying.com/collections/product/products/dmg-gbp-after-sales-ips-lcd) You can use a stock sized lens (and that's what it comes with) but the actual display image is slightly larger than stock and might be best with a custom lens that has a slightly larger opening. You'd have to modify the LCD window in the shell for this as well though. Biggest downside is the battery life but that's been an issue with the Pocket even before this kit. This kit does not help though. I've had issues booting an EZ Flash JR, especially with slightly used NiMh rechargeables. A LiPo mod is probably a good idea for a mod like this. Alternatively, this kit should also work the same way in a Game Boy Light and that will help tremendously with the battery life. (see [my install here](https://youtu.be/ZogFkhIbBq8))
5. [Funnyplaying 'Retro Pixel' Q5 IPS kit](https://www.instagram.com/p/B9mKUbqBT7F/) (teaser) -- There appears to be an updated version to this kit again (v1.2? v2? Unknown) [that was teased with their new IPS ready custom MGB shells.](https://funnyplaying.com/blogs/gameboy-advance-news/spring-festival-holiday-notice-2021) Is this the same kit as the previous iteration? Yes and no. It's the same LCD as their previous mod and likely the exact same hardware adapter too. It still uses integer scaling so the game viewable area is identical. The difference, it appears, is that they look to be applying the "white" color palette to the entire LCD display area to emulate the look of an unmasked backlit OEM screen. It is currently unknown if there are any other changes and if/when this kit will be releasing. This kit will likely replace the previous iteration.
6. One Chip IPS Backlight Kit Q5 Version ([kit](https://i.imgur.com/1kklUjy.jpg)) -- This kit is similar in install compared to the funnyplaying kit above and even uses the same LCD. The tradeoff is the hit to battery life (compared to AIO kits) and the more complicated install. The other full size kit from cloud gaming (item #7) offers simimlar size screen image with a smaller overall LCD. This means an easier install as less trimming is required but overall the picture quality is not as good. My testing did not show any quirks or other performance issues such as screen tearing or unexpected frame dropping and showed no pixel overdrive artifacts. The install is actually somewhat forgiving as no positioning bracket is required. As long as you get the LCD in the shell straight and not askew, you can adjust where the image displays on screen to ensure that your lens cutout is lined up perfectly. Soldering is optional but for full functionality (custom palettes, image position, more brightness levels, battery display), highly recommended. The only quirk that I noticed, if you can even call it that, is that the button combo to pull up the OSD and navigating the menu itself still sends inputs to the game. Depending on your game, this could be highly annoying. Also, there are some games, such as Link's Awakening (DX), that will trigger the OSD just from normal use. A workaround would be to disconnect the button controls (or use dip switches) so the OSD is disabled when not in use. The color palettes are a an excellent feature and allow you to emulate different color backlights or even just set your own custom palettes like some previous kits. You have full RGB control over the color value of each shade output by the MGB (total of four different values). Note that this doesn't add more color information to the screen, the MGB will still only ever output four different colors (stock - white, light gray, dark gray, and black). Another reoccuring feature is going to be the [pixel grid emulation.](https://cdn.discordapp.com/attachments/332487777986019337/787840982209003520/12.png) Personally, I prefer it off as it lowers the image quality and contrast but I know that is an appealing feature for a lot of people. This kit is my all time favorite for Game Boy Pocket. (see [my install here](https://youtu.be/Z5tfjz52N5A))
* Install is more complicated than AIO kits as it involves shell trimming. Install is about the same level of difficulty as previous IPS kits.
* PGE photo from AndehX on the Game Boy discord using a GBC
7. [Taobao](https://2.taobao.com/item.htm?id=616270138565) IPS kit ([console](https://img.alicdn.com/bao/uploaded/i3/O1CN01SNIM0v236r2RrmpwM_!!0-fleamarket.jpg_728x728.jpg)) -- ~~Another kit appeared on taobao and it does not appear to be either of the above two IPS kits. I had one on order but they were out of stock. [It looks really good though.](https://img.alicdn.com/bao/uploaded/i3/O1CN01k7NGBZ1bOtOjAg6Zt_!!0-fleamarket.jpg_728x728.jpg) I'm going to try and get one when these are restocked.~~ This is just a really clean traditional backlight install with a custom backlight panel. This is the OEM screen. Leaving this entry for posterity.
8. [HiVision "AIO XL" TFT Kit](https://www.aliexpress.com/item/4001342123663.html) -- On the surface, this kit appears to be the same kit as the previous AIO kits except with a larger screen. Compatibility with other consoles or screens is not current supported but the screen itself appears to be a larger version of the transflective display used in the smaller AIO kits. The screen itself is not transflective, however. While this means visibility in direct sunlight is limited, the screen does have much better black levels. Viewing angles seem much better on this kit compared to other AIO style kits. The kit does support some basic color palette functionality and five levels of brightness, but the range of both are somewhat disapointing. There is also no pixel grid emulation (which I personally don't mind but I feel is worth mentioning) as the LCD only supports 2x integer scaling and not the minimum 3x that is required. I noticed no frame dropping or tearing. This is a really good kit. If the color palette support and brightness control were better (more options, saves values, maybe even on separate controls), it would take the place of the Funnyplaying IPS kit for my recommendation due to the much easier install and very similar image size and quality. (see [my install here](https://youtu.be/DPtJrJpUTOE))
9. [Freckleshack v2.5 "Aioli" 690 TFT kit](https://www.facebook.com/BennVennElectronics/posts/2606963102750460) -- this kit should be pretty similar to the AIO kit above in both performance and install but should be a lot better on power usage and will actually have the proper framerate. It's hard to say anything else until people start getting these kits in hand with MGB ribbons. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. I do not plan on getting one of these.
10. Other kits -- No new kits are being worked on that aren't already listed above but I'm sure that will change soon so I'll leave this item.
# CGB
## Game Boy Color
This is going to be a long section. There are a lot of kits. My pick for ease of install, performance, and function is definitely the 'One Chip' version of the AIO TFT kit (item #8) but if you can solder, the funyplaying 'Retro Pixel 2.0' Laminated Q5 kit (#11) is better in nearly every single way. The former kit is pretty light on features but requires absolutely zero permanent modification to your CGB and is one of the cheapest in the list (of total replacement kits). It requires no shell modding, no permanent adhesive, and no soldering. The latter kit is arguably easier to install as it requires no brackets and technically no custom lens but does require soldering of at least one wire for power (and three more for full features). Cutting an OEM shell is rather difficult for this mod but when combined with funnyplaying's custom CGB housings, no trimming is required and the install is one of the easiest of all the consoles and kits. While power usage is extremely high with this kit, the performance and appearance is second to none. It comes highly recommended. Neither of these kits are stock sized (but both should come with the proper sized lens). If, for whatever reason, you need a stock sized screen or a screen that's otherwise compatible with a stock sized lens, any of the 9380 kits are a good option but among those options, the 'one chip' kit (#12) may be the only one available. Install will be more difficult than ether of the afore mentioned kits due to the trimming requirement but it will perform as expected and look good while doing it.
|CGB|Full Size|Custom Lens|Soldering|Cutting|Integer Scaling|Pixel Grid|Color Palettes|Adjustable Brightness|Stuttering or Tearing|
:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|
|1. Backlighting the OEM LCD|Yes|No|Required|No|1x|Yes|No|No|No|
|2. AGS-101 / El Clono TFT adapter|Much Smaller|Recommended|No|Shell Milling Required|1x|Yes|No|Button|No|
|3. Taobao kit IPS LCD kit ("Galaxy Screen")|Yes|No|Required|Yes|2x|No|No|Button|No|
|4. Freckleshack v1/v2 690 TFT kit|Much Smaller|Recommended|No|Yes|2x|No|No|Button|v1 yes, v2 no|
|5. McWill 690 TFT kit|Much Smaller|Recommended|V1, Yes, V1.1, No|No|2x|No|No|No|Frame Drops|
|6. MidWest Embedded 690 TFT kit|Much Smaller|Recommended|Recommended|Yes|2x|No|No|Button|Screen Jitter|
|7. HiVision 690 TFT kits (AIO)|Much Smaller|Recommended|No|No|2x|No|Yes|Button or Touch|Frame Drops|
|8. One Chip 690 TFT kits (AIO)|Much Smaller|Recommended|No|No|2x|No|Yes|Button or Touch|No|
|9. Funnyplaying 9380 IPS kit v1|Yes|No|No|Yes|2x|No|No|Touch|See notes|
|10. Funnyplaying 'Retro Pixel 1.0' Q5 IPS kit|Larger|Yes|Required|Yes|4x|Yes - x5|No|Touch|No|
|11. Funnyplaying 'Retro Pixel 2.0' Laminated Q5 IPS kit|Larger|Yes|Required|Yes|4x|Yes - x5|No|Touch|No|
|12. One Chip 9380 IPS kit v1|Yes|No|No|Yes|2x|No|Yes|Button or Touch|Frame Drops|
|13. Freckleshack v2.5 "Aioli" 690 TFT kit|Much Smaller|Recommended|No|No|2x|No|No|Button|No|
|14. One Chip OSD IPS Backlight Kit Q5 Version|Much Larger|Required|Recommended|Yes|4x|Yes|Yes|Button or Touch|No|
1. [Backlighting the OEM LCD](https://docs.google.com/document/d/1Ht5q3zw1vCoMdFDzFzgIKOSc5ckwd9W1ylegf8JsnnA/edit) -- I've never tried this but I've never liked the results I've seen in images. It looks like it *can* work nicely but someone just needs to find the right combo.
2. AGS-101 / El Clono TFT adapter ([console](https://i.imgur.com/jYtWSM6.jpg) and [kit](https://cdn.shopify.com/s/files/1/0804/0095/products/IMG20181213111442_ea7f665d-8f3d-47ca-b914-39c85d61f3c4_360x.jpg)) -- all around not a great mod. Don't get me wrong, it was effectively the first backlight kit so of course we all went nuts for it but compared to the other options, it's not a good idea at all to build a new one with all the newer alternatives. The LCD *and* adapter ribbon are both very expensive (though the new PCB adapter has gotten cheaper, the LCD pricing has more than made up for this). The install process is one of the most difficult as it requires precisely milling out the shell to fit the huge LCD. Due to the increased DPI of GBA LCDs, the actual image on the GBC is smaller than stock as well. Finally, battery life plummets with this mod, especially compared to other kits. One of the few pros is that the colors and image quality itself is pretty good. I ended up building a GBC using BennVenn's v2.3 ribbon. I believe that the actual clones of this adapter use an older version of the firmware that is buggy with certain model GBCs but I had zero issues with my legit ribbon. (I assembled mine before I started filming youtube videos)
3. Taobao kit IPS LCD kit ("Galaxy Screen") ([console](https://i.imgur.com/IHxmiNo.jpg) and [kit](https://i.imgur.com/q2HGCQQ.jpg)) -- this kit is pretty similar to the new Funnyplaying IPS kit (below) except that it's been available for a few years already. This kit saw a super limited release on taobao then was hard to get for a while. You can still get one now but the wait list (as of like a year ago) is still over a month. It requires a not insignificant amount of trimming of the shell (pretty much the same as the funnyplaying kit) and a bit of soldering. The actual display image is very nearly stock sized (42mm wide for this kit vs 43mm wide for stock). The high resolution LCD used allows the kit to use integer scaling for the GBC image. This results in a super clean look with no screen door effect (it's there still if you look really close though). The effect of the higher resolution is actually pretty similar to playing an emulator on PC with smoothing off. It's very crisp. The image quality and viewing angles are absolutely fantastic but the colors look a bit over saturated and a bit, erm, *off*. There is no way to calibrate the kit to my knowledge. When the only other kit was the above AGS-101 kit, this one of the best / highest quality kits available. Now, not so much. There are way better kits for much less money. (see [my install here](https://www.youtube.com/watch?v=RSlGifwcrtU))
4. Freckleshack v1/v2 690 TFT kit ([console (left)](https://i.imgur.com/J3V3KKc.jpg?1) and [kit](https://i.imgur.com/7bfd3pC.png)) -- The first in the new wave of transflective LCD kits. The LCD this kit uses is smaller than stock but this allows certain kits to fit without modification to the console. The LCD also is high resolution and allows for the same integer scaling as the above taobao kit. The v1/batch 1 kits in particular had some screen flickering issues that broke Pokemon Pinball but all the remainder of the v1/v2 kits still do have some minor LCD flickering quirks. These kits also all require trimming cart reader pins and cutting of the shell to fit the kit. Overall, this kit is fantastic for the money, but v2.5 should be a nice improvement. Freckleshack kits tend to have the smallest impact on battery life out of all the other GBC kits. They've all since been discontinued in favor of v2.5. No difference between v1 and v2 kits other than brightness control (v1 has no brightness control and aside from the first batch of v1 kits, they both have the minor quirk where the black screen bezels flicker white on screen transitions). The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. However, V1 kits did not have brightness adjust. (see [my install here](https://www.youtube.com/watch?v=YZCmvE9a9WA))
5. McWill 690 TFT kit ([console (right)](https://i.imgur.com/J3V3KKc.jpg?1) and [kit](https://imgur.com/a/vaIT1nB)) -- This kit came out pretty much at the same time as Freckleshack v1. It uses the exact same LCD but the install was very different. I had quite a few issues with the v1 kit but I'm told that most of them are resolved with v1.1. The install for v1.0 is complicated and way more difficult than it needs to be. The kit is drop in, except for the surface mount crystal oscillator that you have to solder on. Also, [the kit didn't even work in the first GBC I installed it in.](https://imgur.com/Ntpx7Nx) I did notice some screen tearing in this kit. I'm told that the v1.1 fixes both my issues with screen tearing and having to solder that surface mount crystal oscillator but I'll have to take someone else's word for that one. Both v1.0 and v1.1 draw so much power that on a cold boot, you have to reboot your GBC two or three times before it will start up properly. I can only recommend this kit if *literally* nothing else is in stock (unlikely) or if you want the VGA output. Oh and because I want one more thing to complain about, the PCB is glued to the LCD and the screen kit is located within the shell via the shape of the PCB. My screen was glued in crooked and there is likely no way to fix it without breaking something. Thanks McWill. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. However, these kits do not have brightness adjust. (see [my install here](https://www.youtube.com/watch?v=Ad90WUKpQf8))
6. MidWest Embedded 690 TFT kit ([console](https://i.imgur.com/K1MJBM8.png) and [kit](https://www.mw-embedded.com/wp-content/uploads/2019/03/IMG_20180605_090352413-1.jpg)) -- ~~I actually don't have one of these~~ This was also part of the first wave of transflective kits and came out pretty much at the same time as the other two. Between Freckleshack (v1 specifically) and McWill (v1.0), this seemed like the best compromise. Of those three, it was the only kit that supported brightness control and seemed to have no display related issues. However, after installing mine, I did notice a constant jittering of the screen. It does not appear to be dropping frames or tearing but it's not quite buttery smooth either. This kit has a pretty serious affect on battery life. Most people claim to get more than what MWE claims, but even those who have measured the power consumption have noted that it's very high. You do have to cut the screen bezel of the plastic shell to fit this thing. It does result in a much better visual appearance with the LCD closer to the lens though. Despite the issues, there was still a lot of thought put into the install and fit and finish of the mod and I'm still really impressed despite the minor visual issue. Honestly, it is a solid kit if not for the high battery consumption. There are still better kits for the cost though. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. Even with brightness adjust, you cannot disable the backlight with these kits, however. (see [my install here](https://www.youtube.com/watch?v=bYxUQ4jN4vw))
7. HiVision 690 TFT kits (AIO) ([console](https://i.imgur.com/KdcF0eb.jpg) and [kits](https://i.imgur.com/tzDRdkE.jpg)) -- This is that same Chinese kit again. It works in pretty much every Game Boy console except the Advance (I should test one in a Light...). There are several different versions of this kit in particular but the differences boil down to whether the kit is "official" or a "pirate" kit. The "official" kits came first and then the one chip manufacturer came along and started making their own with different hardware and different features. The "official" manufacturer calls the one chip kits "pirate" kits. The "official" kits seem to support more consoles (like the NeoGeo Pocket Color) but also tend to drop frames due to the frame-rate mismatch. Game Boy consoles run at 59.7 FPS or thereabout but the HiVision IC that these kits are made with is locked to 60 FPS. To make the two work together, there is a noticeable screen judder with certain games. The "pirate" kit is made with a more flexible, yet unbranded, IC that does not have to drop frames. See [this imgur album](https://imgur.com/a/KF9GLSc) for more info. The issue is not that bad though to be honest and I think either kit is still worth the money. I have both the "official" and "pirate" kits and while I prefer the pirate kit for the smooth frame rate, I think they are both still great options. The absolute best bang/buck GBC kit is the the pirate kit though this one is a close second. It's anywhere from $35-60 but the price depends entirely on the vendor and the accessories it comes with. Install is literally drop in with no soldering or shell trimming required. It is 100% reversible. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. (see one of [my installs here](https://www.youtube.com/watch?v=CUzda_H1Hks))
8. One Chip 690 TFT kits (AIO) ([console](https://i.imgur.com/KdcF0eb.jpg) and [kits](https://i.imgur.com/lPubcjc.png)) -- I made this into a separate section from the above kit because even though there are two different manufacturers, the kits have been extremely similar up until now. It's been very difficult to even know what kit you are getting ahead of time but it looks like the one chip version of this kit has a new feature. This new feature enables custom color palette support in the same way that the One Chip IPS kit supports custom color palettes. This new feature will also help tell the two kits apart since the HiVision kit does not (yet?) support custom color palettes. Assuming everything works as expected, this is the absolute best bang/buck GBC kit. It's anywhere from $35-60 but the price depends entirely on the vendor and the accessories it comes with. Install is literally drop in with no soldering or shell trimming required. It is 100% reversible. The "pirate" kits are made by the same factory that makes the "one chip" branded IPS kits. I do not yet have one of the color palette kits but I do have one on the way. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. (see [more info on the difference between the HiVision and One Chip kits here](https://www.youtube.com/watch?v=68uECuyASgo))
* Apparently the new version of this kit (with the color palettes) has "a pulsing horizontal on the screen during play." They noted that this line makes it look like the screen has "ripples." ~~I still don't have one yet myself so I cannot confirm but it would match up with some other things I've heard about this kit (like it was pulled from sale until it gets an update).~~ Thanks for the confirmation, u/thor-odenson. I actually just got one of these myself and the kits appear to be fixed. I'm still investigating, however. Video will be up soon.
9. Funnyplaying 9380 IPS kit v1 -- **THERE IS NO V2** ([console](https://i.imgur.com/Nj1x8IN.jpg) and [kit](https://cdn.shopify.com/s/files/1/2481/6766/products/GBC_IPS_LCD_1000_2000x.jpg?v=1585708451)) -- I know I said the AIO kit is the best bang/buck kit but this one is too really. Just in a different way. It can be a bit more expensive on average but I think the other kit fills a niche that this one does not. The AIO TFT kit (and I suppose Freckleshack v2.5) could be installed in a limited edition GBC without having to make permanent modifications if later resale is to be a consideration. On the other hand, this kit requires a lot of irreversible trimming. *If* you don't mind doing the trimming, this is the better kit. Viewing angles are much, much better, the frame rate is synced properly, colors look great (and as accurate to the original GBC as they can be on a backlit screen), and the price/availability is much better than this kit's cousin. This is the first backlit kit that is actually OEM sized. The taobao one is a wee bit smaller but both work well with OEM sized lenses. (see [my install here](https://www.youtube.com/watch?v=PySvT126Loo))
10. [Funnyplaying 'Retro Pixel 1.0' Q5 IPS kit](https://cdn.discordapp.com/attachments/744938437693407393/809765110389276672/image0.jpg) -- This kit will replaces the old version and uses a whole new LCD, the Q5 LCD instead of the 9380 LCD. This results in a much larger image on screen for just about the same effort when it comes to trimming the shell. This kit can be identified by the black ribbon cable. Is this the same kit as the previous iteration? Not at all. It's a new LCD as their previous mod but is likely the exact same hardware adapter. It still uses integer scaling so the game viewable area is still nice and sharp but will be slightly larger and will support the pixel grid emulation. [There are five different options for the pixel grid emulation](https://cdn.shopify.com/s/files/1/0266/1862/6122/products/collage_a3834e98-2c7f-4482-892c-1389c50ed132_2048x2048.png) -- a feature unique to this kit -- and some of the options are rather compelling. I would like to see future kits include this functionality. Performance seems to be the best yet of any GBC kit -- no frame dropping or tearing and no weird artifacts to either side of the screen or missing pixel columns. There are some issues though. The install is largely identical to the OC OSD Q5 backlight kit (#13) but with an increased power consumption (over the OC version), more convoluted controls, and no way to adjust the position of the image on-screen. The last point should be negated by the release of Funnyplaying's IPS Ready custom molded GBC shells but for those wanting to stick with different shells, it means manually aligning the LCD within the shell again. Regarding the controls for the kit, there is a required touch sensor and optional button controls. You can toggle every feature of the kit with the touch sensor only but hooking up the button controls does not provide an easier or better experience like usual. The button controls are used in conjunction with the touch sensor. Hopefully this decision is revised in future iterations of this kit. (see [my install here](https://youtu.be/H5-sYNd3Cas)
11. [Funnyplaying 'Retro Pixel 2.0' Laminated Q5 IPS kit](https://imgur.com/a/j193RTt) -- Much like the 1.0 Retro Pixel kit, this kit will replaces the old version (which is still sold until stock depletes) and uses Q5 LCD but is this time laminated directly to the lens, much like the 9380 SP kit. Image quality and size is much the same as the previous Q5 kit except that the clarity significantly improved and the edges of the LCD are much better hidden due to the much closer LCD. Additionally, this kit features a backlit lens logo and the color is programmable. This kit supports the same pixel grid emulation as the previous Q5 version. [There are five different options for the pixel grid emulation](https://cdn.shopify.com/s/files/1/0266/1862/6122/products/collage_a3834e98-2c7f-4482-892c-1389c50ed132_2048x2048.png) -- a feature unique to this kit -- and some of the options are rather compelling. Performance seems to be the best yet of any GBC kit -- no frame dropping or tearing and no weird artifacts to either side of the screen or missing pixel columns, much like the previous iteration of this kit. There are some issues though. The install is pretty unique to this kit due to the laminated LCD but is possibly the easiest kit to install when used alongside funnyplaying's custom GBC housings. Again, same as the previous kit, this kit features an increased power consumption (over the OC version), more convoluted controls, and a small quirk rendering brightness controls nonfunctional if start and select are pressed simultaneously but not long enough to go into the menu. Power cycling or holding the buttons to enter and then exit the menu again is enough to work around this bug, however. Regarding the controls for the kit, the button controls are used in conjunction with the touch sensor. The touch sensor controls brightness and pixel grid emulation settings whereas the button controls (and touch sensor together) control the position of the display on the LCD (a feature previously unique to the OSD kit, #14) and to change the colors of the GBC logo on the lens. (see [my install here](https://youtu.be/o9NvRFPqGLI)
12. One Chip 9380 IPS kit v1 -- **THERE IS NO V2** ([console and kit](https://imgur.com/a/MB7mdrU)) -- Outwardly, this kit appears the same as the funnyplaying kit above because they use the exact same Blackberry Curve 9380 LCD. The difference, however, is in the function and appearance of the adapter that makes the LCD work with the GBC. The install is pretty much identical to the FP kit except that there is one extra touch sensor. This sensor is used to adjust the color palettes that the kit uses. While this function is not very useful on Game Boy Color games, it can be very usefull on original DMG games or palette enhanced DMG games. One such example is Pokemon Yellow (NA) since you cannot use the built in DMG palettes that the Color has. This kit, however, can override any and all color palettes, even on full color games. As is, this kit does have a few small issues though. ~~The kit does have solder points for button based controls instead of touch sensors but per the manufacturer, these controls are actually not yet implemented (tested and confirmed). Additionally, my kit seemed to have quite a few issues with booting flash carts on full brightness on any batteries that weren't fresh alkalines. When I did manage to get the flash cart booted, I would experience regular screen glitching (see the album or the install video for more info).~~ I got a replacement kit and it looks like these issues were due to a defect with my original kit. They finally implemented the button controls as well in a new quiet revision. Unfortunately, there is no meaningful way to visually distinguish between the early, buggy kits and the latest, stable kits unless the retailer you buy from actually pays attention and knows what they have (not common but RGRS is a confirmed seller of the latest revision of kit). See the new new linked install. This kit looks really good ~~but until these issues (button control and frame dropping) get fixed, I can't say I recommend the kit~~ and has my recommendation for a kit if you want to keep the stock LCD size (can't get a custom lens in the style you want). (see [my install here](https://youtu.be/H0zLjHEVGIA))
13. [Freckleshack v2.5 "Aioli" 690 TFT kit](https://www.facebook.com/BennVennElectronics/posts/2606963102750460) -- this kit should be pretty similar to the AIO kit above in both performance and install but should be a lot better on power usage and will actually have the proper framerate. It's hard to say anything else until people start getting these kits in hand with CGB ribbons. I know these have shipped recently but I have not heard of anyone getting theirs yet. The Palm Centro 690 LCD that this kit uses is transflective which means that with the backlight off, the LCD is perfectly viewable in direct sunlight, just like OEM LCDs. I do not plan on getting one of these.
14. One Chip OSD IPS Backlight Kit Q5 Version ([kit](https://i.imgur.com/DIwcH4R.jpg)) -- This is the first kit that uses a LCD that has a larger image size than stock. All kits before this used large LCDs but the image was either stock sized or even smaller. The result includes much thinner bezels and a much clearer and larger image. The tradeoff is the hit to battery life (compared to AIO kits) and the more complicated install\*. My testing did ~~not~~ show a slight intermittent cropping of one pixel column from the right side of the screen or one row on the bottom of the screen but I did not see any other issues such as screen tearing or unexpected frame dropping and due to the lack of pixel overdrive artifacts present in kits that use the BlackBerry Curve 9380 display, this kit actually performs even better than the other IPS kits available right now. Speaking of the 9380 kits, while this kit does require more shell trimming, the install is actually a bit easier as no positioning bracket is required. As long as you get the LCD in the shell straight and not askew, you can adjust where the image displays on screen to ensure that your lens cutout is lined up perfectly. Soldering is optional but for full functionality (custom palettes, image position, more brightness levels, battery display\*), highly recommended. The only quirk that I noticed, if you can even call it that, is that the button combo to pull up the OSD and navigating the menu itself still sends inputs to the game. Depending on your game, this could be highly annoying. Also, there are some games, such as Link's Awakening (DX), that will trigger the OSD just from normal use. A workaround would be to disconnect the button controls (or use dip switches) so the OSD is disabled when not in use. The color palettes are a neat gimmick and it's cool that you can set custom palettes with this kit. Unlike the MGB version of this kit, the color palettes are more like color filters though as you can set how much red, green, or blue appears in the image (0-100% in 16 or 32 steps). Much more interesting is going to be the [pixel grid emulation.](https://cdn.discordapp.com/attachments/332487777986019337/787840982209003520/12.png) Personally, I prefer it off as it lowers the image quality and contrast but I know that is an appealing feature for a lot of people. This kit is my all time favorite for Game Boy Color. (see [my install here](https://youtu.be/6u5ol_wDfp0))
* Install is more complicated than AIO kits as it involves shell trimming. Install is about the same level of difficulty as previous IPS kits.
* PGE photo from AndehX on the Game Boy discord
* Battery indicator not working on my kit and is apparently a known issue with the kit itself.
* Pixel row/column cropping is pretty minimal and not a deal breaker IMO. This issue is also seemingly intermittent so sometimes will not display the symptom.
* The H/V pos menu also seems to skip number steps. This is a visual bug and doesn't affect the placement of the image, it just means that the programmer cannot count (h pos missing number 33, v pos missing number 7, 27, 37)
* Not all kits have the above three issues. There was a software revision very early with the release of the kit and it's impossible to tell which kit you have until you have it installed and test it out.
14. Other kits -- No new kits are being worked on that aren't already listed above but I'm sure that will change soon so I'll leave this item. There are some unconfirmed kits though. BennVenn mentioned that he was working on a "GBC XL" and an OLED kit. I don't know the details of either and I don't know if they will ever make it to market. ~~There is also yet another kit on the way from the "One chip" makers that uses a different LCD than the BB Curve 9380 LCD. Allegedly the end result should be similar but because the new (unknown) LCD is smaller, the trimming and install is easier. I'm also hoping to talk them into using the Blackberry Q5 LCD (Funnyplaying Game Boy Pocket kit) to make a GBC XL kit but, again, that's not confirmed.~~ We got the Q5 kit ;)
# AGB
## Game Boy Advance
There are a few options here that work on both GBA and GBA SP but I'm going to keep these sections separate as there are some different considerations for certain mods I believe. All of the kits have some downsides but between price and performance and availability, I like the Funnyplaying IPS v2 kit (item #8). It does require a bit of shell modification but pre modified shells are available from several vendors now. I don't think the AGS-101 TFT LCD (item #2) really holds up compared to a more modern LCD, especially with the release of FP's "ITA" kit (item #9) but it is still a worthwhile mention. On that note, FP's "ITA" kit (item #9) is actually a really nice option both for visual appearance, power usage, and price. I prefer the look of their older 9380 kit (#8) but with the price, power usage, and as soon as the new shells start rolling out, it will be difficult to make a valid argument against this kit. The Cloud Game Store drop in IPS kit (item #6) is pretty good, especially if you absolutely must not cut up your console, and there are very few downsides that make it difficult to recommend over the Funnyplaying kit. The CGS kit does not require shell modification (or a replacement shell) and the image quality is very good in comparison to the Funnyplaying 9380 kits (but FP is still better). Install will be significantly improved if you don't mind cutting up the shell a little bit (not nearly as much as the funnyplaying cuts) but this is not required.
|AGB|Full Size|Custom Lens|Soldering|Cutting|Integer Scaling|Pixel Grid|Color Palettes|Adjustable Brightness|Stuttering or Tearing|
:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|
|1. Front light|Yes|No|Yes|No|1x|Yes|No|No|No|
|2. AGS-101 TFT mod|Yes|No|Recommended|Yes|1x|Yes|No|Some|No|
|3. Fake AGS-101 IPS LCD|Yes|No|Recommended|Yes|2x|No|No|Some|No|
|4. Taobao IPS kit ("Galaxy Screen")|Slightly Larger|Recommended|Yes|Yes|2x|No|No|Button Control|No|
|5. Taobao IPS kit - "C Screen"|Yes|No|No|No|2x|No|Yes|Button or Touch|No|
|6. "Cloud Game Store" "Drop In" IPS kit|Yes|No|No|Recommended|2x|No|No|Touch|No|
|7. Funnyplaying 9380 IPS kit (v1)|Slightly Larger|Recommended|No|Yes|2x|No|No|Button Control|Major Frame Tearing|
|8. Funnyplaying 9380 IPS kit (v2)|Slightly Larger|Recommended|No|Yes|2x|No|No|Button Control|No|
|9. Funnyplaying 'ITA' (DSi) TFT LCD kit|Yes|No|No|Yes|1x|Yes|No|Button or Touch|No|
|10. "One chip" 9380 IPS v1|Slightly Larger|Recommended|No|Yes|2x|No|No|Button Control|Frame Dropping|
|11. "One chip" 9380 IPS v2|Slightly Larger|Recommended|No|Yes|2x|No|No|Button Control|No|
|12. "One chip" 9380 IPS "2 in 1"|Slightly Larger|Recommended|No|Yes|2x|No|Yes|Button or Touch|No|
|13. "One chip" 9380 IPS "TV Version"|Slightly Larger|Recommended|Recommended|Yes|2x|No|Yes|Button or Touch|No|
|14. "One chip" IPS "TV Version"|Yes|No|Recommended|Recommended|2x|No|Yes|Button or Touch|No|
|15. insideGadgets Micro TFT adapter|Much Smaller|Recommended|No|No|1x|No|No|No|No|
1. Front light -- Of course you can just frontlight your console. I suppose I should have included this in the GBC section but I never frontlit a GBC before. I did do a [NGPC](https://i.imgur.com/P7cK3Rj.jpg) but that's another story for another time. It's technically an option and I am just now realizing that it's one I should include in my wiki. Honestly though? Don't seriously consider it unless you are weird like me and just want one of every mod. There are two different types of frontlight panels. The first are [salvaged from older devices](https://i.imgur.com/9mUS8sQ.jpg) (like say an AGS-001 or Palm Pilot) or there are [new aftermarket panels.](http://i.imgur.com/8qU1AtJ.jpg). My experience should be pretty obvious from those images since both of those consoles are mine. If you really want a frontlight, and you cannot find a legitimate afterburner kit, just swap in a whole AGS-001 LCD. Don't bother trying to salvage the panel only. They are absurdly delicate and nearly impossible to clean (so touching it with bare fingers will ruin it). The new aftermarket kits *can* look good, so I hear, but I've yet to see one that looked as good or better than an old salvaged panel.
2. AGS-101 TFT mod ([console](https://i.imgur.com/QOXNQ1L.jpg) and [adapter](https://ae01.alicdn.com/kf/HTB12q7NSpXXXXXDXVXXq6xXFXXXv/1pcs-for-GBA-Ribbon-Cable-32pin-40-Pin-AGS-101-Backlit-Adapter-Screen-Mod-with-cable.jpg)) -- The defacto backlight most people think of in Game Boy consoles. I have two issues with this method, the first is that people are *still* cutting up AGS-101 consoles for it (despite the modern alternatives), and the second issue, a direct result of the first, is that it has made aftermarket AGS-101 consoles so absurdly expensive. Unfortunately, stock of aftermarket LCDs (honestly, I'm pretty sure they were just NOS OEM) is nearly dried up so prices have skyrocketed for this mod, but *if you already have a LCD* **AND** *if you do not have an AGS-101 console that it should go into*, this is still a good mod for consideration. As the screen itself is pretty much drop in compatible with the AGB electronics, it has by far the best battery life of any backlight AGB kit. In fact, since the LCD itself is largely just a backlit 32 pin LCD, it even makes redundant the extra voltage regulator in 40 pin AGB consoles and may even save battery life. My tests were inconclusive but a larger sample size might have better results. Anyway, this mod is basically the ideal LCD mod for an AGB. It's as authentic as an aftermarket mod can be. If it weren't for the price and that nowadays you effectively have to convert two consoles into one, it would still be a good option. I think I've done like four of them. Oh, and one more strange quirk, you do have to [adjust the potentiometer](https://imgur.com/ttIFmOw) after installing one on an AGB for optimal image quality. Most ribbon cable adapters are passive and just convert the 32/40p (AGB side) connectors over to 34p connector (AGS side) but there are some active adapters that add other features like extra brightness or brightness control. I don't really recommend these as I believe they take away from what makes this mod so great, but you do you if that's your thing. If you *need* to get one, try finding one of the 2018 reproduction batch units. They are much higher quality than the new old stock (or consoles) that the other LCDs come from and are still fully compatible. These units are identified by the "XF2018" stamp on the ribbon cable connector. (I assembled mine before I started filming youtube videos)
3. Fake AGS-101 IPS LCD ([screen](https://imgur.com/a/ernk5dQ)) -- Yeah, you read that right. Weird, huh? Well, it's basically the funnyplaying IPS mod except in the form factor of an AGS-101 LCD. It drops right into an AGS-101 console with no mods necessary and will install into an AGB with the exact same process as the original AGS-101 mod. Despite being more at home in an AGS, I put this in the AGB section because this screen seems to be commonly sold as an AGB kit with a 32 or 40 pin adapter. This has the same image size as the OEM AGS-101 LCD (unlike the IPS mod which is bigger) but it has the same 2x linear scaling as the IPS kit. It seems to be a bit harder to find for sale as it seems to be listed as an AGS-101 LCD, but most sellers will still refer to it as a "new" version or "clone" or "copy" version. It should be a bit cheaper than AGS-101 screens as well. All in all, I think it's better in every way than AGS-101 LCDs EXCEPT that the power usage much more closely resembles the IPS mods rather than the AGS-101 mods. Interestingly, this kit doesn't seem to suffer from any of the visual artifacts or bugs that the other IPS kits have (no tearing or jittering) and even the ghosting is significantly reduced. (see [my video here](https://www.youtube.com/watch?v=HwSNfLqfv-8))
4. Taobao IPS kit - "Galaxy Screen" ([console (bottom)](https://i.imgur.com/hyoQIuy.jpg) and [kit](https://imgur.com/a/vLYgI5x)) -- From the same person that made the taobao kit for GBC, here is the taobao kit for GBA. It looks like the same LCD to me (as the GBC version) and the electronics on board are pretty much the same. Install and functionality is the same again. It does require a not insignificant amount of shell trimming but this was the first kit that introduced linear scaling (on GBA). This kit is pretty straightforward to install despite all the trimming and soldering, but, especially with these funnyplaying IPS kits, I cannot recommend it. The price is high, the waitlist is (was?) long, and the quality is not as good as the funnyplaying IPS kit. It works, but like the GBC version, it is a battery **HAWG** and the colors seem a bit off. Also, it only works on 40 pin AGBs. The plus side is that these kits had no screen tearing or other frame rate issues and they've been on the market for a few years at this point. Nonetheless, I do not recommend it. (see [my install here](https://www.youtube.com/watch?v=oXXyuFz8bzU))
5. Taobao IPS kit - "C Screen" ([console and kit](https://imgur.com/a/EdF2ZyK) images taken from item listing) -- I finally got my kit in and I'm a little disappointed. Yes, it does require absolutely zero modding to the console itself, no soldering or cutting, yes it does not have any frame tearing or dropping, and yes it does have digital brightness control with touch gestures, but the install is a bit too involved to really call it "drop in." It also has, by far, the biggest affect on battery life I've measured on any kit. The white balance on this kit seems to lean on the very cool side. While not a huge deal, I've grown accustomed to the warmer appearance of the other kits so this one feels "off." When side by side, it's very noticeable but when actually playing, it's perfectly fine. This is a good kit, especially if you do not want to cut up your GBA (though there are alternatives now if you are reshelling) but there are better kits. I'd go with the funnyplaying kit still. (see [my install here](https://youtu.be/ieJb4AnIPqE))
6. "Cloud Game Store" "Drop In" IPS kit ([console and kit](https://i.imgur.com/o1n44vy.png) image taken from item listing) -- This kit is all that the C Screen (above) promised to be and more. It uses a slightly different version of the same LCD but the conversion hardware is significantly improved. Unfortunately, there are no more gesture brightness controls (if you like that sort of thing) or on screen brightness indication but the trade off is a SIGNIFICANT improvement to battery life. Like, this kit may just be the most efficient yet (before modding for increased brightness at least). No soldering or cutting is required but for some model GBAs, soldering may be recommended for increased brightness on 40 pin models. Cutting is recommended to get the LCD to sit flat though all that needs to be cut is bumps on the inside that the OEM LCD sit on, much like what is needed for the other LCD kit installs. No walls need to be trimmed. Funnyplaying and similar kits that use the 9380 LCD tend to have warmer colors wheras the LCD used here tends to be on the cold side. It is nowhere near as blue as the C Screen, thankfully. IPS Ready shells may be used but a bracket will be required (or you can just yolo it with adhesive and hope for the best). (see [my install here](https://www.youtube.com/watch?v=wiyKvD5j7ws))
7. Funnyplaying 9380 IPS kit (v1) ([console](https://i.imgur.com/3f8dfkv.jpg) and [kit](https://cdn.shopify.com/s/files/1/2481/6766/products/4_Pixels_in_1_IPS_Full_Viewing_Angle_GAMEBOY_ADVANCE_Replacement_Project_2000x.jpg)) -- The v1 kit was, quite possibly, one of the best things to happen to the GBA mod scene. It obviously wasn't the first aftermarket LCD kit (taobao kits have a few years on these kits) but it was the first one to really hit the US and EU markets and actually make a splash. For those unaware, taobao is not normally available outside China. It's expanded internationally in the last few years but some people in some locales and for some sellers especially still need to work through an agent and the site is still all in Chinese. Now, the v1 kit definitely had it's fair share of problems but when it came out it was about $35 USD. That made it the cheapest AGB backlight mod, ever, and especially in 2019 by a fair margin. So yeah, of course people (myself especially) were excited. It looked so damn good on paper. Now imagine everyone's disappointment when the kit got into their hands and they saw that awful screen tearing effect that resulted from the rotated LCD. It still looked amazing in pictures, but in motion it was not great and it was a deal breaker for many people. Nonetheless, I was still very pleased with my kit, especially since it would lead to a whole new generation of even better kits. This kit is no longer available and has been replaced with the v2 version. I wouldn't recommend one of these unless the price was right. V2 is better in every other way. (see [my install here](https://www.youtube.com/watch?v=R1PhfmW7h6Q))
8. Funnyplaying 9380 IPS kit (v2) ([console](https://i.imgur.com/mDbMjO8.jpg) and [kit](https://cdn.shopify.com/s/files/1/2481/6766/products/GBA_IPS_LCD_V2_4ec0e1e7-610c-41f1-9643-1f89fe8ad183_2000x.jpg)) -- Yeah, I modded a limited edition. Get over it. The v2 kit came along shortly after the v1 kit bombed (and v1 customers could upgrade to a v2 ribbon for less than $10) and that fixed the screen tearing effect in its entirety. For GBA, this kit right here is the best bang/buck kit. That's not to say there aren't any issues, however. When playing emulators via a flash cart (NES especially) or any of the NES classic GBA games, there are some [visual artifacts on the LCD.](https://i.redd.it/vzjxxfkhv1m31.jpg) Additionally, there are quite a few games that will show flashing sprites. This flashing is technically not a bug rather a sneak peak at a shortcut a lot of devs used on the GB and GBA. The LCDs had such poor refresh rates that it was a cheap way (as in, low system resources) to achieve transparency. On an OEM screen, this flashing blurs together with the background and just shows as transparency but the new LCD shows the actual flashing. The shell does require some irreversable trimming for install but the kit does not require any soldering (brightness control is optional). If you use the included adhesive, the install is PERMANENT. Because the DPI on this kit is smaller than OEM AGB screens (after the linear scaling), it does result in a larger display image than stock. It's not that much bigger but it does require a custom screen lens and some extra trimming but losing the little bit of space at the edges is not even noticeable in any games that I play and it does not bother me. All that to say I definitely recommend the v2 kits. For an AGB, this is probably my favorite kit. I don't really recommend the v1 kits though but I don't think those are for sale anymore except maybe in some already assembled consoles (from third parties). No, you cannot put this in a GBC with an ElClono adapter. I checked. There's a version of this kit for GBC now though. (see [my install here](https://www.youtube.com/watch?v=5q2K_Hgq7Qw))
9. Funnyplaying 'ITA' (DSi) TFT LCD kit ([kit](https://i.imgur.com/pG2AvTd.jpg)) - Main claims of this kit is the much lower price (compared to previous IPS kits), better power usage, and a much more pronounced screen door effect, similar to a stock AGS-101 LCD. So far, the pricing seems absolutely great (as of time of writing, kit is less than $30 USD) for the performance that you get. Funnyplaying has released [these pictures so far](https://imgur.com/a/3i7POFn) and while I was skeptical at first, but after installing one myself, I believe Funnyplaying is using (and distributing) cherry picked LCDs. Compared to an original DSi, the LCD that comes with the FP kit *does* appear higher quality with better color saturation and less ghosting. LCDs are not totally free of ghosting but the observed ghosting does appear pretty minimal and much less significant than AGS-101 LCDs. Biggest downside right now is the amount of cutting required to install one of these in an AGB. This is a big LCD and modification is required both for IPS ready and OEM style (OEM and repro both) shells. Overall, this is a very nice kit. (see [my install here](https://youtu.be/ZYzEtZ7WUjE))
10. "One chip" 9380 IPS v1 ([kit](https://imgur.com/bqvD94F)) -- This uses the same LCD as the Funnyplaying version so the outward appearance is identical. Install and performance are actually pretty damn similar. Both kits will show some flickering sprites in some games and both kits even have that odd image retention on NES games (albeit they both display different issues, check out [this direct comparison here](https://www.youtube.com/watch?v=YezHoRNnUf8)). Even the external appearance is the same. My kit seemed to have some frame dropping issues and was a little bit more power hungry than the funnyplaying version. Unlike the funnyplaying version, this kit will store the last used brightness level and restore that next time you boot it up. If you have a choice, I think the funnyplaying version is the better buy for now but this kit is not a bad option either. (see [my install here](https://www.youtube.com/watch?v=9wGO7S7qhoc))
11. "One chip" 9380 IPS v2 ([kit](https://imgur.com/bqvD94F)) -- ~~In typical "one chip" fashion, they quietly released a revision without actually marking it as such. This is a software revision only so visually the kit is indistinguishable from v1. Allegedly this release fixes the stuttering that I noticed on the v1 kit and improves some of the flickering artifacts in some games. I do not have one of these kits to verify. Everything else should be identical to v1.~~ I'm actually not so sure anymore because the new "2 in 1" kit is also marked as v2. I think the "v2" designation on the kits that look like v1 is purely for marketing reasons. There should actually be a software revision for this kit that fixes the stuttering and frame dropping and I have stumbled across one but this kit was marked the same as the stuttering ones and is otherwise visually identical. It should be assumed that any "one chip" ribbon cable kit that is marked as "v2" could be the initial version that I reviewed above.
12. "One chip" 9380 IPS "2 in 1" ([kit](https://i.imgur.com/sicNDDE.jpg)) -- The "2 in 1" versions of this kit may be shipping with [a new brand of LCD which is considered lower quality than the original.](https://youtu.be/-1Gcq7mMjPw) Some vendors have old-stock LG, some have new-stock LG, some have Toppoly. The old LG LCD is still 100% compatible but these come with Toppoly LCDs instead. Install and performance are actually pretty damn similar to the v1 version and the funnyplaying version. Both kits will show some flickering sprites in some games and both kits even have that odd image retention on NES games. However, it looks like the frame dropping issue has been resolved on this version and [a new color palette/filter feature](https://imgur.com/a/wYgLPUt) has been introduced. This kit comes with both wired control support and touch sensor control support for solderless installs. Unlike the funnyplaying version, this kit will store the last used brightness level and color filter and restore that next time you boot it up. If you have a choice, I think the funnyplaying version is the better buy for now but this kit is not a bad option either. (see [my install here](https://youtu.be/GmUZrIjrxHQ))
13. "One chip" 9380 IPS "TV Version" ([kit](https://i.imgur.com/NzPubSY.jpg)) -- This kit performs largely identically to "2 in 1" version above when not outputting to a TV. Brightness and color palette settings are retained between power cycles but the internal LCD is always enabled after a restart (did not test with GBA sleep mode). Palettes are supported in TV out mode (as is GB/C games) but brightness only affects the internal LCD and is thus irrelevant when TV Out is enabled. When wired up properly and holding L+R+Select for a few seconds, the kit will switch off the internal LCD and enable the TV Out encoder on the adapter PCB. When you use the included custom TV out cable and hook up to a supported composite receiver, the kit outputs a relatively solid analog video signal. The included cable also plugs into the headphone jack to carry the audio signal to via RCA jacks. Quality seems pretty good but my experience is hampered by my lack of analog compatible TVs and an extremely low quality USB capture card. Output format is 4:3 which distorts the original 3:2 signal, though this can be fixed with some post processing via an external analog to digital converter (like an OSSC or framemeister) or via post-processing with a capture card (though the input delay with the latter could make playing difficult). Overall, this is a very solid kit. While soldering is not technically required to use the backlight kit, it is required to use the TV out functionality. Aside from an additional couple wires, install is largely identical to the '2in1' kit and other 9380 based kits before it. (see [my install here](https://www.youtube.com/watch?v=lcxGh4GVFEw)
14. "One chip" "Drop in" IPS "TV Version" ([kit](https://i.imgur.com/nm4lvZT.png)) -- This kit performs identically to "TV Version" version above except uses a different internal LCD. Brightness and color palette settings are retained between power cycles but the internal LCD is always enabled after a restart (did not test with GBA sleep mode). Palettes are supported in TV out mode (as is GB/C games) but brightness only affects the internal LCD and is thus irrelevant when TV Out is enabled. When wired up properly and holding L+R+Select for a few seconds, the kit will switch off the internal LCD and enable the TV Out encoder on the adapter PCB. When you use the included custom TV out cable and hook up to a supported composite receiver, the kit outputs a relatively solid analog video signal. The included cable also plugs into the headphone jack to carry the audio signal to via RCA jacks. Quality seems pretty good but my experience is hampered by my lack of analog compatible TVs and an extremely low quality USB capture card. Output format is 4:3 which distorts the original 3:2 signal, though this can be fixed with some post processing via an external analog to digital converter (like an OSSC or framemeister) or via post-processing with a capture card (though the input delay with the latter could make playing difficult). Overall, this is a very solid kit. While soldering is not technically required to use the backlight kit, it is required to use the TV out functionality. This kit uses a lower quality LCD (similar to the "Cloud Game Store" kit mentioned above in #6). This results in an easier install with an OEM shell and is claimed to be "Drop in" but with the soldering required to actually use the full functionality of the kit, this seems to be a change made for the wrong reasons. (see [my install here](https://youtu.be/xiQeVBDte6w)
15. insideGadgets Micro TFT adapter ([console](https://shop.insidegadgets.com/wp-content/uploads/2020/02/IMG_6392.jpg) and [kit](https://shop.insidegadgets.com/wp-content/uploads/2020/02/IMG_6425-2.jpg)) -- Yeah, that's pretty much exactly what it looks like. 100% reversable and when all is said and done, probably the cheapest backlight kit right now. It does require using a Game Boy Micro LCD, but those are still available on the aftermarket and for reasonably cheap. This kit would go well with a custom screen lens to hide the massive gaps with bezels. The install is rather difficult due to the extreme thickness of the stacked components. It requires bending ribbon cables to a degree that makes most people (well, me at least) uncomfortable. The brightness is very low to start but it can be modded to be brighter. When installed in an AGS-001, the system power consumption actually went down which means using this LCD in place of the frontlit screen (with the light on) will result in better battery life. This is the only kit on the list that you can say that with. (see [my install here](https://youtu.be/0Sy1KXxUtWM))
16. Other kits -- so BennVenn announced that he was making two kits for AGB and neither have come out yet. I'll have to wait to have an opinion on either until they are out but one is an adapter for NDSL LCDs to install in an AGB. If all goes as planned, it would be similar to the AIO kits in GBC but without the linear scaling. It should fit without irreversible mods and the image will be smaller but it will still likely be an improvement over stock. Another kit was his version of the funnyplaying **v1** kit. I don't know how likely the NDSL kit is after the funnyplaying kit came out or if BV's other kit is still in development ever since the funnyplaying v2 kit came out, but it's just always worth consideration that something else is always on the horizon. Because BennVenn knows what he's doing with this hardware, both kits would work with all models of Game Boy Advance (32 pin, 40 pin, and both AGS-001 and AGS-101 models) unlike the taobao kit that only works on 40 pin models. The one chip kits are also getting a new revision. I'm not sure what features are planned (if any) but the difference will be that the main electronics for the adapter will be on a rigid PCB instead of a flex PCB. See the one chip GBC IPS kit for an example of that.
# AGS
## Game Boy Advance SP
I could leave this section empty because the GBA SP already comes in both frontlit and backlit variants. Nonetheless, there are still some mods that I know about or have done so I can still talk about them. Though, I guess I do have a lot to say about SP consoles. I like the Funnyplaying SP IPS kits (item #4) or even just (clean) stock AGS-001s. Yeah, that's right. I like the frontlit ones. I think the AGS-101 consoles are highly over-rated. All of the kits have some downsides but between price and performance and availability, I like the Funnyplaying IPS kit.
|AGS|Full Size|Custom Lens|Soldering|Cutting|Integer Scaling|Pixel Grid|Color Palettes|Adjustable Brightness|Stuttering or Tearing|
:--|:--|:--|:--|:--|:--|:--|:--|:--|:--|
|1. AGB 32P Screen|Yes|No|No|No|1x|Yes|No|No light to adjust|No|
|2. AGS-101 TFT mod|Yes|No|Required|No|1x|Yes|No|Some|No|
|2. Fake AGS-101 IPS LCD|Yes|No|Required|No|2x|No|No|Some|No|
|3. Funnyplaying 9380 IPS kit (AGB v1)|Slightly Larger|Recommended|Recommended|Yes|2x|No|No|Button Control|Major Frame Tearing|
|4. Funnyplaying 9380 IPS kit (AGS v1)|Slightly Larger|Recommended|Recommended|Yes|2x|No|No|Button Control|No|
|5. "One chip" 9380 IPS v1|Slightly Larger|Recommended|Recommended|Yes|2x|No|No|Button Control|Frame Dropping|
|6. "One chip" 9380 IPS v2|Slightly Larger|Recommended|Recommended|Yes|2x|No|No|Button Control|No|
|7. "One chip" 9380 IPS "2 in 1"|Slightly Larger|Recommended|No|Yes|2x|No|Yes|Button or Touch|No|
|8. CGS IPS Kit|Yes*|Recommended|No|Yes|2x|No|No|Button Control|No|
|9. insideGadgets Micro TFT adapter|Much Smaller|Recommended|No|No|1x|No|No|No|No|
1. Unpimp your SP ([adapter](https://i.imgur.com/PWauMf2.jpg)) -- I still don't really know why someone made this adapter. I've managed to repurpose it for another mod that I'll get to in a sec but this adapter came WELL before that other mod did. You can use it to install a non-lit 32 pin AG**B** LCD in your AGS. It works on both AGS (AGS-001) and AGT (AGS-101) motherboards. I guess you can use it to make a functional console out of that AGS-101 you shamefully cannibalized for your AGB? Nonetheless, it's there and, well, it *does* work.
2. AGS-101 mod for AGS-001 -- Ok, I actually don't have one of these. I have regular AGS-101s though. My main complaint about those consoles is the brightness levels and this mod fixes that. If you use a brightness controller (and a voltage regulator), you can actually get much better control over brightness levels in this mod over a stock AGS-101. Otherwise, all other things are the same between a modded AGS-001 and an AGS-101. Mostly. I hear that AGS-001 consoles modded with AGS-101 screens have less ghosting but I think that has more to due with the actual LCD in the unit (the "2018" LCDs seem to perform much better than the OEM or other repro LCDs) than the mod. Seems like it could be a good option if you like AGS consoles but can't get an AGS-101 normally (like for those outside the US and select areas of EU).
3. Funnyplaying v1 GBA 9380 IPS kit ([console](https://i.imgur.com/xh2tkM3.jpg), [kit](https://cdn.shopify.com/s/files/1/2481/6766/products/4_Pixels_in_1_IPS_Full_Viewing_Angle_GAMEBOY_ADVANCE_Replacement_Project_2000x.jpg), and [adapter](https://i.imgur.com/2ayQTau.png)) -- I did this mod before both the SP variant of the funnyplaying GBA mod and the funnyplaying gba v2 mod came out. Why? Because I can. I like GBA SP consoles. And I had a GBA SP console with a really bad screen. It had mold damage. Anyway, yeah, you can just use a v2 kit or even get the SP kit in particular. My mod ended up using a lens from a v2 kit because the v1 lenses were offset. Because I used a v1 ribbon, my kit has all the problems of the v1 kits but there is no reason you cannot use a v2 ribbon. All you need is the strange adapter I mentioned earlier for putting an AGB screen in an AGS. It works on this nicely. One advantage of using the AGB ribbon with adapter over the AGS ribbon is that you get more brightness levels and more control over brightness as you can increase or decrease instead of just being able to cycle levels. As of the SP version of this kit, you can buy a replacement LCD with the SP lens pre-laminated so you don't have to bother trying to fit a custom lens. This is going to be more expensive than just installing the SP version though. (see [my install here](https://www.youtube.com/watch?v=YftGqoLI_kM))
4. Funnyplaying GBA SP 9380 kit v1 -- **THERE IS NO V2** ([console](https://i.ytimg.com/vi/amRFG-DqP2w/hqdefault.jpg) and [kit](https://cdn.shopify.com/s/files/1/2481/6766/products/GBASPIPSLCDKITnologo_2000x.jpg)) -- Yeah, I modded a limited edition GBA SP too. It won't be my last. This kit is basically the funnyplaying v2 GBA kit but for SP instead. This means it has the same downsides too (image retention on NES games and transparent sprite flickering). The screen comes with a custom lens already laminated to the LCD (and it really does look amazing) and already pre-cut so that it self locates within the shell. The trimming for this install is significantly easier than the AGB install. I'd recommend it over shoving the AGB kit in and, honestly, I just recommend this kit in general. It looks really good, it's easy enough to install, and it's pretty easy to get. This is probably my favorite option for AGS consoles. I think this is a much better buy than an AGS-101 especially since the kit works on both AGS and AGT motherboards. (see [my install here](https://www.youtube.com/watch?v=amRFG-DqP2w))
5. "One chip" 9380 IPS mod (v1) ([kit](https://i.imgur.com/pjZ0xAY.jpg)) -- they made one of these for the GBA SP too. Like the GBA version, the SP version is very similar to the funnyplaying equivalent. It uses the same LCD and does come with the lens already applied, same as the funnyplaying version EXCEPT that the lens IS NOT fully laminated like the funnyplaying version. This does not make a huge difference but if you install the foam behind the LCD that the kit comes with (which you are not supposed to do despite the foam being cut for install there), you will end up with a [newtonian ring issue in the middle of the LCD.](https://cdn.discordapp.com/attachments/666796555835015169/682041175779442689/WP_20200225_18_45_50_Rich_LI.jpg) Performance is pretty similar to the AGB version. My kit did not have a frame dropping issue but it did seem to have the same jittering issue that the MidwestEmbedded GBC kit had. Like the AGB version, this is not a bad kit if you have one, but if you have a choice, I'd go with the funnyplaying version instead. (see [my install here](https://www.youtube.com/watch?v=fR3bml4oqTo))
6. "One chip" 9380 IPS v2 ([kit](https://i.imgur.com/pjZ0xAY.jpg)) -- ~~In typical "one chip" fashion, they quietly released a revision without actually marking it as such. This is a software revision only so visually the kit is indistinguishable from v1. Allegedly this release fixes the stuttering that I noticed on the v1 kit and improves some of the flickering artifacts in some games. I do not have one of these kits to verify. Everything else should be identical to v1.~~ I'm actually not so sure anymore because the new "2 in 1" kit is also marked as v2. I think the "v2" designation on the kits that look like v1 is purely for marketing reasons. There may actually be a software revision for this kit that fixes the stuttering and frame dropping but I've been unable to acquire one for verification. It should be assumed that any "one chip" ribbon cable kit that is marked as "v2" should be assumed to be the initial version that I reviewed above.
7. "One chip" 9380 IPS "2 in 1" ([kit](https://i.imgur.com/f3fUyf5.jpg)) -- This is the exact same kit as the AGB "2 in 1" version (hence the name) but with an AGS ribbon cable (34 pin) and a laminated LCD. The "2 in 1" versions of this kit are actually shipping with [a new brand of LCD which is considered lower quality than the original.](https://youtu.be/-1Gcq7mMjPw) The old LG LCD is still 100% compatible but these come with Toppoly LCDs instead. Install and performance are actually pretty damn similar to the v2 version and the funnyplaying version. Both kits will show some flickering sprites in some games and both kits even have that odd image retention on NES games. However, it looks like the frame dropping issue has been resolved on this version (from v1) and [a new color palette/filter feature](https://imgur.com/a/wYgLPUt) has been introduced. This kit comes with both wired control support and touch sensor control support for solderless installs. Unlike the funnyplaying version, this kit will store the last used brightness level and color filter and restore that next time you boot it up. If you have a choice, I think the funnyplaying version is the better buy for now but this kit is not a bad option either. (see [my install here](https://youtu.be/4gL-f7mTw5I))
8. "Cloud Game Store" IPS kit ([kit](https://imgur.com/a/AqVR55t)) -- This is basically the same kit for GBA but with a GBA SP specific ribbon. Function is just about identical. It's a pretty good kit but unfortunately it is not as "drop in" as the early samples implied. No soldering is required to use the kit but will be required for brightness controls. Like the AGB version, the kit does not have any additional color palettes (and does not need them) nor does it retain brightness settings between power cycles. Unlike the AGB kit though, cutting is required to get the LCD installed if using the laminated version or recommended if using the non-laminated version (else the screen will be off-center. Funnyplaying and similar kits that use the 9380 LCD tend to have warmer colors wheras the LCD used here tends to be on the cold side. It is nowhere near as blue as the C Screen, thankfully. IPS Ready shells may be used if you do not want to trim. Non-laminated installs require a lens (not provided). The viewable area of the LCD is ever so slightly larger than the OEM lens cutout so a pixel column may be cut off on either the left or right edge, depending on how well you center the screen. No custom lenses are available specific to this kit but laminated display units are and those come with custom lenses already adhered to the LCD. Lastly, the touch sensor has been removed from kits made after the first batch so hardware controls are required if you want to adjust brightness (not really necessary IMO, it's not that bright and it only gets darker). Overall, not a bad kit but I still like the funnyplaying version better (#4). (see [my non-laminated install here](https://youtu.be/DQT_303eAa0))
9. insideGadgets Micro TFT adapter ([console](https://shop.insidegadgets.com/wp-content/uploads/2020/02/IMG_6392.jpg) and [kit](https://shop.insidegadgets.com/wp-content/uploads/2020/02/IMG_6425-2.jpg)) -- Yeah, that's pretty much exactly what it looks like. 100% reversable and when all is said and done, probably the cheapest backlight kit right now. It does require using a Game Boy Micro LCD, but those are still available on the aftermarket and for reasonably cheap. This kit would go well with a custom screen lens to hide the massive gaps with bezels. The install is rather difficult due to the extreme thickness of the stacked components. It requires bending ribbon cables to a degree that makes most people (well, me at least) uncomfortable. The brightness is very low to start but it can be modded to be brighter. When installed in an AGS-001, the system power consumption actually went down which means using this LCD in place of the frontlit screen (with the light on) will result in better battery life. This is the only kit on the list that you can say that with. For installing, you probably want [this bracket/bezel](https://www.thingiverse.com/thing:4581497) and one of these [ribbon cables.](https://www.aliexpress.com/item/32531674174.html)(see [my install here](https://youtu.be/0Sy1KXxUtWM))
Sorry about the pillar of text but don't act like you have anything better to do than talk about Game Boy mods ;)
tl;dr I spend too much money on mod kits. Each section has a summary for a better tl;dr
edit 2020-02-04: added notes on DMG "one chip" IPS kit
edit 2020-02-10: added notes on GBC MWE kit
edit 2020-03-15: added notes on "one chip" IPS kits, fake AGS-101 kit, and left space for the funnyplaying MGB/DMG IPS kit
edit 2020-05-27: added notes on the new GBP kits and the new OC GBC IPS kit. I also overhauled all the images to add an image of the console as an end result example and an image of the kit for identification purposes. Created new page in the wiki for the content since I hit the character limit.
edit 2020-05-28: split up the AIO TFT kit sections for each manufacturer to add a mention of the new one chip color palette versions of the kits. Added mention of the image retention on the funnyplaying AGB and AGS kits. Added mention of the TFT transflective outdoor viewing.
edit 2020-05-30: added the names for the taobao kits. Do keep in mind that something may be lost in translation so the names could be inaccurate or difficult to search by.
edit 2020-06-12: added my thoughts on the DMG Moon Screen and added new section for the funnyplaying DMG kit (because as it turns out, they are not the same kit)
edit 2020-06-14: added disclaimer on OC GBC AIO kit from thor-odenson
edit 2020-06-20: added my thoughts on the FP MGB IPS kit
edit 2020-07-06: added version numbers for kits that keep getting mislabeled
edit 2020-07-15: added my thoughts on the FP DMG IPS kit and revised all TL;DR sections (some more than others)
edit 2020-07-20: corrected color palette AIO GBC kit end blurb (pending full revision soon)
edit 2020-07-29: added notes on OC IPS V2 kits for AGB and AGS, added notes on iG AGB Micro kit, revised DMG backlight kit notes, and updated OC IPS GBC v1 notes
edit 2020-08-05: moved existing one chip v2 kits to v3 section and added entries for the actual v2 kits
edit 2020-08-07: revised the OC IPS v2 section again because it appears that this is just a marketing stunt and not an actual hardware revision
edit 2020-08-18: added notes on new one chip q5 IPS kits for DMG and MGB. Also added new AIO XL kit for MGB. Since compatibility is only assumed and not yet confirmed, kit has only been added to MGB section.
edit 2020-09-02: Added tables for each section and copied the Micro TFT from the AGB section to AGS since that's where I ultimately installed it.
edit 2020-10-02: added foreword about LCDs and modded section on OCB AGB "v2" with my updated findings
edit 2020-12-15: added CGB Q5 OSD kit notes
edit 2020-12-29: added MGB Q5 OSD kit notes
edit 2021-01-29: added placeholders for two new kits, updated FP MGB IPS kit and Cloud Game Store AGB kit. Also added Q5/9380/690 LCD info to foreward
edit 2021-02-13: added placeholder for FP GBC Retro Pixel kit and added my notes in for CGS AGB kit
edit 2021-02-28: added FP CGB Retro Pixel Q5 notes
edit 2021-05-04: added CGS AGS notes and placeholder for new FP GBA screen and placeholder for OC TV Out kit
edit 2021-05-11: filled in notes for OC TV Out kit and updated opening section
edit 2021-06-17: added new entry for new OC TV out kit, updated FP GBA "ITA" screen kit section, added 690/9380/Q5 designators for kits that were missing them (basically all but some Q5 kits)
edit 2021-06-29: added new entry for FP RP 2.0 kit and updated GBC kit recs section
edit 2021-07-15: added foreword on LCD lamination
|
Python
|
UTF-8
| 678
| 3.734375
| 4
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# 1.Write a function so that the columns of the output matrix are powers of the input
# vector.
# The order of the powers is determined by the increasing boolean argument. Specifically,
# when increasing is False, the i-th output column is the input vector raised element-wise
# to the power of N - i - 1.
# In[1]:
import numpy as np
# In[2]:
x = np.array([1, 2, 3, 5])
# In[3]:
N = 3
# In[4]:
np.vander(x, N)
# In[5]:
np.vander(x, increasing=False)
# In[6]:
np.vander(x, increasing=True)
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
|
Java
|
UTF-8
| 1,094
| 2.265625
| 2
|
[] |
no_license
|
/**
*
*/
package ru.prbb.middleoffice.domain;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author RBr
*
*/
@Entity
public class SwapItem implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
private String swap;
private String related_security;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the swap
*/
public String getSwap() {
return swap;
}
/**
* @param swap
* the swap to set
*/
public void setSwap(String swap) {
this.swap = swap;
}
/**
* @return the related_security
*/
public String getRelated_security() {
return related_security;
}
/**
* @param related_security
* the related_security to set
*/
public void setRelated_security(String related_security) {
this.related_security = related_security;
}
}
|
Java
|
UTF-8
| 637
| 2.84375
| 3
|
[] |
no_license
|
package aic.group5.topic3;
public class AnalyzeResult {
private final Object result;
private boolean error = false;
public AnalyzeResult( Object result ) {
this.result = result;
}
public static AnalyzeResult stillAnalyzing( ) {
return new AnalyzeResult( "analyzing" );
}
public static AnalyzeResult done( double result ) {
return new AnalyzeResult( Math.round( result * 100.0 ) / 100.0 );
}
public static AnalyzeResult error( ) {
AnalyzeResult rs = new AnalyzeResult( null );
rs.error = true;
return rs;
}
public boolean hasError( ) {
return error;
}
public Object getResult( ) {
return result;
}
}
|
C++
|
GB18030
| 1,327
| 3.71875
| 4
|
[] |
no_license
|
#include "String.h"
int main(void)
{
//dz
String s1("AAA");
s1.Display();
String s2 = s1; //Լûʵһ캯 ϵͳṩĬϵĿ캯
// ϵͳṩĬϿ캯ʵʩdzȼs2.str_ = s1.str_
//ԱԱֵ
//s2еstr_ָs1еstr_ָָͬһڴ棬ڹs2ʱûзԼڴ棬
//ָͬһڴ
//2ڽʱҪͬһڴ汻ͷ2Σʱ
//취ϵͳṩĬϵĿ캯Լʵһ캯
//ֵ
String s3;
s3.Display();
s3 = s2; // õȺ
// ϵͳṩĬϵȺʵʩdzȼs3.str_ = s2.str_;ԱԱֵҲһ2Σ
//ṩԼĵȺ
// s3.operator=(s2);
//ֹ
// ҪöǶһģҪֹ
// ǽ캯=Ϊ˽УҲṩǵʵ
return 0;
}
|
C++
|
UTF-8
| 1,259
| 3.78125
| 4
|
[] |
no_license
|
/*
Escriba un programa para calcular cuántas cajas cuadradas pueden contenerse en una sola capa en un estante rectangular, sin voladizo.
Las dimensiones del estante en pies y la dimensión de un lado de la caja en pulgadas se leen desde el teclado.
Use variables de tipo double para la longitud y profundidad del estante y
escriba int para la longitud del lado de un recuadro.
Defina e inicialice una constante entera para convertir de pies a pulgadas.
Calcule el número de cajas que puede contener el estante en una sola capa y escriba el resultado.
*/
#include <iostream>
using namespace std;
int main(){
// 1 pie = 12 pulgadas
const int pulgadas_por_pies = 12;
double longitud;
double profundidad;
double tamanio;
cout << "Ingrese la longitud del estanque, en pies: ";
cin >> longitud;
cout << "Ingrese la profundidad del estanque, en pies: ";
cin >> profundidad;
cout << "Ingrese el tamanio de la caja en pulgadas ";
cin >> tamanio;
long cajas = static_cast<long>((longitud*pulgadas_por_pies)/tamanio)*
static_cast<long>((profundidad*pulgadas_por_pies)/tamanio);
cout << "El numero de cajas que puede contener es: " << cajas << endl;
cin.get();
return 0;
}
|
Java
|
UTF-8
| 16,276
| 3.046875
| 3
|
[] |
no_license
|
//
// Theo Laanstra 2018, 300153944
//
package game;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
//A class for loading game data from a file into the program.
public class GameLoader {
// I threw some Thread.sleep() statements in here to make it look a little
// cooler when the different status messages pop up one by one. Changing
// this
// int adjusts the interval to whatever is desired in milliseconds.
static final int interval = 150;
// I found it was easier to load all the lines of the save file into an
// array
// list and then manipulate them how I wanted.
// This is the array list I load the ENTIRE save file into.
private ArrayList<String> lines = new ArrayList<>();
// An array list of the loaded locations.
private ArrayList<Location> locations;
// A Player object to hold the loaded player.
private Player player;
// An ArrayList of the location IDs of the player's previously visited
// locations.
private ArrayList<String> locationHistory;
// The process the begins loads everything up into the "lines" ArrayList.
boolean beginLoad(String fileName) {
lines = new ArrayList<String>();
// Creates a file object with the defined filename
File file = new File(fileName);
// Reserves space for a loader object.
Scanner loader;
// Try's initializing the loader with the file. If it's successful, it
// loads
// every line of text in the file and strips away
// any preceding or trailing whitespace, ie. the formatting of the XML
// file.
try {
loader = new Scanner(file);
while (loader.hasNext()) {
lines.add(loader.nextLine().trim());
}
loader.close();
file = null;
// for (String temp : lines) System.out.println(temp);
// If the loading is unsuccessful, an error message is displayed and
// the game
// returns to the main menu.
} catch (Exception e) {
System.out.println("\nFile \"" + fileName + "\" Not Found");
return false;
}
// Even if the file is loaded successfully, that doesn't mean it's the
// file type
// that holds correct game data.
// If it is the correct file type, it will have the <!DOCTYPE GWML>
// doctype
// declaration.
// This checks for that.
if (lines.isEmpty()) {
System.out.println("File " + fileName + " is empty");
return false;
}
if (lines.get(0).equals("<!DOCTYPE GWML>")) {
System.out.println("File OK!");
lines.remove(0);
lines.remove(0);
lines.remove(lines.size() - 1);
// Beginning Save Processing
// System.out.println("Starting Save Processing...");
processGameData();
// If it is the correct file type, then the doctype declaration and
// some
// unnecessary structural tags are removed.
// Finally the processing of the game data is initiated.
} else if (!lines.get(0).equals("<!DOCTYPE GWML>")) {
System.out.println("\nInvalid File: Improper DOCTYPE declaration");
return false;
} else {
System.out.println("\nSomething went wrong :-(");
return false;
}
return true;
}
// This does the actual data crunching to extract the various locations and
// items stored in the file, as well as the player character.
private void processGameData() {
// System.out.println("Save Processing Started...");
// ArrayLists of lines of data to be passed to more specific processing
// methods.
ArrayList<String> LText = new ArrayList<String>();
ArrayList<String> playerText = new ArrayList<String>();
locationHistory = new ArrayList<String>();
// Marks the separation point between locations and the player as
// determined by
// the end of the locations section.
int delineator = 0;
// Adds all locations to the location text array list
for (int i = 1; !lines.get(i).equals("</locations>"); i++) {
delineator = i;
LText.add(lines.get(i));
}
try {
Thread.sleep(interval);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Location data gathered...");
// Adds all player data to the player text array list
for (int i = delineator + 3; !lines.get(i).equals("</player>"); i++) {
delineator = i;
playerText.add(lines.get(i));
}
try {
Thread.sleep(interval);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Player data gathered...");
// Gets the location IDs within the <history> tag and saves them to
// locationHistory.
for (int i = delineator + 1; i < lines.size(); i++) {
if (lines.get(i).equals("<history>")) {
while (!lines.get(++i).equals("</history>"))
locationHistory.add(lines.get(i));
}
}
try {
Thread.sleep(interval);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Location History data gathered...");
// Since I'm done with it, this can go in the trash.
lines = null;
// Sends off the lines of location data to be processed into Location
// objects,
// then assigns them to the ArrayList of Locations. Finally it indicates
// when
// the process is done.
locations = processLocations(LText);
try {
Thread.sleep(interval);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Locations processed...");
LText = null;
// Sends off the player to be processed into a Player object, and
// indicates when
// the process is done.
// System.out.println("Starting Player Processing...");
player = processPlayer(playerText);
try {
Thread.sleep(interval);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Player processed...");
playerText = null;
try {
Thread.sleep(interval);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Location History processed...");
}
private ArrayList<Location> processLocations(ArrayList<String> input) {
// System.out.println("Starting Location Processing...");
// Creates an ArrayList of Locations to return to the GameController,
// as well as an ArrayList to hold the text data for each location to be
// passed
// to processLocation();
ArrayList<Location> finalLocations = new ArrayList<Location>();
ArrayList<String> locationText = new ArrayList<String>();
// This marks where each location ends (and implies where the next
// begins) for
// purposes of splitting up the block of location data and passing
// single
// locations to processLocation()
int delin = 0;
// Here iterate through the block of location data in text form and pass
// off
// single locations to be processed.
for (int i = delin; i < input.size(); i++) {
delin = i;
if (input.get(i) != null && input.get(i).equals("</location>")) {
// System.out.println("Found end of a location in file");
// When the end of a location is found, it gets processed into a
// Location object
// here
finalLocations.add(processLocation(locationText));
locationText.clear();
// System.out.println("Location Processed...");
continue;
}
// System.out.println("Processing..." + input.get(i));
locationText.add(input.get(i));
}
// The final ArrayList of Locations
locationText = null;
return finalLocations;
}
// Here is where a block of location data is processed into a Location
// object.
private Location processLocation(ArrayList<String> input) {
// System.out.println("Processing a single location...");
// Sets some default values so the Location can still be created if
// there is a
// minor error.
String name = "Default Name", description = "Default Description", id = "Default ID";
ArrayList<String> connections = new ArrayList<String>();
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<Trigger> triggers = new ArrayList<Trigger>();
// Chews through the structure tags and extracts the name, then chews
// through
// the trailing structure tags to get to the description.
input.remove(0);
input.remove(0);
name = input.get(0);
// System.out.println("Location name processed...");
input.remove(0);
input.remove(0);
input.remove(0);
// Gets the description and removes each line as it is added to the
// description
// string.
while (!input.get(0).equals("</description>")) {
if (description.equals("Default Description"))
description = "";
description += " " + input.get(0) + "\n";
input.remove(0);
}
// System.out.println("Location description processed...");
// Strips away some more structure tags and extracts the location ID,
// then
// strips
// away some more structure tags.
input.remove(0);
input.remove(0);
id = input.get(0);
// System.out.println("Location ID processed...");
input.remove(0);
input.remove(0);
// Now I'm left with the Items in a location, and the other locations it
// can
// connect to.
// Since the connections are after the items in the file, and are easier
// to
// read, I'll work backwards and add them directly to the connections
// ArrayList
// here, leaving nothing but the Items in the "input" ArrayList to be
// passed to
// processItems().
int delin = 0;
// Finds the beginning of the connects element of a location
for (int i = 0; i < input.size(); i++) {
delin = i;
if (input.get(i).equals("<connects>"))
break;
}
// If <connects> was found, add them to the connections ArrayList
if (delin != input.size() - 1) {
input.remove(delin);
while (!input.get(delin).equals("</connects>")) {
connections.add(input.get(delin));
input.remove(delin);
}
input.remove(delin);
}
// The remaining input is just the items of a location and its triggers, so now
// it can be passed off for processing.
items = processItems(input);
input.remove(0);
input.remove(input.size() - 1);
// Gets the triggers of a location
while (!input.isEmpty()) {
input.remove(0);
while (!input.get(0).equals("</trigger>")) {
String mustHave = input.get(0);
input.remove(0);
String item = input.get(0);
input.remove(0);
String actionText = "";
// For getting multiple lines of Action Text
while (!input.get(0).equals("</trigger>")) {
actionText += "\n" + input.get(0);
input.remove(0);
}
// Sets the mustHave boolean according to what was enterd in that field in the
// file.
boolean mustHaveBool = (mustHave.equals("MUST_HAVE")) ? true : false;
// Initializes a new trigger item, and adds it to the triggers ArrayList
Trigger temp = new Trigger(item, actionText, mustHaveBool);
triggers.add(temp);
}
input.remove(0);
}
// Location processing is complete, so now we can create a new location with all
// the loaded fields, and return it.
return new Location(name, description, id, connections, items, triggers);
}
// Here is where a block of player data is processed into a Player object.
private Player processPlayer(ArrayList<String> input) {
// Some temporary variables for creating the Player object.
Location tempLocation;
String tempLocID = "livingRoom";
Inventory tempInventory = new Inventory();
input.remove(0);
// loads the location id of the player's current location as saved in the file.
tempLocID = input.get(0);
tempLocation = this.getLocationById(tempLocID);
input.remove(0);
input.remove(0);
// Adds all the items in the players saved inventory to the temporary inventory.
tempInventory.batchAdd(processItems(input));
// Returns a new Player object
return new Player(tempLocation, tempInventory);
}
// Processes an entire <items> element into an ArrayList of Items
private ArrayList<Item> processItems(ArrayList<String> input) {
// The final ArrayList of loaded Items
ArrayList<Item> finalItems = new ArrayList<>();
// The loaded text of a single item to be processed.
ArrayList<String> itemText = new ArrayList<>();
input.remove(0);
// Gets an <item> element and sends it for processing until there are none left.
while (!input.isEmpty() && !input.get(0).equals("</items>")) {
itemText.add(input.get(0));
if (input.get(0).equals("</item>")) {
// System.out.println("Found end of an Item...");
finalItems.add(processItem(itemText));
itemText.clear();
}
input.remove(0);
}
input.remove(0);
// Returns the final ArrayList of Items
return finalItems;
}
// Returns a single item generated from an ArrayList of text
private Item processItem(ArrayList<String> input) {
// Sets some default values so an item can be returned even if there is an error
// of sorts.
String name = "Default Name", description = "Default Description", useText = "Default Usage Text";
int mass = 1, type = 0, value = 1000;
// Removes some structure tags and then gets the name of the item.
input.remove(0);
input.remove(input.size() - 1);
input.remove(0);
name = input.get(0);
input.remove(0);
input.remove(0);
input.remove(0);
if (description != null || !description.trim().equals("")) {
// Makes sure that description is empty so that each newly loaded line can be
// appended to it.
description = "";
}
// Gets the entire description text
while (!input.get(0).equals("</description>")) {
description += " " + input.get(0);
input.remove(0);
}
input.remove(0);
input.remove(0);
// Same process as for the description
if (useText != null || !useText.trim().equals("")) {
useText = "";
}
while (!input.get(0).equals("</use>")) {
useText += input.get(0) + "\n\t";
input.remove(0);
}
// Removes the \n\t from the last line so formatting in the program isn't weird.
useText = useText.substring(0, useText.length() - 2);
// Removes structure tags and gets Mass, Type, and Value, in that order.
input.remove(0);
input.remove(0);
mass = Integer.parseInt(input.get(0));
input.remove(0);
input.remove(0);
input.remove(0);
type = Integer.parseInt(input.get(0));
input.remove(0);
input.remove(0);
input.remove(0);
value = Integer.parseInt(input.get(0));
// Empties and un-sets the input for memory's sake.
input.clear();
input = null;
// Returns a newly processed Item!
return new Item(name, description, useText, mass, type, value);
}
// For returning the loaded locations back to the GameController.
ArrayList<Location> loadedLocations() {
if (locations == null)
locations = new ArrayList<Location>();
return locations;
}
// Returns the ID strings to the GameController where it can use the
// getLocationById() method to get the actual previous locations.
ArrayList<String> loadedLocationHistory() {
if (locationHistory.isEmpty()) {
locationHistory = null;
return new ArrayList<String>();
}
return locationHistory;
}
// For returning the loaded player back to the GameController.
Player loadedPlayer() {
return player;
}
// Just a utility function for my own use within this class. Returns an item
// with a matching Item ID.
private Location getLocationById(String locationID) {
if (locations == null || locations.isEmpty()) {
System.out.println("\nNo locations to search through...");
return null;
}
for (int i = 0; i < locations.size(); i++) {
if (locations.get(i) == null)
continue;
if (locations.get(i).getLocationId().equals(locationID))
return locations.get(i);
}
System.out.println("Location ID doesn't match any known location.");
return null;
}
}
|
Swift
|
UTF-8
| 2,280
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// JGAdvertCell.swift
// JG_XMLY
//
// Created by 郭军 on 2019/4/23.
// Copyright © 2019 guojun. All rights reserved.
//
import UIKit
class JGAdvertCell: JGBaseCollectionCell {
// 图片
private var imageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
// 标题
private var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
// 子标题
private var subLabel : UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = UIColor.gray
return label
}()
override func configUI() {
self.addSubview(self.imageView)
self.imageView.image = UIImage(named: "fj.jpg")
self.imageView.contentMode = .scaleAspectFill
self.imageView.clipsToBounds = true
self.imageView.snp.makeConstraints { (make) in
make.left.top.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-15)
make.bottom.equalToSuperview().offset(-60)
}
self.addSubview(self.titleLabel)
self.titleLabel.text = "那些事"
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-15)
make.top.equalTo(self.imageView.snp.bottom)
make.height.equalTo(30)
}
self.addSubview(self.subLabel)
self.subLabel.text = "开年会发年终奖呀领导开年会发年终奖呀"
self.subLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-15)
make.top.equalTo(self.titleLabel.snp.bottom)
make.height.equalTo(30)
make.bottom.equalToSuperview()
}
}
var adModel:JGRecommnedAdvertModel? {
didSet {
guard let model = adModel else {return}
self.titleLabel.text = model.name
self.subLabel.text = model.description
// self.imageView.image = UIImage(named: "fj.jpg")
}
}
}
|
Python
|
UTF-8
| 469
| 3.078125
| 3
|
[] |
no_license
|
class Solution:
def maxPathSum(self, root):
self.max_sum = float('-inf')
self.dfs(root)
return self.max_sum
def dfs(self, node):
if not node: return 0
left_sum = max(self.dfs(node.left), 0)
right_sum = max(self.dfs(node.right), 0)
cur_sum = left_sum + right_sum + node.val
self.max_sum = max(self.max_sum, cur_sum)
return max(left_sum, right_sum) + node.val
|
Java
|
UTF-8
| 26,110
| 2.25
| 2
|
[] |
no_license
|
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore.Entry;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import javax.sql.ConnectionPoolDataSource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
//import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
//import com.google.common.collect.HashBasedTable;
//import com.google.common.collect.Table;
//
import com.jolly.center.dubbo.enums.DynamicMenuEnum;
import redis.clients.jedis.Jedis;
import annotation.HelloAnnotation;
import entity.Student;
@HelloAnnotation(say = "do it")
public class HelloWorld {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static String getKey(String pattern, Object... arguments) {
return MessageFormat.format(pattern, arguments);
}
public static void main(String[] args) throws ParseException, IOException {
ObjectMapper oMapper = new ObjectMapper();
System.out.println(9 & (8 - 1));// 按位与
Integer sInteger = 100000;
int in = 100000;
System.out.println(in);
System.out.println(sInteger);
System.out.println(sInteger.toString());
System.out.println(String.valueOf(in));
System.out.println(Double.MAX_VALUE);
System.out.println("=============================================");
String teamId = "1111";
String key = getKey("TEAM_QUEUE", teamId);
System.out.println(key);
long n = 200;
float f = 1.39e-43f;
System.out.println(f);
double max = java.lang.Double.MAX_VALUE;
System.out.println("Max double = " + max);
double min = java.lang.Double.MIN_VALUE;
System.out.println("Min double = " + min);
float maxf = java.lang.Float.MAX_VALUE;
System.out.println("Max float = " + maxf);
float minf = java.lang.Float.MIN_VALUE;
System.out.println("Min float = " + minf);
System.out.println(Math.pow(n, 3));
System.out.println("90 度的正弦值:" + Math.sin(Math.PI / 2));
System.out.println("0度的余弦值:" + Math.cos(0));
System.out.println("60度的正切值:" + Math.tan(Math.PI / 3));
System.out.println("1的反正切值: " + Math.atan(1));
System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI / 2));
System.out.println(Math.PI);
System.out.println(Math.E);
System.out.println(Math.floor(3.1542));
System.out.println(0x10);
// 8进制输出
Integer integer = 20;
System.out.println(Integer.toOctalString(integer));
System.out.println("=============================================");
// 注解
HelloAnnotation annotation = HelloWorld.class.getAnnotation(HelloAnnotation.class);
System.out.println(annotation.say());
System.out.println("=============================================");
String str = "douhao,";
int indx = str.lastIndexOf(",");
String str1 = null;
String str2 = null;
if (indx != -1) {
str1 = str.substring(0, indx);
str2 = str.substring(indx + 1, str.length());
}
System.out.println(str1);
System.out.println(str2);
System.out.println("=============================================");
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(6);
list1.add(7);
System.out.println(list1.toString());
for (Integer i : list1) {
// System.out.println(i.byteValue());
System.out.println(i + "");
}
System.out.println(Collections.max(list1));
// // int page = 2;
// // int count = 5;
// // int start = (page-1)*count;
// // List<Integer> list1=new ArrayList<Integer>();
// // for (int i = start; i < start+count && i < list.size(); i++) {
// // list1.add(list.get(i));
// // }
// // System.out.println(list1);
System.out.println("=============================================");
// Map的打印
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 8);
map.put("name", "jay");
System.out.println(map.size());
// ObjectMapper oMapper = new ObjectMapper();
// System.out.println(oMapper.writeValueAsString(map));
// System.out.println(map.toString());
// System.out.println(map.hashCode());
//map的遍历
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iter.next();
String k = entry.getKey();
Object v = entry.getValue();
System.out.println(k+":"+v);
}
System.out.println("=============================================");
//// //String的比较
//// String s1 = "hello";
//// String s2 = new String("hello");
//// String s3 = "hello";
//// String s4 = s2.intern();
//// int h1=s1.hashCode();
//// int h2=s2.hashCode();
//// int h3=s3.hashCode();
//// int h4=s4.hashCode();
//// if (s1.intern() == s2.intern()) {
//// System.out.println("hello");
//// } else {
//// System.out.println("world");
//// }
//// System.out.println("=============================================");
// //常量池-128,127
//// Integer i1=10;
//// Integer i2=10;
//// System.out.println(i1==i2);
//// Long i3=-129l;
//// Long i4=-129l;
//// System.out.println(i3==i4);
//// System.out.println("=============================================");
// // Integer id=(Integer) map.get("id");
// // System.out.println(id);
// //时间戳
// // Timestamp d = new Timestamp(System.currentTimeMillis());
// // Timestamp loginTime1=new Timestamp(75, 01, 01, 00, 00, 0, 0);
// // Long loginTime=loginTime1.getTime();
// // System.out.println(loginTime1);
// // System.out.println(loginTime);
// // System.out.println(d);
//// System.out.println("=============================================");
// //子字符串
// // String test = "This is test for string";
// // System.out.println(test.indexOf("This")); //0
// // System.out.println(test.indexOf("s")); //2
// // System.out.println(test.indexOf("test")); //8
// // System.out.println(test.indexOf("for")); //13
// // System.out.println(test.indexOf("for string "));//-1
// //
// // if (test.indexOf("this")!=-1){
// // //"只要test.indexOf('this')返回的值不是-1说明test字符串中包含字符串'this',相反如果包含返回的值必定是-1"
// // System.out.println("存在包含关系,因为返回的值不等于-1");
// //
// // }else{
// //
// // System.out.println("不存在包含关系,因为返回的值等于-1");
// // }
// // System.out.println("=============================================");
//
// Date date = new Date(0);
// System.out.println(date);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd
//// HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
// System.out.println(simpleDateFormat.format(date));
// System.out.println(sdf.format(date));
// Timestamp time = Timestamp.valueOf("2010-10-07 14:30:30");
// Long long1 = time.getTime();
// System.out.println(time);
// System.out.println(long1);
// System.out.println("=============================================");
// // String string="abctygf";
// // String string2="Ct";
// // System.out.println(string.contains(string2));
//
Jedis jedis=new Jedis("localhost");
// // System.out.println("连接成功");
// // //Redis Java String(字符串) 实例
// // jedis.set("runoobkey", "www.runoob.com");
// // System.out.println("redis 存储的字符串为: "+ jedis.get("runoobkey"));
// // //Redis Java List(列表) 实例
// // jedis.rpush("list", "Hello");
// // jedis.rpush("list", "world");
// // jedis.rpush("list", "!");
// // List<String> lStrings=jedis.lrange("list", 0, 2);
// // System.out.println(lStrings);
// // //Redis Java Keys 实例
// //// Set<String> keys=jedis.keys("*");
// //// Iterator<String> iterator=keys.iterator();
// //// while (iterator.hasNext()) {
// //// String key = (String) iterator.next();
// //// System.out.println(key);
// //// }
// // //Redis Java set 实例
// // jedis.hset("myhash", "jay", "hjc");
// // System.out.println(jedis.hget("myhash", "jay"));
// //// System.out.println("服务器正在运行"+jedis.ping());
// // jedis.zadd("myzet", 10, "a");
// // System.out.println(jedis.zrange("myzet", 0, -1));
// // jedis.close();
//// System.out.println("=============================================");
//
//
// // User user = new User();
// // user.setName("小民");
// // user.setEmail("xiaomin@sina.com");
// // user.setAge(20);
// //
// // SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
// // user.setBirthday(dateformat.parse("1996-10-01"));
// //
// // /**
// // * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
// // * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
// // * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
// // * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
// // * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
// // * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
// // */
// // ObjectMapper mapper = new ObjectMapper();
// //
// // //User类转JSON
// //
//// //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
// // String json = mapper.writeValueAsString(user);
// // System.out.println(json);
// //
// // String json1 =
// //
//// "{\"name\":\"小明\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";
// //
// // /**
// // * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
// // */
// //// ObjectMapper mapper = new ObjectMapper();
// // User user1 = mapper.readValue(json1, User.class);
// // System.out.println(user1.toString());
//// int h = 0x10000000;
//// System.out.println((Integer.toBinaryString(h)));
//// for(int i = 0; i < 28; i++) {
//// h >>>= 1;
//// System.out.println((Integer.toBinaryString(h)));
//// }
//// int h = -1;
//// System.out.println(Integer.toBinaryString(h));
//// h <<= 10;
//// System.out.println(Integer.toBinaryString(h));
//// for(int i = 0; i < 32; i++) {
//// h >>>= 1;
//// System.out.println(Integer.toBinaryString(h));
//// }
//// System.out.println(Integer.toBinaryString('b'));
//// System.out.println(Integer.parseInt("11", 16));
//// System.out.println(Math.cos(3.1415926));
//// List<Integer> Id = new ArrayList<Integer>();
//// Id.add(3);
//// Id.add(7);
//// Id.add(2);
//// Id.add(8);
//// map.put("childrenId", Id);
//// List<Integer> childrenId = (List<Integer>) map.get("childrenId");
//// StringBuffer stringBuffer = new StringBuffer();
//// for (Integer integer2 : childrenId) {
//// stringBuffer.append(integer2.toString()+",");
//// }
//// stringBuffer.deleteCharAt(stringBuffer.length()-1);
//// System.out.println(stringBuffer.toString());
//// String filename = System.currentTimeMillis() + ".xlsx";
//// System.out.println(filename);
// char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
//// 'n', 'o', 'p', 'q', 'r', 's', 't',
// 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
//// '9'};
// int length = ch.length;
// Random r = new Random();
// String hjc = new String(new char[] {ch[r.nextInt(length)],
// ch[r.nextInt(length)],
// ch[r.nextInt(length)],
// ch[r.nextInt(length)],
// ch[r.nextInt(length)],
// ch[r.nextInt(length)]});
// System.out.println(hjc);
// System.out.println(System.currentTimeMillis());
//// Timestamp d = new Timestamp(System.currentTimeMillis());
//// Long loginTime = d.getTime();
//// System.out.println(loginTime);
//// String string = "{1}";
//// System.out.println(string.length() > 2 ? 1 : 0);
// Map<Integer, String> map1 = new HashMap<>();
// for (int i = 0; i < 10; i++) {
// // putIfAbsent使得我们不用写是否为null值的检测语句;
// map1.putIfAbsent(i, "val_" + i);
// }
//
// // -------1------maps不支持流。然而现在maps包括了许多新的非常有用的方法用于执行通用任务:
// // forEach使用consumer来对map中的每个元素进行操作,执行通用任务。
// Set<Integer> set = map1.keySet();
// for (Integer integer : set) {
// System.out.println(map1.get(integer));
// }
// long ms = 30 * 1000;// 毫秒数
// SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//
// 初始化Formatter的转换格式。
// formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
// String hms = formatter.format(ms);
// // String hString= formatter.forma
// System.out.println(hms);
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd
// HH-mm-ss");
// long time3 = System.currentTimeMillis() + 5000 * 1000;
// Date date2 = new Date(time3);
// date2.setTime(time3);
// System.out.println(simpleDateFormat.format(date2));
//
// System.out.println(converLongTimeToStr(ms));
//
// NumberFormat percentFormat = NumberFormat.getPercentInstance();
// percentFormat.setMaximumFractionDigits(2); // 最大小数位数
// // percentFormat.setMaximumIntegerDigits(2);//最大整数位
// // percentFormat.setMinimumFractionDigits(2); //最小小数位数
// // percentFormat.setMinimumIntegerDigits(1);//最小整数位数
// String string111 = percentFormat.format(1.2455d);// 自动转换成百分比显示..
// System.out.println(string111);
// List<String> header = new ArrayList<>();
// // String[] headers = new String[] {};
// String[] headers = new String[] { "Agent", "Total Login Time", "AVG Respond
// Time", "Total Chat Time",
// "AVG Chat Time", "Chats", "Evaluated", "Evaluated Rate", "Very Satisfied",
// "Very Satisfied Rate",
// "Satisfied", "Satisfied Rate", "General", "General Rate", "Dissatisfied",
// "Dissatisfied Rate",
// "Very Dissatisfied", "Very Dissatisfied Rate" };
// header.addAll(Arrays.asList(headers));
// System.out.println(header);
// List<String> header = new ArrayList<>();
//// List<String> headers = new ArrayList<>();
// Set<String> headers = new HashSet<>();
// for (String string : headers) {
// if ("".equals(string)) {
// System.out.println("head");
// }
// }
// headers.add("Agent");
// headers.add("Evaluated");
// headers.add("General");
// headers.forEach(System.out::println);
// Map<String, Object> param =new HashMap<>();
// param.put("field", headers);
// ObjectMapper objectMapper = new ObjectMapper();
// header =
// objectMapper.readValue(objectMapper.writeValueAsString(param.get("field")),
// new TypeReference<List<String>>() {
// });
// Comparator<String> comparator = (h1, h2) -> h1.compareTo(h2);
// header.sort(comparator.reversed());
// System.out.println(header);
// 反向迭代
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<>();
map1.put("score", 32l);
map1.put("name", "vfghd");
Map<String, Object> map2 = new HashMap<>();
map2.put("score", 53l);
map2.put("name", "gtgds");
Map<String, Object> map3 = new HashMap<>();
map3.put("score", 34l);
map3.put("name", "tgrsd");
list.add(map1);
list.add(map2);
list.add(map3);
int j = list.size() - 1;
while (j >= 0) {
System.out.println(list.get(j));
j--;
}
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}
ListIterator<Map<String, Object>> iListIterator = list.listIterator(list.size());
while (iListIterator.hasPrevious()) {
Map<String, Object> map4 = iListIterator.previous();
System.out.println(map4);
}
// 排序
// Comparator<Map<String, Object>> comparator = new Comparator<Map<String,
// Object>>() {
// @Override
// public int compare(Map<String, Object> o1, Map<String, Object> o2) {
//// return (int) (Long.valueOf(o1.get("score").toString()) -
// Long.valueOf(o2.get("score").toString()));
// return
// Long.valueOf(o1.get("score").toString()).compareTo(Long.valueOf(o2.get("score").toString()));
// }
// };
// getComparator("score");
Collections.sort(list, getComparator("score").reversed());// 倒序
System.out.println(list);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("fd");
if (stringBuilder.length() > 0)
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
System.out.println(stringBuilder);
// Collections.reverse(list);
// Iterator<Map<String, Object>> iterator = list.iterator();
//// Comparator cmp = Collections.reverseOrder();
//// Comparator<Map<String, Object>> comparator2 = (h1,h2) -> ((Long)
// h1.get("score")).compareTo((Long) h1.get("score"));
//// Collections.sort(list,comparator2);
////// list.sort(comparator2.reversed());
// System.out.println(list);
// param.put("9", "h");
// param.merge("9", "ello", (value,newValue)->((String) value).concat((String)
// newValue));
// System.out.println(param);
// Map<Integer, String> map = new HashMap<>();
// map.put(1, "h");
// map.put(2, "e");
// map.put(3, "l");
// map.put(4, "l");
// map.put(5, "o");
//// map.getOrDefault(44, "world");
// map.compute(3, (num, val) -> val + num*10);
//// map.forEach((key,value) -> value.concat("a"));
// map.forEach((key,value) -> System.err.println(key +" : "+value));
// Long waitedTime = (long) ((Double.valueOf("100.3"))*1000);
// int count = 5;
// long g = waitedTime / count;
// System.out.println(g);
// System.out.println(waitedTime);
// List<String> list = new ArrayList<>();
// list.add("abc");
// list.add("hello");
// list.add("world");
// list.add("test");
// Iterator<String> iterator2 = list.iterator();
// ListIterator<String> iterator1 = list.listIterator();
// ListIterator<String> iterator = list.listIterator(list.size());
// while(iterator.hasPrevious()){
// System.out.println(iterator.previous());
// }
System.out.println(md5("lhp"));
// //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
// ServerSocket serverSocket = new ServerSocket(12345);
// InetAddress address = InetAddress.getLocalHost();
// String ip = address.getHostAddress();
// Socket socket = null;
// //2.调用accept()等待客户端连接
// System.out.println("~~~服务端已就绪,等待客户端接入~,服务端ip地址: " + ip);
// socket = serverSocket.accept();
// //3.连接后获取输入流,读取客户端信息
// InputStream is=null;
// InputStreamReader isr=null;
// BufferedReader br=null;
// OutputStream os=null;
// PrintWriter pw=null;
// is = socket.getInputStream(); //获取输入流
// isr = new InputStreamReader(is,"UTF-8");
// br = new BufferedReader(isr);
// String info = null;
// while((info=br.readLine())!=null){//循环读取客户端的信息
// System.out.println("客户端发送过来的信息" + info);
// }
// socket.shutdownInput();//关闭输入流
// socket.close();
test1(-3);
System.out.println("=============================================");
List<Integer> integers = new ArrayList<>();
integers.add(3);
for (Integer integer2 : integers) {
System.out.println(integer2);
}
Iterator<Integer> iterator = integers.iterator();
while (iterator.hasNext()) {
Integer integer2 = (Integer) iterator.next();
if (integer2 > 2) {
iterator.remove();
}
}
System.out.println("list:"+integers);
System.out.println("=============================================");
System.out.println(md5("123456"));
int team = 21112222;
System.out.println(team);
// Table<Integer, Integer, Map<String, Object>> table = HashBasedTable.create();//双键Map
// table.put(1, 1, map);
// table.put(1, 2, map1);
// System.out.println(table.get(1, 2));
List<String> hello = new ArrayList<>();
hello.removeAll(hello);
System.out.println("=============================================");
Student student1 = new Student(1, "jay1", "qwe");
Student student2 = new Student(2, "jay2", "qwe");
Student student3 = new Student(3, "jay3", "qwe");
Student student4 = new Student(4, "jay4", "qwe");
Student student5 = new Student(2, "jay2", "qwe");
List<Student> allStudent = new ArrayList<>();
allStudent.add(student1);
allStudent.add(student2);
allStudent.add(student3);
allStudent.add(student4);
List<Student> boyStudent = new ArrayList<>();
boyStudent.add(student4);
boyStudent.add(student3);
boyStudent.add(student5);
// System.out.println(allStudent.removeAll(boyStudent)+" "+allStudent.size());
System.out.println("=============================================");
map.put("student", allStudent);
map.put("list", list);
map.put("list1", list1);
List<Student> students = json2List(object2Json(map.get("student")), Student.class);
List<Map> list2 = json2List(object2Json(map.get("list")), Map.class);
List<Map<String, Object>> list3 = json2MapList(object2Json(map.get("list")));
List<String> list4 = json2List(object2Json(map.get("list1")), String.class);
System.out.println(list3);
System.out.println(list2);
System.out.println(students);
List<Set<Integer>> origin = new ArrayList<>();
addSet(origin, 1, 2);
addSet(origin, 3, 4);
addSet(origin, 5, 6);
addSet(origin, 2, 5);
addSet(origin, 7, 8);
addSet(origin, 1, 4);
List<Set<Integer>> result = new ArrayList<>();
addSet(result, 1, 2);
for (Set<Integer> o : origin) {
Set<Integer> c = new HashSet<>(o);
compare(c, result);
}
System.out.println(result);
System.out.println("=============================================");
String string = "{\"gf\":\"hjk\"}";
Map<String, Object> map4 = json2Map(string);
System.out.println(map4);
}
private static void compare(Set<Integer> c ,List<Set<Integer>> result) {
boolean bool = false;
boolean b = false;
int a = 0;
int index = 0;
for (int i = 0; i < result.size(); i++) {
Set<Integer> r = result.get(i);
if (isIntersected(c,r)) {
c.removeAll(r);
r.addAll(c);
c = r;
a++;
if (a == 1) {
index = i;
} else {
b = true;
}
bool = true;
}
}
if (!bool) {
result.add(c);
}
if (b) {
result.remove(index);
}
}
private static boolean isIntersected (Set<Integer> o, Set<Integer> r) {
Set<Integer> set = new HashSet<>(o);
set.retainAll(r);
return !set.isEmpty();
}
private static void addSet (List<Set<Integer>> origin, int a, int b) {
Set<Integer> set = new HashSet<>();
set.add(a);
set.add(b);
origin.add(set);
}
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字 // 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code += "0";
}
return md5code;
}
public static String converLongTimeToStr(long time) {
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
long hour = (time) / hh;
long minute = (time - hour * hh) / mi;
long second = (time - hour * hh - minute * mi) / ss;
String strHour = hour < 10 ? "0" + hour : "" + hour;
String strMinute = minute < 10 ? "0" + minute : "" + minute;
String strSecond = second < 10 ? "0" + second : "" + second;
if (hour > 0) {
return strHour + ":" + strMinute + ":" + strSecond;
} else {
return "00:" + strMinute + ":" + strSecond;
}
}
public static Comparator<Map<String, Object>> getComparator(String property) {
Comparator<Map<String, Object>> comparator = new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
return Long.valueOf(o1.get(property).toString()).compareTo(Long.valueOf(o2.get(property).toString()));
}
};
return comparator;
}
private static void test1(int a){
assert a > 0 : "something goes wrong here, a cannot be less than 0";
System.out.println(a);
}
public static String object2Json(Object o) throws JsonProcessingException {
return OBJECT_MAPPER.writeValueAsString(o);
}
public static <T>List<T> json2List(String json, Class<T> clazz) throws IOException {
JavaType type = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, clazz);
return OBJECT_MAPPER.readValue(json, type);
}
public static Map<String, Object> json2Map(String json) throws IOException {
return OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, Object>>(){});
}
public static List<Map<String, Object>> json2MapList(String json) throws IOException {
return OBJECT_MAPPER.readValue(json, new TypeReference<List<Map<String, Object>>>() {
});
}
}
|
JavaScript
|
UTF-8
| 2,982
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
/**
*@module PageTransitionDriver
*@memberof EventDrivers
*/
/**
* event initialization options.
*@typedef {Object} PageTransitionEventInit
*@private
*@property {boolean} [bubbles=true] - boolean value indicating if event bubbles
*@property {boolean} [cancelable=false] - boolean value indicating if event is
* cancelable
*@property {boolean} [persisted=false] - boolean property
*/
import {createDOMEvent, onInstall, host} from '../../Globals.js';
import Driver from './Driver.js';
import PageTransitionEventPollyfill from '../Pollyfills/PageTransitionEventPollyfill.js';
/**
* Page transition event driver class
*@memberof EventDrivers.PageTransitionDriver#
*@see {@link https://html.spec.whatwg.org/multipage/browsing-the-web.html#pagetransitionevent| W3.org}
*/
export default class PageTransitionDriver extends Driver {
/**
* event types in the Page transition event interface
*@memberof EventDrivers.PageTransitionDriver
*@type {Array}
*/
static get events() {
return ['pageshow', 'pagehide'];
}
/**
* event init keys
*@memberof EventDrivers.PageTransitionDriver
*@type {Array}
*/
static get eventInitKeys() {
let keys = Driver.eventInitKeys;
keys.push('persisted');
return keys;
}
/**
* initializes the event according to the PageTransitionEvent interface eventInit requirement
*@memberof EventDrivers.PageTransitionDriver
*@param {Object} storeIn - object in which to store initializations
*@param {PageTransitionEventInit} getFrom - event initialization objects
*@returns {Object}
*/
static initEvent(storeIn, getFrom) {
Driver.initEvent(storeIn, getFrom);
storeIn.persisted = getFrom.persisted? true : false;
return storeIn;
}
/**
* creates a PageTransitionEvent object that can be dispatched to an event target
*@memberof EventDrivers.PageTransitionDriver
*@param {string} type - the event type
*@param {PageTransitionEventInit} eventInit - event initialization object
*@returns {PageTransitionEvent}
*/
static create(type, eventInit) {
return createDOMEvent(
'PageTransitionEvent', type, this.initEvent({}, eventInit), this.eventInitKeys
);
}
/**
*@param {PageTransitionEvent} event - the dispatched event object
*/
constructor(event) {
super(event);
}
/**
*@memberof EventDrivers.PageTransitionDriver#
*@private
*@type {string}
*/
get [Symbol.toStringTag]() {
return 'PageTransitionDriver';
}
/**
* a boolean value indicating if the webpage is loading from cache
*@memberof EventDrivers.PageTransitionDriver#
*@type {boolean}
*/
get persisted() {
return this.event.persisted;
}
}
/* install pollyfill */
onInstall(function() {
PageTransitionEventPollyfill.install(host, PageTransitionDriver.initEvent);
});
|
C++
|
UTF-8
| 886
| 2.546875
| 3
|
[] |
no_license
|
#include <cstdio>
#include <algorithm>
using namespace std;
int r,c, dp[505][505], sum[505][505], grami[505][505];
inline int s(int from, int to, int grames)
{
return sum[grames][to] - sum[grames][from-1];
}
int main()
{
while (scanf("%d%d",&r,&c) && r)
{
for (int y=1; y<=r; y++)
for (int x=1; x<=c; x++)
{
scanf("%d",&grami[y][x]);
grami[y][x] += grami[y][x-1];
}
for (int y=1; y<=r; y++)
for (int x=1; x<=c; x++)
{
scanf("%d",&sum[y][x]);
sum[y][x] += sum[y-1][x] + sum[y][x-1] - sum[y-1][x-1];
}
dp[1][1] = max(sum[1][1],grami[1][1]);
for (int x=2; x<=c; x++) dp[1][x] = max(grami[1][x], dp[1][x-1]+s(x,x,1));
for (int y=2; y<=r; y++)
for (int x=1; x<=c; x++)
{
dp[y][x] = dp[y-1][x] + grami[y][x];
for (int i=0; i<x; i++) dp[y][x] = max(dp[y][x], dp[y][i]+s(i+1,x,y));
}
printf("%d\n",dp[r][c]);
}
}
|
Python
|
UTF-8
| 125
| 3.484375
| 3
|
[] |
no_license
|
print("tapez la valeur de n :")
n = input()
if int(n)%2 == 0:
print("le nombre n est pair")
else:
print("impair")
|
Markdown
|
UTF-8
| 3,099
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
CONTRIBUTING
============
Tabula is an open-source project, which means it depends on volunteers to build and improve it.
Interested in helping out? We'd love to have your help!
You can help by:
- [Reporting a bug](https://github.com/jazzido/tabula).
- Adding or editing documentation.
- Contributing code via a Pull Request from ideas listed in the [Enhancements](https://github.com/tabulapdf/tabula/labels/enhancement) section of the issues.
- Spreading the word about Tabula to people who might be able to benefit from using it.
Did you have a problem? Guidelines for reporting a bug
------------------------------------------------------
Did Tabula not work for you? We'd like to know about it. We'd also like to know if Tabula worked, but wasn't as easy or useful as it could be. Here's what you can tell us to so we can help you better.
1. What error message did you get? (We need the whole thing! If it looks like gobbledygook to you, it's probably very useful to us. That's why it's there!)
2. What steps did you take? The more precise, the better.
3. What PDF were you trying to extract data from? Some PDFs are wacky, so seeing the exact PDF will be useful. We understand that sometimes PDFs are confidential. If you can share it, just not publicly, send us an email. If you cant', we understand, but might not be able to help you.
4. What version of Tabula are you using? If you're using an older version, we may have solved the problem already.
5. What platform are you on? Windows 7 or 8? Mac? Linux? If your computer uses a language other than English or Spanish, we'd like to know that too.
Guidelines for contributing code
--------------------------------
If you'd like to contribute code, here's some stuff you should know: You're also welcome to send us a note, if you'd like. All of our email addresses are listed on our Github pages.
Tabula comes in a bunch of parts, all located in the [TabulaPDF Github organization](github.com/tabulapdf).
-The [tabula](https://github.com/tabulapdf/tabula) repo is the UI. We aim for it to soon be all front-end, but right now has a small web server, written in Ruby, to interface between the front-end and extractor library, called "tabula-extractor"
- the [tabula-extractor](https://github.com/tabulapdf/tabula-extractor/) Ruby gem actually extracts info from PDFs, using table locations provided by the UI (or on the command line). tabula-extractor will be deprecated soon too -- it'll be replaced by 'tabula-java'
- [tabula-java](https://github.com/tabulapdf/tabula-java/) is a pure Java port, for speed/wider usability.
- [tabula-api](https://github.com/tabulapdf/tabula-api/) will eventually serve as the glue layer between tabula-java and the tabula UI (replacing that small web server mentioned above).
The [Enhancements](https://github.com/tabulapdf/tabula/labels/enhancement) section of the issues lists some important improvements to Tabula that you could try out. They're well-suited to contributors, since they don't depend on a deep knowledge of all of Tabula's parts and they don't depend on close coordination.
|
PHP
|
UTF-8
| 819
| 3.09375
| 3
|
[] |
no_license
|
<?php
declare(strict_types=1);
/*------------------------------------
| 具體仲介者
|------------------------------------
|
|
|
*/
namespace Src\Mediator\Basic;
class ConcreteMediator extends Mediator
{
private $colleague1;
private $colleague2;
/**
* @param mixed $colleague1
*/
public function setColleague1($colleague1): void
{
$this->colleague1 = $colleague1;
}
/**
* @param mixed $colleague2
*/
public function setColleague2($colleague2): void
{
$this->colleague2 = $colleague2;
}
public function send($message, Colleague $colleague)
{
if($colleague == $this->colleague1){
$this->colleague2->notify($message);
} else {
$this->colleague1->notify($message);
}
}
}
|
Java
|
UTF-8
| 3,419
| 1.914063
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright (C) 2014-2023 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.peppol.rest;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.helger.commons.error.IError;
import com.helger.commons.error.level.EErrorLevel;
import com.helger.commons.error.level.IErrorLevel;
import com.helger.commons.lang.StackTraceHelper;
import com.helger.commons.state.ETriState;
import com.helger.json.IJsonObject;
import com.helger.json.JsonObject;
public abstract class AbstractJsonBasedAPIExecutor extends AbstractAPIExecutor
{
@Nonnull
protected static String getErrorLevel (@Nonnull final IErrorLevel aErrorLevel)
{
if (aErrorLevel.isGE (EErrorLevel.ERROR))
return "ERROR";
if (aErrorLevel.isGE (EErrorLevel.WARN))
return "WARN";
return "SUCCESS";
}
@Nonnull
protected static String getTriState (@Nonnull final ETriState eTriState)
{
if (eTriState.isTrue ())
return "TRUE";
if (eTriState.isFalse ())
return "FALSE";
return "UNDEFINED";
}
@Nullable
protected static IJsonObject getStackTrace (@Nullable final Throwable t)
{
if (t == null)
return null;
return new JsonObject ().add ("class", t.getClass ().getName ())
.addIfNotNull ("message", t.getMessage ())
.add ("stackTrace", StackTraceHelper.getStackAsString (t));
}
@Nonnull
protected static IJsonObject createItem (@Nonnull final IErrorLevel aErrorLevel,
@Nullable final String sErrorID,
@Nullable final String sErrorFieldName,
@Nullable final String sErrorLocation,
@Nonnull final String sErrorText,
@Nullable final Throwable t)
{
return new JsonObject ().add ("errorLevel", getErrorLevel (aErrorLevel))
.addIfNotNull ("errorID", sErrorID)
.addIfNotNull ("errorFieldName", sErrorFieldName)
.addIfNotNull ("errorLocation", sErrorLocation)
.add ("errorText", sErrorText)
.addIfNotNull ("exception", getStackTrace (t));
}
@Nonnull
protected static IJsonObject createItem (@Nonnull final IError aError, @Nonnull final Locale aDisplayLocale)
{
return createItem (aError.getErrorLevel (),
aError.getErrorID (),
aError.getErrorFieldName (),
aError.hasErrorLocation () ? aError.getErrorLocation ().getAsString () : null,
aError.getErrorText (aDisplayLocale),
aError.getLinkedException ());
}
}
|
Java
|
UTF-8
| 2,160
| 3.578125
| 4
|
[] |
no_license
|
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Example1 {
static class DataOperate {
public static void writeMethod(PipedOutputStream pipedOutputStream) {
try {
System.out.println("Write :");
for (int i = 0; i < 300; i++) {
String outData = "" + (i + 1);
pipedOutputStream.write(outData.getBytes());
System.out.print(outData);
}
System.out.println();
pipedOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void readMethod(PipedInputStream pipedInputStream) {
try {
System.out.println("Read :");
byte[] byteArray = new byte[20];
int readLength = pipedInputStream.read(byteArray);
while(readLength != -1){
String stringData = new String(byteArray, 0, readLength);
System.out.print(stringData);
readLength = pipedInputStream.read(byteArray);
}
System.out.println();
pipedInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 模拟两个线程间的数据交互
* @param args
*/
public static void main(String[] args) {
final PipedInputStream pipedInputStream = new PipedInputStream();
PipedOutputStream pipedOutputStream = new PipedOutputStream();
try {
pipedInputStream.connect(pipedOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
new Thread(()->{
DataOperate.readMethod(pipedInputStream);
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
DataOperate.writeMethod(pipedOutputStream);
}).start();
}
}
|
PHP
|
UTF-8
| 881
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: rndwiga
* Date: 7/7/18
* Time: 9:36 PM
*/
namespace Rndwiga\Mifos\Modules\Product;
use Rndwiga\Mifos\MifosXConnection;
class LoanProductHelper extends MifosXConnection
{
public function listLoanProducts($getArray = false, int $loanProductId = null , array $options = []){
if ($loanProductId){
$urlSegment = "/loanproducts/".$loanProductId;
}else{
$urlSegment = "/loanproducts/";
}
if (count($options) > 0){
$urlSegment = $urlSegment."?fields=".implode(',',array_values($options));
}
$requestedData = $this->curlGetRequest($urlSegment);
if ($getArray == true){
$response = json_decode($requestedData,true);
}else{
$response = json_decode($requestedData);
}
return $response;
}
}
|
Shell
|
UTF-8
| 778
| 3.5625
| 4
|
[] |
no_license
|
#!/bin/bash
destdir=$1
if [ -z "$destdir" ]; then
export destdir=/tmp/skychart
fi
echo Install skychart doc to $destdir
install -v -m 755 -d $destdir
install -v -m 755 -d $destdir/share
install -v -m 755 -d $destdir/share/skychart
for f in $(sort dir-doc.lst)
do
install -v -m 755 -d $destdir/share/skychart/$f
done
for f in $(cat doc.lst)
do
install -v -m 644 $f $destdir/share/skychart/$f
done
if [ ! -d doc/wiki_doc ]; then
cd wiki_doc
./getdoc.sh
./copydoc.sh
cd ..
fi
# create directories
for f in $(find doc/wiki_doc -type d |grep -v .svn)
do
if [ -d $f ]
then install -v -d -m 755 $destdir/share/skychart/$f
fi
done
# install files
for f in $(find doc/wiki_doc/|grep -v .svn)
do
install -v -m 644 $f $destdir/share/skychart/$f
done
|
Markdown
|
UTF-8
| 1,567
| 3.078125
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Text
DeepSea Text manages drawing of arbitrary Unicode text with standard fonts. Rendering is performed using the signed distance field method, allowing a wide range of scaling with the same glyph textures.
One or more fonts are loaded using `dsFaceGroup`. A `dsFont` is created with fonts loaded from the `dsFaceGroup`, allowing for support of international text. If a glyph isn't available in one font, it will try the next until it is found.
Once a font has been created, it can be used along with a Unicode string to create a `dsText` instance. This will do the initial calculations required to draw the text. A `dsTextLayout` object can then be created to apply styling information to compute the geometry that can be rendered. Rendering is typically performed with the `dsTextRenderBuffer` helper object. The vertex format is provided for the text geometry, and a callback is used to provide the vertex information for each glyph. A `dsTextRenderBuffer` object can be used to combine multiple `dsTextLayout` objects into a single draw call.
A shader must be provided and bound to perform drawing of text. When writing shaders, the `dsComputeTextDistance()` and `dsComputeTextColor()` functions in `Text.mslh` can be used to compute the final text color, while the texture containing glyph information can be queried from the `dsFont` instance. The texture containing the fonts Examples can be found in `testers/TestText/Font.msl` and `testers/TestText/FontTess.msl` for drawing standard quads and generating quads with a tesselation shader, respectively.
|
Python
|
UTF-8
| 23,936
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
from __future__ import absolute_import
from builtins import range
import keras.backend as ker
from keras.layers import Dense, Conv2DTranspose, Conv2D, Dot, Reshape, Multiply, Concatenate, Add, Lambda
from keras.models import Model, Input
from numpy import prod
def repeat_dense(inputs, n_layers, n_units=256, activation='relu', name_prefix=None):
"""
Repeat Dense Keras layers, attached to given input.
Args:
inputs: A Keras layer or Tensor preceding the repeated layers
n_layers: number of layers to repeat
n_units: number of units in each layer
activation: the activation in each layer
name_prefix: the prefix of the named layers. A `_i` will be be appended automatically,
where i is the layer number, starting from 0.
Returns:
The last appended Keras layer.
"""
if n_units < 1 or n_layers < 1:
raise ValueError('`n_layers` and `n_units` must be >= 1, '
'found {} and {} respectively'.format(n_layers, n_units))
n_units = int(n_units)
n_layers = int(n_layers)
name_prefix = name_prefix or 'rep_{}_dim{}'.format(activation, n_units)
h = Dense(n_units, activation=activation, name=name_prefix + '_0')(inputs)
for i in range(1, n_layers):
h = Dense(n_units, activation=activation, name=name_prefix + '_{}'.format(i))(h)
return h
def inflating_convolution(inputs, n_inflation_layers, projection_space_shape=(4, 4, 32), name_prefix=None):
assert len(projection_space_shape) == 3, \
"Projection space shape is {} but should be 3.".format(len(projection_space_shape))
flattened_space_dim = prod(projection_space_shape)
projection = Dense(flattened_space_dim, activation=None, name=name_prefix + '_projection')(inputs)
reshape = Reshape(projection_space_shape, name=name_prefix + '_reshape')(projection)
depth = projection_space_shape[2]
inflated = Conv2DTranspose(filters=min(32, depth // 2), kernel_size=(5, 5), strides=(2, 2), activation='relu',
padding='same', name=name_prefix + '_transposed_conv_0')(reshape)
for i in range(1, n_inflation_layers):
inflated = Conv2DTranspose(filters=max(1, depth // 2**(i+1)), kernel_size=(5, 5),
strides=(2, 2), activation='relu', padding='same',
name=name_prefix + '_transpose_conv_{}'.format(i))(inflated)
return inflated
def deflating_convolution(inputs, n_deflation_layers, n_filters_init=32, noise=None, name_prefix=None):
def add_linear_noise(x, eps, ind):
flattened_deflated = Reshape((-1,), name=name_prefix + '_conv_flatten_{}'.format(ind))(x)
deflated_shape = ker.int_shape(x)
deflated_size = deflated_shape[1] * deflated_shape[2] * deflated_shape[3]
noise_transformed = Dense(deflated_size, activation=None,
name=name_prefix + '_conv_noise_dense_{}'.format(ind))(eps)
added_noise = Add(name=name_prefix + '_conv_add_noise_{}'.format(ind))([noise_transformed, flattened_deflated])
x = Reshape((deflated_shape[1], deflated_shape[2], deflated_shape[3]),
name=name_prefix + '_conv_backreshape_{}'.format(ind))(added_noise)
return x
deflated = Conv2D(filters=n_filters_init, kernel_size=(5, 5), strides=(2, 2),
padding='same', activation='relu', name=name_prefix + '_conv_0')(inputs)
if noise is not None:
deflated = add_linear_noise(deflated, noise, 0)
for i in range(1, n_deflation_layers):
deflated = Conv2D(filters=n_filters_init * (2**i), kernel_size=(5, 5), strides=(2, 2),
padding='same', activation='relu', name=name_prefix + '_conv_{}'.format(i))(deflated)
# if noise is not None:
# deflated = add_linear_noise(deflated, noise, i)
return deflated
""" Architectures for reproducing paper experiments on the synthetic 4-points dataset. """
def synthetic_encoder(data_dim, noise_dim, latent_dim=2):
data_input = Input(shape=(data_dim,), name='enc_internal_data_input')
noise_input = Input(shape=(noise_dim,), name='enc_internal_noise_input')
data_noise_concat = Concatenate(axis=1, name='enc_data_noise_concatenation')([data_input, noise_input])
encoder_body = repeat_dense(data_noise_concat, n_layers=2, n_units=256, name_prefix='enc_body')
latent_factors = Dense(latent_dim, activation=None, name='enc_latent')(encoder_body)
latent_model = Model(inputs=[data_input, noise_input], outputs=latent_factors, name='enc_internal_model')
return latent_model
def synthetic_reparametrized_encoder(inputs, latent_dim, name_prefix=''):
encoder_body = repeat_dense(inputs, n_layers=2, n_units=256, name_prefix=name_prefix + 'rep_enc_body')
latent_mean = Dense(latent_dim, activation=None, name=name_prefix + 'rep_enc_mean')(encoder_body)
# since the variance must be positive and this is not easy to restrict, interpret it in the log domain
latent_log_var = Dense(latent_dim, activation=None, name=name_prefix + 'rep_enc_var')(encoder_body)
return latent_mean, latent_log_var
def synthetic_conjoint_encoder(inputs, name_prefix=''):
encoder_body = repeat_dense(inputs, n_layers=2, n_units=256, name_prefix=name_prefix + '_enc_body')
return encoder_body
def synthetic_moment_estimation_encoder(data_dim, noise_dim, noise_basis_dim, latent_dim=2):
noise_input = Input(shape=(noise_basis_dim, noise_dim,), name='enc_internal_noise_input')
# compute the noise basis vectors by attaching small independent fully connected networks to each noise input from
# noise_basis ones in total
def get_inp_row(inputs, **kwargs):
row = kwargs.get('i', 0)
# first axis is the batch size, so skip it
return inputs[:, row]
noise_basis_vectors = []
for i in range(noise_basis_dim):
l = Lambda(get_inp_row, arguments={'i': i}, name='enc_noise_basis_vec_select_{}'.format(i))(noise_input)
fc = Dense(32, activation='relu', name='enc_noise_basis_body_0_basis_{}'.format(i))(l)
fc = Dense(32, activation='relu', name='enc_noise_basis_body_1_basis_{}'.format(i))(fc)
fc = Dense(latent_dim, activation=None, name='enc_noise_basis_body_2_basis_{}'.format(i))(fc)
noise_basis_vectors.append(fc)
noise_basis_vectors_model = Model(inputs=noise_input, outputs=noise_basis_vectors,
name='enc_noise_basis_vector_model')
data_input = Input(shape=(data_dim,), name='enc_internal_data_input')
# center the input around 0
centered_data = Lambda(lambda x: 2 * x - 1, name='enc_centering_data_input')(data_input)
# compute the data embedding using deep convolutional neural network and reshape the output to the noise dim.
extracted_features = repeat_dense(centered_data, n_layers=2, n_units=256, name_prefix='enc_body')
latent_0 = Dense(latent_dim, name='enc_coefficients')(extracted_features)
coefficients = []
for i in range(noise_basis_dim):
coefficients.append(Dense(latent_dim, name='enc_coefficients_{}'.format(i))(extracted_features))
coefficients.append(latent_0)
coefficients_model = Model(inputs=data_input, outputs=coefficients, name='enc_coefficients_model')
return coefficients_model, noise_basis_vectors_model
def synthetic_decoder(inputs, name_prefix=''):
decoder_body = repeat_dense(inputs, n_layers=2, n_units=256, name_prefix=name_prefix + 'dec_body')
return decoder_body
def synthetic_discriminator(data_dim, latent_dim, name_prefix=''):
data_input = Input(shape=(data_dim,), name=name_prefix + 'disc_internal_data_input')
# center the data around 0 in [-1, 1] as it is in [0, 1].
centered_data = Lambda(lambda x: 2 * x - 1, name=name_prefix + 'disc_centering_data_input')(data_input)
discriminator_body_data = repeat_dense(centered_data, n_layers=2, n_units=256, name_prefix= name_prefix + 'disc_body_data')
latent_input = Input(shape=(latent_dim,), name=name_prefix + 'disc_internal_latent_input')
discriminator_body_latent = repeat_dense(latent_input, n_layers=2, n_units=256, name_prefix=name_prefix + 'disc_body_latent')
discriminator_output = Dot(axes=1, name= name_prefix + 'disc_output_dot')([discriminator_body_data, discriminator_body_latent])
discriminator_model = Model(inputs=[data_input, latent_input], outputs=discriminator_output,
name= name_prefix + 'disc_internal_model')
return discriminator_model
def synthetic_adaptive_prior_discriminator(data_dim, latent_dim):
data_input = Input(shape=(data_dim,), name='disc_internal_data_input')
# center the data around 0 in [-1, 1] as it is in [0, 1].
centered_data = Lambda(lambda x: 2 * x - 1, name='disc_centering_data_input')(data_input)
discriminator_body_data = repeat_dense(centered_data, n_layers=2, n_units=256, name_prefix='disc_body_data')
theta = Dense(4*256, activation='relu', name='disc_theta')(discriminator_body_data)
discriminator_body_data_t = repeat_dense(centered_data, n_layers=2, n_units=256, name_prefix='disc_body_data_t')
discriminator_body_data_t = Dense(1, activation=None, name='disc_data_squash')(discriminator_body_data_t)
latent_input = Input(shape=(latent_dim,), name='disc_internal_latent_input')
discriminator_body_latent = repeat_dense(latent_input, n_layers=2, n_units=256, name_prefix='disc_body_latent')
sigma = Dense(4*256, activation='relu', name='disc_sigma')(discriminator_body_latent)
discriminator_body_latent_t = repeat_dense(latent_input, n_layers=2, n_units=256, name_prefix='disc_body_latent_t')
discriminator_body_latent_t = Dense(1, activation=None, name='disc_latent_squash')(discriminator_body_latent_t)
merged_data_latent = Multiply(name='disc_mul_sigma_theta')([theta, sigma])
merged_data_latent = Lambda(lambda x: ker.sum(x, axis=-1), name='disc_add_activ_sig_the')(merged_data_latent)
discriminator_output = Add(name='disc_add_data_latent_t')([discriminator_body_data_t,
discriminator_body_latent_t,
merged_data_latent])
collapsed_noise = Lambda(lambda x: 0.5 * ker.sum(x ** 2, axis=-1), name='disc_noise_addition')(latent_input)
discriminator_output = Add(name='disc_add_all_toghether')([discriminator_output, collapsed_noise])
discriminator_model = Model(inputs=[data_input, latent_input], outputs=discriminator_output,
name='disc_internal_model')
return discriminator_model
""" Architectures for reproducing paper experiments on the MNIST dataset. """
def mnist_encoder(data_dim, noise_dim, latent_dim=8):
data_input = Input(shape=(data_dim,), name='enc_internal_data_input')
noise_input = Input(shape=(noise_dim,), name='enc_internal_noise_input')
# center the input around 0
centered_data = Lambda(lambda x: 2 * x - 1, name='enc_centering_data_input')(data_input)
convnet_input = Reshape((28, 28, 1), name='enc_data_reshape')(centered_data)
conv_output = deflating_convolution(convnet_input, n_deflation_layers=3,
n_filters_init=64, noise=noise_input,
name_prefix='enc_data_body')
conv_output = Reshape((-1,), name='enc_data_features_reshape')(conv_output)
conv_output = Dense(800, activation='relu', name='enc_dense_before_latent')(conv_output)
conv_output = Dense(latent_dim, name='enc_latent_features')(conv_output)
latent_factors = Model(inputs=[data_input, noise_input], outputs=conv_output, name='enc_internal_model')
return latent_factors
def mnist_encoder_simple(data_dim, noise_dim, latent_dim=8):
data_input = Input(shape=(data_dim,), name='enc_internal_data_input')
noise_input = Input(shape=(noise_dim,), name='enc_internal_noise_input')
# center the input around 0
# centered_data = Lambda(lambda x: 2 * x - 1, name='enc_centering_data_input')(data_input)
# concat_input = Concatenate(axis=-1, name='enc_noise_data_concat')([centered_data, noise_input])
enc_body = repeat_dense(data_input, n_layers=2, n_units=256, activation='relu', name_prefix='enc_body')
enc_output = Dense(100, activation='relu', name='enc_dense_before_latent')(enc_body)
enc_output = Dense(latent_dim, name='enc_latent_features')(enc_output)
noise_resized = Dense(latent_dim, activation=None, name='enc_noise_resizing')(noise_input)
enc_output = Add(name='enc_add_noise_data')([enc_output, noise_resized])
latent_factors = Model(inputs=[data_input, noise_input], outputs=enc_output, name='enc_internal_model')
return latent_factors
def mnist_reparametrized_encoder(inputs, latent_dim, name_prefix=''):
# center the input around 0
centered_data = Lambda(lambda x: 2 * x - 1, name=name_prefix + 'enc_centering_data_input')(inputs)
convnet_input = Reshape((28, 28, 1), name=name_prefix + 'rep_enc_data_reshape')(centered_data)
conv_output = deflating_convolution(convnet_input, n_deflation_layers=3,
n_filters_init=64, name_prefix=name_prefix + 'rep_enc_data_body')
latent_factors = Reshape((-1,), name=name_prefix + 'rep_enc_data_features_reshape')(conv_output)
latent_factors = Dense(800, activation='relu', name=name_prefix + 'rep_enc_expanding_before_latent')(latent_factors)
latent_mean = Dense(latent_dim, activation=None, name=name_prefix + 'rep_enc_mean')(latent_factors)
# since the variance must be positive and this is not easy to restrict, interpret it in the log domain
latent_log_var = Dense(latent_dim, activation=None, name=name_prefix + 'rep_enc_var')(latent_factors)
return latent_mean, latent_log_var
def mnist_conjoint_encoder(inputs, name_prefix=''):
# center the input around 0
centered_data = Lambda(lambda x: 2 * x - 1, name=name_prefix + 'enc_centering_data_input')(inputs)
convnet_input = Reshape((28, 28, 1), name=name_prefix + 'rep_enc_data_reshape')(centered_data)
conv_output = deflating_convolution(convnet_input, n_deflation_layers=3,
n_filters_init=64, name_prefix=name_prefix + 'rep_enc_data_body')
latent_factors = Reshape((-1,), name=name_prefix + 'rep_enc_data_features_reshape')(conv_output)
latent_factors = Dense(800, activation='relu', name=name_prefix + 'rep_enc_expanding_before_latent')(latent_factors)
return latent_factors
def mnist_reparametrized_encoder_simple(inputs, latent_dim):
# center the input around 0
centered_data = Lambda(lambda x: 2 * x - 1, name='enc_centering_data_input')(inputs)
enc_body = repeat_dense(centered_data, n_layers=2, n_units=256, activation='relu', name_prefix='enc_body')
enc_output = Dense(100, activation='relu', name='enc_dense_before_latent')(enc_body)
latent_mean = Dense(latent_dim, activation=None, name='rep_enc_mean')(enc_output)
# since the variance must be positive and this is not easy to restrict, interpret it in the log domain
latent_log_var = Dense(latent_dim, activation=None, name='rep_enc_var')(enc_output)
return latent_mean, latent_log_var
def mnist_moment_estimation_encoder(data_dim, noise_dim, noise_basis_dim, latent_dim=8):
noise_input = Input(shape=(noise_basis_dim, noise_dim,), name='enc_internal_noise_input')
# compute the noise basis vectors by attaching small independent fully connected networks to each noise input from
# noise_basis ones in total
def get_inp_row(inputs, **kwargs):
row = kwargs.get('i', 0)
# first axis is the batch size, so skip it
return inputs[:, row]
noise_basis_vectors = []
for i in range(noise_basis_dim):
l = Lambda(get_inp_row, arguments={'i': i}, name='enc_noise_basis_vec_select_{}'.format(i))(noise_input)
fc = Dense(128, activation='relu', name='enc_noise_basis_body_0_basis_{}'.format(i))(l)
fc = Dense(128, activation='relu', name='enc_noise_basis_body_1_basis_{}'.format(i))(fc)
fc = Dense(128, activation='relu', name='enc_noise_basis_body_2_basis_{}'.format(i))(fc)
fc = Dense(latent_dim, activation=None, name='enc_noise_basis_body_3_basis_{}'.format(i))(fc)
noise_basis_vectors.append(fc)
noise_basis_vectors_model = Model(inputs=noise_input, outputs=noise_basis_vectors,
name='enc_noise_basis_vector_model')
data_input = Input(shape=(data_dim,), name='enc_internal_data_input')
assert data_dim == 28 ** 2, "MNIST data should be flattened to 784-dimensional vectors."
# center the input around 0
centered_data = Lambda(lambda x: 2 * x - 1, name='enc_centering_data_input')(data_input)
# compute the data embedding using deep convolutional neural network and reshape the output to the noise dim.
convnet_input = Reshape((28, 28, 1), name='enc_data_reshape')(centered_data)
# add noise to the convolutions
# partial_noise = Reshape((-1,), name='enc_noise_addition_conv')(noise_input)
coefficients = deflating_convolution(convnet_input, n_deflation_layers=3,
n_filters_init=64, name_prefix='enc_data_body')
coefficients = Reshape((-1,), name='enc_data_features_reshape')(coefficients)
extracted_features = Dense(800, activation='relu', name='enc_expanding_before_latent')(coefficients)
latent_0 = Dense(latent_dim, name='enc_coefficients')(extracted_features)
coefficients = []
for i in range(noise_basis_dim):
coefficients.append(Dense(latent_dim, name='enc_coefficients_{}'.format(i))(extracted_features))
coefficients.append(latent_0)
coefficients_model = Model(inputs=data_input, outputs=coefficients, name='enc_coefficients_model')
return coefficients_model, noise_basis_vectors_model
def mnist_decoder(inputs, name_prefix=''):
decoder_body = Dense(200, activation='relu', name=name_prefix + 'dec_body_initial_dense')(inputs)
# use transposed convolutions to inflate the latent space to (?, 32, 32, 8)
decoder_body = inflating_convolution(decoder_body, 3, projection_space_shape=(4, 4, 32),
name_prefix=name_prefix + 'dec_body')
# use single non-padded convolution to shrink the size to (?, 28, 28, 1)
decoder_body = Conv2D(filters=1, kernel_size=(5, 5), strides=(1, 1), activation='relu',
padding='valid', name=name_prefix + 'dec_body_conv')(decoder_body)
# reshape to flatten out the output
decoder_body = Reshape((-1,), name=name_prefix + 'dec_body_reshape_out')(decoder_body)
return decoder_body
def mnist_decoder_simple(inputs):
decoder_body = repeat_dense(inputs, n_layers=3, n_units=512, name_prefix='dec_body')
return decoder_body
def mnist_adaptive_prior_discriminator(data_dim, latent_dim):
data_input = Input(shape=(data_dim,), name='disc_internal_data_input')
# center the data around 0 in [-1, 1] as it is in [0, 1].
centered_data = Lambda(lambda x: 2 * x - 1, name='disc_centering_data_input')(data_input)
discriminator_body_data = repeat_dense(centered_data, n_layers=3, n_units=512, name_prefix='disc_body_data')
theta = Dense(4*512, activation='relu', name='disc_theta')(discriminator_body_data)
discriminator_body_data_t = repeat_dense(centered_data, n_layers=3, n_units=512, name_prefix='disc_body_data_t')
discriminator_body_data_t = Dense(1, activation=None, name='disc_data_squash')(discriminator_body_data_t)
latent_input = Input(shape=(latent_dim,), name='disc_internal_latent_input')
discriminator_body_latent = repeat_dense(latent_input, n_layers=3, n_units=512, name_prefix='disc_body_latent')
sigma = Dense(4*512, activation='relu', name='disc_sigma')(discriminator_body_latent)
discriminator_body_latent_t = repeat_dense(latent_input, n_layers=3, n_units=512, name_prefix='disc_body_latent_t')
discriminator_body_latent_t = Dense(1, activation=None, name='disc_latent_squash')(discriminator_body_latent_t)
merged_data_latent = Multiply(name='disc_mul_sigma_theta')([theta, sigma])
merged_data_latent = Lambda(lambda x: ker.sum(x, axis=-1), name='disc_add_activ_sig_the')(merged_data_latent)
discriminator_output = Add(name='disc_add_data_latent_t')([discriminator_body_data_t,
discriminator_body_latent_t,
merged_data_latent])
collapsed_noise = Lambda(lambda x: 0.5 * ker.sum(x**2, axis=-1), name='disc_noise_addition')(latent_input)
discriminator_output = Add(name='disc_add_all_toghether')([discriminator_output, collapsed_noise])
discriminator_model = Model(inputs=[data_input, latent_input], outputs=discriminator_output,
name='disc_internal_model')
return discriminator_model
def mnist_discriminator_simple(data_dim, latent_dim, name_prefix=''):
data_input = Input(shape=(data_dim,), name=name_prefix + 'disc_internal_data_input')
# center the data around 0 in [-1, 1] as it is in [0, 1].
centered_data = Lambda(lambda x: 2 * x - 1, name=name_prefix + 'disc_centering_data_input')(data_input)
discriminator_body_data = repeat_dense(centered_data, n_layers=4, n_units=512, name_prefix=name_prefix + '_data')
latent_input = Input(shape=(latent_dim,), name=name_prefix + 'disc_internal_latent_input')
discriminator_body_latent = repeat_dense(latent_input, n_layers=4, n_units=512, name_prefix=name_prefix + '_latent')
discriminator_output = Dot(axes=-1, name=name_prefix + 'disc_dot_sigma_theta')([discriminator_body_data,
discriminator_body_latent])
discriminator_model = Model(inputs=[data_input, latent_input], outputs=discriminator_output,
name=name_prefix + 'disc_internal_model')
return discriminator_model
get_network_by_name = {'encoder': {'synthetic': synthetic_encoder,
'mnist': mnist_encoder,
'mnist_simple': mnist_encoder_simple},
'reparametrised_encoder': {'synthetic': synthetic_reparametrized_encoder,
'mnist': mnist_reparametrized_encoder,
'mnist_simple': mnist_reparametrized_encoder_simple},
'conjoint_encoder': {'synthetic': synthetic_conjoint_encoder,
'mnist': mnist_conjoint_encoder},
'moment_estimation_encoder': {'synthetic': synthetic_moment_estimation_encoder,
'mnist': mnist_moment_estimation_encoder},
'decoder': {'synthetic': synthetic_decoder,
'mnist': mnist_decoder,
'mnist_simple': mnist_decoder_simple},
'conjoint_decoder': {'synthetic': synthetic_decoder,
'mnist': mnist_decoder},
'discriminator': {'synthetic': synthetic_discriminator,
'mnist': mnist_discriminator_simple,
'mnist_simple': mnist_discriminator_simple},
'adaptive_prior_discriminator': {'synthetic': synthetic_adaptive_prior_discriminator,
'mnist': mnist_adaptive_prior_discriminator,
'mnist_simple': mnist_discriminator_simple}
}
|
C#
|
UTF-8
| 24,056
| 2.734375
| 3
|
[] |
no_license
|
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using MySql.Data.MySqlClient;
/* Remarques:
* Dans les propriétés des listView, modifier 'FullRowSlect' à 'True' et 'Multiselect' à 'False'.
* Dans les propriétés de F_accueil, 'FormBorderStyle' à 'FixedSingle'.
*/
namespace testMysql
{
public partial class F_accueil : Form
{
//Variable servant à créer la commande de connection au serveur:
string connectionString = "Server=192.168.0.101;Port=3306;Database=BD_parking;Uid=user;Pwd=pass;SslMode=none";
bool connecte = false; // Variable qui informe si la coonection est active ou pas (True ou Flase).
MySqlConnection connection; // coonection = instance de la classe MySqlConnection.
public F_accueil()
{
InitializeComponent();
}
// ***** Fonctions Connection - déconnection : *****
private void button1_Click(object sender, EventArgs e)
{
// Association de l'instance 'connection' à la vraible connectionString:
connection = new MySqlConnection(connectionString);
if (button1.Text == "Se connecter")
{
try // Traitement si exceptions
{ //On vérifie si la connection est fermé:
if (connection.State == ConnectionState.Closed)
{
connection.Open(); // On ouvre la connection.
connecte = true; // On met à true car la connection est ouverte.
MessageBox.Show("Connecté !");
button1.Text = "Se deconnecter";
}
}
catch (MySqlException co) // Si erreur, affichage de l'erreur.
{
MessageBox.Show(co.ToString());
MessageBox.Show("Non Connecté !");
}
}
else
{ // Pour fermer la connection au serveur:
connection.Close();
connecte = false; // On met à false car la connection est fermée.
button1.Text = "Se connecter";
}
}
//***** Fonction Ajouter : *****
private void button2_Click(object sender, EventArgs e)
{ // On vérifie que tout les textBox sont remplis (1 à 5):
if (textBox1.Text == "") MessageBox.Show("Entrez un nom !");
else if (textBox2.Text == "") MessageBox.Show("Entrez un prénom !");
else if (textBox3.Text == "") MessageBox.Show("Entrez le statut !");
else if (textBox4.Text == "") MessageBox.Show("Entrez le code NFC !");
else if (textBox5.Text == "") MessageBox.Show("Entrez l'immatriculation !");
else
{
if (connecte) // Si on est connecté à la base de donnée.
{
try // Gestion des exceptions.
{ // Commande SQL pour ajouter un client dans la base de donnée:
string query = "INSERT INTO TAB_clients(nomClients, prenomClients, statutClients, nfcClients, vehiculeClients) VALUES(@nom, @prenom, @statut, @nfc, @vehicule)";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Prepare();
//On récupére les infos des textBox et on les ajoutent à la commande SQL 'query':
cmd.Parameters.AddWithValue("@nom", textBox1.Text);
cmd.Parameters.AddWithValue("@prenom", textBox2.Text);
cmd.Parameters.AddWithValue("@statut", textBox3.Text);
cmd.Parameters.AddWithValue("@nfc", textBox4.Text);
cmd.Parameters.AddWithValue("@vehicule", textBox5.Text);
cmd.ExecuteNonQuery(); // On envoie la requête SQL au serveur.
cmd.Parameters.Clear();
MessageBox.Show("Ajouté !!!");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Erreur ajouter" + ex.Message + ex.Number);
}
}
else MessageBox.Show ("Vous n'êtes pas connecté !");
}
}
//***** Fonction affichage de la table TAB_clients : *****
private void button3_Click(object sender, EventArgs e)
{
if (connecte)
{
listView1.Items.Clear(); // On efface les données affichées dans le contrôle listView1.
// (listView1 permet d'afficher les différents clients sous
// forme de tableau et colonnes.)
// Commande SQL pour afficher tous les clients de TAB_clients:
string query = "SELECT * FROM TAB_clients";
MySqlCommand cmd = new MySqlCommand(query, connection);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read()) //Boucle qui permet d'afficher tout les clients.
{ // On récupere les infos envoyé par la base de donnée:
string ID = lecture["idClients"].ToString();
string Nom = lecture["nomClients"].ToString();
string Prenom = lecture["prenomClients"].ToString();
string Statut = lecture["statutClients"].ToString();
string Nfc = lecture["nfcClients"].ToString();
string Vehicule = lecture["vehiculeClients"].ToString();
string Date = lecture["date_creationClients"].ToString();
//Affichage des clients dans la listView1:
listView1.Items.Add(new ListViewItem(new[] { ID, Nom, Prenom, Statut, Nfc, Vehicule, Date }));
}
}
}
else
{
MessageBox.Show("Vous n'êtes pas connecté !");
}
}
//***** Fonction supprimer une rangee de donnée de la table TAB_clients : *****
// Ici on utilise le click droit de la souris et l'outil "ContextMenuStrip".
private void supprimerToolStripMenuItem_Click(object sender, EventArgs e)
{
if (connecte)
{
if (listView1.SelectedItems.Count > 0) //count=13 si 13 lignes de donnée.
{
ListViewItem element = listView1.SelectedItems[0]; // 0 ou erreur.
// recupère le contenu de la colonne 0 de la ligne élément ici l'idClients,
// exemple: si SubItems[2].text on récupérera le prénom du client :
string Id = element.SubItems[0].Text;
// Requête SQL pour effacer un client dans TAB_clients en donnant son idClients:
string query = "DELETE FROM TAB_clients WHERE idClients=@id";
MySqlCommand cmd = new MySqlCommand(query, connection);
// On additionne L'ID dans la requête:
cmd.Parameters.AddWithValue("@id", Id);
cmd.ExecuteNonQuery();
element.Remove();
MessageBox.Show("Element supprimé !");
}
}
}
//***** 2ème Fonction supprimer une rangee de donnée de la table TAB_clients : *****
// Ici on utilise l'outil de base "button".
private void button2_Click_1(object sender, EventArgs e)
{
if (connecte)
{
if (listView1.SelectedItems.Count > 0) //count=13 si 13 lignes de donnée.
{
ListViewItem element = listView1.SelectedItems[0]; // 0 ou erreur.
// recupère le contenu de la colonne 0 de la ligne element ici l'idClients.
string Id = element.SubItems[0].Text;
string query = "DELETE FROM TAB_clients WHERE idClients=@id";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@id", Id);
cmd.ExecuteNonQuery();
element.Remove();
MessageBox.Show("Element supprimé !");
}
else MessageBox.Show("Veuillez selectionner un clients !");
}
}
/***** Fonction modifier clients dans la base de donnee : *****
Utilisation du click droit souris puis click sur Modifier.
Apparition d'une fenêtre 'Modifier' pour insérer les nouvelles données.
*/
private void modifierToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0) // Si on a une liste de client.
{ // On récupére les données de chaque colonne du client selectionné :
ListViewItem element = listView1.SelectedItems[0]; // 0 ou erreur.
string ID = element.SubItems[0].Text;
string nom = element.SubItems[1].Text;
string prenom = element.SubItems[2].Text;
string statut = element.SubItems[3].Text;
string nfc = element.SubItems[4].Text;
string vehicule = element.SubItems[5].Text;
// Ci dessous on va modifer le Form nommé 'modifier' avec les données sélectionnées
// dans 'listView' .
using (modifier m = new modifier() )
{
m.Id = ID; // 'm.Id' correspond à la variable crée dans 'modifer.cs'
m.Nom = nom; // Idem pour les données suivantes
m.Prenom = prenom;
m.Statut = statut;
m.Nfc = nfc;
m.Vehicule = vehicule;
//m.ShowDialog(); ligne qui ouvre le Form 'modifier'.
/* La condition suivante ouvre automatiquement la Fenêtre 'Modifier' même si la
condition n'est pas remplie.
Si la condition est remplie, c'est à dire si l'on a clické sur le bouton 'Modifier'
de la Fenêtre 'Modifier' les valeurs du client id,nom etc... affichées dans les 'textBox'
seront envoyées dans la Base de donnée pour la modifier.
*/
if (m.ShowDialog() == DialogResult.Yes)
{ // Préparation de la requête SQL et envoi à la table 'TAB_clients :
string query = "UPDATE TAB_clients SET statutClients=@statut, nfcClients=@nfc, vehiculeClients=@vehicule WHERE idClients=@id ";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@id", ID);
cmd.Parameters.AddWithValue("@statut", m.Statut);
cmd.Parameters.AddWithValue("@nfc", m.Nfc);
cmd.Parameters.AddWithValue("@vehicule", m.Vehicule);
cmd.ExecuteNonQuery();
// mise à jour dela liste clients :
element.SubItems[3].Text = m.Statut;
element.SubItems[4].Text = m.Nfc;
element.SubItems[5].Text = m.Vehicule;
MessageBox.Show("Client modifié !");
}
}
}
}
//***** Fonction chercher un client par son nom : *****
private void button4_Click(object sender, EventArgs e)
{
if (connecte)
{
listView1.Items.Clear();
string query = "SELECT * FROM TAB_clients WHERE nomClients = @nom";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@nom", textBox6.Text);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read())
{
string ID = lecture["idClients"].ToString();
string Nom = lecture["nomClients"].ToString();
string Prenom = lecture["prenomClients"].ToString();
string Statut = lecture["statutClients"].ToString();
string Nfc = lecture["nfcClients"].ToString();
string Vehicule = lecture["vehiculeClients"].ToString();
string Date = lecture["date_creationClients"].ToString();
listView1.Items.Add(new ListViewItem(new[] { ID, Nom, Prenom, Statut, Nfc, Vehicule, Date }));
}
}
}
}
//***** Fonction chercher un client par son immatriculation : *****
private void button5_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
string query = "SELECT * FROM TAB_clients WHERE vehiculeClients = @vehicule";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@vehicule", textBox6.Text);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read())
{
string ID = lecture["idClients"].ToString();
string Nom = lecture["nomClients"].ToString();
string Prenom = lecture["prenomClients"].ToString();
string Statut = lecture["statutClients"].ToString();
string Nfc = lecture["nfcClients"].ToString();
string Vehicule = lecture["vehiculeClients"].ToString();
string Date = lecture["date_creationClients"].ToString();
listView1.Items.Add(new ListViewItem(new[] { ID, Nom, Prenom, Statut, Nfc, Vehicule, Date }));
}
}
}
//***** Fonction affichage de la table TAB_camera : *****
private void button6_Click(object sender, EventArgs e)
{
if (connecte)
{
listView2.Items.Clear();
string query = "SELECT * FROM TAB_camera";
MySqlCommand cmd = new MySqlCommand(query, connection);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read())
{
string ID = lecture["idCamera"].ToString();
string plaque = lecture["plaqueCamera"].ToString();
string nom = lecture["nomCamera"].ToString();
string date = lecture["dateCamera"].ToString();
string heure = lecture["heureCamera"].ToString();
string autorisation = lecture["autorisationCamera"].ToString();
listView2.Items.Add(new ListViewItem(new[] { ID, plaque, nom, date, heure, autorisation }));
}
}
}
else MessageBox.Show("Vous n'êtes pas connecté !");
}
//***** Fonction supprimer une rangee de donnée de la table TAB_camera : *****
// Ici on utilise le click droit de la souris et l'outil "ContextMenuStrip (2)".
private void supprimerToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (connecte)
{
if (listView2.SelectedItems.Count > 0) //count=13 si 13 lignes de donnée.
{
ListViewItem element = listView2.SelectedItems[0]; // 0 ou erreur.
// recupère le contenu de la colonne 0 de la ligne élément ici l'idClients.
string Id = element.SubItems[0].Text;
string query = "DELETE FROM TAB_camera WHERE idCamera=@id";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@id", Id);
cmd.ExecuteNonQuery();
element.Remove();
MessageBox.Show("Element supprimé !");
}
}
}
//***** 2ème Fonction supprimer une rangee de donnée de la table TAB_camera : *****
// Ici on utilise l'outil de base "button".
private void button7_Click(object sender, EventArgs e)
{
if (connecte)
{
if (listView2.SelectedItems.Count > 0) //count=13 si 13 lignes de donnée.
{
ListViewItem element = listView2.SelectedItems[0]; // 0 ou erreur.
// recupère le contenu de la colonne 0 de la ligne element ici l'idClients.
string Id = element.SubItems[0].Text;
string query = "DELETE FROM TAB_clients WHERE idClients=@id";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@id", Id);
cmd.ExecuteNonQuery();
element.Remove();
MessageBox.Show("Element supprimé !");
}
else MessageBox.Show("Veuillez selectionner un clients !");
}
else MessageBox.Show("Vous n'êtes pas connecté !");
}
//***** Fonction chercher un enregistrement par son nom dans TAB_camera: *****
private void button8_Click(object sender, EventArgs e)
{
listView2.Items.Clear();
string query = "SELECT * FROM TAB_camera WHERE nomCamera = @nom";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@nom", textBox8.Text);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read())
{
string ID = lecture["idCamera"].ToString();
string plaque = lecture["plaqueCamera"].ToString();
string Nom = lecture["nomCamera"].ToString();
string date = lecture["dateCamera"].ToString();
string heure = lecture["heureCamera"].ToString();
string autorisation = lecture["autorisationCamera"].ToString();
listView2.Items.Add(new ListViewItem(new[] { ID, plaque, Nom, date, heure, autorisation }));
}
}
}
//***** Fonction chercher un enregistrement par son immatriculation dans TAB_camera: *****
private void button9_Click(object sender, EventArgs e)
{
if (connecte)
{
listView2.Items.Clear();
string query = "SELECT * FROM TAB_camera WHERE plaqueCamera = @plaque";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@plaque", textBox9.Text);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read())
{
string ID = lecture["idCamera"].ToString();
string plaque = lecture["plaqueCamera"].ToString();
string Nom = lecture["nomCamera"].ToString();
string date = lecture["dateCamera"].ToString();
string heure = lecture["heureCamera"].ToString();
string autorisation = lecture["autorisationCamera"].ToString();
listView2.Items.Add(new ListViewItem(new[] { ID, plaque, Nom, date, heure, autorisation }));
}
}
}
else MessageBox.Show("Vous n'êtes pas connecté !");
}
//***** Fonction chercher un enregistrement entre 2 dates dans TAB_camera: *****
// Il faut ici modifier les prompriétés Format=Custom et CustomFormat=yyyy-MM-dd
private void button10_Click(object sender, EventArgs e)
{
if (connecte)
{
listView2.Items.Clear();
string query = "SELECT * FROM TAB_camera WHERE dateCamera BETWEEN @date1 AND @date2";
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@date1", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("@date2", dateTimePicker2.Text);
using (MySqlDataReader lecture = cmd.ExecuteReader())
{
while (lecture.Read())
{
string ID = lecture["idCamera"].ToString();
string plaque = lecture["plaqueCamera"].ToString();
string Nom = lecture["nomCamera"].ToString();
string date = lecture["dateCamera"].ToString();
string heure = lecture["heureCamera"].ToString();
string autorisation = lecture["autorisationCamera"].ToString();
listView2.Items.Add(new ListViewItem(new[] { ID, plaque, Nom, date, heure, autorisation }));
}
}
}
else MessageBox.Show("Vous n'êtes pas connecté !");
}
//***** Sauvegarder la base de donnée : *****
private void button11_Click(object sender, EventArgs e)
{
string constring = "server=192.168.0.101;user=user;pwd=pass;database=BD_parking;";
string file = "D:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ExportToFile(file);
conn.Close();
}
}
}
}
//***** Restaurer la base de donnée : *****
private void button12_Click(object sender, EventArgs e)
{
string constring = "server=192.168.0.101;user=user;pwd=pass;database=BD_parking;";
string file = "D:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = conn;
conn.Open();
mb.ImportFromFile(file);
conn.Close();
}
}
}
}
}
}
|
Markdown
|
UTF-8
| 6,302
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
Toggl time report builder
=========================
Toggl.py is a time report builder, taking data from [Toggl](toggl.com) time tracker using [reports API](https://github.com/toggl/toggl_api_docs/blob/master/reports.md).
It was created for internal use by students in Software Engineering program and tailored for academic purposes. However, I will be glad to hear it is used in industry as well.
At the moment three types of reports are available:
- team time report, charts with weekly teams effort
- individual time report, CSV file
- time logging violations, CSV
- detailed report with all logged entries, CSV
Requirements
----
The only requirement is Python 2.4+.
This tool does not use any libraries besides standard functions. It does not use any kind of database or local storage to store past data, report is completely rebuilt for the given period every time. It introduces ~30 seconds of overhead for 6 month report period, which were sacrificed for tool portability and ease of use.
Setup
----
Get the code:
`git clone git@github.com:user2589/Toggl.py.git`
Then, adjust settings. There is an example settings file you can use as a template:
`mv settings.exapmple.py settings.py`
Following settings available:
- `api_token` - Toggl api token, you can find it in [toggl profile](https://toggl.com/app/profile). Good practice is to create a separate account with access to all monitored teams' workspaces.
- `start_date` and `end_date` - boundaries of the period monitored in `YYY-MM-DD` format. In academia we use semesters, for industry use you might consider quarters.
- `core_courses` - projects you want to get separated in stats. Everything else will be aggregated to a single entity, which will be named by value of `everything_else` setting. It is named so because of the academic past of this tool.
- `everything_else` - see `core_courses` description
- `report date format` - data format to be used to name Mondays in weekly time report
- `template` - string that will be used to format output. Common practice is to read content of html template right in the settings file.
Detailed report
-----------
Detailed report is a CSV file with columns: user, team, project, start, duration. To generate detailed report, run:
./detailed_report > detailed.csv
If you serve CSV reports by a web service, there is a nice visualization of the detailed report (check out the [screenshot](docs/Details.png). Just put `detais.html` into the same folder as CSV files, under the webroot directory of the HTTP server. Usually, it is a good idea to restrict access to detailed and individual reports for privacy purposes, e.g. by using [htpasswd](https://httpd.apache.org/docs/2.4/programs/htpasswd.html) file for Apache2
Individual report
-----------
Individual report is a CSV file, generated from detailed report by aggregating records by users and reporting weeks.
Example individual report opened in LibreOffice:

To produce this report, run:
cat detailed.csv | ./individual_report.py > individual.csv # if you already have a detailed report
./detailed_report | ./individual_report.py > individual.csv # if you don't have detailed report
./detailed_report | tee detailed.csv | ./individual_report.py > individual.csv # if you want to generate both
Logging violations report
-----
This report is a CSV list of suspicious time entries. It is generated by the script of individual report and printed to standard error output. What is treated as violation:
- overlapping time entries
- time entry stretching more than N hours (10 by default)
- time records without project
An example of violations report opened in LibreOffice:

To produce save this report into file, run:
cat detailed.csv | ./individual_report.py 2> violations.csv # to produce logging violations report only
cat detailed.csv | ./individual_report.py > individual.csv 2> violations.csv # to produce both individual and violation reports at once
./detailed_report.py | tee detailed.csv | ./individual_report.py 2> violations.csv > individual.csv # if you want to generate all three: detailed, individual and violations report
Team weekly time report
-----------
Team weekly report is HTML file with charts generated from individual report using template stored in settings.
Example of the report produced with default template:

To produce the report, run:
cat individual.csv | ./team_report.py > team_report.html # output to a fixed file name
cat individual.csv | ./team_report.py > `date +Week_%b%d.html` # name report file by the date it is produced
Putting it altogether:
./detailed_report.py | tee detailed.csv | ./individual_report.py 2> violations.csv | tee individual.csv | ./team_report.py > `date +Week_%b%d.html`
Template for team reports
---------
This report produced by `team_report.py` using template. Template string is set in settings.template and it is just a format string. It is passed four variables for formatting in **JSON**:
- `week_labels` is a list of Mondays in `settings.report_date_format`. Example:
> ["Jan 12", "Jan 19", "Jan 26", "Feb 02", "Feb 09", "Feb 16"]
- `teams` is a list of team names taken from Toggl. Example:
> ["Team Alpha", "Team Bravo", "Team Charlie"]
- `courses` list of courses from `settings.core_courses` plus one more entity named by `settings.everything_else`. If there are no time records for some project, it will not be included in report. Example:
> ["Project Sunshine", "Project Smile", "other stuffs"]
- `report_data` - actual report data in format `report.course.team.weekly_data`. Example:
```
{
"Project Sunshine": {
"Team Alpha": [3.64, 10.29, 10.54, nul, ...],
"Team Bravo": [3.24, 7.26, 8.89, nul, ...],
...
},
...
}
```
Please note that default template contains a workaround not to count Spring Break towards total number of weeks. Look for `spring_break_idx` in template.html, set it blank if you don't need this feature.
License
-------
Distributed under [MIT License](opensource.org/licenses/MIT)
|
JavaScript
|
UTF-8
| 565
| 3.265625
| 3
|
[] |
no_license
|
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let ret = [];
generate(n, n, '');
return ret;
function generate(left, right, s) {
if (left === 0 && right === 0) {
ret.push(s);
return;
}
if (left > right) return;
if (left < right) {
if (left != 0) generate(left - 1, right, s + '(');
generate(left, right - 1, s + ')');
}
if (left == right) {
generate(left - 1, right, s + '(');
}
}
};
|
SQL
|
UTF-8
| 2,838
| 3.546875
| 4
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: May 04, 2020 at 07:00 AM
-- Server version: 5.7.24
-- PHP Version: 7.2.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `coursera_javascript_jquery_and_json`
--
CREATE DATABASE IF NOT EXISTS `coursera_javascript_jquery_and_json` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `coursera_javascript_jquery_and_json`;
-- --------------------------------------------------------
--
-- Table structure for table `profile`
--
CREATE TABLE IF NOT EXISTS `profile` (
`profile_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`first_name` text,
`last_name` text,
`email` text,
`headline` text,
`summary` text,
PRIMARY KEY (`profile_id`),
KEY `profile_ibfk_2` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
--
-- Truncate table before insert `profile`
--
TRUNCATE TABLE `profile`;
--
-- Dumping data for table `profile`
--
INSERT INTO `profile` (`profile_id`, `user_id`, `first_name`, `last_name`, `email`, `headline`, `summary`) VALUES
(2, 2, 'Fakher', 'Chihawi', 'admin@admin.com', 'PHP Web Developer', 'Summary'),
(4, 2, 'Tom', 'Cruze', 'tom@cruze.com', 'Mission Imposibble', 'Mission Imposibble summary'),
(5, 2, 'Lionel', 'Messi', 'lionel@messi.com', 'Barcelona Footballer of the year', 'Barcelona Footballer of the year summary');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`email` varchar(128) DEFAULT NULL,
`password` varchar(128) DEFAULT NULL,
PRIMARY KEY (`user_id`),
KEY `email` (`email`),
KEY `password` (`password`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
--
-- Truncate table before insert `users`
--
TRUNCATE TABLE `users`;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `name`, `email`, `password`) VALUES
(1, 'Chuck', 'csev@umich.edu', '1a52e17fa899cf40fb04cfc42e6352f1'),
(2, 'Fakher', 'fakherchihawi30@gmail.com', 'php123');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `profile`
--
ALTER TABLE `profile`
ADD CONSTRAINT `profile_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Python
|
UTF-8
| 3,369
| 4.15625
| 4
|
[] |
no_license
|
import string
import random
import re
def request_len():
"""
Prompts the user for the password length and returns the length as an int or -1 if input was invalid
:rtype: int
"""
length = input("Type in your desired password length:\n")
# if the input cannot be converted to an integer, it therefore is not a number and invalid
try:
length = int(length)
return length
except:
print("Invalid input for password length.")
return -1
def request_methods():
"""
Prompts the user for password strength and returns list containing the pool of chars to generate from
(string list). Will repromt if input is invalid.
:rtype: list
"""
# initializing spaces (methods)
chars = "abcdefghijklmnopqrstuvwxyzäöü"
chars_upper = chars.upper()
numbers = "1234567890"
others = "!§$%&/()=?*'+#-.,;:[]{}_^"
strength = str(input("Choose your desired password strength. \n"
"(1) lower case chars \n"
"(2) UPPER CASE CHARS \n"
"(3) numbers 1234567890 \n"
"(4) specials !§$%&/()=?*'+#-.,;:[]{}_^ \n"
"(5) ALL (overwrites)\n"
"(6) ALL without specials (overwrites)\n"
"Format: '1,2,3' for lower and upper case chars and numbers \n"))
# if "," or "1" or "2" or "3" or "4" not in strength or strength[0] not in ["1", "2", "3", "4"]:
# print("Invalid input for strength.")
# quit()
# Just for demonstration purposes, way worse that regex and also not complete
# check if input is correct with regex
# best site ever: https://regex101.com/
if not re.match(r'([123456])?', strength) or not re.match(r'(([123456]),)+([123456])?', strength):
print("Invalid input for password strength.")
request_methods()
else:
strength = strength.split(",")
methods = []
# replace input with actual methods
for method_number in strength:
if method_number == "1":
methods.append(chars)
if method_number == "2":
methods.append(chars_upper)
if method_number == "3":
methods.append(numbers)
if method_number == "4":
methods.append(others)
if method_number == "5":
methods = [chars, chars_upper, numbers, others]
if method_number == "6":
methods = [chars, chars_upper, numbers]
return methods
def main():
"""
Main Function
"""
print("-----------------------")
print("PASSWORD GENERATOR v1.0")
print("-----------------------")
length = 0
# request_len returns -1 if input was invalid. Requests Length until valid value was returned
while(length <= 0):
length = request_len()
methods = request_methods()
password = ""
# for "length" chars
# choose (pseudo) random method
# generate char with chosen method and add it to password
for i in range(length):
method = random.choice(methods)
random_char = random.choice(method)
password = password + random_char
print("Length: " + str(length))
print("Your generated password:")
print(password)
if __name__ == '__main__':
main()
|
C#
|
UTF-8
| 2,916
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
using Timetabling.Internal.Specialized;
namespace Timetabling.Internal.Constraints
{
public class SameDays : TimeConstraint
{
public SameDays(int id, bool required, int penalty, int[] classes)
: base(id, required, penalty, classes)
{
}
protected override (int hardPenalty, int softPenalty) Evaluate(Problem problem, Schedule[] configuration)
{
var penalty = 0;
for (var i = 0; i < Classes.Length - 1; i++)
{
var ci = configuration[i];
for (var j = i + 1; j < Classes.Length; j++)
{
var cj = configuration[j];
var ordays = ci.Days | cj.Days;
if (ordays == ci.Days || ordays == cj.Days)
{
continue;
}
penalty++;
}
}
return Required ? (penalty, 0) : (0, Penalty * penalty);
}
//protected override Solution FixRequired(Solution solution, Random random)
//{
// var problem = solution.Problem;
// const int maxVariableLength = 10;
// if (Classes.Length == 0)
// {
// return solution;
// }
// var variables = problem.TimeVariablesSparse;
// var variable0 = variables[Classes[0]].Shuffle(random);
// var best = solution;
// bool Climb(Solution current, int index)
// {
// int variableLength;
// var variable = variables[index];
// var variableLength = Math.Min(variable.Length, maxVariableLength);
// if (variableLength > 0)
// {
// var @class = classes[index];
// for (var i = 0; i < variableLength; i++)
// {
// var time = variable[i];
// var candidate = current.WithTime(@class, time);
// if (candidate.NormalizedPenalty <= best.NormalizedPenalty)
// {
// best = candidate;
// return true;
// }
// if (index < max)
// {
// if (Climb(candidate, index + 1))
// {
// return true;
// }
// }
// }
// }
// else if (index < max)
// {
// if (Climb(current, index + 1))
// {
// return true;
// }
// }
// return false;
// }
// return best;
//}
}
}
|
C#
|
UTF-8
| 5,118
| 2.859375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace EmergenceGuardian.FFmpeg {
#region Interface
/// <summary>
/// Base class to implement a user interface for FFmpeg processes.
/// </summary>
public interface IUserInterfaceManager {
/// <summary>
/// Gets or sets whether the application has exited.
/// </summary>
bool AppExited { get; set; }
/// <summary>
/// Starts a user interface that will receive all tasks with the specified jobId.
/// </summary>
/// <param name="jobId">The jobId associated with this interface.</param>
/// <param name="title">The title to display.</param>
void Start(object jobId, string title);
/// <summary>
/// Closes the user interface for specified jobId.
/// </summary>
/// <param name="jobId">The jobId to close.</param>
void Stop(object jobId);
/// <summary>
/// Displays a FFmpeg process to the user.
/// </summary>
/// <param name="host">The FFmpegProcess to display.</param>
void Display(IProcessManager host);
/// <summary>
/// When implemented in a derived class, creates the graphical interface window.
/// </summary>
/// <param name="title">The title to display.</param>
/// <param name="autoClose">Whether to automatically close the window after the main task is completed.</param>
/// <returns>The newly created user interface window.</returns>
IUserInterfaceWindow CreateUI(string title, bool autoClose);
/// <summary>
/// When implemented in a derived class, displays an error window.
/// </summary>
/// <param name="host">The task throwing the error.</param>
void DisplayError(IProcessManager host);
}
#endregion
/// <summary>
/// Base class to implement a user interface for FFmpeg processes.
/// </summary>
public abstract class UserInterfaceManagerBase : IUserInterfaceManager {
private List<UIItem> UIList = new List<UIItem>();
/// <summary>
/// Gets or sets whether the application has exited.
/// </summary>
public bool AppExited { get; set; } = false;
/// <summary>
/// Starts a user interface that will receive all tasks with the specified jobId.
/// </summary>
/// <param name="jobId">The jobId associated with this interface.</param>
/// <param name="title">The title to display.</param>
public void Start(object jobId, string title) {
if (jobId == null)
throw new ArgumentNullException(nameof(jobId));
if (!AppExited) {
if (!UIList.Any(u => u.JobId.Equals(jobId)))
UIList.Add(new UIItem(jobId, CreateUI(title, false)));
}
}
/// <summary>
/// Closes the user interface for specified jobId.
/// </summary>
/// <param name="jobId">The jobId to close.</param>
public void Stop(object jobId) {
foreach (var item in UIList.Where(u => u.JobId.Equals(jobId)).ToArray()) {
UIList.Remove(item);
item.Value.Stop();
}
}
/// <summary>
/// Displays a FFmpeg process to the user.
/// </summary>
/// <param name="host">The FFmpegProcess to display.</param>
public void Display(IProcessManager host) {
if (!AppExited) {
UIItem UI = null;
if (host.Options.JobId != null)
UI = UIList.FirstOrDefault(u => u.JobId.Equals(host.Options.JobId));
if (UI != null)
UI.Value.DisplayTask(host);
else {
string Title = !string.IsNullOrEmpty(host.Options.Title) ? host.Options.Title : "FFmpeg Work in Progress";
CreateUI(Title, true).DisplayTask(host);
}
}
}
/// <summary>
/// When implemented in a derived class, creates the graphical interface window.
/// </summary>
/// <param name="title">The title to display.</param>
/// <param name="autoClose">Whether to automatically close the window after the main task is completed.</param>
/// <returns>The newly created user interface window.</returns>
public abstract IUserInterfaceWindow CreateUI(string title, bool autoClose);
/// <summary>
/// When implemented in a derived class, displays an error window.
/// </summary>
/// <param name="host">The task throwing the error.</param>
public abstract void DisplayError(IProcessManager host);
private class UIItem {
public object JobId { get; set; }
public IUserInterfaceWindow Value { get; set; }
public UIItem() { }
public UIItem(object jobId, IUserInterfaceWindow ui) {
this.JobId = jobId;
this.Value = ui;
}
}
}
}
|
Java
|
UTF-8
| 2,039
| 1.984375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 配置跨域
*
* @author auto create
* @since 1.0, 2023-08-03 16:04:37
*/
public class AlipayCloudCloudrunStaticsiteCorsModifyModel extends AlipayObject {
private static final long serialVersionUID = 2168378381175153289L;
/**
* 允许跨域域名列表。
域名列表支持配置*,表示任意来源。
值非*的场景下,格式必须包含协议头http://或者https://,支持带端口。
*/
@ApiListField("access_control_allow_origins")
@ApiField("string")
private List<String> accessControlAllowOrigins;
/**
* 预检请求有效期,单位秒,范围[0, 86400]。
*/
@ApiField("access_control_max_age")
private Long accessControlMaxAge;
/**
* 内部使用,uiam角色扮演token
*/
@ApiField("assume_token")
private String assumeToken;
/**
* 是否开启跨域配置
*/
@ApiField("enable")
private Boolean enable;
/**
* 环境ID,唯一,开通小程序云系统会生成环境ID,请从开通页面获取
*/
@ApiField("env")
private String env;
public List<String> getAccessControlAllowOrigins() {
return this.accessControlAllowOrigins;
}
public void setAccessControlAllowOrigins(List<String> accessControlAllowOrigins) {
this.accessControlAllowOrigins = accessControlAllowOrigins;
}
public Long getAccessControlMaxAge() {
return this.accessControlMaxAge;
}
public void setAccessControlMaxAge(Long accessControlMaxAge) {
this.accessControlMaxAge = accessControlMaxAge;
}
public String getAssumeToken() {
return this.assumeToken;
}
public void setAssumeToken(String assumeToken) {
this.assumeToken = assumeToken;
}
public Boolean getEnable() {
return this.enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getEnv() {
return this.env;
}
public void setEnv(String env) {
this.env = env;
}
}
|
Shell
|
UTF-8
| 361
| 2.859375
| 3
|
[] |
no_license
|
#!/bin/bash
echo "Deleting other version of nvidia drivers..."
sudo apt-get purge nvidia*
echo "Getting PPA..."
sudo add-apt-repository ppa:graphics-drivers
echo "Updating..."
sudo apt-get update && sudo apt-get upgrade
echo "Getting the driver"
sudo apt-get install nvidia-390
echo "Freezing driver version..."
sudo apt-mark hold nvidia-390
echo "Done!"
|
JavaScript
|
UTF-8
| 911
| 2.6875
| 3
|
[] |
no_license
|
import React from 'react'
import MenuBar from '../components/MenuBar.js'
import { Profile, Photos, Cocktails, Pokemon} from '../components/Pages.js'
class MainBox extends React.Component {
constructor(props){
super()
this.state = {
display: 'profile'
}
}
notDry = (e) => {
this.setState({
display: e.target.id
})
}
display = () => {
switch(this.state.display){
case 'profile':
return Profile()
case 'photo':
return Photos()
case 'cocktail':
return Cocktails()
case 'pokemon':
return < Pokemon /> //whenever it's calling for a class for info, use tag < />
}
}
render() {
const detailsToDisplay = <div>Hi, I'm div!</div>
return (
<div>
<MenuBar display = {this.state.display} notDry={this.notDry}/>
{this.display()}
</div>
)
}
}
export default MainBox
|
PHP
|
UTF-8
| 3,776
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace SWindon\XmlToArray;
use DOMDocument;
class XmlToArray {
private $NAME_ATTRIBUTES = '@attributes';
private $NAME_CONTENT = '@value';
private $xml;
/**
* Convert a given XML String to Array
*
* @param string $xmlString
* @return array|boolean false for failure
*/
public function parse($xmlString) {
$doc = new DOMDocument();
$load = $doc->loadXML($xmlString);
if ($load == false) {
return false;
}
$this->xml = $doc->documentElement;
return $this;
}
/**
* Convert a given XML String to Array
*
* @param string $xmlString
* @return array|boolean false for failure
*/
public function toArray($extend=false) {
if(!$root = $this->xml) {
throw new Exception('Cannot parse an Array on NULL',1);
}
$output = [
$root->tagName => $this->DOMDocumentToArray($root,$extend),
];
return $output;
}
/**
* Convert a given XML String to Array
*
* @param string $xmlString
* @return array|boolean false for failure
*/
public function dom() {
if(!$root = $this->xml) {
throw new Exception('Cannot parse Dom on NULL',1);
}
return $root;
}
/**
* Convert DOMDocument->documentElement to array
*
* @param DOMElement $documentElement
* @return array
*/
protected function DOMDocumentToArray($documentElement,$extend=false) {
$return = array();
switch ($documentElement->nodeType) {
case XML_CDATA_SECTION_NODE:
$return = trim($documentElement->textContent);
break;
case XML_TEXT_NODE:
$return = trim($documentElement->textContent);
break;
case XML_ELEMENT_NODE:
for ($count=0, $childNodeLength=$documentElement->childNodes->length; $count<$childNodeLength; $count++) {
$child = $documentElement->childNodes->item($count);
$childValue = $this->DOMDocumentToArray($child,$extend);
if(isset($child->tagName)) {
$tagName = $child->tagName;
if(!isset($return[$tagName])) {
$return[$tagName] = array();
}
$return[$tagName][] = $childValue;
}
elseif($childValue || $childValue === '0') {
$return = (string) $childValue;
}
}
if($extend && $documentElement->attributes->length && !is_array($return)) {
$return = array($this->NAME_CONTENT=>$return);
}
if(is_array($return))
{
if($extend && $documentElement->attributes->length)
{
$attributes = array();
foreach($documentElement->attributes as $attrName => $attrNode)
{
$attributes[$attrName] = (string) $attrNode->value;
}
$return[$this->NAME_ATTRIBUTES] = $attributes;
}
foreach ($return as $key => $value)
{
if(is_array($value) && count($value)==1 && $key!=$this->NAME_ATTRIBUTES)
{
$return[$key] = $value[0];
}
}
}
break;
}
if(empty($return)) $return = null;
return $return;
}
}
|
Markdown
|
UTF-8
| 8,285
| 2.796875
| 3
|
[] |
no_license
|
---
layout: post
title: 7 Day Trip To Bhutan
subtitle: Paro, Thimpu, Punakha and Tiger's Nest
bigimg:
- "/img/bhutanhome.jpg"
tags: [Bhutan, travel]
---
{: .box-note}
***Bhutan:*** *Bhutan, a Buddhist kingdom on the Himalayas’ eastern edge, is known for its monasteries, fortresses (or dzongs) and dramatic landscapes that range from subtropical plains to steep mountains and valleys. In the High Himalayas, peaks such as 7,326m Jomolhari are popular trekking destinations. Paro Taktsang monastery (also known as Tiger’s Nest) clings to cliffs above the forested Paro Valley.*
**Bhutan - Land of The Thunder Dragon**
Landlocked between India and China, **Bhutan** which is also known as the "**the happiest kingdom on Earth**", is a tiny treasure chest of alpine landscapes with unspoilt landscapes, fascinating architecture and of course its wonderful people. With one week in Bhutan, you can explore this country to the fullest, making memories that will last forever.
In these 7 days in Bhutan, we visited the 3 major cities: Thimpu, Punakha and Paro. The capital city of Thimpu is known for its landmark Buddhist temples, Punakha is known for its picture perfect scenic views and Paro is known for its striking beauty that is sure to take your breath away.
***Day 1:***<br>
We took an early morning flight from Mumbai to Indira Gandhi International Airport, Delhi. From Delhi, we proceeded towards **Paro**. On our way to Paro, we experienced one of the most spectacular mountain flights. Flying from the heat of the plains of India, we witnessed a series of the world's highest mountain peaks. We descended into the high mountains. As the aircraft lowered, we did not find any airstrip or city. Instead, we enjoyed the view of the approaching Paro valley, the alpine forests, little monasteries, temples and farmhouses. Before the plane touched the runway, we got a glimpse of the fertile **Paro valley**, the **Paro chu (river)** and the magnificient **Paro Dzong**. On arrival at the airport, we were greeted warmly by the local representatives and we proceeded towards the capital city, **Thimpu**.
<img src="/img/bhutan1.PNG" alt="Bhutan">
<img src="/img/bhutan2.PNG" alt="Bhutan">
***Day 2:***<br>
After we had our breakfast, we proceeded for the city tour of **Thimpu**. **Thimpu** is unique in its own way. You will find no traffic lights in **Thimpu**. The people of Bhutan have adopted their own version of the British - Indian colonial times traffic policemen who are capable enough of handling the traffic with their elaborate hand gestures. We visited the **National Memorial Chorten**: a stupa dedicated to the third king of Bhutan, the **Buddha Statue**, and the **Takin Zoo**. We drove downhill to catch a glimpse of the **Tashichho Dzong**. We visited the **National Library** and the **Folk Heritage Museum**. In the afternoon, we took a short walk to the Handicrafts Bazaar to view the traditional arts of Bhutan. We had the evening for ourselves so we walked to the main city from the **Clock Tower Square** for shopping.
<img src="/img/bhutan3.JPG" alt="Bhutan">
<img src="/img/bhutan4.PNG" alt="Bhutan">
<img src="/img/bhutan5.PNG" alt="Bhutan">
<img src="/img/bhutan6.PNG" alt="Bhutan">
<img src="/img/bhutan7.JPG" alt="Bhutan">
***Day 3:***<br>
We proceeded to the low lands of the **Punakha valley** touching the **Dochula pass** (10,000 ft). We had a stop in the **Hongtsho village**, at the immigration check point to stamp in our permit. This was our first mountain pass in the western part of Bhutan. We found the **108 Druk Wangyal chortens** on the top of the pass where the ridges were draped in colorful prayer flags. **Dochula Pass** is at a wonderful location as it offers a stunning 360 degree panaromic view of the Himalayan range. We were lucky enough to have the weather clear on our arrival. The view from the **Dochula pass** was scenic with snowcapped mountains forming a majestic backdrop to the tranquility of the 108 chortens gracing the mountain pass. We were able to see the highest peaks towards the north, **Gangar Punsum** being one of them. It is the highest unclimbed mountain peak (24,000 ft) in the world. We reached **Punakha** in the afternoon. After our lunch, we visited the majestic **Punakha Dzong** which is placed strategically at the junction of the **Pho Chu** and **Mo Chu** rivers.
<img src="/img/bhutan8.JPG" alt="Bhutan">
<img src="/img/bhutan9.JPG" alt="Bhutan">
<img src="/img/bhutan10.JPG" alt="Bhutan">
<img src="/img/bhutan11.JPG" alt="Bhutan">
***Day 4:***<br>
We drove to the beautiful **Gangtey valley** via **Wangdiphodrang Dzong** which is located on a ridge (4,430 ft) that overlooks the highway that forks to the east and south of the country. It is an old town with narrow streets having single storied shops. It is also the gateway to central and eastern Bhutan. The Gangtey Valley is one of the most beautiful open valleys in Bhutan and is the winter home to the endangered black necked cranes (Grus Nigricllis) which migrate to this valley around mid-November from Tibet. These cranes have for centuries captured the human imagination with their intelligence, poise, sociality, beauty and freedom which have given rise to several myths, legends, folktales and songs. The birds fly back across the Himalayas to their summer home towards Tibet and China. The Gangtey village is small and dominated by the yellow roofed Gangtey monastery. We returned to our hotels in the evening.
<img src="/img/bhutan12.JPG" alt="Bhutan">
<img src="/img/bhutan13.JPG" alt="Bhutan">
<img src="/img/bhutan14.JPG" alt="Bhutan">
<img src="/img/bhutan15.JPG" alt="Bhutan">
***Day 5:***<br>
Our next destination was **Paro**. After breakfast, we drove to Paro via the Babesa express highway. Upon reaching the Chuzom check post, we stopped for a while at the bridge. The bridge and its ambience is enough to refresh anybody's mind. We stretched our legs and took a stroll over the bridge before proceeding further. We checked into the hotel around evening and relaxed ourselves for the following day, as it was the main highlight of the tour.
<img src="/img/bhutan16.JPG" alt="Bhutan">
<img src="/img/bhutan17.JPG" alt="Bhutan">
<img src="/img/bhutan18.PNG" alt="Bhutan">
<img src="/img/bhutan19.JPG" alt="Bhutan">
***Day 6:***<br>
The highlight of the tour: Tiger's Nest. **Tiger's Nest**, or the **Paro Taktsang** is a major tourist attraction in Bhutan. Paro Taktsang, is a prominent Himalayan Buddhist sacred site and the temple complex is located in the cliffside of the upper Paro valley in Bhutan. A temple complex was first built in 1692, around the Taktsang Senge Samdup cave where Guru Padmasambhava is said to have meditated for four months in the 8th century. Hiking is the only way to reach the temple. The hike to Tiger's Nest is a moderate one and takes about 3 - 5 hours. Anybody with an average level of fitness can do it. The trek to Tiger's Nest is definitely worth it. The trail to the monastery is a wide, dirt trail. It is uphill the entire way but not very steep. This hike definitely has the best views to offer!
<img src="/img/bhutan20.JPG" alt="Bhutan">
<img src="/img/bhutan21.JPG" alt="Bhutan">
<img src="/img/bhutan22.JPG" alt="Bhutan">
<img src="/img/bhutan23.JPG" alt="Bhutan">
<img src="/img/bhutan24.JPG" alt="Bhutan">
<img src="/img/bhutan25.JPG" alt="Bhutan">
<img src="/img/bhutan26.JPG" alt="Bhutan">
<img src="/img/bhutan27_2.JPG" alt="Bhutan">
<img src="/img/bhutan27.JPG" alt="Bhutan">
The feeling of accomplishment you get when you reach here is just inexplicable.
<img src="/img/bhutan28.JPG" alt="Bhutan">
After the trek, we returned to tha camp and proceeded to the hotel.
***Day 7:***<br>
The last day of the tour. Nobody likes the last day of their tour but sadly, just like bad things, good things don't last forever. We had our breakfast and proceeded to the Paro Airport.
On our flight back to Delhi, we were graced with the view of the world's tallest mountain peak: **Mt. Everest**.
<img src="/img/bhutan30.JPG" alt="Bhutan">
The holiday concluded on a good note. We had fun and a lot of memories to cherish.
<img src="/img/bhutan31.JPG" alt="Bhutan">
***BHUTAN*** *is a must visit for every travel enthusiast!*
|
Java
|
UTF-8
| 3,723
| 2.390625
| 2
|
[] |
no_license
|
package com.fxlc.zklm.test;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.fxlc.zklm.R;
import com.fxlc.zklm.bean.Truck;
import com.fxlc.zklm.db.MySqliteHelper;
import com.fxlc.zklm.util.UriUtil;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class SqlActivity extends AppCompatActivity {
MySqliteHelper helper;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sql);
findViewById(R.id.open).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Intent it = new Intent(Intent.ACTION_GET_CONTENT);
// it.setType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置类型
// it.addCategory(Intent.CATEGORY_OPENABLE);
// startActivityForResult(it, 1);
readDB();
}
});
helper = new MySqliteHelper(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
String uri = data.getData().toString();
Log.d("sql", uri);
String path = UriUtil.getRealFilePath(this, data.getData());
readExcel(path);
}
}
public void readExcel(String path) {
db = helper.getWritableDatabase();
try {
InputStream is = new FileInputStream(path);
Workbook book = Workbook.getWorkbook(is);
int num = book.getNumberOfSheets();
Sheet sheet = book.getSheet(0);
int rows = sheet.getRows();
int cols = sheet.getColumns();
// getCell(Col,Row)获得单元格的值
for (int i = 1; i < rows; ++i) {
Truck truck = new Truck();
truck.setBrand(sheet.getCell(0, i).getContents());
Log.d("excel", truck.getBrand());
truck.setStyle(sheet.getCell(1, i).getContents());
truck.setDrive(sheet.getCell(4, i).getContents());
truck.setSoup(sheet.getCell(2, i).getContents());
saveTruck(truck);
}
book.close();
db.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveTruck(Truck truck) {
String sql = "insert into truck(brand,style,drive,soup) values (?,?,?,?)";
db.execSQL(sql, new String[]{truck.getBrand(), truck.getStyle(), truck.getDrive(), truck.getSoup()});
}
public void readDB() {
db = helper.getWritableDatabase();
String sql = "select * from truck";
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
String brand = cursor.getString(1);
String style = cursor.getString(2);
String drive = cursor.getString(3);
String soup = cursor.getString(4);
Log.d("database", brand + "-" + style + "-" + drive + "-" + soup);
}
}
}
|
Java
|
UTF-8
| 263
| 1.835938
| 2
|
[] |
no_license
|
package com.itkweb.xwinga.service;
import java.util.List;
import java.util.Map;
import com.itkweb.xwinga.model.Box;
public interface XWingService {
public List<Box> getBoxList();
public void buildTeams(Map<Box, Integer> boxesSelection, int teamPoints);
}
|
Java
|
UTF-8
| 5,356
| 1.945313
| 2
|
[] |
no_license
|
package com.sweethill.orderstore.web.screens.productspecification;
import com.haulmont.cuba.core.app.UniqueNumbersService;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.global.PersistenceHelper;
import com.haulmont.cuba.gui.Notifications;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.model.CollectionPropertyContainer;
import com.haulmont.cuba.gui.screen.*;
import com.sweethill.orderstore.entity.Goods;
import com.sweethill.orderstore.entity.Units;
import com.sweethill.orderstore.entity.production.management.ProductSpecification;
import com.sweethill.orderstore.entity.production.management.RowMaterial;
import com.sweethill.orderstore.service.OrderStoreService;
import javax.inject.Inject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@UiController("orderstore_ProductSpecification.edit")
@UiDescriptor("product-specification-edit.xml")
@EditedEntityContainer("productSpecificationDc")
@LoadDataBeforeShow
public class ProductSpecificationEdit extends StandardEditor<ProductSpecification> {
@Inject
private OrderStoreService orderStoreService;
@Inject
private DataGrid<RowMaterial> materialsTable;
@Inject
private Notifications notifications;
@Inject
private MessageBundle messageBundle;
@Inject
private Metadata metadata;
@Inject
private CollectionPropertyContainer<RowMaterial> materialsDC;
private String execAction;
@Inject
private PickerField<Units> unitField;
@Inject
private UniqueNumbersService uniqueNumbersService;
@Subscribe("productField")
public void onProductFieldValueChange(HasValue.ValueChangeEvent<Goods> event) {
Goods good = event.getValue();
if (good != null)
unitField.setValue(good.getUnit());
}
@Subscribe
public void onInitEntity(InitEntityEvent<ProductSpecification> event) {
ProductSpecification productSpecification = event.getEntity();
productSpecification.setSpecNumber(Long.toString(uniqueNumbersService.getNextNumber(("SpecificationNumber"))));
productSpecification.setOwner(orderStoreService.getCurrentUserOwner());
productSpecification.setSpecDate(new Date());
productSpecification.setActive(true);
}
@Subscribe
public void onBeforeShow(BeforeShowEvent event) {
ProductSpecification productSpecification = getEditedEntity();
if (!PersistenceHelper.isNew(productSpecification)) {
String caption = messageBundle.getMessage("editInstanceCaption");
Date specdate = productSpecification.getSpecDate();
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
caption = caption
.replace("%n", productSpecification.getSpecNumber())
.replace("%d", dateFormat.format(specdate));
getWindow().setCaption(caption);
}
}
@Subscribe("materialsTable.create")
public void onMaterialsTableCreate(Action.ActionPerformedEvent event) {
if (materialsTable.isEditorActive()) {
notifications.create()
.withCaption(messageBundle.formatMessage("materialEditMessage"))
.show();
return;
}
RowMaterial rowMaterial = metadata.create(RowMaterial.class);
RowMaterial merged = getScreenData().getDataContext().merge(rowMaterial);
materialsDC.getMutableItems().add(merged);
execAction = "create";
materialsTable.edit(merged);
}
@Subscribe("materialsTable.edit")
public void onMaterialsTableEdit(Action.ActionPerformedEvent event) {
RowMaterial selected = materialsTable.getSingleSelected();
if (selected != null) {
execAction = "edit";
materialsTable.edit(selected);
} else {
notifications.create()
.withCaption(messageBundle.formatMessage("materialSelectItem"))
.show();
}
}
@Subscribe("materialsTable")
public void onMaterialsTableEditorPreCommit(DataGrid.EditorPreCommitEvent event) {
ProductSpecification productSpecification = getEditedEntity();
RowMaterial rowMaterial = (RowMaterial) event.getItem();
rowMaterial.setProductSpecification(productSpecification);
}
@Subscribe("materialsTable")
public void onMaterialsTableEditorClose(DataGrid.EditorCloseEvent event) {
RowMaterial rowMaterial = (RowMaterial) event.getItem();
execAction = (execAction == null) ? "edit" : execAction;
if (execAction.equals("create")) {
materialsDC.getMutableItems().remove(rowMaterial);
getScreenData().getDataContext().remove(rowMaterial);
}
execAction = null;
}
@Subscribe("materialsTable")
public void onMaterialsTableEditorOpen(DataGrid.EditorOpenEvent editorOpenEvent ) {
Map fields = editorOpenEvent.getFields();
PickerField fieldGood = (PickerField) fields.get("good");
Field fieldUnit = (PickerField) fields.get("unit");
fieldGood.addValueChangeListener(e -> {
Goods good = (Goods) fieldGood.getValue();
if (good != null)
fieldUnit.setValue(good.getUnit());
});
}
}
|
Python
|
UTF-8
| 1,455
| 4.28125
| 4
|
[] |
no_license
|
# https://www.interviewcake.com/python-interview-questions
# Slicing lists from the end
# We want to run some analytics on our investments. To start, we're given a list containing
# the balance at the end of the day for some number of days. The last item in the list
# represents yesterday's closing balance and each previous item refers to the day before.
#
# daily_balances = [107.92, 108.67, 109.86, 110.15]
# Python 2.7
# The first step in the process is to grab adjacent items in the list. To get started, we want
# a function that takes in our list of daily_balances and prints pairs of adjacent balances fo
# r the last 3 days:
#
# show_balances(daily_balances)
# Python 2.7
# should print:
#
# "slice starting 3 days ago: [108.67, 109.86]"
# "slice starting 2 days ago: [109.86, 110.15]"
#
# "slice starting 3 days ago: [108.67, 109.86]"
# "slice starting 2 days ago: [109.86, 110.15]"
daily_balances = [107.92, 108.67, 109.86, 110.15]
def show_balances(daily_balances_):
num_balances = len(daily_balances_)
# do not include -1 because that slice will only have 1 balance, yesterday
for day in range(num_balances - 3, num_balances - 1):
balance_slice = daily_balances_[day: day + 2]
days_ago = num_balances - day
# use positive number for printing
print("slice starting %d days ago: %s" % (abs(days_ago), balance_slice))
show_balances(daily_balances)
print(daily_balances[-2: -1])
|
Java
|
UTF-8
| 570
| 3.453125
| 3
|
[] |
no_license
|
package BasicPrograms;
import java.util.Scanner;
public class WindChill {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Temprature(Number Should be above 50)");
double t = sc.nextDouble();
System.out.println("Enter Wind Speed(Number Should be between 3 to 120)");
double v = sc.nextDouble();
if (t > 50 && v < 120 && v > 3) {
double windchill = (35.74 + 0.6215 * t + (0.4275 * t - 35.75) * Math.pow(v, 0.16));
System.out.println("WindChill Value :- " + windchill);
}
}
}
|
C#
|
UTF-8
| 1,513
| 2.78125
| 3
|
[] |
no_license
|
using System;
using KataWordWrap2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace WordWrapTest
{
[TestClass]
public class WordWrapTest
{
[TestMethod]
public void WrapTest_WhenShort_ThenNoWrap()
{
Assert.AreEqual("text", Wrapper.Wrap("text", 10));
}
[TestMethod]
public void WrapTest_WhenBreakAtWordEnd_ThenReplaceSpaceWithBreak()
{
Assert.AreEqual("text text\ntext", Wrapper.Wrap("text text text", 9));
}
[TestMethod]
public void WrapTest_WhenMoreLines_ThenReplaceSpaceWithBreak()
{
Assert.AreEqual("text text\ntext text\ntext", Wrapper.Wrap("text text text text text", 9));
}
[TestMethod]
public void WrapTest_WhenBreakAtSpace_ThenReplaceSpaceWithBreak()
{
Assert.AreEqual("text text\ntext", Wrapper.Wrap("text text text", 10));
Assert.AreEqual("text text\ntext", Wrapper.Wrap("text text text", 11));
Assert.AreEqual("text text\ntext", Wrapper.Wrap("text text text", 12));
}
[TestMethod]
public void WrapTest_WhenBreakInWord_ThenReplaceLastSpace()
{
Assert.AreEqual("text\ntext\ntext", Wrapper.Wrap("text text text", 8));
}
[TestMethod]
public void WrapTest_WhenLongerWordThanLine_ThenBreakInWordMiddle()
{
Assert.AreEqual("textt\next\ntext", Wrapper.Wrap("texttext text", 5));
}
}
}
|
TypeScript
|
UTF-8
| 650
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
import { Entity } from "../../../../../src/decorator/entity/Entity"
import { Index } from "../../../../../src/decorator/Index"
import { PrimaryGeneratedColumn } from "../../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { Column } from "../../../../../src/decorator/columns/Column"
import { Profile } from "./Profile"
@Entity()
@Index("index_name_english", ["nameEnglish"], { unique: true })
@Index("index_profile_job", ["profile.job"])
export class Customer {
@PrimaryGeneratedColumn()
id: number
@Column()
nameHebrew: string
@Column()
nameEnglish: string
@Column(() => Profile)
profile: Profile
}
|
Python
|
UTF-8
| 13,273
| 2.875
| 3
|
[] |
no_license
|
import traceback
import MyPlane
import Enemy
import Supply
import random
import pygame
pygame.init()
pygame.mixer.init()
pygame.mixer.set_num_channels(20)
#主屏幕、背景
size=[width,height]=[480,700]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("飞机大战".center(110))
bg_img=pygame.image.load("img/background.png").convert_alpha()
#暂停、继续按钮图标
pause_img=pygame.image.load("img/pause.png").convert_alpha()
pause_pressed_img=pygame.image.load("img/pause_pressed.png").convert_alpha()
resume_img=pygame.image.load("img/resume.png").convert_alpha()
resume_pressed_img=pygame.image.load("img/resume_pressed.png").convert_alpha()
pause_rect=pause_img.get_rect()
pause_rect.right=width-10
pause_rect.top=5
pause_bg=bg_img.subsurface(pause_rect)
#音乐、音效
pygame.mixer.music.load("sound/bg_music.ogg")
pygame.mixer.music.set_volume(0.1)
button_sound=pygame.mixer.Sound("sound/button.wav")
button_sound.set_volume(0.2)
supply_sound=pygame.mixer.Sound("sound/supply.wav")
supply_sound.set_volume(0.2)
upgrade_sound=pygame.mixer.Sound("sound/upgrade.wav")
upgrade_sound.set_volume(0.2)
def main():
#播放背景音乐
pygame.mixer.music.play(-1)
#我的飞机,设定生命
myplane=MyPlane.MyPlane(size)
myplane.life=3
#敌机
enemies=pygame.sprite.Group()
enemies1=pygame.sprite.Group()
enemies2=pygame.sprite.Group()
enemies3=pygame.sprite.Group()
def add_enemy1(n):
for i in range(n):
e=Enemy.Enemy1(size)
enemies.add(e)
enemies1.add(e)
def add_enemy2(n):
for i in range(n):
e=Enemy.Enemy2(size)
enemies.add(e)
enemies2.add(e)
def add_enemy3(n):
for i in range(n):
e=Enemy.Enemy3(size)
enemies.add(e)
enemies3.add(e)
def speedup(group,increment):
for each in group:
each.speed+=increment
add_enemy1(15)
add_enemy2(4)
add_enemy3(2)
#补给定时,设置定时事件
supplies=[Supply.Bullet_Supply(size),Supply.Bomb_Supply(size),Supply.Super_Supply(size)]
for each in supplies:
each.active=0
SUPPLY_COME=pygame.USEREVENT
supply_time=300
supply_n=supply_time
pygame.time.set_timer(SUPPLY_COME,100)
BULLET2_RESET=pygame.USEREVENT+1
BULLET3_RESET=pygame.USEREVENT+2
#分数
score=0
score_font=pygame.font.Font("font/xiaozhuan.ttf",36)
#设置难度级别
level=1
level_font=pygame.font.Font("font/xiaozhuan.ttf",36)
level_dict=["简单","普通","困难","王者","地狱"]
def levelup():
nonlocal level
if level==1:
if score>5000:
level=2
upgrade_sound.play()
add_enemy1(3)
add_enemy2(2)
add_enemy3(1)
speedup(enemies1,1)
elif level==2:
if score>30000:
level=3
upgrade_sound.play()
add_enemy1(5)
add_enemy2(3)
add_enemy3(2)
speedup(enemies1,1)
speedup(enemies2,1)
elif level==3:
if score>100000:
level=4
upgrade_sound.play()
add_enemy1(5)
add_enemy2(3)
add_enemy3(2)
speedup(enemies1,1)
speedup(enemies2,1)
elif level==4:
if score>300000:
level=5
upgrade_sound.play()
add_enemy1(5)
add_enemy2(3)
add_enemy3(2)
speedup(enemies,1)
running=1
paused=0
usebomb=0
ending=0
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=0
break
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_UP or event.key==pygame.K_w:
myplane.up+=1
elif event.key==pygame.K_DOWN or event.key==pygame.K_s:
myplane.down+=1
elif event.key==pygame.K_LEFT or event.key==pygame.K_a:
myplane.left+=1
elif event.key==pygame.K_RIGHT or event.key==pygame.K_d:
myplane.right+=1
elif event.key==pygame.K_SPACE:
if not paused:
usebomb=1
elif event.type==pygame.KEYUP:
if event.key==pygame.K_UP or event.key==pygame.K_w:
myplane.up-=1
elif event.key==pygame.K_DOWN or event.key==pygame.K_s:
myplane.down-=1
elif event.key==pygame.K_LEFT or event.key==pygame.K_a:
myplane.left-=1
elif event.key==pygame.K_RIGHT or event.key==pygame.K_d:
myplane.right-=1
elif event.type==pygame.MOUSEBUTTONDOWN:
if event.button==1:
if pause_rect.collidepoint(event.pos):
if paused and resume_img.get_at((event.pos[0]-pause_rect.left,event.pos[1]-pause_rect.top))[3]:
paused=0
button_sound.play()
pygame.time.set_timer(SUPPLY_COME,100)
if myplane.bullet_type==2:
pygame.time.set_timer(BULLET2_RESET,100)
if myplane.bullet_type==3:
pygame.time.set_timer(BULLET3_RESET,100)
pygame.mixer.music.unpause()
pygame.mixer.unpause()
elif not paused and pause_img.get_at((event.pos[0]-pause_rect.left,event.pos[1]-pause_rect.top))[3]:
paused=1
usebomb=0
button_sound.play()
pygame.time.set_timer(SUPPLY_COME,0)
if myplane.bullet_type==2:
pygame.time.set_timer(BULLET2_RESET,0)
if myplane.bullet_type==3:
pygame.time.set_timer(BULLET3_RESET,0)
pygame.mixer.music.pause()
pygame.mixer.pause()
elif event.type==SUPPLY_COME:
supply_n-=1
if not supply_n:
supply_n=supply_time
supply_sound.play()
rand=random.randint(0,9)
if rand<5:
supplies[0].reset()
elif rand<9:
supplies[1].reset()
else:
supplies[2].reset()
elif event.type==BULLET2_RESET or event.type==BULLET3_RESET:
myplane.bullet_check()
if running:
if paused:
screen.blit(pause_bg,pause_rect)
pos=pygame.mouse.get_pos()
if pause_rect.collidepoint(pos) and resume_img.get_at((pos[0]-pause_rect.left,pos[1]-pause_rect.top))[3]:
screen.blit(resume_pressed_img,pause_rect)
else:
screen.blit(resume_img,pause_rect)
else:
screen.blit(bg_img,(0,0))
#敌机行动
for each in enemies:
each.move()
#炸弹行动
if usebomb:
usebomb=0
score+=myplane.usebomb(enemies)
#子弹行动
myplane.bullet_make()
myplane.bullet_move()
score+=myplane.bullet_collide(enemies)
#飞机行动
myplane.move()
score+=myplane.collide(enemies)
#补给行动
for each in supplies:
each.move()
myplane.getsupply(supplies)
#敌机画出
for each in enemies3:
each.show(screen)
for each in enemies2:
each.show(screen)
for each in enemies1:
each.show(screen)
#子弹画出
myplane.bullet_show(screen)
#补给画出
for each in supplies:
each.show(screen)
#飞机画出(包括炸弹、生命)
myplane.show(screen)
#分数画出
screen.blit(score_font.render("Score: %09d"%score,1,(0,0,0)),(10,5))
#等级画出
levelup()
screen.blit(level_font.render("Level: %s"%level_dict[level-1],1,(0,0,0)),(10,5+score_font.get_linesize()))
#按钮画出
pos=pygame.mouse.get_pos()
if pause_rect.collidepoint(pos) and pause_img.get_at((pos[0]-pause_rect.left,pos[1]-pause_rect.top))[3]:
screen.blit(pause_pressed_img,pause_rect)
else:
screen.blit(pause_img,pause_rect)
if myplane.life<0:
running=0
ending=1
pygame.display.flip()
pygame.time.delay(20)
if ending:
pygame.mixer.music.stop()
pygame.mixer.stop()
pygame.time.set_timer(SUPPLY_COME,0)
pygame.time.set_timer(BULLET2_RESET,0)
pygame.time.set_timer(BULLET3_RESET,0)
with open("record.txt",'r') as file:
try:
best_score=int(file.read())
except:
best_score=0
if best_score<score:
best_score=score
with open("record.txt",'w') as file:
file.write(str(score))
end_font=pygame.font.Font("font/xiaozhuan.ttf",50)
font1=score_font.render("Best Score:%d"% best_score,1,(0,0,0))
font1_rect=font1.get_rect()
font1_rect.left,font1_rect.top=50,50
font2=end_font.render("Your Score:",1,(0,0,0))
font2_rect=font2.get_rect()
font2_rect.centerx=width//2
font2_rect.top=230
font3=end_font.render("%d"%score,1,(0,0,0))
font3_rect=font3.get_rect()
font3_rect.centerx=width//2
font3_rect.top=300
gameover_img=pygame.image.load("img/gameover.png").convert_alpha()
gameover_rect=gameover_img.get_rect()
gameover_rect.centerx=width//2
gameover_rect.top=420
gameover_pressed_img=pygame.image.load("img/gameover_pressed.png").convert_alpha()
gameover_pressed_rect=gameover_pressed_img.get_rect()
gameover_pressed_rect.center=gameover_rect.center
restart_img=pygame.image.load("img/restart.png").convert_alpha()
restart_rect=gameover_img.get_rect()
restart_rect.centerx=width//2
restart_rect.top=480
restart_pressed_img=pygame.image.load("img/restart_pressed.png").convert_alpha()
restart_pressed_rect=restart_pressed_img.get_rect()
restart_pressed_rect.center=restart_rect.center
while ending:
for event in pygame.event.get():
if event.type==pygame.QUIT:
ending=0
break
if event.type==pygame.MOUSEBUTTONDOWN:
if event.button==1:
if restart_rect.collidepoint(event.pos) and restart_img.get_at((event.pos[0]-restart_rect.left,event.pos[1]-restart_rect.top))[3]:
Enemy.enemy3_flying_playlist.clear()
return 1
elif gameover_rect.collidepoint(event.pos) and gameover_img.get_at((event.pos[0]-gameover_rect.left,event.pos[1]-gameover_rect.top))[3]:
return 0
if ending:
screen.blit(bg_img,(0,0))
screen.blit(font1,font1_rect)
screen.blit(font2,font2_rect)
screen.blit(font3,font3_rect)
pos=pygame.mouse.get_pos()
if gameover_rect.collidepoint(pos) and gameover_img.get_at((pos[0]-gameover_rect.left,pos[1]-gameover_rect.top))[3]:
screen.blit(gameover_pressed_img,gameover_pressed_rect)
else:
screen.blit(gameover_img,gameover_rect)
if restart_rect.collidepoint(pos) and restart_img.get_at((pos[0]-restart_rect.left,pos[1]-restart_rect.top))[3]:
screen.blit(restart_pressed_img,restart_pressed_rect)
else:
screen.blit(restart_img,restart_rect)
pygame.display.flip()
pygame.time.delay(20)
return 0
if __name__=="__main__":
restart=1
while restart:
try:
restart=main()
except:
restart=0
traceback.print_exc()
a=input()
pygame.quit()
|
Python
|
UTF-8
| 230
| 3.109375
| 3
|
[] |
no_license
|
index_of_synthesis = float(input())
if index_of_synthesis < 2:
print("Analytic")
elif index_of_synthesis <= 2 >= 3:
print("Synthetic")
elif index_of_synthesis > 3:
print("Polysynthetic")
else:
print("Checker.com")
|
Python
|
UTF-8
| 3,866
| 3.25
| 3
|
[] |
no_license
|
"""Calibration class """
import numpy as np
from pyspec.errors import CalibrationError
MIN_CALIBRATION_POINTS = 5
ACCEPTED_FORMATS = [".dat"]
class Calibration():
"""Computes and stores the wavelength solution for flux calibration
Clas methods
------------
from_file
Methods
-------
__init__
Attributes
----------
calibration_points: np.ndarray
Named array with the calibration points. Must have fields "X" and
"wavelength(Angs)"
wave_solution: np.Polynomial
Wavelength solution
"""
def __init__(self, calibration_points):
"""Initialize class instance
Arguments
---------
calibration_points: np.ndarray
Named array with the calibration points. Must have fields "x" and
"wave"
"""
self.calibration_points = calibration_points
if self.calibration_points.size < MIN_CALIBRATION_POINTS:
raise CalibrationError(
"Compute Calibration: Error: too few points")
# check that the pairs of (x, wave) are properly ordered
for item1, item2 in zip(calibration_points[:-1], calibration_points[1:]):
if item1["x"] >= item2["x"] or item1["wave"] >= item2["wave"]:
raise CalibrationError(
"Compute Calibration: Error: points are not properly sorted. "
"Each point should have larger X and wavelength than the "
"previous one")
# compute the wavelength solution
self.wave_solution = np.polynomial.Polynomial.fit(
calibration_points["x"],
calibration_points["wave"],
3)
def calibrate(self, size):
"""Return the wavelength solution
Arguments
---------
size: int
Size of the spectrum array
"""
return self.wave_solution(np.arange(size))
@classmethod
def from_file(cls, filename):
"""Compute the wavelength solution from read data points and store it as
a class intance
Arguments
---------
filename: str
Name of the file containing the calibration points
Return
------
instance: Calibration
The initialized instance
"""
calibration_points = np.genfromtxt(filename, names=True)
return cls(calibration_points)
@classmethod
def from_points(cls, calibration_points_dict):
"""Compute the wavelength solution from a dictionary of data points and
store it as a class intance
Arguments
---------
calibrationPoints: dict
Dictionary with the calibration points. Keys are the position in pixels and
values are the wavelengths
Return
------
instance: Calibration
The initialized instance
"""
calibration_points = np.array(
list(calibration_points_dict.items()),
dtype=[("x", float), ("wave", float)]
)
return cls(calibration_points)
def save(self, filename):
"""Save calibration points
Raise
-----
CalibrationError if the filename does not have the correct format
"""
# check filename extension
extension = None
for format_check in ACCEPTED_FORMATS:
if filename.endswith(format_check):
extension = format_check
if extension is None:
raise CalibrationError(
"Calibration: 'filename' has incorrect extension. Valid"
"extensions are " + ", ".join(ACCEPTED_FORMATS)
)
with open(filename, "w", encoding="UTF-8") as file:
file.write("# x wave\n")
for item in self.calibration_points:
file.write(f"{item['x']} {item['wave']}\n")
|
Markdown
|
UTF-8
| 5,763
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
# SeedHq
[](https://travis-ci.org/cagosta/SeedHq)
## Introduction
Elegant customizable inheritance, attributes and events in JavaScript.
* **inheritance**, `Seed.extend` and the `'+method'` convention help you inherit fast and easily, see [Extend with Seed.js](documentation/Extendable.md)
* **attributes**, with easy and flexible `options` keyword, see [Manage attributes with 'options'](documentation/options.md)
* **events** and **subscriptions**, to avoid object persistance due to dirty event subscriptions see [Use events](documentation/Events.md)
* **sub**, build a sub object of a parent one see [What is it sub ?](documentation/sub.md)
## Basic Usage
### Extend your own Constructors
```js
var Fruit = S.extend({
options : {
// by default the fruit is Tasty
isTasty : true,
//and no one owns it
owner : null
},
// i like to taste any fruit
taste : function() {
console.log('I like to taste a fruit');
},
dump : function() {
return {
objectType : 'a fruit'
}
}
});
var Banana = Fruit.extend({
// by default the banana is owned by a banana eater and is yellow
'+options' : {
owner : 'banana eater',
color : 'yellow'
},
// but the taste of the banana depends if it tasty
'+taste' : function() {
console.log(this.isTasty ? 'GREAT' : 'beurk');
},
'+dump' : function() {
return {
color : this.color
}
}
});
```
### Instanciate them
```
var oldBanana = new Banana({
isTasty : false,
color : 'black',
owner : 'me'
});
// options are set as attributes in the instance
oldBanana.isTasty
//=> false
// +taste in Banana is executed after taste in Fruit
oldBanana.taste();
// I like to test fruits
// beurk
var favoriteBanana = new Banana();
favoriteBanana.taste();
// I like to test fruits
// GREAT
favoriteBanana.dump();
//=> { color : 'yellow', objectType : 'a fruit'}
```
## More infos/usages
Seed.js is a package of 4 little Tools :
* **Extendable**, (in SeedHq/Extendable), extend objects protoypes gracefully with +/- convention see [Extend with Seed.js](documentation/Extendable.md)
* **Eventable**, (in SeedHq/Eventable), emit and subscribe event properly, see [Use events](documentation/Eventable.md)
* **options**, (in SeedHq), elegant attributes set. see [Manage attributes with 'options'](documentation/options.md)
* **sub**, (in SeedHq), elegant attributes set [What is sub ?](documentation/sub.md)
## Demo ##
See [cagosta.github.io/Seed](http://cagosta.github.io/Seed)
## Install ##
SeedHq is developed as [AMD module](http://requirejs.org/docs/whyamd.html) but can be installed with npm, bower or old-fashioned src=".min.js".
#### With npm: ####
```
npm install seedhq
```
and use it with nodejs:
```
var Seed = require('seedgq')
```
#### With bower: ####
```
bower install Seed
```
Point `Seed` to `[bower_components_path]/SeedHq/app/Seed.js` into your requirejs path config
and load it with requirejs:
```javascript
require(['Seed/Seed'], function( Seed ){
})
```
#### With src=" .min.js" ####
Inside the `dist` folder, [download latest standalone minified version](https://raw.github.com/cagosta/SeedHq/master/dist/SeedHq-latest-standalone-min.js) or [development version](https://raw.github.com/cagosta/SeedHq/master/dist/SeedHq-latest-standalone.js) and include it in your html page:
```html
<script src="[path_to_source]/SeedHq-latest-standalone-min.js%>"></script>
```
The module is available via the scope
```javascript
window.SeedHq
```
## To do ##
* rewrite old tests with mocha
* document plugins
## Documentation ##
See jsdoc-generated documentation in /documentation
### Folder Structure ###
app -> development files
|- bower_components -> bower front-end packages
|- main.js -> main file for browser and node.js, handle AMD config
|- seed_hq -> main AMD module
test -> unit tests
|
tasks -> grunt tasks, see [generator-mangrove-module](https://github.com/cagosta/generator-mangrove-module)
|
dist -> distribution & build files
|
node_modules -> node packages
|
documentation -> [jsdoc](http://usejsdoc.org/about-jsdoc3.html) generated documentation
## Run unit tests ##
#### On the browser ####
Run `grunt test:browser` and open `test/` on your browser.
#### On a headless browser ####
`grunt test:headless` will run your tests in a headless browser, with [phantomjs](http://phantomjs.org/) and [mocha](http://visionmedia.github.io/mocha/)
### On node ####
`grunt test:node` will run your tests with node and mocha.
Because of requirejs, the `mocha` command does not work.
## Build your own ##
This project uses [Node.js](http://nodejs.org/), [Grunt](http://gruntjs.com/) and [Require.js](http://requirejs.org/docs/optimization.html) for the build process. If for some reason you need to build a custom version install Node.js, `npm install` and run:
grunt build
## Yeoman Mangrove module Generator ##
This module is based on a [Yeoman](https://github.com/yeoman/yeoman/wiki/Getting-Started) generator: [Generator-mangrove-module](https://github.com/cagosta/generator-mangrove-module)
Check it for task-related references such as build, deploy etc ..
## Authors
* [Cyril Agosta](https://github.com/cagosta)
* [Sam Ton That](https://github.com/KspR)
* [Pierre Cole](https://github.com/piercus)
## License ##
[MIT License](http://www.opensource.org/licenses/mit-license.php)
|
Java
|
UTF-8
| 15,873
| 1.625
| 2
|
[
"Apache-2.0",
"EPL-1.0"
] |
permissive
|
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.common.ui.editmodel;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.bpel.model.resource.BPELResourceSetImpl;
import org.eclipse.bpel.common.ui.CommonUIPlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
/**
* EditModel is shared between editor with the same primary file input. It holds
* on to a command stack, and a resource set.
*
* This class has a reference count cache of EditModels. Once all editors that
* reference a editModel are closed all resource in the shared resource set are
* unloaded.
*
* Life-cycle call getEditModel using its primary file. the shared resource set
* reference count is incremented; call getResourceInfo using any file that need
* to be loaded the shared resource reference count is incremented; call
* releaseReference the shared resource reference count is decremented; call
* release if it is the last reference the shared resource set is disposed
*/
public class EditModel {
protected static EditModelCache cache = new EditModelCache();
protected Map<IFile,ResourceInfo> fileToResourceInfo = new HashMap<IFile,ResourceInfo>();
protected ResourceSet resourceSet;
protected int referenceCount = 0;
protected IResource primaryFile;
protected EditModelCommandStack commandStack;
private List<IEditModelListener> updateListeners = null;
/**
* Get the edit model based on the primary resource file.
*
* @param primaryFile
* @return the edit model
*/
public static EditModel getEditModel(IResource primaryFile) {
return cache.getEditModel(primaryFile, new Factory());
}
/**
* Get the edit model based on the primary resource file.
* @param primaryFile primary file (the BPEL resource)
* @param factory factory
* @return the editor model
*
*/
public static EditModel getEditModel(IResource primaryFile, Factory factory) {
return cache.getEditModel(primaryFile, factory);
}
/**
* Private constructor. Use the static factory methods.
*/
protected EditModel(ResourceSet rSet, IResource bpelFile) {
this.resourceSet = rSet;
this.primaryFile = bpelFile;
this.updateListeners = new ArrayList<IEditModelListener>();
}
/**
* Add a model listener.
* @param listener
*/
public void addListener (IEditModelListener listener) {
if (updateListeners.contains(listener)) {
return;
}
updateListeners.add(listener);
}
/**
* Remove a model listener.
* @param listener
*/
public void removeListener(IEditModelListener listener) {
updateListeners.remove(listener);
}
protected void fireModelDirtyStateChanged(ResourceInfo sr) {
for (IEditModelListener next : updateListeners ) {
next.modelDirtyStateChanged(sr);
}
}
protected void fireModelDeleted(ResourceInfo sr) {
// bugzilla 324006
// Prevent concurrent list modification exception:
// When a resource is deleted, the BPEL editor shuts itself down for no
// apparently good reason (I'm sure it's to avoid some other kinds of disasters
// that it isn't equipped to deal with!) This causes the editor to remove itself
// from our update listeners list.
ArrayList<IEditModelListener> listeners = new ArrayList<IEditModelListener>(updateListeners.size());
listeners.addAll(updateListeners);
for (IEditModelListener next : listeners ) {
next.modelDeleted(sr);
}
}
protected void fireModelReloaded(ResourceInfo sr) {
ArrayList<IEditModelListener> listeners = new ArrayList<IEditModelListener>(updateListeners.size());
listeners.addAll(updateListeners);
for (IEditModelListener next : listeners ) {
next.modelReloaded(sr);
}
}
protected void fireModelLocationChanged(ResourceInfo sr, IFile movedToFile) {
ArrayList<IEditModelListener> listeners = new ArrayList<IEditModelListener>(updateListeners.size());
listeners.addAll(updateListeners);
for (IEditModelListener next : listeners ) {
next.modelLocationChanged(sr,movedToFile);
}
}
protected void fireModelMarkersChanged (ResourceInfo sr, IMarkerDelta[] markerDelta ) {
ArrayList<IEditModelListener> listeners = new ArrayList<IEditModelListener>(updateListeners.size());
listeners.addAll(updateListeners);
for (IEditModelListener next : listeners ) {
next.modelMarkersChanged(sr,markerDelta );
}
}
/**
* Return the resource set associated with this editModel.
* @return the resource set used by this Edit Model client.
*/
public ResourceSet getResourceSet() {
return resourceSet;
}
/**
* Returns the cached ResourceInfo for <code>file</code>
*
* Creates a new ResourceInfo it is not found in the cache, otherwise
* increment the reference count and return it.
*/
ResourceInfo getResourceInfoForLoadedResource(Resource resource) {
URI uri = resource.getURI();
IFile file = getIFileForURI(uri);
if (file == null)
return null;
ResourceInfo resourceInfo = fileToResourceInfo.get(file);
if (resourceInfo == null) {
resourceInfo = new ResourceInfo(this, file);
resourceInfo.setResource(resource);
addResourceInfo(resourceInfo);
resourceInfo.resourceLoaded();
}
if (!resourceInfo.loading)
resourceInfo.referenceCount++;
return resourceInfo;
}
/**
* Returns the cached ResourceInfo for <code>file</code>
*
* Creates a new ResourceInfo it is not found in the cache, otherwise
* increment the reference count and return it.
*
* @param file the file
* @return the cached resource info for that file.
*/
public ResourceInfo getResourceInfo(IFile file) {
ResourceInfo resourceInfo = fileToResourceInfo.get(file);
if (resourceInfo == null) {
resourceInfo = new ResourceInfo(this, file);
addResourceInfo(resourceInfo);
try {
resourceInfo.load();
} catch (RuntimeException ex) {
resourceInfo.referenceCount++;
releaseReference(resourceInfo);
throw ex;
}
}
resourceInfo.referenceCount++;
return resourceInfo;
}
static ResourceInfo [] EMPTY_RESOURCE_ARRAY = {};
/**
*
* @return The resource infos
*
*/
public ResourceInfo[] getResourceInfos() {
return fileToResourceInfo.values().toArray(EMPTY_RESOURCE_ARRAY);
}
private void setPrimaryFile(IFile newFile) {
IResource oldFile = primaryFile;
primaryFile = newFile;
cache.updatePrimaryFile(oldFile, newFile);
}
/**
* @return the primary resource (primary file) for this edit model.
*/
public IResource getPrimaryFile() {
return primaryFile;
}
/**
* Decrement the reference count for <code>resourceInfo</code> and dispose
* if it is the last reference.
* @param resourceInfo
*/
public void releaseReference (ResourceInfo resourceInfo) {
resourceInfo.referenceCount--;
if (resourceInfo.referenceCount == 0) {
resourceInfo.dispose();
removeResourceInfo(resourceInfo);
}
}
/**
* Add resourceInfo to the cache
*/
protected void addResourceInfo(ResourceInfo sr) {
fileToResourceInfo.put(sr.getFile(), sr);
}
/*
* Remove the resourceInfo from the cache.
*/
protected void removeResourceInfo(ResourceInfo sr) {
fileToResourceInfo.remove(sr.getFile());
}
/**
* Dispose this EditModel if there is no other reference to it;
*/
public void release() {
referenceCount--;
if (referenceCount == 0) {
cache.remove(this);
for (ResourceInfo resourceInfo : fileToResourceInfo.values().toArray(EMPTY_RESOURCE_ARRAY) ) {
resourceInfo.dispose();
}
fileToResourceInfo.clear();
}
}
public static IFile getIFileForURI(URI uri) {
String filePath = null;
String scheme = uri.scheme();
IFile file = null;
if ("file".equals(scheme)) { //$NON-NLS-1$
filePath = uri.toFileString();
if (filePath == null)
return null;
file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
new Path(filePath));
} else if ("platform".equals(scheme) && uri.segmentCount() > 1 && "resource".equals(uri.segment(0))) { //$NON-NLS-1$//$NON-NLS-2$
StringBuffer platformResourcePath = new StringBuffer();
for (int i = 1, size = uri.segmentCount(); i < size; ++i) {
platformResourcePath.append('/');
platformResourcePath.append(uri.segment(i));
}
filePath = platformResourcePath.toString();
if (filePath == null)
return null;
file = ResourcesPlugin.getWorkspace().getRoot().getFile(
new Path(filePath));
}
return file;
}
/**
* Get the command stack.
*
* @return the command stack.
*/
public EditModelCommandStack getCommandStack() {
return commandStack;
}
/**
* Set the command stack.
*
* @param stack the command stack.
*/
public void setCommandStack(EditModelCommandStack stack) {
this.commandStack = stack;
}
/**
* Saves the model
*
* @param progressMonitor progress monitor.
* @return if all went OK true, false otherwise.
*/
public boolean saveAll(IProgressMonitor progressMonitor) {
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
@Override
protected void execute(IProgressMonitor monitor)
throws InvocationTargetException {
getCommandStack().markSaveLocation();
try {
ResourceInfo[] sResource = getResourceInfos();
for (int i = 0; i < sResource.length; i++) {
ResourceInfo resource = sResource[i];
if (resource.isDirty())
resource.save();
}
} catch (IOException e) {
throw new InvocationTargetException(e);
}
}
};
try {
operation.run(progressMonitor);
} catch (InvocationTargetException e) {
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
/**
* Save primary resource as ...
*
* @param resourceInfo
* @param savedFile
* @param progressMonitor
* @return save result (true is OK).
*/
public boolean savePrimaryResourceAs(final ResourceInfo resourceInfo,
final IFile savedFile, IProgressMonitor progressMonitor) {
boolean result = saveResourceAs(resourceInfo, savedFile,
progressMonitor);
if (result)
setPrimaryFile(savedFile);
return result;
}
/**
* Save resource as ...
* @param resourceInfo
* @param savedFile
* @param progressMonitor
* @return the status of the save ...
*/
public boolean saveResourceAs(final ResourceInfo resourceInfo,
final IFile savedFile, IProgressMonitor progressMonitor) {
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
@Override
protected void execute(IProgressMonitor monitor)
throws InvocationTargetException {
try {
getCommandStack().markSaveLocation();
resourceInfo.saveAs(savedFile);
} catch (IOException e) {
throw new InvocationTargetException(e);
}
}
};
try {
operation.run(progressMonitor);
} catch (InvocationTargetException e) {
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
/**
*
* @author IBM
*
*/
public static class Factory {
protected EditModel createEditModel(ResourceSet resourceSet,
IResource primaryFile) {
return new EditModel(resourceSet, primaryFile);
}
}
static class EditModelCache {
protected Map<ResourceSet,EditModel> resourceSetToEditModel = new HashMap<ResourceSet,EditModel>();
protected Map<IResource,ResourceSet> fileToResourceSet = new HashMap<IResource,ResourceSet>();
/**
* Return a new ResourceSet for the specified file.
* @param primaryFile
* @param factory
* @return the edit model.
*/
public EditModel getEditModel(IResource primaryFile, Factory factory) {
ResourceSet resourceSet = getResourceSet(primaryFile);
return getEditModel(resourceSet, primaryFile, factory);
}
/**
* Return the EditModel for specified resource set.
*
* Creates a new EditModel it is not found in the cache, otherwise
* increment the reference count and return it.
*/
@SuppressWarnings("unchecked")
private EditModel getEditModel(ResourceSet resourceSet,
IResource primaryFile, Factory factory) {
EditModel editModel = resourceSetToEditModel.get(resourceSet);
if (editModel != null) {
editModel.referenceCount++;
return editModel;
}
editModel = factory.createEditModel(resourceSet, primaryFile);
editModel.referenceCount++;
resourceSetToEditModel.put(resourceSet, editModel);
final EditModel finalEditModel = editModel;
resourceSet.eAdapters().add(new AdapterImpl() {
@Override
public void notifyChanged(Notification msg) {
Resource r = (Resource) msg.getNewValue();
finalEditModel.getResourceInfoForLoadedResource(r);
}
});
return editModel;
}
/*
* Return a new ResourceSet for the specified file.
*/
private ResourceSet getResourceSet(IResource primaryFile) {
ResourceSet resourceSet = fileToResourceSet.get(primaryFile);
if(resourceSet != null)
return resourceSet;
// TODO: Extensibility
resourceSet = new BPELResourceSetImpl();
fileToResourceSet.put(primaryFile,resourceSet);
return resourceSet;
}
/**
*
* @param editModel
*/
public void remove(EditModel editModel) {
resourceSetToEditModel.remove(editModel.resourceSet);
fileToResourceSet.remove(editModel.primaryFile);
}
void updatePrimaryFile(IResource oldFile, IResource newFile) {
ResourceSet rs = fileToResourceSet.get(oldFile);
fileToResourceSet.remove(oldFile);
fileToResourceSet.put(newFile, rs);
}
}
static String EXTPT_RESOURCE_SET_PROVIDER = "resourceSetProvider"; //$NON-NLS-1$
static String ELM_PROVIDER = "provider"; //$NON-NLS-1$
static String ATT_CLASS = "class"; //$NON-NLS-1$
static private IResourceSetProvider gfResourceSetProvider;
static IResourceSetProvider getResourceSetProvider () {
if (gfResourceSetProvider != null) {
return gfResourceSetProvider;
}
for(IConfigurationElement elm : CommonUIPlugin.getConfigurationElements( EXTPT_RESOURCE_SET_PROVIDER)) {
if (ELM_PROVIDER.equals(elm.getName()) == false) {
continue;
}
String clazz = elm.getAttribute(ATT_CLASS);
if (clazz != null) {
try {
gfResourceSetProvider = (IResourceSetProvider) elm.createExecutableExtension(ATT_CLASS);
} catch ( CoreException ce ) {
CommonUIPlugin.getDefault().getLog().log(ce.getStatus());
}
}
if (gfResourceSetProvider != null) {
break;
}
}
if (gfResourceSetProvider == null) {
gfResourceSetProvider = new IResourceSetProvider () {
public ResourceSet getResourceSet (IResource resource) {
return new ResourceSetImpl();
}
};
}
return gfResourceSetProvider;
}
}
|
Go
|
UTF-8
| 4,095
| 2.515625
| 3
|
[] |
no_license
|
package app
import (
"fmt"
"os"
"path"
"regexp"
"strings"
"github.com/ericsgagnon/qgenda/pkg/qgenda"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
// Config contains all app config parameters
type Config struct {
App AppConfig
Cache qgenda.CacheConfig
Client qgenda.ClientConfig
Logger LogConfig //zap.Config `yaml:"-"`
DBClients map[string]qgenda.DBClientConfig `yaml:"dbClients"`
Data map[string]qgenda.RequestConfig
// DBClients map[string]url.URL `yaml:"dbClients"`
}
func DefaultConfig(ac *AppConfig) *Config {
if ac == nil {
ac = NewAppConfig()
}
cacheCfg, err := qgenda.NewCacheConfig(ac.Name)
if err != nil {
panic(err)
}
// sd, _ := time.Parse(time.RFC3339, "2006-01-01T00:00:00Z")
// qcc := qgenda.ClientConfig{}
return &Config{
App: *ac,
Cache: *cacheCfg,
Client: *qgenda.DefaultClientConfig(),
Logger: NewLogConfig(),
DBClients: map[string]qgenda.DBClientConfig{
"odbc": qgenda.ExampleDBClientConfig(),
},
Data: map[string]qgenda.RequestConfig{
"schedule": *qgenda.DefaultScheduleRequestConfig(),
},
}
}
func LoadAndParseConfig(filename string) (*Config, error) {
// read config file
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
cfg := Config{}
if err := yaml.Unmarshal(b, &cfg); err != nil {
return nil, err
}
return &cfg, nil
}
// NewExampleConfig creates an example config
func NewExampleConfig() Config {
cfg := Config{
// "postgres://postgres:password@localhost:5432/postgres?sslmode=disable"
// Endpoints: map[string]ConfigEndpoint{
// "postgres": {
// Name: "postgres",
// Kind: "odbc",
// Host: "db.example.com",
// Port: 5432,
// Database: "example",
// User: "user",
// Password: "password",
// Arguments: url.Values{
// "ssl": []string{
// "require",
// }},
// },
// // "dest": {
// // Name: "dest",
// // Kind: "odbc",
// // Host: "db.example.com",
// // Database: "example",
// // User: "user",
// // Password: "password",
// // Arguments: url.Values{
// // "ssl": []string{
// // "require",
// // }},
// // },
// },
}
// cfg.Endpoints["src"].ConnectionString =
return cfg
}
// ConfigFile is a convenience function that returns an os dependent
// default for /path/to/config/file or returns cf if not nil
func ConfigFile(app string, filename string) (string, error) {
if filename == "" {
userConfigDir, err := os.UserConfigDir()
if err != nil {
return filename, err
}
filename = path.Join(userConfigDir, app, "config.yaml")
}
// os.IsExist()
return filename, nil
}
// ExpandEnvVars substitutes environment variables of the form ${ENV_VAR_NAME}
// if you have characters that need to be escaped, they should be surrounded in
// quotes in the source string.
func ExpandEnvVars(s string) string {
re := regexp.MustCompile(`\$\{.+\}`)
envvars := map[string]string{}
for _, m := range re.FindAllString(s, -1) {
mre := regexp.MustCompile(`[${}]`)
mtrimmed := mre.ReplaceAllString(m, "")
// fmt.Printf("%s:\t%s\n", mtrimmed, os.Getenv(mtrimmed))
envvars[m] = os.Getenv(mtrimmed)
}
for k, v := range envvars {
s = strings.ReplaceAll(s, k, v)
}
return s
}
func ConfigToYAML(cfg Config) (string, error) {
b, err := yaml.Marshal(cfg)
if err != nil {
return "", err
}
return string(b), nil
}
// func (c Config) MarshalYAML() (any, error) {
// return ConfigToYAML(c)
// }
//
// initConfig reads in config file / Env vars
// and returns a Config
func initConfig(cf string) (Config, error) {
c := Config{}
v := viper.New()
v.SetConfigFile(cf)
// v.AutomaticEnv() // read in environment variables that match - maybe later
if err := v.ReadInConfig(); err != nil {
fmt.Printf("Error using config file: %s\n", v.ConfigFileUsed())
return c, err
}
fmt.Printf("Using config file: %s\n", v.ConfigFileUsed())
if err := v.Unmarshal(&c); err != nil {
fmt.Printf("Error parsing config file: %s", err)
return c, err
}
return c, nil
}
|
C++
|
UTF-8
| 1,087
| 2.8125
| 3
|
[] |
no_license
|
#include "DataChecksum.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <boost/crc.hpp>
DataChecksum::DataChecksum()
{
//ctor
}
DataChecksum::~DataChecksum()
{
//dtor
}
void DataChecksum::addFile(std::string p_file)
{
m_files.push_back(p_file);
}
void DataChecksum::addFiles(std::vector<std::string> p_files)
{
int i;
for(i=0;i<p_files.size();i++)
m_files.push_back(p_files[i]);
}
void DataChecksum::process()
{
int i;
for(i=0;m_files.size();i++){
boost::crc_32_type result;
std::ifstream fichier(m_files[i].c_str()); // ouvre un fichier en lecture
if(fichier) // échoue si le fichier n'est pas ouvert
{
std::stringstream buffer;
buffer << fichier.rdbuf(); // copier le contenu du fichier dans le buffer
fichier.close();
result.process_bytes(buffer.str().c_str(), buffer.str().size());
m_checksums[m_files[i]]=result.checksum();
}
}
}
std::map<std::string, checksum> DataChecksum::getChecksums()
{
return m_checksums;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.