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
TypeScript
UTF-8
3,206
2.90625
3
[]
no_license
import axios from 'axios'; export default class Api { static create() { return new Api(); } // static requestErrorHandler(error) { // throw Api.parseError(error); // } // static parseError(error) { // let message = error.message; // let stack = error.stack; // let errorData = error; // if (error.response) { // errorData = error.response; // if (error.response.status === 401) { // message = "Access denied."; // // } else if (error.response.status === 404) { // // message = "Not found." // } else if (error.response.data) { // message = // error.response.data.message || // `Unknown error ${error.response.status}`; // stack = error.response.data.stacktrace; // } // } else if (error.request) { // errorData = error.request; // message = "No response from server"; // } // return { ...errorData, message, stack }; // } static post(url: string, data: unknown, params = {}, customHeaders = {}) { return Api.create().post(url, data, params, customHeaders); } static get(url: string, data = {}, customHeaders = {}) { return Api.create().get(url, data, customHeaders); } static put(url: string, data: unknown, customHeaders = {}) { return Api.create().put(url, data, customHeaders); } static delete( url: string, data: unknown, params: unknown, customHeaders = {}, ) { return Api.create().delete(url, data, params, customHeaders); } post(url: string, data: unknown, params: unknown, customHeaders: unknown) { const requestConfig = { method: 'POST', url: `${url}`, data, params, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; return this.request(requestConfig, customHeaders); } get(url: string, data: unknown, customHeaders: unknown) { const requestConfig = { method: 'GET', url: `${url}`, params: data, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; return this.request(requestConfig, customHeaders); } put(url: string, data: unknown, customHeaders: unknown) { const requestConfig = { method: 'PUT', url: `${url}`, data, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; return this.request(requestConfig, customHeaders); } delete(url: string, data: unknown, params: unknown, customHeaders: unknown) { const requestConfig = { method: 'DELETE', url: `${url}`, data, params, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; return this.request(requestConfig, customHeaders); } request(requestConfig: any, customHeaders: unknown) { Object.assign(requestConfig.headers, customHeaders); const req = axios(requestConfig); // this is weird to be here, it outputs warning for unhandled Promises // even is they are handled // req.catch(Api.requestErrorHandler); return req; } }
Java
UTF-8
2,666
1.9375
2
[]
no_license
/* * @Copyright: 江西金磊科技发展有限公司 All rights reserved.Notice 仅限于授权后使用,禁止非授权传阅以及私自用于商业目的。 */ package com.jeecms.front.controller; import com.jeecms.auth.service.CoreUserService; import com.jeecms.common.base.controller.BaseController; import com.jeecms.common.exception.GlobalException; import com.jeecms.common.exception.SystemExceptionEnum; import com.jeecms.common.response.ResponseInfo; import com.jeecms.content.service.ContentFrontService; import com.jeecms.member.domain.UserCollection; import com.jeecms.member.service.UserCollectionService; import com.jeecms.util.SystemContextUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.concurrent.locks.ReentrantLock; /** * 我的收藏 * * @author xiaohui * @version 1.0 * @date 2019-04-24 */ @RequestMapping("/usercollections") @RestController public class UserCollectionController extends BaseController<UserCollection, Integer> { @Autowired ContentFrontService contentFrontService; @Autowired private CoreUserService userService; @Autowired private UserCollectionService service; private final transient ReentrantLock lock = new ReentrantLock(); @PostConstruct public void init() { String[] queryParams = new String[]{}; super.setQueryParams(queryParams); } /** * 添加 * * @param userCollection 收藏对象 * @param request HttpServletRequest * @param result BindingResult * @return ResponseInfo * @throws GlobalException 异常 */ @PostMapping public ResponseInfo save(@RequestBody @Valid UserCollection userCollection, HttpServletRequest request, BindingResult result) throws GlobalException { validateId(userCollection.getContentId()); Integer userId = SystemContextUtils.getUserId(request); if (userId != null) { lock.lock(); try { service.save(userCollection, userId); return new ResponseInfo(true); } finally { lock.unlock(); } } else { return new ResponseInfo(SystemExceptionEnum.ACCOUNT_NOT_LOGIN.getCode(), SystemExceptionEnum.ACCOUNT_NOT_LOGIN.getDefaultMessage()); } } }
Python
UTF-8
2,197
2.875
3
[]
no_license
import gym import tensorflow as tf import random import numpy as np random.seed() env = gym.make('CartPole-v1') all_times= [] for i_episode in range(20000): observation = env.reset() observations = [] actions = [] for t in range(100): # env.render() action = random.randint(0,1) observations.append(observation) observation, reward, done, info = env.step(action) t_action = [0,0] t_action[action] = 1 actions.append(t_action) if done: print("Episode finished after {} timesteps".format(t+1)) if t+1 > 80: all_times.append((t+1,observations,actions)) break all_times.sort(key = lambda x : x[0],reverse = True) training_data = all_times print len(training_data) tf_input = tf.placeholder(dtype = tf.float32,shape = [None,4]) tf_actual = tf.placeholder(dtype = tf.float32,shape = [None,2]) l1 = tf.layers.dense(inputs = tf_input, units = 5 , activation = tf.tanh) l2 = tf.layers.dense(inputs = l1, units = 3 , activation = tf.tanh) output = tf.layers.dense(inputs = l2, units = 2 , activation = tf.tanh) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=tf_actual)) optimizer = tf.train.AdamOptimizer(learning_rate=0.01) train_op = optimizer.minimize(loss_op) init = tf.global_variables_initializer() print "Start Learning" with tf.Session() as sess: sess.run(init) for step in range(100): for data in training_data: sess.run(train_op,feed_dict = { tf_input : data[1] , tf_actual : data[2]}) print "Done Learning" for i_episode in range(20): observation = env.reset() t=0 while True: t+=1 env.render() observation, reward, done, info = env.step(action) action = np.argmax(sess.run(output,feed_dict={tf_input:[observation]})) observations.append(observation) actions.append(action) if done: print("Episode finished after {} timesteps".format(t+1)) all_times.append((t+1,observations,actions)) raw_input("Enter") break
Markdown
UTF-8
6,659
2.8125
3
[]
no_license
<script type="text/javascript"> var head = document.getElementsByTagName('head')[0]; cssURL = '/public/liao.css'; linkTag = document.createElement('link'); linkTag.href = cssURL; linkTag.setAttribute('type','text/css'); linkTag.setAttribute('rel','stylesheet'); head.appendChild(linkTag); </script> <style type="text/css"> section{text-align: center; font-size: 24px;} section p{text-align: center; font-size: 20px;} </style> ### 考城隍 在繁复的《聊斋志异》的不同版本中,尽管收录的小说在数目、卷次、篇目排列的次序上有所差异,但有一点,那就是——《考城隍》无论是在蒲松龄的手稿本,还是在后人不同的编辑阶段,一直都是放在第一篇的位置上。更值得注意的是:在《聊斋志异》的评论史上,评论者都非常重视它在《聊斋志异》中开篇的地位:何垠说:“一部书如许,托始于《考城隍》,赏善罚淫之旨见矣。”但明伦说:“一部大文章,以此开宗明义。” #### 【原文】 <section> <h3>小窗幽记</h3> <h6>陈继儒(明)</h6> 多读两句书,少说一句话,读得两行书,说得几句话。 士人不当以世事分读书,当以读书通世事。&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;天下之事,利害常相半;有全利,而无小害者,惟书。 佳思忽来,书能下酒;侠情一往,云可赠人。 好读书非求身后之名,但异见异闻,心之所愿。是以孜孜搜讨,欲罢不能,岂为声名劳七尺也。 富贵功名、荣枯得丧,人间惊见白头;风花雪月、诗酒琴书,世外喜逢青眼。 &nbsp;&nbsp;人生有书可读,有暇得读,有资能读,又涵养之,如不识字人,是谓善读书者。 &nbsp;&nbsp;享世间清福,未有过于此也。 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;竹外窥莺,树外窥水,峰外窥云,难道我有意无意; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;鸟来窥人,月来窥酒,雪来窥书,却看他有情无情。 云水中载酒,松篁里煎茶,岂必銮坡侍宴;山林下著书,花鸟间得句,何须凤沼挥毫。 亲兄弟折箸,壁合翻作瓜分;士大夫爱钱,书香化为铜臭。 眼里无点灰尘,方可读书千卷;胸中没些渣滓,才能处世一番。 闭门阅佛书,开门接佳客,出门寻山水,此人生三乐。 竹风一阵,飘飏茶灶疏烟;梅月半湾,掩映书窗残雪。 以看世人青白眼,转而看书,则圣贤之真见识;以议论人雌黄口,转而论史,则左狐之真是非。 书引藤为架,人将薜作衣。 闭门即是深山,读书随处净土。 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;看书只要理路通透,不可拘泥旧说,更不可附会新说。 &nbsp;&nbsp;&nbsp;&nbsp;简傲不可谓高,谄谀不可谓谦,刻薄不可谓严明,阘茸不可谓宽大。 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;皮囊速坏,神识常存,杀万命以养皮囊,罪卒归于神识。 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;佛性无边,经书有限,穷万卷以求佛性,得不属于经书。 &nbsp;&nbsp;&nbsp;&nbsp;书屋前,列曲槛栽花,凿方池浸月,引活水养鱼; 小窗下,焚清香读书,设净几鼓琴,卷疏帘看鹤,登高楼饮酒。&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 贫不能享客,而好结客;老不能徇世,而好维世;穷不能买书,而好读奇书。 读书到快目处,起一切沉沦之色;说话到洞心处,破一切暧昧之私。 读一篇轩快之书,宛见山青水白;听几句伶俐之语,如看岳立川行。 读书如竹外溪流,洒然而往;咏诗如苹末风起,勃焉而扬。 有书癖而无剪裁,徒号书厨;惟名饮而少酝藉,终非名饮。 茅齐独坐茶频煮,七碗后,气爽神清;竹榻斜眠书漫抛,一枕余,心闲梦稳。 &nbsp;&nbsp;灯下玩花,帘内看月,雨后观景,醉里题诗,梦中闻书声,皆有别趣。 闲中觅伴书为上,身外无求睡最安。 虚堂留烛,抄书尚存老眼;有客到门,挥麈但说青山。 半轮新月数竿竹,千卷藏书一盏茶。 </section> > 据《聊斋志异》手稿本 > 1-6 书相关 #### 【白话】 <aside> 宋先生上马后,便告别而去。他回到家中,就好像是从一场大梦中突然醒来一样。其时他已经死去三天了。宋母听见棺材里有呻吟声,急忙把他扶出来,过了半天,宋先生才能说出话来。他派人去长山打听,果然有个姓张的秀才,在那天死去了。过了九年,宋母真的去世了。宋先生将母亲安葬完毕,自己洗浴料理后进了屋子里就死了。宋先生的岳父家住在城中的西门里,这天忽然看见宋先生骑着装饰华美的骏马,身后跟随着许多车马仆役,进了内堂,向他拜别离去。全家人都很惊疑,不知道宋先生已经成了神。宋先生的岳父派人跑到宋先生的家乡去打听消息,才知道宋先生已经死了。 宋先生曾写有自己的小传,可惜经过战乱没有保存下来,这里记述的只是个大略情况。 </aside> > 【注释】 <b>讳</b>:旧时对帝王尊长不直称其名,叫避讳;因称其名为“讳”。 <b>邑廪生</b>:本县廪膳生员。明洪武二年(1369)始,凡考取入学的生员(习称“秀才”),每人月廪食米六斗,以补助其生活。后生员名额增多,成化年间(1465—1487)改为定额内者食廪,称廪膳生员,省称廪生;增额者为增广生员和附学生员,省称增生和附生。清沿明制,廪生月供廪饩银四两,增生岁、科两试一等前列者,可依次升廪生,称补廪。参见《明史•选举志》、《清史稿•选举志》。 <b>白颠马</b>:白额马。颠,额端。《诗•秦风•车邻》:“有车邻邻,有马白颠。”朱熹注:“白颠,额有白毛,今谓之的颡。” <b>文宗</b>:文章宗匠。原指众人所宗仰的文章大家。《后汉书•崔駰传》:“崔为文宗,世禅雕龙。”清代用以誉称省级学官提督学政(简称“提学”、“学政”)。临:指案临。清制,各省学政在三年任期内依次到本省各地考试生员,称案临。考试的名目有“岁考”、“科考”两种。 <b>力疾</b>:强支病体。此据青柯亭刻本,原作“力病”。
Java
UTF-8
1,329
1.960938
2
[]
no_license
package ru.georgeee.bachelor.yarn.dict.ya; import com.google.gson.annotations.SerializedName; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public class LookupResponse { private List<Def> def; @Getter @Setter public static class Def { private String text; private String pos; @SerializedName("ts") private String transcription; @SerializedName("tr") private List<Translation> translations; } @Getter @Setter public static class Translation { private String text; private String pos; @SerializedName("anm") private String animality; @SerializedName("gen") private String gender; @SerializedName("syn") private List<Word> synonyms; @SerializedName("mean") private List<Word> meanings; @SerializedName("ex") private List<TWord> examples; } @Getter @Setter public static class TWord { private String text; private String pos; private String gen; @SerializedName("tr") private List<Word> translations; } @Getter @Setter public static class Word { private String text; private String pos; private String gen; } }
Markdown
UTF-8
1,700
2.515625
3
[]
no_license
--- title: Serverless Cheatsheet category: cloud tags: python dotNET --- # Serverless Cheatsheet [Serverless home page](https://serverless.com/) ## Install ```bash npm install -g serverless ``` ## Examples [Serverless Examples](https://github.com/serverless/examples) [Serverless Starter](https://github.com/serverless/serverless-starter) [Python example](https://serverlesscode.com/post/python-on-serverless-intro/) [C# example](https://serverless.com/blog/serverless-v1.4.0/) ## Cheatsheet * Create a Service: ```bash # NodeJS serverless create -p [SERVICE NAME] -t aws-nodejs # C# serverless create --path serverlessCSharp --template aws-csharp ``` * Install a Service This is a convenience method to install a pre-made Serverless Service locally by downloading the Github repo and unzipping it. ```bash serverless install -u [GITHUB URL OF SERVICE] ``` * Deploy All Use this when you have made changes to your Functions, Events or Resources in ``serverless.yml`` or you simply want to deploy all changes within your Service at the same time. ```bash serverless deploy -s [STAGE NAME] -r [REGION NAME] -v ``` * Deploy Function Use this to quickly overwrite your AWS Lambda code on AWS, allowing you to develop faster. ```bash serverless deploy function -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME] ``` * Invoke Function Invokes an AWS Lambda Function on AWS and returns logs. ```bash serverless invoke -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME] -l ``` * Streaming Logs Open up a separate tab in your console and stream all logs for a specific Function using this command. ```bash serverless logs -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME] ```
Python
UTF-8
6,349
2.578125
3
[]
no_license
# llia.keytab.registry # 2016.03.18 from __future__ import print_function import json from llia.generic import is_keytable, dump from llia.keytab.keytable import KeyTable import llia.keytab.eqtemp as eqt import llia.keytab.just as jst class KeyTableRegistry(dict): """KeyTableRegistry provides dictionary of KeyTable objects.""" @staticmethod def extension(): """Returns String, the filename extension.""" return "ktr" def __init__(self): """Constructs new KeyTableRegistry.""" dict.__init__(self) self.clear() self._filename = "" def __setitem__(self, key, ktab): """ Add KeyTable to registry. Raises TypeError if ktab is not a KeyTable object. """ if is_keytable(ktab): key = key or ktab.name dict.__setitem__(self, key, ktab) else: msg = "Can not add %s to KeyTableRegistry" msg = msg % type(ktab) raise TypeError(msg) def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return eqt.EQ12 def clear(self): """Remove all but default key tables.""" dict.clear(self) self[None] = eqt.EQ12 self[None] = eqt.EQ19 self[None] = eqt.EQ24 self[None] = eqt.EQ31 self[None] = jst.JUST_C1 self[None] = jst.S44_39_12 self[None] = jst.BLUE_JI self[None] = jst.PRE_ARCHYTAS self[None] = jst.BICYCLE self[None] = jst.BREEDBALL3 self[None] = jst.AL_FARABI self[None] = jst.CANTON self[None] = jst.CARLOS_HARM self[None] = jst.CENTAUR self[None] = jst.COLLAPSAR self[None] = jst.MAJOR_CLUS self[None] = jst.MINOR_CLUS self[None] = jst.THIRTEENDENE self[None] = jst.UNIMAJOR def reset(self): """reset is an alias for clear.""" self.clear() def eqtemp(self, npo, name=None, refkey=(69, 440.0), octave=2.0): """ Adds equal-tempered key table to registry. ARGS: name - String, table name. If name is "" or None a default name based on note-count is used. npo - int, notes per octave. refkey - optional tuple, reference keynumber and frequency used to tune the table. Default (69, 440.0) octave - optional float, sets ratio used for an octave. Default 2.0 RETURNS: KeyTable """ ktab = eqt.EqTempKeyTable(name, npo, refkey, 0, octave) self[ktab.name] = ktab return ktab def just(self, template, name, refkey=(69, 440.0), transpose=-9, npo=12): """ Adds key table with just intonation to registry. ARGS: template - Nested list of scale degree ratios ((n0, d0),(n1,d1),(n2, d2)...) where each ni, di define the ratio of step i as the fraction ni/di. name - String refkey - optional tuple, (keynumber, frequency), default (69, 440.0) transpose - optional int, transposition amount. See JustKeyTable docs. Default -9 npo - optional int, notes per octave. npo is informational only, the actual number of notes per octave is determined by template. Default 12 RETURNS: KeyTable """ ktab = jst.JustKeyTable(name, template, refkey, npo, transpose) self[name] = ktab return ktab def __str__(self): return "KeyTableRegistry" def dump(self, tab=0, verbosity=0): pad=' '*4*tab pad2 = pad+' '*4 acc = "%s%s\n" % (pad, str(self)) for k in sorted(list(self.keys())): acc += "%s%s\n" % (pad2, k) return acc def serialize(self): """Convert to serialized form.""" acc = ["llia.KeyTableRegistry"] header = {} header["count"] = len(self) acc.append(header) data = {} for kname in sorted(list(self.keys())): ktab = self[kname] data[kname] = ktab.serialize() acc.append(data) return acc def default_filename(self): return self._filename def save(self, filename): """Save self to file.""" with open(filename, 'w') as output: s = self.serialize() json.dump(s, output, indent=4) self._filename = filename @staticmethod def deserialize(obj): """Construct KeyTableRegistry from serialized data.""" cls = obj[0] if cls == "llia.KeyTableRegistry": header, data = obj[1], obj[2] other = KeyTableRegistry() for name, ktab in data.items(): other[name] = KeyTable.deserialize(ktab) return other else: msg = "Can not deserialize %s as KeyTableRegistry" msg = msg % obj raise TypeError(msg) def load(self, filename): """ Update self from external file. All non-default tables are removed and replaced by those in the file. """ with open(filename, 'r') as input: obj = json.load(input) if type(obj) == list: other = self.deserialize(obj) self.clear() self._filename = filename for name, ktab in other.items(): self[name] = ktab @dump.when_type(KeyTableRegistry) def _dump(ktr): print(ktr.dump()) # ---------------------------------------------------------------------- # Test def test(): print("KeyTableRegistry test") r = KeyTableRegistry() dump(r) r.eqtemp(56) template = ((1, 1),(13, 12),(14,12),(15,12), (16,12),(17,12),(18,12),(19,12), (20,12),(21,21),(22, 12),(23,12)) r.just(template, "zzz") dump(r) # filename = "/home/sj/t/keytab" # r.save(filename) # r2 = KeyTableRegistry() # dump(r2) # r2.load(filename) # dump(r2)
Python
UTF-8
725
4.03125
4
[]
no_license
mystring = "My Name is Pratik" print(mystring) # Slicing print(mystring[0:]) # Starting to the End print(mystring[:5]) #Starting upto specified index print(mystring[0:6]) #From specified starting index to specified ending index print(mystring[::-1]) # Printitng the reversea a string print(mystring[0:-1:2]) # printing staring to the end with gap of 2 #String Function print(mystring.count('a')) print(mystring.capitalize()) print(mystring.lower()) print(mystring.upper()) print(mystring.replace("Pratik", "PrKapadnis")) mystring = mystring.replace("Pratik", "PrKapadnis") print(mystring) print(mystring.find("PrKapadnis")) mystring = "".join(mystring) print(mystring) print(f"The length of string is {len(mystring)}")
JavaScript
UTF-8
2,071
3.03125
3
[]
no_license
import React, {useState, useEffect} from 'react'; import logo from './logo.svg'; import './velha.css'; import './jogoVelha' function jogoVelha() { const empytBoard = Array(9).fill(""); const [bord, setBord] = useState(empytBoard); const [currentPlayer, setCurrentPlayer] = useState("O"); const [winner, setWinner] = useState(); const handleCellClick =(index)=>{ if(winner) { return null; } if(bord[index] !== "") { return null; } setBord(board.map((item, Itemindex)=> Itemindex === index ? currentPlayer : item)); setCurrentPlayer(currentPlayer === "X"? "O": "X"); } const checkWinner = ()=>{ const possibleWaysTowin =[ [bord[0], bord[1], bord[2]], [bord[3], bord[4], bord[5]], [bord[6], bord[7], bord[8]], [bord[0], bord[3], bord[6]], [bord[1], bord[4], bord[7]], [bord[2], bord[5], bord[8]], [bord[0], bord[4], bord[8]], [bord[2], bord[4], bord[6]], ]; possibleWaysTowin.forEach(cells =>{ if(cells.every(cell => cell === "O"))setWinner("O venceu"); if(cells.every(cell => cell === "X"))setWinner("X venceu"); }); checkDraw(); } const checkDraw=()=>{ if(board.every(item => item !== "")){ setWinner("E"); } } useEffect(checkWinner, [bord]); const resetGame=()=>{ setCurrentPlayer("O"); setBord(empytBoard); setWinner(null); } return ( <main> <h1>Jogo da velha</h1> <div className={`board ${winner ? "game-over" : ""}`}> {board.map((Item, index) => ( <div key={index} className={`cell ${item}`} onClick={()=>handleCellClick(index)}> {item} </div> ))} </div> {winner & <footer> {winner === "E" ? <h2 className="winner-message"> <span className={winner}> empatou! </span> </h2> : <h2 className="winner-message"> <span className={winner}> {winner} </span> venceu! </h2> } <button onClick={resetGame}>Reiniciar jogo</button> </footer> } </main> ); } export default jogoVelha;
Markdown
UTF-8
1,680
2.875
3
[]
no_license
# Fotobox A "photobooth"-application for Raspberry Pi and dslr. It lets you capture images and sort them in albums from a web interface. I use a Raspberry Pi 3, but it will probably work on other versions as well. The site interface is in norwegian. ## Beware This program will mercilessly delete all files on your dslr, so make sure you don´t have important files on your cameras sd-card before starting. ## Displaying images on monitor from RP To make this program able to display images on the monitor, you will need to install feh and run this command prior to startup: ``` export DISPLAY=:0 ``` This will set your monitor as the output display so feh can do its thing. It´s fully possible (and functional) to run the project without a monitor connected to the RP thoug. ## Requirements This project uses Gphoto2 for connecting to the dslr. I recommend downloading it with https://github.com/gonzalo/gphoto2-updater. The rest can be intalled with `pip install -r requirements.txt` I haven´t really tried setting up the project from scratch yet (It´s on the todo-list), so there might be something missing here. ## Customizing the site You can customize how the site behaves with the Settings-model from the admin-site. Here you can change wether you want a countdown to be displayed on monitor before capture, and wether you want full-sized or down-sized images to be shown on the page after an image is captured. You can also set contact information shown on site and select a main album, making it the only album accessible on the site. ## Design The site design is heavily inspired by (read "stolen from") https://getbootstrap.com/docs/4.1/examples/album/
C++
UTF-8
827
3.40625
3
[]
no_license
#include <cassert> #include <mutex> #include <gtest/gtest.h> // // This example demonstrates resource acqusition in C++. // The lifetime of the guard object determines when // the mutex is being acquired and released. // auto func(std::mutex& m, int val, bool b) { auto&& guard = std::lock_guard<std::mutex>{m}; // The mutex is locked [auto&& is needed in current version of MSVC] if (b) { // The lock automatically releases the mutex at early exit return; } if (val == 313) { // The lock automatically releases if an exception is thrown throw std::exception(); } // The lock automatically releases the mutex at function exit } TEST(ResourceAcquisition, Mutex) { auto&& m = std::mutex{}; // [auto&& is needed in current version of MSVC] auto v = int{}; auto b = bool{}; func(m, v, b); }
C
UTF-8
2,395
3.421875
3
[]
no_license
#include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <time.h> const int LOADING_WIDTH = 30; int main(int argc, char *argv[]) { // check args if (argc < 2) { printf("Usage: %s [file]\n", argv[0]); return 1; } // attempt to open file FILE *file = fopen(argv[1], "r"); // check if failed to open file if (!file) { printf("Error: Failed to open file.\n"); return -1; } // get file size fseek(file, 0L, SEEK_END); long long fileSize = ftell(file); fseek(file, 0L, SEEK_SET); printf("Attempting to read a %lld byte file randomly.\n", fileSize); // seed rand srand(time(NULL)); long long count = 0; // has to be u64 or will overflow long long rand_num; // u64 to be large enough for file size int res; // response code of fseek, just returns an int // progress bar stuff char s1[] = "##############################"; char s2[] = ".............................."; // time display time_t start = time(0); time_t now; time_t diff; time_t last_diff; double perc; char buff_eta[100]; char buff_elapsed[100]; while(count < fileSize) { do { // generate random u64 number rand_num = rand(); // upper bits rand_num = (rand_num << 32) | rand(); // lower bits // seek to random position res = fseek(file, rand_num % fileSize, SEEK_SET); // retry if fseek failed, non zero number on fail } while(res); fgetc(file); // returns something but dont care ++count; // calculate time diff now = time(0); diff = now - start; // only output once per second if (last_diff != diff) { last_diff = diff; perc = (count * 1.0 / fileSize * 1.0); float perc_100 = perc * 100.0; // percent to display // calculate eta and elapsed time float perc_left = 100 - perc_100; time_t eta = (diff / perc_100) * perc_left; strftime(buff_eta, 100, "%H:%M:%S", gmtime(&eta)); strftime(buff_elapsed, 100, "%H:%M:%S", gmtime(&diff)); // output data to stdout printf("\rProgress: %6.*f%% [%.*s%.*s] ETA %s (%s elapsed)", 2, perc_100, (int)(LOADING_WIDTH * perc), s1, (int)(LOADING_WIDTH * (1 - perc)), s2, buff_eta, buff_elapsed); fflush(stdout); } } printf("\nFinished reading file.\n"); return 0; }
C#
UTF-8
1,713
2.828125
3
[]
no_license
using System; using System.Diagnostics.Contracts; using Autofac; namespace GraphLabs.CommonUI.Configuration { /// <summary> IOC-контейнер </summary> internal static class DependencyResolver { /// <summary> Экземпляр IOC-контейнера </summary> public static IContainer Current { get { return _current; } private set { CheckNotBuilt(); _current = value; } } private static bool _built = false; private static readonly Lazy<ContainerBuilder> _builder = new Lazy<ContainerBuilder>(); private static IContainer _current; /// <summary> Получить построитель контейнера (чтобы зарегистрировать в нём ещё что-нибудь) </summary> /// <remarks> Имеет смыл до тех пор, пока контейнер не был сконфигурирован. </remarks> internal static ContainerBuilder GetBuilder() { CheckNotBuilt(); return _builder.Value; } /// <summary> Сконфигурировать IOC-контейнер </summary> internal static void Setup() { CheckNotBuilt(); var builder = _builder.Value; Current = builder.Build(); _built = true; } private static void CheckNotBuilt() { Contract.Requires<InvalidOperationException>(!_built, "IOC-контейнер уже сконфигурирован."); } } }
C++
UTF-8
1,500
2.515625
3
[]
no_license
#if !defined(_SCENE_H_) #define _SCENE_H_ #include <list> #include "Iw2DSceneGraph.h" using namespace Iw2DSceneGraphCore; using namespace Iw2DSceneGraph; class SceneManager; class Scene : public CNode { protected: unsigned int m_NameHash; bool m_IsActive; bool m_IsInputActive; SceneManager* m_Manager; int SceneDifficulty = 1; int SceneMode = 1; public: bool IsActive() const { return m_IsActive; } void SetActive(bool active) { m_IsActive = active; } void SetName(const char* name); unsigned int GetNameHash() const { return m_NameHash; } void SetManager(SceneManager* manager) { m_Manager = manager; } void SetInputActive(bool active) { m_IsInputActive = active; } void SetSceneDifficulty(int diff) { SceneDifficulty = diff; } int GetSceneDifficulty() { return SceneDifficulty; } void SetSceneMode(int mode) { SceneMode = mode; } int GetSceneMode() { return SceneMode; } public: Scene(); virtual ~Scene(); virtual void Init(); virtual void Update(float deltaTime = 0.0f, float alphaMul = 1.0f); virtual void Render(); }; class SceneManager { protected: Scene* m_Current; Scene* m_Next; std::list<Scene*> m_Scenes; public: Scene* GetCurrent() { return m_Current; } SceneManager(); ~SceneManager(); void SwitchTo(Scene* scene); void Update(float deltaTime = 0.0f); void Render(); void Add(Scene* scene); void Remove(Scene* scene); Scene* Find(const char* name); }; extern SceneManager* g_pSceneManager; #endif
Python
UTF-8
2,830
3.9375
4
[ "MIT" ]
permissive
"""Bass class for all objects on the game board.""" from bricks.types.point import Point class GameObject: """ Bass class for all objects on the game board. Abstract class only to be used with inheritance. Attributes ---------- top_left: Point Top left coordinate of the game object. top_right: Point Top right coordinate of the game object. bottom_left: Point Bottom left coordinate of the game object. bottom_right: Point Bottom right coordinate of the game object. width: float Width of the game object. height: float Height of the game object. """ def __init__( self, top_left: Point = Point(0.0, 0.0), width: float = 0.0, height: float = 0.0, ): """ Raises ValueError if height, width or top left contain negative values. Raises Exception on direct use as GameObject. """ if type(self) is GameObject: raise Exception( "GameObject is an abstract class and cannot be instantiated " "directly" ) self._top_left = _check_args_point(top_left) self._witdh = _check_args_width(width) self._height = _check_args_height(height) @property def top_left(self) -> Point: return self._top_left @top_left.setter def top_left(self, top_left: Point): self._top_left = top_left @property def bottom_right(self) -> Point: return Point( self._top_left.x + self._witdh, self._top_left.y + self._height ) @property def bottom_left(self) -> Point: return Point(self._top_left.x, self._top_left.y + self._height) @property def top_right(self) -> Point: return Point(self._top_left.x + self._witdh, self._top_left.y) @property def width(self) -> float: return self._witdh @property def height(self) -> float: return self._height def _check_args_point(point: Point) -> Point: if point.x < 0.0 or point.y < 0.0: raise ValueError( "game_object.def _check_args_point(point):\n" "Point must be >= 0\n" "Point x: %s\n" "Point y: %s\n" % (point.x, point.y) ) return point def _check_args_width(width: float) -> float: if width < 0.0: raise ValueError( "game_object.def _check_args_width(point):\n" "Width must be >= 0\n" "Width: %s\n" % (width) ) return width def _check_args_height(height: float) -> float: if height < 0.0: raise ValueError( "game_object.def _check_args_height(point):\n" "Height must be >= 0\n" "Height: %s\n" % (height) ) return height
C++
UTF-8
1,207
2.96875
3
[]
no_license
//----------------------------------------------------------------------------- // media-h.cc //----------------------------------------------------------------------------- #include <iostream> // std::cout std::endl #include <limits> // std::numeric_limits #include <numeric> // std::accumulate //----------------------------------------------------------------------------- const int N = 9; int v[N] = {0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, std::numeric_limits<int>::max()}; //----------------------------------------------------------------------------- long long int suma64s(int v[], int n) { long long int t = 0; for (int i = 0; i < n; ++i) t += v[i]; return t; } //----------------------------------------------------------------------------- long long int media(int v[], int n) { return suma64s(v, n) / n; } //----------------------------------------------------------------------------- int main(int argc, char* argv[]) { std::cout << "media = " << media(v, N) << std::endl; std::cout << "media = " << std::accumulate(&v[0], &v[0] + N, 0ll) / N << std::endl; } //-----------------------------------------------------------------------------
JavaScript
UTF-8
2,686
2.59375
3
[]
no_license
/* 1. 鼠标移入显示,移出隐藏 目标: 手机京东, 客户服务, 网站导航, 我的京东, 去购物车结算, 全部商品 2. 鼠标移动切换二级导航菜单的切换显示和隐藏 3. 输入搜索关键字, 列表显示匹配的结果 4. 点击显示或者隐藏更多的分享图标 5. 鼠标移入移出切换地址的显示隐藏 6. 点击切换地址tab 7. 鼠标移入移出切换显示迷你购物车 8. 点击切换产品选项 (商品详情等显示出来) 9. 点击向右/左, 移动当前展示商品的小图片 10. 当鼠标悬停在某个小图上,在上方显示对应的中图 11. 当鼠标在中图上移动时, 显示对应大图的附近部分区域 */ /* 1)对哪些元素绑定监听--2)对哪些元素进行什么DOM操作 找规律 */ $(function () { showhide() hoverSubMenu() search() share() // 5. 鼠标移入移出切换地址的显示隐藏 //4. 点击显示或者隐藏更多的分享图标 function share() { var isOpen = false //关闭 打开状态,定义一个布尔值 标识当前状态,初始为关闭 var $shareMore = $('#shareMore') var $parent = $shareMore.parent() var $as = $shareMore.prevAll('a:lt(2)') var $b = $shareMore.children('b') $shareMore.click(function () { if (isOpen) { //去关闭 isOpen = false $parent.css('width', 155) $as.hide() $b.removeClass('backword') } else { //去打开 isOpen = true $parent.css('width', 200) $as.show() $b.addClass('backword') } }) } // 3. 输入搜索关键字, 列表显示匹配的结果 function search() { $('#txtSearch') .on('focus keyup', function () { //如果输入框有文本才显示列表 var txt = this.value.trim() if (txt) { $('#search_helper').show() } }) .blur(function () { $('#search_helper').hide() }) } /*2. 鼠标移动切换二级导航菜单的切换显示和隐藏*/ function hoverSubMenu() { $('#category_items>div').hover( function () { $(this).children(':last').show() }, function () { $(this).children(':last').hide() } ) } // 1. 鼠标移入显示,移出隐藏 目标: 手机京东, 客户服务, 网站导航, 我的京东, 去购物车结算, 全部商品 function showhide() { $('[name=show_hide]').hover( function () { //显示 var id = this.id + '_items' $('#' + id).show() }, function () { //隐藏 var id = this.id + '_items' $('#' + id).hide() } ) } })
Markdown
UTF-8
5,669
3.078125
3
[]
no_license
+++ date = "2016-07-04T07:07:55-07:00" title = "TaskPaper + Vim + Dropbox + Editorial = GTD & Checklist Perfection" slug = "taskpaper-+-vim-+-dropbox-+-editorial-checklist-perfection" +++ I have tried worryingly many methods for tracking my personal and professional projects, some of which I have written about here before. I finally boiled down what I wanted to: 1. _The ability to edit things with Vim._ I feel so much more productive when writing in Vim, and even more productive when reorganizing things in Vim, that using another tool always felt frustrating. 2. _The ability to capture while mobile._ While I can use Vim on iOS, it's not the same. I wanted to the ability to add new things to my todo list, mark things off, review my projects while in a meeting, and so on. I've finally found something that works for me, and works well. * [Editorial](http://omz-software.com/editorial/): a fantastic, programmable with python, iOS text editor * The [TaskPaper](http://omz-software.com/editorial/docs/ios/editorial_writing_todo_lists.html) text file format, supported excellently by both Editorial and Vim * [Vim](http://www.vim.org/), my favorite editor when I have a full keyboard, with a [TaskPaper](https://github.com/davidoc/taskpaper.vim) plugin installed * And finally, [Dropbox](http://dropbox.com) to keep the files in sync. ### Taskpaper If you've never used Taskpaper, it's wonderfully simple. You can create projects, tasks, subtasks, and general tags with very little syntax. Blog About TaskPaper: - Gather links to the relevant projects @home - Get blog software working again after a blogging hiatus - Upgrade to the python3 version @done(2016-07-03) - Check for broken configuration @today And that's about it. You can use the tags to filter your views of things or, in editorial, show things as checked/completed, or color coded. It's just enough capability for Todo/GTD type work. I find when my `todo.taskpaper` file becomes unwieldy, it's a good sign that I'm tracking too many things that will never get done anyway, and it's time to archive or delete projects. ### Vim Two small changes made Vim work great in this setup. First, with `taskpaper.vim` installed, you get a lot of nice hotkeys for things like: * focusing on a single project * marking tasks done * archiving all completed tasks * marking tasks as due today, and focusing only on today's tasks I generally have a vim running with my `todo.taskpaper` file open at all times. However, that's not ideal for the 'ubiquitous capture.' If I have the file open, and I haven't saved all my edits, I may clobber them if editing on mobile. Similarly, if I make a mobile edit, and don't reopen the file in vim, I'll lose those changes. Some small settings in `.vimrc` make this a non-issue. (Using `Vundle` syntax here to show the plugins needed.) " Autosave taskpaper files Plugin 'vim-scripts/vim-auto-save' Plugin 'djoshea/vim-autoread' autocmd filetype taskpaper let g:auto_save = 1 autocmd filetype taskpaper :WatchForChanges! Translating to English -- if the filetype is one that's used by the taskpaper extension, then auto-save the files on edit, and do a force-reload if file changes are detected on the filesystem. Because I'm the only one actually editing this file, the risk of a race condition here is nearly nil. ### Editorial I can't say enough about the Editorial app. It's incredibly useful to be able to simply extend it with Python, when needed, and even without that capability it's wonderful out of the box. If you work in Markdown at all, give it a look. Because it supports Dropbox, the synchronization is easy. As long as I'm online, it's got the latest versions of all my files. The UI for working with taskpaper files is great, very easy to drag things around to reorganize them, fold projects to focus on specific ones, and most importantly, check things off as they're completed. ### Bonus Use Case: Checklists! These tools together have provided me pretty much everything I need for day to day GTD/To Do. But I discovered another use case that's very handy: frequently used checklists! For example, I have a `car_camping.taskpaper` file for camping trips, which looks like so: Pantry: - Pancake Mix - Olive Oil - Salt & Pepper ... Equipment: - 6 person tent - Sun shade - Head Lamp When I'm ready to actually go camping, I can make a new copy of the basic taskpaper config: $ cp car_camping.taskpaper 2016_06_beverly_beach_camping.taskpaper Then I can add extra planning sections for this particular trip, like removing equipment that's only needed in colder weather, or planning meals and shopping trips: Meals: - Monday - Breakfast: Pancakes, Eggs, Fruit ... Shopping: - Propane Bottles - Bubble Solution Then, as I confirm that I have indeed purchased or packed any item, I can check it off. I do all the planning with a nice keyboard, and access to vim, and check things off on my phone as I go. The best of both worlds! And finally, it's nice to have the completed checklists as records of the past. ("What did we eat last trip? The kids seemed to do really well with that.") ### Plain Text Saves The Day It's fairly surprising, with how duct-taped this solution is together, how happy I've been with it, and how it handles two somewhat different use cases (daily project management, and periodic checklist execution) with basically the same workflow. It's a real testament to the power of simple, plain text formats and what we can do when there's consensus around them.
Java
UTF-8
22,093
1.664063
2
[]
no_license
package com.nd.hilauncherdev.app; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.nd.android.pandahome2.shop.R; import com.nd.hilauncherdev.analysis.AppAnalysisConstant; import com.nd.hilauncherdev.analysis.AppDistributeStatistics; import com.nd.hilauncherdev.app.WarnBean.WarnCategory; import com.nd.hilauncherdev.app.WarnBean.WarnItem; import com.nd.hilauncherdev.appmarket.AppMarketUtil; import com.nd.hilauncherdev.framework.view.commonview.HeaderView; import com.nd.hilauncherdev.kitset.util.AndroidPackageUtils; import com.nd.hilauncherdev.kitset.util.TelephoneUtil; import com.nd.hilauncherdev.kitset.util.ThreadUtil; import com.nd.hilauncherdev.shop.Global; import com.nd.hilauncherdev.shop.shop3.AsyncImageLoader; import com.nd.hilauncherdev.shop.shop3.AsyncImageLoader.ImageCallback; import com.nd.hilauncherdev.webconnect.downloadmanage.model.BaseDownloadInfo; import com.nd.hilauncherdev.webconnect.downloadmanage.model.DownloadManager; import com.nd.hilauncherdev.webconnect.downloadmanage.model.DownloadServerService; import com.nd.hilauncherdev.webconnect.downloadmanage.model.DownloadServerServiceConnection; import com.nd.hilauncherdev.webconnect.downloadmanage.model.filetype.FileType; import com.nd.hilauncherdev.webconnect.downloadmanage.util.DownloadBroadcastExtra; import com.nd.hilauncherdev.webconnect.downloadmanage.util.DownloadState; /** * 匣子搜索应用详情界面。 Title: DrawerSearchAppDetailView Description: Company: ND * * @author MaoLinnan * @date 2014年12月12日 */ public class ShopRecommendAppDetailView extends LinearLayout { private Context context; private ShopRecommendAppDetailPopupWindow appDetailPopupWindow; private ImageAdapter imageAdapter; private int state = DownloadState.STATE_NONE;// 下载状态 private int progress = 0;// 下载进度 private SoftDetialBean softDetialBean;// 软件详情 private AsyncImageLoader asyncImageLoader;// 异步加载图片 private RelativeLayout mRoot; private ScrollView scrollView; private ImageView icon;// 应用图标 private ImageView apptype;// 类型标志 private TextView appTitle;// 应用名 private RatingBar ratingBar;// 评分 private LinearLayout scanInfo;// 扫描信息 private TextView scanIconView;// 扫描标示 private ImageView scanMoreInfoBtn;// 扫描信息按钮 private LinearLayout marketPower;// 安全信息列表 private TextView appSize;// 应用大小 private TextView downNumber;//下载次数 private TextView appVersion;// 应用版本号 private LinearLayout networkTipsLinearlayout;// 网络提醒布局 private Button networkTipsBtn;// 继续浏览按钮 private HorizontalListView appThumbnail;// 应用缩略图 private TextView detailInfoContent;// 应用简介 private TextView btnDownload;// 应用下载控制按钮 public ShopRecommendAppDetailView(Context context, ShopRecommendAppDetailPopupWindow appDetailPopupWindow) { super(context); this.context = context; this.appDetailPopupWindow = appDetailPopupWindow; this.imageAdapter = new ImageAdapter(); asyncImageLoader = new AsyncImageLoader(); initView(); initListener(); } private void initView() { mRoot = (RelativeLayout) View.inflate(context, R.layout.searchbox_hotword_detail_info_view_shop_v6, null); HeaderView headView = (HeaderView) mRoot.findViewById(R.id.head_view); headView.setTitle(getResources().getString(R.string.searchbox_hotword_detail_info)); headView.setGoBackListener(new OnClickListener() { @Override public void onClick(View v) { appDetailPopupWindow.cancelDrawerSearchAppDetailPopupWindow(); } }); scrollView = (ScrollView) mRoot.findViewById(R.id.drawer_search_app_detail_scrollview); icon = (ImageView) mRoot.findViewById(R.id.drawer_search_app_detail_icon); apptype = (ImageView) mRoot.findViewById(R.id.drawer_search_app_detail_apptype_imageview); appTitle = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_app_title); downNumber = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_app_downnumber); ratingBar = (RatingBar) mRoot.findViewById(R.id.drawer_search_app_detail_ratingBar); scanInfo = (LinearLayout) mRoot.findViewById(R.id.drawer_search_app_detail_scan_info); scanIconView = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_scan_icon_view); scanMoreInfoBtn = (ImageView) mRoot.findViewById(R.id.drawer_search_app_detail_scan_more_info_btn); marketPower = (LinearLayout) mRoot.findViewById(R.id.rawer_search_app_detail_market_power); appSize = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_app_size); appVersion = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_app_version); networkTipsLinearlayout = (LinearLayout) mRoot.findViewById(R.id.drawer_search_app_detail_network_tips_linearlayout); networkTipsBtn = (Button) mRoot.findViewById(R.id.drawer_search_app_detail_network_tips_btn); appThumbnail = (HorizontalListView) mRoot.findViewById(R.id.drawer_search_app_detail_app_thumbnail); detailInfoContent = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_detail_info_content); btnDownload = (TextView) mRoot.findViewById(R.id.drawer_search_app_detail_btnDownload); appThumbnail.setAdapter(imageAdapter); this.addView(mRoot, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } private void initListener() { // 扫描信息 scanInfo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (marketPower.getVisibility() == View.GONE) {// 要显示 marketPower.setVisibility(View.VISIBLE); scanMoreInfoBtn.setBackgroundResource(R.drawable.app_market_detail_security_hide); } else {// 要隐藏 marketPower.setVisibility(View.GONE); scanMoreInfoBtn.setBackgroundResource(R.drawable.app_market_detail_security_expand); } } }); // 继续浏览缩略图 networkTipsBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { networkTipsLinearlayout.setVisibility(View.GONE); appThumbnail.setVisibility(View.VISIBLE); // 加载缩略图 initAppThumbnail(); } }); // 下载按钮 btnDownload.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(softDetialBean.identifier)) {// 已安装应用直接打开 if (AndroidPackageUtils.isPkgInstalled(getContext(), softDetialBean.identifier)) { AndroidPackageUtils.runApplication(getContext(), softDetialBean.identifier); appDetailPopupWindow.cancelDrawerSearchAppDetailPopupWindow(); return; } } AppDistributeStatistics.AppDistributePercentConversionStatistics(getContext(), "606"); Resources r = getContext().getResources(); switch (state) { case DownloadState.STATE_PAUSE: case DownloadState.STATE_CANCLE: case DownloadState.STATE_NONE: // to start download case -1: btnDownload.setText(r.getString(R.string.searchbox_waiting)); if (mConnection != null) { // 添加到下载管理器 BaseDownloadInfo dlInfo = new BaseDownloadInfo(softDetialBean.getKey(), FileType.FILE_APK.getId(), softDetialBean.downloadUrl, softDetialBean.resName, AppMarketUtil.PACKAGE_DOWNLOAD_DIR, (softDetialBean.getKey() + ".apk"), Global.url2path(softDetialBean.downloadUrl, Global.CACHES_HOME_MARKET)); dlInfo.setDisId(softDetialBean.resName); dlInfo.setDisSp(AppAnalysisConstant.SP_HOTWORD_RECOMMEND_APP); mConnection.addDownloadTask(dlInfo); } break; case DownloadState.STATE_DOWNLOADING: // to pause download btnDownload.setText(r.getString(R.string.searchbox_pause_with_progress, progress)); if (mConnection != null) mConnection.pause(softDetialBean.getKey()); break; case DownloadState.STATE_FINISHED:// 下载完成 btnDownload.setText(r.getString(R.string.searchbox_download_completed)); //假如有下载好了,就直接安装 try{ File file = new File(AppMarketUtil.PACKAGE_DOWNLOAD_DIR + softDetialBean.getKey() + ".apk"); if (file.exists()) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); } }catch (Exception e) { e.printStackTrace(); } default: break; } } }); } /** * 请求更新详情内容 Title: requestUpdateDrawerSearchAppDetailView Description: * * @param packageName * @author maolinnan_350804 */ public void requestUpdateDrawerSearchAppDetailView(final SoftDetialBean softDetialBean) { if (softDetialBean == null) { return; } this.softDetialBean = softDetialBean; // 填入对应信息 icon.setImageResource(R.drawable.app_market_default_icon); Drawable tmp = asyncImageLoader.loadDrawable(softDetialBean.iconUrl, new ImageCallback() { @Override public void imageLoaded(Drawable imageDrawable, String imageUrl) { icon.setImageDrawable(imageDrawable); } }); if(tmp != null){ icon.setImageDrawable(tmp); } AppTypeBusiness.showType(apptype, softDetialBean.appType); appTitle.setText(softDetialBean.resName); ratingBar.setProgress(softDetialBean.star); appSize.setText(softDetialBean.size); appVersion.setText(String.format(context.getString(R.string.searchbox_hotword_detail_info_app_version), softDetialBean.version)); detailInfoContent.setText(Html.fromHtml(softDetialBean.getDescript())); downNumber.setText(context.getString(R.string.searchbox_hotword_detail_downnumber) + softDetialBean.downloadNumber); // 填充安全信息 initWarnInfo(); if (TelephoneUtil.isWifiEnable(context)) {// 在wifi环境下 networkTipsLinearlayout.setVisibility(View.GONE); appThumbnail.setVisibility(View.VISIBLE); // 加载缩略图 initAppThumbnail(); } // 恢复布局状态 scrollView.scrollTo(0, 0); marketPower.setVisibility(View.GONE); scanMoreInfoBtn.setBackgroundResource(R.drawable.app_market_detail_security_expand); btnDownload.setText(R.string.common_button_download); // 获取下载状态 if (mConnection != null) { BaseDownloadInfo baseDownloadInfo = mConnection.getDownloadTask(softDetialBean.getKey()); if (baseDownloadInfo != null) { state = baseDownloadInfo.getState(); progress = baseDownloadInfo.progress; }else{ state = DownloadState.STATE_NONE; progress = 0; } }else{//清空当前状态 state = DownloadState.STATE_NONE; progress = 0; } updateDownloadUI(); // 已经安装直接显示打开 if (!TextUtils.isEmpty(softDetialBean.identifier)) {// 已安装应用直接打开 if (AndroidPackageUtils.isPkgInstalled(getContext(), softDetialBean.identifier)) { btnDownload.setText(R.string.common_button_open); } } } /** * 初始化缩略图 Title: initAppThumbnail Description: * * @author maolinnan_350804 */ private void initAppThumbnail() { if (softDetialBean == null) { return; } imageAdapter.setDate(softDetialBean.snapshots); } private class ImageAdapter extends BaseAdapter { private ArrayList<String> snapshots = new ArrayList<String>(); private Map<String, Drawable> imageThumbnail; public ImageAdapter() { imageThumbnail = new HashMap<String, Drawable>(); } public void setDate(ArrayList<String> snapshots) { if (snapshots == null){ return; } this.snapshots = snapshots; this.notifyDataSetChanged(); } @Override public int getCount() { return snapshots.size(); } @Override public Object getItem(int position) { return snapshots.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ImageView image; if (convertView == null) { convertView = View.inflate(context, R.layout.searchbox_hotword_detail_info_view_v6_item, null); image = (ImageView) convertView.findViewById(R.id.image); convertView.setTag(image); } else { image = (ImageView) convertView.getTag(); } Drawable drawable = imageThumbnail.get(snapshots.get(position)); if (drawable != null) { image.setBackgroundDrawable(drawable); } else { image.setBackgroundResource(R.drawable.framwork_viewfactory_load_data_img); asyncImageLoader.loadDrawable(snapshots.get(position), new ImageCallback() { @Override public void imageLoaded(Drawable imageDrawable, String imageUrl) { image.setBackgroundDrawable(imageDrawable); imageThumbnail.put(imageUrl, imageDrawable); } }); } return convertView; } } /** * 填充安全信息 Title: initWarnInfo Description: * * @author maolinnan_350804 */ private void initWarnInfo() { if (softDetialBean == null) { return; } WarnBean bean = this.softDetialBean.safeInfo; if (bean == null) { return; } marketPower.removeAllViews(); WarnCategory scanCate = bean.warnCategorys.get(WarnBean.WARN_SCANPROVIDER); float commTextsize = 14; if (scanCate != null && scanCate.state != 0) { formatWarnCateTextView(scanIconView, scanCate, 0, 0, 0, 0); List<WarnItem> items = scanCate.warnItems; for (Iterator<WarnItem> it = items.iterator(); it.hasNext();) { WarnItem item = (WarnItem) it.next(); if (item != null && item.state != 0) { String title = item.title; if (!TextUtils.isEmpty(title)) { LinearLayout itemLayout = new LinearLayout(getContext()); itemLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); itemLayout.setOrientation(LinearLayout.HORIZONTAL); itemLayout.setGravity(Gravity.CENTER_VERTICAL); marketPower.addView(itemLayout); ImageView iconView = new ImageView(getContext()); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.setMargins(40, 0, 0, 0); iconView.setLayoutParams(lp); int defaultImage = 0; if (!TextUtils.isEmpty(title)) { if (title.contains(context.getText(R.string.searchbox_hotword_detail_info_warn_qq))) { defaultImage = R.drawable.market_warn_qq; } else if (title.contains(context.getText(R.string.searchbox_hotword_detail_info_warn_kingsoft))) { defaultImage = R.drawable.market_warn_kingsoft; } else if (title.contains(context.getText(R.string.searchbox_hotword_detail_info_warn_lbe))) { defaultImage = R.drawable.market_warn_lbe; } else { defaultImage = R.drawable.market_warn_360; } } if (defaultImage == 0) { iconView.setImageResource(R.drawable.market_warn_gray); } else { iconView.setImageResource(defaultImage); } itemLayout.addView(iconView); TextView itemView = new TextView(getContext()); itemView.setTextColor(Color.BLACK); itemView.setTextSize(commTextsize); String str = title + context.getText(R.string.searchbox_hotword_detail_info_warn_fruit) + (item.state == 1 ? context.getText(R.string.searchbox_hotword_detail_info_warn_pass) : context .getText(R.string.searchbox_hotword_detail_info_warn_never_tested)); SpannableStringBuilder style = new SpannableStringBuilder(str); int iconlen = 0; int titlelen = iconlen + title.length() + context.getText(R.string.searchbox_hotword_detail_info_warn_fruit).length(); style.setSpan(new ForegroundColorSpan(getStateColor(item.state)), titlelen, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); itemView.setText(style); itemLayout.addView(itemView); } } } } } /** 填充安全提示 */ public void formatWarnCateTextView(TextView textView, WarnCategory cate, int marginleft, int marginTop, int marginRight, int marginBottom) { if (cate == null || cate.state == 0) { textView.setVisibility(View.GONE); return; } if (cate.state == 1) { textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.market_warn_green, 0, 0, 0); } else if (cate.state == 2) { textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.market_warn_yellow, 0, 0, 0); } else if (cate.state == 3) { textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.market_warn_red, 0, 0, 0); } else if (cate.state == 4) { textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.market_warn_gray, 0, 0, 0); } textView.setCompoundDrawablePadding(8); textView.setTextColor(getStateColor(cate.state)); textView.setText(cate.title); textView.setTextSize(14); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.setMargins(marginleft, marginTop, marginRight, marginBottom); textView.setLayoutParams(lp); } private int getStateColor(int state) { switch (state) { case 0: case 1: return Color.rgb(0x71, 0xa7, 0x01); case 2: return Color.rgb(0xf8, 0x69, 0x00); case 3: return Color.rgb(0xdd, 0x03, 0x03); case 4: return Color.rgb(0x76, 0x76, 0x76); } return Color.rgb(0x71, 0xa7, 0x01); } /** * 下载状态监听 */ private DownloadProgressReceiver mProgressReceiver; /** * 下载管理进程通讯连接 */ private DownloadServerServiceConnection mConnection; /** * 绑定下载服务 */ private void bindService() { if (mConnection != null) return; ThreadUtil.executeDrawer(new Runnable() { @Override public void run() { try { // 绑定下载进程 mConnection = new DownloadServerServiceConnection(getContext()); getContext().bindService(new Intent(getContext(), DownloadServerService.class), mConnection, Context.BIND_AUTO_CREATE); } catch (Exception ex) { ex.printStackTrace(); } } }); } /** * 解除绑定 */ private void unbindService() { if (mConnection == null) return; ThreadUtil.executeDrawer(new Runnable() { @Override public void run() { try { getContext().unbindService(mConnection); } catch (Exception ex) { ex.printStackTrace(); } } }); } private void registerDownloadProgressReceiver() { try { // 注册下载状态监听 if (mProgressReceiver == null) mProgressReceiver = new DownloadProgressReceiver(); IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_STATE); getContext().registerReceiver(mProgressReceiver, filter); } catch (Exception e) { e.printStackTrace(); } } private void unregisterDownloadProgressReceiver() { try { if (mProgressReceiver != null) getContext().unregisterReceiver(mProgressReceiver); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); this.registerDownloadProgressReceiver(); this.bindService(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); this.unregisterDownloadProgressReceiver(); this.unbindService(); } /** * 下载进度广播监听 */ private class DownloadProgressReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { String identification = intent.getStringExtra(DownloadBroadcastExtra.EXTRA_IDENTIFICATION); if (identification == null || !identification.equals(softDetialBean.getKey())) return; state = intent.getIntExtra(DownloadBroadcastExtra.EXTRA_STATE, DownloadState.STATE_NONE); progress = intent.getIntExtra(DownloadBroadcastExtra.EXTRA_PROGRESS, 0); updateDownloadUI(); } catch (Exception e) { e.printStackTrace(); } } }// end DownloadReceiver private void updateDownloadUI() { if (!TextUtils.isEmpty(softDetialBean.identifier)) {// 已安装应用直接打开 if (AndroidPackageUtils.isPkgInstalled(getContext(), softDetialBean.identifier)) { btnDownload.setText(R.string.common_button_open); } } Resources r = getContext().getResources(); switch (state) { case DownloadState.STATE_DOWNLOADING: // ■ 下载中 btnDownload.setText(r.getString(R.string.searchbox_downloading, progress)); break; case DownloadState.STATE_PAUSE: // ■ 暂停 btnDownload.setText(r.getString(R.string.searchbox_pause_with_progress, progress)); break; case DownloadState.STATE_WAITING: // ■ 等待下载 btnDownload.setText(r.getString(R.string.searchbox_waiting)); break; case DownloadState.STATE_FINISHED: // ■ 下载完成 btnDownload.setText(r.getString(R.string.searchbox_download_completed)); break; case DownloadState.STATE_CANCLE: // ■ 取消 btnDownload.setText(r.getString(R.string.searchbox_canceled)); break; default: break; } } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { if (hasWindowFocus) {// 界面显示的时候 // 已经安装直接显示打开 if (!TextUtils.isEmpty(softDetialBean.identifier)) {// 已安装应用直接打开 if (AndroidPackageUtils.isPkgInstalled(getContext(), softDetialBean.identifier)) { btnDownload.setText(R.string.common_button_open); } } } } }
JavaScript
UTF-8
762
2.890625
3
[]
no_license
//WATSON FILE IN MODELS FOLDER const ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3'); const { iam_apikey, url } = require('../config'); const toneAnalyzer = new ToneAnalyzerV3({ version_date: '2017-09-21', iam_apikey, url }); const text = 'omg what'; const analyseTone = text => { const toneParams = { tone_input: { text }, content_type: 'application/json' }; return new Promise((resolve, reject) => { toneAnalyzer.tone(toneParams, function(error, toneAnalysis) { if (error) reject(error); else resolve(toneAnalysis); }); }); }; analyseTone(text) .then(analysis => console.log(analysis)) .catch(err => console.log(err)); //analyseTone(text) returns a PROMISE; module.exports = { analyseTone };
Java
UTF-8
1,015
2.265625
2
[]
no_license
package com.lee.neihanduanzi.bean; import java.util.List; /** * Created by u on 2017/6/30. */ public class DataBeanX extends BaseBean { private boolean has_more; private int min_time; private String tip; private double max_time; private List<DataBean> data; public boolean isHas_more() { return has_more; } public void setHas_more(boolean has_more) { this.has_more = has_more; } public int getMin_time() { return min_time; } public void setMin_time(int min_time) { this.min_time = min_time; } public String getTip() { return tip; } public void setTip(String tip) { this.tip = tip; } public double getMax_time() { return max_time; } public void setMax_time(double max_time) { this.max_time = max_time; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } }
Markdown
UTF-8
1,052
2.578125
3
[]
no_license
## WorkspaceApp This app allows you to signup for premier work-spaces and events, whether you need a pass for a day, a dedicated desk for your business, or an office suite for your entire company. Developed using Typescript, CSS3, HTML 5 and .NET CORE REST API. The app can perfom all the CRUD operations-for creating, reading, updating and deleting various components(workspaces,events,services etc). For the backend, I am using a REST WEB service. This project was generated with [Ionic CLI](https://ionicframework.com/docs/cli/) version 4.2.1. ## Development server Start the server using command - `ionic serve(for browser view)` or `ionic lab(for mobile view)`. ## Steps to setup blueSpace App 1. Open the downloaded blueSpace app folder 2. Install node_modules package e.g `npm -i` 3. Install ion-text-avatar e.g `npm install --save ionic-text-avatar` 4. Run the project using command `ionic serve(for browser view)` or `ionic lab(for mobile view)` * NOTE: YOU WILL NEED TO REGISTER OR CREATE ACCOUNT TO USE THIS APP *
Python
UTF-8
905
2.75
3
[]
no_license
# -*- coding: UTF-8 -*- import requests import lxml from bs4 import BeautifulSoup # FT中文 首页内容 ft = requests.get('http://www.ftchinese.com/') source = BeautifulSoup(ft.text,"lxml"); # 获取头条文章链接 article = source.find('div',class_="XL8").find('a',class_='item-headline-link')['href'] # 每日头条文章 全文模式 newFt = requests.get('http://www.ftchinese.com'+article,params={'full':'y'}) newSource = BeautifulSoup(newFt.text,"lxml"); # 获取文章链接,标题,副标题,内容 url = newFt.url title = newSource.find('h1',class_='story-headline').get_text() subtitle = newSource.find('div',class_='story-lead').get_text() articlecontent = newSource.find('div',class_='story-body').find_all('p') print url,title.encode('utf-8'),subtitle.encode('utf-8') body = [] for index in articlecontent: body.append(index.get_text()) print index.get_text().encode('utf-8')
Java
UTF-8
897
3.484375
3
[]
no_license
package exer9; import java.lang.reflect.Constructor; /** * 2. 利用反射和重载完成以下功能 * 1)创建Student类,类中有属性name和age并封装属性 * 2)重载Student的构造函数,一个是无参构造并,另一个是带两个参数的有参构造,要求在构造函数打印提示信息 * 3)创建带main函数的NewInstanceTest类,利用Class类得到Student对象 * 4)通过上述获取的Class对象分别调用Student有参函数和无参函数 * @author: 86173 * @date: 2021/4/26 19:25 */ public class ReflectionTest1 { public static void main(String[] args) throws Exception { Class<Student> s1 = Student.class; Student s3 = s1.newInstance(); Constructor<Student> d1 = s1.getDeclaredConstructor(String.class, int.class); d1.setAccessible(true); Student s2 = d1.newInstance("Tom", 12); } }
C
UTF-8
12,023
2.609375
3
[ "MIT" ]
permissive
/* Catalog routines (no swapping) */ /* Translated to C: 12/10/96 at 11:37 */ /* Translator Version: 0.000 */ /* Catalog routines: . VALID_FILECHAR (c): returns TRUE if character C is valid in a filename . VALID_FILENAME (name): returns TRUE if passed filename is valid . CLEAN_FILENAME (name, fcb_name): converts XPL string format to FCB name format . CLEAN_FCBNAME (fcb_name, name): converts FCB name to XPL string format . . CACHE (bufptr, bufmed): cache contents of catalog buffer in buffer BUFPTR on BUFMED . REINIT_CACHE (n, buffer): reinitialize caching to provide for N caches . FLUSH_CACHE (n): flush cache N to disk/tape . DISABLE_CACHE (n): disable cache N . ENABLE_CACHE (n): enable cache N . CACHE_TREENAME (enable): enable/disable treename caching . . SET_CATBUF (bufptr, bufmed): set the catalog buffer pointer . READCAT (ms_sector, ls_sector, dir_size, ms_length, ls_length): read in a catalog . WRITECAT: write out the catalog buffer . READDIR (name): read in catalog NAME . . GET_FCB (fcb#, fcb): extract an FCB from the catalog buffer . PUT_FCB (fcb#, fcb): replace an FCB into the catalog buffer . . FINDFILE (name): find a file in the catalog buffer . REMOVEFILE (name): remove file NAME from catalog . ADDFILE (name, type, ms_sectors, ls_sectors, length): add file NAME to catalog . SHORTENFILE (name, ms_sectors, ls_sectors, length): shorten file NAME . RENAMEFILE (old_name, new_name): rename OLD_NAME to NEW_NAME . FINDSTORAGE (ms_sectors, ls_sectors): find storage . FINDMAX: find maximum storage available . . READ_CATALOG (treename, level): read catalog TREENAME on LEVEL . WRITE_CATALOG: write out the catalog buffer . DELETE (treename, level): delete file TREENAME on LEVEL . REPLACE (treename, type, ms_sectors, ls_sectors, length, level): replace file TREENAME on LEVEL . TRUNCATE (treename, ms_sectors, ls_sectors, length, level): truncate file TREENAME on LEVEL . RENAME (old_name, new_name, level): rename OLD_NAME to NEW_NAME on LEVEL . LOCATE (treename, level): locate file TREENAME on LEVEL . LOOKSTORAGE (treename, ms_sectors, ls_sectors, level): look for storage on TREENAME/LEVEL . LOOKMAX (treename, level): lookup maximum storage available on TREENAME/LEVEL . ENTER_CATALOG (treename, level): enter catalog TREENAME on LEVEL . ENTER_ALTERNATE (treename, level): enter alternate catalog TREENAME on LEVEL */ #include "XPL.h" /* Catalog entry definitions */ #define c_nm 0 /* filename (four words) */ #define c_ls 4 /* Ls starting sector */ #define c_ll 5 /* Ls sector length */ #define c_wd 6 /* word length (modulo 64K) */ #define c_ty 7 /* Ms starting sector (8 bits)/MS sector length (4 bits)/file type (4 bits) */ #define c_len 8 /* number of words in a catalog entry */ #define c_dir_max 1024 /* maximum directory size (words) */ /* Fcb definitions (used with GET_FCB and PUT_FCB) */ #define f_nm 0 /* filename (four words) */ #define f_ls 4 /* Ls starting sector */ #define f_ms 5 /* Ms starting sector */ #define f_ll 6 /* Ls sector length */ #define f_ml 7 /* Ms sector length */ #define f_wd 8 /* word length (modulo 64K) */ #define f_ty 9 /* file type */ #define f_len 10 /* number of words in an FCB */ #define f_name_len 4 /* number of words in a filename */ /* File type definitions */ #define t_text 0 /* text file */ #define t_exec 1 /* executable binary */ #define t_reloc 2 /* relocatable binary */ #define t_data 3 /* data file */ #define t_sync 4 /* synclavier sequence */ #define t_sound 5 /* sound file */ #define t_subc 6 /* subcatalog */ #define t_lsubc 7 /* large subcatalog */ #define t_dump 8 /* dump file */ #define t_spect 9 /* spectral file */ #define t_index 10 /* index file */ #define t_timbre 11 /* synclavier timbre */ #define t_max 11 /* maximum defined filetype */ /* Errors returned in C#STATUS */ #define e_none 0 /* no error encountered */ #define e_os 1 /* operating system error - magic number not set */ #define e_buffer 2 /* no catalog buffer allocated */ #define e_no_dir 3 /* no directory in memory */ #define e_no_config 4 /* device not configured */ #define e_no_floppy 5 /* no floppy in drive */ #define e_fcb 6 /* Fcb number out of bounds */ #define e_level 7 /* level number out of bounds */ #define e_storage 8 /* not enough available storage */ #define e_cstorage 9 /* not enough contiguous storage available */ #define e_dir_full 10 /* no entries left in the directory */ #define e_invalid 11 /* invalid directory */ #define e_name 12 /* invalid filename specified for operation requested */ #define e_duplicate 13 /* duplicate filename */ #define e_no_file 14 /* file not found */ #define e_not_cat 15 /* name specified is required to be a catalog, but isn't */ #define e_treename 16 /* incorrect format for treename */ #define e_no_path 17 /* intermediate catalog (in treename) not found */ #define e_type 18 /* type mismatch between saved file and replaced file (ADDFILE/REPLACE only) */ #define e_protect 19 /* write protected floppy */ #define e_too_large 20 /* file too large (>= 2^20 sectors) */ #define e_truncate 21 /* truncation error - trying to expand a file (or truncate tape file) */ #define e_diskerror 22 /* disk error: the disk could not be read */ /* Caching literals */ #define __vars 5 /* five variables/cache */ /* Global catalog variables */ extern fixed c_status; /* status of last catalog operation */ extern fixed c_bufptr; /* pointer to the catalog buffer */ extern fixed* c_bufhost; /* catalog buffer in host computer memory */ extern fixed c_bufmed; /* catalog buffer media: 0 - main memory, 1 - external memory */ extern fixed c_ms_sector; /* device and MS starting sector of catalog */ extern fixed c_ls_sector; /* Ls starting sector of catalog */ extern fixed c_ms_length; /* Ms sector length of catalog (including directory) */ extern fixed c_ls_length; /* Ls sector length of catalog (including directory) */ extern fixed c_dir_size; /* size of catalog directory (in words) */ /* Global file variables */ extern array f_name; /* name of last filename scanned off treename */ extern fixed f_ms_sector; /* device and MS starting sector of file */ extern fixed f_ls_sector; /* Ls starting sector of file */ extern fixed f_ms_length; /* Ms sector length of file */ extern fixed f_ls_length; /* Ls sector length of file */ extern fixed f_words; /* word length of file (modulo 64K) */ extern fixed f_type; /* type of file */ /* Alternate catalog variables (for reference only - do NOT modify) */ extern array a_name; /* name of alternate catalog */ extern fixed a_ms_sector; /* device and MS starting sector of catalog */ extern fixed a_ls_sector; /* Ls starting sector of catalog */ extern fixed a_ms_length; /* Ms sector length of catalog (including directory) */ extern fixed a_ls_length; /* Ls sector length of catalog (including directory) */ extern fixed a_dir_size; /* size of catalog directory (in words) */ /* Filename processing */ extern boolean valid_filechar(fixed); /* return TRUE if specified character is valid in a filename */ extern boolean valid_filename(fixed[]); /* return TRUE if passed filename is valid */ extern void clean_filename(fixed[], fixed[]); /* convert XPL string format to FCB name format */ extern void clean_fcbname(fixed[], fixed[]); /* convert FCB name to XPL string format */ /* Caching */ extern fixed cache(fixed, fixed); /* cache contents of catalog buffer */ extern void reinit_cache(fixed, fixed); /* reinitialize caching to provide for N caches */ /* note: was fixed, fixed *; second arg */ /* is able_core space pointer... */ extern boolean flush_cache(fixed); /* flush cache N to disk/tape */ extern void disable_cache(fixed); /* disable cache N */ extern void enable_cache(fixed); /* enable cache N */ extern void cache_treename(boolean); /* enable/disable treename caching */ /* Buffer interface */ extern void set_catbuf(fixed, fixed); /* set the catalog buffer pointer */ /* note: was pointer, fixed */ /* first arg points to cat buffer in able_core */ /* data space */ extern boolean readcat(fixed, fixed, fixed, fixed, fixed); /* read in a catalog */ extern boolean writecat(); /* write out the catalog buffer */ extern boolean readdir(fixed[]); /* read in catalog NAME */ extern boolean get_fcb(fixed, fixed[]); /* extract an FCB from the catalog buffer */ extern boolean put_fcb(fixed, fixed[]); /* replace an FCB into the catalog buffer */ extern fixed findfile(fixed[]); /* find a file in the catalog buffer */ extern boolean removefile(fixed[]); /* remove file NAME from catalog */ extern boolean addfile(fixed[], fixed, fixed, fixed, fixed); /* add file NAME to catalog */ extern boolean shortenfile(fixed[], fixed, fixed, fixed); /* shorten file NAME */ extern boolean renamefile(fixed[], fixed[]); /* rename OLD_NAME to NEW_NAME */ extern fixed findstorage(fixed, fixed); /* find storage */ extern boolean findmax(); /* find maximum storage available */ /* Level interface */ extern boolean get_device_size(fixed); /* get catalog size for a device */ extern boolean read_catalog(fixed[], fixed); /* read catalog TREENAME on LEVEL */ extern boolean write_catalog(); /* write out the catalog buffer */ extern boolean XPLdelete(void *, fixed, int isCString); /* delete file NAME on LEVEL */ extern boolean replace(void *, fixed, fixed, fixed, fixed, fixed, int isCString); /* replace file NAME on LEVEL */ extern boolean AbleCatRtns_GetCatalog ( void *theName, fixed level, int isCString); /* gets the catalog into memory */ extern boolean AbleCatRtns_AddFile (void *, fixed, fixed, fixed, fixed, int isCString); extern boolean AbleCatRtns_UpdateFile (void *, fixed, fixed, fixed, fixed, int isCString, void* newName); extern boolean AbleCatRtns_UpdateName (void *theName, int isCString, fixed newName[4]); extern boolean AbleCatRtns_FindFile (void *, int isCString); extern boolean truncate(void *, fixed, fixed, fixed, fixed, int isCString); /* truncate file NAME on LEVEL */ extern boolean rename_able_file(void *, void *, fixed, int isCString); /* rename OLD_NAME to NEW_NAME on LEVEL */ extern boolean locate(void *, fixed, int isCString); /* locate file NAME on LEVEL */ extern boolean lookstorage(void *, fixed, fixed, fixed, int isCString); /* look for storage on TREENAME/LEVEL */ extern boolean lookmax(void *, fixed, int isCString); /* lookup maximum storage available on TREENAME/LEVEL */ extern boolean enter_catalog(void *, fixed, int isCString); /* enter catalog NAME on LEVEL */ extern boolean enter_alternate(void *, fixed, int isCString); /* enter alternate catalog NAME on LEVEL */ // Host interface extern fixed AbleCatRtns_AllowTypeReplace; // true to allow replace file to have different file type extern fixed AbleCatRtns_SoundFileChanged; // set true of subcat or sound file changes extern void initialize_able_catalog_routines();
Python
UTF-8
750
3.328125
3
[]
no_license
"""Parse python-style keyword args from a text config file, one key-value pair per line. """ import ast from typing import Any, Dict def config_parser(fname: str) -> Dict[str, Any]: """ Args: fname (str): Name of the config file Returns: (Dict[str, Any]): Dictionary of parsed config args. """ parsed_kwargs = {} with open(fname, 'r') as file: lines = [line for line in file.read().split('\n') if len(line) > 0] for line in lines: if '=' in line: split = line.split('=') parsed_kwargs[split[0]] = ast.literal_eval( split[1].replace('\n', '')) else: print(f'Warning: Ignoring config line {line}') return parsed_kwargs
Python
UTF-8
3,004
3.265625
3
[]
no_license
# importing needed libaries import os import csv # Getting to the file path with my needed csv. One directory backwards and then into resources PyPoll = os.path.join('..','Resources', 'PyPoll_Resources_election_data.csv') # Declaring all my needed variables and lists total_votes = 0 khan_count = 0 correy_count = 0 tooley_count = 0 li_count = 0 names = [] list_of_names = [] diff_names_count = 0 khan_percent = 0 correy_percent = 0 tooley_percent = 0 li_percent = 0 # reading my csv file with open (PyPoll) as PyPoll: csv_reader = csv.reader(PyPoll, delimiter = ",") # skips the header header = next(csv_reader) for i in csv_reader: # make a list of every single name in column 3 of the csv names.append(i[2]) # counts total votes total_votes = total_votes + 1 for name in names: # to make a list of different names if name not in list_of_names: list_of_names.append(name) # Used for debugging purposes # diff_names_count = diff_names_count + 1 # counting all Khans, correys, lis, and tooleys in list_of names if name == "Khan": khan_count = khan_count + 1 if name == "Correy": correy_count = correy_count + 1 if name == "Li": li_count = li_count + 1 if name == "O'Tooley": tooley_count = tooley_count + 1 # creating percentages khan_percent = 100*(round(khan_count/total_votes, 2)) correy_percent = 100*(round(correy_count/total_votes, 2)) tooley_percent = 100*(round(tooley_count/total_votes, 2)) li_percent = 100*(round(li_count/total_votes, 2)) #Printing requested information print("Election Results") print("Total Votes: " + str(total_votes)) print("Candidates" + str(list_of_names)) #print(diff_names_count) print("Khan: " + str(khan_percent) + "% " + str(khan_count)) print("Correy: " + str(correy_percent) + "% " + str(correy_count)) print("Li: " + str(li_percent) + "% " + str(li_count)) print("O'Tooley: " + str(tooley_percent) + "% " + str(tooley_count)) # If statment to choose Winner if khan_count > correy_count and khan_count > li_count and khan_count > tooley_count: print("Winner: Khan") if correy_count > khan_count and correy_count > li_count and correy_count > tooley_count: print("Winner: Correy") if li_count > khan_count and li_count > correy_count and li_count > tooley_count: print("Winnder: Li") if tooley_count > khan_count and tooley_count > correy_count and tooley_count > li_count: print("Winner: O'Tooley") else: print("Winner: No one") file = open("PyPoll_Analysis.txt", "w") file.write("Election Results") file.write("\n") file.write("Total Votes: " + str(total_votes)) file.write("\n") file.write("Candidates" + str(list_of_names)) file.write("\n") file.write("Khan: " + str(khan_percent) + "% " + str(khan_count)) file.write("\n") file.write("Correy: " + str(correy_percent) + "% " + str(correy_count)) file.write("\n") file.write("Li: " + str(li_percent) + "% " + str(li_count)) file.write("\n") file.write("O'Tooley: " + str(tooley_percent) + "% " + str(tooley_count)) # closing the text file file.close()
Markdown
UTF-8
1,412
2.8125
3
[]
no_license
dcdumper ======== Adding tools to the dotcloud CLI which make it easier to do backups. ## Installation `pip install https://github.com/metalivedev/dcdumper/archive/master.zip` ## Use The first addition is `sshconf` which is super-useful for working directly with `ssh`, `scp` and `rsync` ``` $ dcdumper sshconf -A myapp --file myapp.conf ==> Wrote 1 entries to myapp.conf. You can now sync your data with: ==> "rsync -azv -e 'ssh -F myapp.conf' myapp.myservice.0:code/ code" ``` Every one of your dotCloud code services has a full copy of all the code for all the code services in that application. The code is always under the symbolic link `code/` so it is easy to find and rsync it down, and you only need to pull it once, since each service has a full copy. You could use the same technique to `rsync` your `data` directory too. Unlike the `code` directory, the `data` directory is unique to each service, so you will need to repeat the `rsync` for each service id, for example: ``` rsync -azv -e 'ssh -F myapp.conf' myapp.myservice.0:data/ data.0/ rsync -azv -e 'ssh -F myapp.conf' myapp.myservice.1:data/ data.1/ ``` For more information about using `ssh`, `scp` and `rsync` with your dotCloud applications, please see [the docs](http://docs.dotcloud.com/guides/copy/#generic-ssh-scp-rsync) The magic is in using the `-F` parameter to let `ssh` know to use the file as your configuration file.
Ruby
UTF-8
814
2.671875
3
[ "MIT" ]
permissive
module Groupdate class Series attr_accessor :magic, :relation def initialize(magic, relation) @magic = magic @relation = relation end # clone to prevent modifying original variables def method_missing(method, *args, &block) # https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/calculations.rb if ActiveRecord::Calculations.method_defined?(method) magic.perform(relation, method, *args, &block) elsif @relation.respond_to?(method, true) Groupdate::Series.new(magic, relation.send(method, *args, &block)) else super end end def respond_to?(method, include_all = false) ActiveRecord::Calculations.method_defined?(method) || relation.respond_to?(method) || super end end end
C++
UTF-8
2,341
2.875
3
[]
no_license
#include "duckcrud.h" DuckCRUD::DuckCRUD(QObject *parent) : QObject(parent), db(nullptr), con(db), counter(1) // counter(1) { qDebug() << "called"; // Create a table in constructor and insert some default values con.Query("CREATE TABLE people(id INTEGER, name VARCHAR)"); con.Query("CREATE TABLE test"); con.Query("INSERT INTO people VALUES (0,'Mark'), (1, 'Hannes')"); } void DuckCRUD::insertData() { // Increment the counter // append to the table and close the appender to add data to database // Read more here https://duckdb.org/docs/data/appender counter++; duckdb::Appender appender(con, "people"); QString newData = "Test" + QString::number(counter); appender.AppendRow(counter, newData.toUtf8().constData()); appender.Close(); emit dataUpdated(); } QStringList DuckCRUD::readTableData() { QStringList output; auto result = con.Query("SELECT * FROM people"); // If failed to fetch data from table if (!result->success){ qDebug() << result->error.at(0); output << "NULL"; } else{ // Get the size of the collection // Get the result and convert standard string to QString // before inserting in QStringList idx_t a = result->collection.count; for (idx_t i = 0; i < a; i++){ output << QString::fromStdString(result->GetValue(1, i).ToString()); } } return output; } void DuckCRUD::updateData() { // Update date using prepared statement QString name = "Replaced name" + QString::number(counter); auto prepared = con.Prepare("UPDATE people SET name = $1 WHERE id = $2"); auto prep = prepared->Execute(name.toUtf8().constData(), counter); emit dataUpdated(); } void DuckCRUD::deleteData() { auto result = con.Query("DELETE FROM people WHERE id = " + QString::number(counter).toStdString()); counter--; emit dataUpdated(); } void DuckCRUD::processCsv() { QElapsedTimer timer; timer.start(); // I tested on Macbook Air Early 2015, i5, 4gb with 1.5GB file // It takes about 30 seconds auto result = con.Query("CREATE TABLE t1 AS SELECT * FROM read_csv_auto ('/Abosolute/Path/To/CSV/File.csv')"); result->Print(); qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds"; }
C++
UTF-8
814
3.78125
4
[]
no_license
//标准库中的模板类vector< > x vector类中定义了x.size() 返回值为vector<>模板类中定义 //的vector<int>::size_type 无符号整形 unsigned //<algorithm>标准库中的算法头文件 //x.push_back(num) 将num放在向量x的末尾 x.begin() x.end()分别为向量x的第一和末尾 // #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; int main() { typedef vector<int>::size_type vv; vector<int> num; int x; while(cin>>x) { num.push_back(x); } sort(num.begin(), num.end()); vv size = num.size(); cout<<"vector<int>中一共保存了 "<<size<<" 个元素"<<endl; for(int i = 0 ; i < size ; i++) { cout<<num[i] <<" "; } cout<<endl; return 0; }
Markdown
UTF-8
356
2.515625
3
[]
no_license
# Christmas Card This is a 3d representation of the popup Christmas card I made for my grandma a couple years ago. It is built with ThreeJS. I learned ThreeJS for fun one week when I was bored at work! You can zoom in and move the card around! ![Screenshot of page](https://github.com/HannahRipley17/christmascard/blob/main/img/screenshot.png?raw=true)
Java
UTF-8
1,650
1.789063
2
[ "Apache-2.0" ]
permissive
package com.guli.guliproduclt.service; import com.baomidou.mybatisplus.extension.service.IService; import com.guli.common.utils.PageUtils; import com.guli.guliproduclt.entity.CategoryEntity; import com.guli.guliproduclt.vo.Catelog2Vo; import java.util.List; import java.util.Map; /** * 商品三级分类 * * @author fry * @email eeeeee@gmail.com * @date 2020-06-06 19:56:22 */ public interface CategoryService extends IService<CategoryEntity> { PageUtils queryPage(Map<String, Object> params); /** * 作者 FRY * 功能描述 : 三级分类查询分类 * 日期 2020/6/15 19:22 * 参数 * 返回值 java.util.List<com.guli.guliproduclt.entity.CategoryEntity> */ List<CategoryEntity> listWhiBel(); /** *@Description: 踩踩踩 *@Param: [asList] *@return: void *@Author: fry *@Date: 2020/8/15 13:03 *@Version: 1.0 *@Company: 版权所有 */ void rremoveMenuById(List<Long> asList); /** *@Author: fry *@Description: 查询父节点 *@Param: [catelogId] *@Date: 2020/8/15 13:05 */ Long[] findCcatelogPath(Long catelogId); /** *@Author: fry *@Description: 跟新冗余 *@Param: [category] *@Date: 2020/8/15 17:59 */ void updateClassification(CategoryEntity category); /** *@Author: fry *@Description: 首页父类菜单列表查询 *@Param: [] *@Date: 2020/8/25 17:13 */ List<CategoryEntity> selectCategorys(); /** *@Author: fry *@Description: 查询父分类下的所有 *@Param: [] *@Date: 2020/8/25 18:38 */ Map<String, List<Catelog2Vo>> getCatalogJson(); }
Java
UTF-8
942
2.0625
2
[]
no_license
package tw.com.pershing.databean; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="Response") public class ETLresponse { private String msg; private List<String> logs; private String error; private String fileInfo; @XmlElement(name="msg") public String getMsg() { return msg; } public List<String> getLogs() { return logs; } @XmlElement(name="logs") public void setLogs(List<String> logs) { this.logs = logs; } public void setMsg(String msg) { this.msg = msg; } @XmlElement(name="errorMsg") public String getError() { return error; } public void setError(String error) { this.error = error; } @XmlElement(name="fileInfo") public String getFileInfo() { return fileInfo; } public void setFileInfo(String fileInfo) { this.fileInfo = fileInfo; } }
Markdown
UTF-8
1,476
2.75
3
[]
no_license
# RESTFUL-API This RestFul API project is written in C# and ASP.NET Core 2.1 using SQL Server and Entity Framework Code First a. What is required for running the project - Open from Visual Studio - Change the database Server in appsetting.json to be your server b. Steps how to run scripts that will setup database for the project To able to run the database you need to run these scripts in Package Manager Console. The scripts are : - first => 'add-migration nameOfMigration' - second => 'update-database' then database scheme has been written in your database c. Steps how to build and run the project - Build the project using Visual Studio or on the command line with 'dotnet build' - Run the project. API will start up on http://localhost:5000/ , or http://localhost:5000/ with 'dotnet run' if u use command line - Use HTTP client like Postman or Swagger. The API has been configured wit Swagger. It can be checked on https://localhost:5001/swagger/index.html d. Example usages (ie. like example curl commands) - GET All Note => http://localhost:5000/api/v1/Note - GET Specific Note => http://localhost:5000/api/v1/Note/{id} - POST Note => http://localhost:5000/api/v1/Note/ Body:{"title": "string","content":"string"} - PUT Note (Update) => http://localhost:5000/api/v1/Note/{id} Body:{"title": "string","content":"string"} - DELETE Note => http://localhost:5000/api/v1/Note/{id} - GET history of specific Note => http://localhost:5000/api/v1/Note/history/{id}
Java
UTF-8
332
1.921875
2
[]
no_license
package com.whatsapp; import com.whatsapp.VoiceService.VoiceServiceEventCallback; class so implements Runnable { final VoiceServiceEventCallback a; so(VoiceServiceEventCallback voiceServiceEventCallback) { this.a = voiceServiceEventCallback; } public void run() { this.a.bufferQueue.a(); } }
Python
UTF-8
292
4.03125
4
[]
no_license
names = ["Alice", "Charlie", "Bob"] print(sorted(names, key=len)) names.sort(key=len) print(names) # sortieren nach dem zweiten Buchstaben names.sort(key=lambda name: name[1]) print(names) def get_second_letter(name): return name[1] names.sort(key=get_second_letter) print(names)
Shell
UTF-8
418
2.515625
3
[]
no_license
#!/usr/bin/env sh # 發生錯誤時執行終止指令 set -e # 打包編譯 npm run build # 移動到打包資料夾下,若你有調整的話打包後的資料夾請務必調整 # cd dist # 部署到自定義網域 # echo 'www.example.com' > CNAME git init git add -A git commit -m 'VueCLI 切換頁面' # 部署到 https://<USERNAME>.github.io/<REPO> git push -f git@github.com:kaiachun/PetPal.git master:main cd -
Java
UTF-8
291
1.617188
2
[]
no_license
package com.yc.mapper; import java.util.List; import com.yc.entity.TempPage; import com.yc.entity.UserRole; public interface UserRoleMapper { TempPage<UserRole> findUserRoles(int page, int size); int deleteById(int id); List<UserRole> findRoleByuid(int user_id); }
C++
UTF-8
1,549
3.671875
4
[]
no_license
/* For each tree the program checks if it can be placed to the left by comparing the last position occupied by the previous tree and its height. If this cannot be done it checks if the tree can be place to the right in a similar way. The first tree can alway be placed to its left. This works since by choosing the left segment over the right one we have more chances to cut also the next tree. Also if we prevent a tree to be cut by cutting the previous one this won't affect the final number of trees that can be cut. Then the program scans once the array so it takes O( n ) time. Reference:none */ #include <vector> #include <iostream> using namespace std; struct Tree { int position; int height; }; int main( ) { int n; cin >> n; vector<Tree> road( n ); for( int i = 0; i < n; i++ ) { cin >> road[i].position >> road[i].height; } int noCuttedTrees = 1; int lastUsedPosition = road[0].position; for( int i = 1; i < n; i++ ) { if( ( road[i].position - road[i].height ) > lastUsedPosition ) { noCuttedTrees++; lastUsedPosition = road[i].position; } else if( i + 1 >= n ) { noCuttedTrees++; } else if( ( road[i].position + road[i].height ) < road[i + 1].position ) { noCuttedTrees++; lastUsedPosition = road[i].position + road[i].height; } else { lastUsedPosition = road[i].position; } } cout << noCuttedTrees << endl; }
Rust
UTF-8
878
3.984375
4
[]
no_license
fn main() { let x = 123; println!("x is {}", x); { let x = 456; println!("x is {}", x); } println!("x is {}", x); let mut y = 123; println!("y is {}", y); { y = 456; println!("y is {}", y); } println!("y is {}", y); // DOESN'T WORK: must be `mut` mutable to re-assign. // // let z = 123; // println!("z is {}", z); // { // z = 456; // println!("z is {}", z); // } // println!("z is {}", z); const C:i32 = 123; println!("C is {}", C); { // Shadowing constants actually works if it's another scope, // I was surprised by this. // It doesn't work if it's in the same scope though, // which will work with normal variables. const C:i32 = 456; println!("C is {}", C); } println!("C is {}", C); }
C#
UTF-8
2,030
2.59375
3
[]
no_license
using EjemploApi.Common.Logic; using EjemploApi.DataAccess.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace EjemploApi.Business.Facade.Logic.Controllers { public class UsuarioAsyncController : ApiController { private readonly IUsuarioBlAsync _usuarioBlAsync; public UsuarioAsyncController(IUsuarioBlAsync usuarioBlAsync) { this._usuarioBlAsync = usuarioBlAsync; } /// <summary> /// Return one Student for Redis /// </summary> /// <param name=<em>"key"</em>>Redis key of tables</param> /// <returns>Student Json Serialize</returns> [HttpGet()] public async Task<IHttpActionResult> GetAsync(string key) { try { var result = await this._usuarioBlAsync.GetAsync(key); if (result==null) return NotFound(); else return Ok(result); } catch (Exception ex) { return InternalServerError(); } } /// <summary> /// Add one Student in Redis /// </summary> /// <param name=<em>"key"</em>>Redis key of tables</param> /// <param name=<em>"entity"</em>>The student to save</param> /// <returns>Student Json Serialize</returns> [HttpPost()] public async Task<IHttpActionResult> AddAsync(string key ,Usuario entity ) { try { var result = await this._usuarioBlAsync.AddAsync(entity, key).ConfigureAwait(false); if (result ==null)return NotFound(); else return Ok(result); } catch (Exception) { return InternalServerError(); } } } }
Java
UTF-8
1,255
2.515625
3
[]
no_license
package com.openclassrooms.realestatemanager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView textViewMain; private TextView textViewQuantity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //this.textViewMain = findViewById(R.id.activity_second_activity_text_view_main); this.textViewMain = findViewById(R.id.activity_main_activity_text_view_main); this.textViewQuantity = findViewById(R.id.activity_main_activity_text_view_quantity); this.configureTextViewMain(); this.configureTextViewQuantity(); } private void configureTextViewMain(){ this.textViewMain.setTextSize(15); this.textViewMain.setText("Le premier bien immobilier enregistré vaut "); } private void configureTextViewQuantity(){ int quantity = Utils.convertDollarToEuro(100); this.textViewQuantity.setTextSize(20); //this.textViewQuantity.setText(quantity); this.textViewQuantity.setText(String.valueOf(quantity)); } }
SQL
UTF-8
887
3.765625
4
[]
no_license
SELECT * FROM `dreamhome-db`.staff ORDER BY fname ASC; Select salary, fname, lname, salary from staff -- Produce a list of all properties that have been views(at least once). showing only the propery number. select viewDate from viewing where viewdate >1; -- Produce a list of monthly Salaries for all staff, showing the staff numner, the first and last names, the monthly_salary[Include some necessary SQL code in your query to make the monthly_salary data -- be displayed under te column heading named, monthly_salary SELECT -- List all Staff whose salary is more than 10000. Display the list sorted beginning from the highest earner to the lowest-- select salary from staff where salary >10000 Order by Salary DSC; --List the data of all branch offices which are located in either London or Bristol Select city from branch where city is London || city is Bristol;
Swift
UTF-8
569
2.859375
3
[]
no_license
// // Photo.swift // Lots of Images // // Created by Vince Kearney on 12/06/2017. // Copyright © 2017 vince. All rights reserved. // import UIKit class Photo: NSObject { // MARK: Properties public var imageData : Data? public var imageTitle : String? public var imageIdentifier : String? override init() { super.init() } convenience init(withData : Data, title : String, id : String) { self.init() self.imageData = withData self.imageTitle = title self.imageIdentifier = id } }
C#
UTF-8
1,790
2.59375
3
[]
no_license
using System.Linq; using CQSS.Promotion.DataContract; using PromotionData = CQSS.Promotion.DataContract; namespace CQSS.Promotion.DataService.PromotionSettingValidator { public abstract class ValidatorBase : IValidator { /// <summary> /// 保证 Promotion 不为空, /// 保证 Promotion 必须配置有 PromotionRule,且所有的 PromotionRule 的 RuleType 必须相同 /// 保证 PromotionRule 必须配置有 PromotionSolution。 /// </summary> public virtual ValidateResult Validate(PromotionData.Promotion promotion) { if (promotion == null) return new ValidateResult { Success = false, ErrorMessage = "促销实体为空" }; if (promotion.Rules.Count == 0) return new ValidateResult { Success = false, ErrorMessage = "未配置促销规则" }; if (promotion.Rules.Any(r => r.Solutions.Count == 0)) return new ValidateResult { Success = false, ErrorMessage = "未配置优惠方案" }; if (promotion.Rules.Select(r => r.RuleType).Distinct().Count() != 1) return new ValidateResult { Success = false, ErrorMessage = "配置了多种类型的促销规则" }; foreach (var rule in promotion.Rules) { var mostCount = 1; var realCount = rule.Solutions.Where(s => s.SolutionType <= PromotionData.SolutionType.FixedAmount).Count(); if (realCount > mostCount) return new ValidateResult { Success = false, ErrorMessage = "配置了多种金额减免类型的优惠方案" }; } return new ValidateResult { Success = true }; } } }
C++
UTF-8
3,143
2.921875
3
[]
no_license
// // main.cpp // 417.Pacific Atlantic Water Flow // // Created by stevenxu on 12/28/19. // Copyright © 2019 stevenxu. All rights reserved. // #include <iostream> #include <vector> using namespace std;; class Solution { vector<int> dirs = {0, -1, 0, 1, 0}; vector<vector<int>> res; vector<vector<int>> visited; public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) return res; int m = matrix.size(), n = matrix[0].size(); visited.resize(m, vector<int>(n)); for (int i = 0; i < m; ++i) { helper(matrix, i, 0, INT_MIN, 1); helper(matrix, i, n - 1, INT_MIN, 2); } for (int j = 0; j < n; ++j) { helper(matrix, 0, j, INT_MIN, 1); helper(matrix, m - 1, j, INT_MIN, 2); } return res; } void helper(vector<vector<int>>& matrix, int i, int j, int pre, int preV) { if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || matrix[i][j] < pre || (visited[i][j] & preV) == preV) return; visited[i][j] |= preV; if (visited[i][j] == 3) res.push_back({i, j}); for (int k = 0; k < 4; ++k) { int nextI = i + dirs[k], nextJ = j + dirs[k + 1]; helper(matrix, nextI, nextJ, matrix[i][j], visited[i][j]); } } }; class Solution { vector<int> dirs = {0, -1, 0, 1, 0}; public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { vector<vector<int>> res; if (matrix.empty() || matrix[0].empty()) return res; int m = matrix.size(), n = matrix[0].size(); vector<vector<bool>> pacific(m, vector<bool>(n, false)); vector<vector<bool>> atlantic(m, vector<bool>(n, false)); for (int i = 0; i < m; ++i) { helper(matrix, i, 0, pacific); helper(matrix, i, n - 1, atlantic); } for (int j = 0; j < n; ++j) { helper(matrix, 0, j, pacific); helper(matrix, m - 1, j, atlantic); } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (pacific[i][j] && atlantic[i][j]) res.push_back({i, j}); } } return res; } void helper(vector<vector<int>>& matrix, int i, int j, vector<vector<bool>> &visited) { int m = matrix.size(), n = matrix[0].size(); visited[i][j] = true; for (int k = 0; k < 4; ++k) { int nextI = i + dirs[k], nextJ = j + dirs[k + 1]; if (nextI < 0 || nextI >= m || nextJ < 0 || nextJ >= n || visited[nextI][nextJ] || matrix[nextI][nextJ] < matrix[i][j]) continue; helper(matrix, nextI, nextJ, visited); } } }; int main(int argc, const char * argv[]) { // insert code here... vector<vector<int>> test = {{1,2,2,3,5},{3,2,3,4,4},{2,4,5,3,1},{6,7,1,4,5},{5,1,1,2,4}}; // vector<vector<int>> test = {{1,2,3},{8,9,4},{7,6,5}}; Solution s = Solution(); vector<vector<int>> res = s.pacificAtlantic(test); std::cout << "Hello, World!\n"; return 0; }
Markdown
UTF-8
2,718
2.8125
3
[ "MIT", "CC-BY-4.0" ]
permissive
--- title: Una questione di equilibrio slug: giusto-mezzo dateCreated: 2022-11-15 00:11 dateUpdated: 2022-11-15 00:11 visible: true tags: - filosofia --- ## <span class="newthought">In un mondo</span> sempre più polarizzato è importate evitare estremi dogmatici. Uno strumento che ci viene in aiuto è il principio del _Giusto Mezzo_, espresso da Aristotele\cite{aristotele}, secondo cui la virtù umana altro non è che il punto di equilibro tra due opposti errori, l’uno dei quali pecca per difetto e l’altro per eccesso. I Greci consideravano la moderazione essere un attributo della bellezza, e di conseguenza, buona. Nel secondo libro dell’Etica Nicomachea, il Filosofo elenca le singole virtù: - Coraggio: giusto mezzo fra viltà e temerarietà; - Temperanza: giusto mezzo tra intemperanza e insensibilità; - Generosità: giusto mezzo fra avarizia e prodigalità; - Magnificenza: giusto mezzo fra volgarità e grettezza d'animo; - Magnanimità: giusto mezzo tra la vanità e l'umiltà; - Mitezza: giusto mezzo tra l'iracondia e l'eccessiva flemma; - Amabilità: giusto mezzo tra misantropia e compiacenza; - Sincerità: giusto mezzo tra l'ironia e la vanità; - Arguzia: giusto mezzo tra la buffoneria e la rusticità; - Giustizia: la virtù principale, “nella giustizia ogni virtù si raccoglie in una sola”. Un simile concetto è presente anche nel Buddismo, nel Confucianesimo e nella teologia cristiana medievale. <div class="epigraph"> <blockquote> <p>«La strada dell'illuminazione è la linea che sta tra tutti gli opposti estremi.»</p> <footer>Siddharta</footer> </blockquote> </div> Le virtù etiche non si possiedono per natura, anche se l'uomo ha dimostrato di avere la capacità di acquisirle. **Si tratta ovviamente di un equilibrio difficile, che non è agevole raggiungere e mantenere**. Esso nasce da una ricerca incessante, che si muove tra positivo e negativo e si nutre del continuo alternarsi di sentimenti, esperienze, incontri, riflessioni. La complessità ci può sgomentare e scoraggiare, ma le illusioni semplicistiche generalmente conducono a una vita miserabile. Attraverso un interminabile esercizio possiamo navigare nell’apparente contraddizione degli opposti e imparare a lasciare spazio al dubbio mentre si coltiva un solido codice morale; o a essere in grado di vedere il mondo realisticamente, pur vivendo romanticamente; o a essere in grado di pensare profondamente, mentre si agisce instancabilmente. Niente di buono nella vita accade e basta, bisogna essere intenzionali: “Agisco, dunque sono”. <bibliography> @book{aristotele, title = "Etica Nicomachea, libro II", author = "Aristotele", } </bibliography>
C#
UTF-8
963
3.5625
4
[]
no_license
using System; using System.Collections.Generic; public class Game { public string name; public float price; public Genres genre; public List<DLC> dlcs = new List<DLC>(); public Game(string n, float p, Genres g) { name = n; price = p; genre = g; } public Game(string n, float p) { name = n; price = p; } public void AddDLC(string name, float price) { DLC newDLC = new DLC(name, price, this); dlcs.Add(newDLC); } public void PrintDLCs() { if (dlcs.Count == 0) { Console.WriteLine("No available DLCs"); } else { Console.WriteLine("Available DLCs:"); foreach (DLC dlc in dlcs) { Console.WriteLine(dlc.name + "; " + dlc.price); } } } } public enum Genres { Adventure, RPG, Puzzle, FPS, Horror }
JavaScript
UTF-8
688
2.640625
3
[]
no_license
import React from 'react'; import './randomquote.scss'; export default class RandomQuote extends React.Component { generateQuote() { fetch('https://api.kanye.rest').then(response => { return response.json(); }).then(response => { response = response.quote; console.log(response); document.querySelector('.quote').innerHTML = response; }) }; render() { const className = [ "quote-generator" ]; return ( <div className="quote-wrapper"> <button onClick={this.generateQuote} className={className}>Generate Quote</button> <span> <p className="quote"></p> </span> </div> ); } };
C#
UTF-8
3,036
2.703125
3
[]
no_license
using System.Collections.Generic; using System.Globalization; using System.Linq; namespace System.Web.Routing { public class DictionaryRouteValueTranslationProvider : IRouteValueTranslationProvider { public IList<RouteValueTranslation> Translations { get; private set; } public DictionaryRouteValueTranslationProvider(IList<RouteValueTranslation> translations) { this.Translations = translations; } public RouteValueTranslation TranslateToRouteValue(string translatedValue, CultureInfo culture) { // Find translation in specified CultureInfo RouteValueTranslation translation = ( from t in this.Translations orderby t.Culture.Name descending where ( t.Culture.Name == culture.Name || t.Culture.TwoLetterISOLanguageName == culture.TwoLetterISOLanguageName ) && t.TranslatedValue == translatedValue select t ).FirstOrDefault(); if (translation != null) return translation; // Find translation without taking account on CultureInfo translation = this.Translations.Where(t => t.TranslatedValue == translatedValue ).FirstOrDefault(); if (translation != null) return translation; // Return the current values return new RouteValueTranslation( culture, translatedValue, translatedValue ); } public RouteValueTranslation TranslateToTranslatedValue(string routeValue, CultureInfo culture) { // Find translation in specified CultureInfo RouteValueTranslation translation = ( from t in this.Translations orderby t.Culture.Name descending where ( t.Culture.Name == culture.Name || t.Culture.TwoLetterISOLanguageName == culture.TwoLetterISOLanguageName ) && t.RouteValue == routeValue select t ).FirstOrDefault(); if ( translation != null ) return translation; // Find translation without taking account on CultureInfo translation = this.Translations.Where( t => t.RouteValue == routeValue ).FirstOrDefault(); if ( translation != null ) return translation; // Return the current values return new RouteValueTranslation( culture, routeValue, routeValue ); } } }
Markdown
UTF-8
1,699
2.703125
3
[]
no_license
Title: Personalizar y añadir color a la consola de Linux Date: 2012-06-20 15:17 Author: ramborg Category: GNU/Linux Tags: Customize Slug: personalizar-y-anadir-color-a-la-consola-de-linux Actualmente la mayoria de distribuciones de linux ya vienen con un poco de color, al menos el ls, pero a veces no. Para añadir color a la consola de linux es necesario: - Crear un archivo en la ruta del usuario de normbre ".bashrc", también se puede encontrar una plantilla en /etc/skel/(al menos en Arch). - Añadir alias, por ejemplo: > *        alias ls='ls --color=auto'* > > *        alias grep='grep --color=auto'* - Tambien se puede personalizar el prompt de la consola, yo no lo cambio, pero al final dejo un enlace donde explica como. - A parte del color, para mi es importante el "autocomplete" de las opciones de los comandos, para esto hay que tener descargado el paquete "bash-completion" y añadir lo siguiente a nuestro .bashrc: >      * if [ -f /etc/bash\_completion ]; then* > *            . /etc/bash\_completion* > *      fi* - Por último, si se usa Vim como editor, para poner color a la sintaxis, se hace creando un archivo ".vimrc" y escribiendo en el: >      *syntax on* **Nota**: en mi caso el .bashrc para root no me lo reconocia. Existe el fichero /etc/bash.bashrc donde también se pueden poner estos cambios. Los articulos de donde he sacado la información son los siguientes: Personalización consola(mas completo, tiene lo del prompt): <http://jfibergran.wordpress.com/2009/04/10/personalizar-la-consola-de-linux-bashrc/> Vim con color: <http://rm-rf.es/activar-colores-en-vim/>
Python
UTF-8
200
2.8125
3
[]
no_license
import yaml # 读取YAML # 加载配置项 with open('python01.yaml',encoding='utf-8') as f: # 先打开文件 data = yaml.load(f.read(), Loader=yaml.FullLoader) # 全量加载 print(data)
Python
UTF-8
1,858
4.125
4
[]
no_license
import random # Password Generator Project letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] print("Welcome to the PyPassword Generator!") nr_letters = int(input("How many letters would you like in your password?\n")) nr_symbols = int(input(f"How many symbols would you like?\n")) nr_numbers = int(input(f"How many numbers would you like?\n")) # Eazy Level - Order not randomised: # e.g. 4 letter, 2 symbol, 2 number = JduE&!91 letters_len = len(letters) numbers_len = len(numbers) symbols_len = len(symbols) initial_pass = '' # this list cant be shuffled pass_list = [] # we can shuffle if the passwords are saved in a list for letter in range(0, nr_letters): rand_letter = random.randint(0, letters_len-1) initial_pass += letters[rand_letter] pass_list.append(letters[rand_letter]) # print(letters[rand_letter]) print(initial_pass) for num in range(0, nr_numbers): rand_num = random.randint(0, numbers_len - 1) initial_pass += numbers[rand_num] pass_list.append(numbers[rand_num]) print(initial_pass) for num in range(0, nr_symbols): rand_sym = random.randint(0, symbols_len - 1) initial_pass += symbols[rand_sym] pass_list.append(symbols[rand_sym]) print(f"Un-random: \t\t\t{initial_pass}") # Hard Level - Order of characters randomised: # e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P # shuffle the password list final_password = '' random.shuffle(pass_list) for chr in pass_list: final_password += chr print(f'Random password: \t{final_password}')
Python
UTF-8
2,381
3.125
3
[ "Python-2.0", "BSD-3-Clause", "MIT" ]
permissive
import unittest import error_handling as er from test_utils import FileLike class ErrorHandlingTest(unittest.TestCase): def test_throw_exception(self): with self.assertRaisesWithMessage(Exception): er.handle_error_by_throwing_exception() def test_return_none(self): self.assertEqual(er.handle_error_by_returning_none('1'), 1, 'Result of valid input should not be None') self.assertIsNone(er.handle_error_by_returning_none('a'), 'Result of invalid input should be None') def test_return_tuple(self): successful_result, result = er.handle_error_by_returning_tuple('1') self.assertIs(successful_result, True, 'Valid input should be successful') self.assertEqual(result, 1, 'Result of valid input should not be None') failure_result, result = er.handle_error_by_returning_tuple('a') self.assertIs(failure_result, False, 'Invalid input should not be successful') def test_filelike_objects_are_closed_on_exception(self): filelike_object = FileLike(fail_something=True) with self.assertRaisesWithMessage(Exception): er.filelike_objects_are_closed_on_exception(filelike_object) self.assertIs(filelike_object.is_open, False, 'filelike_object should be closed') self.assertIs(filelike_object.was_open, True, 'filelike_object should have been opened') self.assertIs(filelike_object.did_something, True, 'filelike_object should call do_something()') def test_filelike_objects_are_closed_without_exception(self): filelike_object = FileLike(fail_something=False) er.filelike_objects_are_closed_on_exception(filelike_object) self.assertIs(filelike_object.is_open, False, 'filelike_object should be closed') self.assertIs(filelike_object.was_open, True, 'filelike_object should have been opened') self.assertIs(filelike_object.did_something, True, 'filelike_object should call do_something()') # Utility functions def assertRaisesWithMessage(self, exception): return self.assertRaisesRegex(exception, r".+") if __name__ == '__main__': unittest.main()
Java
UTF-8
269
2.734375
3
[]
no_license
package training; public class Parser { public static void addToInt(int x, int y){ x = x+y; } public static void main(String[] args) { int a = 15; int y = 10; Parser.addToInt(a, y); System.out.println(a); } }
Python
UTF-8
4,589
2.796875
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- """ Plot frame differences and print YouTube Video IDs @author: ghowa """ import sys import scipy.stats import pylab import guess_language from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() def main(argv=None): """ Main function """ if argv is None: argv = sys.argv points = [] labels = [] points_labels = [] title_labels = dict() lang_labels = dict() type_labels = dict() type_file = open('../youTubeData/video_type', "r") type_line = type_file.readline() while not type_line == "": type_labels[type_line.split(";")[0]] = type_line.split(";")[1].strip() type_line = type_file.readline() lang_file = open('../youTubeData/manually_recognized', "r") lang_line = lang_file.readline() while not lang_line == "": lang_labels[lang_line.split(";")[0]] = lang_line.split(";")[1].strip() lang_line = lang_file.readline() title_file = open("../youTubeData/all_frames_stats_title", "r") line = " " manual = 0 while not line == "": line = title_file.readline() lbl = line.strip() # .lower().replace("stepan bandera","en") title = title_file.readline() title_labels[lbl] = title title_lang = guess_language.guessLanguage(strip_tags(title)) desc = title_file.readline() try: desc.split("No description available")[1] desc = "" except IndexError: pass desc_lang = guess_language.guessLanguage(strip_tags(desc)) line = title_file.readline() lang = guess_language.guessLanguage( strip_tags(title) + strip_tags(desc)) if lbl in lang_labels: print lbl, " found" continue print lbl, " not found" if lang in ['uk', 'ru', 'pl', 'en']: lang_labels[lbl] = lang else: manual += 1 print "------------------------------------------------------------" print title_lang, desc_lang print title print desc print "------------------------------------------------------------" l = raw_input("which language? ") lang_labels[lbl] = l print manual, " manually recognized" lang_file.close() lang_file_content = "" print lang_labels for key in lang_labels.keys(): lang_file_content += key + ";" + lang_labels[key] + "\r\n" print lang_file_content lang_file = open('../youTubeData/manually_recognized', "w") lang_file.write(lang_file_content) lang_file.close() text_file = open('../youTubeData/all_frames_stats', "r") line = " " counter = 0 while not line == "": line = text_file.readline() counter = counter + 1 try: values = map(float, line.split('\r\n')[0].split(';')[1:]) label = line.split(';')[0] labels.append(label) size, min_max, mean, variance, skew, kurt = scipy.stats.describe( values) # throw out vids under 20 seconds if size < 20: print "video too short: ", label continue # cut min variance at 0.001, otherwise the plot gets quite # distorted if variance < 0.001: variance = 0.001 except ValueError: print "error calculating stats for ", label continue point = [mean, variance] points.append(point) points_labels.append(label) print counter, " lines read." print "number of labels ", str(len(labels)) print "number of labels ", str(len(lang)) pylab.show() pylab.xlabel('Mean') pylab.ylabel('Variance') # pylab.yscale("log") pylab.title("Frame Likenesses of Bandera Youtube Clips") pylab.plot(*zip(*points), marker='o', color='w', ls='') counter = 0 for label in points_labels: pylab.annotate(label, points[counter]) counter += 1 figure = pylab.gcf() figure.set_size_inches( figure.get_size_inches()[0] * 5, figure.get_size_inches()[1] * 5) figure.savefig('video_labels.png', bbox_inches='tight') if __name__ == "__main__": sys.exit(main())
Markdown
UTF-8
5,078
2.703125
3
[]
no_license
## 2019.7.19 字节跳动一面 :turtle: 1. 介绍项目。 2. Redis 缓存刚删除,来了很大流量读取订单信息(直接打数据库上),怎么处理? 面试官:不删缓存,先减缓存中的数量,然后每100ms同步一次数据库。(透过缓存的请求遇到并发更改失败怎么办?只能把缓存中的数量调得比实际大一些,具体看乐观锁失败的比例,允许少量数据不一致)。 3. 一致性hash算法主要解决了什么问题?(数据均匀分布,容错性) 4. MySQL 引擎,与MyISAM的区别。 B+树, B树区别。 5. 秒杀场景中怎么迅速通知用户失败或者是成功?(市面上也有不立即通知成功的,跑小人排队那种情况) 面试官:……….. 6. 如果几千万流量同时访问一个热 Key 怎么办?集群变单机,单机炸了怎么处理?(缓存击穿问题,分布式锁),[布隆过滤器](https://www.cnblogs.com/rjzheng/p/8908073.html) 如果能预判热点 Key 是什么,可以预先将这些 Key 放到前端各个 JVM 缓存里面,减轻 Redis 的压力。 如果无法预判,可以使用基于 storm 的大数据流处理实时预判热点 Key。 [20W 流量同时访问一个热 Key](https://www.geek-share.com/detail/2769605901.html) 7. 2000W高考成绩排序,O(n)复杂度。(HashMap,计数排序) 8. 链表加法。 ## 2019.7.23 字节跳动二面 :bug: 1. 项目介绍 2. 限流算法有哪几种?Token怎么产生的?对比漏桶算法优点? Token 的数量是根据系统的负载来设定的。对比漏铜算法的优点是能支持突发流量。 3. 4. Redis怎么保证高可用? 5. kafka怎么保证消费的时序性? 6. SQL语句,id, name, sex, age, city等字段,怎么建索引?查询男性当中平均年龄最大的城市。 ```sql CREATE table findMaxAvgAgeCity( id int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', name char(20) NOT NULL COMMENT '名称', sex char(20) NOT NULL COMMENT 'sex', age int(11) NOT NULL COMMENT 'age', city char(20) NOT NULL COMMENT 'city', PRIMARY KEY (id), KEY idx_sex(sex), KEY idx_city(city) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='table for find maxmale's avr of city'; INSERT INTO findMaxAvgAgeCity (name, sex, age, city) VALUES ('name1', 'male', 40, 'chengdu'), ('name2', 'male', 30, 'chengdu'), ('name3', 'male', 40, 'beijing'), ('name4', 'male', 50, 'beijing'), ('name5', 'male', 40, 'shenzhen'), ('name6', 'male', 40, 'shenzhen'), ('name7', 'female', 40, 'chengdu'); SELECT city FROM findMaxAvgAgeCity WHERE sex = 'male' GROUP BY city ORDER BY AVG(age) DESC limit 1; ``` 7. 二叉树,蛇形遍历。 ```java /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { Deque<TreeNode> deque = new LinkedList<>(); public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> retList = new ArrayList<>(); if (pRoot == null) { return retList; } int levelNum = 0; boolean flag = false; deque.add(pRoot); while (!deque.isEmpty()) { levelNum = deque.size(); ArrayList<Integer> list = new ArrayList<>(); while (levelNum > 0) { if (flag) { TreeNode node = deque.pollLast(); list.add(node.val); // 先放右子节点 if (node.right != null) deque.addFirst(node.right); if (node.left != null) deque.addFirst(node.left); } else { TreeNode node = deque.pollFirst(); list.add(node.val); if (node.left != null) deque.addLast(node.left); if (node.right != null) deque.addLast(node.right); } levelNum--; } flag = !flag; if (list.size() > 0) { retList.add(list); } } return retList; } } ``` ## 2019.8.19 美团二面 1. 大流量场景怎么保证 Redis 高可用? 2. Redis 热点数据怎么处理? 3. 死锁怎么产生和避免? 4. 数据库中死锁怎么产生?怎么解决?写条死锁的 sql 语句。 5. 分布式限流怎么做的?手写基于 Java 的限流伪代码。 6. 分布式锁。 7. B+树原理。 8. 数据库慢查询优化。 9. ThreadLocal 了解吗? 10. 强引用和弱引用。 11. volatile 关键字。 12. GC 中 CMS 收集器有哪几个步骤。 13. 数据库,表 T,学生名字,课程名称,分数。查出平均分大于80的学生名字。HAVING 和 WHERE 的区别。 14. 小名先往北走10公里,再往东走40公里,再往南走10公里,求地球上所有满足条件的点。
Python
UTF-8
544
3.21875
3
[]
no_license
import sqlite3 import pandas as pd dbpath = 'test.sqlite' conn = sqlite3.connect(dbpath) while True: print('과일명 ?') fruit = input() if fruit=='x': break print('가격은 ?') price = int(input()) sql = "insert into items(name, price) values(?,?)" cur = conn.cursor() cur.execute(sql,(fruit, price)) conn.commit() sql2 = "select * from items" cur.execute(sql2) list = [] items = cur.fetchall() for i in items: list.append(i) df = pd.DataFrame(list, columns=['아이디','과일명','가격'])
Java
UTF-8
361
1.984375
2
[]
no_license
package com.practice.springJPAMongo.entity; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Data @Document(value="student") public class Student { @Id private String id; private String firstName; private String lastName; private String grade; }
C
UTF-8
424
3.234375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { printf("Hello world!\n"); int numar; int max =-1000000; int cont; do{ scanf("%d", &numar); if(numar == -1) continue; cont++; if(numar>max) max=numar; }while(numar != -1); if (cont) printf("Cel mai mare numar este %d.\n", max); else printf("Glumesti? Nu a-ti introdus niciun numar.\n"); return 0; }
C++
UTF-8
263
2.640625
3
[]
no_license
#ifndef MAN #define MAN #include "iostream" #include "Person.h" using namespace std; class Man:public Person { public: Man(string name):Person(name) { } void goHome() { cout<<"Man:"; Person::goHome(); } }; #endif // MAN
Markdown
UTF-8
1,450
2.640625
3
[ "MIT" ]
permissive
--- layout: page title: Identifying Airplane Parts for Aeronautical Engineering subtitle: Case Study at Greater Brighton Metropolitan College permalink: /case-studies/aeronautical-engineering categories: [case_studies] --- <a data-fancybox data-type="iframe" href="https://www.thinglink.com/mediacard/1065618713442516995"> ![Identifying Airplane Parts for Aeronautical Engineering](/images/case-studies/aeronautical-engineering.jpg "Identifying Airplane Parts for Aeronautical Engineering") </a> *Click the image to launch example content* The aeronautics workshop at GBMC contains a large selection of specialist equipment that students need to become familiar with in a short period of time. The team saw the potential to take immersive 360o videos of tools and part in operation as both a student induction activity and as a regular refresher throughout their programme. Each tool or part was capture by the learning technology team and current students. Wide-angle photos of the workshops, garages and other practical areas were also captured. All of this content is currently being put into a virtual tour using ThingLink. Like with previous trials, the biggest challenge was getting the virtual tours to work effectively on virtual reality headsets. Head-mount VR has limited interactivity. Since the virtual tour was designed for browsers, the resources worked better as an immersive website accessed from the colleges digital classroom.
Python
SHIFT_JIS
1,063
2.953125
3
[ "Unlicense" ]
permissive
# ABC154e def main(): import sys import math input = sys.stdin.readline sys.setrecursionlimit(10 ** 6) # ċA֐gȂPypyŏo n = int(input()) ns = str(n) k = int(input()) keta = len(ns) if keta < k: print(0) exit(0) # dp[i+1][smaller][j]=iڂ܂łŁAtOsmallerA0̌j dp = [[[0]*(keta+1) for i in range(2)] for j in range(keta + 1)] dp[0][0][0] = 1 for i in range(keta): for smaller in range(2): for j in range(i+1): for x in range(10 if smaller == 1 else int(ns[i])+1): # if i == 0 and x == 0: # continue dp[i + 1][1 if smaller == 1 or x < int(ns[i]) else 0][j if x != 0 else j+1] += dp[i][smaller][j] # print(dp) # print(dp[keta][0][keta-k]) #print(dp[keta][1][keta - k]) print(dp[keta][0][keta-k]+dp[keta][1][keta - k]) if __name__ == '__main__': main()
C#
UTF-8
3,414
3.015625
3
[]
no_license
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; namespace Gdp_problem { public class Program { private static string convertJsonPath = "../../../../data/convertcsv.json"; private static string outputPath = "../../../../../actual_output.json"; private static Dictionary<string, string> Dict() { var dict = new Dictionary<string, string>(); if(File.Exists(convertJsonPath)) { using (StreamReader file = File.OpenText(convertJsonPath)) using (JsonTextReader reader = new JsonTextReader(file)) { JToken o2 = JToken.ReadFrom(reader); foreach(var i in o2) { dict.Add((string)i["Country"], (string)i["Continent"]); } } } return dict; } public static string FileNot() { return "not found the file"; } public static void GdpSol() { List<string[]> s = new List<string[]>(); using (var r = new StreamReader("../../../../data/datafile.csv")) { while (!r.EndOfStream) { string line = r.ReadLine(); var res = (line.Replace("\"", "")).Split(','); s.Add(res); /*Console.WriteLine(res);*/ } /* foreach (var items in s)s { Console.WriteLine($"{items[0]} {items[4]} {items[7]}"); }*/ r.Close(); var abc = Dict(); // Console.WriteLine(abc); var result = new Dictionary<string, Dictionary<string,decimal>> (); foreach(var x in s) { if(abc.ContainsKey(x[0])) { string continent = abc[x[0]]; if (result.ContainsKey(continent)) { result[continent]["POPULATION_2012"] += Decimal.Parse(x[4]); result[continent]["GDP_2012"] += Decimal.Parse(x[7]); } else { result[continent] = new Dictionary<string, decimal>(); result[continent].Add("GDP_2012", Decimal.Parse(x[7])); result[continent].Add("POPULATION_2012", Decimal.Parse(x[4])); } } else { } } /* foreach(var items in result) { Console.WriteLine($"{items.Key}"); foreach(var item in items.Value) { Console.WriteLine($"{item.Value} {item.Key}"); } }*/ File.WriteAllText(outputPath, JsonConvert.SerializeObject(result)); } } static void Main(string[] args) { GdpSol(); //Console.WriteLine(Directory.GetCurrentDirectory()); } } }
Ruby
UTF-8
370
2.640625
3
[]
no_license
class Product < ActiveRecord::Base has_many :orders #Product model has_many orders--because many orders have the same product on them has_many :comments #Comments model has_many comments--because one product can have many comments or reviews validates :name, presence: true def average_rating comments.average(:rating).to_f end end
Java
UTF-8
519
2.34375
2
[]
no_license
package it.iad2.dto4; public class RichiediMessaggiDto { private String sessione; public RichiediMessaggiDto() { } public RichiediMessaggiDto(String sessione) { this.sessione = sessione; } public String getSessione() { return sessione; } public void setSessione(String sessione) { this.sessione = sessione; } @Override public String toString() { return "RichiediMessaggiDto{" + "sessione=" + sessione + '}'; } }
Python
UTF-8
873
3.625
4
[]
no_license
import re def password(value): flag = 0 while True: if len(value) < 9: print('password length should be atleast 8 character long!') flag = 1 break elif re.search('[A-Z]',value) is None: print("password should have atleast one character capital") flag = 1 break elif re.search('[0-9]',value) is None: print("There should be atleast one nnumber to make your password Strong") flag = 1 break elif re.search('[!@#$%^&*]',value) is None: print("there should be atleast one special character ' ! @ # $ % ^ & * ' ") flag = 1 break else: flag = 0 break if flag == 0: print("correct password") # user = input("enter the password: ") # password(user)
Python
UTF-8
496
3.484375
3
[ "MIT" ]
permissive
# Runtime: 20 ms, faster than 98.27% of Python3 online submissions for Pascal's Triangle II. # Memory Usage: 13.9 MB, less than 7.69% of Python3 online submissions for Pascal's Triangle II. class Solution: def getRow(self, rowIndex: int) -> List[int]: '''memory-efficient DP: Time O(k^2) Space O(k)''' ans = [1] * (rowIndex + 1) for row in range(2, rowIndex + 1): for col in range(row - 1, 0, -1): ans[col] += ans[col-1] return ans
Java
UTF-8
2,392
3.3125
3
[]
no_license
package bazam; import java.util.*; /** * An aggregation of all the match statistics, mapping trackID's to their respective histograms of matches. * @author Brook * */ public class MatchResults { /** The file matched for this MatchResults */ private String fileMatched; /** The results of the matching process. The key is the id of the song that matches, the histogram is the count at particular time * intervals */ private Map <TrackID,Histogram> matchResults; /** * Constructs a new Match Results object for a file that is to be matched. * @param fileMatched The file that was matched. */ public MatchResults(String fileMatched) { matchResults = new HashMap<TrackID,Histogram>(); this.fileMatched = fileMatched; } /** * Increments the count on a particular index. * @param index The index of probe query. * @param dataPoints The list of data points that was mapped to an identical probe. */ public void matchTally(int index, ArrayList<ProbeDataPoint> dataPoints) { for(ProbeDataPoint dataPoint : dataPoints){ TrackID id = dataPoint.getTrackID(); int indexOfMatch = dataPoint.getIndex(); int diff = index - indexOfMatch;//the index difference between the probe to match and the matching probe. if(!matchResults.containsKey(id)){//matching song not yet in map Histogram h = new Histogram(); h.matchAt(diff); matchResults.put(id, h); } else {//the specific song already has a match Histogram h = matchResults.get(id); h.matchAt(diff); matchResults.put(id, h); } } } /** * Gets the name of the file queried to be matched. * @return The name of the file queried. */ public String getFileMatched() { return fileMatched; } /** * Facilitates iterating over the entire match results object. * @return An iterator. */ public Iterator<TrackID> getContentsIterator() { return matchResults.keySet().iterator(); } /** * Prints out contents in matchResults */ public void print() { for(TrackID id : matchResults.keySet()){ int ID = id.getIntID(); Histogram h = matchResults.get(id); System.out.print("TrackID: " + ID + " "); h.print(); } } /** * Get a histogram at the specified index key. * @param id The TrackID index. * @return A histogram at the id. */ public Histogram getHistogramAt(TrackID id) { return matchResults.get(id); } }
C++
UTF-8
1,392
3.21875
3
[]
no_license
#include <gtest/gtest.h> #ifdef __cplusplus extern "C" { #endif #include "libft.h" #ifdef __cplusplus } #endif class RemoveListNodeTest: public ::testing::Test { protected: t_list list; virtual void SetUp() { init_list(&list); } virtual void TearDown() { clear_list(&list); } }; TEST_F(RemoveListNodeTest, empty) { pop_list_node(0, &list); pop_list_node(1, &list); pop_list_node(2, &list); ASSERT_EQ((int)list.length, 0); ASSERT_EQ((long)list.head, NULL); ASSERT_EQ((long)list.tail, NULL); } TEST_F(RemoveListNodeTest, one_exist) { char *data = strdup("hello"); push_list_node(data, &list); pop_list_node(0, &list); ASSERT_EQ((int)list.length, 0); ASSERT_EQ((long)list.head, NULL); ASSERT_EQ((long)list.tail, NULL); } TEST_F(RemoveListNodeTest, multi_exist) { char *d1 = strdup("hello"); char *d2 = strdup("world"); char *d3 = strdup("foo"); push_list_node(d1, &list); push_list_node(d2, &list); push_list_node(d3, &list); pop_list_node(1, &list); ASSERT_EQ((int)list.length, 2); ASSERT_EQ((long)list.head->data, (long)d1); ASSERT_EQ((long)list.tail->data, (long)d3); pop_list_node(1, &list); ASSERT_EQ((int)list.length, 1); ASSERT_EQ((long)list.head->data, (long)d1); ASSERT_EQ((long)list.head, (long)list.tail); pop_list_node(0, &list); ASSERT_EQ((int)list.length, 0); ASSERT_EQ((long)list.head, NULL); ASSERT_EQ((long)list.tail, NULL); }
TypeScript
UTF-8
2,701
2.765625
3
[ "MIT" ]
permissive
import Phaser from "phaser"; import Monster from "./monster"; const MIN_SPEED = 200; const DRAG = 1000; const INIT_SPEED = 1500; class Spear extends Phaser.Physics.Arcade.Sprite { id: string; _angle: number; _velocity: any; _initSpeed: number; _maxSpeed: number; _wallHit: boolean; _monstersHit: Phaser.GameObjects.Group sfx: any; constructor(scene : Phaser.Scene, x, y, id, angle = 0) { console.log("SPEAR:", x, y, angle); super(scene, x, y, "spear", 0); this.id = id; this._angle = angle; this._initSpeed = INIT_SPEED; this._maxSpeed = 6000; this._wallHit = false; this._monstersHit = scene.add.group() this.sfx = this.scene.sound.add('spear'); } setup(scene: Phaser.Scene, group: Phaser.GameObjects.Group) { scene.physics.world.enable(this); scene.add.existing(this); group.add(this); this.setSize(50, 50); this.setDisplaySize(40, 40); this.sfx.play() if (this.body) { const body = this.body as Phaser.Physics.Arcade.Body; // this.body.setSize(this.), 40); body.rotation = (this._angle / (2 * Math.PI)) * 360; var speed = this._initSpeed; body.setVelocity(speed * Math.cos(this._angle), speed * Math.sin(this._angle)); // body.setAcceleration(accel * Math.cos(this._angle), accel * Math.sin(this._angle)) body.setDrag(Math.abs(DRAG * Math.cos(this._angle)), Math.abs(DRAG * Math.sin(this._angle))); this._velocity = body.velocity; body.setMaxSpeed(this._maxSpeed); // body.drag.set(1, 0); } } onWallHit() { if (this._wallHit) return; this._wallHit = true; this.scene.cameras.main.shake(25, 0.01, true); } onHitMonster(m: Monster) { if (this._monstersHit.contains(m)) return; this._monstersHit.add(m); this.scene.cameras.main.shake(20, 0.02, false); } update() { if (this.body) { const body = this.body as Phaser.Physics.Arcade.Body; body.rotation = (this._angle / (2 * Math.PI)) * 360 + 90; if (this._wallHit) { body.setVelocityX(0); body.setVelocityY(0); body.setImmovable(); } else { if (body.speed < MIN_SPEED) { body.setVelocityX(MIN_SPEED * Math.cos(this._angle)); body.setVelocityY(MIN_SPEED * Math.sin(this._angle)); } this._velocity = body.velocity; } this._monstersHit.setXY(body.position.x, body.position.y) } } _addAnimations(anims, frameRate = 60, loop = false) { // for (var i = 0, l = anims.length; i < l; ++i) { // let anim = anims[i]; // // this.animations.add(anim.name, anim.frames, frameRate, loop); // } } } export default Spear;
Java
UTF-8
2,282
2.59375
3
[]
no_license
package net.calzoneman.TileLand.gui; import net.calzoneman.TileLand.ResourceManager; import net.calzoneman.TileLand.gfx.Font; import net.calzoneman.TileLand.gfx.Screen; import net.calzoneman.TileLand.util.Delegate; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.newdawn.slick.Color; public class PauseMenu extends GUIMenu { static final Color backgroundColor = new Color(64, 64, 64); static final String pauseMessage = "GAME PAUSED"; public PauseMenu() { super(); init(0, 0, Display.getWidth(), Display.getHeight()); } @Override public void init(int x, int y, int width, int height) { GUIContainer container = new GUIContainer(Display.getWidth()/2 - 320, Display.getHeight()/2 - 240, 640, 480); container.addChild("title", new GUIImage(container.getWidth()/2 - 256, 50, ResourceManager.TITLE_TEXTURE)); GUIButton backBtn = new GUIButton(170, 260, 300, "Return to game"); backBtn.setClickHandler( new Delegate<GUIContainer, Void>() { @Override public Void run(GUIContainer param) { MenuManager.getMenuManager().goBack(); return null; } }); container.addChild("backbtn", backBtn); GUIButton quitBtn = new GUIButton(170, 300, 300, "Quit"); quitBtn.setClickHandler( new Delegate<GUIContainer, Void>() { @Override public Void run(GUIContainer param) { MenuManager.getMenuManager().openMenu("mainmenu"); return null; } }); container.addChild("quitbtn", quitBtn); container.setParent(this); addChild("container", container); } @Override public void reInit(int x, int y, int width, int height) { children.clear(); init(x, y, width, height); } @Override public void handleInput() { super.handleInput(); //if(keys[Keyboard.KEY_ESCAPE]) { // MenuManager.getMenuManager().goBack(); //} } @Override public void render(Screen screen) { screen.renderFilledRect(0, 0, Display.getWidth(), Display.getHeight(), backgroundColor); for(GUIComponent child : children.values()) { child.render(screen); } int sx = Display.getWidth() / 2 - Font.getWidthLarge(pauseMessage) / 2; int sy = Display.getHeight() / 2 - Font.getHeightLarge(pauseMessage) / 2; Font.drawLarge(pauseMessage, screen, sx, sy, backgroundColor); } }
PHP
UTF-8
2,645
2.515625
3
[]
no_license
<?php /** * Base module helper. * * PHP Version 5 * * @category Class * @package Symantec_NortonShoppingGuarantee * @author Symantec Corporation * @copyright 2016 Symantec Corporation, All Rights Reserved. */ /** * Class declaration * * @category Class_Type_Helper * @package Symantec_NortonShoppingGuarantee * @author Symantec Corporation */ class Symantec_NortonShoppingGuarantee_Helper_Data extends Mage_Core_Helper_Abstract { const EDITION_COMMUNITY = 'Community'; const EDITION_ENTERPRISE = 'Enterprise'; const EDITION_PROFESSIONAL = 'Professional'; /** * Get the Magento version number. * * @return string */ public function getAppVersion() { return Mage::getVersion(); } /** * Get the merchant hash. * * @return string|boolean */ public function getHash() { if ( ($hash = Mage::helper('core')->decrypt(Mage::getStoreConfig('nsg_options/nsg_config/nsg_hash'))) ) { return $hash; } return false; } /** * Get the store number. * * @return string|boolean */ public function getStoreNumber() { if ( ($storeNumber = Mage::getStoreConfig('nsg_options/nsg_config/nsg_shop')) ) { return $storeNumber; } return false; } /** * Determine whether the merchant hash is set. * * @return boolean */ public function hasHash() { if (Mage::getStoreConfig('nsg_options/nsg_config/nsg_hash')) { return true; } return false; } /** * Determine whether a store number is available. * * @return boolean */ public function hasStoreNumber() { if (Mage::getStoreConfig('nsg_options/nsg_config/nsg_shop')) { return true; } return false; } /** * Determine whether the feature is enabled. * * @return boolean */ public function isEnabled() { return $this->hasHash() ? true : false; } /** * Perform an edition check. * * @return string */ public function register() { $modules = (array) Mage::getConfig()->getNode('modules')->children(); if (isset($modules['Enterprise_Pci']) && $modules['Enterprise_Pci']->active == 'false') { return self::EDITION_PROFESSIONAL; } else if (isset($modules['Enterprise_Enterprise'])) { return self::EDITION_ENTERPRISE; } return self::EDITION_COMMUNITY; } }
Shell
UTF-8
543
3.609375
4
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env bash SCRIPT="`pwd`/getPackageInfo.py" CLASSFILE="`pwd`/ROSGenMsg" # on my machine, messages are located in: echo "// This is an auto-generated file." >> "$CLASSFILE.h" echo "#import \"ROSMsg.h\"" > "$CLASSFILE.h" echo "// This is an auto-generated file." >> "$CLASSFILE.m" echo "#import \"$CLASSFILE.h\"" > "$CLASSFILE.m" pushd /opt/ros/groovy/ msgs=`find . -name \*\.msg` a="" for m in $msgs; do a="$a `$SCRIPT $m $CLASSFILE`" #echo $a #./genClass.py < $a done popd echo $a | ./prettyPrintClasses.py
PHP
UTF-8
2,242
2.53125
3
[]
no_license
<?php session_start(); if (isset($_SESSION['login_valid'])&&(isset($_SESSION['login_name']))): header("Location: panel.php"); endif; $startChecking=true; $con=null; if (isset($_POST['submit_login'])): if (isset($_POST['input_box'])): $input = $_POST['input_box']; for ($i=0; $i<count($input); $i++): if ($input[$i]==null||$input[$i]==NULL||$input[$i]=="null"||$input[$i]==""||$input[$i]==''): $startChecking=false; endif; endfor; if ($startChecking): //========================================== DB CONNECTION ==================================== include_once '../../assets/class/dbConnection.php'; //========================================== DB CONNECTION ==================================== if (mysqli_connect_errno()): $message = "Sorry we are on maintenance right now, please comeback again in a few hours, Thank you"; else: $result = mysqli_query($con, "SELECT * FROM t_cms"); if ($result!=null||$result!=NULL): while ($row = mysqli_fetch_array($result)): if (($input[0]==$row['username'])&&($input[1]==$row['password'])): $_SESSION['login_valid']=true; $_SESSION['login_name']=$row['username']; $_SESSION['username'] = $row['username']; $_SESSION['password'] = $row['password']; header("Location: panel.php"); endif; endwhile; endif; endif; endif; endif; endif; ?> <html> <head> <title>Control Panel</title> </head> <body> <form method="post"> <table width="80%" align="center"> <tr> <td> Username </td> </tr> <tr> <td> <input type="text" value="" name="input_box[]" placeholder="Username" style="width: 100%" maxlength="50"/> </td> </tr> <tr> <td> Password </td> </tr> <tr> <td> <input type="password" value="" name="input_box[]" placeholder="Password" style="width: 100%" maxlength="50"/> </td> </tr> <tr> <td> <button id="submit_login" name="submit_login" value="Submit" style="width: 100%">Login</button> </td> </tr> </table> </form> </body> </html> <?php if ($con!=null||$con!=NULL): mysqli_close($con); endif; ?>
C++
UTF-8
23,453
2.5625
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "Server.h" #include "SocketWrappers.h" //#include <WinBase.h> #include <string> #include <thread> #include <iostream> #include <string.h> #include <iterator> #include <fstream> #pragma comment(lib, "Ws2_32.lib") #pragma warning(disable: 4996) //using namespace std; using std::cerr; using std::cout; using std::endl; using std::string; // initialize static memebers. WSAEVENT Server::EventArray[WSA_MAXIMUM_WAIT_EVENTS]; LPSOCKET_INFORMATION Server::SocketArray[WSA_MAXIMUM_WAIT_EVENTS]; CRITICAL_SECTION Server::CriticalSection; DWORD Server::EventTotal = 0; std::map<SOCKET, ClientInformation> Server::mapClient; /*-------------------------------------------------------------------------- -- FUNCTION: Server -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Comment Added -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: Server () -- -- NOTES: -- Ctor --------------------------------------------------------------------------*/ Server::Server() :isStreaming(false) { initializeWSA(); // load map of songs sockUDP = makeWSASocket(SOCK_DGRAM, 0); } /*-------------------------------------------------------------------------- -- FUNCTION: Server -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Comment Added -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: Server () -- -- NOTES: -- Dtor --------------------------------------------------------------------------*/ Server::~Server() { if (isStreaming) stopStream(); closeWSA(); GlobalFree(SocketInfo); } /*-------------------------------------------------------------------------- -- FUNCTION: startStream -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Comment added -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: void startStream () -- desc -- -- RETURNS: -- RETURN -- -- NOTES: -- Starts the UDP Streaming of songs. -- creates a thread for packetizatio and a thread for streaming -- **** make sure the Library is loaded when calling start stream ! --------------------------------------------------------------------------*/ void Server::startStream() { // get file name library isStreaming = true; // make threads for streaming 1 for pack , 1 for send packThread = streamPack(); sendThread = streamSend(); return; } /*-------------------------------------------------------------------------- -- FUNCTION: loadLibrary -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Commented the code -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: loadLibrary (const char * libpath) -- const char * libpath : The path the the directory of the library -- The deafult for the path is in server.h -- -- -- NOTES: -- This function loads all the mp3 files found in the folder -- * Future versions may also extend to .wav , .flac , etc . --------------------------------------------------------------------------*/ void Server::loadLibrary(const char * libpath) { // look for mp3 files only static const char * rgx = "*.mp3"; // if library has already been loaded, if (playlist.size() != 0) { if (isStreaming) //you must stop streaming first! { cerr << "Streaming must stop before loading library." << endl; return; } else { playlist.clear(); } } int sid = 0; // song id assiocated with map string path = ""; (path = libpath).append(rgx); WIN32_FIND_DATA winfd; HANDLE hFind = FindFirstFile(path.c_str(), &winfd); if (hFind != INVALID_HANDLE_VALUE) { do { // if it is a file and not a directory if (!(winfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { // add file path and name of file to map (playlist[sid++] = libpath).append(winfd.cFileName); } } while (FindNextFile(hFind, &winfd)); FindClose(hFind); } } /*-------------------------------------------------------------------------- -- FUNCTION: stopStream -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Commented -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: void stopStream () -- -- -- RETURNS: -- -- NOTES: -- called when the streaming wants to be aborted entirely ( Note, this is not a pause ) --------------------------------------------------------------------------*/ void Server::stopStream() { isStreaming = false; //join thread stream Send Loop sendThread.join(); packThread.join(); //join thread Stream Pack Loop } /*-------------------------------------------------------------------------- -- FUNCTION: streamPackLoop -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Comment added -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: void streamPackLoop () -- -- -- NOTES: -- this is a the thread loop for -- thread will exit when somone stops streaming -- Continuously loop through the map of songs ( loop back play ) -- and packetize each song -- Once the cBuff has the last packet of the song, the next song will -- be packetized. --------------------------------------------------------------------------*/ void Server::streamPackLoop() { while (isStreaming) { //continuously loop through the map of songs for (std::map<int, std::string>::iterator it = playlist.begin(); it != playlist.end(); ++it) { packer.makePacketsFromFile(it->second.c_str()); long ttl = packer.getTotalPackets(); for (long i = 0; i < ttl; ++i) { if (!isStreaming) break; cbuff.push_back(packer.getNextPacket()); } } } } /*-------------------------------------------------------------------------- -- FUNCTION: streamSendLoop -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Comment -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: streamSendLoop () -- -- NOTES: -- This is the thread loop for the streaming. -- the loop will exit when the flag exits -- the initial 21K of a song is sent every 2 milliseconds -- after that, the data slows down at sending rate that matches the speed -- of streaming --------------------------------------------------------------------------*/ void Server::streamSendLoop() { sockaddr_in addr; char * pstr; int bsent; const long long initialLoadInterval = -20000LL; // 2 MS const long long initialLoadSize = 21; const long long regularLoadInterval = -1000000LL; // 100 MS memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; inet_pton(AF_INET, MCAST_IP, &(addr.sin_addr.s_addr)); addr.sin_port = htons(PORTNO); while (isStreaming) { //get info of next song long ttl = packer.getTotalPackets(); long lastpsz = packer.getLastPackSize(); timer.cancelTimer(); timer.setTimer(initialLoadInterval); //end the song for (long i = 0; i < ttl; ++i) { if (!isStreaming) break; // if it is no longer the intial part of the song if (i == initialLoadSize) { // reset due time to regulkar mp3 rates timer.cancelTimer(); timer.setTimer(regularLoadInterval); } timer.resetTimer(); if (waitForTimer()) { pstr = cbuff.pop(); // get next pack if (!pstr) continue; bsent = sendto(sockUDP, pstr, BUFFSIZE, 0, (struct sockaddr *)&addr, sizeof(addr)); cout << "Bytes sent: " << bsent << "\n"; } } if (!isStreaming) break; pstr = cbuff.pop(); //send last pack if (pstr) bsent = sendto(sockUDP, pstr, lastpsz, 0, (struct sockaddr *)&addr, sizeof(addr)); cout << "Bytes sent: " << bsent << "\n"; } } /*-------------------------------------------------------------------------- -- FUNCTION: waitForTimer -- -- DATE: APR. 09, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/APR/09 - Comment -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: inline bool waitForTimer () -- desc -- -- RETURNS: -- boolean -- whether the timer object tiggered the event -- -- NOTES: -- a wait for event function wrapper -- that specifically waits for a timer object --------------------------------------------------------------------------*/ inline bool Server::waitForTimer() { if (WaitForSingleObject(timer.getTimer(), INFINITE) != WAIT_OBJECT_0) { printf("WaitForSingleObject failed (%d)\n", GetLastError()); return false; } return true; } /***************************************************************************** Jamies portion *****************************************************************************/ void Server::RunServer(SOCKET& serverSock) { char temp[STR_SIZE]; InitializeCriticalSection(&CriticalSection); if ((SocketInfo = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL) { sprintf_s(temp, STR_SIZE, "GlobalAlloc() failed with error %d", GetLastError()); Display(temp); return; } SocketInfo->BytesRECV = 0; SocketInfo->BytesSEND = 0; SocketInfo->PacketsRECV = 0; SocketInfo->DataBuf.len = BUF_SIZE; if (!initializeWSA()) return; // create a socket. if ((tcp_listen = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) return; struct sockaddr_in server; memset((char *)&server, 0, sizeof(struct sockaddr_in)); server.sin_family = AF_INET; server.sin_port = htons(g_port); server.sin_addr.s_addr = htonl(INADDR_ANY); // Accept connections from any client // Bind an address to the socket if ( bind(tcp_listen, (struct sockaddr *)&server, sizeof(server)) == -1) return; if (listen(tcp_listen, MAX_NUM_CLIENT) == SOCKET_ERROR) { sprintf_s(temp, STR_SIZE, "listen() failed with error %d", WSAGetLastError()); Display(temp); return; } /*if ((EventArray[0] = WSACreateEvent()) == WSA_INVALID_EVENT) { sprintf_s(temp, STR_SIZE, "WSACreateEvent() failed with error %d", WSAGetLastError()); Display(temp); return; } AcceptEvent = EventArray[0];*/ sprintf_s(temp, STR_SIZE, "Listen TCP port %d", g_port); Display(temp); std::thread threadAccept(&Server::AcceptFunc, this); threadAccept.detach(); std::thread workThread(&Server::WorkThread, this); workThread.detach(); } void Server::AcceptFunc() { int client_len; struct sockaddr_in client; char temp[STR_SIZE]; if ((AcceptEvent = WSACreateEvent()) == WSA_INVALID_EVENT) { printf("WSACreateEvent() failed with error %d\n", WSAGetLastError()); return; } EventTotal = 1; while (true) { client_len = sizeof(client); //SOCKET acceptedSocket; if ((AcceptSocket = accept(tcp_listen, (struct sockaddr *)&client, &client_len)) == INVALID_SOCKET) { sprintf_s(temp, STR_SIZE, "accept() failed with error %d", WSAGetLastError()); Display(temp); break; } /*std::thread workThread(&Server::WorkerThread, this, (LPVOID)AcceptEvent); workThread.detach();*/ char* acceptedClientIp = inet_ntoa(client.sin_addr); SocketInfo->Socket = AcceptSocket; sprintf_s(temp, STR_SIZE, "Socket number %d connected: IP=%s", (int)AcceptSocket, acceptedClientIp); Display(temp); SendInitialInfo(AcceptSocket, SocketInfo); // Mapping the accepted client. ClientInformation clientInformation; sprintf(clientInformation.ip, "%s", acceptedClientIp); sprintf(clientInformation.username, "%s", "Unknown"); mapClient[AcceptSocket] = clientInformation; if (WSASetEvent(AcceptEvent) == FALSE) { sprintf_s(temp, STR_SIZE, "WSASetEvent failed with error %d", WSAGetLastError()); Display(temp); return; } // completion routines EnterCriticalSection(&CriticalSection); // Create a socket information structure to associate with the accepted socket. if ((SocketArray[EventTotal] = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL) { sprintf_s(temp, STR_SIZE, "GlobalAlloc() failed with error %d\n", GetLastError()); Display(temp); return; } // Fill in the details of our accepted socket. SocketArray[EventTotal]->Socket = AcceptSocket; ZeroMemory(&(SocketArray[EventTotal]->Overlapped), sizeof(OVERLAPPED)); SocketArray[EventTotal]->BytesSEND = 0; SocketArray[EventTotal]->BytesRECV = 0; SocketArray[EventTotal]->DataBuf.len = BUF_SIZE; SocketArray[EventTotal]->DataBuf.buf = SocketArray[EventTotal]->Buffer; SocketArray[EventTotal]->index = EventTotal; if ((SocketArray[EventTotal]->Overlapped.hEvent = EventArray[EventTotal] = WSACreateEvent()) == WSA_INVALID_EVENT) { sprintf_s(temp, STR_SIZE, "WSACreateEvent() failed with error %d", WSAGetLastError()); Display(temp); return; } DWORD Flags = 0; DWORD RecvBytes; if (WSARecv(SocketArray[EventTotal]->Socket, &(SocketArray[EventTotal]->DataBuf), 1, &RecvBytes, &Flags, &(SocketArray[EventTotal]->Overlapped), WorkerRoutine) == SOCKET_ERROR) { if (WSAGetLastError() != ERROR_IO_PENDING) { sprintf_s(temp, STR_SIZE, "WSARecv() failed with error %d", WSAGetLastError()); Display(temp); return; } } EventTotal++; LeaveCriticalSection(&CriticalSection); // // Signal the first event in the event array to tell the worker thread to // service an additional event in the event array // if (WSASetEvent(AcceptEvent) == FALSE) { sprintf_s(temp, STR_SIZE, "WSASetEvent failed with error %d", WSAGetLastError()); Display(temp); return; } } } void Server::SendInitialInfo(SOCKET socket, LPSOCKET_INFORMATION SocketInfo) { for (const auto& entry : mapClient) { INFO_CLIENT infoClient; infoClient.header = PH_INFO_CLIENT; sprintf_s(infoClient.username, PACKET_STR_MAX, "%s", entry.second.username); sprintf_s(infoClient.ip, IP_LENGTH, "%s", entry.second.ip); SocketInfo->DataBuf.buf = (char*)&infoClient; SocketInfo->DataBuf.len = sizeof(INFO_CLIENT); SendTCP(socket, SocketInfo); } { INFO_SONG infoSong; infoSong.header = PH_INFO_SONG; infoSong.SID = 1; sprintf_s(infoSong.title, PACKET_STR_MAX, "%s", "Title of a song"); sprintf_s(infoSong.artist, PACKET_STR_MAX, "%s", "Artist of a song"); SocketInfo->DataBuf.buf = (char*)&infoSong; SocketInfo->DataBuf.len = sizeof(INFO_SONG); SendTCP(socket, SocketInfo); } } void Server::WorkThread() { DWORD Flags; LPSOCKET_INFORMATION SI; DWORD Index; DWORD RecvBytes; char temp[STR_SIZE]; // Save the accept event in the event array. EventArray[0] = AcceptEvent; while (TRUE) { if ((Index = WSAWaitForMultipleEvents(EventTotal, EventArray, FALSE, WSA_INFINITE, FALSE)) == WSA_WAIT_FAILED) { sprintf_s(temp, STR_SIZE, "WSAWaitForMultipleEvents failed %d", WSAGetLastError()); return; } // If the event triggered was zero then a connection attempt was made // on our listening socket. if ((Index - WSA_WAIT_EVENT_0) == 0) { WSAResetEvent(EventArray[0]); continue; } SI = SocketArray[Index - WSA_WAIT_EVENT_0]; WSAResetEvent(EventArray[Index - WSA_WAIT_EVENT_0]); // Create a socket information structure to associate with the accepted socket. Flags = 0; if (WSARecv(SI->Socket, &(SI->DataBuf), 1, &RecvBytes, &Flags, &(SI->Overlapped), WorkerRoutine) == SOCKET_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { sprintf_s(temp, STR_SIZE, "WSARecv() failed with error %d\n", WSAGetLastError()); Display(temp); return; } } sprintf_s(temp, STR_SIZE, "Recv from %d\n", (int)SI->Socket); Display(temp); } return; } DWORD WINAPI Server::WorkerThread(LPVOID lpParameter) { char temp[STR_SIZE]; DWORD Flags; LPSOCKET_INFORMATION SocketInfo; WSAEVENT EventArray[1]; DWORD Index; DWORD RecvBytes; // Save the accept event in the event array. EventArray[0] = (WSAEVENT)lpParameter; while (TRUE) { // Wait for accept() to signal an event and also process WorkerRoutine() returns. while (TRUE) { Index = WSAWaitForMultipleEvents(1, EventArray, FALSE, WSA_INFINITE, TRUE); if (Index == WSA_WAIT_FAILED) { printf("WSAWaitForMultipleEvents failed with error %d\n", WSAGetLastError()); return FALSE; } if (Index != WAIT_IO_COMPLETION) { // An accept() call event is ready - break the wait loop break; } } WSAResetEvent(EventArray[Index - WSA_WAIT_EVENT_0]); // Create a socket information structure to associate with the accepted socket. if ((SocketInfo = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL) { printf("GlobalAlloc() failed with error %d\n", GetLastError()); return FALSE; } // Fill in the details of our accepted socket. SocketInfo->Socket = AcceptSocket; ZeroMemory(&(SocketInfo->Overlapped), sizeof(WSAOVERLAPPED)); SocketInfo->BytesSEND = 0; SocketInfo->BytesRECV = 0; SocketInfo->DataBuf.len = DATA_BUFSIZE; SocketInfo->DataBuf.buf = SocketInfo->Buffer; Flags = 0; if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes, &Flags, &(SocketInfo->Overlapped), WorkerRoutine) == SOCKET_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { printf_s(temp, STR_SIZE, "WSARecv() failed with error %d\n", WSAGetLastError()); Display(temp); return FALSE; } } printf_s(temp, STR_SIZE, "Socket %d connected", (int)AcceptSocket); Display(temp); } return TRUE; } bool Server::SendTCP(SOCKET& clientSock, LPSOCKET_INFORMATION SocketInfo) { char temp[STR_SIZE]; ZeroMemory(&SocketInfo->Overlapped, sizeof(WSAOVERLAPPED)); SocketInfo->Overlapped.hEvent = WSACreateEvent(); if (WSASend(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &SocketInfo->BytesSEND, 0, &(SocketInfo->Overlapped), NULL) == SOCKET_ERROR) { if (WSAGetLastError() != ERROR_IO_PENDING) { sprintf_s(temp, STR_SIZE, "TCPControlWorker::SendToClient() WSASend() failed with: %d", WSAGetLastError()); Display(temp); return false; } if (WSAWaitForMultipleEvents(1, &SocketInfo->Overlapped.hEvent, FALSE, INFINITE, FALSE) == WAIT_TIMEOUT) { sprintf_s(temp, STR_SIZE, "TCPControlWorker::SendToClient timed out"); Display(temp); return false; } } DWORD flags; if (!WSAGetOverlappedResult(SocketInfo->Socket, &(SocketInfo->Overlapped), &SocketInfo->BytesSEND, FALSE, &flags)) { sprintf_s(temp, STR_SIZE, "TCPControlWorker::SendToClient overlappedresult error %d", WSAGetLastError()); return false; } sprintf_s(temp, STR_SIZE, "Sent %d bytes", SocketInfo->BytesSEND); Display(temp); return true; } void CALLBACK WorkerRoutine(DWORD Error, DWORD BytesTransferred, LPWSAOVERLAPPED Overlapped, DWORD InFlags) { char temp[STR_SIZE]; DWORD SendBytes, RecvBytes; DWORD Flags; // Reference the WSAOVERLAPPED structure as a SOCKET_INFORMATION structure LPSOCKET_INFORMATION SI = (LPSOCKET_INFORMATION)Overlapped; if (Error != 0) { sprintf_s(temp, STR_SIZE, "I/O operation failed with error %d", Error); Display(temp); } if (BytesTransferred == 0) { sprintf_s(temp, STR_SIZE, "Closing socket %d", static_cast<int>(SI->Socket)); Display(temp); } if (Error != 0 || BytesTransferred == 0) { auto found = Server::mapClient.find(SI->Socket); Server::mapClient.erase(found); if (closesocket(SI->Socket) == SOCKET_ERROR) { sprintf_s(temp, STR_SIZE, "closesocket() failed with error %d", WSAGetLastError()); } GlobalFree(SI); WSACloseEvent(Server::EventArray[SI->index]); // Cleanup SocketArray and EventArray by removing the socket event handle // and socket information structure if they are not at the end of the // arrays. EnterCriticalSection(&Server::CriticalSection); if ((SI->index) + 1 != Server::EventTotal) for (int i = SI->index; i < Server::EventTotal; i++) { Server::EventArray[i] = Server::EventArray[i + 1]; Server::SocketArray[i] = Server::SocketArray[i + 1]; } Server::EventTotal--; LeaveCriticalSection(&Server::CriticalSection); return; } // Check to see if the BytesRECV field equals zero. If this is so, then // this means a WSARecv call just completed so update the BytesRECV field // with the BytesTransferred value from the completed WSARecv() call. if (SI->BytesRECV == 0) { SI->BytesRECV = BytesTransferred; SI->BytesSEND = 0; } else { SI->BytesSEND += BytesTransferred; } if (SI->BytesRECV > SI->BytesSEND) { // Post another WSASend() request. // Since WSASend() is not gauranteed to send all of the bytes requested, // continue posting WSASend() calls until all received bytes are sent. ZeroMemory(&(SI->Overlapped), sizeof(WSAOVERLAPPED)); SI->DataBuf.buf = SI->Buffer + SI->BytesSEND; SI->DataBuf.len = SI->BytesRECV - SI->BytesSEND; if (WSASend(SI->Socket, &(SI->DataBuf), 1, &SendBytes, 0, &(SI->Overlapped), WorkerRoutine) == SOCKET_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { printf("WSASend() failed with error %d\n", WSAGetLastError()); return; } } } else { SI->BytesRECV = 0; SI->PacketsRECV++; // Now that there are no more bytes to send post another WSARecv() request. char temp[STR_SIZE]; if (SI->IsFile) { std::string recvFileData(SI->Buffer, BytesTransferred); size_t found = recvFileData.find("EndOfPacket"); if (found != std::string::npos) { SI->IsFile = false; SI->vecBuffer.push_back(recvFileData.substr(0, found)); fwrite(SI->Buffer, 1, found, SI->file); fclose(SI->file); sprintf_s(temp, STR_SIZE, "Save a song file: %s", SI->FileName.c_str()); Display(temp); } else { SI->vecBuffer.push_back(recvFileData); fwrite(SI->Buffer, 1, BytesTransferred, SI->file); } sprintf_s(temp, STR_SIZE, "default: length=%d", BytesTransferred); Display(temp); } else { int header; memcpy(&header, SI->Buffer, sizeof(int)); switch (header) { case PH_REQ_UPLOAD_SONG: { SI->IsFile = true; SI->vecBuffer.clear(); ReqUploadSong songData; memcpy(&songData, SI->Buffer, sizeof(ReqUploadSong)); SI->FileName = std::string(songData.filename); std::string recvFileData(SI->Buffer + sizeof(ReqUploadSong), BytesTransferred - sizeof(ReqUploadSong)); SI->vecBuffer.push_back(recvFileData); fopen_s(&SI->file, SI->FileName.c_str(), "wb"); sprintf_s(temp, STR_SIZE, "Upload - file: %s, title: %s, artist: %s", songData.filename, songData.title, songData.artist); Display(temp); } break; case PH_REQ_DOWNLOAD_SONG: { ReqDownloadSong songData; memcpy(&songData, SI->Buffer, sizeof(ReqDownloadSong)); SoundFilePacketizer packer(PACKET_SIZE); packer.makePacketsFromFile(songData.filename); long totalNumberOfPackets = packer.getTotalPackets(); int lastPacketSize = packer.getLastPackSize(); SI->BytesSEND = 0; SI->SentBytesTotal = 0; //send all packets except for last one for (int i = 0; i < totalNumberOfPackets - 1; i++) { SI->DataBuf.buf = packer.getNextPacket(); SI->DataBuf.len = PACKET_SIZE; Server::SendTCP(SI->Socket, SI); } SI->DataBuf.buf = packer.getNextPacket(); SI->DataBuf.len = lastPacketSize; Server::SendTCP(SI->Socket, SI); char complete[] = "EndOfPacket"; SI->DataBuf.buf = complete; SI->DataBuf.len = strlen(complete) + 1; Server::SendTCP(SI->Socket, SI); } break; default: break; } } Flags = 0; ZeroMemory(&(SI->Overlapped), sizeof(WSAOVERLAPPED)); SI->DataBuf.len = DATA_BUFSIZE; SI->DataBuf.buf = SI->Buffer; if (WSARecv(SI->Socket, &(SI->DataBuf), 1, &RecvBytes, &Flags, &(SI->Overlapped), WorkerRoutine) == SOCKET_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { printf("WSARecv() failed with error %d\n", WSAGetLastError()); return; } } //SleepEx(INFINITE, TRUE); } }
Java
UTF-8
37,472
2.3125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.text; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Objects; import javax.swing.event.*; import java.lang.ref.SoftReference; import java.util.HashMap; /** * Implements View interface for a simple multi-line text view * that has text in one font and color. The view represents each * child element as a line of text. * * @author Timothy Prinzing * @see View */ public class PlainView extends View implements TabExpander { /** * Constructs a new PlainView wrapped on an element. * * @param elem the element */ public PlainView(Element elem) { super(elem); } /** * Returns the tab size set for the document, defaulting to 8. * * @return the tab size */ protected int getTabSize() { Integer i = (Integer) getDocument().getProperty(PlainDocument.tabSizeAttribute); int size = (i != null) ? i.intValue() : 8; return size; } /** * Renders a line of text, suppressing whitespace at the end * and expanding any tabs. This is implemented to make calls * to the methods <code>drawUnselectedText</code> and * <code>drawSelectedText</code> so that the way selected and * unselected text are rendered can be customized. * * @param lineIndex the line to draw &gt;= 0 * @param g the <code>Graphics</code> context * @param x the starting X position &gt;= 0 * @param y the starting Y position &gt;= 0 * @see #drawUnselectedText * @see #drawSelectedText * * @deprecated replaced by * {@link #drawLine(int, Graphics2D, float, float)} */ @Deprecated(since = "9") protected void drawLine(int lineIndex, Graphics g, int x, int y) { drawLineImpl(lineIndex, g, x, y); } private void drawLineImpl(int lineIndex, Graphics g, float x, float y) { Element line = getElement().getElement(lineIndex); Element elem; try { if (line.isLeaf()) { drawElement(lineIndex, line, g, x, y); } else { // this line contains the composed text. int count = line.getElementCount(); for(int i = 0; i < count; i++) { elem = line.getElement(i); x = drawElement(lineIndex, elem, g, x, y); } } } catch (BadLocationException e) { throw new StateInvariantError("Can't render line: " + lineIndex); } } /** * Renders a line of text, suppressing whitespace at the end * and expanding any tabs. This is implemented to make calls * to the methods {@code drawUnselectedText} and * {@code drawSelectedText} so that the way selected and * unselected text are rendered can be customized. * * @param lineIndex the line to draw {@code >= 0} * @param g the {@code Graphics} context * @param x the starting X position {@code >= 0} * @param y the starting Y position {@code >= 0} * @see #drawUnselectedText * @see #drawSelectedText * * @since 9 */ protected void drawLine(int lineIndex, Graphics2D g, float x, float y) { drawLineImpl(lineIndex, g, x, y); } private float drawElement(int lineIndex, Element elem, Graphics g, float x, float y) throws BadLocationException { int p0 = elem.getStartOffset(); int p1 = elem.getEndOffset(); p1 = Math.min(getDocument().getLength(), p1); if (lineIndex == 0) { x += firstLineOffset; } AttributeSet attr = elem.getAttributes(); if (Utilities.isComposedTextAttributeDefined(attr)) { g.setColor(unselected); x = Utilities.drawComposedText(this, attr, g, x, y, p0-elem.getStartOffset(), p1-elem.getStartOffset()); } else { if (sel0 == sel1 || selected == unselected) { // no selection, or it is invisible x = callDrawUnselectedText(g, x, y, p0, p1); } else if ((p0 >= sel0 && p0 <= sel1) && (p1 >= sel0 && p1 <= sel1)) { x = callDrawSelectedText(g, x, y, p0, p1); } else if (sel0 >= p0 && sel0 <= p1) { if (sel1 >= p0 && sel1 <= p1) { x = callDrawUnselectedText(g, x, y, p0, sel0); x = callDrawSelectedText(g, x, y, sel0, sel1); x = callDrawUnselectedText(g, x, y, sel1, p1); } else { x = callDrawUnselectedText(g, x, y, p0, sel0); x = callDrawSelectedText(g, x, y, sel0, p1); } } else if (sel1 >= p0 && sel1 <= p1) { x = callDrawSelectedText(g, x, y, p0, sel1); x = callDrawUnselectedText(g, x, y, sel1, p1); } else { x = callDrawUnselectedText(g, x, y, p0, p1); } } return x; } /** * Renders the given range in the model as normal unselected * text. Uses the foreground or disabled color to render the text. * * @param g the graphics context * @param x the starting X coordinate &gt;= 0 * @param y the starting Y coordinate &gt;= 0 * @param p0 the beginning position in the model &gt;= 0 * @param p1 the ending position in the model &gt;= 0 * @return the X location of the end of the range &gt;= 0 * @throws BadLocationException if the range is invalid * * @deprecated replaced by * {@link #drawUnselectedText(Graphics2D, float, float, int, int)} */ @Deprecated(since = "9") protected int drawUnselectedText(Graphics g, int x, int y, int p0, int p1) throws BadLocationException { return (int) drawUnselectedTextImpl(g, x, y, p0, p1, false); } private float callDrawUnselectedText(Graphics g, float x, float y, int p0, int p1) throws BadLocationException { return drawUnselectedTextOverridden && (g instanceof Graphics2D) ? drawUnselectedText((Graphics2D) g, x, y, p0, p1) : drawUnselectedText(g, (int) x, (int) y, p0, p1); } private float drawUnselectedTextImpl(Graphics g, float x, float y, int p0, int p1, boolean useFPAPI) throws BadLocationException { g.setColor(unselected); Document doc = getDocument(); Segment s = SegmentCache.getSharedSegment(); doc.getText(p0, p1 - p0, s); float ret = Utilities.drawTabbedText(this, s, x, y, g, this, p0, null, useFPAPI); SegmentCache.releaseSharedSegment(s); return ret; } /** * Renders the given range in the model as normal unselected * text. Uses the foreground or disabled color to render the text. * * @param g the graphics context * @param x the starting X coordinate {@code >= 0} * @param y the starting Y coordinate {@code >= 0} * @param p0 the beginning position in the model {@code >= 0} * @param p1 the ending position in the model {@code >= 0} * @return the X location of the end of the range {@code >= 0} * @throws BadLocationException if the range is invalid * * @since 9 */ protected float drawUnselectedText(Graphics2D g, float x, float y, int p0, int p1) throws BadLocationException { return drawUnselectedTextImpl(g, x, y, p0, p1, true); } /** * Renders the given range in the model as selected text. This * is implemented to render the text in the color specified in * the hosting component. It assumes the highlighter will render * the selected background. * * @param g the graphics context * @param x the starting X coordinate &gt;= 0 * @param y the starting Y coordinate &gt;= 0 * @param p0 the beginning position in the model &gt;= 0 * @param p1 the ending position in the model &gt;= 0 * @return the location of the end of the range * @throws BadLocationException if the range is invalid * * @deprecated replaced by * {@link #drawSelectedText(Graphics2D, float, float, int, int)} */ @Deprecated(since = "9") protected int drawSelectedText(Graphics g, int x, int y, int p0, int p1) throws BadLocationException { return (int) drawSelectedTextImpl(g, x, y, p0, p1, false); } float callDrawSelectedText(Graphics g, float x, float y, int p0, int p1) throws BadLocationException { return drawSelectedTextOverridden && g instanceof Graphics2D ? drawSelectedText((Graphics2D) g, x, y, p0, p1) : drawSelectedText(g, (int) x, (int) y, p0, p1); } private float drawSelectedTextImpl(Graphics g, float x, float y, int p0, int p1, boolean useFPAPI) throws BadLocationException { g.setColor(selected); Document doc = getDocument(); Segment s = SegmentCache.getSharedSegment(); doc.getText(p0, p1 - p0, s); float ret = Utilities.drawTabbedText(this, s, x, y, g, this, p0, null, useFPAPI); SegmentCache.releaseSharedSegment(s); return ret; } /** * Renders the given range in the model as selected text. This * is implemented to render the text in the color specified in * the hosting component. It assumes the highlighter will render * the selected background. * * @param g the graphics context * @param x the starting X coordinate {@code >= 0} * @param y the starting Y coordinate {@code >= 0} * @param p0 the beginning position in the model {@code >= 0} * @param p1 the ending position in the model {@code >= 0} * @return the location of the end of the range * @throws BadLocationException if the range is invalid * * @since 9 */ protected float drawSelectedText(Graphics2D g, float x, float y, int p0, int p1) throws BadLocationException { return drawSelectedTextImpl(g, x, y, p0, p1, true); } /** * Gives access to a buffer that can be used to fetch * text from the associated document. * * @return the buffer */ protected final Segment getLineBuffer() { if (lineBuffer == null) { lineBuffer = new Segment(); } return lineBuffer; } /** * Checks to see if the font metrics and longest line * are up-to-date. * * @since 1.4 */ protected void updateMetrics() { Component host = getContainer(); Font f = host.getFont(); FontMetrics fm = (font == null) ? null : host.getFontMetrics(font); if (font != f || !Objects.equals(metrics, fm)) { // The font changed, we need to recalculate the // longest line. calculateLongestLine(); if (useFloatingPointAPI) { FontRenderContext frc = metrics.getFontRenderContext(); float tabWidth = (float) font.getStringBounds("m", frc).getWidth(); tabSize = getTabSize() * tabWidth; } else { tabSize = getTabSize() * metrics.charWidth('m'); } } } // ---- View methods ---------------------------------------------------- /** * Determines the preferred span for this view along an * axis. * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into &gt;= 0. * Typically the view is told to render into the span * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. * @throws IllegalArgumentException for an invalid axis */ public float getPreferredSpan(int axis) { updateMetrics(); switch (axis) { case View.X_AXIS: return getLineWidth(longLine); case View.Y_AXIS: return getElement().getElementCount() * metrics.getHeight(); default: throw new IllegalArgumentException("Invalid axis: " + axis); } } /** * Renders using the given rendering surface and area on that surface. * The view may need to do layout and create child views to enable * itself to render into the given allocation. * * @param g the rendering surface to use * @param a the allocated region to render into * * @see View#paint */ public void paint(Graphics g, Shape a) { Shape originalA = a; a = adjustPaintRegion(a); Rectangle alloc = (Rectangle) a; tabBase = alloc.x; JTextComponent host = (JTextComponent) getContainer(); Highlighter h = host.getHighlighter(); g.setFont(host.getFont()); sel0 = host.getSelectionStart(); sel1 = host.getSelectionEnd(); unselected = (host.isEnabled()) ? host.getForeground() : host.getDisabledTextColor(); Caret c = host.getCaret(); selected = c.isSelectionVisible() && h != null ? host.getSelectedTextColor() : unselected; updateMetrics(); // If the lines are clipped then we don't expend the effort to // try and paint them. Since all of the lines are the same height // with this object, determination of what lines need to be repainted // is quick. Rectangle clip = g.getClipBounds(); int fontHeight = metrics.getHeight(); int heightBelow = (alloc.y + alloc.height) - (clip.y + clip.height); int heightAbove = clip.y - alloc.y; int linesBelow, linesAbove, linesTotal; if (fontHeight > 0) { linesBelow = Math.max(0, heightBelow / fontHeight); linesAbove = Math.max(0, heightAbove / fontHeight); linesTotal = alloc.height / fontHeight; if (alloc.height % fontHeight != 0) { linesTotal++; } } else { linesBelow = linesAbove = linesTotal = 0; } // update the visible lines Rectangle lineArea = lineToRect(a, linesAbove); int y = lineArea.y + metrics.getAscent(); int x = lineArea.x; Element map = getElement(); int lineCount = map.getElementCount(); int endLine = Math.min(lineCount, linesTotal - linesBelow); lineCount--; LayeredHighlighter dh = (h instanceof LayeredHighlighter) ? (LayeredHighlighter)h : null; for (int line = linesAbove; line < endLine; line++) { if (dh != null) { Element lineElement = map.getElement(line); if (line == lineCount) { dh.paintLayeredHighlights(g, lineElement.getStartOffset(), lineElement.getEndOffset(), originalA, host, this); } else { dh.paintLayeredHighlights(g, lineElement.getStartOffset(), lineElement.getEndOffset() - 1, originalA, host, this); } } if (drawLineOverridden && (g instanceof Graphics2D)) { drawLine(line, (Graphics2D) g, (float) x, (float) y); } else { drawLine(line, g, x, y); } y += fontHeight; if (line == 0) { // This should never really happen, in so far as if // firstLineOffset is non 0, there should only be one // line of text. x -= firstLineOffset; } } } /** * Should return a shape ideal for painting based on the passed in * Shape <code>a</code>. This is useful if painting in a different * region. The default implementation returns <code>a</code>. */ Shape adjustPaintRegion(Shape a) { return a; } /** * Provides a mapping from the document model coordinate space * to the coordinate space of the view mapped to it. * * @param pos the position to convert &gt;= 0 * @param a the allocated region to render into * @return the bounding box of the given position * @throws BadLocationException if the given position does not * represent a valid location in the associated document * @see View#modelToView */ @SuppressWarnings("deprecation") public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { // line coordinates Document doc = getDocument(); Element map = getElement(); int lineIndex = map.getElementIndex(pos); if (lineIndex < 0) { return lineToRect(a, 0); } Rectangle lineArea = lineToRect(a, lineIndex); // determine span from the start of the line tabBase = lineArea.x; Element line = map.getElement(lineIndex); int p0 = line.getStartOffset(); Segment s = SegmentCache.getSharedSegment(); doc.getText(p0, pos - p0, s); if (useFloatingPointAPI) { float xOffs = Utilities.getTabbedTextWidth(s, metrics, (float) tabBase, this, p0); SegmentCache.releaseSharedSegment(s); return new Rectangle2D.Float(lineArea.x + xOffs, lineArea.y, 1, metrics.getHeight()); } int xOffs = Utilities.getTabbedTextWidth(s, metrics, tabBase, this,p0); SegmentCache.releaseSharedSegment(s); // fill in the results and return lineArea.x += xOffs; lineArea.width = 1; lineArea.height = metrics.getHeight(); return lineArea; } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param x the X coordinate &gt;= 0 * @param y the Y coordinate &gt;= 0 * @param a the allocated region to render into * @return the location within the model that best represents the * given point in the view &gt;= 0 * @see View#viewToModel */ public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { // PENDING(prinz) properly calculate bias bias[0] = Position.Bias.Forward; Rectangle alloc = a.getBounds(); Document doc = getDocument(); if (y < alloc.y) { // above the area covered by this icon, so the position // is assumed to be the start of the coverage for this view. return getStartOffset(); } else if (y > alloc.y + alloc.height) { // below the area covered by this icon, so the position // is assumed to be the end of the coverage for this view. return getEndOffset() - 1; } else { // positioned within the coverage of this view vertically, // so we figure out which line the point corresponds to. // if the line is greater than the number of lines contained, then // simply use the last line as it represents the last possible place // we can position to. Element map = doc.getDefaultRootElement(); int fontHeight = metrics.getHeight(); int lineIndex = (fontHeight > 0 ? (int)Math.abs((y - alloc.y) / fontHeight) : map.getElementCount() - 1); if (lineIndex >= map.getElementCount()) { return getEndOffset() - 1; } Element line = map.getElement(lineIndex); int dx = 0; if (lineIndex == 0) { alloc.x += firstLineOffset; alloc.width -= firstLineOffset; } if (x < alloc.x) { // point is to the left of the line return line.getStartOffset(); } else if (x > alloc.x + alloc.width) { // point is to the right of the line return line.getEndOffset() - 1; } else { // Determine the offset into the text try { int p0 = line.getStartOffset(); int p1 = line.getEndOffset() - 1; Segment s = SegmentCache.getSharedSegment(); doc.getText(p0, p1 - p0, s); tabBase = alloc.x; int offs = p0 + Utilities.getTabbedTextOffset(s, metrics, tabBase, x, this, p0, true); SegmentCache.releaseSharedSegment(s); return offs; } catch (BadLocationException e) { // should not happen return -1; } } } } /** * Gives notification that something was inserted into the document * in a location that this view is responsible for. * * @param changes the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see View#insertUpdate */ public void insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) { updateDamage(changes, a, f); } /** * Gives notification that something was removed from the document * in a location that this view is responsible for. * * @param changes the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see View#removeUpdate */ public void removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) { updateDamage(changes, a, f); } /** * Gives notification from the document that attributes were changed * in a location that this view is responsible for. * * @param changes the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @see View#changedUpdate */ public void changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) { updateDamage(changes, a, f); } /** * Sets the size of the view. This should cause * layout of the view along the given axis, if it * has any layout duties. * * @param width the width &gt;= 0 * @param height the height &gt;= 0 */ public void setSize(float width, float height) { super.setSize(width, height); updateMetrics(); } // --- TabExpander methods ------------------------------------------ /** * Returns the next tab stop position after a given reference position. * This implementation does not support things like centering so it * ignores the tabOffset argument. * * @param x the current position &gt;= 0 * @param tabOffset the position within the text stream * that the tab occurred at &gt;= 0. * @return the tab stop, measured in points &gt;= 0 */ public float nextTabStop(float x, int tabOffset) { if (tabSize == 0) { return x; } int ntabs = (int) ((x - tabBase) / tabSize); return tabBase + ((ntabs + 1) * tabSize); } // --- local methods ------------------------------------------------ /** * Repaint the region of change covered by the given document * event. Damages the line that begins the range to cover * the case when the insert/remove is only on one line. * If lines are added or removed, damages the whole * view. The longest line is checked to see if it has * changed. * * @param changes the change information from the associated document * @param a the current allocation of the view * @param f the factory to use to rebuild if the view has children * @since 1.4 */ protected void updateDamage(DocumentEvent changes, Shape a, ViewFactory f) { Component host = getContainer(); updateMetrics(); Element elem = getElement(); DocumentEvent.ElementChange ec = changes.getChange(elem); Element[] added = (ec != null) ? ec.getChildrenAdded() : null; Element[] removed = (ec != null) ? ec.getChildrenRemoved() : null; if (((added != null) && (added.length > 0)) || ((removed != null) && (removed.length > 0))) { // lines were added or removed... if (added != null) { int currWide = getLineWidth(longLine); for (int i = 0; i < added.length; i++) { int w = getLineWidth(added[i]); if (w > currWide) { currWide = w; longLine = added[i]; } } } if (removed != null) { for (int i = 0; i < removed.length; i++) { if (removed[i] == longLine) { calculateLongestLine(); break; } } } preferenceChanged(null, true, true); host.repaint(); } else { Element map = getElement(); int line = map.getElementIndex(changes.getOffset()); damageLineRange(line, line, a, host); if (changes.getType() == DocumentEvent.EventType.INSERT) { // check to see if the line is longer than current // longest line. int w = getLineWidth(longLine); Element e = map.getElement(line); if (e == longLine) { preferenceChanged(null, true, false); } else if (getLineWidth(e) > w) { longLine = e; preferenceChanged(null, true, false); } } else if (changes.getType() == DocumentEvent.EventType.REMOVE) { if (map.getElement(line) == longLine) { // removed from longest line... recalc calculateLongestLine(); preferenceChanged(null, true, false); } } } } /** * Repaint the given line range. * * @param host the component hosting the view (used to call repaint) * @param a the region allocated for the view to render into * @param line0 the starting line number to repaint. This must * be a valid line number in the model. * @param line1 the ending line number to repaint. This must * be a valid line number in the model. * @since 1.4 */ protected void damageLineRange(int line0, int line1, Shape a, Component host) { if (a != null) { Rectangle area0 = lineToRect(a, line0); Rectangle area1 = lineToRect(a, line1); if ((area0 != null) && (area1 != null)) { Rectangle damage = area0.union(area1); host.repaint(damage.x, damage.y, damage.width, damage.height); } else { host.repaint(); } } } /** * Determine the rectangle that represents the given line. * * @param a the region allocated for the view to render into * @param line the line number to find the region of. This must * be a valid line number in the model. * @return the rectangle that represents the given line * @since 1.4 */ protected Rectangle lineToRect(Shape a, int line) { Rectangle r = null; updateMetrics(); if (metrics != null) { Rectangle alloc = a.getBounds(); if (line == 0) { alloc.x += firstLineOffset; alloc.width -= firstLineOffset; } r = new Rectangle(alloc.x, alloc.y + (line * metrics.getHeight()), alloc.width, metrics.getHeight()); } return r; } /** * Iterate over the lines represented by the child elements * of the element this view represents, looking for the line * that is the longest. The <em>longLine</em> variable is updated to * represent the longest line contained. The <em>font</em> variable * is updated to indicate the font used to calculate the * longest line. */ private void calculateLongestLine() { Component c = getContainer(); font = c.getFont(); metrics = c.getFontMetrics(font); Document doc = getDocument(); Element lines = getElement(); int n = lines.getElementCount(); int maxWidth = -1; for (int i = 0; i < n; i++) { Element line = lines.getElement(i); int w = getLineWidth(line); if (w > maxWidth) { maxWidth = w; longLine = line; } } } /** * Calculate the width of the line represented by * the given element. It is assumed that the font * and font metrics are up-to-date. */ @SuppressWarnings("deprecation") private int getLineWidth(Element line) { if (line == null) { return 0; } int p0 = line.getStartOffset(); int p1 = line.getEndOffset(); int w; Segment s = SegmentCache.getSharedSegment(); try { line.getDocument().getText(p0, p1 - p0, s); w = Utilities.getTabbedTextWidth(s, metrics, tabBase, this, p0); } catch (BadLocationException ble) { w = 0; } SegmentCache.releaseSharedSegment(s); return w; } static boolean getFPMethodOverridden(Class<?> cls, String method, FPMethodArgs methodArgs) { HashMap<FPMethodItem, Boolean> map = null; boolean initialized = methodsOverriddenMapRef != null && (map = methodsOverriddenMapRef.get()) != null; if (!initialized) { map = new HashMap<>(); methodsOverriddenMapRef = new SoftReference<>(map); } FPMethodItem key = new FPMethodItem(cls, method); Boolean isFPMethodOverridden = map.get(key); if (isFPMethodOverridden == null) { isFPMethodOverridden = checkFPMethodOverridden(cls, method, methodArgs); map.put(key, isFPMethodOverridden); } return isFPMethodOverridden; } @SuppressWarnings("removal") private static boolean checkFPMethodOverridden(final Class<?> className, final String methodName, final FPMethodArgs methodArgs) { return AccessController .doPrivileged(new PrivilegedAction<Boolean>() { @Override public Boolean run() { return isFPMethodOverridden(methodName, className, methodArgs.getMethodArguments(false), methodArgs.getMethodArguments(true)); } }); } private static boolean isFPMethodOverridden(String method, Class<?> cls, Class<?>[] intTypes, Class<?>[] fpTypes) { Module thisModule = PlainView.class.getModule(); while (!thisModule.equals(cls.getModule())) { try { cls.getDeclaredMethod(method, fpTypes); return true; } catch (Exception e1) { try { cls.getDeclaredMethod(method, intTypes); return false; } catch (Exception e2) { cls = cls.getSuperclass(); } } } return true; } enum FPMethodArgs { IGNN, IIGNN, GNNII, GNNC; public Class<?>[] getMethodArguments(boolean isFPType) { Class<?> N = (isFPType) ? Float.TYPE : Integer.TYPE; Class<?> G = (isFPType) ? Graphics2D.class : Graphics.class; switch (this) { case IGNN: return new Class<?>[]{Integer.TYPE, G, N, N}; case IIGNN: return new Class<?>[]{Integer.TYPE, Integer.TYPE, G, N, N}; case GNNII: return new Class<?>[]{G, N, N, Integer.TYPE, Integer.TYPE}; case GNNC: return new Class<?>[]{G, N, N, Character.TYPE}; default: throw new RuntimeException("Unknown method arguments!"); } } } private static class FPMethodItem { final Class<?> className; final String methodName; public FPMethodItem(Class<?> className, String methodName) { this.className = className; this.methodName = methodName; } @Override public boolean equals(Object obj) { if (obj instanceof FPMethodItem) { FPMethodItem that = (FPMethodItem) obj; return this.className.equals(that.className) && this.methodName.equals(that.methodName); } return false; } @Override public int hashCode() { return 31 * methodName.hashCode() + className.hashCode(); } } // --- member variables ----------------------------------------------- /** * Font metrics for the current font. */ protected FontMetrics metrics; /** * The current longest line. This is used to calculate * the preferred width of the view. Since the calculation * is potentially expensive we try to avoid it by stashing * which line is currently the longest. */ Element longLine; /** * Font used to calculate the longest line... if this * changes we need to recalculate the longest line */ Font font; Segment lineBuffer; float tabSize; int tabBase; int sel0; int sel1; Color unselected; Color selected; /** * Offset of where to draw the first character on the first line. * This is a hack and temporary until we can better address the problem * of text measuring. This field is actually never set directly in * PlainView, but by FieldView. */ int firstLineOffset; private static SoftReference<HashMap<FPMethodItem, Boolean>> methodsOverriddenMapRef; final boolean drawLineOverridden = getFPMethodOverridden(getClass(), "drawLine", FPMethodArgs.IGNN); final boolean drawSelectedTextOverridden = getFPMethodOverridden(getClass(), "drawSelectedText", FPMethodArgs.GNNII); final boolean drawUnselectedTextOverridden = getFPMethodOverridden(getClass(), "drawUnselectedText", FPMethodArgs.GNNII); final boolean useFloatingPointAPI = drawUnselectedTextOverridden || drawSelectedTextOverridden; }
Python
UTF-8
5,087
2.90625
3
[ "MIT", "LGPL-3.0-only", "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- """ Validation Utils ~~~~~~~~~~~~~~~~ :copyright: Copyright 2019 Autodesk, Inc. :license: MIT, see LICENSE for details. """ import attr NUMERIC_TYPES = (int, float) def Boolean(**kwargs): _add_validator_to_kwargs(kwargs, instance_of(bool)) return attr.ib(**kwargs) def Integer(**kwargs): _add_validator_to_kwargs(kwargs, instance_of(int)) return attr.ib(**kwargs) def Number(**kwargs): _add_validator_to_kwargs(kwargs, is_number()) return attr.ib(**kwargs) def Enum(values, **kwargs): _add_validator_to_kwargs(kwargs, one_of(values)) return attr.ib(**kwargs) def String(**kwargs): _add_validator_to_kwargs(kwargs, instance_of(str)) return attr.ib(**kwargs) def List(**kwargs): _add_validator_to_kwargs(kwargs, instance_of(list)) return attr.ib(**kwargs) def Dict(**kwargs): _add_validator_to_kwargs(kwargs, instance_of(dict)) return attr.ib(**kwargs) def Color(**kwargs): """Color value. Can be specified as three-item list/tuple (RGB) or four- item list/tuple (RGBA). """ _add_validator_to_kwargs(kwargs, is_color()) return attr.ib(**kwargs) def Points(**kwargs): _add_validator_to_kwargs(kwargs, is_points_list()) return attr.ib(**kwargs) def Field(allowed_type, **kwargs): """Generic field, e.g. Field(ContentStream).""" _add_validator_to_kwargs(kwargs, instance_of(allowed_type)) return attr.ib(**kwargs) def is_points_list(): def validate(obj, attr, value): if isinstance(value, (list, tuple)): for point in value: if len(point) != 2 or not ( isinstance(point[0], NUMERIC_TYPES) and isinstance(point[1], NUMERIC_TYPES) ): raise ValueError( 'Value ({}) must be a list of points'.format(value) ) elif value is not None: raise ValueError( 'Value ({}) must be a list of points'.format(value) ) return validate def greater_than_eq(i): def validate(obj, attr, value): if value is not None and not value >= i: raise ValueError('Value ({}) must be >= than {}'.format(value, i)) return validate positive = greater_than_eq(0) def between(a, b): def validate(obj, attr, value): if value is not None and not (a <= value <= b): raise ValueError( 'Value ({}) must be between {} and {}'.format(value, a, b) ) return validate def instance_of(types): def validate(obj, attr, value): if value is not None and not isinstance(value, _tupleize(types)): raise ValueError( 'Value ({}) must be of type ({})'.format(value, types) ) return validate def is_number(): def validate(obj, attr, value): if value is not None and not isinstance(value, NUMERIC_TYPES): raise ValueError('Value ({}) must be numeric'.format(value)) return validate def one_of(values): def validate(obj, attr, value): if value is not None and value not in values: raise ValueError( 'Value ({}) must be in ({})'.format(value, values) ) return validate def is_color(): def validate(obj, attr, value): if isinstance(value, (list, tuple)): if len(value) not in (3, 4): raise ValueError( 'Value ({}) is not a RGB(A) color'.format(value) ) for component in value: if not ( isinstance(component, NUMERIC_TYPES) and component >= 0 and component <= 1 ): raise ValueError( 'Value ({}) is not a RGB(A) color'.format(value) ) elif value is not None: raise ValueError('Value ({}) is not a RGB(A) color'.format(value)) return validate def validate_dash_array(obj, attr, value): msg = ( 'Value ({}) must be a dash array of the form ' '[dash_array, dash_phase], where dash_array is a list of integers,' ' and dash_phase is an integer' ) if isinstance(value, list): if ( len(value) != 2 or not isinstance(value[0], list) or any(not isinstance(x, int) for x in value[0]) or not isinstance(value[1], int) ): raise ValueError(msg.format(value)) elif value is not None: raise ValueError(msg.format(value)) def _listify(v): if isinstance(v, tuple): return list(v) elif not isinstance(v, list): return [v] return v def _tupleize(v): if isinstance(v, list): return tuple(v) elif not isinstance(v, tuple): return (v,) return v def _add_validator_to_kwargs(kwargs, validator): existing = _listify(kwargs.pop('validator', [])) existing.append(validator) kwargs['validator'] = existing
Java
UTF-8
6,078
2.015625
2
[]
no_license
package com.chinamobo.ue.course.restful; import java.lang.reflect.InvocationTargetException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.BeanParam; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.chinamobo.ue.course.entity.TomGradeDimension; import com.chinamobo.ue.course.service.GradeDimensionService; import com.chinamobo.ue.ums.DBContextHolder; import com.chinamobo.ue.ums.shiro.ShiroUser; import com.chinamobo.ue.ums.util.ShiroUtils; import com.chinamobo.ue.utils.JsonMapper; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.Maps; /** * * 版本: [1.0] * 功能说明: 评论管理 * * 作者: WangLg * 创建时间: 2016年3月3日 上午10:45:34 */ @Path("/commentScore") @Scope("request") @Component public class CommentScoreRest { @Autowired private GradeDimensionService gradeDimensionService;//评分服务 ShiroUser user=ShiroUtils.getCurrentUser(); @PUT @Path("/delete") public String deleteGradeDimenCom(@QueryParam("gradeDimensionId") int gradeDimensionId,@Context HttpServletResponse servletResponse){ //设置主库查询 DBContextHolder.setDbType(DBContextHolder.MASTER); try { gradeDimensionService.deleteGradeDimension(gradeDimensionId); return "{\"result\":\"success\"}"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return "{\"result\":\"error\"}"; } } /** * 功能描述:[修改讲师评分/课程评分] * * 创建者:WangLg * 创建时间: 2016年3月2日 下午1:30:50 * @param gradeDimensionType * @param gradeDimensionName * @param gradeDimensionNumber * @param request * @return */ @POST @Path("/update") public String updateGradeDimenCom(@BeanParam TomGradeDimension gradeDimension,@Context HttpServletResponse servletResponse){ //设置主库查询 DBContextHolder.setDbType(DBContextHolder.MASTER); try { gradeDimension.setOperator(user.getName()); gradeDimension.setOperatorId(user.getCode()); gradeDimensionService.updateGradeDimension(gradeDimension); return "{\"result\":\"success\"}"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return "{\"result\":\"error\"}"; } } /** * 功能描述:[添加讲师评分/课程评分] * * 创建者:WangLg * 创建时间: 2016年3月2日 上午9:45:28 * @param gradeDimensionType * @param gradeDimensionName * @param request * @return */ @POST @Path("/add") public String saveGradeDimenCom(@BeanParam TomGradeDimension gradeDimension,@Context HttpServletResponse servletResponse){ //设置主库查询 DBContextHolder.setDbType(DBContextHolder.MASTER); try { gradeDimension.setCreator(user.getName()); gradeDimension.setCreatorId(user.getCode()); gradeDimension.setOperator(user.getName()); gradeDimensionService.saveGradeDimension(gradeDimension); return "{\"result\":\"success\"}"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return "{\"result\":\"error\"}"; } } /** * 功能描述:[查询讲师/课程维度] * * 创建者:WangLg * 创建时间: 2016年3月2日 上午11:49:32 * @param gradeDimensionType * @param gradeDimensionName * @param request * @return * @throws JsonProcessingException */ @GET @Path("/findList") @Produces({MediaType.APPLICATION_JSON}) public String findGradeDimenComList(@DefaultValue("1") @QueryParam("pageNum") int pageNum,@DefaultValue("10") @QueryParam("pageSize") int pageSize, @QueryParam("gradeDimensionName") String gradeDimensionName,@QueryParam("gradeDimensionType") String gradeDimensionType, @Context HttpServletRequest request) throws JsonProcessingException{ JsonMapper jsonMapper = new JsonMapper(); Map<Object, Object> queryMap = Maps.newHashMap(); if(gradeDimensionName!=null){ gradeDimensionName=gradeDimensionName.replaceAll("/", "//"); gradeDimensionName=gradeDimensionName.replaceAll("%", "/%"); gradeDimensionName=gradeDimensionName.replaceAll("_", "/_"); } if("'C'".equals(gradeDimensionType)){ gradeDimensionType ="C"; }else if("'L'".equals(gradeDimensionType)){ gradeDimensionType ="L"; } queryMap.put("gradeDimensionName", gradeDimensionName); queryMap.put("gradeDimensionType", gradeDimensionType); String json = jsonMapper.toJson(gradeDimensionService.findGradeDimenComList(pageNum, pageSize, queryMap)); return json; } @GET @Path("/findDetails") @Produces({MediaType.APPLICATION_JSON}) public String findDetails(@QueryParam(value = "gradeDimensionId") int gradeDimensionId,@Context HttpServletRequest request,@Context HttpServletResponse servletResponse) throws JsonProcessingException{ JsonMapper jsonMapper = new JsonMapper(); Map<Object,Object> map = Maps.newHashMap(); map.put("gradeDimensionId", gradeDimensionId); String json; json= jsonMapper.toJson(gradeDimensionService.findDetails(map)); return json; } @GET @Path("/findModel") @Produces({MediaType.APPLICATION_JSON}) public String findGradeDimenComModel(@QueryParam("gradeDimensionType") String gradeDimensionType, @Context HttpServletRequest request,@Context HttpServletResponse servletResponse) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{ JsonMapper jsonMapper = new JsonMapper(); Map<Object, Object> queryMap = Maps.newHashMap(); queryMap.put("gradeDimensionType", gradeDimensionType); String json = ""; json = jsonMapper.toJson(gradeDimensionService.findGradeDimenModel(queryMap)); return json; } }
C
UTF-8
493
2.828125
3
[]
no_license
#include <stdio.h> #include "final_ex1.h" #include <math.h> #include <string.h> #include <stdlib.h> int main(){ Team Teams [POPULATION_TEAMS]; printf ("Bem vindo ao programa que analisa pontos de times.\nPor favor, insira dados dos times:\n\n"); populate_teams (Teams); //geraltable_ex2(Teams); int winnerteam = tournment (Teams); printf ("\n\n\t-------> Time vencedor: Time %d! <-------\n\n", (winnerteam+1)); goodbye_greeting(); return 0; }
Markdown
UTF-8
1,053
2.65625
3
[]
no_license
# nm-otool Toy implementation of nm & otool bsd commands. The general idea was to learn how a binary file work and how to parse it properly. These tools only support mach-o files. ## Build & run Just run `make`, it will generate `ft_nm` and `ft_otool`. #### Tests You can test nm with some system binaries by launching `make test_all`. It will assert there is no output difference between my implementation and the current system implementation. Tests will take some time to complete! ## ft_nm #### Usage `./ft_nm -uUrpj [FILE ...]` #### Options ``` -u Display only undefined symbols. -U Don't display undefined symbols. -r Sort in reverse order. -p Don't sort; display in symbol-table order. -j Just display the symbol names (no value or type). ``` ## ft_otool #### Usage `./ft_otool -td [FILE ...]` #### Options ``` -t Display the contents of the (__TEXT,__text) section. -d Display the contents of the (__DATA,__data) section. ``` **This project is a student exercise and is by no mean intended to be used for real**
Rust
UTF-8
2,104
3.59375
4
[]
no_license
use std::thread; use std::time::Duration; fn simulated_expensive_calculation(intensity: u32) -> u32 { // ゆっくり計算します println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); intensity } fn main() { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout(simulated_user_specified_value, simulated_random_number); let sum: u32 = Counter::new() .zip(Counter::new().skip(1)) .map(|(a, b)| a * b) .filter(|x| x % 3 == 0) .sum(); assert_eq!(18, sum); } fn generate_workout(intensity: u32, random_number: u32) { let expensive_closure = |num| { println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); num }; if intensity < 25 { println!( // 今日は{}回腕立て伏せをしてください! "Today, do {} pushups!", //simulated_expensive_calculation(intensity) expensive_closure(intensity) ); println!( // 次に、{}回腹筋をしてください! "Next, do {} situps!", //simulated_expensive_calculation(intensity) expensive_closure(intensity) ); } else { if random_number == 3 { // 今日は休憩してください!水分補給を忘れずに! println!("Take a break today! Remember to stay hydrated!"); } else { println!( // 今日は、{}分間走ってください! "Today, run for {} minutes!", //simulated_expensive_calculation(intensity) expensive_closure(intensity) ); } } } struct Counter { count: u32, } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.count) } else { None } } }
C
UTF-8
375
3.59375
4
[]
no_license
#include <stdio.h> void main(){ int i,vT[10],nExiste; for(i = 0;i<10;i++){ printf("(%d/10)Digite um numero: ",i+1); scanf("%d",&vT[i]); } for(i = 0;i < 10;i++){ if(vT[i] > 50){ printf("O numero %d e maior que 50 e esta na posicao %d\n",vT[i],i); nExiste++; } } if(nExiste == 0){ printf("Nenhum numero maior que 50 encontrado"); } }
JavaScript
UTF-8
2,361
2.8125
3
[]
no_license
const { response } = require("express"); const express = require("express"); const jsonfile = require('jsonfile') const fetch = require('node-fetch'); var cors = require('cors'); //create express app const app = express(); app.use(cors()); const file = 'data.json' var globalData = ''; //port at which the server will run const port = process.env.PORT || 3000; //create end point app.get("/", (request, response) => { //send 'Hi, from Node server' to client response.send("Hi s, from Node server"); }); function getData(url) { return new Promise((resolve, reject) => { fetch(url) .then((resp) => resp.json()) .then((data) => { resolve(data) }) }) } function loadPrices() { let userRequests = [] const range = '5d'; // Data of past 5 days const stockSymbols = ["SPY", "FXAIX", "VTSAX", "IVV", "VSMPX", "FDRXX", "VMFXX", "VTI", "SPAXX", "VITSX", "VGTSX", "VOO", "VTSMX", "QQQ", "FGTXX", "VIIIX", "VTBIX", "AGTHX", "VBTLX", "OGVXX", "VINIX", "TFDXX", "FCNTX", "FRGXX"] stockSymbols.forEach( (stockSymbol) => { userRequests.push(getData(`https://query1.finance.yahoo.com/v8/finance/chart/${stockSymbol}?region=IN&lang=en-IN&includePrePost=false&useYfid=true&range=${range}&corsDomain=in.finance.yahoo.com&.tsrc=finance`)) }) Promise.all(userRequests) .then((responseData) => { writeData(responseData) }) } async function writeData(responseData) { var _objects ={} // console.log(responseData) const data = await responseData.map((items)=>{ const closeArray = items.chart.result[0].indicators.quote[0].close; const symbol = (items.chart.result[0].meta.symbol) return _objects[symbol]=closeArray }) jsonfile.writeFile(file, _objects, function (err) { if (err) console.error(err) }) globalData = _objects; console.log(globalData) } app.get("/top-25",async (request, response) => { // const data = await loadPrices(); console.log(globalData); response.send(globalData); }); function checkResponseStatus(res) { if (res.ok) { return res } else { throw new Error(`The HTTP status of the reponse: ${res.status} (${res.statusText})`); } } app.listen(port, () => //a callback that will be called as soon as server start listening console.log(`server is listening at http://localhost:${port}`) );
Java
UTF-8
5,727
3.40625
3
[]
no_license
package UI_seminarska; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; public class Main { /** * @param filename name of the input file * @return 2d char array */ private static char[][] readFile(String filename) { ArrayList<char[]> input = new ArrayList<>(); // If file not found, exit try { Scanner sc = new Scanner(new File(filename)); // Read file while (sc.hasNextLine()) { String[] line = sc.nextLine().replace("'", "").split(","); char[] lineChar = new char[line.length]; for (int i = 0; i < line.length; i++) lineChar[i] = line[i].charAt(0); input.add(lineChar); } sc.close(); } catch (FileNotFoundException ex) { System.out.println("Datoteka " + filename + " ni bila najdena."); System.exit(2); } // Array dimensions int P = 0, N = 0; // Get dimensions try { P = input.size(); N = input.get(0)[0]; } catch (Exception ex) { System.out.println("Error reading files"); System.exit(2); } // Convert ArrayList to char array char[][] out = new char[P][N]; for (int i = 0; i < P; i++) out[i] = input.get(i); return out; } /** Print 2d char array */ public static void print2DArray(char[][] conf) { for (char[] chars : conf) { for (char c : chars) System.out.print(c + ","); System.out.println(); } } /** * Take top box from column p and move to top of column r * Changes the input array * @param conf 2d char configuration array * @param p where to take from * @param r where to move */ private static void move(char[][] conf, int p, int r) { if (r < 1 || p < 1 || p == r) return; // Index p--; r--; char top = ' '; // Find top of column p for (int y = 0; y < conf.length; y++) { if (conf[y][p] != ' ') { top = conf[y][p]; conf[y][p] = ' '; break; } } // If there are no blocks in column p if (top == ' ') return; // Put on top of column r for (int y = conf.length - 1; y >= 0; y--) { if (conf[y][r] == ' ') { conf[y][r] = top; break; } } } /** Is array a equal to array b */ public static boolean compare(char[][] a, char[][] b) { if (a.length != b.length) return false; if (a.length == 0) return true; if (a[0].length != b[0].length) return false; for (int y = 0; y < a.length; y++) for (int x = 0; x < a[y].length; x++) if (a[y][x] != b[y][x]) return false; return true; } /** Copy 2d array */ private static char[][] copy(char[][] a) { char[][] c = new char[a.length][a[0].length]; for (int y = 0; y < a.length; y++) System.arraycopy(a[y], 0, c[y], 0, a[y].length); return c; } /** * Does ArrayList of configurations contain the given configuration * @param nodes ArrayList configurations * @param conf given config * @return true or false */ public static boolean containsConf(ArrayList<Node> nodes, char[][] conf) { for (Node value : nodes) if (compare(conf, value.conf)) return true; return false; } /** * Generate all possible configurations from given conf * and store parameters on how to get them. * @param conf given start configuration * @return ArrayList of all configurations & parameters */ public static ArrayList<Node> generate(char[][] conf) { final int cols = conf[0].length; ArrayList<Node> nodes = new ArrayList<>(); nodes.add(new Node(conf, 0,0)); // Try placing blocks to the right of current block for (int y = 0; y < cols; y++) { for (int x = 1; x < cols; x++) { char[][] tmpConf = copy(conf); move(tmpConf, y+1, x+1); if (!containsConf(nodes, tmpConf)) nodes.add(new Node(tmpConf, y+1, x+1)); } } // Try placing blocks to the left of current block for (int y = cols-1; y >= 0; y--) { for (int x = cols-2; x >= 0; x--) { char[][] tmpConf = copy(conf); move(tmpConf, y+1, x+1); if (!containsConf(nodes, tmpConf)) nodes.add(new Node(tmpConf, y+1, x+1)); } } return nodes; } /** * Does stack contain given configuration * @param stack given stack * @param node given configuration * @return true or false */ public static boolean stackContains(Stack<Node> stack, Node node) { for (Node value : stack) if (compare(node.conf, value.conf)) return true; return false; } public static void main(String[] args) { char[][] startConf = readFile("primer3_zacetna.txt"); char[][] endConf = readFile("primer3_koncna.txt"); //DFS.search(startConf, endConf); //BFS.search(startConf, endConf); //IDDFS.search(startConf, endConf); //AStar.search(startConf, endConf); new IDAStar().find(startConf, endConf); } }
PHP
UTF-8
2,840
2.75
3
[]
no_license
<?php class AalLink { var $id; var $link; var $keywords; var $medium; var $hooks = array(); function AalLink($id = '',$link,$keywords,$medium) { $this->id = $id; $this->link = $link; $this->keywords = $keywords; $this->medium = $medium; } function showAll($medium = '') { global $wpdb; $table_name = $wpdb->prefix . "automated_links"; $orderby = filter_input(INPUT_GET, 'aalorder', FILTER_SANITIZE_SPECIAL_CHARS); // $_GET['aalorder']; if($orderby) $ordersql = " ORDER BY ". $orderby; $myrows = $wpdb->get_results( "SELECT * FROM ". $table_name . $ordersql); if($myrows) { foreach($myrows as $row) { $link = new AalLink($row->id,$row->link,$row->keywords,$row->medium); $link->display(); } } else { echo '<div>Add some links using the form above</div>'; } } function display() { ?> <form name="edit-link-<?php echo $this->id; ?>" method="post"> <input value="<?php echo $this->id; ?>" name="edit_id" type="hidden" /> <input type="hidden" name="aal_edit" value="ok" /> <?php if (function_exists('wp_nonce_field')) wp_nonce_field('WP-auto-affiliate-links_edit_link'); ?> <li style="" class="aal_links_box"> <input type="checkbox" name="aal_massids[]" value="<?php echo $this->id; ?>" /> Link: <input style="margin: 5px 10px;width: 37%;" type="text" name="aal_link" value="<?php echo $this->link; ?>" /> Keywords: <input style="margin: 5px 10px;width: 20%;" type="text" name="aal_keywords" value="<?php echo $this->keywords; ?>" /> <input class="button-primary" style="margin: 5px 2px;" type="submit" name="ed" value="Update" /> <a href="#" id="<?php echo $this->id; ?>" class="aalDeleteLink"><img src="<?php echo plugin_dir_url(__FILE__);?>../images/delete.png"/></a> </li> </form> <?php } } function aalGetLink($id) { if(!$id) return false; global $wpdb; $table_name = $wpdb->prefix . "automated_links"; $myrows = $wpdb->get_results( "SELECT * FROM ". $table_name ." WHERE id='". $id ."' "); $link = AalLink($id,$link,$keyword,$medium); } function aalGetLinkByUrl($url) { if(!$url) return false; global $wpdb; $table_name = $wpdb->prefix . "automated_links"; $myrows = $wpdb->get_results( "SELECT * FROM ". $table_name ." WHERE link='". $url ."' "); $link = AalLink($id,$link,$keyword,$medium); } ?>
Java
UTF-8
1,263
2.515625
3
[]
no_license
package inSeongJo.aHenIntoTheWild.view; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import javax.swing.JLabel; import javax.swing.JPanel; public class LoadingPage extends JPanel{ private Image loadingImage; private MainFrame mf; private JPanel loading = this; Media media = new Media(); public LoadingPage(MainFrame mf) { this.mf = mf; this.setBounds(0, 0, 1024, 768); this.setLayout(null); mf.add(this); Toolkit toolkit = Toolkit.getDefaultToolkit(); loadingImage = toolkit.getImage("images/Loading.gif").getScaledInstance(1024, 740, 0);//배경 이미지 Thread timer = new Thread(new Runnable() { int i = 0; @Override public void run() { media.sound("keyboard"); while (i < 2300) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } i++; repaint(); } media.soundStop(); ChangePanel.changePanel(mf, loading, new MainPage(mf)); } }); timer.start(); } @Override protected void paintComponent(Graphics g) { g.drawImage(loadingImage, 0, 0, this);// 배경 그리기 } }
Swift
UTF-8
575
3.3125
3
[ "MIT" ]
permissive
// // Monoid.swift // Pods // // Created by José Manuel Sánchez Peñarroja on 31/5/17. // // import Foundation public struct Monoid<T> { public var empty: T public var semigroup: Semigroup<T> public var combine: (T, T) -> T { return semigroup.combine } public init(empty: T, semigroup: Semigroup<T>) { self.empty = empty self.semigroup = semigroup } public init(empty: T, combine: @escaping (T, T) -> T) { self.init(empty: empty, semigroup: Semigroup<T>.init(combine: combine)) } } extension Monoid { public func combine(_ items: T...) -> T { items.reduced(self) } }
Rust
UTF-8
10,804
3.3125
3
[ "Unlicense" ]
permissive
use std::mem; // Day 11 - Seating System static ADJACENT_SEATS: [(isize, isize); 8] = [ (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), ]; #[derive(Copy, Clone, Eq, PartialEq)] pub enum SeatingSystem { Empty, Floor, Occupied, } impl std::str::FromStr for SeatingSystem { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "L" => SeatingSystem::Empty, "." => SeatingSystem::Floor, "#" => SeatingSystem::Occupied, _ => unreachable!("Invalid seat"), }) } } #[derive(Clone)] struct Grid { rows: usize, cols: usize, grid: Vec<Vec<SeatingSystem>>, } impl Grid { fn occupied_seats(&self) -> usize { self.grid .iter() .flat_map(|row| row.iter()) .filter(|&&c| c == SeatingSystem::Occupied) .count() } fn get(&self, r: usize, c: usize) -> SeatingSystem { self.grid[r][c] } fn set(&mut self, seat: SeatingSystem, r: usize, c: usize) { self.grid[r][c] = seat; } fn new(grid: &[Vec<SeatingSystem>]) -> Grid { Grid { rows: grid.len(), cols: grid[0].len(), grid: grid.to_owned(), } } } #[aoc_generator(day11)] pub fn input_generator(input: &str) -> Vec<Vec<SeatingSystem>> { input .lines() .map(|l| l.chars().map(|c| c.to_string().parse().unwrap()).collect()) .collect() } fn find_neighbors( grid: &[Vec<SeatingSystem>], (dr, dc): (isize, isize), (r, c): (usize, usize), ) -> Option<SeatingSystem> { let (mut r, mut c) = (r as isize, c as isize); loop { r += dr; c += dc; match grid.get(r as usize).and_then(|row| row.get(c as usize)) { Some(SeatingSystem::Floor) => (), Some(&seat) => return Some(seat), None => break, } } None } fn should_swap_part_1(grid: &[Vec<SeatingSystem>], r: usize, c: usize) -> bool { let mut neighbors = ADJACENT_SEATS .iter() .map(|&(dr, dc)| (r as isize + dr, c as isize + dc)) .filter_map(|(r, c)| grid.get(r as usize).and_then(|v| v.get(c as usize))); match grid[r][c] { SeatingSystem::Empty => neighbors.all(|&c| c != SeatingSystem::Occupied), SeatingSystem::Occupied => { neighbors.filter(|&&c| c == SeatingSystem::Occupied).count() >= 4 } _ => unreachable!("Not Important"), } } fn should_swap_part_2(grid: &[Vec<SeatingSystem>], r: usize, c: usize) -> bool { let mut neighbors = ADJACENT_SEATS .iter() .filter_map(|&dir| find_neighbors(grid, dir, (r, c))); match grid[r][c] { SeatingSystem::Empty => neighbors.all(|c| c != SeatingSystem::Occupied), SeatingSystem::Occupied => neighbors.filter(|&c| c == SeatingSystem::Occupied).count() >= 5, _ => unreachable!("Not important"), } } fn simulate_seating<F: Fn(&[Vec<SeatingSystem>], usize, usize) -> bool>( grid: &[Vec<SeatingSystem>], should_swap: F, ) -> usize { let mut grid = Grid::new(grid); let mut previous_grid = grid.to_owned(); loop { let mut changed = false; for r in 0..grid.rows { for c in 0..grid.cols { if grid.get(r, c) == SeatingSystem::Floor { continue; } let seat = match (grid.get(r, c), should_swap(&grid.grid, r, c)) { (SeatingSystem::Empty, true) => SeatingSystem::Occupied, (SeatingSystem::Occupied, true) => SeatingSystem::Empty, (seat, _) => seat, }; previous_grid.set(seat, r, c); changed |= seat != grid.get(r, c); } } mem::swap(&mut grid, &mut previous_grid); if !changed { break; } } grid.occupied_seats() } /* Part One * * Your plane lands with plenty of time to spare. * The final leg of your journey is a ferry that goes directly to the tropical island * where you can finally start your vacation. As you reach the waiting area to board the ferry, * you realize you're so early, nobody else has even arrived yet! * * By modeling the process people use to choose (or abandon) their seat in the waiting area, * you're pretty sure you can predict the best place to sit. You make a quick map of the seat layout (your puzzle input). * * The seat layout fits neatly on a grid. Each position is either floor (.), * an empty seat (L), or an occupied seat (#). For example, the initial seat layout might look like this: * * L.LL.LL.LL * LLLLLLL.LL * L.L.L..L.. * LLLL.LL.LL * L.LL.LL.LL * L.LLLLL.LL * ..L.L..... * LLLLLLLLLL * L.LLLLLL.L * L.LLLLL.LL * * Now, you just need to model the people who will be arriving shortly. * Fortunately, people are entirely predictable and always follow a simple set of rules. * All decisions are based on the number of occupied seats adjacent to a given seat * (one of the eight positions immediately up, down, left, right, or diagonal from the seat). * The following rules are applied to every seat simultaneously: * * If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. * If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. * Otherwise, the seat's state does not change. * Floor (.) never changes; seats don't move, and nobody sits on the floor. * * After one round of these rules, every seat in the example layout becomes occupied: * * #.##.##.## * #######.## * #.#.#..#.. * ####.##.## * #.##.##.## * #.#####.## * ..#.#..... * ########## * #.######.# * #.#####.## * After a second round, the seats with four or more occupied adjacent seats become empty again: * * #.LL.L#.## * #LLLLLL.L# * L.L.L..L.. * #LLL.LL.L# * #.LL.LL.LL * #.LLLL#.## * ..L.L..... * #LLLLLLLL# * #.LLLLLL.L * #.#LLLL.## * This process continues for three more rounds: * * #.##.L#.## * #L###LL.L# * L.#.#..#.. * #L##.##.L# * #.##.LL.LL * #.###L#.## * ..#.#..... * #L######L# * #.LL###L.L * #.#L###.## * #.#L.L#.## * #LLL#LL.L# * L.L.L..#.. * #LLL.##.L# * #.LL.LL.LL * #.LL#L#.## * ..L.L..... * #L#LLLL#L# * #.LLLLLL.L * #.#L#L#.## * #.#L.L#.## * #LLL#LL.L# * L.#.L..#.. * #L##.##.L# * #.#L.LL.LL * #.#L#L#.## * ..L.L..... * #L#L##L#L# * #.LLLLLL.L * #.#L#L#.## * * At this point, something interesting happens: the chaos stabilizes and further * applications of these rules cause no seats to change state! * Once people stop moving around, you count 37 occupied seats. * * Simulate your seating area by applying the seating rules repeatedly until no seats change state. * How many seats end up occupied? */ /// Your puzzle answer was /// ``` /// use advent_of_code_2020::day_11::*; /// let input = include_str!("../input/2020/day11.txt"); /// assert_eq!(solve_part_01(&input_generator(input)), 2183); #[aoc(day11, part1)] pub fn solve_part_01(grid: &[Vec<SeatingSystem>]) -> usize { simulate_seating(grid, should_swap_part_1) } /* Part Two * * As soon as people start to arrive, you realize your mistake. * People don't just care about adjacent seats - they care about the * first seat they can see in each of those eight directions! * * Now, instead of considering just the eight immediately adjacent seats, * consider the first seat in each of those eight directions. * For example, the empty seat below would see eight occupied seats: * * .......#. * ...#..... * .#....... * ......... * ..#L....# * ....#.... * ......... * #........ * ...#..... * * The leftmost empty seat below would only see one empty seat, but cannot see any of the occupied ones: * * ............. * .L.L.#.#.#.#. * ............. * * The empty seat below would see no occupied seats: * * .##.##. * #.#.#.# * ##...## * ...L... * ##...## * #.#.#.# * .##.##. * * Also, people seem to be more tolerant than you expected: * it now takes five or more visible occupied seats for an occupied seat to become empty * (rather than four or more from the previous rules). The other rules still apply: * empty seats that see no occupied seats become occupied, seats matching no rule don't change, and floor never changes. * * Given the same starting layout as above, these new rules cause the seating area to shift around as follows: * * L.LL.LL.LL * LLLLLLL.LL * L.L.L..L.. * LLLL.LL.LL * L.LL.LL.LL * L.LLLLL.LL * ..L.L..... * LLLLLLLLLL * L.LLLLLL.L * L.LLLLL.LL * * #.##.##.## * #######.## * #.#.#..#.. * ####.##.## * #.##.##.## * #.#####.## * ..#.#..... * ########## * #.######.# * #.#####.## * * #.LL.LL.L# * #LLLLLL.LL * L.L.L..L.. * LLLL.LL.LL * L.LL.LL.LL * L.LLLLL.LL * ..L.L..... * LLLLLLLLL# * #.LLLLLL.L * #.LLLLL.L# * * #.L#.##.L# * #L#####.LL * L.#.#..#.. * ##L#.##.## * #.##.#L.## * #.#####.#L * ..#.#..... * LLL####LL# * #.L#####.L * #.L####.L# * * #.L#.L#.L# * #LLLLLL.LL * L.L.L..#.. * ##LL.LL.L# * L.LL.LL.L# * #.LLLLL.LL * ..L.L..... * LLLLLLLLL# * #.LLLLL#.L * #.L#LL#.L# * * #.L#.L#.L# * #LLLLLL.LL * L.L.L..#.. * ##L#.#L.L# * L.L#.#L.L# * #.L####.LL * ..#.#..... * LLL###LLL# * #.LLLLL#.L * #.L#LL#.L# * * #.L#.L#.L# * #LLLLLL.LL * L.L.L..#.. * ##L#.#L.L# * L.L#.LL.L# * #.LLLL#.LL * ..#.L..... * LLL###LLL# * #.LLLLL#.L * #.L#LL#.L# * * Again, at this point, people stop shifting around and the seating area reaches equilibrium. * Once this occurs, you count 26 occupied seats. * * Given the new visibility method and the rule change for occupied seats becoming empty, * once equilibrium is reached, how many seats end up occupied? */ /// Your puzzle answer was /// ``` /// use advent_of_code_2020::day_11::*; /// let input = include_str!("../input/2020/day11.txt"); /// assert_eq!(solve_part_02(&input_generator(input)), 1990); /// ``` #[aoc(day11, part2)] pub fn solve_part_02(grid: &[Vec<SeatingSystem>]) -> usize { simulate_seating(grid, should_swap_part_2) } #[cfg(test)] mod tests { use super::*; /// Test example data on part 1 #[test] fn test_example_part_1() { let data = "L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL "; assert_eq!(solve_part_01(&input_generator(data)), 37) } /// Test example data on part 2 #[test] fn test_example_part_2() { let data = "L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL "; assert_eq!(solve_part_02(&input_generator(data)), 26) } }
SQL
UTF-8
670
3.921875
4
[]
no_license
--Câu truy vấn tương đương viết inner join SELECT distinct s.MaSach, s.TenSach FROM Sach s INNER JOIN Sach_TacGia stg ON s.MaSach = stg.MaSach WHERE stg.SoGio > 10; --cho biết tổng số giờ viết mỗi cuốn sách SELECT s.TenSach, truyvancon1.tong_so_gio_viet FROM Sach s, (SELECT stg.MaSach, SUM(stg.SoGio) AS tong_so_gio_viet FROM Sach_TacGia stg GROUP BY stg.MaSach) truyvancon1 WHERE truyvancon1.MaSach = s.MaSach; -- cho biết sách với số giờ lớn nhất của mỗi loại sách SELECT s.MaSach, s.TenSach, (SELECT MAX(stg.SoGio) FROM Sach_TacGia stg WHERE s.MaSach = stg.MaSach) as truyvancon2 FROM Sach s;
Java
UTF-8
531
1.953125
2
[]
no_license
package com.example.restapi.repository; import com.example.restapi.entity.AirCompany; import com.example.restapi.entity.Flight; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Repository public interface FlightRepository extends CrudRepository<Flight, Long> { List<Flight> findByFlightStatus(Flight.FlightStatus status); @Transactional void deleteById(Long id); }
JavaScript
UTF-8
1,007
3.1875
3
[]
no_license
function Device(id, name, room, properties) { this.id = id; this.name = name; this.properties = properties; this.roomID = room; } function Room(id, name) { this.id = id; this.name = name; } function HashMap() { var array = []; this.get = function get(key) { for(i = 0; i < array.length; ++i) { var obj = array[i]; // alert(key + "-" + obj.key); if(obj.key === key) { return obj.value; break; } } return null; } this.add = function add(key, value) { var entry = new KeyValue(key, value); for(i = 0; i < array.length; ++i) { var obj = array[i]; if(obj.key === key) { obj.value = value; break; } } array.push(entry); } this.containsKey = function containsKey(key) { for(i = 0; i < array.length; ++i) { var obj = array[i]; if(obj.key === key) { return true; break; } } return false; } this.size = function size() { return array.length; } } function KeyValue(key, value) { this.key = key; this.value = value; }
Ruby
UTF-8
589
3.796875
4
[ "WTFPL" ]
permissive
# Parent class for objects that hold cards class CardHolder attr_reader :pile def initialize @pile = [] end # Add a card to this CardHolder def append(card) @pile << card end # remove the top card from the pile def pop @pile.pop end # reveals the top card from the pile def peek @pile.last end # return the number of cards in this CardHolder def count @pile.count end def to_s if @pile.empty? "[]" else @pile.reduce("") { |acc, card| acc += "#{card} " } end end def empty? @pile.empty? end end
Java
UHC
2,595
3.671875
4
[]
no_license
package crypto; import java.util.Scanner; public class CaesarCipher { // ȣ ΰ? // ޼ ְޱ (ȣ ä ) // ȣȭ(Encryption) // (Ϲ ޼) ȣ( ޼) ٲٴ // ȣȭ(Decryption) // ȣ ǵ // Ű(key) // ȣȭ ȣȭ Ǵ // (ī̻縣) ȣ // ĺ Ű(key) ŭ ̵Ű ȣ // ȣȭ : Ű ŭ ̵Ŵ // ȣȭ : ȣ Ű ŭ ̵Ŵ // /ȣȭ // ABCDEFGHIJKLMNOPQRSTUVWXYZ !@#$,abcdef... // key 3 ȣȭ (+3) // "Hello, World!" => "Khoorc#Zruog%" // key 3 ȣȭ (-3) // "Khoorc#Zruog%" => "Hello, World!" int key; public CaesarCipher(int key) { this.key = key; } //32~126 public String encryption(String plain_text) { //Ű ȣȭ Ͽ ϴ Լ StringBuilder result = new StringBuilder(""); Scanner sc = new Scanner(System.in); for (int i = 0; i < plain_text.length(); i++) { if(plain_text.charAt(i)>=32 && plain_text.charAt(i)<=216) { if(plain_text.charAt(i)+key>126) { char tmp = plain_text.charAt(i); for (int j = 0; j < key%94; j++) { if(tmp==126) { tmp=32; }else { tmp++; } } result.append(tmp); }else { result.append((char)(plain_text.charAt(i)+key)); } }else { result.append(plain_text.charAt(i)); } } return result.toString(); } public String decryption(String crypto_text) { // Ű ȣ ȣȭ Ͽ ϴ Լ StringBuilder result = new StringBuilder(""); for (int i = 0; i < crypto_text.length(); i++) { if(crypto_text.charAt(i)>=32 && crypto_text.charAt(i)<=216) { if(crypto_text.charAt(i)-key<32) { char tmp = crypto_text.charAt(i); for (int j = 0; j < key%94; j++) { if(tmp==32) { tmp=126; }else { tmp--; } } result.append((char)tmp); }else { result.append((char)(crypto_text.charAt(i)-key)); } }else { result.append(crypto_text.charAt(i)); } } return result.toString(); } }
Markdown
UTF-8
1,735
4.375
4
[]
no_license
# Smallest Difference In this activity you will be writing code to create a function that takes in two sorted arrays of integers. Your function should return a new two element array containing one number from each sorted array with the smallest difference. ## Instructions - Open [Unsolved/smallest-difference.js](Unsolved/smallest-difference.js) in your code editor -- **this is the only file you will modify in this activity.** - In this file you will be writing code in the body of the `smallestDifference` function to achieve the following: - Return a two element array containing the integers from both arrays with the smallest distance. - For example, given the following arrays: ```js const arr1 = [1, 6, 7, 9]; const arr1 = [8, 9, 10, 11, 12, 13]; ``` - The following should be returned: ```js [9, 9]; ``` - Since both arrays contain the number `9` and the difference between same numbers is `0`. - Given the following arrays: ```js const arr1 = [2, 4, 6, 8, 15, 20]; const arr2 = [17, 25, 30, 47]; ``` - The following should be returned: ```js [15, 17]; ``` - Since the difference between `15` and `17` is `2`, the smallest difference between any two numbers across the arrays - Assume each array will contain at least one integer. - You can check to see if your function works properly by opening [Unsolved/test.html](Unsolved/test.html) in your web browser. - Functions that _pass_ the tests will be denoted with a **green check mark**. - Functions that _fail_ the tests will be denoted with a **red x and an error message**. ### Hints - How can you use the fact that the arrays are sorted to your advantage?
PHP
UTF-8
445
2.640625
3
[]
no_license
<?php namespace Admin\Controller; use Hdphp\Controller\Controller; /** * 商品详细管理控制器 */ class GoodsDetailController extends CommonController{ // 定义一个商品属性,为了全局调用 private $model; // 构造方法 public function __construct(){ // 防止父级构造方法被覆盖 parent::__construct(); // 实例化\Common\Model(命名空间)下的控制器Goods $this->model = new \Common\Model\Goods; } }
Java
UTF-8
11,969
2.015625
2
[]
no_license
/* * Copyright (C) 2014 omar * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tn.mariages.gui; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.UIManager; import tn.mariages.dao.ClientDAO; import tn.mariages.dao.ReclamationDAO; import tn.mariages.entities.Reclamation; /** * * @author omar */ public class AjouterReclamation extends javax.swing.JFrame { /** * Creates new form AjouterReclamation */ int id; public AjouterReclamation() { try { org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); UIManager.put("RootPane.setupButtonVisible", false); } catch (Exception e) { //TODO exception } initComponents(); } public AjouterReclamation(int id) { try { org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); UIManager.put("RootPane.setupButtonVisible", false); } catch (Exception e) { //TODO exception } this.id=id; initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); texteReclamation = new javax.swing.JTextArea(); texteMail = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); texteObjet = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); texteReclamation.setColumns(20); texteReclamation.setRows(5); texteReclamation.setText("Reclamation"); jScrollPane1.setViewportView(texteReclamation); texteMail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { texteMailActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Corbel", 1, 14)); // NOI18N jLabel1.setText("Reclamation"); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/circle_plus.png"))); // NOI18N jButton1.setText("Ajouter"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); texteObjet.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { texteObjetActionPerformed(evt); } }); jLabel2.setText("Mail"); jLabel3.setText("Objet"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(81, 81, 81) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(texteMail, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(texteObjet))))) .addContainerGap(90, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(texteMail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(texteObjet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1) .addGap(50, 50, 50)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void texteMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_texteMailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_texteMailActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String date_format="yyyy-MM-dd"; Calendar cal=Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(date_format); String dt = sdf.format(cal.getTime()); Reclamation r = new Reclamation(texteMail.getText(),dt,texteObjet.getText(),texteReclamation.getText()); ReclamationDAO rdao = new ReclamationDAO(); rdao.insertReclamation(r); }//GEN-LAST:event_jButton1ActionPerformed private void texteObjetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_texteObjetActionPerformed // TODO add your handling code here: }//GEN-LAST:event_texteObjetActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened texteMail.setText(new ClientDAO().findClientById(id).getEmailClient()); }//GEN-LAST:event_formWindowOpened /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AjouterReclamation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AjouterReclamation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AjouterReclamation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AjouterReclamation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> try { org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); UIManager.put("RootPane.setupButtonVisible", false); } catch (Exception e) { //TODO exception } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AjouterReclamation().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField texteMail; private javax.swing.JTextField texteObjet; private javax.swing.JTextArea texteReclamation; // End of variables declaration//GEN-END:variables }
Java
UTF-8
594
2.359375
2
[]
no_license
package com.khtn.npuzzle.model; public class TopUserScore { private String Nickname; private int TongDiem; public String getNickname() { return Nickname; } public void setNickname(String nickname) { Nickname = nickname; } public int getTongDiem() { return TongDiem; } public void setTongDiem(int tongDiem) { TongDiem = tongDiem; } public TopUserScore(String nickname, int tongDiem) { super(); Nickname = nickname; TongDiem = tongDiem; } @Override public String toString() { return "TopUserScore [Nickname=" + Nickname + ", TongDiem=" + TongDiem + "]"; } }
Java
UTF-8
30,635
2.25
2
[]
no_license
package com.karlo.gui; import com.karlo.bl.AppointmentsHandler; import com.karlo.bl.GeneralPhysiciansHandler; import com.karlo.bl.MedicalPerscriptionsHandler; import com.karlo.bl.PatientsHandler; import com.karlo.bl.SpecialistsHandler; import com.karlo.bl.TestsHandler; import com.karlo.model.Appointment; import com.karlo.model.GeneralPhysician; import com.karlo.model.MedicalPerscription; import com.karlo.model.Patient; import com.karlo.model.Specialist; import com.karlo.model.Test; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.ListSelectionModel; import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER; import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; import javax.swing.UnsupportedLookAndFeelException; public class MainMenu extends JFrame{ private static final GeneralPhysiciansHandler GENERALPHYSICIAN_HANDLER = new GeneralPhysiciansHandler(); private static final PatientsHandler PATIENTS_HANDLER = new PatientsHandler(); private static final SpecialistsHandler SPECIALISTS_HANDLER = new SpecialistsHandler(); private static final AppointmentsHandler APPOINTMENTS_HANDLER = new AppointmentsHandler(); private static final MedicalPerscriptionsHandler MEDICAL_P_HANDLER = new MedicalPerscriptionsHandler(); private static final TestsHandler TESTS_HANDLER = new TestsHandler(); final static String GENPANEL = "General Physicians"; final static String SPECPANEL = "Specialists"; public MainMenu() throws HeadlessException { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { try { javax.swing.UIManager.setLookAndFeel(info.getClassName()); } catch (ClassNotFoundException ex) { Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex); } break; } } javax.swing.SwingUtilities.invokeLater(() -> { createMainMenu(); }); } public void createMainMenu() { JFrame frame = new JFrame("Virgo Hospital"); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setResizable(false); loadMainMenu(frame); frame.pack(); frame.setVisible(true); } public void loadMainMenu(JFrame frame) { JTabbedPane tpMainGui = new JTabbedPane(); // <editor-fold defaultstate="collapsed" desc="Patient Registration"> JPanel pnlRegistration = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JButton btnMiniRegistration = new JButton("Mini Registration Form"); btnMiniRegistration.setPreferredSize(new Dimension(300,70)); c.insets = new Insets(3, 3, 3, 3); JButton btnComprehensiveRegistration = new JButton("Comprehensive Registration Form"); btnComprehensiveRegistration.setPreferredSize(new Dimension(300,70)); pnlRegistration.add(btnMiniRegistration,c); btnMiniRegistration.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new MiniRegistration(); } }); btnComprehensiveRegistration.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new ComprehensiveRegistration(); } }); pnlRegistration.add(btnComprehensiveRegistration,c); tpMainGui.add("Patient Registration",pnlRegistration); frame.add(tpMainGui); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="View Patients"> JPanel pnlViewPatients = new JPanel(new GridBagLayout()); JComboBox<GeneralPhysician> cbGeneralPhysician = new JComboBox(); DefaultComboBoxModel<GeneralPhysician> doctorsModel; doctorsModel = new DefaultComboBoxModel<>(); GENERALPHYSICIAN_HANDLER.getGeneralPhysicians().forEach(e -> doctorsModel.addElement(e)); cbGeneralPhysician.setModel(doctorsModel); cbGeneralPhysician.setPreferredSize(new Dimension(100,35)); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST; pnlViewPatients.add(cbGeneralPhysician,c); c.insets = new Insets(3, 220, 3, 3); JCheckBox cbAllPatients = new JCheckBox("View All Patients"); pnlViewPatients.add(cbAllPatients,c); c.insets = new Insets(3, 3, 3, 3); JList<Patient> lPatients = new JList(PATIENTS_HANDLER.getPatients().toArray()); DefaultListModel<Patient> patientsModel; patientsModel = new DefaultListModel<>(); JScrollPane scrollPane1 = new JScrollPane(); scrollPane1.setViewportView(lPatients); lPatients.setLayoutOrientation(JList.VERTICAL); cbAllPatients.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED){ patientsModel.clear(); PATIENTS_HANDLER.getPatients().forEach(ef -> patientsModel.addElement(ef)); lPatients.setModel(patientsModel); } else refreshPatientsList(cbGeneralPhysician, patientsModel, lPatients, cbAllPatients); } }); refreshPatientsList(cbGeneralPhysician, patientsModel, lPatients,cbAllPatients); cbGeneralPhysician.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cbAllPatients.setSelected(false); refreshPatientsList(cbGeneralPhysician, patientsModel, lPatients,cbAllPatients); } }); c.gridx = 0; c.gridy = 1; scrollPane1.setPreferredSize(new Dimension(500,200)); pnlViewPatients.add(scrollPane1,c); c.gridy = 2; JButton btnEdit = new JButton("Edit Patient"); c.anchor = GridBagConstraints.WEST; btnEdit.setPreferredSize(new Dimension(90,30)); pnlViewPatients.add(btnEdit,c); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { new EditPatient(lPatients.getSelectedValue().getId()); } catch (NullPointerException ex) { JOptionPane.showMessageDialog(frame, "Please select a patient!!"); } } }); JButton btnApp = new JButton("Make new appointment"); btnApp.setPreferredSize(new Dimension(160,30)); c.insets = new Insets(3, 120, 3, 3); pnlViewPatients.add(btnApp,c); btnApp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { new MakeAppointmentForPatient(lPatients.getSelectedValue().getId(),((GeneralPhysician)doctorsModel.getSelectedItem()).getId()); } catch (NullPointerException ex) { JOptionPane.showMessageDialog(frame, "Please select a patient!!"); } } }); JButton btnMed = new JButton("Delete Patient"); btnMed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (lPatients.getSelectedValue() != null) { if (JOptionPane.showConfirmDialog(frame, "Are you sure?") == JOptionPane.YES_OPTION) { PATIENTS_HANDLER.deletePatient(lPatients.getSelectedValue().getId()); } } else JOptionPane.showMessageDialog(frame, "Select Patient"); } }); btnMed.setPreferredSize(new Dimension(130,30)); c.insets = new Insets(3, 312, 3, 3); pnlViewPatients.add(btnMed,c); tpMainGui.add("Patients",pnlViewPatients); JTabbedPane tpPersonel = new JTabbedPane(); //</editor-fold> // <editor-fold defaultstate="collapsed" desc="View General Physicians"> JPanel pnlGeneralPhysician = new JPanel(new GridBagLayout()); JList<GeneralPhysician> listGP = new JList(); DefaultListModel<GeneralPhysician> listdoctorsModel; listdoctorsModel = new DefaultListModel<>(); refreshGenPhyList(listGP, listdoctorsModel); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(listGP); listGP.setLayoutOrientation(JList.VERTICAL); scrollPane.setPreferredSize(new Dimension(500,200)); c.insets = new Insets(3,3,3,3); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.EAST; pnlGeneralPhysician.add(scrollPane,c); c.gridy = 1; JButton btnCreateGP = new JButton("Create"); c.anchor = GridBagConstraints.WEST; c.insets = new Insets(3, 3, 3, 3); btnCreateGP.setPreferredSize(new Dimension(80,30)); pnlGeneralPhysician.add(btnCreateGP,c); btnCreateGP.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new CreateGeneralPhysician(); } }); JButton btnEditGP = new JButton("Edit"); btnEditGP.setPreferredSize(new Dimension(80,30)); c.insets = new Insets(3, 86, 3, 3); pnlGeneralPhysician.add(btnEditGP,c); btnEditGP.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listGP.getSelectedValue() == null) { JOptionPane.showMessageDialog(frame, "Please select Physician"); } else new EditGeneralPhysician(listGP.getSelectedValue().getId()); } }); JButton btnDeleteGP = new JButton("Delete"); btnDeleteGP.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(frame, "Are you sure you want to delete the General Physician?") == JOptionPane.YES_OPTION) { try { GENERALPHYSICIAN_HANDLER.deleteGeneralPhysician(listGP.getSelectedValue().getId()); } catch (NullPointerException ex) { JOptionPane.showMessageDialog(frame, "Please select General Physician!"); } } } }); btnDeleteGP.setPreferredSize(new Dimension(80,30)); c.insets = new Insets(3, 169, 3, 3); pnlGeneralPhysician.add(btnDeleteGP,c); tpPersonel.add("General Physicians",pnlGeneralPhysician); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="View Spec"> c.insets = new Insets(3, 3, 3, 3); c.gridy = 0; JPanel viewSpec = new JPanel(new GridBagLayout()); JList<Specialist> listSpec = new JList(); DefaultListModel<Specialist> specModel; specModel = new DefaultListModel<>(); SPECIALISTS_HANDLER.getSpecialists().forEach(ef -> specModel.addElement(ef)); listSpec.setModel(specModel); JScrollPane scrollPane2 = new JScrollPane(); scrollPane2.setViewportView(listSpec); listSpec.setLayoutOrientation(JList.VERTICAL); scrollPane2.setPreferredSize(new Dimension(500,200)); viewSpec.add(scrollPane2,c); c.gridy = 1; JButton btnCreateS = new JButton("Create"); c.anchor = GridBagConstraints.WEST; c.insets = new Insets(3, 3, 3, 3); btnCreateS.setPreferredSize(new Dimension(80,30)); viewSpec.add(btnCreateS,c); JButton btnEditS = new JButton("Edit"); btnEditS.setPreferredSize(new Dimension(80,30)); btnEditS.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listSpec.getSelectedValue() == null) { JOptionPane.showMessageDialog(frame, "Please choose Specialist"); } else new EditSpecialist(listSpec.getSelectedValue().getId()); } }); c.insets = new Insets(3, 86, 3, 3); viewSpec.add(btnEditS,c); btnCreateS.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new CreateSpecialist(); } }); JButton btnDeleteS = new JButton("Delete"); btnDeleteS.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(frame, "Are you sure you want to delete the Specialist?") == JOptionPane.YES_OPTION) { try { SPECIALISTS_HANDLER.deleteSpecialist(listSpec.getSelectedValue().getId()); refreshSpecialist(specModel, listSpec); } catch (NullPointerException ex) { JOptionPane.showMessageDialog(frame, "Please select Specialist!"); } } } }); btnDeleteS.setPreferredSize(new Dimension(80,30)); c.insets = new Insets(3, 169, 3, 3); viewSpec.add(btnDeleteS,c); tpPersonel.add("Specialists",viewSpec); tpMainGui.add("Personel",tpPersonel); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="View Appointments"> JPanel viewAppointments = new JPanel(new GridBagLayout()); c.insets = new Insets(3, 3, 3, 3); c.gridx = 0; c.gridy = 0; String[] choose = { "Upcoming", "All" }; JComboBox cbApp = new JComboBox(choose); c.anchor = GridBagConstraints.WEST; viewAppointments.add(cbApp); c.gridy = 1; cbGeneralPhysician.setPreferredSize(new Dimension(200,20)); JList<Appointment> listApp = new JList(); JScrollPane spApp = new JScrollPane(); spApp.setViewportView(listApp); DefaultListModel<Appointment> appModel = new DefaultListModel<>(); listApp.setLayoutOrientation(JList.VERTICAL); spApp.setPreferredSize(new Dimension(500,200)); viewAppointments.add(spApp,c); setUpcoming(appModel, listApp); cbApp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (cbApp.getSelectedItem().toString() == "All") { appModel.clear(); APPOINTMENTS_HANDLER.getAppointments().forEach((Appointment ef) -> { if ("ERROR".equals(ef.toString())) { } else appModel.addElement(ef);}); listApp.setModel(appModel); } else{ appModel.clear(); APPOINTMENTS_HANDLER.getUpcomingAppointments().forEach(ef -> { if (ef.toString() == "ERROR") { } else appModel.addElement(ef);}); listApp.setModel(appModel); }} }); c.gridy = 2; c.insets = new Insets(3, 3, 3, 3); JButton btnCreateApp = new JButton("Create Appontment"); btnCreateApp.setPreferredSize(new Dimension(150,30)); viewAppointments.add(btnCreateApp,c); btnCreateApp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new CreateNewAppointment(); } }); c.insets = new Insets(3, 160, 3, 3); JButton btnDelApp = new JButton("Delete Appontment"); btnDelApp.setPreferredSize(new Dimension(150,30)); viewAppointments.add(btnDelApp,c); btnDelApp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listApp.getSelectedValue() == null) { JOptionPane.showMessageDialog(frame, "Please choose Appointment"); } else{ if (JOptionPane.showConfirmDialog(frame, "Are you sure?") == JOptionPane.YES_OPTION) { APPOINTMENTS_HANDLER.deleteAppointment(listApp.getSelectedValue().getId()); } } } }); c.insets = new Insets(3, 320, 3, 3); JButton btnOpenApp = new JButton("Manage Appointment"); btnOpenApp.setPreferredSize(new Dimension(150,30)); viewAppointments.add(btnOpenApp,c); btnOpenApp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (listApp.getSelectedValue() != null) { new ViewTreatment(listApp.getSelectedValue()); } else JOptionPane.showMessageDialog(frame, "Please choose Appointment"); } }); tpMainGui.add("Appointments",viewAppointments); // </editor-fold> //<editor-fold defaultstate="collapsed" desc="History"> JTabbedPane tpHistory = new JTabbedPane(); JPanel historyApp = new JPanel(new GridBagLayout()); JPanel historyTest = new JPanel(new GridBagLayout()); JPanel historyMedP = new JPanel(new GridBagLayout()); c.anchor = GridBagConstraints.WEST; c.gridx = 0; c.gridy = 0; c.insets = new Insets(3, 3, 3, 3); JComboBox<Patient> cbPat = new JComboBox(); DefaultComboBoxModel<Patient> patModel; patModel = new DefaultComboBoxModel<>(); PATIENTS_HANDLER.getPatients().forEach(e -> patModel.addElement(e)); cbPat.setModel(patModel); historyApp.add(cbPat,c); JList<Appointment> listAppH = new JList(); JScrollPane spAppH = new JScrollPane(); spAppH.setViewportView(listAppH); DefaultListModel<Appointment> appModel2 = new DefaultListModel<>(); listAppH.setLayoutOrientation(JList.VERTICAL); spAppH.setPreferredSize(new Dimension(500,200)); listAppH.setPreferredSize(new Dimension(500,200)); c.gridy = 1; APPOINTMENTS_HANDLER.getAppForPatient(((Patient)cbPat.getSelectedItem())).forEach(ef -> appModel2.addElement(ef)); listAppH.setModel(appModel2); historyApp.add(spAppH,c); cbPat.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { appModel2.clear(); APPOINTMENTS_HANDLER.getAppForPatient(((Patient)cbPat.getSelectedItem())).forEach(ef -> appModel2.addElement(ef)); listAppH.setModel(appModel2); } }); tpHistory.add(historyApp,"Appointments"); c.anchor = GridBagConstraints.WEST; c.gridx = 0; c.gridy = 0; c.insets = new Insets(3, 3, 3, 3); JComboBox<Patient> cbPat2 = new JComboBox(); DefaultComboBoxModel<Patient> patModel2; patModel2 = new DefaultComboBoxModel<>(); PATIENTS_HANDLER.getPatients().forEach(e -> patModel2.addElement(e)); cbPat2.setModel(patModel2); historyMedP.add(cbPat2,c); JList<MedicalPerscription> listMedH = new JList(); JScrollPane spMedH = new JScrollPane(); spMedH.setViewportView(listMedH); DefaultListModel<MedicalPerscription> appModel3 = new DefaultListModel<>(); listMedH.setLayoutOrientation(JList.VERTICAL); spMedH.setPreferredSize(new Dimension(500,200)); listMedH.setPreferredSize(new Dimension(500,200)); c.gridy = 1; MEDICAL_P_HANDLER.getMedicalPerscriptionsForPatient(((Patient)cbPat.getSelectedItem())).forEach(ef -> appModel3.addElement(ef)); listMedH.setModel(appModel3); historyMedP.add(spMedH,c); tpHistory.add(historyMedP,"Medicines Perscribed"); cbPat2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { appModel3.clear(); MEDICAL_P_HANDLER.getMedicalPerscriptionsForPatient(((Patient)cbPat2.getSelectedItem())).forEach(ef -> appModel3.addElement(ef)); listMedH.setModel(appModel3); } }); c.gridx = 0; c.gridy = 0; JComboBox<Patient> cbPat3 = new JComboBox(); DefaultComboBoxModel<Patient> patModel3; patModel3 = new DefaultComboBoxModel<>(); PATIENTS_HANDLER.getPatients().forEach(e -> patModel3.addElement(e)); cbPat3.setModel(patModel3); historyTest.add(cbPat3,c); JList<Test> listTestH = new JList(); JScrollPane spTestH = new JScrollPane(); spTestH.setViewportView(listTestH); DefaultListModel<Test> appModel4 = new DefaultListModel<>(); listTestH.setLayoutOrientation(JList.VERTICAL); spTestH.setPreferredSize(new Dimension(500,200)); listTestH.setPreferredSize(new Dimension(500,200)); c.gridy = 1; Patient p = PATIENTS_HANDLER.getPatient(cbPat3.getSelectedIndex()+1); TESTS_HANDLER.getTestsForPatient(p).forEach(ef1 -> appModel4.addElement(ef1)); listTestH.setModel(appModel4); historyTest.add(spTestH,c); tpHistory.add(historyTest,"Tests"); cbPat3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Patient p2 = PATIENTS_HANDLER.getPatient(cbPat3.getSelectedIndex()+1); appModel4.clear(); TESTS_HANDLER.getTestsForPatient(p2).forEach(ef1 -> appModel4.addElement(ef1)); listTestH.setModel(appModel4); } }); listAppH.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { new ViewTreatment(listAppH.getSelectedValue()); } } }); tpMainGui.add(tpHistory,"History"); //</editor-fold> listApp.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); lPatients.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listGP.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listSpec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listAppH.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listTestH.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listMedH.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); spAppH.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED); spTestH.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED); spMedH.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED); spAppH.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER); spTestH.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER); spMedH.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER); frame.addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e){ refreshCBGenPhy(cbGeneralPhysician, doctorsModel); refreshPatientsList(cbGeneralPhysician, patientsModel, lPatients,cbAllPatients); specModel.clear(); SPECIALISTS_HANDLER.getSpecialists().forEach(ef -> specModel.addElement(ef)); listSpec.setModel(specModel); refreshGenPhyList(listGP,listdoctorsModel); Patient p2 = PATIENTS_HANDLER.getPatient(cbPat3.getSelectedIndex()+1); appModel4.clear(); TESTS_HANDLER.getTestsForPatient(p2).forEach(ef1 -> appModel4.addElement(ef1)); listTestH.setModel(appModel4); appModel3.clear(); MEDICAL_P_HANDLER.getMedicalPerscriptionsForPatient(((Patient)cbPat2.getSelectedItem())).forEach(ef -> appModel3.addElement(ef)); appModel2.clear(); APPOINTMENTS_HANDLER.getAppForPatient(((Patient)cbPat.getSelectedItem())).forEach(ef -> appModel2.addElement(ef)); listAppH.setModel(appModel2); listMedH.setModel(appModel3); if (cbApp.getSelectedItem().toString() == "Upcoming") { setUpcoming(appModel, listApp); } else { appModel.clear(); APPOINTMENTS_HANDLER.getAppointments().forEach((Appointment ef) -> { if ("ERROR".equals(ef.toString())) { } else appModel.addElement(ef);}); listApp.setModel(appModel); } } }); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - frame.getWidth()) / 4); int y = (int) ((dimension.getHeight() - frame.getHeight()) / 4); frame.setLocation(x, y); frame.setPreferredSize(new Dimension(930,590)); } public void setUpcoming(DefaultListModel<Appointment> appModel, JList<Appointment> listApp) { appModel.clear(); APPOINTMENTS_HANDLER.getUpcomingAppointments().forEach(ef -> { if (ef.toString() == "ERROR") { } else appModel.addElement(ef);}); listApp.setModel(appModel); } private void refreshSpecialist(DefaultListModel<Specialist> specModel, JList<Specialist> listSpec) { specModel.clear(); SPECIALISTS_HANDLER.getSpecialists().forEach(ef -> specModel.addElement(ef)); listSpec.setModel(specModel); } private void refreshPatientsList(JComboBox<GeneralPhysician> cbGP, DefaultListModel<Patient> patientsModel,JList<Patient> lPatients,JCheckBox all){ if (all.isSelected()) { patientsModel.clear(); PATIENTS_HANDLER.getPatients().forEach(ef -> patientsModel.addElement(ef)); lPatients.setModel(patientsModel); } else{ try { patientsModel.clear(); PATIENTS_HANDLER.getPatientsForGeneralPhysician(((GeneralPhysician) cbGP.getSelectedItem()).getId()).forEach(ef -> patientsModel.addElement(ef)); lPatients.setModel(patientsModel); } catch (NullPointerException e) { }} } private void refreshCBGenPhy(JComboBox<GeneralPhysician> cbGP, DefaultComboBoxModel<GeneralPhysician> doctorsModel) { try { doctorsModel.removeAllElements(); GENERALPHYSICIAN_HANDLER.getGeneralPhysicians().forEach(e -> doctorsModel.addElement(e)); cbGP.setModel(doctorsModel); } catch (Exception e) { } } private void refreshGenPhyList(JList<GeneralPhysician> listGP, DefaultListModel<GeneralPhysician> listdoctorsModel) { try { listdoctorsModel.clear(); GENERALPHYSICIAN_HANDLER.getGeneralPhysicians().forEach(e -> listdoctorsModel.addElement(e)); listGP.setModel(listdoctorsModel); } catch (Exception e) { } } }