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
Ruby
UTF-8
1,949
2.6875
3
[]
no_license
require "test_helper" class RealStateTest < ActiveSupport::TestCase test "validations" do model = RealState.new assert !model.valid? error_messages = model.errors.full_messages assert (error_messages.include? "Name is too short (minimum is 1 character)") assert (error_messages.include? "Real state type is not included in the list") assert (error_messages.include? "Street is too short (minimum is 1 character)") assert (error_messages.include? "External number is too short (minimum is 1 character)") assert (error_messages.include? "External number only alphanumerics and dash (-)") assert (error_messages.include? "Neighborhood is too short (minimum is 1 character)") assert (error_messages.include? "City is too short (minimum is 1 character)") assert (error_messages.include? "Country is the wrong length (should be 2 characters)") assert (error_messages.include? "Country only ISO 3166 alpha 2 codes") assert (error_messages.include? "Rooms is not a number") assert (error_messages.include? "Bathrooms is not a number") assert (error_messages.include? "Comments is too short (minimum is 0 characters)") end test "add" do before_count = RealState.count RealState.create!([ { name: 'Place1', real_state_type: 'house', street: 'street1', external_number: 'number1', internal_number: 'i1', neighborhood: 'neighborhood1', city: 'city1', country: 'ES', rooms: 0, bathrooms: 1.0, comments: '' } ]) after_count = RealState.count assert after_count == (before_count + 1) end test "update" do model = RealState.last id = model.id model.name = "name updated" model.save! modified_model = RealState.find(id) assert modified_model.name == "name updated" end test "remove" do before_count = RealState.count RealState.last.destroy! after_count = RealState.count assert after_count == (before_count - 1) end end
Markdown
UTF-8
2,385
2.578125
3
[]
no_license
--- ID: 2498 post_title: 'Infinio Accelerator v2 announced at #VMworld &#8211; Now with iSCSI and FC support' author: Jonathan Frappier post_date: 2014-08-25 09:14:34 post_excerpt: "" layout: post permalink: > http://www.virtxpert.com/infinio-accelerator-v2-announced-vmworld-now-iscsi-fc-support/ published: true dsq_thread_id: - "2957520737" --- <em>**Disclaimer:  Infinio is a sponsor of virtxpert.com - I was not asked to write this article, I am simply sharing the news about the new features from a great product**</em> While at VMworld I learned that Infinio has announced a new version of Infinio Accelerator which now supports block storage protocols (iSCSI, FC, and FCoE) as well as NAS (NFS).  Infinio came out of beta last year at VMworld with their RAM based read cache solution for NAS storage.  Now companies who need to accelerate traditional block are also able to do so with the easy to install Infinio Accelerator. <a href="http://www.virtxpert.com/wp-content/uploads/2014/08/how-infinio-works.png"><img class="aligncenter wp-image-2504 size-full" src="http://www.virtxpert.com/wp-content/uploads/2014/08/how-infinio-works.png" alt="how-infinio-works" width="518" height="260" /></a> <h3>From the press release:</h3> <blockquote>In addition to support for the NFS storage protocol, v2.0 will also include full support for Fibre Channel, iSCSI, FCoE, and environments with multiple protocols. No matter which storage protocol customers choose, the Infinio user experience remains the same, including wizard-driven installation, zero operational impact, and instant access to advanced reporting.</blockquote> In addition to block storage support, Infinio also announced application level reporting and a sizing adviser to help you determine how much memory to allocate to cache.  You can sign up to be notified when the beta of version two will be available at here: <a href="http://www.infinio.com/infinio-accelerator-20" target="_blank">http://www.infinio.com/infinio-accelerator-20</a>.  If you are at VMworld this week, swing by booth 623 for a demo. <a href="http://www.virtxpert.com/wp-content/uploads/2014/08/Infinio-VMworld14-booth-623-map.png"><img class="aligncenter size-full wp-image-2501" src="http://www.virtxpert.com/wp-content/uploads/2014/08/Infinio-VMworld14-booth-623-map.png" alt="Infinio-VMworld14-booth-623-map" width="800" height="500" /></a>
Java
UTF-8
2,157
2.171875
2
[]
no_license
package com.skstructure.view; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import com.skstructure.SKHelper; import com.skstructure.core.SKIPre; import com.skstructure.modules.structure.SKStructureModel; import com.skstructure.utils.SKClassGenericTypeUtil; /** * @创建人 weishukai * @创建时间 2018/3/7 09:47 * @类描述 一句话描述 你的类 */ public abstract class SKFragment<P extends SKIPre> extends Fragment { private SKStructureModel skStructureModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); skStructureModel = new SKStructureModel(this); SKHelper.getSkStructureManager().attach(skStructureModel); } @Override public void onDestroy() { super.onDestroy(); SKHelper.getSkStructureManager().detach(skStructureModel); } /** * 获取对应的Pre * * @return */ public P pre() { if (skStructureModel == null || skStructureModel.getSkProxy() == null || skStructureModel.getSkProxy().proxy == null) { Class iPre = SKClassGenericTypeUtil.getClassGenericTypeNotSure(getClass(), 0); return (P) SKHelper.getSkMethodProxy().createNullProxy(iPre); } return (P) skStructureModel.getSkProxy().proxy; } public <C extends SKIPre> C pre(Class<C> cClass) { return pre(cClass, 0); } /** * 获取指定的Pre,用于调用其他打开的页面 * * @param cClass * @param index 按照打开的顺序,最后打开为0 * @param <C> * @return */ public <C extends SKIPre> C pre(Class<C> cClass, int index) { if (skStructureModel != null && skStructureModel.getIPre().equals(cClass)) { if (skStructureModel.getSkProxy() == null || skStructureModel.getSkProxy().proxy == null) { return SKHelper.getSkMethodProxy().createNullProxy(cClass); } return (C) skStructureModel.getSkProxy().proxy; } return SKHelper.pre(cClass, index); } }
C++
UTF-8
453
2.875
3
[]
no_license
#include <cstdio> #include <cstring> char buf[2048]; int main() { int i, ans; gets(buf); ans = 0; for (i = 0; i < strlen(buf); ++i) { if ((buf[i] >= 'a') && (buf[i] <= 'z')) { ans += ((buf[i] - 'a') % 3) + 1; } else if (buf[i] == '.') { ans += 1; } else if (buf[i] == ',') { ans += 2; } else if (buf[i] == '!') { ans += 3; } else if (buf[i] == ' ') { ans += 1; } } printf("%d\n", ans); return 0; }
Python
UTF-8
721
4.3125
4
[]
no_license
# a realistic example to add scala functionality in Python tuple """ In Scala, the element in tuple can be accessed like val a_tuple = ("z", 3, “Python”, -1) println(a_tuple._1) // “z” println(a_tuple._3) // “Python” """ class Tuple(tuple): def __getattr__(self, name): def _int(val): try: return int(val) except ValueError: return False if not name.startswith("_") or not _int(name[1:]): raise AttributeError("'tuple' object has no attribute '%s'" % name) index = _int(name[1:]) - 1 return self[index] t = Tuple(["z", 3, "Python", -1]) print(t._1) print(t._2) print(t._3)
Java
UTF-8
1,069
3.34375
3
[]
no_license
package demo01; public class Top { static int x= 1; public Top(int y){ x *= 3; } } class Passer{ static final int x= 5; public static void main(String[] args) { new Passer().go(x); System.out.print(x); } void go(int x){ System.out.print(x++); } } class Wrench{ public static void main(String[] args) { Wrench w=new Wrench(); Wrench w2=new Wrench(); w2=go(w, w2); System.out.print(w2==w); } static Wrench go(Wrench wrl,Wrench wr2){ Wrench wr3=wrl; wrl = wr2; wr2 = wr3; return wr3; } } class Test2{ public static void main(String[] args) { short a, b, c; a = 1; b = 2; a += 2; c = (short) (a + b); } } class Test4{ public static void main(String[] args){ boolean x=true; boolean y=false; short z=42; if((z++==42)&&(y=true)) z++; if((x=false)||(++z==45)) z++; System.out.println("z="+z); } }
Java
UTF-8
2,384
1.9375
2
[]
no_license
package tests.cloud.appium; import com.experitest.appium.SeeTestClient; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.MobileCapabilityType; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.ScreenOrientation; import org.openqa.selenium.remote.DesiredCapabilities; import tests.BaseTest; import java.net.MalformedURLException; import java.net.URL; public class NetworkTransaction extends BaseTest { protected AndroidDriver<AndroidElement> driver = null; DesiredCapabilities dc = new DesiredCapabilities(); SeeTestClient seetest; @Before public void setUp() throws MalformedURLException { dc.setCapability("testName", "Network Transaction"); dc.setCapability("accessKey", this.accessKey); dc.setCapability("deviceQuery", "@serialNumber='" + this.deviceSN + "'"); dc.setCapability(MobileCapabilityType.APP, "cloud:com.experitest.ExperiBank/.LoginActivity"); dc.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.experitest.ExperiBank"); dc.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".LoginActivity"); driver = new AndroidDriver<>(new URL(this.url + "/wd/hub"), dc); seetest = new SeeTestClient(driver); dc.setCapability(MobileCapabilityType.UDID, "deviceid"); } @Test public void networkTransactionDemoTest() { seetest.startPerformanceTransactionForApplication("com.experitest.ExperiBank", "4G-average"); driver.rotate(ScreenOrientation.PORTRAIT); driver.findElement(By.xpath("//*[@id='usernameTextField']")).sendKeys("company"); driver.hideKeyboard(); driver.findElement(By.xpath("//*[@id='passwordTextField']")).sendKeys("company"); driver.findElement(By.xpath("//*[@id='loginButton']")).click(); String loginPerfData = seetest.endPerformanceTransaction("Login"); System.out.println(loginPerfData); } @After public void tearDown() { System.out.println(NetworkTransaction.class.getName() + ": Report URL for device " + this.deviceSN + ": "+ driver.getCapabilities().getCapability("reportUrl")); driver.quit(); } }
C++
UTF-8
1,240
2.609375
3
[]
no_license
/* AlturaPetiso * * Arduino Nano, 1 HC-SR04, 1 rele, * 1 pestillo * * * Sputnik Ar * 21/08/30 */ //INCLUDES #include <NewPing.h> //DEFINES #define ALTURA 160 //en cm #define TIEMPO 1 //en segundos #define CHANGUI 10 //en cm #define LED 3 #define RELE 10 #define TRIGGER_PIN 12 #define ECHO_PIN 11 #define MAX_DISTANCE 200 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); unsigned long filtrado = 0; void setup() { Serial.begin(9600); pinMode(OUTPUT, RELE); digitalWrite(RELE, HIGH); pinMode(OUTPUT, LED); digitalWrite(LED, LOW); } void loop() { boolean correcto = true; filtrado = millis(); while(correcto && ((millis() - filtrado) < TIEMPO*1000)){ int cm = sonar.ping_cm(); Serial.print("Ping: "); Serial.print(sonar.ping_cm()); Serial.println("cm"); delay(50); if(cm < ALTURA + CHANGUI && cm > ALTURA - CHANGUI){}else{correcto = false;}} if(correcto){ digitalWrite(RELE,LOW); digitalWrite(LED,1); Serial.print("Resuelto"); delay(TIEMPO*1000); }else{ digitalWrite(RELE,HIGH); digitalWrite(LED,0); } }
C++
UTF-8
5,637
2.546875
3
[]
no_license
#include "flib.h" #include "flib_vec2.h" #include "transform.h" #include "hitbox.h" #include "functions.h" #include "scene.h" #include <math.h> #include "collision.h" TCollideResult CollideCircle(TTransform * tFirst, TTransform * tOther){ TGfxVec2 tFirstPos = tFirst->m_tHitBox->GetGlobalPos() ; TGfxVec2 tOtherPos = tOther->m_tHitBox->GetGlobalPos() ; float fDistance = (tFirstPos - tOtherPos).Length(); float fFirstRadius = tFirst->m_tHitBox->GetRadius(); float fOtherRadius = tOther->m_tHitBox->GetRadius(); float fLength = 0; TGfxVec2 normVec; if(fDistance < fFirstRadius + fOtherRadius) { fLength = (fFirstRadius + fOtherRadius) - fDistance; if(tFirstPos !=tOtherPos) { normVec = (tFirstPos-tOtherPos).Normalize(); } else normVec = TGfxVec2(0,0); } TCollideResult result; result.fLength = fLength; result.tNormal = normVec; return result; } TCollideResult CollideCircleBox(TTransform * tCircle, TTransform * tBox){ TCollideResult tResult; const TGfxVec2 & tBoxCenter = tBox->m_tHitBox->GetGlobalPos(); const TGfxVec2 & tBoxRadius = tBox->m_tHitBox->GetRadiusBox(); const float fAngle = tBox->GetAngle(); const TGfxVec2 & tCircleCenter = tCircle->m_tHitBox->GetGlobalPos(); const float & fCircleRadius = tCircle->m_tHitBox->GetRadius(); const TGfxVec2 tAxisX = TGfxVec2(cosf(fAngle),sinf(fAngle)); const TGfxVec2 tAxisY = TGfxVec2(-sinf(fAngle),cosf(fAngle)); const TGfxVec2 tAxeX = tBoxCenter + tAxisX ; const TGfxVec2 tAxeY = tBoxCenter + tAxisY ; float fDotProductX = (tCircleCenter-tBoxCenter).DotProduct(tAxeX-tBoxCenter) ; float fDotProductY = (tCircleCenter-tBoxCenter).DotProduct(tAxeY-tBoxCenter) ; const TGfxVec2 tAxeX2 = tBoxCenter + tAxisX * MClamp(fDotProductX, -tBoxRadius.x, tBoxRadius.x); const TGfxVec2 tAxeY2 = tBoxCenter + tAxisY * MClamp(fDotProductY, -tBoxRadius.y, tBoxRadius.y); const TGfxVec2 tNearestPoint = tAxeX2+tAxeY2 - tBoxCenter; if((tCircleCenter-tNearestPoint).Length()<fCircleRadius) { TGfxVec2 normVec; const TGfxVec2 tNormale = TGfxVec2(1, sin(fAngle)); float length = fCircleRadius - (tCircleCenter-tNearestPoint).Length(); if((tCircleCenter-tNearestPoint).Length() != 0) { normVec = (tCircleCenter-tNearestPoint).Normalize(); }else{ normVec = tCircleCenter-tNearestPoint; } tResult.fLength = length; tResult.tNormal = normVec; return tResult; }else{ tResult.fLength = 0; return tResult; } } TCollideResult CollideCircleTriangle(TTransform * tCircle, TTransform * tBox){ TCollideResult tResult; tResult.self = tCircle; tResult.other = tBox; const TGfxVec2 & tBoxCenter = tBox->m_tHitBox->GetGlobalPos(); const TGfxVec2 & tBoxRadius = tBox->m_tHitBox->GetRadiusBox(); const float fAngle = tBox->GetAngle(); const TGfxVec2 & tCircleCenter = tCircle->m_tHitBox->GetGlobalPos(); const float & fCircleRadius = tCircle->m_tHitBox->GetRadius(); const TGfxVec2 tAxisX = TGfxVec2(cosf(fAngle),sinf(fAngle)); const TGfxVec2 tAxisY = TGfxVec2(-sinf(fAngle),cosf(fAngle)); TGfxVec2 tCircleToBox = tCircleCenter - tBoxCenter; float fAngleNormal = CorrectRange( atan2f(tBox->m_tHitBox->GetNormal().y, tBox->m_tHitBox->GetNormal().x) ); float fAngleObjects = CorrectRange( atan2f(tCircleToBox.y, tCircleToBox.x) ); if( CorrectRange( fAngleNormal -fAngleObjects ) > M_PI_2 || CorrectRange( fAngleNormal - fAngleObjects ) < -M_PI_2 ){ const TGfxVec2 tAxeX = tBoxCenter + tAxisX ; const TGfxVec2 tAxeY = tBoxCenter + tAxisY ; float fDotProductX = (tCircleCenter-tBoxCenter).DotProduct(tAxeX-tBoxCenter) ; float fDotProductY = (tCircleCenter-tBoxCenter).DotProduct(tAxeY-tBoxCenter) ; const TGfxVec2 tAxeX2 = tBoxCenter + tAxisX * MClamp(fDotProductX, -tBoxRadius.x, tBoxRadius.x); const TGfxVec2 tAxeY2 = tBoxCenter + tAxisY * MClamp(fDotProductY, -tBoxRadius.y, tBoxRadius.y); const TGfxVec2 tNearestPoint = tAxeX2+tAxeY2 - tBoxCenter; if((tCircleCenter-tNearestPoint).Length()<fCircleRadius) { TGfxVec2 normVec; const TGfxVec2 tNormale = TGfxVec2(1, sin(fAngle)); float length = fCircleRadius - (tCircleCenter-tNearestPoint).Length(); if((tCircleCenter-tNearestPoint).Length() != 0) { normVec = (tCircleCenter-tNearestPoint).Normalize(); }else{ normVec = tCircleCenter-tNearestPoint; } tResult.fLength = length; tResult.tNormal = normVec; return tResult; } }else{ float length = tCircleToBox.DotProduct(tBox->m_tHitBox->GetNormal()); if(length<fCircleRadius) { float distance = fabs(tCircleToBox.DotProduct(-tBox->m_tHitBox->GetTangent())); if(distance - fCircleRadius < tBox->m_tHitBox->GetHypo()/2 ) { tResult.fLength = length - fCircleRadius; tResult.tNormal = - tBox->m_tHitBox->GetNormal(); return tResult; } } } tResult.fLength = 0; return tResult; } TCollideResult Collide(TTransform * tFirst, TTransform * tOther){ if( tFirst->m_tHitBox->eCollisionType == Circle && tOther->m_tHitBox->eCollisionType == Circle) { return CollideCircle(tFirst, tOther); }else if( tFirst->m_tHitBox->eCollisionType == Circle && tOther->m_tHitBox->eCollisionType == Box) { return CollideCircleBox(tFirst, tOther); }else if( tFirst->m_tHitBox->eCollisionType == Box && tOther->m_tHitBox->eCollisionType == Circle) { return CollideCircleBox(tOther, tFirst); }else if( tFirst->m_tHitBox->eCollisionType == Circle && tOther->m_tHitBox->eCollisionType == Triangle) { return CollideCircleTriangle(tFirst, tOther); }else{ TCollideResult result; result.fLength = 0; return result; } }
C#
UTF-8
1,723
3.5
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab1_2 { class BubbleSortFunction { //public static int[] input { get; private set; } //public static string rawinput { get; private set; } static int[] input =new int[1000]; static int inc; static void inputfn() { string rawinput; int tmp; rawinput = Console.ReadLine(); int.TryParse(rawinput, out inc); for (int i=0;i<inc;i++) { string rinput = Console.ReadLine(); int.TryParse(rinput, out tmp); input.SetValue(tmp, i); } } // process static void process() { bool flag = true; while (flag) { flag = false; for (int i = 0; i != inc - 1; i++) { if (input[i] > input[i + 1]) { int temp = input[i]; input[i] = input[i + 1]; input[i + 1] = temp; flag = true; } } } } // output static void output() { for (int i = 0; i != inc; i++) { Console.Write(input[i]); Console.Write(" "); } Console.ReadKey(); } static void Main(string[] args) { //Console.WriteLine("Input : "); inputfn(); process(); output(); } } }
Markdown
UTF-8
5,134
2.78125
3
[]
no_license
![지뢰찾기](../img/지뢰찾기.PNG) 우리가 어린시절에 하던 지뢰찾기원리와 같습니다. 단지 난이도가 많이 쉽습니다. [지뢰찾기코드](../GamePrac/PyagameMine_sweeper.py) ### 코드알아보기 ```buildoutcfg while True: a = input("난이도를 몇으로 하시겠습니까? 1, 2, 3, 4:\n") if a == '1': WIDTH = 10 HEIGHT = 10 BOMBS = 10 break elif a == '2': WIDTH = 15 HEIGHT = 15 BOMBS = 15 break elif a == '3': WIDTH = 25 HEIGHT = 20 BOMBS = 22 break elif a == '4': WIDTH = 30 HEIGHT = 20 BOMBS = 30 break else: print("잘못입력하셨습니다, 1에서 4까지 다시 입력하세요\n") continue ``` <br> 게임실행전 난이도를 설정하기 위한 코드입니다. 난이도를 조정해서 각자 맞는 실력에 게임을 실행할수있습니다. <br> ```buildoutcfg SIZE =30 #1칸의 가로세로 곱의 크기 EMPTY = 0 #맵상의 타일에 아무것도 없는 상태 BOMB = 1 #맵상의 타일에 폭탄이 있는 상태 OPENED =2 # 맵상의 타일이 이미 비어진 상태 OPEN_COUNT = 0 #열린 타일의 수 CHECKED = [[0 for _ in range(WIDTH)] for _ in range(HEIGHT)] #타일의 상태를 이미 확인했는지 기록하는 배열 ``` <br> ```buildoutcfg def bomb(field, x_pos, y_pos): count = 0 for yoffset in range(-1,2): for xoffset in range(-1,2): xpos, ypos = (x_pos + xoffset, y_pos+ yoffset) if 0 <=xpos <WIDTH and 0<=ypos <HEIGHT and field[ypos][xpos] == BOMB: count += 1 return count ``` <br> 주변의 폭탄수를 세어나갑니다. 그리고 주위의 폭탄수를 반환하여 폭탄을 피할수있게 도와줍니다. <br> ```buildoutcfg def open_tile(field, x_pos, y_pos): global OPEN_COUNT if CHECKED[y_pos][x_pos]: return CHECKED[y_pos][x_pos] =True for yoffset in range(-1,2): for xoffset in range(-1,2): xpos, ypos = (x_pos + xoffset, y_pos + yoffset) if 0 <= xpos < WIDTH and 0 <= ypos < HEIGHT and field[ypos][xpos] == EMPTY: field[ypos][xpos] = OPENED OPEN_COUNT += 1 count = bomb(field,xpos,ypos) if count == 0 and not (xpos== x_pos and ypos == y_pos): open_tile(field,xpos,ypos) ``` <br> 폭탄이 있는 칸 주위에 폭탄이 존재하지않는다면 주위의 칸을 열고 무한으로 같은 함수를 호출하지 않게 return값을 반환하여 탈출시킵니다. 그리고 빈타일이 클릭되면 인접하는 모든 빈타일이 일제히 open되게 해줍니다. <br> ```buildoutcfg field = [[EMPTY for xpos in range(WIDTH)] for ypos in range(HEIGHT)] ``` <br> 리스트내포 표기를 이중으로 해서 2차원 배열을 초기화합니다. <br> ```buildoutcfg while True: for event in pygame.event.get(): if event.type ==QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN and event.button == 1: xpos, ypos = floor(event.pos[0] / SIZE), floor(event.pos[1]/ SIZE) if field[ypos][xpos] == BOMB: game_over = True else: open_tile(field,xpos,ypos) ``` <br> 이벤트 타입이 quit이면 게임을 종료하고 마우스 왼쪽 버튼을 클릭하면 x 좌표와 y좌료를 size로 나누고 floor를 사용하여 정수로 표현합니다. 이렇게 구한 칸에 폭탄이있다면 게임오버를 알려주고 아니면 타일을 열어주고 있습니다. <br> ```buildoutcfg #화면그리기 SURFACE.fill((0,0,0)) for ypos in range(HEIGHT): for xpos in range(WIDTH): tile = field[ypos][xpos] rect = (xpos*SIZE,ypos*SIZE,SIZE,SIZE) if tile == EMPTY or tile == BOMB: pygame.draw.rect(SURFACE,(192,192,192),rect) if game_over and tile == BOMB: pygame.draw.ellipse(SURFACE,(225,225,0),rect) elif tile == OPENED: count = bomb(field,xpos,ypos) if count>0: num_image = smallfont.render("{}".format(count),True,(255,255,0)) SURFACE.blit(num_image,(xpos*SIZE+10,ypos*SIZE+10)) ``` <br> ```buildoutcfg # 선 그리기 for index in range(0,WIDTH*SIZE, SIZE): pygame.draw.line(SURFACE, (96,96,96),(index,0),(index,HEIGHT*SIZE)) for index in range(0, HEIGHT * SIZE, SIZE): pygame.draw.line(SURFACE,(96,96,96),(0,index),(WIDTH*SIZE,index)) #메세지 나타내기 if OPEN_COUNT == WIDTH *HEIGHT - BOMBS: SURFACE.blit(message_clear,message_rect.topleft) elif game_over: SURFACE.blit(message_over, message_rect.topleft) SURFACE.blit(message_F5, message_rect.bottomleft) pygame.display.update() FPSCLOCK.tick(15) ```
Python
UTF-8
8,190
3
3
[ "MIT" ]
permissive
import os import numpy as np # from scipy.signal import convolve2d import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec def visualize_HiC_epigenetics(HiC, epis, output, fig_width=12.0, vmin=0, vmax=None, cmap='Reds', colorbar=True, colorbar_orientation='vertical', epi_labels=None, x_ticks=None, fontsize=24, epi_colors=None, epi_yaxis=True, heatmap_ratio=0.6, epi_ratio=0.1, interval_after_heatmap=0.05, interval_between_epi=0.01, ): """ Visualize matched HiC and epigenetic signals in one figure Args: HiC (numpy.array): Hi-C contact map, only upper triangle is used. epis (list): epigenetic signals output (str): the output path. Must in a proper format (e.g., 'png', 'pdf', 'svg', ...). fig_width (float): the width of the figure. Then the height will be automatically calculated. Default: 12.0 vmin (float): min value of the colormap. Default: 0 vmax (float): max value of the colormap. Will use the max value in Hi-C data if not specified. cmap (str or plt.cm): which colormap to use. Default: 'Reds' colorbar (bool): whether to add colorbar for the heatmap. Default: True colorbar_orientation (str): "horizontal" or "vertical". Default: "vertical" epi_labels (list): the names of epigenetic marks. If None, there will be no labels at y axis. x_ticks (list): a list of strings. Will be added at the bottom. THE FIRST TICK WILL BE AT THE START OF THE SIGNAL, THE LAST TICK WILL BE AT THE END. fontsize (int): font size. Default: 24 epi_colors (list): colors of epigenetic signals epi_yaxis (bool): whether add y-axis to epigenetic signals. Default: True heatmap_ratio (float): the ratio of (heatmap height) and (figure width). Default: 0.6 epi_ratio (float): the ratio of (1D epi signal height) and (figure width). Default: 0.1 interval_after_heatmap (float): the ratio of (interval between heatmap and 1D signals) and (figure width). Default: 0.05 interval_between_epi (float): the ratio of (interval between 1D signals) and (figure width). Default: 0.01 No return. Save a figure only. """ # Make sure the lengths match # len_epis = [len(epi) for epi in epis] # if max(len_epis) != min(len_epis) or max(len_epis) != len(HiC): # raise ValueError('Size not matched!') N = len(HiC) # Define the space for each row (heatmap - interval - signal - interval - signal ...) rs = [heatmap_ratio, interval_after_heatmap] + [epi_ratio, interval_between_epi] * len(epis) rs = np.array(rs[:-1]) # Calculate figure height fig_height = fig_width * np.sum(rs) rs = rs / np.sum(rs) # normalize to 1 (ratios) fig = plt.figure(figsize=(fig_width, fig_height)) # Split the figure into rows with different heights gs = GridSpec(len(rs), 1, height_ratios=rs) # Ready for plotting heatmap ax0 = plt.subplot(gs[0, :]) # Define the rotated axes and coordinates coordinate = np.array([[[(x + y) / 2, y - x] for y in range(N + 1)] for x in range(N + 1)]) X, Y = coordinate[:, :, 0], coordinate[:, :, 1] # Plot the heatmap vmax = vmax if vmax is not None else np.max(HiC) im = ax0.pcolormesh(X, Y, HiC, vmin=vmin, vmax=vmax, cmap=cmap) ax0.axis('off') ax0.set_ylim([0, N]) ax0.set_xlim([0, N]) if colorbar: if colorbar_orientation == 'horizontal': _left, _width, _bottom, _height = 0.12, 0.25, 1 - rs[0] * 0.25, rs[0] * 0.03 elif colorbar_orientation == 'vertical': _left, _width, _bottom, _height = 0.9, 0.02, 1 - rs[0] * 0.7, rs[0] * 0.5 else: raise ValueError('Wrong orientation!') cbar = plt.colorbar(im, cax=fig.add_axes([_left, _bottom, _width, _height]), orientation=colorbar_orientation) cbar.ax.tick_params(labelsize=fontsize) cbar.outline.set_visible(False) # print(rs/np.sum(rs)) # Ready for plotting 1D signals if epi_labels: assert len(epis) == len(epi_labels) if epi_colors: assert len(epis) == len(epi_colors) for i, epi in enumerate(epis): # print(epi.shape) ax1 = plt.subplot(gs[2 + 2 * i, :]) if epi_colors: ax1.fill_between(np.arange(N), 0, epi, color=epi_colors[i]) else: ax1.fill_between(np.arange(N), 0, epi) ax1.spines['left'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.spines['bottom'].set_visible(False) if not epi_yaxis: ax1.set_yticks([]) ax1.set_yticklabels([]) else: ax1.spines['right'].set_visible(True) ax1.tick_params(labelsize=fontsize) ax1.yaxis.tick_right() if i != len(epis) - 1: ax1.set_xticks([]) ax1.set_xticklabels([]) # ax1.axis('off') # ax1.xaxis.set_visible(True) # plt.setp(ax1.spines.values(), visible=False) # ax1.yaxis.set_visible(True) ax1.set_xlim([-0.5, N - 0.5]) if epi_labels: ax1.set_ylabel(epi_labels[i], fontsize=fontsize, rotation=0) ax1.spines['bottom'].set_visible(True) if x_ticks: tick_pos = np.linspace(0, N - 1, len(x_ticks)) # 这个坐标其实是不对的 差1个bin 但是为了ticks好看只有先这样了 ax1.set_xticks(tick_pos) ax1.set_xticklabels(x_ticks, fontsize=fontsize) else: ax1.set_xticks([]) ax1.set_xticklabels([]) plt.savefig(output) plt.close() if __name__ == '__main__': # Get current path my_path = os.path.abspath(os.path.dirname(__file__)) ####################################################################################### # The below lines need to be consistent with 01_generate_example_input_regions.py ####################################################################################### # Cell name impute_cell_name = 'HFF' # epigenomics names epi_names = ['DNase_seq', 'CTCF', 'H3K4me1', 'H3K4me3', 'H3K27ac', 'H3K27me3'] # The regions you need to impute (must >= 250Kb) ch_coord = {'chr2': (23850000, 24100000)} # temp folder for storage temp_folder = f'{my_path}/temp' ####################################################################################### # The above lines are all you need to set ####################################################################################### for ch in ch_coord: st, ed = ch_coord[ch] # print(ch, st, ed) for position in range(st, ed - 249999, 50000): print(ch, position) hic = np.load(f'{temp_folder}/example_inputs/{ch}_{position}_hic.npy') # print(hic.shape) epi = np.load(f'{temp_folder}/example_inputs/{ch}_{position}_epi.npy') # print(epi.shape) pred = np.load(f'{temp_folder}/example_outputs/{ch}_{position}_pred.npy') # print(pred.shape) visualize_HiC_epigenetics(hic, epi, f'{temp_folder}/example_outputs/{ch}_{position}_input.png', colorbar=True, interval_after_heatmap=0., interval_between_epi=0., epi_labels=epi_names, epi_yaxis=True, fontsize=20, epi_ratio=0.045, x_ticks=['', '', '', '', '', ''], vmax=np.quantile(hic, 0.98)) visualize_HiC_epigenetics(pred, epi, f'{temp_folder}/example_outputs/{ch}_{position}_pred.png', colorbar=True, interval_after_heatmap=0., interval_between_epi=0., epi_labels=epi_names, epi_yaxis=True, fontsize=20, epi_ratio=0.045, x_ticks=['', '', '', '', '', ''], vmax=np.quantile(pred, 0.98))
Java
UTF-8
648
3.390625
3
[]
no_license
import java.util.Scanner; public class essayDeterminer1 { public static void main(String[] args) { int value = 0; do { System.out.println("Enter your email address:"); Scanner input = new Scanner (System.in); String email = input.nextLine(); String verifier = "."; System.out.println(email.charAt(14)); System.out.println(email.length()); // I'm not sure why it isn't working... if (email.substring(email.length()-4) == verifier) { System.out.println("Your email is valid."); } else { System.out.println("Your email is invalid."); } } while(value >= 0); } }
C++
UTF-8
1,158
2.75
3
[ "MIT" ]
permissive
#ifndef INPUT_MANAGER_H #define INPUT_MANAGER_H #define NUM_KEY_INFOS 256 #define KEY_PRESSED 1 // flag, indicating that key was pressed #define KEY_QUERIED 2 // flag, indicating that key was queried #define KEY_MULTI_PRESSED 4 // flag, indicating that key was pressed more than once // INPUT_MANAGER // Simple manager for keyboard-/ mouse-input (based on windows input). class INPUT_MANAGER { public: INPUT_MANAGER() { memset(keyInfos,0,NUM_KEY_INFOS*sizeof(int)); } // gets windows input messages bool GetInputMessages(UINT uMsg,WPARAM wParam); // updates keyInfos per frame void Update(); // returns true, as long as key pressed bool GetTriggerState(unsigned char keyCode); // returns true, exactly once, when key is pressed bool GetSingleTriggerState(unsigned char keyCode); // gets mouse-position in screen-space POINT GetMousePos() const; // centers mouse-position in screen-space void CenterMousePos() const; private: // sets key-state void SetTriggerState(unsigned char keyCode,bool pressed); // array of keyInfos (each representing a bitmask, holding flags) int keyInfos[NUM_KEY_INFOS]; }; #endif
Markdown
UTF-8
4,001
3.0625
3
[]
no_license
--- author: hzmangel categories: - Happy coding date: '2007-06-14T09:37:03' tags: [] title: 说说回调 --- 最近做个项目,在设计的时候想到有可能要用到回调,对于这个东西已经弄不懂很久了,于是就上网找资料看,经过一个程序的磨炼后,差不多弄懂了,说说吧。<!--more-->默认情况下,函数调用的过程是这样的:程序中某懒人A想做件事,但是不想自己去做,于是用了个时髦的方法,外包给B(函数调用),然后B辛辛苦苦的把事情做完后,把结 果再恭恭敬敬的送给(return)一直在那等着(阻塞调用)的A,然后A把剩下的钱给B,两清了。经过了这次事情,这两人就有了业务上的联系,A经常把事情外包给B ,B也经常从A那拿到钱,皆大欢喜。但是突然有一天,A扔给了B一个任务,与往常不同的是,A还扔给了B一个联系方式,上面写着怎么去找C(函数的地址)。原来A发现 这个活有些地方B不一定做的好,而C可以做好,为了不让B自己在那瞎折腾,顺便把C的地址也给了他。后面的嘛,自然,B在C的帮助下做好了这件事,按时完工。 差不多就是这样,调用者A在传给B的参数中加上了一个指向函数的指针C,在B中要调用C来完成工作。想看例子的话,可以去看STL中的qsort,它的最后一个参数就 是一个函数指针,要利用传递进去的函数来做比较,进行排序。从网上找一段: 函数之类本是为调用者准备的美餐,其烹制者应对食客了如指掌,但实情并非如此。例如,写一个快速排序函数供他人调用,其中必包含比较大小。麻烦来了:此时并不知要比较 的是何类数据--整数、浮点数、字符串?于是只好为每类数据制作一个不同的排序函数。更通行的办法是在函数参数中列一个回调函数地址,并通知调用者:君需自己准备一个 比较函数,其中包含两个指针类参数,函数要比较此二指针所指数据之大小,并由函数返回值说明比较结果。排序函数借此调用者提供的函数来比较大小,借指针传递参数,可以 全然不管所比较的数据类型。被调用者回头调用调用者的函数(够咬嘴的),故称其为回调(callback)。 回调函数的作用差不多弄明白了,下面就要开始写了。刚啃回调的时候看不懂,请教了身边的几个人,清一色告诉我说回调是Windos下的,要用WinAPI,当时那叫一 个郁闷啊。后来仔细一下,不对,于是开始满世界的google,最后终于被我找到了一个例子,拿来,看差不多明白了,自己随便改了一下,发上来吧 **19 ****#include ****<string>** **20 ****#include ****<iostream>** **21 ****#include ****<boost/function.hpp>** **22 ** **23 ****using** **namespace** std; **24 ****using** **namespace** boost; **25 ** **26 ****static** **void** foo() **27 **{ **28 ** cout << **"Hello World"** << endl; **29 **} **30 ** **31 ****static** **void** bar(**int** f_times, boost::function<**void** ()> f_fun) **32 **{ **33 ** **for** (**int** i = **0**; i < f_times; i++) **34 ** { **35 ** f_fun(); **36 ** } **37 **} **38 ** **39 ****int** main() **40 **{ **41 ** bar(**10**, foo); **42 ** **return** **0**; **43 **} 前面的注释没弄上来,foo函数是我自己定义的一个函数,而bar就是传说中的回调函数,传递给它的参数中有一个函数指针,用的是boost库的东西,然后bar在执 行的过程中调用foo,看上去应该还算清楚。 都是自己琢磨的东西,希望木有错。
Python
UTF-8
5,543
2.9375
3
[]
no_license
import matplotlib.pyplot as plt from ClusteringAlgorithm.ABClustering import ABClustering from ClusteringAlgorithm.ABClassifier import ABClassifier from utils.ClusteringObjectiveFunction import * import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, accuracy_score import time """ plotting the points where the x & y axises are the second and forth features the left graph illustrates the clusters in the first round and the right graph illustrates the clusters in the end of the ABC algorithm """ def clustering_with_abc(): data = MinMaxScaler().fit_transform(load_iris()['data'][:, [1, 3]]) objective_function1 = SSE(dim=6, n_centroids=3, data=data) abc1 = ABClustering(objective_function=objective_function1, colony_size=30, cycles=300, max_tries_employee=100, max_tries_onlooker=100, processing_opt=None) abc1.optimize() plt.figure(figsize=(9, 8)) plt.subplot(1, 2, 1) centroids = dict(enumerate(decode_centroids(abc1.optimal_value_tracking[0][0], n_clusters=3, data=data))) custom_tgt = [] for instance in data: custom_tgt.append(assign_centroid(centroids, instance)) colors = ['r', 'g', 'y'] for instance, tgt in zip(data, custom_tgt): plt.scatter(instance[0], instance[1], s=50, edgecolor='w', alpha=0.5, color=colors[tgt]) for centroid in centroids: plt.scatter(centroids[centroid][0], centroids[centroid][1], color='k', marker='x', lw=3, s=500) plt.title('Iris dataset partitioned by ABC - round 1') plt.subplot(1, 2, 2) centroids = dict(enumerate(decode_centroids(abc1.get_best_source(), n_clusters=3, data=data))) custom_tgt = [] for instance in data: custom_tgt.append(assign_centroid(centroids, instance)) colors = ['r', 'g', 'y'] for instance, tgt in zip(data, custom_tgt): plt.scatter(instance[0], instance[1], s=50, edgecolor='w', alpha=0.5, color=colors[tgt]) for centroid in centroids: plt.scatter(centroids[centroid][0], centroids[centroid][1], color='k', marker='x', lw=3, s=500) plt.title('Iris dataset partitioned by ABC - final') plt.show() def decode_centroids(centroids, n_clusters, data): return np.reshape(centroids, (n_clusters, data.shape[1])) def assign_centroid(centroids, point): distances = [np.linalg.norm(point - centroids[idx]) for idx in centroids] return np.argmin(distances) """ testing various colony sizes mixed with different ratios of employees to onlookers moreover, plotting the time taken to train & predict by the model in various colony sizes """ def plot_iris_testing_ratio_colony_sizes_time(): datasets = { 'iris': load_iris(), } colony_sizes = [10 * (i + 1) for i in range(13)] all_a = [[] for _ in range(7)] all_times = [] for c_size in colony_sizes: for i in range(len(all_a)): dataset = datasets['iris'] data = dataset.data X_train, X_test, y_train, y_test = train_test_split(data, dataset.target, test_size=0.25, random_state=42, stratify=dataset.target) classifier = ABClassifier(colony_size=c_size, employee_to_onlooker_ratio=(i+1)*0.25) try: t0 = time.time() classifier.fit(X_train, y_train.tolist()) labels = classifier.predict(X_test) t1 = time.time() print(confusion_matrix(y_true=y_test, y_pred=labels)) all_a[i].append(accuracy_score(y_true=y_test, y_pred=labels)) if i == 2: all_times.append(t1-t0) except: all_a[i].append(0) if i == 2: all_times.append(0) """ plotting the graphs: the right is time taken to predict & train the model with default ratio (1.0) the left is the different ratios in various sizes of populations """ plt.figure(1, figsize=(6, 3)) plt.subplot(1, 2, 1) for i in range(len(all_a)): plt.plot(colony_sizes, all_a[i]) plt.ylabel('accuracy') plt.xlabel('colony size') plt.legend(['1/2', '3/4', '1/1', '5/4', '3/2', '7/4', '2/1'], loc='upper left') plt.subplot(1, 2, 2) plt.bar(colony_sizes, all_times) plt.ylabel('time to train and predict') plt.xlabel('colony size') plt.show() def clustering_illustration_abc(): data = MinMaxScaler().fit_transform(load_iris()['data'][:, [1, 3]]) objective_function1 = SSE(dim=6, n_centroids=3, data=data) abc1 = ABClustering(objective_function=objective_function1, colony_size=30, cycles=300, max_tries_employee=100, max_tries_onlooker=100, processing_opt=None) abc1.optimize() d_s = {'cluster centers': [np.reshape(i, (3, 2)) for i, j in abc1.optimal_value_tracking], 'SSE': [j for i, j in abc1.optimal_value_tracking]} pd.DataFrame.from_dict(d_s).to_csv('abc_illustration.csv') if __name__ == '__main__': # clustering_with_abc() # plot_iris_testing_ratio_colony_sizes_time() clustering_illustration_abc()
Java
UTF-8
354
2.5
2
[]
no_license
import java.text.MessageFormat; public class MessageFormats { public static void main(String[] args) { // TODO Auto-generated method stub String 버뮤다="이름:{0},그레이드:{1},파워{2}"; String[] 피나= {"피나","3","13000"}; String b=MessageFormat.format(버뮤다, 피나); System.out.print(b); } }
Swift
UTF-8
6,160
3.609375
4
[ "Apache-2.0" ]
permissive
/// Witness for the `Trampoline<A>` data type. To be used in simulated Higher Kinded Types. public final class ForTrampoline {} /// Partial application of the Trampoline type constructor, omitting the last type parameter. public typealias TrampolinePartial = ForTrampoline /// Higher Kinded Type alias to improve readability over `Kind<ForTrampoline, A>` public typealias TrampolineOf<A> = Kind<ForTrampoline, A> /// The Trampoline type helps us overcome stack safety issues of recursive calls by transforming them into loops. public final class Trampoline<A>: TrampolineOf<A> { fileprivate init(_ value: _Trampoline<A>) { self.value = value } fileprivate let value: _Trampoline<A> /// Creates a Trampoline that does not need to recurse and provides the final result. /// /// - Parameter value: Result of the computation. /// - Returns: A Trampoline that provides a value and stops recursing. public static func done(_ value: A) -> Trampoline<A> { Trampoline(.done(value)) } /// Creates a Trampoline that performs a computation and needs to recurse. /// /// - Parameter f: Function describing the recursive step. /// - Returns: A Trampoline that describes a recursive step. public static func `defer`(_ f: @escaping () -> Trampoline<A>) -> Trampoline<A> { Trampoline(.defer(f)) } /// Creates a Trampoline that performs a computation in a moment in the future. /// /// - Parameter f: Function to compute the value wrapped in this Trampoline. /// - Returns: A Trampoline that delays the obtention of a value and stops recursing. public static func later(_ f: @escaping () -> A) -> Trampoline<A> { .defer { .done(f()) } } /// Executes the computations described by this Trampoline by converting it into a loop. /// /// - Returns: Value resulting from the execution of the Trampoline. public final func run() -> A { var trampoline = self while true { let step = trampoline.step() if step.isLeft { trampoline = step.leftValue() } else { return step.rightValue } } } internal func step() -> Either<() -> Trampoline<A>, A> { value.step() } /// Safe downcast. /// /// - Parameter fa: Value in the higher-kind form. /// - Returns: Value cast to Trampoline. public static func fix(_ fa: TrampolineOf<A>) -> Trampoline<A> { fa as! Trampoline<A> } } /// Safe downcast. /// /// - Parameter fa: Value in higher-kind form. /// - Returns: Value cast to Trampoline. public postfix func ^<A>(_ fa: TrampolineOf<A>) -> Trampoline<A> { Trampoline.fix(fa) } /// Internal representation of `Trampoline` private enum _Trampoline<A> { case done(A) case `defer`(() -> Trampoline<A>) case flatMap(Coyoneda<ForTrampoline, Trampoline<A>>) func step() -> Either<() -> Trampoline<A>, A> { switch self { case .done(let a): return .right(a) case .defer(let deferred): return .left(deferred) case .flatMap(let coyoneda): return coyoneda.coyonedaF.run(FlatMapStep()) } } func map<B>(_ g: @escaping (A) -> B) -> Trampoline<B> { switch self { case .done(let a): return .later { g(a) } case .defer(let f): return .defer { f().map(g)^ } case .flatMap: return flatMap(Trampoline.done <<< g) } } func flatMap<B>(_ f: @escaping (A) -> Trampoline<B>) -> Trampoline<B> { switch self { case .done, .defer: return Trampoline(.flatMap(Coyoneda(pivot: Trampoline(self), f: f))) case .flatMap(let coyoneda): return coyoneda.coyonedaF.run(FlatMapFlatMap(f)) } } } private final class FlatMapStep<A>: CokleisliK<CoyonedaFPartial<ForTrampoline, Trampoline<A>>, Either<() -> Trampoline<A>, A>> { override init() {} override func invoke<X>(_ fa: CoyonedaFOf<ForTrampoline, Trampoline<A>, X>) -> Either<() -> Trampoline<A>, A> { let pivot = fa^.pivot^ let f = fa^.f switch pivot.value { case .done(let x): return .left { [f] in f(x) } case .defer(let deferred): return .left { [f] in deferred().flatMap(f.invoke)^ } default: fatalError("Invalid Trampoline case") } } } private final class FlatMapFlatMap<A, B>: CokleisliK<CoyonedaFPartial<ForTrampoline, Trampoline<A>>, Trampoline<B>> { init(_ g: @escaping (A) -> Trampoline<B>) { self.g = g } let g: (A) -> Trampoline<B> override func invoke<X>(_ fa: CoyonedaFOf<ForTrampoline, Trampoline<A>, X>) -> Trampoline<B> { let pivot = fa^.pivot^ let f = fa^.f return Trampoline( .flatMap( Coyoneda( pivot: pivot, f: { [g] a in f(a).flatMap(g)^ }) ) ) } } // MARK: Instance of Functor for Trampoline extension TrampolinePartial: Functor { public static func map<A, B>(_ fa: TrampolineOf<A>, _ f: @escaping (A) -> B) -> TrampolineOf<B> { fa^.value.map(f) } } // MARK: Instance of Applicative for Trampoline extension TrampolinePartial: Applicative { public static func pure<A>(_ a: A) -> TrampolineOf<A> { Trampoline.done(a) } } // MARK: Instance of Selective for Trampoline extension TrampolinePartial: Selective {} // MARK: Instance of Monad for Trampoline extension TrampolinePartial: Monad { public static func flatMap<A, B>(_ fa: TrampolineOf<A>, _ f: @escaping (A) -> TrampolineOf<B>) -> TrampolineOf<B> { fa^.value.flatMap { f($0)^ } } public static func tailRecM<A, B>(_ a: A, _ f: @escaping (A) -> TrampolineOf<Either<A, B>>) -> TrampolineOf<B> { f(a)^.flatMap { e in e.fold { a in return tailRecM(a, f) } _: { b in return Trampoline.done(b) } } } }
Markdown
UTF-8
807
2.890625
3
[]
no_license
# NPM NPM comes shipped with an installation of Node.js Npm allows us to use third party packages The project will end up being a combination of code sources. --* <Developer> --* <Node Core Packages> --* <Dependencies> The dependencies are essentially the packages we install/manage via NPM and track with the package.json file. Run npm install to install dependencies The package.json lock file indicates the exact version used upon initial installation. Useful for sharing repos/code or debugging issues. Third party modules will need to be both installed via npm and imported, akin to the core modules. //example Core Module ~~~ const html = require('html') ~~~ //example Third party module ~~~ //command line npm install emojis //within file const smile = require('emojis-smile'); ~~~
Java
UTF-8
450
2.46875
2
[]
no_license
package com.cendric.ecs.systems; import java.util.List; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.cendric.ecs.Entity; public abstract class RenderSystem { public void render(List<Entity> entities, SpriteBatch spriteBatch, float stateTime) { for (Entity e : entities) { render(e, spriteBatch, stateTime); } } protected abstract void render(Entity entity, SpriteBatch spriteBatch, float stateTime); }
Python
UTF-8
1,384
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LGPL-2.1-only", "Python-2.0", "GPL-3.0-only", "BSD-3-Clause", "MIT", "GPL-1.0-or-later", "LGPL-2.0-or-later", "GPL-2.0-only", "BSD-2-Clause" ]
permissive
# coding: utf-8 # Back to the main [Index](../index.ipynb) # ### Parameter scan # Perform a parameter scan. # In[1]: #!!! DO NOT CHANGE !!! THIS FILE WAS CREATED AUTOMATICALLY FROM NOTEBOOKS !!! CHANGES WILL BE OVERWRITTEN !!! CHANGE CORRESPONDING NOTEBOOK FILE !!! from __future__ import print_function import tellurium as te r = te.loada(''' J1: $Xo -> x; 0.1 + k1*x^4/(k2+x^4); x -> $w; k3*x; k1 = 0.9; k2 = 0.3; k3 = 0.7; x = 0; ''') # parameter scan p = te.ParameterScan(r, # settings startTime = 0, endTime = 15, numberOfPoints = 50, polyNumber = 10, endValue = 1.8, alpha = 0.8, value = "x", selection = "x", color = ['#0F0F3D', '#141452', '#1A1A66', '#1F1F7A', '#24248F', '#2929A3', '#2E2EB8', '#3333CC', '#4747D1', '#5C5CD6'] ) # plot p.plotPolyArray() # In[2]: r = te.loada(''' $Xo -> S1; vo; S1 -> S2; k1*S1 - k2*S2; S2 -> $X1; k3*S2; vo = 1 k1 = 2; k2 = 0; k3 = 3; ''') # parameter scan p = te.ParameterScan(r, # settings startTime = 0, endTime = 6, numberOfPoints = 50, startValue = 1, endValue = 5, colormap = "cool", independent = ["Time", "k1"], dependent = "S1", xlabel = "Time", ylabel = "x", title = "Model" ) # plot p.plotSurface() # In[3]:
TypeScript
UTF-8
1,551
2.765625
3
[]
no_license
import Controller from './controller/controller' import LogicModel from './model/logicModel/logicModel' import Mediator from './model/logicModel/mediator/mediator' import UIModel from './model/uiModel/uiModel' import ImageLoader from './view/subrenderers/imageLoader/imageLoader' import View from './view/view' // ? Load spritesheetData by config? import terrainsheetData from '../assets/terrain/terrainsheetData' import uisheetData from '../assets/ui/uiSheetData' import unitsheetData from '../assets/units/unitsheetData' export default class Engine { public view: View public controller: Controller public uiModel: UIModel public logicModel: LogicModel constructor() { // this could be `new LogicModel()` in a local version, as mediator will implement the LogicModel interface this.logicModel = new Mediator() this.uiModel = new UIModel(this.logicModel) this.view = new View( this.logicModel, this.uiModel, { terrain: terrainsheetData, ui: uisheetData, units: unitsheetData }, ) this.controller = new Controller(this.uiModel) // And this.view if using mouse input? this.performAsyncSetup() } public async performAsyncSetup() { // Call and await all initial async functions here. // Eg. this.view.loadSpritesheets() await Promise.all([ ImageLoader.load(terrainsheetData, uisheetData, unitsheetData), // Any other async set up functions ]) this.runGame() } public runGame() { setInterval(() => { this.view.render() }, 1000 / 30) } }
Python
UTF-8
1,053
4.15625
4
[]
no_license
#!/usr/bin/python3 # encoding:utf_8 # 第十五题 一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3。 # 首先,先设置1000以内的数循环 for wanshu in range(2,10001): a=0 yinzi=[] i=wanshu while (i!=1): for y in range(2, int(i + 1)): if i%y==0: i/=y yinzi.append(y) break for z in range(0,len(yinzi)): a+=yinzi[z] if (a+1)==wanshu: print(wanshu) # for wanshu in range(2, 1001): # a = 0 # # 建立列表,保存因子 # yinzi = [] # i = wanshu # # 设置内循环,找出所有因子(前面题目有详细解释) # while (i != 1): # for y in range(2, int(i+1)): # if i % y == 0: # i /= y # yinzi.append(y) # break # # 求出列表里所有数的和 # for z in range(0, len(yinzi)): # a += yinzi[z] # # 不要忘记1 # if (a+1) == wanshu: # print(wanshu)
Java
UTF-8
1,026
3.90625
4
[]
no_license
package java0522_collection; /* * stack * 1 LIFO(Last In First Out) : 마지막에 저장된 요소를 먼저 꺼낸다. * 2 수식계산, 수식괄호검사, undo/redo, 뒤로/앞으로 */ import java.util.LinkedList; public class Java182_LinkedList { public static void main(String[] args) { LinkedList<String> nStack = new LinkedList<String>(); //추가 //stack을 사용하려면 push()메소드를 써야 한다. nStack.push(new String("java")); nStack.push(new String("jsp")); nStack.push(new String("spring")); System.out.println("size:" + nStack.size()); /* System.out.println(nStack.pop()); System.out.println(nStack.pop()); System.out.println(nStack.pop()); */ //반복문을 쓰면 안 가져옴. 왜? pop은 get()과 달리 완전히 꺼내오기 때문이다. 그럼 뭘 써야 할까? isEmpty! for(int i=0; i<nStack.size(); i++) System.out.println(nStack.pop()); while(!nStack.isEmpty()) System.out.println(nStack.pop()); } // end main() } // end class
Java
UTF-8
887
2.578125
3
[]
no_license
package com.edu.upc.businessbook.models; import com.edu.upc.businessbook.R; import java.util.ArrayList; import java.util.List; public class LocalsRepository { private static LocalsRepository instance; private List<Local> locals; public static LocalsRepository getInstance(){ if(instance == null) instance = new LocalsRepository(); return instance; } public List<Local> getLocals() { if (locals == null) init(); return locals; } private LocalsRepository init(){ locals = new ArrayList<>(); locals.add( new Local("Local 1", "Av. Marina","ACT", R.drawable.img_marketplace_logo)); locals.add( new Local("Local 2", "Av. La Paz", "ACT", R.drawable.img_marketplace_logo)); locals.add( new Local("Local 3", "Av. Salaverry", "ACT", R.drawable.img_marketplace_logo)); return this; } }
C#
UTF-8
3,176
2.5625
3
[]
no_license
namespace Shrinkr.Infrastructure.EntityFramework { using System; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.Infrastructure; public class DatabaseFactory : Disposable, IDatabaseFactory { private static readonly object syncObject = new object(); private readonly DbProviderFactory providerFactory; private readonly string connectionString; private static DbCompiledModel model; private Database database; public DatabaseFactory(DbProviderFactory providerFactory, string connectionString) { Check.Argument.IsNotNull(providerFactory, "providerFactory"); Check.Argument.IsNotNullOrEmpty(connectionString, "connectionString"); this.providerFactory = providerFactory; this.connectionString = connectionString; } public virtual Database Get() { if (database == null) { DbConnection connection = providerFactory.CreateConnection(); if (connection != null) { connection.ConnectionString = connectionString; if (model == null) { lock (syncObject) { if (model == null) { model = CreateDbModel(connection); } } } database = model.CreateObjectContext<Database>(connection); } return database; } return database; } [DebuggerStepThrough] protected override void DisposeCore() { if (database != null) { database.Dispose(); } } private static DbCompiledModel CreateDbModel(DbConnection connection) { var modelBuilder = new DbModelBuilder(); IEnumerable<Type> configurationTypes = typeof(DatabaseFactory).Assembly .GetTypes() .Where( type => type.IsPublic && type.IsClass && !type.IsAbstract && !type.IsGenericType && type.BaseType != null && type.BaseType.IsGenericType && (type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>) || type.BaseType.GetGenericTypeDefinition() == typeof(ComplexTypeConfiguration<>)) && (type.GetConstructor(Type.EmptyTypes) != null)); foreach (var configuration in configurationTypes.Select(Activator.CreateInstance)) { modelBuilder.Configurations.Add((dynamic)configuration); } return modelBuilder.Build(connection).Compile(); } } }
Java
UTF-8
5,315
1.921875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.afp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import org.junit.Test; import static org.junit.Assert.assertTrue; import org.apache.commons.io.IOUtils; import org.apache.fop.afp.util.AFPResourceUtil; /** * Tests the {@link AFPResourceUtil} class. */ public class AFPResourceUtilTestCase { private static final String RESOURCE_FILENAME = "expected_resource.afp"; private static final String NAMED_RESOURCE_FILENAME = "expected_named_resource.afp"; private static final String RESOURCE_ANY_NAME = "resource_any_name.afp"; private static final String RESOURCE_NAME_MATCH = "resource_name_match.afp"; private static final String RESOURCE_NAME_MISMATCH = "resource_name_mismatch.afp"; private static final String RESOURCE_NO_END_NAME = "resource_no_end_name.afp"; private static final String PSEG_A = "XFEATHER"; private static final String PSEG_B = "S1CODEQR"; /** * Tests copyResourceFile() * @throws Exception - */ @Test public void testCopyResourceFile() throws Exception { compareResources(new ResourceCopier() { public void copy(InputStream in, OutputStream out) throws IOException { AFPResourceUtil.copyResourceFile(in, out); } }, RESOURCE_FILENAME, RESOURCE_FILENAME); } /** * Tests copyNamedResource() * @throws Exception - */ @Test public void testCopyNamedResource() throws Exception { compareResources(new ResourceCopier() { public void copy(InputStream in, OutputStream out) throws IOException { AFPResourceUtil.copyNamedResource(PSEG_A, in, out); } }, RESOURCE_FILENAME, NAMED_RESOURCE_FILENAME); } private void compareResources(ResourceCopier copyResource, String resourceA, String resourceB) throws IOException { ByteArrayOutputStream baos = copyResource(resourceA, copyResource); byte[] expectedBytes = resourceAsByteArray(resourceB); assertTrue(Arrays.equals(expectedBytes, baos.toByteArray())); } private ByteArrayOutputStream copyResource(String resource, ResourceCopier resourceCopier) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = null; try { in = getClass().getResourceAsStream(resource); resourceCopier.copy(in, baos); } finally { in.close(); } return baos; } private byte[] resourceAsByteArray(String resource) throws IOException { InputStream in = null; byte[] expectedBytes = null; try { in = getClass().getResourceAsStream(resource); expectedBytes = IOUtils.toByteArray(in); } finally { in.close(); } return expectedBytes; } /** * Tests the validity of a closing structured field having an FF FF name which * allows it to match any existing matching starting field * @throws Exception - */ @Test public void testResourceAnyName() throws Exception { testResource(RESOURCE_ANY_NAME, PSEG_B); } /** * Tests a matching end structured field name * @throws Exception - */ @Test public void testResourceNameMatch() throws Exception { testResource(RESOURCE_NAME_MATCH, PSEG_B); } /** * Tests to see whether a matching structured field pair with mismatching * names fails. * @throws Exception - */ @Test(expected = Exception.class) public void testResourceNameMismatch() throws Exception { testResource(RESOURCE_NAME_MISMATCH, PSEG_B); } /** * Tests a matching structured end field with no name * @throws Exception - */ @Test public void testResourceNoEndName() throws Exception { testResource(RESOURCE_NO_END_NAME, PSEG_B); } private void testResource(String resource, final String pseg) throws Exception { copyResource(resource, new ResourceCopier() { public void copy(InputStream in, OutputStream out) throws IOException { AFPResourceUtil.copyNamedResource(pseg, in, out); } }); } private interface ResourceCopier { void copy(InputStream in, OutputStream out) throws IOException; } }
Python
UTF-8
443
3.203125
3
[]
no_license
import json # using json library, open file tweetFile = open("../TwitterData/tweets_small.json", "r") # load file to new variable tweetData = json.load(tweetFile) tweetFile.close() print("Tweet id: ",tweetData[0]["id"]) print("Tweet text: ", tweetData[0]["text"]) # shortcut for idx in tweetData: print("Tweet text: " + tweet["text"]) # other way for idx in range(len(tweetdata)): print("Tweet text: " + tweeDatat[idx]["text"])
Java
UTF-8
7,177
1.8125
2
[ "Apache-2.0" ]
permissive
/* * #! * % * Copyright (C) 2014 - 2016 Humboldt-Universität zu Berlin * % * 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 de.hub.cs.dbis.lrb.operators; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.stubbing.OngoingStubbing; import org.powermock.modules.junit4.PowerMockRunner; import backtype.storm.task.OutputCollector; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import de.hub.cs.dbis.aeolus.testUtils.TestDeclarer; import de.hub.cs.dbis.aeolus.testUtils.TestOutputCollector; import de.hub.cs.dbis.aeolus.utils.TimestampMerger; import de.hub.cs.dbis.lrb.queries.utils.TopologyControl; import de.hub.cs.dbis.lrb.types.AccountBalanceRequest; import de.hub.cs.dbis.lrb.types.DailyExpenditureRequest; import de.hub.cs.dbis.lrb.types.PositionReport; import de.hub.cs.dbis.lrb.types.TravelTimeRequest; /** * @author mjsax */ @RunWith(PowerMockRunner.class) public class DispatcherBoltTest { @SuppressWarnings("boxing") @Test public void testExecute() { List<Values> expectedResult = new ArrayList<Values>(); expectedResult.add(new PositionReport((short)8400, 32, 0, 0, (short)1, (short)0, (short)2, 11559)); expectedResult.add(new AccountBalanceRequest((short)8410, 106483, 42)); expectedResult.add(new DailyExpenditureRequest((short)8420, 104954, 4, 43, (short)3)); expectedResult.add(new TravelTimeRequest((short)8430, 104596, 3, 44, (short)5, (short)8, (short)4, (short)67)); Tuple tuple = mock(Tuple.class); when(tuple.getSourceStreamId()).thenReturn("streamId"); // Type, Time, VID, Spd, XWay, Lane, Dir, Seg, Pos, QID, S_init, S_end, DOW, TOD, Day OngoingStubbing<String> tupleStub1 = when(tuple.getString(1)); tupleStub1 = tupleStub1.thenReturn("0,8400,32,0,0,1,0,2,11559,-1,-1,-1,-1,-1,-1"); tupleStub1 = tupleStub1.thenReturn("2,8410,106483,-1,-1,-1,-1,-1,-1,42,-1,-1,-1,-1,-1"); tupleStub1 = tupleStub1.thenReturn("3,8420,104954,-1,4,-1,v,-1,-1,43,-1,-1,-1,-1,3"); tupleStub1 = tupleStub1.thenReturn("4,8430,104596,-1,3,-1,-1,-1,-1,44,5,8,4,67,-1"); tupleStub1.thenReturn(null); OngoingStubbing<Long> tupleStub2 = when(tuple.getLong(0)); tupleStub2 = tupleStub2.thenReturn(8400L); tupleStub2 = tupleStub2.thenReturn(8410L); tupleStub2 = tupleStub2.thenReturn(8420L); tupleStub2 = tupleStub2.thenReturn(8430L); tupleStub2.thenReturn(null); DispatcherBolt bolt = new DispatcherBolt(); TestOutputCollector collector = new TestOutputCollector(); bolt.prepare(null, null, new OutputCollector(collector)); for(int i = 0; i < 4; ++i) { bolt.execute(tuple); } Assert.assertEquals(4, collector.output.size()); Assert.assertEquals(1, collector.output.get(TopologyControl.POSITION_REPORTS_STREAM_ID).size()); Assert.assertEquals(1, collector.output.get(TopologyControl.ACCOUNT_BALANCE_REQUESTS_STREAM_ID).size()); Assert.assertEquals(1, collector.output.get(TopologyControl.DAILY_EXPEDITURE_REQUESTS_STREAM_ID).size()); Assert.assertEquals(1, collector.output.get(TopologyControl.TRAVEL_TIME_REQUEST_STREAM_ID).size()); Assert.assertEquals(expectedResult.get(0), collector.output.get(TopologyControl.POSITION_REPORTS_STREAM_ID) .get(0)); Assert.assertEquals(expectedResult.get(1), collector.output.get(TopologyControl.ACCOUNT_BALANCE_REQUESTS_STREAM_ID).get(0)); Assert.assertEquals(expectedResult.get(2), collector.output.get(TopologyControl.DAILY_EXPEDITURE_REQUESTS_STREAM_ID).get(0)); Assert.assertEquals(expectedResult.get(3), collector.output.get(TopologyControl.TRAVEL_TIME_REQUEST_STREAM_ID) .get(0)); Assert.assertNull(collector.output.get(TimestampMerger.FLUSH_STREAM_ID)); Tuple flushTuple = mock(Tuple.class); when(flushTuple.getSourceStreamId()).thenReturn(TimestampMerger.FLUSH_STREAM_ID); bolt.execute(flushTuple); Assert.assertEquals(1, collector.output.get(TimestampMerger.FLUSH_STREAM_ID).size()); Assert.assertEquals(new Values((Object)null), collector.output.get(TimestampMerger.FLUSH_STREAM_ID).get(0)); } @Test public void testDeclareOutputFields() { DispatcherBolt bolt = new DispatcherBolt(); TestDeclarer declarer = new TestDeclarer(); bolt.declareOutputFields(declarer); final int numberOfOutputStreams = 5; Assert.assertEquals(numberOfOutputStreams, declarer.streamIdBuffer.size()); Assert.assertEquals(numberOfOutputStreams, declarer.schemaBuffer.size()); Assert.assertEquals(numberOfOutputStreams, declarer.directBuffer.size()); HashMap<String, Fields> expectedStreams = new HashMap<String, Fields>(); expectedStreams.put(TopologyControl.POSITION_REPORTS_STREAM_ID, new Fields(TopologyControl.TYPE_FIELD_NAME, TopologyControl.TIMESTAMP_FIELD_NAME, TopologyControl.VEHICLE_ID_FIELD_NAME, TopologyControl.SPEED_FIELD_NAME, TopologyControl.XWAY_FIELD_NAME, TopologyControl.LANE_FIELD_NAME, TopologyControl.DIRECTION_FIELD_NAME, TopologyControl.SEGMENT_FIELD_NAME, TopologyControl.POSITION_FIELD_NAME)); expectedStreams.put(TopologyControl.ACCOUNT_BALANCE_REQUESTS_STREAM_ID, new Fields( TopologyControl.TYPE_FIELD_NAME, TopologyControl.TIMESTAMP_FIELD_NAME, TopologyControl.VEHICLE_ID_FIELD_NAME, TopologyControl.QUERY_ID_FIELD_NAME)); expectedStreams.put(TopologyControl.DAILY_EXPEDITURE_REQUESTS_STREAM_ID, new Fields( TopologyControl.TYPE_FIELD_NAME, TopologyControl.TIMESTAMP_FIELD_NAME, TopologyControl.VEHICLE_ID_FIELD_NAME, TopologyControl.XWAY_FIELD_NAME, TopologyControl.QUERY_ID_FIELD_NAME, TopologyControl.DAY_FIELD_NAME)); expectedStreams.put(TopologyControl.TRAVEL_TIME_REQUEST_STREAM_ID, new Fields(TopologyControl.TYPE_FIELD_NAME, TopologyControl.TIMESTAMP_FIELD_NAME, TopologyControl.VEHICLE_ID_FIELD_NAME, TopologyControl.XWAY_FIELD_NAME, TopologyControl.QUERY_ID_FIELD_NAME, TopologyControl.START_SEGMENT_FIELD_NAME, TopologyControl.END_SEGMENT_FIELD_NAME, TopologyControl.DAY_OF_WEEK_FIELD_NAME, TopologyControl.TIME_OF_DAY_FIELD_NAME)); expectedStreams.put(TimestampMerger.FLUSH_STREAM_ID, new Fields("ts")); Assert.assertEquals(expectedStreams.keySet(), new HashSet<String>(declarer.streamIdBuffer)); for(int i = 0; i < numberOfOutputStreams; ++i) { Assert.assertEquals(expectedStreams.get(declarer.streamIdBuffer.get(i)).toList(), declarer.schemaBuffer .get(i).toList()); Assert.assertEquals(new Boolean(false), declarer.directBuffer.get(i)); } } }
Python
UTF-8
1,232
2.578125
3
[]
no_license
from configparser import ConfigParser from pathlib import Path import getpass class GrenierRemote(object): def __init__(self, name, rclone_config_file): self.name = name self.is_directory = False self.is_disk = False self.is_cloud = False self.full_path = None if Path(name).is_absolute(): self.full_path = Path(name) self.is_directory = True elif Path("/run/media/%s/%s" % (getpass.getuser(), name)).exists(): self.full_path = Path("/run/media/%s/%s" % (getpass.getuser(), name)) self.is_disk = True else: # out of options... # check if known rclone remote conf = ConfigParser() conf.read(str(rclone_config_file)) self.is_cloud = self.name in conf.sections() @property def is_known(self): return self.is_cloud or self.is_directory or self.is_disk def __str__(self): if self.is_directory: return "%s (dir)" % self.name elif self.is_disk: return "%s (disk)" % self.name elif self.is_cloud: return "%s (cloud)" % self.name else: return "%s (unknown)" % self.name
C++
UTF-8
615
3.21875
3
[]
no_license
#ifndef __BUBBLE_H__ #define __BUBBLE_H__ #include "DynArray.h" template <class TYPE> class BubbleSort { public: DynArray<TYPE> data; int times = 0; BubbleSort(){} BubbleSort(DynArray<TYPE> A) { data = A; } int SortBigger() { int size = data.GetSize(); bool finished = false; while (!finished) { printf("Fila: "); int a = times; for (int i = 0; i < (size - 1); i++) { if (data[i] > data[i + 1]) { times += 1; data.Swap(i, i + 1); } printf("%i ", data[i]); } printf("\n"); if (a == times) finished = true; } return times; } }; #endif
C
UTF-8
2,412
3.953125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> // Функция -- сравнение 2-х символов // Возвращает число < 0 если символ, хранящийся по адресу p1 < символа, хранящегося по адресу p2 // (в кодировке ASCII) // Возвращает число > 0 если *p1 > *p2 // Возвращает 0 если *p1 == *p2 // Это означает, что символы будут сортироваться по возрастанию // (в кодировке ASCII) int cmp(const void * p1, const void * p2) { // На вход этой функции передаются указатели типа void* // Чтобы по ним получить символ, на который указывает этот указатель // Нужно сделать 2 вещи: // 1) Переконвертировать указатеть void* в указатель char* // чтобы компилятор понимал, что по данному адресу содержится символ // это делается так: (char *)p1 // 2) Разыменовать указатель // т.е. из указателя на символ получить сам символ // это делается с помощью оператора * // В итоге, чтобы получить символ по void* нужно написать *(char *) p1 char a = *(char *) p1; char b = *(char *) p2; // Также нужно конвертировать символы char в int return (int)a - (int)b; } int main() { char c; int i = 0; char s[1001]; // Считываем символы из стандартного входа по одному // пока не встретим символ . while ((c = getc(stdin)) != '.') { // Строчка ниже одновременно присваивает s[i] к c И увеличивает i на 1 s[i++] = c; // т.е. это то же самое, что и: // s[i] = c; // i++; } // Нужно установить последний символ строки нулевым s[i] = '\0'; // Сортируем строку по символам qsort(s, strlen(s), sizeof(char), cmp); // Печатаем строку + символ . printf("%s.\n", s); return 0; }
Java
UTF-8
2,276
2.15625
2
[]
no_license
package com.skillsmap.role.application.entity; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.ws.rs.FormParam; import javax.xml.bind.annotation.XmlRootElement; @Entity @Table(name="role") @XmlRootElement public class Role { @FormParam("role_id") public int role_id; @FormParam("role_title") public String role_title; @FormParam("role_grade") public String role_grade; @FormParam("version_id") public int version_id; @FormParam("role_summary") public String role_summary; @FormParam("role_group_id") public int role_group_id; RoleGroup roleGroup; @ManyToOne @JoinColumn(name="role_group_id", insertable=false, updatable=false) public RoleGroup getRoleGroup() { return roleGroup; } public void setRoleGroup(RoleGroup roleGroup) { this.roleGroup = roleGroup; } @Override public String toString() { return "Role [role_id=" + role_id + ", role_title=" + role_title + ", role_grade=" + role_grade + ", version_id=" + version_id + ", role_summary=" + role_summary + "]"; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getRole_id() { return role_id; } public void setRole_id(int role_id) { this.role_id = role_id; } public String getRole_title() { return role_title; } public void setRole_title(String role_title) { this.role_title = role_title; } public String getRole_grade() { return role_grade; } public void setRole_grade(String role_grade) { this.role_grade = role_grade; } public String getRole_summary() { return role_summary; } public void setRole_summary(String role_summary) { this.role_summary = role_summary; } public int getVersion_id() { return version_id; } public void setVersion_id(int version_id) { this.version_id = version_id; } public int getRole_group_id() { return role_group_id; } public void setRole_group_id(int role_group_id) { this.role_group_id = role_group_id; } }
JavaScript
UTF-8
1,161
4.75
5
[]
no_license
// Write an algorithm to determine if a number is "happy". // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. // Example: // Input: 19 // Output: true // Explanation: // 12 + 92 = 82 // 82 + 22 = 68 // 62 + 82 = 100 // 12 + 02 + 02 = 1 let isHappy = function(n, counter = 0) { result = false if (counter < 8) { // break the number into single digits array and square each number let arr = n.toString().split('').map(num => num*num) console.log("arr", arr) // get the sum - 0 is the initial value let sum = arr.reduce((a, b) => a + b, 0) console.log(sum) // if sum is 1 return true else go back and repeat the process if (sum === 1) { result = true console.log(result) return result } else { counter++ return isHappy(sum, counter) } } return result } isHappy(19)
JavaScript
UTF-8
1,988
2.703125
3
[]
no_license
const mock_zipobj = require("@littlezigy/zipobject"); const db = require("../../bin/database"); jest.mock("../../bin/database", () => ({ update: jest.fn(function(){ const data = mock_zipobj(arguments[1], arguments[2]) return { message: "Product updated!", data }; }), create: jest.fn( function() { const rows = mock_zipobj(arguments[1], arguments[2]) console.log("ARGUMENTS", arguments); console.log("\nDATA\n---------------",{ rows }); return { rows }; }) })); const productmodel = require("../../components/products/model.product"); const faker = require("faker"); describe("Create product", function() { let productname = faker.commerce.productName(); let store_id = parseInt(Math.random()*150); test("With name and store_id only", async function() { let create = await productmodel.create({name_: productname, 'store_id': store_id, user: {_id: 39}}); console.log("Create function ", create, "create.name", create.name_); expect(create).toHaveProperty('name_', productname); expect(create).toHaveProperty('store_id', store_id); }); test("With product name only. should throw error", async function() { const fn = async () => { await productmodel.create({name_: productname}); } expect(fn()).rejects.toThrowError(); }); }); describe("Update Product", function() { test("When product.isactive is set to true, returns true", async function() { let update = await productmodel.update({name: faker.commerce.productName(), isactive: true}); expect(update.data).toHaveProperty('isactive', true); }); test("When product.isactive is set to false, returns true", async function() { let update = await productmodel.update({name: faker.commerce.productName(), isactive: false}); expect(update.data).toHaveProperty('isactive', false); }); });
Python
UTF-8
1,145
3.53125
4
[]
no_license
import numpy.random as npr import numpy as np import matplotlib.pyplot as plt import random nran = 1000 xvals = npr.random(nran) uniform = xvals radius = uniform radvals = np.sqrt(radius) n1, bins1, patches1 = plt.hist(radvals,bins=50,normed=1,histtype='stepfilled') plt.setp(patches1,'facecolor','g','alpha',0.75) tries=100000 hits = 0 throws = 0 good_radius = [] for i in range (0, tries): throws += 1 x = random.uniform(-1,1) y = random.uniform(-1,1) distsquared = x**2 + y**2 if distsquared <= 1.0: hits = hits + 1.0 good_radius.append(np.sqrt(distsquared)) n1, bins1, patches1 = plt.hist(good_radius,bins=50,normed=1,histtype='stepfilled') plt.setp(patches1,'facecolor','r','alpha',0.75) """ How the histograms compare: The hits within the radius (good_radius) are roughly 70% of the original radii created and plotted with the first histogram. The more times you run the full code and overplot the histograms the more this 70% becomes apparent. Also of note is that the good_radius histogram is much more consistent (i.e. there is a more stable slope than the jumpy original radius histogram). """
C++
UTF-8
19,514
3.09375
3
[]
no_license
//PlayerTest.cpp // compile with g++ -std=c++11 -pedantic -Wall -Wextra -O PlayerTest.cpp Card.cpp Token.cpp // #include "Player.h" #include "Player.cpp" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <assert.h> #include <map> using std::cout; using std::endl; using std::map; void createDeck(); void setupTokens(); void fakeDealMarket(); void printMarket(); // temp deck for testing vector<Card> deck; vector<Card> market; // TOKEN vectors vector<Token> bonus3; //bonus tokens traded for 3 cards vector<Token> bonus4; vector<Token> bonus5; vector<Token> clothT; //cloth tokens vector<Token> leatherT; vector<Token> spiceT; vector<Token> silverT; vector<Token> goldT; vector<Token> diamondT; map<string, vector<Token>*> tokenBag; /*= {{"bonus3", bonus3},{"bonus4", bonus4},{"bonus5", bonus5},{"Cloth", clothT},{"Leather", leatherT},{"Spice", spiceT},{"Sliver", silverT}, {"Gold", goldT},{"Diamonds", diamondT}};*/ vector<int> marketIndicesForTrading; vector<int> playerIndicesForTrading; vector<int> handIndicesForSelling; int main() { createDeck(); setupTokens(); fakeDealMarket(); Player p1("Player1"); Player p2("Player2"); cout << endl; //cout << "Leather token vector size: " << (int)leatherT.size() << endl; cout << "Leather token vector size: " << (int)tokenBag.at("Leather")->size() << endl; // Test print tokens /*for (int i = 0; i < (int)leatherT.size(); i++) { cout << "Leather token [" << i << "]: " << leatherT.at(i).getPoint() << endl; }*/ for (int i = 0; i < (int)tokenBag.at("Leather")->size(); i++) { cout << "Leather token [" << i << "]: " << tokenBag.at("Leather")->at(i).getPoint() << endl; } // Print market printMarket(); // Print first's hand cout << "Herd size (before): " << p1.myHerd.size() << endl; for (int i = 0; i < (int) p1.myHerd.size(); i++) { cout << p1.myHerd.at(i).getType() << endl; } p1.takeCamels(&market, &deck); cout << "_______" << endl; cout << "Herd size (after): " << p1.myHerd.size() << endl; for (int i = 0; i < (int) p1.myHerd.size(); i++) { cout << p1.myHerd.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Take Gold cout << "Before taking 1 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 1); cout << "_______" << endl; cout << "After taking 1 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Take Silver cout << "Before taking 2 (Silver): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 2); cout << "_______" << endl; cout << "After taking 2 (Silver): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Take Another Silver cout << "Before taking 0 (Silver): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 0); cout << "_______" << endl; cout << "After taking 0 (Silver): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Populate trading vectors marketIndicesForTrading.push_back(0); marketIndicesForTrading.push_back(1); marketIndicesForTrading.push_back(2); playerIndicesForTrading.push_back(0); playerIndicesForTrading.push_back(1); playerIndicesForTrading.push_back(2); cout << "Before trading 0,1,2 in market for 0,1,2 in hand: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } assert(p1.trade(&market, &marketIndicesForTrading, &playerIndicesForTrading)); cout << "_______" << endl; cout << "After trading: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); /* marketIndicesForTrading.push_back(0); marketIndicesForTrading.push_back(1); marketIndicesForTrading.push_back(4); playerIndicesForTrading.push_back(0); playerIndicesForTrading.push_back(1); playerIndicesForTrading.push_back(2); cout << "Before trading 0,1,4 in market for 0,1,2 in hand: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } assert(p1.trade(&market, &marketIndicesForTrading, &playerIndicesForTrading)); cout << "_______" << endl; cout << "After trading: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); */ // TEST SELL ONE cout << "Testing p1.sellOne(): " << endl; cout << "Before selling 0 in hand: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } // Player points before/after cout << "Player point's before: " << p1.getPoints() << endl; p1.sellOne(&tokenBag, 0); cout << "_______" << endl; cout << "After selling: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } // Player points before/after cout << "Player point's after: " << p1.getPoints() << endl; cout<<endl; cout<<endl; // TEST SELL ONE cout << "Testing p1.sellOne(): " << endl; cout << "Before selling 0 in hand: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; // Player points before/after cout << "Player point's before: " << p1.getPoints() << endl; p1.sellOne(&tokenBag, 0); cout << "_______" << endl; cout << "After selling: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; // Player points before/after cout << "Player point's after: " << p1.getPoints() << endl; printMarket(); // Take Gold cout << "Before taking 0 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 0); cout << "_______" << endl; cout << "After taking 0 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Take Gold cout << "Before taking 3 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 3); cout << "_______" << endl; cout << "After taking 3 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Take Gold cout << "Before taking 0 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 0); cout << "_______" << endl; cout << "After taking 0 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; /* //add silver to hand. cout<<"Adding silver to hand for testing purposes"<<endl; Card c("Silver"); p1.myHand.push_back(c); // TEST SELL MULT //handIndicesForSelling.push_back(0); handIndicesForSelling.push_back(1); handIndicesForSelling.push_back(2); handIndicesForSelling.push_back(3); cout << "Testing p1.sellMult(): " << endl; cout << "Before selling 1,2,3 in hand: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.sellMult(&handIndicesForSelling, &tokenBag); cout << "_______" << endl; cout << "After selling: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<< "p1 points: "<<p1.getPoints() <<endl; cout<<endl; cout<<endl; printMarket(); // Take Another Gold cout << "Before taking 4 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 4); cout << "_______" << endl; cout << "After taking 4 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); // Take Another Gold cout << "Before taking 3 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 3); cout << "_______" << endl; cout << "After taking 3 (Gold): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); //add gold to hand. cout<<"Adding 2 gold to hand for testing purposes"<<endl; Card myc("Gold"); p1.myHand.push_back(myc); p1.myHand.push_back(myc); for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); */ // TEST SELL MULT handIndicesForSelling.clear(); //handIndicesForSelling.push_back(0); handIndicesForSelling.push_back(1); handIndicesForSelling.push_back(2); handIndicesForSelling.push_back(3); //handIndicesForSelling.push_back(4); cout << "Testing p1.sellMult(): " << endl; cout << "Before selling 1,2,3" << endl; cout<< "p1 points: "<<p1.getPoints()<<"\nHand: " <<endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.sellMult(&handIndicesForSelling, &tokenBag); cout << "_______" << endl; cout << "After selling: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<< "p1 points: "<<p1.getPoints() <<endl; cout<<endl; cout<<endl; //TEST SELLING LEATHER printMarket(); // Take Leather cout << "Before taking 3 (Leather): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 3); cout << "_______" << endl; cout << "After taking 3 (Leather): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; printMarket(); cout << "Before taking 2,3 (Leather): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.take(&market, &deck, 2); p1.take(&market, &deck, 3); cout << "_______" << endl; cout << "After taking 2,3 (Leather): " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<<endl; cout<<endl; handIndicesForSelling.clear(); //handIndicesForSelling.push_back(0); handIndicesForSelling.push_back(1); handIndicesForSelling.push_back(2); handIndicesForSelling.push_back(3); cout << "Testing p1.sellMult(): " << endl; cout << "Before selling 1,2,3" << endl; cout<< "p1 points: "<<p1.getPoints()<<"\nHand: " <<endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.sellMult(&handIndicesForSelling, &tokenBag); cout << "_______" << endl; cout << "After selling: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<< "p1 points: "<<p1.getPoints() <<endl; cout<<endl; cout<<endl; //attempt illegal sell of cloth using sell mult handIndicesForSelling.clear(); handIndicesForSelling.push_back(0); cout << "Testing Illegal p1.sellMult(): " << endl; cout << "Before selling 0" << endl; cout<< "p1 points: "<<p1.getPoints()<<"\nHand: " <<endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } p1.sellMult(&handIndicesForSelling, &tokenBag); cout << "_______" << endl; cout << "After selling: " << endl; for (int i = 0; i < (int) p1.myHand.size(); i++) { cout << p1.myHand.at(i).getType() << endl; } cout<< "p1 points: "<<p1.getPoints() <<endl; cout<<endl; cout<<endl; } void printMarket() { // Print market cout << "|" << market.at(0).getType() << "|"<< market.at(1).getType() << "|" << market.at(2).getType() << "|" << market.at(3).getType() << "|" << market.at(4).getType() << "|" <<endl; } void fakeDealMarket() { for (int i = 0; i < 5; i++) { market.push_back(deck.back()); deck.pop_back(); } } void createDeck(){ //include all 55 cards in deck container //create 9 leather cards for (int i=0;i<9;i++){ string leather = "Leather"; Card card(leather); deck.push_back(card); } //create 8 spice cards for (int i=0;i<8;i++){ string spice = "Spice"; Card card(spice); deck.push_back(card); } //create 6 cloth cards for (int i=0;i<6;i++){ string cloth = "Cloth"; Card card(cloth); deck.push_back(card); } //create 6 silver cards for (int i=0;i<6;i++){ string silver = "Silver"; Card card(silver); deck.push_back(card); } //create 6 gold cards for (int i=0;i<6;i++){ string gold = "Gold"; Card card(gold); deck.push_back(card); } //create 6 diamonds cards for (int i=0;i<6;i++){ string diamond = "Diamonds"; Card card(diamond); deck.push_back(card); } //create 11 camels cards for (int i=0;i<11;i++){ string camel = "Camels"; Card card(camel); deck.push_back(card); } // Shuffle deck std::random_shuffle ( deck.begin(), deck.end() ); // Add three camel to back of deck for marketplace setup for (int i=0;i<3;i++){ string camel = "Camels"; Card card(camel); deck.push_back(card); } } /* OLD */ void setupTokens(){ // Line below assures randomization of each shuffle per round/game std::srand ( unsigned ( std::time(0) ) ); //create and populate vectors //leather 1,1,1,1,1,1,2,3,4 string leather = "Leather"; for (int i=0;i<6;i++){ Token token(1,leather); leatherT.push_back(token); } Token ltoken2(2,leather); leatherT.push_back(ltoken2); Token ltoken3(3,leather); leatherT.push_back(ltoken3); Token ltoken4(4,leather); leatherT.push_back(ltoken4); // Add to tokenBag tokenBag["Leather"] = &leatherT; //cloth 1,1,2,2,3,3,5 string cloth = "Cloth"; Token ctoken(1,cloth); clothT.push_back(ctoken); clothT.push_back(ctoken); Token ctoken2(2,cloth); clothT.push_back(ctoken2); clothT.push_back(ctoken2); Token ctoken3(3,cloth); clothT.push_back(ctoken3); clothT.push_back(ctoken3); Token ctoken5(5,cloth); clothT.push_back(ctoken5); // Add to tokenBag tokenBag["Cloth"] = &clothT; //spice 1,1,2,2,3,3,5 string spice = "Spice"; Token stoken(1,spice); spiceT.push_back(stoken); spiceT.push_back(stoken); Token stoken2(2,spice); spiceT.push_back(stoken2); spiceT.push_back(stoken2); Token stoken3(3,spice); spiceT.push_back(stoken3); spiceT.push_back(stoken3); Token stoken5(5,spice); spiceT.push_back(stoken5); // Add to tokenBag tokenBag["Spice"] = &spiceT; //silver 5,5,5,5,5 for (int i=0;i<5;i++){ string s = "Silver"; Token token(5,s); silverT.push_back(token); } // Add to tokenBag tokenBag["Silver"] = &silverT; //gold 5,5,5,6,6, for (int i=0;i<3;i++){ string s = "Gold"; Token token(5,s); goldT.push_back(token); } for (int i=0;i<2;i++){ string s = "Gold"; Token token(6,s); goldT.push_back(token); } // Add to tokenBag tokenBag["Gold"] = &goldT; //diamond 5,5,5,7,7 string diamond = "Diamonds"; Token dtoken5(5,diamond); diamondT.push_back(dtoken5); diamondT.push_back(dtoken5); diamondT.push_back(dtoken5); Token dtoken7(7,diamond); diamondT.push_back(dtoken7); diamondT.push_back(dtoken7); // Add to tokenBag tokenBag["Diamonds"] = &diamondT; //bonus3 1,1,2,2,3,3 string b3 = "3cardBonus"; Token btoken3(3,b3); bonus3.push_back(btoken3); bonus3.push_back(btoken3); Token btoken2(2,b3); bonus3.push_back(btoken2); bonus3.push_back(btoken2); Token btoken1(1,b3); bonus3.push_back(btoken1); bonus3.push_back(btoken1); // Shuffle bonus3 tokens std::random_shuffle ( bonus3.begin(), bonus3.end() ); // Add to tokenBag tokenBag["bonus3"] = &bonus3; //bonus4 6,6,5,5,4,4 string b4 = "4cardBonus"; Token btoken4(4,b4); bonus4.push_back(btoken4); bonus4.push_back(btoken4); Token btoken5(5,b4); bonus4.push_back(btoken5); bonus4.push_back(btoken5); Token btoken6(6,b4); bonus4.push_back(btoken6); bonus4.push_back(btoken6); // Shuffle bonus4 tokens std::random_shuffle ( bonus4.begin(), bonus4.end() ); // Add to tokenBag tokenBag["bonus4"] = &bonus4; //bonus5 10,10,9,9,8,8 string b5 = "5cardBonus"; Token btoken8(8,b5); bonus5.push_back(btoken8); bonus5.push_back(btoken8); Token btoken9(9,b5); bonus5.push_back(btoken9); bonus5.push_back(btoken9); Token btoken10(10,b5); bonus5.push_back(btoken10); bonus5.push_back(btoken10); // Shuffle bonus5 tokens std::random_shuffle ( bonus5.begin(), bonus5.end() ); // Add to tokenBag tokenBag["bonus5"] = &bonus5; }
C#
UTF-8
1,778
3.328125
3
[]
no_license
using System.Text; namespace Ex03.GarageLogic { abstract class EnergySource { private protected readonly float r_MaxCapacity; private protected float m_CurrentCapacity; private protected float m_PrecentageFull; internal EnergySource(float i_MaxCapacity, float i_RemainingEnergy) { if (i_RemainingEnergy > i_MaxCapacity || i_RemainingEnergy < 0) { throw new ValueOutOfRangeException(i_MaxCapacity, 0); } this.r_MaxCapacity = i_MaxCapacity; this.m_CurrentCapacity = i_RemainingEnergy; this.m_PrecentageFull = m_CurrentCapacity / r_MaxCapacity * 100; } internal virtual void Charge(float i_EnergyAmuont) { if (i_EnergyAmuont + m_CurrentCapacity <= r_MaxCapacity && i_EnergyAmuont >= 0) { this.m_CurrentCapacity += i_EnergyAmuont; this.m_PrecentageFull = m_CurrentCapacity / r_MaxCapacity * 100; } else { throw new ValueOutOfRangeException(r_MaxCapacity - m_CurrentCapacity,0); } } internal virtual string ToString() { StringBuilder energyDetails = new StringBuilder(); energyDetails.Append(string.Format("Max capacity: {0}.", this.r_MaxCapacity) + System.Environment.NewLine); energyDetails.Append(string.Format("Current capacity: {0}.", this.m_CurrentCapacity) + System.Environment.NewLine); energyDetails.Append(string.Format("Percentage: {0}.", this.m_PrecentageFull) + System.Environment.NewLine); return energyDetails.ToString(); } } }
Shell
UTF-8
1,250
3.578125
4
[ "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
permissive
#!/usr/bin/bash IMAGE_PATH="$1" if [ ! -f "$IMAGE_PATH" ]; then echo "vm image '$IMAGE_PATH' not found" exit 1 fi # USING 'set -e' error detection for everything below this point. set -e PORT=${PORT:-3260} WWN=${WWN:-iqn.2018-01.io.kubevirt:wrapper} LUNID=1 echo "Starting tgtd at port $PORT" tgtd -f --iscsi portal="0.0.0.0:${PORT}" & sleep 5 echo "Adding target and exposing it" tgtadm --lld iscsi --mode target --op new --tid=1 --targetname $WWN tgtadm --lld iscsi --mode target --op bind --tid=1 -I ALL if [ -n "$PASSWORD" ]; then echo "Adding authentication for user $USERNAME" tgtadm --lld iscsi --op new --mode account --user $USERNAME --password $PASSWORD tgtadm --lld iscsi --op bind --mode account --tid=1 --user $USERNAME fi echo "Adding volume file as LUN" tgtadm --lld iscsi --mode logicalunit --op new --tid=1 --lun=$LUNID -b $IMAGE_PATH tgtadm --lld iscsi --mode logicalunit --op update --tid=1 --lun=$LUNID --params thin_provisioning=1 echo "Start monitoring" touch previous_state while true; do tgtadm --lld iscsi --mode target --op show >current_state diff -q previous_state current_state || ( date cat current_state ) mv -f current_state previous_state sleep 5 done
Python
UTF-8
792
2.546875
3
[ "Apache-2.0" ]
permissive
library = """ ->(left:, right:) = {arg: left, value: right}; # All ORDER BY arguments are wrapped, to avoid confusion with # column index. ArgMin(a) = SqlExpr("ARRAY_AGG({arg} order by [{value}][offset(0)] limit 1)[OFFSET(0)]", {arg: a.arg, value: a.value}); ArgMax(a) = SqlExpr( "ARRAY_AGG({arg} order by [{value}][offset(0)] desc limit 1)[OFFSET(0)]", {arg: a.arg, value: a.value}); ArgMaxK(a, l) = SqlExpr( "ARRAY_AGG({arg} order by [{value}][offset(0)] desc limit {lim})", {arg: a.arg, value: a.value, lim: l}); ArgMinK(a, l) = SqlExpr( "ARRAY_AGG({arg} order by [{value}][offset(0)] limit {lim})", {arg: a.arg, value: a.value, lim: l}); Array(a) = SqlExpr( "ARRAY_AGG({value} order by [{arg}][offset(0)])", {arg: a.arg, value: a.value}); """
C#
UTF-8
1,246
2.5625
3
[ "MIT" ]
permissive
using System; namespace JabbR.Infrastructure { public static class LoggingExtensions { public static void Error(this IRealtimeLogger logger, string message, params object[] args) { logger.Log(LogType.Error, String.Format(message, args)); } public static void Information(this IRealtimeLogger logger, string message, params object[] args) { logger.Log(LogType.Message, String.Format(message, args)); } public static void Debug(this IRealtimeLogger logger, string message, params object[] args) { logger.Log(LogType.Debug, String.Format(message, args)); } public static void Log(this IRealtimeLogger logger, Exception exception) { logger.Log(LogType.Error, "Exception:\r\n" + exception.ToString()); } public static void LogError(this IRealtimeLogger logger, string message, params object[] args) { logger.Log(LogType.Error, String.Format(message, args)); } public static void Log(this IRealtimeLogger logger, string message, params object[] args) { logger.Log(LogType.Message, String.Format(message, args)); } } }
Java
UTF-8
1,117
1.976563
2
[]
no_license
package com.example.e_fordoapp.Service; import com.example.e_fordoapp.Model.Order; import com.example.e_fordoapp.Model.Product; import com.example.e_fordoapp.Model.ProductCategory; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; public interface OrderService { //Invoice Save @POST("api/order/save") Call<Order> saveInvoice(@Body Order order); //Get order history @GET("api/order/orderHistory") Call<List<Order>> getOrderHistory(@Query("userId") String userId, @Query("password") String password, @Query("orderNumber") String orderNumber, @Query("orderDate") String orderDate); //Get order history @GET("api/order/orderDetails") Call<List<Product>> getorderDetails(@Query("userId") String userId, @Query("password") String password, @Query("orderID") String orderID); }
C#
UTF-8
846
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LibreriaDeClases.Interfaces; namespace LibreriaDeClases { public class Nodo<T> : IComparable<T> { public T dato { get; set; } public int factorEquilibrio { get; set; } public Nodo<T> izquierdo { get; set; } public Nodo<T> derecho { get; set; } public ComparadorNodosDelegate<T> comparador; public Nodo(T dato, ComparadorNodosDelegate<T> _comparador) { this.dato = dato; this.factorEquilibrio = 0; this.derecho = null; this.izquierdo = null; comparador = _comparador; } public int CompareTo(T other) { return comparador(this.dato, other); } } }
Markdown
UTF-8
11,452
3.21875
3
[]
no_license
--- title: Huangshan (The Yellow Mountain) image: https://assets.goddamnyouryan.com/blog/asia/huangshan-mountains.jpg date: 2014-01-18 --- Huangshan is about a 5 hour bus ride west of Shanghai. But I took the overnight train, which was a 12 hour journey. The train was going really fast so it must have not been a very direct route. All the "soft sleepers" were booked so I got a "hard sleeper", which is essentially a very thin mat on the 2nd level of a triple story bunk bed. Surprisingly it was comfortable enough that I got a really solid rest. I then learned that it's pretty standard practice on Chinese overnight trains for them to wake you up at 6am. I was awoken by a train guy banging on my bed and yelling at me in Mandarin. A young guy passing by translated "move cars", which I still don't fully understand why we did but I moved nonetheless. It was a total shitshow once you arrive at the Huangshan train station at 9am. Tons of people yelling at you and trying to sell you things, maps and hiking poles and bottles of water and such. You're herded through the throngs to a bunch of busses. I had no idea what I was doing so I just went along with it. I was sitting in a bus seat when a lady got in a huge screaming match with another lady halfway on the bus. I had no idea what was going on. After what seemed like an hour wait the bus was finally on the way. For those that don't know (I certainly didn't before I got there, Huangshan translates to "yellow mountain". It's famous for being (supposedly) the most beautiful mountain in all of China. It was described to me as "one of the most breath-taking sites and the King of all the mountains in China" so naturally I had to go check it out. The first bus takes you from the train station to a bus station. It's about an hour. Then you catch another hour long bus ride to the base of the mountain. When you get there you can either hike to the top or take a cable car. I opted to hike because a) I'm cheap and b) I hadn't done any real exercise since I left. If I had known what I was in for I probably would have changed my tune. ![](https://assets.goddamnyouryan.com/blog/asia/huangshan-eastern-stairs.jpg) Hiking up Huangshan involves stairs. Endless, endless amounts of stairs. It's basically 6km of stairs straight up the side of the mountain. It took me 3 or 4 hours to do, and between the altitude and my pack I was utterly exhausted by the time I got to the top. All I had had that day was some water and crackers that I bought from a store at the base of the mountain. Everyone complains about how expensive water is on the mountain, and it is, relative to everywhere else (10RMB or about $1.70) though still insanely cheap by US standards obviously. There's 4 or 5 hotels on top of the mountain and when I got there I checked into a dormitory style room in the first one I saw. The room was totally empty and I was psyched. I took a nice long shower and relaxed for a bit and spent the rest of the day wandering around the mountaintop, taking in the beautiful sites. The only place that serves food that isn't of the convenience store variety is this super corny, but I guess fancy? restaurant in my hotel, I order a single pork and noodles dish which sets me back about $20, which is absolute highway robbery in China, the same dish would cost $3 in shanghai, but I haven't eaten all day and I hiked up a goddamned mountain so it was worth it. When I get back to my room there's like 10 Chinese 18 year olds yelling, drinking and playing cards. None of them speak English of course, and I just want to go to sleep, though I can't for several hours. I woke up at 5:30am when the rest of my room did, everyone gets up this early on the mountain to watch the sunrise, which is supposed to be spectacular. On this particular morning it was fairly overcast so I was pretty underwhelmed. ![](https://assets.goddamnyouryan.com/blog/asia/huangshan-sunrise.jpg) I had heard of a bridge on the mountain called the Fairy Bridge and I was determined to see it, then my plan was to hike down the mountain via the western route (I came up the eastern one). I expected it to be fairly straightforwards. I did those things but literally almost managed to kill myself in the process: ![](https://assets.goddamnyouryan.com/blog/asia/huangshan-fairy-stairs.jpg) First it was just confusing as fuck how to get to the fairy bridge. There's no signs and all the maps aren't to scale and most trails aren't on the maps at all (not to mention half of them are only in chinese). So by asking every park ranger I see I am finally able I make it to the bridge after about 2 hours (I set off at 8am). It's epic as fuck: ![](https://assets.goddamnyouryan.com/blog/asia/huangshan-fairy-bridge.jpg) And also hilariously there is a monkey eating of the trash right next to it: ![](https://assets.goddamnyouryan.com/blog/asia/huangshan-monkey.jpg) I had no idea they even had monkeys here so I was completely caught off guard. But I was laughing at the little guy (though he probably weighed 50 lbs). According to all the maps you can keep going past the bridge and you'll do this big downward loop that's 15k long that'll eventually plop you out at the bottom of the mountain where all the busses are. Since it's entirely downhill I figured 15k was doable in a few hours. The thing is, no one else is going down that way. Fuckit, I say. Very quickly I realize why. On the way up the steps were super nice and well maintained. These steps are carved directly into the mountainside and look like they've never been maintained. They're narrow, insanely steep, and slippery. Never have I ever so carefully descended a staircase before. ![](https://assets.goddamnyouryan.com/blog/asia/huangshan-west-stairs.jpg) Once I've been going down very carefully for about 20 minutes I see a monkey on the stairs in front of me. He looks nothing like the one I saw eating trash, he's lean and looks mean. His chest is all puffed out and he's slowly walking towards me and making a growling noise. I hear a noise on either side of the path and I notice there are monkeys there too. I look behind me and yep, another one. Fuck, I'm surrounded. I'm on these narrow as stairs and I'll admit it, I'm scared of this monkey attack that is looming. I've never seen a monkey in the wild in my life and haven't the faintest clue what to do. Not to mention I can very easily fall down these stairs or off the side (no guard rail of course) to my thousand foot doom. I decide the best course of action is to run down the stairs towards the leader of the monkey pack at full speed. It works, he scurries away. For the next half mile or so I can hear them following me down the cliff side. Not long after I start to see a little bit of snow on the stairs. Then a lot of snow. Pretty soon they are covered in snow and ice. I was already going down the stairs very carefully, I'm reduced to a crawl. I almost fall so many times it's not even funny. Turns out boat shoes are no good for descending a snowy mountain. After about 5 miles I make it to this ranger outpost. The ranger pulls out this little translation card asking me to sign my name and phone number. Presumably this is so they can fish my corpse out from a the bottom of a cliff later. The next few miles follow this river down and it's actually super pleasant. In my head I'm composing the story of this blog post, and it's warm out, I'm almost down and in psyched. I'm starting to get hungry. I get to what looks like the bottom and instead it's a weird looking construction site. This isn't a trailhead. I flag down a construction worker and show him my map and point at the base of the mountain. He points back up the way I came and jerks his hand to the right, like I missed a turn. There's a road from the construction site and I consider trying to convince him to give me a ride but I figure I'll go look for this trail first. I walk back up 10 minutes and see another trail on the other side of this abandoned building that was hidden from the way down. I start walking up it. And quickly realize it's all uphill. Fuck, I thought I was done with that shit. I only brought one bottle of water with me because I thought I was only going downhill, it's half gone. I ate what I believe was a chinese energy bar at 7:30am and I have no more food on me. Also I should note that every trail I've followed thus far had a sign of some kind letting you know how long it was and what's on the other end. This trail has no such thing. I walk up it for a while and after not long I'm exhausted, but I keep going because I'm nothing if not stubborn. Eventually this trail gets covered with snow too, only this time I'm going up. I can't emphasize enough how tiring it is walking up snow covered endless ancient stairs. I keep going and going, every 5 minutes I debate turning around but my prospects back that way don't look to promising either. I'm drenched in sweat, starving, freezing, have potential frostbite on my toes and I only have about two swigs left of water. After about 3 hours of this my toes feel like they are on the verge of getting frost bitten and I'm starting to seriously try to remember any survivalist skills I may have once had. I tell myself 15 more minutes, if I don't see anything promising in 15 minutes I'll turn back and beg the construction workers for some water and worry about what to do next then. Both of my quads are starting to seize up and the snow covered stairs still ascend endlessly in front of me. After 15 minutes I look up and it looks like the Great Wall of China is above me. I figure I'm hallucinating from tiredness but I decide to walk up to it anyways. It turns out it's real! It's a big wall covering the crest of the mountain! I've made it to the top. Of course there is nothing to signify this apart from the wall. I don't take any pictures because I'm still worried about dying. The path on the other side goes into an identical looking valley. I have a choice, if I continue down it means if I turn around it's going to be uphill and I'm not sure I can handle anymore uphill. Fuckit, I say again. If I'm on the verge of death I can drink some water from this creek that the onwards path seems to follow. The path continuing down is much nicer, minimal snow, and it's slightly warmer. I follow it for about an hour and wayyyyy down below me, 2 or 3 miles I can see 2 or 3 tiny buildings. This encourages me. I keep on following it down and another half an hour I've made it to the buildings. But they look like empty offices. And the trail ends in a closed gate. At this point I'm beyond caring. I climb up the 10 foot gate, haul my pack over, and jump down. I'm on some kind of road! And there's a sign for a temple 1km away. I start walking towards it and I make it to some stairs that are going upwards, it says it's 0.1km up the stairs to the temple. Never in my life has it taken me so long to walk 0.1km. I had to stop like 5 times on the stairs I was so tired. There were a bunch of busses at the temple! I try to get on with my return ticket but they claim it was one way (totally bullshit) I don't care at all though, pay the 20rmb and climb aboard. Then I compose the majority of this blog post. I'm now at the bus station waiting for my bus to Hangzhou to leave. I drank a whole coke, a whole water, a dove bar and a weird tasting chinese meat stick, and I'm alive.
C#
UTF-8
1,970
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Maps; namespace LiveMapApp2 { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); MyMap = new Map(MapSpan.FromCenterAndRadius(new Position(37, -122), Distance.FromMiles(0.3))) { IsShowingUser = true, HeightRequest = 100, WidthRequest = 960, VerticalOptions = LayoutOptions.FillAndExpand, MapType = MapType.Street, }; MyMap.MoveToRegion( MapSpan.FromCenterAndRadius( new Position(18.988009, -287.189060), Distance.FromMiles(1))); var testpin1 = new Position(18.989216, -287.189113); var testpin2 = new Position(18.989104, -287.187708); var pin = new Pin { Type = PinType.Place, Position = testpin1, Label = "custom pin", Address = "custom detail info" }; var pin2 = new Pin { Type = PinType.Place, Position = testpin2, Label = "custom pin", Address = "custom detail info" }; MyMap.Pins.Add(pin); MyMap.Pins.Add(pin2); } protected override void OnAppearing() { base.OnAppearing(); //var slider = new Slider(1, 18, 1); //slider.ValueChanged += (sender, e) => //{ // var zoomLevel = e.NewValue; // var latlongdegrees = 360 / (Math.Pow(2, zoomLevel)); // MyMap.MoveToRegion(new MapSpan(MyMap.VisibleRegion.Center, latlongdegrees, latlongdegrees)); //}; } } }
Markdown
UTF-8
4,713
2.59375
3
[]
no_license
### 美国经济非常健康 近期股市为何下挫? ------------------------ <p> 【大纪元2018年11月23日讯】(大纪元记者林燕编译报导) <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E5%9B%BD%E7%BB%8F%E6%B5%8E.html"> 美国经济 </a> 非常健康,为何 <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E5%9B%BD%E8%82%A1%E5%B8%82.html"> 美国股市 </a> 近期却大幅下挫,最简单的答案是市场并非经济本身。《华尔街日报》周四(11月22日)发表首席经济评论家叶伟平(Greg Ip)的文章,解释了这种反常现象,其实根植于全球两个不寻常的特征。 </p> <p> 第一, <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E5%9B%BD%E7%BB%8F%E6%B5%8E.html"> 美国经济 </a> 借助一波财政刺激蓬勃发展,但全球其它地区的经济增长正在放缓,这损害在海外做生意的 <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E5%9B%BD%E4%BC%81%E4%B8%9A.html"> 美国企业 </a> 的前景。第二,美国联邦储备委员会( <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E8%81%94%E5%82%A8.html"> 美联储 </a> )正在渐进退出过去衰退时的货币刺激政策,这些政策在过去十年间提振了经济以及各资产部门。这些都是即便经济良好,股市仍会大跌的背后原因。 </p> <p> 美国经济正在全速前进,各项经济指标均非常健康。今年前三季度美国经济GDP增长3%,为2014年以来最大增幅。失业率也跌至1969年以来最低水平,同时消费者信心和首次申领失业保险等指标也很正常。 </p> <p> 文章认为,美国经济强势的主要原因是:减税和联邦支出增加刺激了企业、消费者和政府支出。但美国以外的情况却大不相同,第三季度德国和日本经济均出现收缩,而中国经济增速则降至十年来最低水平。 </p> <p> 而全球需求疲软令石油等大宗商品承压,美元升值和美中贸易摩擦,这些都给海外经营的 <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E5%9B%BD%E4%BC%81%E4%B8%9A.html"> 美国企业 </a> 前景蒙上阴影。根据FactSet的数据,分析师预计国际业务多的公司第四季度的利润增长为9.4%,而以美国市场为主的公司利润增长是16.5%。 </p> <p> 另一方面,以 <a href="http://www.epochtimes.com/gb/tag/%E7%BE%8E%E8%81%94%E5%82%A8.html"> 美联储 </a> 为首的各国央行正在退出过去十年实施的货币宽松政策,这意味着过去的零利率(或接近为零的低利率)政策“前瞻性指引”将逐渐消失。 </p> <p> 投资者、个人和企业将现金从银行存款和政府债券中转移到风险更高的投资上的成本将增加,可能会抑制房地产价格和股价上涨,同时减少流向高负债公司的贷款。 </p> <p> 市场并非经济本身。文章指,除非最近的市场动荡影响到经济数据,否则美联储官员不大可能改变加息路径。 </p> <p> 国际货币基金组织(IMF)金融顾问亚德里安(Tobias Adrian)也认为,综合来看,美国现在的金融状况自2015年以来实际上有所放松。相比之下,在美联储此前的三轮加息周期中,金融形势均收紧。 </p> <p> 也有人认为,美联储应暂停加息脚步,看看资本市场传递出的问题,这些问题是否比经济数据所显示的更加严重。 </p> <p> 美联储一直以来的政策目标就是控制通货膨胀以及稳定充分就业。外界认为,如果通胀上升较快,美联储一定会随之升息;但如果经济显露出的问题比美联储预期的更严重,降息空间就十分有限。 </p> <p> 美联储官员已经表示,他们仍在为美国经济提供支持。现在联邦基金利率略高于2%,若按通胀因素调整后仍接近零。 </p> <p> 面对这两大新特征,市场是否能逐渐适应,美国经济是否能在明年夏天打破历史最长的经济扩张纪录,都是接下来关注的焦点。# </p> <p> 责任编辑:林妍 </p> 原文链接:http://www.epochtimes.com/gb/18/11/22/n10869220.htm ------------------------ #### [禁闻聚合首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;|&nbsp; [Web代理](https://github.com/gfw-breaker/open-proxy/blob/master/README.md) &nbsp;|&nbsp; [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) &nbsp;|&nbsp; [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) &nbsp;|&nbsp; [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md#绪论)
Java
UTF-8
1,983
2.25
2
[]
no_license
package com.epam.esm.dto.converter; import com.epam.esm.dto.impl.ShopUserDto; import com.epam.esm.model.ShopUser; import com.epam.esm.model.role.Role; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.modelmapper.ModelMapper; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) public class ShopUserModelConverterTest { private static final long ID = 1L; private static final String USER_NAME = "admin"; private static final String USER_PASS = "admin"; private static final String USER_ROLE = "admin"; private ShopUser shopUser; private ShopUserDto shopUserDto; @InjectMocks private ShopUserModelConverter shopUserModelConverter; @Mock private ModelMapper modelMapper; @Before public void init() { shopUser = new ShopUser(); shopUser.setId(ID); shopUser.setName(USER_NAME); shopUser.setLogin(USER_NAME); shopUser.setPassword(USER_PASS); shopUser.setRole(Role.ADMINISTRATOR); shopUserDto = new ShopUserDto(); shopUserDto.setId(ID); shopUserDto.setName(USER_NAME); shopUserDto.setLogin(USER_NAME); shopUserDto.setPassword(USER_PASS); shopUserDto.setRole("ADMINISTRATOR"); Mockito.when(modelMapper.map(shopUser, ShopUserDto.class)).thenReturn(shopUserDto); Mockito.when(modelMapper.map(shopUserDto, ShopUser.class)).thenReturn(shopUser); } @Test public void testToDtoShouldReturnShopUserDto() { ShopUserDto actual = shopUserModelConverter.toDto(shopUser); Assert.assertEquals(shopUserDto, actual); } @Test public void testToModelShouldReturnShopUser() { ShopUser actual = shopUserModelConverter.toModel(shopUserDto); Assert.assertEquals(shopUser, actual); } }
Python
UTF-8
2,491
2.859375
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @file @brief pubg APIからtelemetryファイルを取得するスクリプト (アカウントIDで検索かけるメッソドもおまけ) @date 2018-09-04 ''' import requests import json API_KEY = "<自身のAPIキー>" SERVER = "<好きなShardidに変更>" ''' Player名と{アカウントID + 参加したマッチIDのリスト}を対応させたdictを返す @params {string list} 検索したいPlayer名のリスト @return {object} Player名とアカウントIDの対応 ''' def request_accountInfo(playername_list): # リクエスト準備 headers = { "Authorization" : "Bearer "+ API_KEY, "Accept": "application/json" } end_point = "https://api.pubg.com/shards/{}/players".format(SERVER) query = { "filter[playerNames]": ','.join(playername_list) } # リクエスト実行 res = requests.get(end_point, headers=headers,params=query) res_json = json.loads(res.text) # parse処理 return_obj = {} for account_data in res_json['data']: if account_data['attributes']['name'] in playername_list: add_obj = {} add_obj['accountid'] = account_data['id'] tmp_list = [] for match in account_data['relationships']['matches']['data']: tmp_list.append(match['id']) add_obj['matchIDs'] = tmp_list return_obj[account_data['attributes']['name']] = add_obj return return_obj ''' 検索したいマッチIDを受け取って対応するtelemetry.jsonのURLを返す @params {string} 検索したいマッチのID @return {object} telemetry.jsonが取れるURL ''' def request_matchTelemetry(matchID): # リクエスト準備 headers = { "Authorization" : "Bearer "+ API_KEY, "Accept": "application/json" } end_point = "https://api.pubg.com/shards/{}/matches/{}".format(SERVER,matchID) # リクエスト実行 res = requests.get(end_point, headers=headers) res_json = json.loads(res.text) # parse処理 telemetry_URL = [x['attributes']["URL"] for x in res_json['included'] if x['type'] == 'asset'] return telemetry_URL # テスト用のメイン処理 if __name__ == '__main__' : accountInfo = request_accountInfo(["yobiyobi","nicky_pon"]) print(accountInfo) telemetryURL = request_matchTelemetry(accountInfo["yobiyobi"]["matchIDs"][0]) print (telemetryURL)
Java
UTF-8
1,369
1.992188
2
[]
no_license
package com.yunxi.stamper.service; import com.yunxi.stamper.entity.ApplicationKeeper; import com.yunxi.stamper.entity.ApplicationNode; import com.yunxi.stamper.entity.Signet; import com.yunxi.stamper.entity.User; import javax.validation.constraints.NotNull; import java.util.List; /** * @author zhf_10@163.com * @Description 授权处理业务层 * @date 2019/5/5 0005 13:48 */ public interface ApplicationKeeperService { void add(ApplicationKeeper ak); void update(ApplicationKeeper applicationKeeper); //查询指定申请单id List<ApplicationKeeper> getByApplication(Integer applicationId); //查询指定申请单id+授权人Id List<ApplicationKeeper> getByApplicationAndKeeper(Integer applicationId, Integer keeperId); //查询印章的授权记录(正在授权中) List<ApplicationKeeper> getBySignet(Integer signetId, Integer signetOrgId); void del(ApplicationKeeper ak); //根据授权节点,创建授权记录 void createByNode(ApplicationNode node); List<ApplicationKeeper> getByApplicationAndNode(Integer applicationId, Integer nodeId); /** * 设备管理员发生变更授权记录 * @param signet 设备 * @param keeper 新设备管理员 */ void updateFromSignetDate(@NotNull Signet signet,@NotNull Integer oldKeeperId,@NotNull User keeper); ApplicationKeeper getByApplicationOK(Integer applicationId,Integer deviceId); }
Java
UTF-8
1,636
2.484375
2
[ "Apache-2.0", "MIT" ]
permissive
package com.springessentialsbook.chapter5.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; @Component public class MyCustomizedAuthenticationProvider implements AuthenticationProvider { @Autowired UserDetailsService userService; public Authentication authenticate(Authentication authentication) throws AuthenticationException { User user=null; Authentication auth=null; String username=authentication.getName(); String password=authentication.getCredentials().toString(); user= (User) userService.loadUserByUsername(username); if(password ==null || ! password.equals(user.getPassword())) throw new UsernameNotFoundException("wrong user/password"); if(user !=null){ auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); } else throw new UsernameNotFoundException("wrong user/password"); return auth; } public boolean supports(Class<?> aClass) { return true; } }
SQL
UTF-8
11,313
3.203125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Aug 02, 2016 at 08:05 PM -- Server version: 10.1.10-MariaDB -- PHP Version: 5.6.19 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `poms` -- -- -------------------------------------------------------- -- -- Table structure for table `fakulteti` -- CREATE TABLE `fakulteti` ( `id` int(11) NOT NULL, `fakulteti` varchar(60) COLLATE utf8_bin NOT NULL, `departamenti` varchar(60) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `fakulteti` -- INSERT INTO `fakulteti` (`id`, `fakulteti`, `departamenti`) VALUES (1, 'FSHK', 'SD'), (2, 'FSHK', 'TIT'); -- -------------------------------------------------------- -- -- Table structure for table `lenda` -- CREATE TABLE `lenda` ( `id` int(11) NOT NULL, `emri` varchar(50) COLLATE utf8_bin NOT NULL, `ects` smallint(6) NOT NULL, `fakulteti` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `ligjeratat` -- CREATE TABLE `ligjeratat` ( `id` int(11) NOT NULL, `lenda` int(11) NOT NULL, `profesori` int(11) NOT NULL, `fakulteti` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `profesori` -- CREATE TABLE `profesori` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `emri` varchar(30) COLLATE utf8_bin NOT NULL, `mbiemri` varchar(30) COLLATE utf8_bin NOT NULL, `titulli` varchar(15) COLLATE utf8_bin DEFAULT NULL, `fakulteti` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `profesori` -- INSERT INTO `profesori` (`id`, `user_id`, `emri`, `mbiemri`, `titulli`, `fakulteti`) VALUES (1, 1, 'Filan', 'Fisteku', 'Dr.', 1); -- -------------------------------------------------------- -- -- Table structure for table `profi_fk` -- CREATE TABLE `profi_fk` ( `profi_id` int(11) NOT NULL, `fk_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `publikimet` -- CREATE TABLE `publikimet` ( `id` int(11) NOT NULL, `lenda` int(11) NOT NULL, `profesori` int(11) NOT NULL, `fakulteti` int(11) NOT NULL, `permbajtja` varchar(500) COLLATE utf8_bin NOT NULL, `data_e_postimit` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `referenti` -- CREATE TABLE `referenti` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `emri` varchar(30) COLLATE utf8_bin NOT NULL, `mbiemri` varchar(30) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `referenti` -- INSERT INTO `referenti` (`id`, `user_id`, `emri`, `mbiemri`) VALUES (1, 2, 'Filan', 'Fisteku'); -- -------------------------------------------------------- -- -- Table structure for table `rezultatet` -- CREATE TABLE `rezultatet` ( `id` int(11) NOT NULL, `pershkrimi` varchar(100) COLLATE utf8_bin NOT NULL, `lenda` int(11) NOT NULL, `profesori` int(11) NOT NULL, `fakulteti` int(11) NOT NULL, `data` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `studenti` -- CREATE TABLE `studenti` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `nr_id` int(11) NOT NULL, `emri` varchar(30) COLLATE utf8_bin NOT NULL, `mbiemri` varchar(30) COLLATE utf8_bin NOT NULL, `datelindja` date NOT NULL, `fakulteti` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `studenti` -- INSERT INTO `studenti` (`id`, `user_id`, `nr_id`, `emri`, `mbiemri`, `datelindja`, `fakulteti`) VALUES (1, 3, 12345678, 'Valon', 'Kito', '1995-10-23', 1); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `type` int(11) NOT NULL, `email` varchar(100) COLLATE utf8_bin NOT NULL, `password` char(150) COLLATE utf8_bin NOT NULL, `salt` char(150) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `type`, `email`, `password`, `salt`) VALUES (1, 2, 'p@g.com', '00807432eae173f652f2064bdca1b61b290b52d40e429a7d295d76a71084aa96c0233b82f1feac45529e0726559645acaed6f3ae58a286b9f075916ebf66cacc', 'f9aab579fc1b41ed0c44fe4ecdbfcdb4cb99b9023abb241a6db833288f4eea3c02f76e0d35204a8695077dcf81932aa59006423976224be0390395bae152d4ef'), (2, 1, 'r@g.com', '00807432eae173f652f2064bdca1b61b290b52d40e429a7d295d76a71084aa96c0233b82f1feac45529e0726559645acaed6f3ae58a286b9f075916ebf66cacc', 'f9aab579fc1b41ed0c44fe4ecdbfcdb4cb99b9023abb241a6db833288f4eea3c02f76e0d35204a8695077dcf81932aa59006423976224be0390395bae152d4ef'), (3, 3, 's@g.com', '00807432eae173f652f2064bdca1b61b290b52d40e429a7d295d76a71084aa96c0233b82f1feac45529e0726559645acaed6f3ae58a286b9f075916ebf66cacc', 'f9aab579fc1b41ed0c44fe4ecdbfcdb4cb99b9023abb241a6db833288f4eea3c02f76e0d35204a8695077dcf81932aa59006423976224be0390395bae152d4ef'); -- -------------------------------------------------------- -- -- Table structure for table `user_types` -- CREATE TABLE `user_types` ( `id` int(11) NOT NULL, `name` char(20) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `user_types` -- INSERT INTO `user_types` (`id`, `name`) VALUES (1, 'Referent'), (2, 'Profesor'), (3, 'Student'); -- -- Indexes for dumped tables -- -- -- Indexes for table `fakulteti` -- ALTER TABLE `fakulteti` ADD PRIMARY KEY (`id`); -- -- Indexes for table `lenda` -- ALTER TABLE `lenda` ADD PRIMARY KEY (`id`), ADD KEY `fakultetild` (`fakulteti`); -- -- Indexes for table `ligjeratat` -- ALTER TABLE `ligjeratat` ADD PRIMARY KEY (`id`), ADD KEY `ligjeratat_lenda` (`lenda`), ADD KEY `ligjeratat_fakulteti` (`fakulteti`), ADD KEY `ligjeratat_profesori` (`profesori`); -- -- Indexes for table `profesori` -- ALTER TABLE `profesori` ADD PRIMARY KEY (`id`), ADD KEY `profesori_user_id` (`user_id`), ADD KEY `profesori_fakulteti` (`fakulteti`); -- -- Indexes for table `profi_fk` -- ALTER TABLE `profi_fk` ADD UNIQUE KEY `profi_id` (`profi_id`), ADD KEY `fk_id` (`fk_id`); -- -- Indexes for table `publikimet` -- ALTER TABLE `publikimet` ADD PRIMARY KEY (`id`), ADD KEY `publikimet_fakulteti` (`fakulteti`), ADD KEY `publikimet_profesori` (`profesori`), ADD KEY `publikimet_lenda` (`lenda`); -- -- Indexes for table `referenti` -- ALTER TABLE `referenti` ADD PRIMARY KEY (`id`), ADD KEY `referenti_user_id` (`user_id`); -- -- Indexes for table `rezultatet` -- ALTER TABLE `rezultatet` ADD PRIMARY KEY (`id`), ADD KEY `rezultatet_lenda` (`lenda`), ADD KEY `rezultatet_fakulteti` (`fakulteti`), ADD KEY `rezultatet_profesori` (`profesori`); -- -- Indexes for table `studenti` -- ALTER TABLE `studenti` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `nr_id` (`nr_id`), ADD KEY `studenti_user_id` (`user_id`), ADD KEY `studenti_fakulteti` (`fakulteti`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `email` (`email`), ADD KEY `users_type` (`type`); -- -- Indexes for table `user_types` -- ALTER TABLE `user_types` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `fakulteti` -- ALTER TABLE `fakulteti` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `lenda` -- ALTER TABLE `lenda` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `ligjeratat` -- ALTER TABLE `ligjeratat` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `profesori` -- ALTER TABLE `profesori` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `publikimet` -- ALTER TABLE `publikimet` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `referenti` -- ALTER TABLE `referenti` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `rezultatet` -- ALTER TABLE `rezultatet` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `studenti` -- ALTER TABLE `studenti` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `user_types` -- ALTER TABLE `user_types` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Constraints for dumped tables -- -- -- Constraints for table `lenda` -- ALTER TABLE `lenda` ADD CONSTRAINT `fakultetild` FOREIGN KEY (`fakulteti`) REFERENCES `fakulteti` (`id`); -- -- Constraints for table `ligjeratat` -- ALTER TABLE `ligjeratat` ADD CONSTRAINT `ligjeratat_fakulteti` FOREIGN KEY (`fakulteti`) REFERENCES `fakulteti` (`id`), ADD CONSTRAINT `ligjeratat_lenda` FOREIGN KEY (`lenda`) REFERENCES `lenda` (`id`), ADD CONSTRAINT `ligjeratat_profesori` FOREIGN KEY (`profesori`) REFERENCES `profesori` (`id`); -- -- Constraints for table `profesori` -- ALTER TABLE `profesori` ADD CONSTRAINT `profesori_fakulteti` FOREIGN KEY (`fakulteti`) REFERENCES `fakulteti` (`id`), ADD CONSTRAINT `profesori_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `profi_fk` -- ALTER TABLE `profi_fk` ADD CONSTRAINT `profi_fk_ibfk_1` FOREIGN KEY (`profi_id`) REFERENCES `profesori` (`id`), ADD CONSTRAINT `profi_fk_ibfk_2` FOREIGN KEY (`fk_id`) REFERENCES `fakulteti` (`id`); -- -- Constraints for table `publikimet` -- ALTER TABLE `publikimet` ADD CONSTRAINT `publikimet_fakulteti` FOREIGN KEY (`fakulteti`) REFERENCES `fakulteti` (`id`), ADD CONSTRAINT `publikimet_lenda` FOREIGN KEY (`lenda`) REFERENCES `lenda` (`id`), ADD CONSTRAINT `publikimet_profesori` FOREIGN KEY (`profesori`) REFERENCES `profesori` (`id`); -- -- Constraints for table `referenti` -- ALTER TABLE `referenti` ADD CONSTRAINT `referenti_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `rezultatet` -- ALTER TABLE `rezultatet` ADD CONSTRAINT `rezultatet_fakulteti` FOREIGN KEY (`fakulteti`) REFERENCES `fakulteti` (`id`), ADD CONSTRAINT `rezultatet_lenda` FOREIGN KEY (`lenda`) REFERENCES `lenda` (`id`), ADD CONSTRAINT `rezultatet_profesori` FOREIGN KEY (`profesori`) REFERENCES `profesori` (`id`); -- -- Constraints for table `studenti` -- ALTER TABLE `studenti` ADD CONSTRAINT `studenti_fakulteti` FOREIGN KEY (`fakulteti`) REFERENCES `fakulteti` (`id`), ADD CONSTRAINT `studenti_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Constraints for table `users` -- ALTER TABLE `users` ADD CONSTRAINT `users_type` FOREIGN KEY (`type`) REFERENCES `user_types` (`id`); /*!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
2,489
2.671875
3
[ "MIT" ]
permissive
import cv2 import matplotlib.pyplot as plt import numpy as np from PIL import Image import os import shutil import sys import _global def cut_width(page, page_num, is_png=False): ''' Cut uncessery scanned page from left and right Note: there is a difference between pages ''' width, height = page.size bottom = height right = width top = 0 left = 0 if page_num == 1: if is_png: left = 37 else: # is tiff left = 100 elif page_num == 2: if is_png: right = width - 80 bottom = bottom - 300 else: # is tiff right = width - 100 bottom = bottom - 622 cropped = page.crop((left, top, right, bottom)) # cropped.show() return cropped def image_to_png(png): width, height = png.size page1, page2 = png.crop((0, 0, width, height/2)), png.crop((0,height/2, width, height)) page1, page2 = cut_width(page1, 1, True), cut_width(page2, 2, True) concat = get_concat_vertical(page1, page2) concat.save(_global.CONCAT_AS_ONE_IMAGE) #concat.show() def tiff_to_jpeg(tiff): page_count = 0 if not os.path.exists('temp'): os.mkdir('temp') while 1: try: save_name = 'page' + str(page_count) + ".jpeg" try: tiff.save('temp/'+save_name) except OSError: ''' Deal with OSError by saving tiff as jpeg ''' tiff = tiff.convert("RGB") tiff.save('temp/'+save_name) page_count = page_count+1 tiff.seek(page_count) except EOFError: page1 = Image.open('temp/page0.jpeg') page1 = cut_width(page1, 1) if page_count > 1: # doc has 2 pages page2 = Image.open('temp/page1.jpeg') page2 = cut_width(page2, 2) concat = get_concat_vertical(page1, page2) concat.save(_global.CONCAT_AS_ONE_IMAGE) else: # doc has 1 page page1.save(_global.CONCAT_AS_ONE_IMAGE) return def get_concat_vertical(im1,im2): dst = Image.new('RGB', (im1.width, im1.height + im2.height)) dst.paste(im1, (0,0)) dst.paste(im2, (0, im1.height)) return dst def get_prepared_doc(name='data/500.tiff'): extantion = name.split('.')[-1] try: img = Image.open(name) except FileNotFoundError: print("ERROR: {}: file not found".format(name)) sys.exit(1) if extantion == 'tiff' or extantion == 'tif': tiff_to_jpeg(img) shutil.rmtree('./temp/') if extantion == 'png' or extantion == 'jpeg': image_to_png(img) img = cv2.imread(_global.CONCAT_AS_ONE_IMAGE,0) os.remove(_global.CONCAT_AS_ONE_IMAGE) return img
JavaScript
UTF-8
3,402
2.65625
3
[]
no_license
//------------------------------------------------- // Navegador Sticky //------------------------------------------------- window.onscroll = function () { myFunction() }; var navbar = document.getElementById("navbar"); var sticky = navbar.offsetTop; function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else { navbar.classList.remove("sticky"); } } //------------------------------------------------- // Navbar + Burger Menú | Responsive //------------------------------------------------- const navSlide = () => { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links'); const navLinks = document.querySelectorAll('.nav-links li'); burger.addEventListener('click', () => { //Toogle Nav nav.classList.toggle('nav-active'); //Animate Links navLinks.forEach((link, index) => { if (link.style.animation) { link.style.animation = ''; } else { link.style.animation = 'navLinkFade 0.5s ease forwards ${index / 7 + 1.5}s'; } }); //Burger Animation burger.classList.toggle('toggle'); }); } navSlide(); $('#navbar li').on('click', function(){ $('.nav-links').removeClass('nav-active'); $('.burger').removeClass('toggle'); }); //------------------------------------------------- // Opacity Background Image | Turn Off/On Lámpara //------------------------------------------------- const turnElem = document.querySelector('.turn'); const offElem = document.querySelector('.off'); const onElem = document.querySelector('.on'); const scrollAmount = -500; window.addEventListener('scroll', (event) => { const { top } = turnElem.getBoundingClientRect(); const turnInView = top - window.innerHeight < scrollAmount; offElem.style.opacity = +!turnInView; onElem.style.opacity = +turnInView; }); //------------------------------------------------- // Slider | Storytelling //------------------------------------------------- $(function () { $('.bxslider').bxSlider({ auto: false, mode: 'fade', controls: true, pagerCustom: "#bx-pager", link: $("#bx-pager a"), speed: 400, infiniteLoop: false, hideControlOnEnd: true, }); $('.bxslider2').bxSlider({ auto: false, mode: 'fade', randomStart: false, controls: true, pager: true, speed: 600, }); $('.bxslider3').bxSlider({ auto: false, mode: 'fade', controls: true, pager: true, speed: 600, }); $('.bxslider4').bxSlider({ auto: false, mode: 'fade', controls: true, pager: true, speed: 600, }); $('.bxslider5').bxSlider({ auto: false, mode: 'fade', controls: true, pager: true, speed: 600, }); }); //------------------------------------------------- // Comportamiento del Scrolling //------------------------------------------------- $('.menu a').on('click', function (e) { if (this.hash !== '') { e.preventDefault(); const hash = this.hash; $('html, body') .animate({ scrollTop: $(hash).offset().top }, 800); } });
Java
UTF-8
759
1.953125
2
[]
no_license
package com.smartwifi.bean; import android.databinding.BaseObservable; import android.databinding.Bindable; import com.smartwifi.BR; /** * Created by Administrator on 2018/7/19. */ public class FootLoadMoreBean extends BaseObservable { public void setStatus(int status) { this.status = status; notifyPropertyChanged(BR.status); } public void setText(String text) { this.text = text; notifyPropertyChanged(BR.text); } public void setShowLine(boolean showLine) { isShowLine = showLine; notifyPropertyChanged(BR.isShowLine); } @Bindable public int status; @Bindable public String text; @Bindable public boolean isShowLine; }
C#
UTF-8
1,228
2.921875
3
[ "MIT" ]
permissive
using UnityEngine; using System.Collections; public class Select : MonoBehaviour { public RaycastHit hit; private GameObject selectedObject = null; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2,Screen.height/2,0)); bool gotHit = Physics.Raycast (ray, out hit, 2); if(gotHit) { if( isSelectable(hit.collider.gameObject) && !isObjectSelected()) { //Debug.Log ("Selecting Object"); selectObject(hit.collider.gameObject); } } else if (isObjectSelected()){ deselectObject(selectedObject); } } private bool isSelectable(GameObject gameObject) { bool selectable = gameObject.GetComponent<Selectable>() != null; //Debug.Log ("Object is selectable: " + selectable.ToString()); return selectable; } private bool isObjectSelected() { return (selectedObject != null); } private void selectObject(GameObject gameObject) { selectedObject = gameObject; selectedObject.GetComponent<Selectable>().OnSelect (); } private void deselectObject(GameObject gameObject) { selectedObject.GetComponent<Selectable>().OnDeselect (); selectedObject = null; } }
TypeScript
UTF-8
4,874
3.03125
3
[ "MIT" ]
permissive
import { expect } from "chai"; import { Texture2D } from "../../../../src/graphics/textures/texture2d"; import { TextureBindingCache } from "../../../../src/graphics/textures/textureBindingCache"; import { TextureNoHandle } from "../../_generators/graphics/textures/texture2d.gen"; import "mocha"; describe("TextureBindingCache", () => { describe("constructor()", () => { it("throws if number of binding locations is < 1", () => { expect(() => new TextureBindingCache(0)).to.throw; }); }); describe("getNumBindLocations()", () => { it("returns value the cache was constructed with", () => { const count = 32; const cache = new TextureBindingCache(count); expect(cache.getNumBindLocations()).to.equal(32); }); }); describe("getBindLocation()", () => { it("roundtrips with bindAtLocation()", () => { const count = 2; const cache = new TextureBindingCache(count); const texture = TextureNoHandle; const location = 0; cache.bindAtLocation(texture, location); expect(cache.getBindLocation(texture)).to.equal(location); }); it("returns undefined for any unbound texture", () => { const count = 2; const cache = new TextureBindingCache(count); const texture = TextureNoHandle; expect(cache.getBindLocation(texture)).to.be.undefined; }); }); describe("bindAnywhere()", () => { it("works for a cache with only 1 bind location", () => { const count = 1; const cache = new TextureBindingCache(count); const texture = TextureNoHandle; cache.bindAnywhere(texture); expect(cache.getBindLocation(texture)).to.equal(0); }); }); describe("bindAtLocation()", () => { it("throws if the provided location is negative", () => { const cache = new TextureBindingCache(69); expect(() => cache.bindAtLocation(TextureNoHandle, -1)).to.throw; }); it("throws if the provided location exceeds cache size", () => { const count = 1; const cache = new TextureBindingCache(count); expect(() => cache.bindAtLocation(TextureNoHandle, count)).to.throw; }); it("returns true if texture is already bound to the provided location", () => { const cache = new TextureBindingCache(32); const texture = TextureNoHandle; const location = 8; cache.bindAtLocation(texture, location); expect(cache.bindAtLocation(texture, location)).to.be.true; }); it("returns false if texture is not already bound to the provided location", () => { const cache = new TextureBindingCache(32); const texture = TextureNoHandle; const location = 8; expect(cache.bindAtLocation(texture, location)).to.be.false; }); }); describe("markDirty()", () => { it("throws if the provided location is negative", () => { const cache = new TextureBindingCache(69); expect(() => cache.markDirty(-1)).to.throw; }); it("throws if the provided location exceeds cache size", () => { const count = 1; const cache = new TextureBindingCache(count); expect(() => cache.markDirty(count)).to.throw; }); it("marks a previously bound texture as unbound", () => { const cache = new TextureBindingCache(32); const texture = TextureNoHandle; const location = 8; cache.bindAtLocation(texture, location); expect(cache.getBindLocation(texture)).to.equal(location); cache.markDirty(location); expect(cache.getBindLocation(texture)).to.be.undefined; }); }); describe("markAllDirty()", () => { // Pretty hacky test... it("removes all textures from the cache", () => { const size = 5; const cache = new TextureBindingCache(size); const textures: Texture2D[] = []; for (let i = 0; i < size; i += 1) { const newTexture = JSON.parse(JSON.stringify(TextureNoHandle)) as Texture2D; textures[i] = newTexture; cache.bindAtLocation(newTexture, i); } cache.markAllDirty(); for (let i = 0; i < size; i += 1) { const texture = textures[i]; expect(cache.getBindLocation(texture)).to.be.undefined; } }); }); });
Java
UTF-8
1,145
3.796875
4
[]
no_license
package ds.algorithms.hackerRank; import java.util.HashMap; import java.util.Map; /** * Given a list of prices for the flavors of ice cream, select the two that will cost all of the money they have. * * For example, they have m = 6 and cost = [1,3,4,5,6] then 1+5 =8 index are 0 and 3 * crieria is 1 based indexing so value is 1 and 4 * * algo * m = x + y * x is the element in array * m = 6 * so we need to find y in the array * * y=m-x // if this value exist in the array then return that index * * create a map and put key as value and value as index * for each elemetn in array * y=m-x and check y is there in the map if not put it or get it back * */ public class IceCreamParlor { static int[] icecreamParlor(int m, int[] arr) { int[] result = new int[2]; Map<Integer,Integer> map=new HashMap<>(); for (int i = 0; i < arr.length; i++) { int y=m-arr[i]; if(map.containsKey(y)){ result[0]=i+1; result[1]=map.get(y)+1; }else{ map.put(arr[i],i); } } return result; } }
JavaScript
UTF-8
1,716
3.84375
4
[]
no_license
/* ------------------------------------------------------- description: 给定一个无重复元素的有序整数数组 nums 。 返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。 列表中的每个区间范围 [a,b] 应该按如下格式输出: "a->b" ,如果 a != b "a" ,如果 a == b   示例 1: 输入:nums = [0,1,2,4,5,7] 输出:["0->2","4->5","7"] 解释:区间范围是: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7" 示例 2: 输入:nums = [0,2,3,4,6,8,9] 输出:["0","2->4","6","8->9"] 解释:区间范围是: [0,0] --> "0" [2,4] --> "2->4" [6,6] --> "6" [8,9] --> "8->9" 示例 3: 输入:nums = [] 输出:[] 示例 4: 输入:nums = [-1] 输出:["-1"] 示例 5: 输入:nums = [0] 输出:["0"] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/summary-ranges 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ------------------------------------------------------- */ /** * @param {number[]} nums * @return {string[]} */ var summaryRanges = function(nums) { var start = 0, end = 1, res = []; while(start < nums.length) { if (nums[end - 1] + 1 === nums[end] && nums[end] !== undefined) { end ++; } else { if (start !== (end - 1)) { res.push(nums[start] + '->' + nums[end-1]); } else { res.push(String(nums[start])); } start = end; end++; } } return res; };
Java
UTF-8
5,235
3.453125
3
[ "BSD-3-Clause" ]
permissive
package vg.civcraft.mc.civmodcore.util; /** * General math utility class that <i>may</i> exist elsewhere, but I have none the foggiest where. If any of y'all * figure out where, feel free to lodge an official complaint. * * @author Protonull */ public final class MoreMath { /** * Limits a value between and including two values. * * @param value The value to clamp. * @param min The minimum value. * @param max The maximum value. * @return The clamped value. */ public static int clamp(final int value, final int min, final int max) { return Math.max(min, Math.min(value, max)); } /** * Limits a value between and including two values. * * @param value The value to clamp. * @param min The minimum value. * @param max The maximum value. * @return The clamped value. */ public static long clamp(final long value, final long min, final long max) { return Math.max(min, Math.min(value, max)); } /** * Limits a value between and including two values. * * @param value The value to clamp. * @param min The minimum value. * @param max The maximum value. * @return The clamped value. */ public static float clamp(final float value, final float min, final float max) { return Math.max(min, Math.min(value, max)); } /** * Limits a value between and including two values. * * @param value The value to clamp. * @param min The minimum value. * @param max The maximum value. * @return The clamped value. */ public static double clamp(final double value, final double min, final double max) { return Math.max(min, Math.min(value, max)); } /** * Normalises a value within a min-max range into a range between 0-1. * * @param value The value to normalise. * @param min The min range value. * @param max The max range value. * @return The normalised value. */ public static int norm(final int value, final int min, final int max) { return (value - min) / (max - min); } /** * Normalises a value within a min-max range into a range between 0-1. * * @param value The value to normalise. * @param min The min range value. * @param max The max range value. * @return The normalised value. */ public static long norm(final long value, final long min, final long max) { return (value - min) / (max - min); } /** * Normalises a value within a min-max range into a range between 0-1. * * @param value The value to normalise. * @param min The min range value. * @param max The max range value. * @return The normalised value. */ public static float norm(final float value, final float min, final float max) { return (value - min) / (max - min); } /** * Normalises a value within a min-max range into a range between 0-1. * * @param value The value to normalise. * @param min The range's lower limit. * @param max The range's upper limit. * @return The normalised value. */ public static double norm(final double value, final double min, final double max) { return (value - min) / (max - min); } /** * Applies a normalised value to a range. * * @param norm The {@link #norm(int, int, int) normalised} value. * @param min The range's lower limit. * @param max The range's upper limit. * @return The linearly interpolated value. */ public static int lerp(final int norm, final int min, final int max) { return (max - min) * norm + min; } /** * Applies a normalised value to a range. * * @param norm The {@link #norm(long, long, long) normalised} value. * @param min The range's lower limit. * @param max The range's upper limit. * @return The linearly interpolated value. */ public static long lerp(final long norm, final long min, final long max) { return (max - min) * norm + min; } /** * Applies a normalised value to a range. * * @param norm The {@link #norm(float, float, float) normalised} value. * @param min The range's lower limit. * @param max The range's upper limit. * @return The linearly interpolated value. */ public static float lerp(final float norm, final float min, final float max) { return (max - min) * norm + min; } /** * Applies a normalised value to a range. * * @param norm The {@link #norm(double, double, double) normalised} value. * @param min The range's lower limit. * @param max The range's upper limit. * @return The linearly interpolated value. */ public static double lerp(final double norm, final double min, final double max) { return (max - min) * norm + min; } /** * <p>This function will round numbers <i>away</i> from zero.</p> * * <ul> * <li>1.5 → 2</li> * <li>-1.5 → -2</li> * </ul> * * @param value The value to round away from zero. * @return The rounded value. */ public static double roundOut(final double value) { return value < 0 ? Math.floor(value) : Math.ceil(value); } /** * <p>This function will round numbers <i>towards</i> zero.</p> * * <ul> * <li>1.5 → 1</li> * <li>-1.5 → -1</li> * </ul> * * @param value The value to round towards zero. * @return The rounded value. */ public static double roundIn(final double value) { return value < 0 ? Math.ceil(value) : Math.floor(value); } }
Java
UTF-8
2,581
2.1875
2
[]
no_license
package de.fu_berlin.inf.dpp.activities.serializable; import org.apache.commons.lang.ObjectUtils; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamConverter; import de.fu_berlin.inf.dpp.activities.SPathDataObject; import de.fu_berlin.inf.dpp.activities.business.FileActivity.Purpose; import de.fu_berlin.inf.dpp.activities.business.FileActivity.Type; import de.fu_berlin.inf.dpp.activities.business.IActivity; import de.fu_berlin.inf.dpp.activities.business.RecoveryFileActivity; import de.fu_berlin.inf.dpp.filesystem.IPathFactory; import de.fu_berlin.inf.dpp.misc.xstream.JIDConverter; import de.fu_berlin.inf.dpp.net.JID; import de.fu_berlin.inf.dpp.session.ISarosSession; /** * Subclass of FileActivityDataObject that is used during the Recovery-Process * and allows the specification of targets. This Activity will is sent from the * host to the client that requested the recovery. */ @XStreamAlias("recoveryFileActivity") public class RecoveryFileActivityDataObject extends FileActivityDataObject implements IActivityDataObject { @XStreamAsAttribute @XStreamConverter(JIDConverter.class) protected JID target; public RecoveryFileActivityDataObject(JID source, JID target, Type type, SPathDataObject newPath, SPathDataObject oldPath, byte[] data) { super(source, type, newPath, oldPath, data, Purpose.RECOVERY); this.target = target; } @Override public IActivity getActivity(ISarosSession sarosSession, IPathFactory pathFactory) { return new RecoveryFileActivity(sarosSession.getUser(getSource()), sarosSession.getUser(target), getType(), path.toSPath(sarosSession, pathFactory), (oldPath != null ? oldPath.toSPath(sarosSession, pathFactory) : null), data); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ObjectUtils.hashCode(target); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof RecoveryFileActivityDataObject)) return false; RecoveryFileActivityDataObject other = (RecoveryFileActivityDataObject) obj; if (!ObjectUtils.equals(this.target, other.target)) return false; return true; } }
Java
UTF-8
618
2.46875
2
[]
no_license
package com.clomagno.codemapper.mapper.facades.dbf; import org.jamel.dbf.utils.DbfUtils; import com.clomagno.codemapper.mapper.ICell; public class DBFCellFacade implements ICell { private Object content; public DBFCellFacade(Object object) { this.content = object; } public void setCellValue(String value) { content = value; } @Override public String toString(){ try{ return new String(DbfUtils.trimLeftSpaces((byte[])content)); } catch (ClassCastException e){ try{ return ((Double) content).toString(); } catch (ClassCastException e2){ return content.toString(); } } } }
PHP
UTF-8
1,137
3.03125
3
[]
no_license
<?php include_once "CRUD/CRUDOperate.php"; $obj = new CRUDOperate(); echo "1- Number of Sales by ABA method<br>"; $query = "SELECT count(method) as amount FROM sales WHERE method='ABA'"; $result = $obj->select($query); foreach ($result->fetchAll() as $row){ // echo $row->item."-".$row->price."-".$row->quantity."-".$row->method."-".$row->total."<br>"; echo $row->amount; } echo "<br>"; echo "2- Number of Sales by PiPay and Wing method<br>"; $query = "SELECT count(method) as amount FROM sales WHERE method IN ('PiPay', 'Wing')"; $result = $obj->select($query); foreach ($result->fetchAll() as $row){ // echo $row->item."-".$row->price."-".$row->quantity."-".$row->method."-".$row->total."<br>"; echo $row->amount; } echo "<br>"; echo "3- Display all sales ordering by biggest total amount<br>"; $query = "SELECT * FROM sales ORDER BY total DESC"; $result = $obj->select($query); foreach ($result->fetchAll() as $row){ echo $row->item."-".$row->price."-".$row->quantity."-".$row->method."-".$row->total."<br>"; }
Rust
UTF-8
2,048
2.703125
3
[]
no_license
use std::env; use std::path::PathBuf; use std::path::Path; use std::fs; const REBUILD_BLOCKLIST: &[&str] = &[".git", "build"]; fn visit_dir(dir: &Path) -> std::io::Result<()> { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { if !REBUILD_BLOCKLIST.contains(&path.file_name().unwrap().to_str().unwrap()) { visit_dir(&path)?; } } else { println!("cargo:rerun-if-changed={}", fs::canonicalize(path)?.display()); } } Ok(()) } fn main() { let dst = cmake::build("stefan-code"); // Tell cargo to tell rustc where to find libstefan println!( "cargo:rustc-link-search={}", dst.display() ); // Tell cargo to tell rustc to link the static libstefan println!("cargo:rustc-link-lib=static=stefan"); // Also link the c++ standard library under Linux if cfg!(unix) { println!("cargo:rustc-link-lib=stdc++"); } // Tell cargo to invalidate the built crate whenever the C++ code changed visit_dir(Path::new("./stefan-code/")).unwrap(); // The bindgen::Builder is the main entry point // to bindgen, and lets you build up options for // the resulting bindings. let bindings = bindgen::Builder::default() // The input header we would like to generate // bindings for. .header("stefan-code/include/stefan.h") // Tell cargo to invalidate the built crate whenever any of the // included header files changed. .parse_callbacks(Box::new(bindgen::CargoCallbacks)) // Finish the builder and generate the bindings. .generate() // Unwrap the Result and panic on failure. .expect("Unable to generate bindings"); // Write the bindings to the $OUT_DIR/bindings.rs file. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); }
Markdown
UTF-8
27,885
2.828125
3
[ "MIT" ]
permissive
### 1 Git简介 Git是一个开源的分布式版本控制系统,用以有效、高速的处理从很小到非常大的项目版本管理。 GitHub可以托管各种git库的站点。 GitHub Pages免费的静态站点,三个特点:免费托管、自带主题、支持自制页面和Jekyll。 ### 2 为什么使用Github Pages \1. 搭建简单而且免费; \2. 支持静态脚本; \3. 可以绑定你的域名; \4. DIY自由发挥,动手实践一些有意思的东西git,markdown,bootstrap,jekyll; \5. 理想写博环境,git+github+markdown+jekyll; ### 3 创建Github Pages #### 3.1 安装git工具 [http://windows.github.com/](http://windows.github.com/) [http://mac.github.com/](http://mac.github.com/) #### 3.2 两种pages模式 1. **User/Organization Pages** 个人或公司站点 1) 使用自己的用户名,每个用户名下面只能建立一个; 2) 资源命名必须符合这样的规则username/username.github.com; 3) 主干上内容被用来构建和发布页面 2. **Project Pages** 项目站点 1) gh-pages分支用于构建和发布; 2) 如果user/org pages使用了独立域名,那么托管在账户下的所有project pages将使用相同的域名进行重定向,除非project pages使用了自己的独立域名; 3) 如果没有使用独立域名,project pages将通过子路径的形式提供服务username.github.com/projectname; 4) 自定义404页面只能在独立域名下使用,否则会使用User Pages 404; 5) 创建项目站点步骤: > $ git clone https://github.com/USERNAME/PROJECT.git PROJECT > > $ git checkout --orphan gh-pages > > $ git rm -rf . > > $ git add . > > $ git commit -a -m "First pages commit" > > $ git push origin gh-pages \3. 可以通过**User/Organization Pages**建立主站,而通过**Project Pages**挂载二级应用页面。 #### 3.3 创建步骤 第一步:创建个人站点 ![img](http://images.cnitblog.com/blog/275810/201303/07214321-2098fc71740240a7b33147881fa56d53.png) 第二步:设置站点主题 进入资源-setting ![img](http://images.cnitblog.com/blog/275810/201303/07214346-182c6e03424c4a74804530c5d61b9c72.png)  更新你的站点   ![img](http://images.cnitblog.com/blog/275810/201303/07214412-d3e051f728a4498d8ea7841a04b48f38.png)  选择主题并发布 ![img](http://images.cnitblog.com/blog/275810/201303/07214438-a18d78f052f84d2fa2d57a93ed4e54b2.png) #### 3.4 常用命令 > $ git clone [git@github.com:username/username.github.com.git](mailto:git@github.com:heiniuhaha/heiniuhaha.github.com.git) //本地如果无远程代码,先做这步,不然就忽略 > > $ cd .ssh/username.github.com //定位到你blog的目录下 > > $ git pull origin master //先同步远程文件,后面的参数会自动连接你远程的文件 > > $ git status //查看本地自己修改了多少文件 > > $ git add . //添加远程不存在的git文件 > > $ git commit * -m "what I want told to someone" > > $ git push origin master //更新到远程服务器上 ### 4 使用Jekyll搭建博客 #### 4.1 什么是jekyll Jekyll是一种简单的、适用于博客的、静态网站生成引擎。它使用一个模板目录作为网站布局的基础框架,支持Markdown、Textile等标记语言的解析,提供了模板、变量、插件等功能,最终生成一个完整的静态Web站点。说白了就是,只要安装Jekyll的规范和结构,不用写html,就可以生成网站。[[jekyll介绍](http://jekyllbootstrap.com/lessons/jekyll-introduction.html)][[jekyll on github](https://github.com/mojombo/jekyll)][[jekyllbootstrap](http://jekyllbootstrap.com/)]。 Jekyll使用Liquid模板语言,{{page.title}}表示文章标题,{{content}}表示文章内容。我们可以用两种Liquid标记语言:输出标记(output markup)和标签标记 (tag markup)。输出标记会输出文本(如果被引用的变量存在),而标签标记不会。输出标记是用双花括号分隔,而标签标记是用花括号-百分号对分隔。[[Liquid模板语言](https://github.com/shopify/liquid/wiki/liquid-for-designers)] [[Liquid模板变量参考](https://github.com/mojombo/jekyll/wiki/Template-Data)]。 jekyll与github的关系:GitHub Pages一个由 GitHub 提供的用于托管项目主页或博客的服务,jekyll是后台所运行的引擎。 #### 4.2 jekyll本地环境搭建 \1. 下载最新的[RubyInstaller](http://rubyforge.org/frs/?group_id=167)并安装(我下载的是[rubyinstaller-1.9.3-p194.exe](http://rubyforge.org/frs/download.php/76054/rubyinstaller-1.9.3-p194.exe)),设置环境变量,path中配置C:\Ruby193\bin目录,然后在命令行终端下输入gem update --system来升级gem; \2. 下载最新的[DevKit](https://github.com/oneclick/rubyinstaller/downloads/),DevKit是windows平台下编译和使用本地C/C++扩展包的工具。它就是用来模拟Linux平台下的make,gcc,sh来进行编译。但是这个方法目前仅支持通过RubyInstaller安装的Ruby,并双击运行解压到C:\DevKit。然后打开终端cmd,输入下列命令进行安装: > cd C:\DevKit > > ruby dk.rb init > > ruby dk.rb install \3. 完成上面的准备就可以安装Jekyll了,因为Jekyll是用Ruby编写的,最好的安装方式是通过RubyGems(gem): > gem install Jekyll 并使用命令检验是否安装成功 > jekyll --version \4. 安装Rdiscount,这个用来解析Markdown标记的包,使用如下命令: > gem install rdiscount \5. 运行本地工程: cd 到工程目录,启动服务: > jekyll --server #### 4.3 jekyll目录结构 -  **_posts**: _posts中的数据文档,通过注入_layouts定义的模板,通过jekyll --server最终生成的静态页面在_sites目录。目录是用来存放你的文章的,一般以日期的形式书写标题。 -  **_layouts**:_layouts中的模板一般指向了_includes/themes中的模板。目录是用来存放模板的,在这里你可以定义页面中不同的头部和底部。 -  **_includes**: > 1) _includes/JB中有一些常用的工具,用于列表显示、评论等; > > 2) _includes/themes中可参看主题的相关html文档。 > > 3) _includes/themes中的主题一般包含default.html、post.html和page.html三个文档。default.html定义了网站的最上层框架(模板),post.html和page.html是其子框架(模板)。 > > 4) 生成好的html子页面通过default.html的{{ content }}变量调用,生成整个页面。 -  **assets** 渲染页面的CSS和JS文档在assets/themes中 -  **_config.yml** 站点生成需要用到_config.yml配置文件,站点的全局变量在_config.yml中定义,用site.访问;页面的变量在YAML Front Matter中定义,用page.访问,更多的模板变量可参考模板数据。 -  **index.html**是你的页面首页。 #### 4.4 Jekyll-Bootstrap创建博客 \1. 创建个人站点,即创建一个新资源,格式为username.github.com; \2. 安装Jekyll-Bootstrap: > $ git clone https://github.com/plusjade/jekyll-bootstrap.git USERNAME.github.com > > $ cd USERNAME.github.com > > $ git remote set-url origin git@github.com:USERNAME/USERNAME.github.com.git > > $ git push origin master \3. 访问创建好的个人站点:username.github.com \4. 在本地测试查看效果: > cd USERNAME.github.com > > jekyll --server #### 4.5 Jekyll 写博过程 1、 **配置**_config.yml: 1) **修改标题**:title : My Blog =) 2) **修改个人信息**: > author : > > name : Name Lastname > > email : blah@email.test > > github : username > > twitter : username > > feedburner : feedname 3) **引用**:_config.yml中的键值均引用到其他页面{{ site.title }}; **2、 ****写文章** 按照_config.yml的格式permalink: /:categories/:year/:month/:day/:title,可以修改格式,创建markdown格式文件,就可以当初博客发布了。 **3、 ****发布** 本地预览修改:运行jekyll –server,预览http:127.0.0.1:4000。 发布到github上:通过命令提交或者客户端提交。 #### 4.6 个性化博客 Github Page完成了博客的主要功能,写作、发布、修改,这些都是相对静态的东西,就是你自己可以控制的事情,还有一些动态的东西Github Pages无法支持,比如说文章浏览次数、文章的评论等,还有一些个性化的东西,像个性化页头页尾、代码高亮可以把博客整的更漂亮一点,其实这写都可以通过第三方应用来实现,个性化自己的博客。 加上Disqus云评论: 注册[http://disqus.com/](http://disqus.com/) > 修改_config.yml: > > comments : > > provider : disqus > > disqus : > > short_name : tiansj ### 5 使用Markdown #### 5.1 简介 Markdown 的宗旨是实现「易读易写」。可读性,无论如何,都是最重要的。 Markdown 的语法全由一些符号所组成,这些符号经过精挑细选,其作用一目了然。格式撰写的文件可以直接以纯文本发布,并且看起来不会像是由许多标签或是格式指令所构成。 资料:[[搭建环境](http://www.cnblogs.com/purediy/archive/2013/01/10/2855397.html)] #### 5.2 基本语法 - 使用一个或多个空行分隔内容段来生成段落 <p>。 - 标题(h1~h6)格式为使用相应个数的“#”作前缀,比如以下代码表示 h3: \### this is a level-3 header ### - 使用“>”作为段落前缀来标识引用文字段落。这其实是 email 中标记引用文字的标准方式: \> 引用的内容 \> 这个记号直接借鉴的邮件标准 - 使用“*”“+”“-”来表示无序列表;使用数字加“.”表示有序列表。如: \1. I am ordered list item 1... \2. So I should be item 2!? - 使用 4 个以上 空格或 1 个以上 的 tab 来标记代码段落,它们将被<pre> 和 <code> 包裹,这意味着代码段内的字体会是 monospace家族的,并且特殊符号不会被转义。 - 使用 [test](http://example.net "optional title") 来标记普通链接。 - 使用 ![img](http://example.net/img.png "optional title") 来标记图片。 引号内的 title 文字是可选的,链接也可以使用相对路径。 - 使用 * 或 _ 包裹文本产生 strong 效果: _语气很重的文本_ 以及 **语气更重的文本** #### 5.3 Notepad++支持Markdown语法高亮 \1. 下载[userDefineLang.xml](https://github.com/thomsmits/markdown_npp) \2. 将 userDefineLang.xml 放置到此目录:C:\Users\Administrator\AppData\Roaming\Notepad++ \3. 重启 Notepad++,在语言菜单下可以看到自定义的 Markdown 高亮规则 # 3.5. 建立主页 很多开源项目托管平台都支持为托管的项目建立主页,但主页的维护方式都没有GitHub这么酷。大多数托管平台无非是开放一个FTP或类似服务,用户把制作好的网页或脚本上传了事,而在GitHub用户通过创建特殊名称的Git版本库或在Git库中建立特别的分支实现对主页的维护。 ## 3.5.1. 创建个人主页 GitHub 为每一个用户分配了一个二级域名<user-id>.github.io,用户为自己的二级域名创建主页很容易,只要在托管空间下创建一个名为<user-id>.github.io的版本库,向其master分支提交网站静态页面即可,其中网站首页为index.html。下面以gotgithub用户为例介绍如何创建个人主页。 - 用户gotgithub创建一个名为gotgithub.github.io的Git版本库。 在GitHub上创建版本库的操作,参见“第3.1节 [*创建新项目*](http://www.worldhello.net/gotgithub/03-project-hosting/010-new-project.html#new-project)”。 - 在本地克隆新建立的版本库。 ``` $ git clone git@github.com:gotgithub/gotgithub.github.io.git $ cd gotgithub.github.io/ ``` - 在版本库根目录中创建文件index.html作为首页。 ``` $ printf "<h1>GotGitHub's HomePage</h1>It works.\n" > index.html ``` - 建立提交。 ``` $ git add index.html $ git commit -m "Homepage test version." ``` - 推送到GitHub,完成远程版本库创建。 ``` $ git push origin master ``` - 访问网址: [http://gotgithub.github.io/](http://gotgithub.github.io/) 。 最多等待10分钟,GitHub就可以完成新网站的部署。网站完成部署后版本库的所有者会收到邮件通知。 还有要注意访问用户二级域名的主页要使用HTTP协议非HTTPS协议。 ## 3.5.2. 创建项目主页 如前所述,GitHub会为每个账号分配一个二级域名<user-id>.github.io作为用户的首页地址。实际上还可以为每个项目设置主页,项目主页也通过此二级域名进行访问。 例如gotgithub用户创建的helloworld项目如果启用了项目主页,则可通过网址http://gotgithub.github.io/helloworld/访问。 为项目启用项目主页很简单,只需要在项目版本库中创建一个名为gh-pages的分支,并向其中添加静态网页即可。也就是说如果项目的Git版本库中包含了名为gh-pages分支的话,则表明该项目提供静态网页构成的主页,可以通过网址http://<user-id>.github.io/<project-name>访问到。 下面以用户gotgithub的项目helloworld为例,介绍如何维护项目主页。 如果本地尚未从GitHub克隆helloworld版本库,执行如下命令。 ``` $ git clone git@github.com:gotgithub/helloworld.git $ cd helloworld ``` 当前版本库只有一个名为master的分支,如果直接从master分支创建gh-pages分支操作非常简单,但是作为保存网页的gh-pages分支中的内容和master分支中的可能完全不同。如果不希望gh-pages分支继承master分支的历史和文件,即想要创建一个干净的gh-pages分支,需要一点小技巧。 若使用命令行创建干净的gh-pages分支,可以从下面三个方法任选一种。 第一种方法用到两个Git底层命令:git write-tree和git commit-tree。步骤如下: - 基于master分支建立分支gh-pages。 ``` $ git checkout -b gh-pages ``` - 删除暂存区文件,即相当于清空暂存区。 ``` $ rm .git/index ``` - 创建项目首页index.html。 ``` $ printf "hello world.\n" > index.html ``` - 添加文件index.html到暂存区。 ``` $ git add index.html ``` - 用Git底层命令创建新的根提交,并将分支gh-pages重置。 ``` $ git reset --hard $(echo "branch gh-pages init." | git commit-tree $(git write-tree)) ``` - 执行推送命令,在GitHub远程版本库创建分支gh-pages。 ``` $ git push -u origin gh-pages ``` 第二种方法用到Git底层命令:git symbolic-ref。步骤如下: - 用git symbolic-ref命令将当前工作分支由master切换到一个尚不存在的分支gh-pages。 ``` $ git symbolic-ref HEAD refs/heads/gh-pages ``` - 删除暂存区文件,即相当于清空暂存区。 ``` $ rm .git/index ``` - 创建项目首页index.html。 ``` $ printf "hello world.\n" > index.html ``` - 添加文件index.html到暂存区。 ``` $ git add index.html ``` - 执行提交。提交完毕分支gh-pages完成创建。 ``` $ git commit -m "branch gh-pages init." ``` - 执行推送命令,在GitHub远程版本库创建分支gh-pages。 ``` $ git push -u origin gh-pages ``` 第三种方法没有使用任何Git底层命令,是从另外的版本库获取提交建立分支。操作如下: - 在helloworld版本库之外创建另外一个版本库,例如helloworld-web。 ``` $ git init ../helloworld-web $ cd ../helloworld-web ``` - 在helloworld-web版本库中创建主页文件index.html。 ``` $ printf "hello world.\n" > index.html ``` - 添加文件index.html到暂存区。 ``` $ git add index.html ``` - 执行提交。 实际提交到master分支,虽然提交说明中出现的是gh-pages 。 ``` $ git commit -m "branch gh-pages init." ``` - 切换到helloworld版本库目录。 ``` $ cd ../helloworld ``` - 从helloworld-web版本库获取提交,并据此创建gh-pages分支。 ``` $ git fetch ../helloworld-web $ git checkout -b gh-pages FETCH_HEAD ``` - 执行推送命令,在GitHub远程版本库创建分支gh-pages。 ``` $ git push -u origin gh-pages ``` 无论哪种方法,一旦在GitHub远程版本库中创建分支gh-pages,项目的主页就已经建立。稍后(不超过10分钟),用浏览器访问下面的地址即可看到刚刚提交的项目首页:[http://gotgithub.github.io/helloworld/](http://gotgithub.github.io/helloworld/) 。 除了以上通过命令行创建gh-pages分支为项目设定主页之外,GitHub还提供了图形操作界面。如图3-19所示。 [![../images/github-pages.png](http://www.worldhello.net/gotgithub/images/github-pages.png)](http://www.worldhello.net/gotgithub/images/github-pages.png)图3-19:项目管理页面中的GitHub Pages选项 当在项目管理页面中勾选“GitHub Pages”选项,并按照提示操作,会自动在项目版本库中创建gh-pages分支。然后执行下面命令从版本库检出gh-pages分支,对项目主页进行相应定制。 ``` $ git fetch $ git checkout gh-pages ``` ## 3.5.3. 使用专有域名 无论是用户主页还是项目主页,除了使用github.com下的二级域名访问之外,还可以使用专有域名。实现起来也非常简单,只要在master分支(用户主页所在版本库)或gh-pages分支(项目版本库)的根目录下检入一个名为CNAME的文件,内容为相应的专有域名。当然还要更改专有域名的域名解析,使得该专有域名的IP地址指向相应的GitHub二级域名的IP地址。 例如worldhello.net[[1\]](http://www.worldhello.net/gotgithub/03-project-hosting/050-homepage.html#id9)是我的个人网站,若计划将网站改为由GitHub托管,并由账号gotgit通过个人主页提供服务,可做如下操作。 首先按照前面章节介绍的步骤,为账号gotgit设置账户主页。 1. 在账户gotgit下创建版本库gotgit.github.io以维护该账号主页。 地址: [https://github.com/gotgit/gotgit.github.io/](https://github.com/gotgit/gotgit.github.io/) 2. 将网站内容提交并推送到该版本库master分支中。 即在gotgit.github.io版本库的根目录下至少包含一个首页文件,如index.html。还可以使用下节将要介绍到的 Jekyll 技术,让网页有统一的显示风格,此时首页文件可能并非一个完整的HTML文档,而是套用了页面模版。 3. 至此当访问网址[http://gotgit.github.io](http://gotgit.github.io/)时,会将账号gotgit的版本库gotgit.github.io中的内容作为网站内容显示出来。 接下来进行如下操作,使得该网站能够使用专有域名www.worldhello.net提供服务。 1. 在账号gotgit的版本库gotgit.github.io根目录下添加文件CNAME,文件内容为:www.worldhello.net。 参见: [https://github.com/gotgit/gotgit.github.io/blob/master/CNAME](https://github.com/gotgit/gotgit.github.io/blob/master/CNAME) 2. 然后更改域名www.worldhello.net的IP地址,指向域名gotgit.github.io对应的IP地址(注意不是github.com的IP地址)。 完成域名的DNS指向后,可试着用ping或dig命令确认域名www.worldhello.net和gotgit.github.io指向同一IP地址。 ``` $ dig @8.8.8.8 -t a www.worldhello.net ... ; ANSWER SECTION: www.worldhello.net. 81078 IN A 204.232.175.78 $ dig @8.8.8.8 -t a gotgit.github.io ... ; ANSWER SECTION: gotgit.github.io. 43200 IN A 204.232.175.78 ``` 设置完成后用浏览器访问 [http://www.worldhello.net/](http://www.worldhello.net/) 即可看到由账号gotgit的版本库gotgit.github.io维护的页面。若将域名worldhello.net(不带www前缀)也指向IP地址204.232.175.78,则访问网址[http://worldhello.net/](http://worldhello.net/)会发现GitHub体贴地将该网址重定向到正确的地址[http://www.worldhello.net/](http://www.worldhello.net/)。 在账号gotgit下的其他版本库,若包含了gh-pages分支,亦可由域名www.worldhello.net访问到。 - 网址 [http://www.worldhello.net/doc](http://www.worldhello.net/doc) 实际对应于版本库 [gotgit/doc](https://github.com/gotgit/doc) 。 - 网址 [http://www.worldhello.net/gotgit](http://www.worldhello.net/gotgit) 实际对应于版本库 [gotgit/gotgit](https://github.com/gotgit/gotgit) 。 - 网址 [http://www.worldhello.net/gotgithub](http://www.worldhello.net/gotgithub) 实际对应于版本库 [gotgit/gotgithub](https://github.com/gotgit/gotgithub)。 ## 3.5.4. 使用Jekyll维护网站 Jekyll是一个支持Textile、Markdown等标记语言的静态网站生成软件,还支持博客和网页模版,由Tom Preston-Werner(GitHub创始人之一)开发。Jekyll用Ruby语言实现,项目在GitHub的托管地址: [http://github.com/mojombo/jekyll/](http://github.com/mojombo/jekyll/) ,专有的URL地址为:[http://jekyllrb.com/](http://jekyllrb.com/)。 GitHub为用户账号或项目提供主页服务,会从相应版本库的master分支或gh-pages分支检出网页文件,然后执行 Jekyll 相应的命令对网页进行编译。因此在设计GitHub的用户主页和项目主页时都可以利用Jekyll,实现用Markdown等标记语言撰写网页及博客,并用页面模版实现网页风格的统一。 安装Jekyll最简单的方法是通过RubyGems安装,会自动将Jekyll依赖的directory_watcher、liquid、open4、maruku和classifier等Gem包一并安装。 ``` $ gem install jekyll ``` 如果安装过程因编译扩展模组遇到错误,可能是因为尚未安装所需的头文件,需要进行如下操作: - 对于Debian Linux、Ubuntu等可以用如下方法安装所需软件包: ``` $ sudo apt-get install ruby1.8-dev ``` - 如果是Red Hat、CentOS或Fedora等系统,使用如下命令安装: ``` $ sudo yum install ruby-devel ``` - 对于Mac OSX,可能需要更新RubyGems,如下: ``` $ sudo gem update --system ``` Jekyll安装完毕,执行下面的命令显示软件版本: ``` $ jekyll -v Jekyll 0.11.0 ``` 要学习如何用Jekyll设计网站,可以先看一下作者Tom Preston-Werner在GitHub上的个人网站是如何用Jekyll制作出来的。 克隆版本库: ``` $ git clone git://github.com/mojombo/mojombo.github.com.git ``` 版本库包含的文件如下: ``` $ cd mojombo.github.com $ ls -F CNAME _config.yml _posts/ css/ index.html README.textile _layouts/ atom.xml images/ random/ ``` 版本库根目录下的index.html文件不是一个普通的HTML文件,而是使用Liquid模版语言[[2\]](http://www.worldhello.net/gotgithub/03-project-hosting/050-homepage.html#id10)定义的页面。 ``` 1 --- 2 layout: default 3 title: Tom Preston-Werner 4 --- 5 6 <div id="home"> 7 <h1>Blog Posts</h1> 8 <ul class="posts"> 9 {% for post in site.posts %} 10 <li><span>{{ post.date | date_to_string }}</span> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li> 11 {% endfor %} 12 </ul> ... 63 </div> ``` 为方便描述为内容添加了行号,说明如下: - 第1-4行是YAML格式的文件头,设定了该文件所使用的模版文件及模版中要用到的变量。 凡是设置有YAML文件头的文件(目录_layouts除外)无论文件扩展名是什么,都会在Jekyll编译时进行转换。若源文件由Markdown等标记语言撰写(扩展名为.md、.textile等),Jekyll还会将编译后的文件还将以扩展名.html来保存。 - 其中第2行含义为使用default模版。 对应的模版文件为_layouts/default.html。 - 第3行设定本页面的标题。 在模版文件_layouts/default.html中用{{ page.title }}语法嵌入所设置的标题。下面是模版文件中部分内容: ``` <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>{{ page.title }}</title> ``` - 第6行开始的内容绝大多数是标准的HTML语法,其中夹杂少量Liquid模版特有的语法。 - 第9行和第11行,对于有着Liquid或其他模版编程经验的用户,不难理解其中出现的由“{%”和“%}”标识的指令是一个循环指令(for循环),用于逐条对博客进行相关操作。 - 第10行中由“{{”和“}}”标识的表达式则用于显示博文的日期、链接和标题。 非下划线(_)开头的文件(包括子目录中文件),如果包含YAML文件头,就会使用Jekyll进行编译,并将编译后的文件复制到目标文件夹(默认为_site目录)下。对于包含YAML文件头并用标记语言Markdown等撰写的文件,还会将编译后的文件以.html扩展名保存。而以下划线开头的文件和目录有的直接忽略不予处理(如_layouts、_site目录等),有的则需要特殊处理(如_post目录)。 目录_post用于保存博客条目,每个博客条目都以<YYYY>-<MM>-<DD>-<blog-tiltle>格式的文件名命名。扩展名为.md的为Markdown格式,扩展名为.textile的为Textile格式。这些文件都包含类似的文件头: ``` --- layout: post title: How I Turned Down $300,000 from Microsoft to go Full-Time on GitHub --- ``` 即博客使用文件_layouts/post.html作为页面模版,而不是index.html等文件所使用的_layouts/default.html模版。这些模版文件都采用Liquid模版语法。保存于_post目录下的博客文件编译后会以<YYYY>/<MM>/<DD>/<blog-title>.html文件名保存在输出目录中。 在根目录下还有一个配置文件_config.yml用于覆盖Jekyll的默认设置,例如本版本库中的设置。 ``` markdown: rdiscount pygments: true ``` 第1行设置使用rdiscount软件包作为Markdown的解析引擎,而非默认的Maruku。第2行开启pygments支持。对于中文用户强烈建议通过配置文件_config.yml重设 markdown 解析引擎,默认的 Maruku 对中文支持不好,而使用 rdiscount 或 kramdown 均可。关于该配置文件的更多参数详见Jekyll项目维基[[3\]](http://www.worldhello.net/gotgithub/03-project-hosting/050-homepage.html#id11) 。 编译Jekyll编辑网站只需在根目录执行jekyll命令,下面的命令是GitHub更新网站所使用的默认指令。 ``` $ jekyll --pygments --safe ``` 现在执行这条命令,就会将整个网站创建在目录_site下。 如果没有安装Apache等Web服务器,还可以使用Jekyll的内置Web服务器。 ``` $ jekyll --server ``` 默认在端口4000开启Web服务器。 网址 [http://gitready.com/](http://gitready.com/) 是一个提供Git使用小窍门的网站,如图3-20所示。 [![../images/gitready.png](http://www.worldhello.net/gotgithub/images/gitready.png)](http://www.worldhello.net/gotgithub/images/gitready.png)图3-20:Git Ready 网站 你相信这是一个用Jekyll制作的网站么?看看该网站对应的IP,会发现其指向的正是GitHub。研究GitHub上 [gitready](https://github.com/gitready) 用户托管的版本库,会发现en版本库的gh-pages分支负责生成gitready.com网站,de版本库的gh-pages分支负责生成德文网站de.gitready.com,等等。而gitready版本库则是各种语种网站的汇总。 我的个人网站也使用Jekyll构建并托管在GitHub上,网址:[http://www.worldhello.net/](http://www.worldhello.net/)。 | [[3\]](http://www.worldhello.net/gotgithub/03-project-hosting/050-homepage.html#id8) | [http://www.worldhello.net/gotgithub/03-project-hosting/050-homepage.html](https://github.com/mojombo/jekyll/wiki/configuration) | | ---------------------------------------- | ---------------------------------------- | | | |
Java
UTF-8
2,705
2.875
3
[]
no_license
package atcoder.TDPC; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class TDPC_E { int d; int MOD = 1000000007; char[] cs; public static void main(String args[]) { new TDPC_E().run(); } void run() { FastReader sc = new FastReader(); d = sc.nextInt(); cs = sc.next().toCharArray(); solve(); } void solve() { int[] nDigits = new int[cs.length]; for (int i = 0; i < cs.length; i++) { nDigits[i] = Character.getNumericValue(cs[i]); } long[][][] dp = new long[10001][2][100]; dp[0][0][0] = 1; for (int i = 0; i < nDigits.length; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < d; k++) { int limit = j == 1 ? 9 : nDigits[i]; for (int l = 0; l <= limit; l++) { int jNum = j; if (l < limit) { jNum = 1; } int kNum = (k + l) % d; dp[i + 1][jNum][kNum] += dp[i][j][k]; dp[i + 1][jNum][kNum] %= MOD; } } } } long ans = 0; for (int j = 0; j < 2; j++) { ans += dp[nDigits.length][j][0]; ans %= MOD; } ans += MOD - 1; ans %= MOD; System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
C#
UTF-8
4,220
2.765625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinearVisualEncoding { public delegate Color ColourSelection<T>(T obj); public delegate float ThicknessSelection<T>(T obj); public delegate void EndMarkerDrawer(Graphics g, PointF focusPoint, PointF connectionPoint, TransferPath tp, Color? colorOverride = null); public abstract class Path { public int zorder; public Color colour; public float thickness; public abstract void draw(Graphics g, Color? colourOverride = null); public abstract RectangleF bounds { get; } public abstract float length { get; } } public class EntityDepictionParameters { public ColourSelection<Entity> colourSelection; public ThicknessSelection<Entity> thicknessSelection; } public class EntityPath : Path { public Entity entity; public DepictionInterval di; public float u, y, x0, x1; public override void draw(Graphics g, Color? colourOverride = null) { Color c = (colourOverride.HasValue ? colourOverride.Value : this.colour); using (Pen p = new Pen(c, this.thickness)) { g.DrawLine(p, x0, y, x1, y); } //g.DrawString(entity.id + "", LinearVisualEncoding.keyFont, Brushes.Black, x0, y - 5); } public override RectangleF bounds { get { float s = 2 * Math.Max(1, thickness); return new RectangleF(x0 - s, y - s, x1 - x0 + 2 * s, 2 * s); } } public override float length { get { return x1 - x0; } } } public class TransferDepictionParameters { public EndMarkerDrawer startMarkerDrawer; public EndMarkerDrawer finishMarkerDrawer; public ColourSelection<Transfer> colourSelection; public ThicknessSelection<Transfer> thicknessSelection; public float ls, lf; } public class TransferPath : Path { public Transfer transfer; public PointF focusPointA, focusPointB; public PointF connectionPointA, connectionPointB; public EndMarkerDrawer startMarkerDrawer; public EndMarkerDrawer finishMarkerDrawer; public override void draw(Graphics g, Color? colourOverride = null) { Color c = colourOverride.HasValue ? colourOverride.Value : this.colour; using (Pen p = new Pen(c, this.thickness)) { g.DrawLine(p, connectionPointA, connectionPointB); startMarkerDrawer(g, focusPointA, connectionPointA, this, c); finishMarkerDrawer(g, focusPointB, connectionPointB, this, c); } } public static float min(params float[] values) { float minV = values[0]; for (int i = 1; i < values.Length; i++) { minV = minV < values[i] ? minV : values[i]; } return minV; } public static float max(params float[] values) { float minV = values[0]; for (int i = 1; i < values.Length; i++) { minV = minV > values[i] ? minV : values[i]; } return minV; } public override RectangleF bounds { get { float x0 = min(focusPointA.X, focusPointB.X, connectionPointA.X, connectionPointB.X); float x1 = max(focusPointA.X, focusPointB.X, connectionPointA.X, connectionPointB.X); float y0 = min(focusPointA.Y, focusPointB.Y, connectionPointA.Y, connectionPointB.Y); float y1 = max(focusPointA.Y, focusPointB.Y, connectionPointA.Y, connectionPointB.Y); float s = 2 * thickness; return new RectangleF(x0 - s, y0 - s, x1 - x0 + 2 * s, y1 - y0 + 2 * s); } } public override float length { get { return Math.Abs(focusPointB.Y - focusPointA.Y); } } } }
Java
UTF-8
1,732
2.578125
3
[]
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 hilos; import java.util.logging.Level; import java.util.logging.Logger; import proyecto2.RecogeBloques; /** * * @author USUARIO */ public class hilo_temporal implements Runnable { @Override public void run() { while (true) { // if(RecogeBloques.lista_rojos.choque(RecogeBloques.jugador)==true){ // System.out.println("choque con rojo"); // break; // } // // if(RecogeBloques.lista_azules.choque(RecogeBloques.jugador)==true){ // System.out.println("choque con azul"); // break; // } // if( RecogeBloques.lista_amarillos.choque(RecogeBloques.jugador)==true){ // System.out.println("choque con amarillo"); // break; // } // if( RecogeBloques.lista_verdes.choque(RecogeBloques.jugador)==true){ // System.out.println("choque con verde"); // break; // } RecogeBloques.lista_rojos.choque(RecogeBloques.jugador); RecogeBloques.lista_azules.choque(RecogeBloques.jugador); RecogeBloques.lista_amarillos.choque(RecogeBloques.jugador); RecogeBloques.lista_verdes.choque(RecogeBloques.jugador); // try { // Thread.sleep(200); // } catch (InterruptedException ex) { // Logger.getLogger(hilo_temporal.class.getName()).log(Level.SEVERE, null, ex); // } } } }
Markdown
UTF-8
1,016
2.671875
3
[]
no_license
# Helm Charts The canonical source for Helm charts is the [Helm Hub](https://hub.helm.sh/), an aggregator for distributed chart repos. This GitHub project is the source for Helm `stable` and `incubator` [Helm chart repositories](https://v3.helm.sh/docs/topics/chart_repository/), currently listed on the Hub. For more information about installing and using Helm, see the [Helm Docs](https://helm.sh/docs/). For a quick introduction to Charts, see the [Chart Guide](https://helm.sh/docs/topics/charts/). ## Status of the Project Similar to the [Helm 2 Support Plan](https://helm.sh/blog/2019-10-22-helm-2150-released/#helm-2-support-plan), this GitHub project has begun transition to a 1 year "maintenance mode" (see [Deprecation Timeline](#deprecation-timeline) below). Given the deprecation plan, this project is intended for [apiVersion: v1](https://helm.sh/docs/topics/charts/#the-apiversion-field) Charts (installable by both Helm 2 and 3), and not for `apiVersion: v2` charts (installable by Helm 3 only).
Markdown
UTF-8
6,709
3.140625
3
[]
no_license
# 敏感接口加固 &emsp;&emsp;目前前后端交互过程中没有考虑过敏感数据的安全问题,极易被攻击者利用,擅自篡改敏感数据使得接口被攻击。 ## 整改思路 1. 敏感数据存储后台,不允许直接使用前台的数据 2. 关联接口进行依赖校验,必须成功完成前置接口,才能调用下一个接口。 ## 接口整改 &emsp;&emsp;现在 wsg 中使用一个公共的 Controller 接受前端调用的接口,然后调用对应的 hsf 服务。现在需要将这部分逻辑提取出来形成单独的 Controller,并为其添加自己单独的逻辑。 ### 选号、选占接口 #### 选号接口修改 &emsp;&emsp;接口前端调用的文件为`op_web_view_o2o\apps\serviceapps\pub-ui\service_js\shopInfoWrite.js`,用户下单的页面 &emsp;&emsp;原有的选号接口在`op_web_view_o2o\online-ui\js\ajaxconfig.js`中配置的路径为: ```js 'share-selectSerialNumber': '/o2o/wsg/def/com_sitech_o2o_contact_service_ISelectNumServiceSvc_selectNum', //分享业务移网号码选择 ``` &emsp;&emsp;即使用了 wsg 中公用的 Controller 转发请求到后台各个域。现在需要进行改造,创建新的专用 Controller。其中的代码逻辑和原有的公共逻辑没有变化,仅增加将返回的选号数组保存 wsg 的 session 中,提供选占接口使用。例如: ```js session.setItem("selectNumArray", JSON.toJSONString(["186xxxx8680","155xxxx9680","173xxxx9680"]) ``` &emsp;&emsp;新的选号接口路径建议为:`/o2o/wsg/selectNum` &emsp;&emsp;<b>改造点:</b> 1. 创建新的 Controller,其中实现保存返回选号数据到 session 2. 新的 Controller 路径需要加入免登录校验配置中 3. 前端`ajaxconfig.js`中的 share-selectSerialNumber 的 key 对应的值更改为新的链接路径 #### 选占接口修改 &emsp;\$emsp;接口前端调用的文件为`op_web_view_o2o\apps\serviceapps\pub-ui\service_js\shopInfoWrite.js`,用户下单的页面 &emsp;&emsp;原有的选号接口在`op_web_view_o2o\online-ui\js\ajaxconfig.js`中配置的路径为: ```js 'share-serialNumberStateChange': '/o2o/wsg/def/com_sitech_o2o_contact_service_ISelectNumServiceSvc_changeNumStatus' ``` &emsp;&emsp;这个接口原来也是使用的公共 Controller 转到各个域。现在需要进行调整,创建单独的 Controller,校验入参中的校验参数,‘选占号码’不允许传入具体的手机号码,只允许传入对应选号时保存在 session 中的标识。然后取下 session 中的数据替换该字段数据。 &emsp;&emsp;判断后台服务是否返回选占成功,如果选占成功,则将选占成功的号码保存在 session 中。例如:`session.setItem("checkedNum", "183xxxx9680")` &emsp;&emsp;新的选号接口路径建议为:`/o2o/wsg/changeNumStatus` &emsp;&emsp;<b>改造点:</b> 1. 创建新的 Controller,校验‘选占号码’的入参必须为标识,然后从 session 中能取到该数据,在替换掉选在号码字段内容。 2. 新的 Controller 路径需要加入免登录校验配置中 3. 前端`ajaxconfig.js`中的 share-serialNumberStateChange 的 key 对应的值更改为新的链接路径。 ### 订单归集接口 &emsp;&emsp;接口前端调用的文件为`op_web_view_o2o\apps\serviceapps\pub-ui\service_js\shopInfoWrite.js`,用户下单的页面 &emsp;&emsp;原有的选号接口在`op_web_view_o2o\online-ui\js\ajaxconfig.js`中配置的路径为: ```js 'share-preSubmit':'/o2o/wsg/def/com_sitech_o2o_trade_service_ITradePreSubmitServiceSvc_insertITradePreSubmitTable', ``` &emsp;&emsp;现在订单归集接口需要修改为选占号码不从前台传输,该从 wsg 的 session 中获取选占号码。 &emsp;&emsp;创建新的 Controller,复制原有公共 Controller 的调用 hsf 的逻辑。当 Controller 被调用时,从 session 中获取 key(`checkedNum`)对应的手机号码,判断号码准确性后放置在请求报文对应的`serialNumber`字段,(位置大概在{"array":[{"serialNumber":"xxx"}]}) &emsp;&emsp;<b>改造点:</b> 1. 创建新的 Controller,从 session 中取下‘选占号码’,判断准确性后放入入参中对应位置,替换原数据。 2. 新的 Controller 路径需要加入免登录校验配置中 3. 前端`ajaxconfig.js`中的 share-preSubmit 的 key 对应的值更改为新的链接路径。 ### 支付接口 &emsp;&emsp;通过代码走查,并询问前后台开发陈庆、廖云辉、柴铭。<b>基本确认订单归集到支付,这部分流程中“不存在被篡改金额规避支付金额数量”的风险。</b> &emsp;&emsp;移网下单(零元商品),该场景中,前台传递 goodsFee 字段给后台,但是传递的是空字符串,后台判断为零元商品,此处既然是零元商品,则不可能篡改更低。 &emsp;&emsp;权益商品(有价商品),该场景中,前台不会直接传递支付金额给后台,只会传递用于展示的金额参数,真正支付时会通过接口查询对应商品的价格。 ### 后激活接口 &emsp;&emsp;订单只有在激活之后才能使用订购的手机卡。询问后台开发后确认,后激活一共调用四个接口,一个查询接口一个辅助接口,两个关键性接口。最后的活体认证,即后激活最后确认成功的接口,该接口存在被攻击的风险,后台没有做接口之间的关联。 &emsp;&emsp;经过分析发现,<b>该接口可能出现被篡改数据激活成功的现象。</b> &emsp;&emsp;我们不会直接暴露腾讯优图的接口给前台,而是做了封装,暴露自己的服务给前台。 &emsp;&emsp;我们自己封装的“OCR 接口”与“人脸核身”接口之间没有关联。“人脸核身”接口可以被直接调用,通过之后还需要进行人工审核,才能正式通过。 &emsp;&emsp;我们封装的“人脸核身”接口被直接调用,可以被篡改视频、证件信息。篡改的信息会被透传给优图,他们也可能用这些信息系统判断认为检测通过。我们此处没有做校验,直接信任优图返回的成功接口。虽然后面还有人工审核,但是系统还是有风险的。 &emsp;&emsp;原有的选号接口在`op_web_view_o2o\online-ui\js\ajaxconfig.js`中配置的路径为: ```js 'activation-faceBodyVerify':'/o2o/wsg/def/com_sitech_o2o_trade_service_ICardActivationServiceSvc_faceBodyVerifyForAct', ``` &emsp;&emsp;<b>改造点:</b> 1. 增加校验逻辑,在我们封装的“人脸核身”接口中,在调用优图人脸核身接口之前,判断传入的证件号码是否为下单证件号码,若不是不予进行下一步。
TypeScript
UTF-8
1,772
2.59375
3
[]
no_license
import { Injectable } from '@angular/core'; import { environment } from '../../../../environments/environment'; import { HttpClient } from '@angular/common/http'; import { Tecnico } from './tecnico'; import {Observable} from 'rxjs'; const API_URL = environment.apiURL; const tecnicos = '/tecnicos'; @Injectable({ providedIn: 'root' }) /** * The service provider for everything related to tecnicos */ export class TecnicoService { /** * Constructor of the service * @param http The HttpClient - This is necessary in order to perform requests */ constructor(private http: HttpClient) { } /** * Returns the Observable object containing the list of tecnicos retrieved from the API * @returns The list of tecnio in real time */ getTecnicos(): Observable<Tecnico[]> { return this.http.get<Tecnico[]>(API_URL + '/tecnicos'); } /** * Creates a new tecnico * @param tecnico The new tenico * @returns The tecnicos with its new id if it was created, false if it wasn't */ createTecnico(tecnico): Observable<Tecnico> { return this.http.post<Tecnico>(API_URL + tecnicos, tecnico); } /** * Updates a tecnico * @param Tecnico The updated tecnico * @returns The updated tecnico */ updateTecnico(tecnico): Observable<Tecnico> { return this.http.put<Tecnico>(API_URL + tecnicos + '/' + tecnico.id, tecnico); } /** * Returns the Observable object containing the list of editorials retrieved from the API * @returns The list of books in real time */ getTecnico(tecnicoId): Observable<Tecnico> { console.log("Paso por el modulo correcto"); return this.http.get<Tecnico>(API_URL + tecnicos + '/' + tecnicoId); } }
C
GB18030
3,899
3.84375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 10 #define NEW 1 #define USED 2 // ɾ () /*ҼҴ˵³ǰ һ˵³*/ //->car1->car2->car3->car4->car5 //for example if the car3 is the cheapeast new car ,we have to insert the newcar here //->car1->car2->car3->newcar->car4->car5 typedef struct cars { int price; int grade; char brand[N];//char *brand; struct cars *next; }list; //iteratively find the position list* FindC(list *h) { list *current; list *c; c=NULL;//c remember the cheapest car pointer for( current=h ; current!=NULL; current=current->next){ if(current->grade==NEW &&(c==NULL ||current->price < c->price )){ c = current; } } return c; } //recursively find the position list* rFindC(list* head){ list *minc; if(head==NULL){ return NULL; } minc = rFindC(head->next);/*Ҫע⣡&&ӦҪӸ*/ if(head->grade ==NEW &&(minc==NULL || minc->price>head->price)){ minc = head; } return minc; } void insert(list *h,list *pos,list *in)//iteration { list *temp; if(h==NULL) return; for(temp=h;temp!=NULL;temp=temp->next){ if(temp==pos){ in->next=temp->next; temp->next=in; return; } } return; } void insertR(list *h,list *pos,list *in){ list* current; if(h==NULL){ return; } if(h==pos){ in->next=h->next; h->next=in; return; } insertR(h->next,pos,in); return; } void printlist(list *h) // ȥlistβ ΪNULLٷؿʼӡ FIFO Ϊʱ һʱ listβ { //Ϳ԰˳ӡ insertlistǸposĺ Ǵӡposǰ if(h==NULL){ return; } printlist(h->next); printf("%d %d %s\n",h->price,h->grade,h->brand); } int main() { int p,g,i; char b[N]; list *current,*head,*insertin; head=NULL; printf("input the information of some cars with the price ,grade(2 used or 1 new) and the brand\n"); i=0; while(i<3){ scanf("%d%d%s",&p,&g,b); current=(list*)malloc(sizeof(list)); //if(current!=NULL)..... current->price=p; current->grade=g; strcpy(current->brand,b); current->next=head; head=current; i++; } /*Ҫcurrent=(list*)malloc(sizeof(List)); //ֻһָ Ҫ ֻǼס˵³λ //λõָ붼Ҫռ*/ current=FindC(head);//Find the position if(current!=NULL) printf("\nThe cheapest new car found by iteration is %s with the price %d\n",current->brand,current->price); else printf("No new car!\n"); current=rFindC(head); if(current!=NULL) printf("The cheapest new car found by recursion is %s with the price %d \n",current->brand,current->price); else printf("No new car!\n"); printf("Insert the new car information:\n"); //ﲻҪǼӸmalloc ΪҪ洢µcarȥlist insertin=(list*)malloc(sizeof(list)); if(insertin==NULL){ printf("Error Allocation!\n"); exit(-1); } scanf("%d%d%s",&insertin->price,&insertin->grade,insertin->brand); insert(head,current,insertin); //˵³ǰ printf("After inserting the newest car before the cheapest car by iteration,the list becomes:\n"); printlist(head); return 0; } /*OKAY*/
C
UTF-8
3,491
2.953125
3
[]
no_license
#include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> enum{ ONLINE, SEARCHING, REQUESTING, REQUESTED, PLAYING }; int main(){ char account[16]; char password[16]; printf("Account: "); fgets(account, 16, stdin); account[strlen(account) - 1] = '\0'; printf("Password: "); fgets(password, 16, stdin); password[strlen(password) - 1] = '\0'; int sockfd = socket(AF_INET, SOCK_STREAM, 0); int maxfd = sockfd; struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port = htons(8869); if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0){ fprintf(stderr, "connect() failed\n"); close(sockfd); return -1; } char line[1024]; /* test login */ sprintf(line, "LOGIN %s %s\n", account, password); write(sockfd, line, strlen(line)); char buf[2048]; // read buffer from server read(sockfd, buf, 2048); if(strcmp(buf, "FAIL") == 0){ fprintf(stderr, "login failed!\n"); close(sockfd); return -1; } fd_set fdset; FD_ZERO(&fdset); FD_SET(sockfd, &fdset); FD_SET(0, &fdset); char prompt[5][64] = { "(p)lay\t(l)ist users\t(q)uit> ", "Search user account> ", "Waiting for accept... (c)ancel> ", "Accept? (y)es\t(n)o> ", "(1~9)\t(p)rint> " }; int curPrompt = ONLINE; printf("%s", prompt[curPrompt]); fflush(stdout); while(1){ fd_set readset = fdset; struct timeval tv = {0, 0}; // let select() return immediately if(select(maxfd + 1, &readset, NULL, NULL, &tv) == -1){ fprintf(stderr, "select() failed\n"); break; } if(FD_ISSET(sockfd, &readset)){ // if get something from server int len = read(sockfd, buf, 2048); write(1, buf, len); if(curPrompt == SEARCHING){ if(strncmp(buf, "Request failed :(\n", 18) == 0) curPrompt = ONLINE; else curPrompt = REQUESTING; } else if(strncmp(buf, "\nInvitation from", 16) == 0) curPrompt = REQUESTED; else if(strncmp(buf, "\nRequest canceled...\n", 21) == 0) curPrompt = ONLINE; else if(strncmp(buf, "\nInvitation been rejected...\n", 29) == 0){ curPrompt = ONLINE; } else if(strncmp(buf, "Join", 4) == 0 || strncmp(buf, "\nJoin", 5) == 0) curPrompt = PLAYING; else if(curPrompt == PLAYING && (strstr(buf, "--- You") != NULL || strstr(buf, "--- Tie") != NULL)) curPrompt = ONLINE; else if(strstr(buf, " logout :(\n") != NULL) curPrompt = ONLINE; printf("%s", prompt[curPrompt]); // prompt again fflush(stdout); } if(FD_ISSET(0, &readset)){ // if get something from user input fgets(line, 1024, stdin); write(sockfd, line, strlen(line)); // write user input to server if(curPrompt == ONLINE && strncmp(line, "p\n", 2) == 0){ curPrompt = SEARCHING; printf("%s", prompt[curPrompt]); // prompt again fflush(stdout); } else if(curPrompt == ONLINE && strncmp(line, "q\n", 2) == 0){ printf("logout\n"); break; } else if(curPrompt == REQUESTING && strncmp(line, "c\n", 2) == 0){ printf("Request canceled\n"); curPrompt = ONLINE; printf("%s", prompt[curPrompt]); // prompt again fflush(stdout); } else if(curPrompt == REQUESTED && strncmp(line, "n\n", 2) == 0) curPrompt = ONLINE; } } close(sockfd); return 0; }
C++
UTF-8
2,042
4.28125
4
[]
no_license
/** CS-11 Asn 6, loopychars.cpp Purpose: Loops and characters. @author Your Name @version 1.0 Date Completed */ #include <iostream> using namespace std; int main() { int n; // the integer number char ch; // the single character cout << "** Loopy Characters!**\n\n"; cout << "Enter an integer between 1 and 20: "; cin >> n; cout << "Enter a single character: "; cin >> ch; cout << endl; // Repeating the char n times with a for-loop. cout << "#1. Printing " << ch << " " << n << " times:\n"; // Put your code here for (int i = 1; i <= n; i++) { cout << ch; } cout << endl << endl; // Printing starting with char and the following n ASCII chars. cout << "#2. Printing starting with " << ch << " and the following " << n - 1 << " ASCII characters:\n"; // Put your code here for (int i = 0; i < n; i++) { cout << (char)(ch + i); } cout << endl << endl; // Repeating the char n times with stars on odd indexes. cout << "#3. Printing " << ch << " character " << n << " times substituting '*' on odd indexes:\n"; // Put your code here for (int i = 0; i < n; i++) { if (i % 2 != 0) { cout << "*"; } else { cout << ch; } } cout << endl << endl; // Repeating the character n times with tick marks (+) every 5 chars cout << "#4. Printing " << ch << " character " << n << " times substituting (+) every fifth character:\n"; // Put your code here for (int i = 1; i <= n; i++) { if (i % 5 == 0) { cout << "+"; } else { cout << ch; } } cout << endl << endl; cout << "#5. Printing " << n << " lines of the previous loop:\n"; // Hint: put your for-loop from the previous challenge inside another // for-loop that has a different counting variable. // Put your code here for (int i = 1; i <= 10; i++) { for (int j = 1; j <= n; j++) { if (j % 5 == 0) { cout << "+"; } else { cout << ch; } } cout << endl; } return 0; }
C#
UTF-8
1,202
3.296875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Logs_Aggregator { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); var dict = new Dictionary<string, Dictionary<string, int>>(); for (int i = 0; i < n; i++) { var input = Console.ReadLine().Split(); var name = input[1]; var IP = input[0]; var duration = int.Parse(input[2]); if (!dict.ContainsKey(name)) { dict.Add(name, new Dictionary<string, int>()); } if (!dict[name].ContainsKey(IP)) { dict[name][IP] = duration; } else { dict[name][IP] += duration; } } foreach (var item in dict.OrderBy(x => x.Key)) { Console.WriteLine($"{item.Key}: {string.Join("",item.Value.Values.Sum())} [{string.Join(", ", item.Value.Keys.OrderBy(x => x))}]"); } } } }
Markdown
UTF-8
3,103
3.078125
3
[]
no_license
# Disqover **Disqover** is a social networking site where users can discover others who share similar music and movie tastes, as well as a portal to discovering new music and movies. ### Disclaimer This project is created by Jeremy Velo, Aaron Neme, and Marcos Benedicto solely for the use and purpose of completing the necessary project requirements for General Assembly's Software Engineering Immersive (remote). The Goal of this project is to create a full-stack CRUD application with a team of individuals. The project highlights skills and techniques learned during the course of the program. A list of technologies used can be found below. The current state of the application is for development purposes only and is currently not available for public use. If you wish to use the code and work with, please contact the the owner of this repository. Thank you! ### Live Site [Disqover](https://disqoverapplication.herokuapp.com/) ### User Stories * User can create their disqover which includes their profile name, an image, age, bio, favorite artists, and favorite movies. * Users can edit and delete their disqover. * Users can view and search through all disqovers. * Users can search for similar music and/or movies, based on their specified search criteria. * Users can like a similar result and view all of their likes. * Users can leave a comment on other users disqover pages. * Users can like a comment that was leaved by another user. ### Technologies Used #### Node.js Node.js is an event driven, lock-free javascript runtime. It handles multiple events concurrently, and fires callbacks upon each connection. #### Express Express is a web framework for Node.js. #### Angular Angular is a structural framework for developing dynamic single-page applications in HTML, CSS, and JavaScript #### Mongoose Mongoose is a schema based framework for modeling application data. It connects to MongoDb, and has built-in type-casting and validation. ### The API We used the [TastedDive](https://tastedive.com/read/api) API to get similar results for music and movies, based on the users search criteria. We limited results to 5, and se the type of query based on whether the user selected movies or music. While using the API, we came across a CORS (Cross-Origin Resource Sharing) issue. TasteDive was not sending the Access-Control-Allow-Origin header, so Heroku would not get resuklts from the API. As a workaround, for the purposes of this project, all users need to install the [Allow-Control-Allow-Origin](https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi) plugin, which allows you to make an http request to any site from any source. ### Unsolved Challenges * Not sending an error message if a user enters the wrong password. They can just reattempt to login with the correct password. * API CORS issue - we could improve the app by using a different API with similar functionality, but we didn't find any that were as good yet. * Comments can be posted, however, we haven't assigned a user to the comment or saved comments on each disqvoer page.
Markdown
UTF-8
2,131
3.046875
3
[]
no_license
# Requerimientos Composer PHP > 7.3 Node (nvm) > 7.1.1 # Instalacion Tener instalado los paquetes de [composer](https://getcomposer.org/) y [npm](https://www.npmjs.com/) para poder ejecutar los siguientes comandos (instalan todas las dependencias del proyecto): ```bash composer install && npm install ``` ## Configuracion En las variables de entorno debe configurar los datos para la base de datos correctamente. (DB_DATABASE, DB_USERNAME, DB_PASSWORD) Ejecutar los siguientes comandos: ```bash php artisan migrate php artisan passport:install ``` # Rutas disponibles Todas las rutas tienen el prefijo /api/ ## Rutas para register y login ```bash POST /auth/register (Registra un nuevo usuario) - Parametros: name, email y password POST /auth/login (Inicia la sesion) - Parametros: email y password - La key access_token es el token que deben enviar para la verificacion de sesion en el sistema. Header Authorization Bearer <token> POST /auth/logout (Cierra la sesion) ``` ## Rutas de productos ```bash GET /productos (Obtiene los productos) - Parametros: limit (opcional, elementos por pagina), order (opcional, columna para ordenar), order_type (opcional, desc o asc), q (opcional, busca coincidencias en nombre y descripcion) - Return: Array de productos GET /productos/{id} (Obtiene producto por id) - Parametros: id POST /productos (Crea un producto) - Parametros: nombre, descripcion, precio_compra, precio_venta - Return: El producto creado POST /productos/{id} (Edita un producto) - Parametros: nombre, descripcion, precio_compra, precio_venta, id - Return: El producto editado DELETE /productos/delete/{id} (Elimina un producto) - Parametros: id, - Return: delete = true ``` ## Rutas de pokemons ```bash GET /pokemons/save (Obtiene los pokemons de la api y los guarda en caso de que no exista) - Return: message = 'Save success' GET /pokemons (Obtiene los pokemons) - Parametros: limit (opcional, elementos por pagina) - Return: Array de pokemons POST /pokemons (Crea un pokemon) - Parametros: nombre, detalle_url - Return: El pokemon creado ```
JavaScript
UTF-8
1,041
2.96875
3
[ "MIT" ]
permissive
"use strict"; // Include our "db" const db = require("../db"); // Exports all the functions to perform on the db module.exports = { find, findOne }; /** * List products * @param {Object} options [Query options] * @return {Array} [Array of products] */ async function find(options = {}) { try { const statement = "SELECT * FROM product"; const values = []; const result = await db.query(statement, values); if (result.rows?.length) { return result.rows; } return []; } catch (err) { throw err; } } /** * Retrieve product by ID * @param {Object} id [Product ID] * @return {Object|null} [Product record] */ async function findOne(productId) { try { const statement = `SELECT * FROM product WHERE product_id = $1`; const values = [productId]; const result = await db.query(statement, values); if (result.rows?.length) { return result.rows[0] } return null; } catch(err) { throw err; } }
C
UTF-8
1,855
2.625
3
[ "MIT" ]
permissive
#include "window-private.h" #include "render-private.h" #include "render.h" void clear(Window* w) { glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); } void swapBuffers(Window* w) { SDL_GL_SwapWindow(w->window); } void drawRect( Window* window, float* mvp, float* color) { glUniformMatrix3fv(window->shaderMvp, 1, GL_FALSE, mvp); glUniform1i(window->shaderMode, 0); glUniform4fv(window->shaderColor, 1, color); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0); } void drawTexture( Window* window, float* mvp, Texture* t) { glUniformMatrix3fv(window->shaderMvp, 1, GL_FALSE, mvp); glUniform1i(window->shaderMode, 1); glBindTexture(GL_TEXTURE_2D, t->id); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0); } int textureWidth(Texture* t) { return t->width; } int textureHeight(Texture* t) { return t->height; } void deleteTexture(Texture* t) { glDeleteTextures(1, &t->id); free(t); } Texture* surfaceToTexture(SDL_Surface* surface) { Texture* t = malloc(sizeof(Texture)); glGenTextures(1, &(t->id)); glBindTexture(GL_TEXTURE_2D, t->id); GLenum mode = GL_RGB; if(surface->format->BytesPerPixel == 4) { mode = GL_RGBA; } glTexImage2D( GL_TEXTURE_2D, 0, mode, surface->w, surface->h, 0, mode, GL_UNSIGNED_BYTE, surface->pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); SDL_FreeSurface(surface); t->width = surface->w; t->height = surface->h; return t; }
Java
UTF-8
2,713
3.34375
3
[ "MIT" ]
permissive
import java.util.*; //The loader that validates and places abilities into the storage public class AbilityLoader extends Loader{ //Implementation of template method protected void parse_line(String[] line_split){ int ab_type; int ab_tgt_type; int ab_num_dice; int ab_num_face; int ab_base; String ab_name; Ability ab; Storage store = new Storage(); //Validate the lines and catch LoadingFileException thrown from invalid lines, then exit try{ line_checker(line_split, store); } catch(LoadingFileException lfe){ System.out.println("Error: " + lfe); } finally{ System.exit(1); } ab_type = line_split[0].equals("D") ? 2 : 3; ab_name = line_split[1]; ab_tgt_type = line_split[2].equals("S") ? 0 : 1; ab_base = Integer.parseInt(line_split[3]); ab_num_dice = Integer.parseInt(line_split[4]); ab_num_face = Integer.parseInt(line_split[5]); //create Ability and insert into storage ab = new Ability(ab_name, ab_base, ab_num_dice, ab_num_face, ab_type, ab_tgt_type); store.add_ab_to_storage(ab_name, ab); } //Validates the line given protected void line_checker(String[] line_split, Storage store) throws LoadingFileException{ if(line_split.length != 6) throw new LoadingFileException("Make sure all and just the information listed in the header is provided"); if(!line_split[0].equals("D") && !line_split[0].equals("H")) throw new LoadingFileException("Make sure the ability is either a Damage Type (D) or a Healing Type (H)"); if(line_split[1].equals("") || line_split[1].equals(" ")) throw new LoadingFileException("Make sure the ability name is not empty or simply whitespace"); if(!line_split[2].equals("M") && !line_split[2].equals("S")) throw new LoadingFileException("Make sure the ability is either a Single-Target Type (S) or a Multi-Target Type (M)"); //Checks to see if the items entered are actually numbers try{ Integer.parseInt(line_split[3]); Integer.parseInt(line_split[4]); Integer.parseInt(line_split[5]); if(store.check_ab_exist(line_split[1])) throw new LoadingFileException("Make sure the following ability is not a duplicate: " + line_split[1]); } catch(NumberFormatException nfe){ throw new LoadingFileException("Make sure the ability base damage, and number of dice and faces are represented as whole numbers"); } } }
Java
UTF-8
7,305
1.984375
2
[]
no_license
package com.ametis.cms.datamodel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="benefit_category") public class BenefitCategory implements java.io.Serializable{ private static final long serialVersionUID = 1L; //Fields /**data for the column : --------- benefit_category.benefit_category_id --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = auto_increment defaultValue = null decDigits = 0 radix = 10 nullable = 0 ordinal = 1 size = 11 type = 4 isPrimaryKey = true ========================================= */ private Integer benefitCategoryId; /**data for the column : --------- benefit_category.benefit_category_name --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 2 size = 255 type = 12 isPrimaryKey = false ========================================= */ private String benefitCategoryName; /**data for the column : --------- benefit_category.description --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 3 size = 65535 type = -1 isPrimaryKey = false ========================================= */ private String description; /**data for the column : --------- benefit_category.created_time --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 4 size = 19 type = 93 isPrimaryKey = false ========================================= */ private java.sql.Timestamp createdTime; /**data for the column : --------- benefit_category.created_by --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 5 size = 50 type = 12 isPrimaryKey = false ========================================= */ private String createdBy; /**data for the column : --------- benefit_category.deleted_time --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 6 size = 19 type = 93 isPrimaryKey = false ========================================= */ private java.sql.Timestamp deletedTime; /**data for the column : --------- benefit_category.deleted_by --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 7 size = 50 type = 12 isPrimaryKey = false ========================================= */ private String deletedBy; /**data for the column : --------- benefit_category.modified_time --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 8 size = 19 type = 93 isPrimaryKey = false ========================================= */ private java.sql.Timestamp modifiedTime; /**data for the column : --------- benefit_category.modified_by --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 9 size = 50 type = 12 isPrimaryKey = false ========================================= */ private String modifiedBy; /**data for the column : --------- benefit_category.deleted_status --------- schema = null tableName = benefit_category foreignCol = foreignTab = catalog = insurance remarks = defaultValue = null decDigits = 0 radix = 10 nullable = 1 ordinal = 10 size = 11 type = 4 isPrimaryKey = false ========================================= */ private Integer deletedStatus; // foreign affairs // -- foreign affairs end // -- exported key // -- exported key end // Fields End // PK GETTER SETTER @Id @Column(name="benefit_category_id") @GeneratedValue(strategy=GenerationType.IDENTITY) public java.lang.Integer getBenefitCategoryId(){ return benefitCategoryId; } public void setBenefitCategoryId(java.lang.Integer value){ benefitCategoryId = value; } // PK GETTER SETTER END @Column(name="benefit_category_name") public java.lang.String getBenefitCategoryName(){ return benefitCategoryName; } public void setBenefitCategoryName(java.lang.String value){ benefitCategoryName = value; } @Column(name="description") public java.lang.String getDescription(){ return description; } public void setDescription(java.lang.String value){ description = value; } @Column(name="created_time") public java.sql.Timestamp getCreatedTime(){ return createdTime; } public void setCreatedTime(java.sql.Timestamp value){ createdTime = value; } @Column(name="created_by") public java.lang.String getCreatedBy(){ return createdBy; } public void setCreatedBy(java.lang.String value){ createdBy = value; } @Column(name="deleted_time") public java.sql.Timestamp getDeletedTime(){ return deletedTime; } public void setDeletedTime(java.sql.Timestamp value){ deletedTime = value; } @Column(name="deleted_by") public java.lang.String getDeletedBy(){ return deletedBy; } public void setDeletedBy(java.lang.String value){ deletedBy = value; } @Column(name="modified_time") public java.sql.Timestamp getModifiedTime(){ return modifiedTime; } public void setModifiedTime(java.sql.Timestamp value){ modifiedTime = value; } @Column(name="modified_by") public java.lang.String getModifiedBy(){ return modifiedBy; } public void setModifiedBy(java.lang.String value){ modifiedBy = value; } @Column(name="deleted_status") public java.lang.Integer getDeletedStatus(){ return deletedStatus; } public void setDeletedStatus(java.lang.Integer value){ deletedStatus = value; } // foreign affairs // foreign affairs end // exported key //exported key end }
Java
UTF-8
7,466
2.25
2
[]
no_license
package com.cai310.lottery.entity.lottery; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import org.hibernate.type.EnumType; import com.cai310.entity.CreateMarkable; import com.cai310.entity.IdEntity; import com.cai310.entity.UpdateMarkable; import com.cai310.lottery.common.ChaseState; import com.cai310.lottery.common.Lottery; /** * 追号详细实体 * <p> * 倍数的存放规则 正整数表示该期追号 0表示该期不追号 负整数表示该期在追号过程中被停掉的 数字用这个"[]"包着的,表示该期已经做过相应处理. * 例:[1],[0],-2,2 这个串表示追号共追3期;第二期在发起时选择了不追;追号过程中又把第三期给停掉了;目前第一期 第二期 已经处理过,下一期 * 是追第三期 * </p> */ @Table(name = com.cai310.lottery.Constant.LOTTERY_TABLE_PREFIX + "CHASE_PLAN_DETAIL") @Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class ChasePlanDetail extends IdEntity implements CreateMarkable, UpdateMarkable { private static final long serialVersionUID = -4650685530026841524L; /** * 彩种类型 * * @see com.cai310.lottery.common.Lottery */ private Lottery lotteryType; /** 方案编号 */ private Long chasePlanId; /** 方案编号 */ private Long schemeId; private String schemeNum; private Integer allCount; private Integer nowCount; /** 追号状态 **/ private ChaseState state; private Boolean ifHitStop; /** 用户编号 */ private Long userId; /** 用户名 */ private String userName; /** 认购金额 */ private BigDecimal betCost; private Integer betCostPerMul; private String multiples; private Integer prePayId; private Boolean schemeWon; private String wonDesc; /** 创建时间 */ private Date createTime; /** 最后更新时间 */ private Date lastModifyTime; /** * @return the lotteryType */ @Type(type = "org.hibernate.type.EnumType", parameters = { @Parameter(name = EnumType.ENUM, value = "com.cai310.lottery.common.Lottery"), @Parameter(name = EnumType.TYPE, value = Lottery.SQL_TYPE) }) @Column(nullable = false, updatable = false) public Lottery getLotteryType() { return lotteryType; } /** * @param lotteryType the lotteryType to set */ public void setLotteryType(Lottery lotteryType) { this.lotteryType = lotteryType; } /** * @return the chasePlanId */ @Column(nullable = false) public Long getChasePlanId() { return chasePlanId; } /** * @param chasePlanId the chasePlanId to set */ public void setChasePlanId(Long chasePlanId) { this.chasePlanId = chasePlanId; } /** * @return the schemeId */ @Column(nullable = false) public Long getSchemeId() { return schemeId; } /** * @param schemeId the schemeId to set */ public void setSchemeId(Long schemeId) { this.schemeId = schemeId; } /** * @return the schemeNum */ @Column(nullable = false) public String getSchemeNum() { return schemeNum; } /** * @param schemeNum the schemeNum to set */ public void setSchemeNum(String schemeNum) { this.schemeNum = schemeNum; } /** * @return the allCount */ @Column(nullable = false) public Integer getAllCount() { return allCount; } /** * @param allCount the allCount to set */ public void setAllCount(Integer allCount) { this.allCount = allCount; } /** * @return the nowCount */ @Column(nullable = false) public Integer getNowCount() { return nowCount; } /** * @param nowCount the nowCount to set */ public void setNowCount(Integer nowCount) { this.nowCount = nowCount; } /** * @return the state */ @Type(type = "org.hibernate.type.EnumType", parameters = { @Parameter(name = EnumType.ENUM, value = "com.cai310.lottery.common.ChaseState"), @Parameter(name = EnumType.TYPE, value = ChaseState.SQL_TYPE) }) @Column(nullable = false) public ChaseState getState() { return state; } /** * @param state the state to set */ public void setState(ChaseState state) { this.state = state; } /** * @return the ifHitStop */ public Boolean getIfHitStop() { return ifHitStop; } /** * @param ifHitStop the ifHitStop to set */ public void setIfHitStop(Boolean ifHitStop) { this.ifHitStop = ifHitStop; } /** * @return the userId */ @Column(nullable = false, updatable = false) public Long getUserId() { return userId; } /** * @param userId the userId to set */ public void setUserId(Long userId) { this.userId = userId; } /** * @return the userName */ @Column(nullable = false, updatable = false) public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the betCost */ @Column(nullable = false, updatable = false) public BigDecimal getBetCost() { return betCost; } /** * @param betCost the betCost to set */ public void setBetCost(BigDecimal betCost) { this.betCost = betCost; } /** * @return the betCostPerMul */ @Column(nullable = false, updatable = false) public Integer getBetCostPerMul() { return betCostPerMul; } /** * @param betCostPerMul the betCostPerMul to set */ public void setBetCostPerMul(Integer betCostPerMul) { this.betCostPerMul = betCostPerMul; } /** * @return the multiples */ @Column(nullable = false, updatable = false) public String getMultiples() { return multiples; } /** * @param multiples the multiples to set */ public void setMultiples(String multiples) { this.multiples = multiples; } /** * @return the prePayId */ @Column(updatable = false) public Integer getPrePayId() { return prePayId; } /** * @param prePayId the prePayId to set */ public void setPrePayId(Integer prePayId) { this.prePayId = prePayId; } /** * @return the schemeWon */ @Column(nullable = true) public Boolean getSchemeWon() { return schemeWon; } /** * @param schemeWon the schemeWon to set */ public void setSchemeWon(Boolean schemeWon) { this.schemeWon = schemeWon; } /** * @return the wonDesc */ @Column(nullable = true) public String getWonDesc() { return wonDesc; } /** * @param wonDesc the wonDesc to set */ public void setWonDesc(String wonDesc) { this.wonDesc = wonDesc; } @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false, updatable = false) public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Temporal(TemporalType.TIMESTAMP) @Column(insertable = false) public Date getLastModifyTime() { return lastModifyTime; } public void setLastModifyTime(Date lastModifyTime) { this.lastModifyTime = lastModifyTime; } }
Python
UTF-8
225
3.484375
3
[]
no_license
# coding: utf-8 remaining_questions = True while remaining_questions: try: value_a, value_b = map(int, input().split(" ")) print(len(str(value_a + value_b))) except: remaining_questions = False
C#
UTF-8
1,580
2.84375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Xml; public class utils : MonoBehaviour { public static int LoadGameDataElementInt(string String, XmlDocument xmlDoc) { int ReturnInt = 0; try { ReturnInt = int.Parse(LoadGameDataElement(String, xmlDoc)); } catch (System.Exception) { Debug.Log("Can't parse " + String + " to int"); } return ReturnInt; } public static float LoadGameDataElementFloat(string String, XmlDocument xmlDoc) { float ReturnFloat = 0f; try { ReturnFloat = float.Parse(LoadGameDataElement(String, xmlDoc)); } catch (System.Exception) { Debug.Log("Can't parse " + String + " to float"); } return ReturnFloat; } public static string LoadGameDataElement(string String, XmlDocument xmlDoc) { string mystr = ""; try { mystr = xmlDoc.GetElementsByTagName(String)[0].InnerText; } catch (System.Exception) { Debug.Log("Could not load element: " + String); } return mystr; } public static Object FindInactiveObjects(string name, System.Type type) { Object[] objs = Resources.FindObjectsOfTypeAll(type); foreach (GameObject obj in objs) { if (obj.name == name) { return obj; } } return null; } }
Java
UTF-8
3,078
3.546875
4
[ "MIT" ]
permissive
package HighConcurrency.CinemaTicket; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; /** * 通过卖票程序读懂多线程--单线程程序 * * @author zhuhuix * @date 2020-05-12 */ public class TicketSingle { private static final String ROOM = "中央放映厅"; private static final int ROW = 10; private static final int COL = 20; private static final String FILM_NAME = "战狼3"; private static final BigDecimal PRICE = BigDecimal.valueOf(30); private static List<Ticket> tickets = new ArrayList<>(); private static final int CUSTOMER_COUNT = 250; private static List<Customer> customers = new ArrayList<>(CUSTOMER_COUNT); public static void main(String[] args) { //中央放映厅总共有250个座位,2020-05-12 18:00 放映战狼3,售票价格为30元 int ticketId=1; for (int row = 1; row <= ROW; row++) { for (int col = 1; col <= COL; col++) { Ticket ticket = new Ticket(ticketId++, ROOM, row, col, FILM_NAME, PRICE, LocalDateTime.of(2020, 5, 10, 18, 00)); tickets.add(ticket); } } Iterator<Ticket> iterator = tickets.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toString()); } //顾客到售票点进行随机买票 Collections.shuffle(tickets); int index = 1; while (tickets.size() > 0 && index <= CUSTOMER_COUNT) { Ticket ticket = tickets.get(tickets.size() - 1); Customer customer = new Customer(index); customer.buyTicket(ticket); customers.add(customer); tickets.remove(ticket); System.out.println(tickets.size() + "," + index); System.out.println(index + "号顾客买到了" + "第" + customer.getTicket().getRow() + "行,第" + customer.getTicket().getCol() + "列的票"); index++; try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("电影票出售情况如下:"); //剩余票的状态 System.out.println("剩余票数:" + tickets.size()); Iterator<Ticket> ticketIterator = tickets.iterator(); while (ticketIterator.hasNext()) { System.out.println(ticketIterator.next().toString()); } //顾客购买情况 System.out.println("买到票的人数:" + customers.size()); Iterator<Customer> customerIterator = customers.iterator(); while (customerIterator.hasNext()) { System.out.println(customerIterator.next().toString()); } System.out.println("未买到票的人数:" +(CUSTOMER_COUNT- customers.size())); } }
Markdown
UTF-8
3,961
3.15625
3
[]
no_license
# Mentoring Workflow ## Navigating the Mentor Dashboard To get started with mentoring, log into your Exercism account and click on “Mentor Dashboard” in the main menu. ![menu](https://user-images.githubusercontent.com/5421823/42646491-efd24170-85f8-11e8-9284-87929f379f39.png) You will see your Mentor Dashboard which lists solutions that have been submitted by learners and are ready for mentor feedback. Here you can filter the solutions by Status, Track (language) or Exercise. We recommend using the “Exercise” filter so you can give feedback on multiple solutions while a particular exercise is fresh in your mind. The right hand side shows how many solutions you’ve mentored so far so you can see how your hard work is helping out the community. ![dashboard](https://user-images.githubusercontent.com/5421823/42657796-40b30242-861b-11e8-9f98-112665eb4e99.png) Click on one of the solutions to start giving feedback. This will take you to the mentor feedback interface where you can write and submit your feedback. ## Giving Mentor Feedback You can click the “Instructions” tab to remind yourself of what the exercise is about. These are the same instructions given to the learner. ![instructions](https://user-images.githubusercontent.com/5421823/42658359-fb059e42-861c-11e8-8b91-cb8e1e83f38e.png) The "Test Suite" tab shows the tests that the user has made pass in order to solve the exercise. ![testsuite](https://user-images.githubusercontent.com/5421823/42658351-f5cd79f4-861c-11e8-9190-9a41fa863f69.png) The “Solution” tab is the code the learner has submitted for feedback. The iteration number is shown in the top right corner. ![solution](https://user-images.githubusercontent.com/5421823/42658374-086b9c94-861d-11e8-8b11-22767a49049d.png) We recommend taking a look at the learners previous iterations so you can see their progress and give helpful feedback which considers their journey. ![iterations_censored](https://user-images.githubusercontent.com/5421823/42646801-e43aaa04-85f9-11e8-8915-9cb519db47bc.jpg) Under "Mentor Discussion" you will see two tabs where you can write your feedback and preview what you've written. ![write](https://user-images.githubusercontent.com/5421823/42646496-f0e26ed2-85f8-11e8-97f2-55b96760053e.png) ![preview](https://user-images.githubusercontent.com/5421823/42646493-f03d4286-85f8-11e8-89bf-8a303f0e897b.png) Once you're happy with the feedback you've written, click "Comment". If you're not sure what feedback to give, paste a link to the solution (e.g. https://exercism.io/mentor/solutions/...) on the relevant language channel on Slack and brainstorm some ideas with other mentors. ![comment](https://user-images.githubusercontent.com/5421823/42646488-ef0c7aa8-85f8-11e8-840e-bdfdf748bcae.png) If you come across a solution you don't want to give feedback to, you can click the "I'll pass, thanks" button and you won't ever see the solution in your Mentor Dashboard queue again. _Note: this button is labeled as `Leave conversation` for solutions you are actively mentoring. Clicking this button will return the solution to the mentor queue for another mentor to assume._ ![pass](https://user-images.githubusercontent.com/5421823/42646492-f0077750-85f8-11e8-8621-e77da7ec018f.png) When you think a learner has learnt enough from the exercise (i.e. they've touched upon a couple of concepts and made good progress with each iteration based on the feedback given), you can allow the learner to progress by clicking on the "Approve and comment" button (appears when you type). You will need to add a comment before hitting this button, for example "It looks like you've learnt enough from this exercise, great work." ![approve](https://user-images.githubusercontent.com/5421823/42646486-eecd1a3e-85f8-11e8-92de-d7d34298a3f6.png) Once you have submitted your comment you can go back to the Mentor Dashboard and choose another solution to give feedback on.
Java
UTF-8
4,291
2.3125
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package cn.gdeiassistant.Service.Phone; import cn.gdeiassistant.Exception.VerificationException.SendSMSException; import cn.gdeiassistant.Exception.VerificationException.VerificationCodeInvalidException; import cn.gdeiassistant.Pojo.Entity.Phone; import cn.gdeiassistant.Pojo.Entity.User; import cn.gdeiassistant.Repository.Redis.VerificationCode.VerificationCodeDao; import cn.gdeiassistant.Repository.SQL.Mysql.Mapper.GdeiAssistant.Phone.PhoneMapper; import cn.gdeiassistant.Service.UserLogin.UserCertificateService; import cn.gdeiassistant.Service.OpenAPI.VerificationCode.VerificationCodeService; import com.aliyuncs.exceptions.ClientException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PhoneService { @Autowired private PhoneMapper phoneMapper; @Autowired private VerificationCodeDao verificationCodeDao; @Autowired private UserCertificateService userCertificateService; @Autowired private VerificationCodeService verificationCodeService; /** * 查询用户绑定的手机号信息 * * @param sessionId * @return */ public Phone QueryUserPhone(String sessionId) { User user = userCertificateService.GetUserLoginCertificate(sessionId); Phone phone = phoneMapper.selectPhone(user.getUsername()); if (phone != null) { //隐藏用户绑定的手机号 StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < phone.getPhone().length(); i++) { if (i < 3) { stringBuilder.append(phone.getPhone().charAt(i)); } else { stringBuilder.append('*'); } } phone.setPhone(stringBuilder.toString()); } return phone; } /** * 获取手机验证码 * * @param code * @param phone */ public void GetPhoneVerificationCode(int code, String phone) throws ClientException, SendSMSException { //生成随机数 int randomCode = (int) ((Math.random() * 9 + 1) * 100000); //写入Redis缓存记录 verificationCodeDao.SavePhoneVerificationCode(code, phone, randomCode); if (code == 86) { //国内手机号 verificationCodeService.SendChinaPhoneVerificationCodeSMS(randomCode, phone); } else { //国际/港澳台手机号 verificationCodeService.SendGlobalPhoneVerificationCodeSMS(randomCode, code, phone); } } /** * 检测手机验证码正确性 * * @param code * @param phone * @param randomCode */ public void CheckVerificationCode(int code, String phone, int randomCode) throws VerificationCodeInvalidException { Integer verificationCode = verificationCodeDao.QueryPhoneVerificationCode(code, phone); if (verificationCode != null) { if (verificationCode.equals(randomCode)) { //移除手机验证码记录 verificationCodeDao.DeletePhoneVerificationCode(code, phone); //校验通过 return; } } throw new VerificationCodeInvalidException(); } /** * 添加或更新绑定的手机号信息 * * @param sessionId * @param code * @param phone */ public void AttachUserPhone(String sessionId, Integer code, String phone) { User user = userCertificateService.GetUserLoginCertificate(sessionId); Phone data = phoneMapper.selectPhone(user.getUsername()); if (data != null) { data.setCode(code); data.setPhone(phone); phoneMapper.updatePhone(data); } else { phoneMapper.insertPhone(user.getUsername(), code, phone); } } /** * 解除绑定用户的手机号信息 * * @param sessionId */ public void UnAttachUserPhone(String sessionId) { User user = userCertificateService.GetUserLoginCertificate(sessionId); Phone data = phoneMapper.selectPhone(user.getUsername()); if (data != null) { phoneMapper.deletePhone(user.getUsername()); } } }
Java
UTF-8
2,573
3.671875
4
[]
no_license
public class NQueens { private int num; private int[][] board; // public static void main(String[] args) throws Exception { //my main function to print to console // NQueens nq = new NQueens(8); // // if(nq.placeNQueens()) { // nq.printToConsole(); // } // // } NQueens(int n) { num = n; board = new int[num][num]; } // throws Exception if board size less than 1 boolean placeNQueens() throws Exception{ if (num < 1) { throw new Exception("Number must be greater than 0"); } if (placeQ(0)) { return true; } else { return false; } } boolean placeQ(int row) { if (row == num) { return true; } for (int col = 0; col < num; col++) { if (!isAttacked(row, col)) { //if it is not attacked then places 1 in space, representing queen board[row][col] = 1; if (placeQ(row + 1)) { //recursive call return true; } board[row][col] = 0;//backtracking by making spots that didn't work 0 } } return false; } boolean isAttacked(int r, int c) { int i, j; for (i = 0; i < num; i++) {//checks all rows in the same column for an attacking queen :1 if (i!=r&&board[i][c] == 1) return true; } for (i = r, j = c; i >= 0 && j >= 0; i--, j--) {//checks upper left diagonal if (i!=r&&j!=c&&board[i][j] == 1) return true; } for (i = r, j = c; i >= 0 && j < num; i--, j++) {//checks upper right diagonal if (i!=r&&j!=c&&board[i][j] == 1) return true; } for (i = r, j = c; i < num && j >= 0; i++, j--) {//checks lower left diagonal if (i!=r&&j!=c&&board[i][j] == 1) return true; } for (i = r, j = c; i < num && j < num; i++, j++) {//checks upper right diagonal if (i!=r&&j!=c&&board[i][j] == 1) return true; } return false; } void printToConsole() { for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { if (board[i][j] == 1) { System.out.print("Q "); } else { System.out.print("_ "); } } System.out.println(); } System.out.println(""); } }
Shell
UTF-8
229
2.640625
3
[]
no_license
run=$1 histo=$2 verbose=$3 sed -e "s/HISTO/$histo/g" FFT_3.c > FFT_3.tmp1 sed -e "s/RUN/$run/g" FFT_3.tmp1 > FFT.c rm FFT_3.tmp1 if [ "$verbose" == "v" ]; then root -l FFT.c else root -b -q -l FFT.c fi
Python
UTF-8
2,236
4.84375
5
[]
no_license
# print("hello world") # print("I am Kasey") # print("Nice to meet you") #functions, how to write a function # def introduction(): # print("hello world") # print("I am Kasey") # print("Nice to meet you") # introduction() # def introduction_specialized(name): # print("hello world") # print("I am", name) # print("Nice to meet you") # introduction_specialized("Justin") # introduction_specialized("Miley") # introduction_specialized("Kim") # introduction_specialized("Taylor") # introduction_specialized("Kanye") # introduction_specialized("Selena") # what happens if I call the function before I define it? # functions with parameters, input/output # ex, function that sees if the number is greater than 100 # Assignment 1: write a function that takes in user input, and tests if the number is divisible by 10 # user_input = int(input("Type in a number: ")) # def divisible_by_ten(number): # if number % 10 == 0: # print("Your number: ", number, "is divisible by ten") # else: # print("Your number: ", number, "is not divisible by ten") # divisible_by_ten(user_input) print("Welcome to my calculator! You will be able to add, subtract, divide, or multiply two numbers") print("Type 'a' to add, 's' to subtract, 'd' to divide, or 'm' to multiply: ") operation = input() def add(number_one, number_two): total = number_one + number_two return(total) def subtract(number_one, number_two): total = number_one - number_two return(total) def multiply(number_one, number_two): total = number_one * number_two return(total) def divide(number_one, number_two): total = number_one / number_two return(total) first_number = int(input("Type in one number: ")) second_number = int(input("Type in a second number: ")) if (operation == "a"): print(add(first_number,second_number)) elif (operation == "s"): print(subtract(first_number,second_number)) elif (operation == "m"): print(multiply(first_number,second_number)) elif (operation == "d"): print(divide(first_number,second_number)) else: print("bleh") # functions with more than one parameter # Assignment 2: create a calculator: add, subract, divide, multiply functions, user input two #s # function that adds two numbers # obamicon
SQL
UTF-8
1,728
2.8125
3
[]
no_license
PROMPT ===================================================================================== PROMPT *** Run *** ========== Scripts /Sql/BARS/View/V_OBPC_FILEP.sql =========*** Run *** = PROMPT ===================================================================================== PROMPT *** Create view V_OBPC_FILEP *** CREATE OR REPLACE FORCE VIEW BARS.V_OBPC_FILEP ("FILE_NAME", "FILE_DATE", "DOC_REF", "DOC_TT", "DOC_KV", "DOC_SUM", "DOC_NLSA", "DOC_NAMA", "DOC_NLSB", "DOC_NAMB") AS SELECT p.f_n, p.f_d, o.REF, o.tt, o.kv, o.s/100, DECODE (o.dk, 0, o.nlsb, o.nlsa), DECODE (o.dk, 0, o.nam_b, o.nam_a), DECODE (o.dk, 0, o.nlsa, o.nlsb), DECODE (o.dk, 0, o.nam_a, o.nam_b) FROM oper o, pkk_que p WHERE o.REF = p.REF AND p.sos > 0 ORDER BY p.f_n ; PROMPT *** Create grants V_OBPC_FILEP *** grant SELECT on V_OBPC_FILEP to BARSREADER_ROLE; grant DELETE,FLASHBACK,INSERT,SELECT,UPDATE on V_OBPC_FILEP to BARS_ACCESS_DEFROLE; grant DELETE,INSERT,SELECT,UPDATE on V_OBPC_FILEP to OBPC; grant SELECT on V_OBPC_FILEP to UPLD; grant DELETE,FLASHBACK,INSERT,SELECT,UPDATE on V_OBPC_FILEP to WR_ALL_RIGHTS; PROMPT ===================================================================================== PROMPT *** End *** ========== Scripts /Sql/BARS/View/V_OBPC_FILEP.sql =========*** End *** = PROMPT =====================================================================================
C
UTF-8
6,258
2.953125
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <gmp.h> #include "rsa.h" #include "prf.h" /* NOTE: a random composite surviving 10 Miller-Rabin tests is extremely * unlikely. See Pomerance et al.: * http://www.amps.org/mcom/1993-61-203/S0025-5718-1993-1189518-9/ * */ #define ISPRIME(x) mpz_probab_prime_p(x,10) #define NEWZ(x) mpz_t x; mpz_init(x) #define BYTES2Z(x,buf,len) mpz_import(x,len,-1,1,0,0,buf) #define Z2BYTES(buf,len,x) mpz_export(buf,&len,-1,1,0,0,x) /* utility function for read/write mpz_t with streams: */ int zToFile(FILE* f, mpz_t x) { size_t i,len = mpz_size(x)*sizeof(mp_limb_t); unsigned char* buf = malloc(len); /* force little endian-ness: */ for (i = 0; i < 8; i++) { unsigned char b = (len >> 8*i) % 256; fwrite(&b,1,1,f); } Z2BYTES(buf,len,x); fwrite(buf,1,len,f); /* kill copy in buffer, in case this was sensitive: */ memset(buf,0,len); free(buf); return 0; } int zFromFile(FILE* f, mpz_t x) { size_t i,len=0; /* force little endian-ness: */ for (i = 0; i < 8; i++) { unsigned char b; /* XXX error check this; return meaningful value. */ fread(&b,1,1,f); len += (b << 8*i); } unsigned char* buf = malloc(len); fread(buf,1,len,f); BYTES2Z(x,buf,len); /* kill copy in buffer, in case this was sensitive: */ memset(buf,0,len); free(buf); return 0; } int rsa_keyGen(size_t keyBits, RSA_KEY* K) { rsa_initKey(K); /* TODO: write this. Use the prf to get random byte strings of * the right length, and then test for primality (see the ISPRIME * macro above). Once you've found the primes, set up the other * pieces of the key ({en,de}crypting exponents, and n=pq). */ //~~~~~~~~~~~~~~~~~~~~~~~~Initializing arrays~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// unsigned char* p; // define space for prime p unsigned char* q; // define space for prime q p = malloc(keyBits/8); //memory allocation q = malloc(keyBits/8); //memory allocation randBytes(p,keyBits/8);// generate random bytes randBytes(q,keyBits/8);// generate random bytes //~~~~~~~~~~~~~~~~~~~~~~~~Finding the first prime~~~~~~~~~~~~~~~~~~~~~~~~~~~// NEWZ(P);// define gmp variable BYTES2Z(P,p,keyBits/8); //asigned the randombyte to interger into P NEWZ(nextP); mpz_nextprime(nextP,P); //finding a prime for nextP if(ISPRIME(nextP)==1) //makes sure it is prime { mpz_set(K->p,nextP); //sets P into the initKey } else printf("P IS NOT PRIME"); //~~~~~~~~~~~~~~~~~~~~~~~~Finding the second prime~~~~~~~~~~~~~~~~~~~~~~~~~// NEWZ(Q); BYTES2Z(Q,q,keyBits/8); //asigned the randombyte to interger into Q NEWZ(nextQ); mpz_nextprime(nextQ,Q); //finding a prime for nextQ if(ISPRIME(nextQ)==1) //make sure it is prime { mpz_set(K->q,nextQ); //sets Q into the initKey } else printf("Q IS NOT PRIME"); //~~~~~~~~~~~~~~~~~~~~~~~~Computing N~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// NEWZ(N); mpz_mul(N,K->p,K->q); //computes N. mpz_set(K->n,N); //sets N to the initKey //~~~~~~~~~~~~~~~~~~~~~~~~Computing phi~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// NEWZ(phi); NEWZ(p1); NEWZ(q1); //creating variables for phi mpz_sub_ui(p1,K->p,1); //getting P-1 mpz_sub_ui(q1,K->q,1); //getting Q-1 mpz_mul(phi,p1,q1); //~~~~~~~~~~~~~~~~~~~~~~~~Computing E~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// NEWZ(temp); // Test - What if we have key size = keyBits/8? unsigned char* buffer = malloc(keyBits/8); //create memory do{ randBytes(buffer,keyBits/8); // create randomBytes BYTES2Z(K->e,buffer, keyBits/8); // convert and put into e mpz_gcd(temp,K->e,phi); //compute gcd(e,phi) } while(mpz_cmp_ui(temp,1)); // check that the gcd(e,phi) = 1, yes = 0 //~~~~~~~~~~~~~~~~~~~~~~~Computind D~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// NEWZ(t); //temporary asignment mpz_invert(t,K->e,phi); mpz_set(K->d,t); //~~~~~~~~~~~~~~~~~~~~~~~Clearing memory~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// mpz_clear(P); mpz_clear(nextP); mpz_clear(Q); mpz_clear(nextQ); mpz_clear(N); mpz_clear(phi); mpz_clear(temp); mpz_clear(p1); mpz_clear(q1); mpz_clear(t); return 0; } size_t rsa_encrypt(unsigned char* outBuf, unsigned char* inBuf, size_t len, RSA_KEY* K) { /* TODO: write this. Use BYTES2Z to get integers, and then * Z2BYTES to write the output buffer. */ NEWZ(mg); NEWZ(ct); BYTES2Z(mg,inBuf,len); mpz_powm(ct,mg,K->e,K->n); // ct = message^e mod n Z2BYTES(outBuf,len,ct); mpz_clear(mg); mpz_clear(ct); return len; /* TODO: return should be # bytes written */ } size_t rsa_decrypt(unsigned char* outBuf, unsigned char* inBuf, size_t len, RSA_KEY* K) { /* TODO: write this. See remarks above. */ NEWZ(ct); NEWZ(pt); BYTES2Z(ct,inBuf,len); mpz_powm(pt,ct,K->d,K->n); // mg = c^d mod n Z2BYTES(outBuf,len,pt); mpz_clear(ct); mpz_clear(pt); return len; } size_t rsa_numBytesN(RSA_KEY* K) { return mpz_size(K->n) * sizeof(mp_limb_t); } int rsa_initKey(RSA_KEY* K) { mpz_init(K->d); mpz_set_ui(K->d,0); mpz_init(K->e); mpz_set_ui(K->e,0); mpz_init(K->p); mpz_set_ui(K->p,0); mpz_init(K->q); mpz_set_ui(K->q,0); mpz_init(K->n); mpz_set_ui(K->n,0); return 0; } int rsa_writePublic(FILE* f, RSA_KEY* K) { /* only write n,e */ zToFile(f,K->n); zToFile(f,K->e); return 0; } int rsa_writePrivate(FILE* f, RSA_KEY* K) { zToFile(f,K->n); zToFile(f,K->e); zToFile(f,K->p); zToFile(f,K->q); zToFile(f,K->d); return 0; } int rsa_readPublic(FILE* f, RSA_KEY* K) { rsa_initKey(K); /* will set all unused members to 0 */ zFromFile(f,K->n); zFromFile(f,K->e); return 0; } int rsa_readPrivate(FILE* f, RSA_KEY* K) { rsa_initKey(K); zFromFile(f,K->n); zFromFile(f,K->e); zFromFile(f,K->p); zFromFile(f,K->q); zFromFile(f,K->d); return 0; } int rsa_shredKey(RSA_KEY* K) { /* clear memory for key. */ mpz_t* L[5] = {&K->d,&K->e,&K->n,&K->p,&K->q}; size_t i; for (i = 0; i < 5; i++) { size_t nLimbs = mpz_size(*L[i]); if (nLimbs) { memset(mpz_limbs_write(*L[i],nLimbs),0,nLimbs*sizeof(mp_limb_t)); mpz_clear(*L[i]); } } /* NOTE: a quick look at the gmp source reveals that the return of * mpz_limbs_write is only different than the existing limbs when * the number requested is larger than the allocation (which is * of course larger than mpz_size(X)) */ return 0; }
TypeScript
UTF-8
462
2.640625
3
[]
no_license
export interface UserLocation { lat: number; long: number; } export interface WeatherProps { dt: number; name: string; main: { temp: number; feels_like: number; humidity: number; }; sys: { sunrise: number; sunset: number; }; weather: [ { description: string; } ]; } export interface HourlyProps { dt: number; temp: number; weather: [ { icon: string; description: string; } ]; }
Java
UTF-8
599
2.46875
2
[]
no_license
package fr.marseille.formation.initiation.Entity; public class CompteCourant { public int nbComptesCourants = 3000; public int numero; public String intitule; public double solde; public double montantDecouvertAutorise; public CompteCourant(String numero, String intitule, double solde, double montantDecouvertAutorise) { this(); } public CompteCourant() { super(); this.nbComptesCourants++; } public int getNbComptesCourants() { return nbComptesCourants; } public void setNbComptesCourants(int nbComptesCourants) { this.nbComptesCourants = nbComptesCourants; } }
Markdown
UTF-8
3,380
2.78125
3
[ "MIT" ]
permissive
--- layout: post title: 与子说|关于钱的那些事儿(2) tags: [育儿育己] category: Education --- # <center> 一 <img width="398" alt="截屏2020-12-02 下午12 12 04" src="https://user-images.githubusercontent.com/23351109/100827635-2841b400-3498-11eb-99fa-f08318ab084f.png"> (四岁) 蹬蹬蹬——跑下琴行前的台阶,老母亲追随小童的身影,望了望远处的路灯。夏日的晚风,轻轻摩挲着裙裾,小童背上的小书包快活得摆来摆去。 「妈妈!」小童回头,「快点!快点!我回去还要找小姨讲故事。」 最近,外婆、外公和小姨一起来家里了。简陋的二居室,一下子热闹起来。老母亲感慨,早上上个厕所都要排队了。 小童转转眼珠子,「妈妈,那你为什么不买个大房子?」 「我没有那么多钱!」老母亲内心直翻白眼。 「那姥姥、姥爷在老家就有大房子。」小童毫不客气地指出来。 「老家房子便宜,再说,姥姥和姥爷工作那么久了,我才工作多久?」老母亲忍不住辩白,「等我到姥姥和姥爷那个年纪,兴许能买的起大房子吧……」 小童笑了,「那你买呀。」 老母亲也笑了,「那你等吧!」😂😂😂😂😂 # <center> 二 ![buyingcar](https://user-images.githubusercontent.com/23351109/100827559-f892ac00-3497-11eb-957d-a0b48d7233a2.jpeg) (四岁) 路边并排站着的两棵香樟树,树冠顶上渐渐发黄——秋色已深,吐着寒气的冬天正在路上。白色、黑色、棕色的小汽车一辆接着一辆,在送上学的人流中穿行。老母亲拉着小童的手,避让着车流穿行,自言自语道,「看来还是要有辆车,有车的话,还是有希望实现接送你上学的。」 小童扬起小脸,「你会开吗?」 「我当然会啊!」老母亲不乐意了,「就是胆子太小,不敢开。」 「可是你买不起车啊。」 「谁说的?」老母亲心想,保时捷的话,那确实买不起。 「我爸爸说的。」小童露出天真无邪的眼神,「他现在开的那辆很贵的,你买不起。」 「很贵是多少钱?」老母亲在心里哼哼,这是哪儿来的蜜汁自信? 「嗯,三百块。」 「那给我来一打。」老母亲强忍住笑。 文盲小童懵比,「一打啥意思?」 # <center> 三 ![savingMondy](https://user-images.githubusercontent.com/23351109/100827761-7656b780-3498-11eb-83fd-9ddc1e7a1688.jpeg) (六岁) 清晨的阳光,爬上阳台上的防盗窗,将忽闪着的亮光送进客厅。老母亲捏着手里的面包,怔怔地望着那光发呆。 刺溜——小童喝了一大口粥,抬头看见老母亲的眼神,也扭头看看,忍不住发问,「妈妈,你为什么总看阳台?」 老母亲瞥了他一眼,「想事情。」 「什么事情?」小童追问。 想起来昨天刚回答过「大人的事情」,老母亲改口说,「怎么赚钱的事。」 小童眨巴眨巴眼睛,「我存钱罐的钱够多了。」 老母亲忍不住想笑,「那够一天的伙食费吗?」 「不知道……」小童垂下了眼睛。 「还有,以后的钱够用吗?」老母亲愤愤不平,「我想的不光是现在,还有将来好不好?!」 # changelog 1. 2020-12-01 从(1)拆分 2. 2020-12-02 配图
JavaScript
UTF-8
1,036
2.765625
3
[]
no_license
var engine, world; var paper; var left, bottom, right; var ground; const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; function preload() { binImg = loadImage("images/dustbingreen.png"); } function setup() { createCanvas(1500, 700); bin = createSprite(1080,520) bin.addImage(binImg) bin.scale = 0.75 engine = Engine.create(); world = engine.world; //Create the Bodies Here. paper = new Paper(200,648,50); ground = new Ground(width/2, 650, width, 15); left = new Dustbin(1000,540,20,200); bottom = new Dustbin(1080,630,180,20); right = new Dustbin(1160,540,20,200); Engine.run(engine); } function draw() { rectMode(CENTER); background(255); Engine.update(engine); paper.display(); left.display(); bottom.display(); right.display(); ground.display(); keyPressed(); drawSprites(); function keyPressed() { if(keyCode === UP_ARROW) { Matter.Body.applyForce(paper.body, paper.body.position, {x:75, y:-75 }) } } }
Java
UTF-8
1,357
3.296875
3
[]
no_license
package pack1; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Demo { public static void main(String[] args) { List<Integer> l1 = new LinkedList<>(); l1.add(0); l1.add(5); l1.add(null); l1.add(25); System.out.println(l1); l1.set(1, 3); System.out.println(l1.size()); Integer i = 0; l1.remove(i);//remove element; l1.remove(2);//remove index System.out.println(l1); System.out.println(l1.contains(null)); l1.remove(null); System.out.println(l1); l1.add(4); l1.add(5); Collections.reverse(l1); System.out.println(l1); Collections.shuffle(l1); System.out.println(l1); Collections.sort(l1,Collections.reverseOrder()); System.out.println(l1); Collections.sort(l1); System.out.println(Collections.binarySearch(l1, 4)); List <Integer> list1 = new LinkedList<>(Arrays.asList(12,33,55,11,11,29,30)); System.out.println("list1"+list1); List<Integer> list2 = new ArrayList<>(Arrays.asList(12,33,55,11));//arraylist System.out.println("list2"+list2); list1.retainAll(list2); System.out.println(list1); list1.removeAll(list2); System.out.println("list1"+list1); list1.addAll(list2);//union all System.out.println("union"+list1); } }
C++
UTF-8
3,881
2.625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*----------------------------------------------------------- * 2c - Cross Platform 3D Application Framework *----------------------------------------------------------- * Copyright © 2010 - 2011 France Telecom * This software is distributed under the Apache 2.0 license, * see the "license.txt" file for more details. *----------------------------------------------------------- * File Name : SceneSample1.cpp *----------------------------------------------------------- */ #include "CCDefines.h" #include "Samples.h" SceneSample1::SceneSample1() { // Create a new camera camera = new CCCameraAppUI(); gEngine->addCamera( camera ); // Set it up to take up the entire screen camera->setupViewport( 0.0f, 0.0f, 1.0f, 1.0f ); } // Called after our constructor is called void SceneSample1::setup() { // Set our virtual camera width to be 320 // This means that the width of the view will be 320 camera->setCameraWidth( 320.0f ); // Background { CCTile3DButton *tile = new CCTile3DButton( this ); // Pass in this scene tile->setupTextured( 640.0f, // Specify the width of the tile "Resources/background.png" ); // Texture to load // Add the tile to our list of touchable tiles, to allow for user interaction addTile( tile ); } // Create a tile CCTile3DButton *tileHelloWorld = NULL; { CCTile3DButton *tile = new CCTile3DButton( this ); tile->setupText( "Hello World", // Tell it to say 'Hello World' 64.0f, // Specify the height of the text true ); // Request the text to be centered // Set the colour of the text model to be black tile->setTextColour( CCColour( 1.0f ), true ); addTile( tile ); tileHelloWorld = tile; } // Create a tile with an image { CCTile3DButton *tile = new CCTile3DButton( this ); tile->setupTextured( 128.0f, "Resources/f7u12_derp.png" ); addTile( tile ); // Position it underneath our hello world tile tile->positionTileBelow( tileHelloWorld ); } // refresh the scene range refreshCameraView(); } void SceneSample1::destruct() { super::destruct(); } // CCSceneBase const bool SceneSample1::updateScene(const CCTime &gameTime) { // Called once a frame and internally updates all objects managed by this scene return super::updateScene( gameTime ); } const bool SceneSample1::updateCamera(const CCTime &gameTime) { // Called once a frame and internally updates the camera view return super::updateCamera( gameTime ); } void SceneSample1::renderOctreeObject(CCSceneObject *object, const CCCameraBase *inCamera, const int pass, const bool alpha) { // Called on render by our octree which handles drawing objects only in view if( camera == inCamera ) { object->renderObject( camera, alpha ); } } const bool SceneSample1::touchPressed(const CCScreenTouches &touch) { // Callback for when a touch is first detected return super::touchPressed( touch ); } const bool SceneSample1::touchMoving(const CCScreenTouches &touch, const CCPoint &touchDelta) { // Callback for when a touch is moving return super::touchMoving( touch, touchDelta ); } const bool SceneSample1::touchReleased(const CCScreenTouches &touch, const CCTouchAction touchAction) { // Callback for when a touch is released return super::touchReleased( touch, touchAction ); } const bool SceneSample1::touchCameraRotating(const float x, const float y) { // Callback for when two touches are panning the camera to rotate return super::touchCameraRotating( x, y ); }
Java
UTF-8
7,370
2.171875
2
[]
no_license
package org.adscale.bragi.player.modules.pandora; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.BufferedInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URI; import java.net.URISyntaxException; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class XmlRpc { private static final Logger logger = Logger.getLogger(XmlRpc.class.getName()); private HttpPost postMethod; private CloseableHttpClient client; public XmlRpc(String url){ XmlRpcClientConfigImpl xmlRpcClientConfig = new XmlRpcClientConfigImpl(); try { URI uri = new URI(url); } catch (URISyntaxException e) { e.printStackTrace(); } client = HttpClients.createDefault(); postMethod = new HttpPost(); } /* * This method is extracted from the parent class with slight modifications for sending a request with a * predetermined body content. */ public Object callWithBody(String url, String body) throws Exception { // logger.info("url = " + url); // logger.info("body = " + body); postMethod.setURI(URI.create(url)); try { // set POST body HttpEntity entity = new StringEntity(body); postMethod.setEntity(entity); // Log.d(Tag.LOG, "ros HTTP POST"); // execute HTTP POST request HttpResponse response = client.execute(postMethod); // Log.d(Tag.LOG, "ros HTTP POSTed"); // check status code int statusCode = response.getStatusLine().getStatusCode(); // Log.d(Tag.LOG, "ros status code:" + statusCode); if (statusCode != HttpStatus.SC_OK) { throw new Exception("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK); } // parse response stuff // // setup pull parser XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); entity = response.getEntity(); Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent()), "UTF-8"); // for testing purposes only // reader = new StringReader("<?xml // version='1.0'?><methodResponse><params><param><value>\n\n\n</value></param></params></methodResponse>"); pullParser.setInput(reader); // lets start pulling... pullParser.nextTag(); pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE); pullParser.nextTag(); // either Tag.PARAMS (<params>) or Tag.FAULT (<fault>) String tag = pullParser.getName(); if (tag.equals(Tag.PARAMS)) { // normal response pullParser.nextTag(); // Tag.PARAM (<param>) pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM); pullParser.nextTag(); // Tag.VALUE (<value>) // no parser.require() here since its called in XMLRPCSerializer.deserialize() below // deserialize result // Object obj = iXMLRPCSerializer.deserialize(pullParser); entity.consumeContent(); return null; } else if (tag.equals(Tag.FAULT)) { // fault response pullParser.nextTag(); // Tag.VALUE (<value>) // no parser.require() here since its called in XMLRPCSerializer.deserialize() below // deserialize fault result // Map<String, Object> map = (Map<String, Object>) iXMLRPCSerializer.deserialize(pullParser); // String faultString = (String) map.get(Tag.FAULT_STRING); // int faultCode = (Integer) map.get(Tag.FAULT_CODE); entity.consumeContent(); throw new RuntimeException("fault occured"); } else { entity.consumeContent(); throw new Exception("Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>"); } } catch (Exception e) { logger.log(Level.WARNING, "Exception caught.", e); ; // wrap any other Exception(s) around XMLRPCException throw new Exception(e); } } public void addHeader(String header, String value) { postMethod.addHeader(header, value); } public static String value(String v) { return "<value><string>" + v.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") + "</string></value>"; } public static String value(boolean v) { return v ? "<value><boolean>1</boolean></value>" : "<value><boolean>0</boolean></value>"; } public static String value(int v) { return "<value><int>" + String.valueOf(v) + "</int></value>"; } public static String value(Number v) { return value(v.intValue()); } public static String value(String[] list) { StringBuilder result = new StringBuilder("<value><array><data>"); for (int i = 0; i < list.length; i++) { result.append(value(list[i])); } return result.append("</data></array></value>").toString(); } public static String value(int[] list) { StringBuilder result = new StringBuilder("<value><array><data>"); for (int i = 0; i < list.length; i++) { result.append(value(list[i])); } return result.append("</data></array></value>").toString(); } public static String value(AbstractCollection<?> list) { StringBuilder result = new StringBuilder("<value><array><data>"); Iterator<?> listIter = list.iterator(); while (listIter.hasNext()) { result.append(valueGuess(listIter.next())); } return result.append("</data></array></value>").toString(); } public static String valueGuess(Object v) { if (v instanceof Number) return value((Number) v); else if (v instanceof Boolean) return value((Boolean) v); else if (v instanceof String) return value((String) v); else if (v instanceof AbstractCollection<?>) return value((AbstractCollection<?>) v); else return value(v.toString()); } public static String makeCall(String method, ArrayList<Object> args) { StringBuilder argsStr = new StringBuilder(); Iterator<Object> argsIter = args.iterator(); while (argsIter.hasNext()) { Object item = argsIter.next(); argsStr.append("<param>").append(valueGuess(item)).append("</param>"); } return "<?xml version=\"1.0\"?><methodCall><methodName>" + method + "</methodName><params>" + argsStr.toString() + "</params></methodCall>"; } }
PHP
UTF-8
1,132
2.984375
3
[]
no_license
<?php namespace application\handbook; use common\libraries\Configuration; use common\libraries\Utilities; /** * This is a skeleton for a data manager for the Handbook Application. * Data managers must extend this class and implement its abstract methods. * * * @author Nathalie Blocry */ class HandbookDataManager { /** * Instance of this class for the singleton pattern. */ private static $instance; /** * Constructor. */ public function __construct() { $this->initialize(); } /** * Uses a singleton pattern and a factory pattern to return the data * manager. The configuration determines which data manager class is to * be instantiated. * @return HandbookDataManager The data manager. */ static function get_instance() { if (!isset (self :: $instance)) { $type = Configuration :: get_instance()->get_parameter('general', 'data_manager'); require_once dirname(__FILE__).'/data_manager/'.Utilities :: camelcase_to_underscores($type).'.class.php'; $class = __NAMESPACE__ . '\\' . $type.'HandbookDataManager'; self :: $instance = new $class (); } return self :: $instance; } } ?>
C#
UTF-8
1,924
2.75
3
[]
no_license
using System.Collections.Generic; public class GeometryStage : IGeometryStage { private IVertexShade vertexShade; private IPrimitiveAssemble primitiveAssemble; private IClip clip; private ICull cull; public GeometryStage() { vertexShade = new VertexShade(); primitiveAssemble = new PrimitiveAssemble(); clip = new Clip(); cull = new Cull(); } public ITriangle[] Process(IDrawCall drawCall, ICamera camera) { // vertex shade vertexShade.MVP = camera.P * camera.V * drawCall.M; vertexShade.N = (camera.V * drawCall.M).Inverse().Transpose().Minor(3, 3); Vector4[] vertices = drawCall.vertices; Vector3[] normals = drawCall.normals; IVertexOutputData[] outputs = new VertexOutputData[vertices.Length]; for (int vIndex = 0; vIndex < vertices.Length; vIndex++) { IVertexInputData input = new VertexInputData(); input.vertex = vertices[vIndex]; input.normal = normals[vIndex]; outputs[vIndex] = vertexShade.Process(input); } // primitive assembly ITriangle[] primitives = primitiveAssemble.Process(outputs, drawCall.indices); Queue<ITriangle> triangles = new Queue<ITriangle>(); for (int pIndex = 0; pIndex < primitives.Length; pIndex++) { // back-face culling ITriangle t = cull.Process(primitives[pIndex]); if (t != null) { // clipping ITriangle[] ts = clip.Process(t); if (ts != null) { foreach (ITriangle each in ts) { triangles.Enqueue(each); } } } } return triangles.ToArray(); } }