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
Java
UTF-8
1,219
2.875
3
[]
no_license
package main; import items.Item; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.io.IOException; import javax.imageio.ImageIO; public class PlayerInventory extends Inventory { Image img; int imgWidth = 442, imgHeight = 64; public Item equippedItem = null; public PlayerInventory() { super(); columns = 8; rows = 1; } public void render(Graphics g, int screenX, int screenY) { try { img = ImageIO.read(Game.class.getResourceAsStream("inventory.png")); } catch (IOException e) { System.out.println("Inventory image not found! (1)"); } catch (IllegalArgumentException e) { System.out.println("Inventory image not found! (2)"); } g.drawImage(img, screenX/2 - imgWidth/2, screenY - imgHeight, screenX/2 + imgWidth/2, screenY, 0, 0, imgWidth, imgHeight, null); InventoryItem item; for(int i=0; i<items.size(); i++) { item = items.get(i); //item.item.render(g, screenX/2 - imgWidth/2 + i*2, screenY - imgHeight/2 - 1.0f); g.setColor(Color.WHITE); g.drawString("" + item.quantity, screenX/2 - imgWidth/2 + 8, screenY - imgHeight + 18); } } }
Markdown
UTF-8
1,853
4.28125
4
[]
no_license
# EX27: Memorizing Logic * ### 学习内容:`not`;`or`;`and`;`not or`;`not and`;`!=`;`==` * #### `not` | Not | True? | | ----------- | ------- | | `not False` | `True` | | `not True` | `False` | * #### `or` * 只要有`True`,即为`True`;必须全`False`,才为`False`。 | OR | True? | | ---------------- | ------- | | `True or False` | `True` | | `True or True` | `True` | | `False or True` | `True` | | `False or False` | `False` | * #### `and` * 必须全`True`,才为`True`;只要有`False`,即为`False` | AND | True? | | ----------------- | ------- | | `True and False` | `False` | | `True and True` | `True` | | `False and True` | `False` | | `False and False` | `False` | * #### `not or` * 按或操作,结果取反 | NOT OR | True? | | --------------------- | ------- | | `not(True or False)` | `False` | | `not(True or True)` | `False` | | `not(False or True)` | `False` | | `not(False or False)` | `True` | * #### `not and` * 按与操作,结果取反 | NOT AND | True? | | --------------------- | ------- | | `not(True and False)` | `True` | | `not(True and True)` | `False` | | `not(False and True)` | `True` | | `not(False or False)` | `True` | * #### `!=` * 不等于 | != | True? | | -------- | ------- | | `1 != 0` | `True` | | `1 != 1` | `False` | | `0 != 1` | `True` | | `0 != 0` | `False` | * #### `==` * 比较是否相等 | == | True? | | -------- | ------- | | `1 == 0` | `False` | | `1 == 1` | `True` | | `0 == 1` | `False` | | `0 == 0` | `True` |
Ruby
UTF-8
376
4.21875
4
[]
no_license
def sum(c,d) val = c+d return val #single return end puts sum(4,5) def kotak(a,b,c) return a*a, b*b, c*c #multi return end arr = kotak(1,2,3) puts arr def demo(a, b) a = b - 5 b = a - 3 #akhir bari akan me return hasil end puts demo(2,6) def add(a,b) a+b end def times(a,b) a*b end x = times(add(2,3),add(1,2)) #return dari method puts x
Python
UTF-8
429
3
3
[]
no_license
from numbers.mqt_number import MqtNumber from numbers.number_types import MQT_DECIMAL_FRACTION class MqtDecimalFraction(MqtNumber): __type = MQT_DECIMAL_FRACTION @property def type(self): return self.__type @property def value(self): return self.__value def __init__(self, value: float): self.__value = value def value_to_str(self) -> str: return str(self.value)
C++
UTF-8
1,597
2.65625
3
[ "MIT" ]
permissive
#include "../include/helper.hpp" #include <random> void printProgress(double percentage) { int val = (int)(percentage * 100); int lpad = (int)(percentage * PBWIDTH); int rpad = PBWIDTH - lpad; printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, ""); fflush(stdout); if (val == 100) printf("\n"); } void generateRandomState(spin_t trotters[MAX_NTROT][MAX_NSPIN], int nTrot, int nSpin) { /* Random Device & Random Number Generator */ static std::random_device rd; static std::mt19937 rng(rd()); static std::uniform_int_distribution<int> unif(0, 1); /* Generate */ for (int i = 0; i < nTrot; i++) { for (int j = 0; j < nSpin; j++) { trotters[i][j] = (bool)unif(rng); } } } fp_t computeEnergyPerTrotter(int nSpin, spin_t trotter[MAX_NSPIN], fp_t Jcoup[MAX_NSPIN][MAX_NSPIN], fp_t h[MAX_NSPIN]) { /* Follow the Formula */ /* H = sum(J(i,j) * spin[i] * spin[j]) + sum(h[i] * spin[i]) */ /* Total Energy */ fp_t H = 0; /* Traverse All Spins */ for (int i = 0; i < nSpin; i++) { /* Two-Spin Energy */ for (int j = 0; j < nSpin; j++) { if (trotter[i] == trotter[j]) H += Jcoup[i][j]; else H -= Jcoup[i][j]; } /* One-Spin Energy */ if (trotter[i]) H += h[i]; else H -= h[i]; } /* Return */ // return fabs(H); return (H); }
C++
UTF-8
2,112
3.1875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; typedef long long int ll; struct node{ node(int label, node* left, node* right) : label(label), left(left), right(right){} int label; node *left, *right; }; string s; unordered_map<int, node*> access; void prepare() { cin >> s; } node* build_list(string s) { access.clear(); node* current = nullptr; node* c; for(int i=0;i<s.size();i++){ int l = s[i]-'0'; node* n = new node(l, nullptr, nullptr); access[l] = n; if(!current){ current = n; n->left = n; n->right = n; c = n; continue; } c->right = n; n->left = c; n->right = current; current->left = n; c = n; } return current; } void step(node* n) { node *p1, *p2, *p3; p1 = n->right; p2 = p1->right; p3 = p2->right; int nl = n->label; nl = nl == 1 ? access.size() : nl-1; while(nl == p1->label || nl == p2->label || nl == p3->label){ nl = nl == 1 ? access.size() : nl-1; } n->right = p3->right; p3->right->left = n; node* dest = access[nl]; node* dest_right = dest->right; dest->right = p1; p1->left = dest; dest_right->left = p3; p3->right = dest_right; } int first() { node* current = build_list(s); for(int i=0;i<100;i++){ step(current); current = current->right; } while(current->label != 1) current = current->right; int res = 0; current = current->right; do{ res = (res*10)+current->label; current = current->right; }while(current->label != 1); return res; } ll second() { node* current = build_list(s); node* c = current; for(int i=0;i<8;i++){ c = c->right; } for(int i=10;i<=1000000;i++){ node* n = new node(i,nullptr, nullptr); access[i] = n; c->right = n; n->left = c; n->right = current; current->left = n; c = n; } for(int i=0;i<10000000;i++){ step(current); current = current->right; } while(current->label != 1) current = current->right; return (ll)current->right->label * (ll)current->right->right->label; } int main() { prepare(); cout << "First: " << first() << endl; cout << "Second: " << second() << endl; return 0; }
Markdown
UTF-8
5,140
3.328125
3
[]
no_license
## 16种MBTI人格相处模拟程序 ### 功能: 本项目可以用来模拟两名用户指定的不同MBTI人格的人,在一定时间的交往之后,对相互之间产生的影响以及两人的关系。 --- ### 使用方法: 1. 编译src文件夹下的项目文件,再运行Interaction.java 2. 按照程序提示输入两名用户(Adam & Eve)的人格类型 3. 输入两人将要相处的时间 4. 查看结果 --- ### 运行逻辑: 项目逻辑的核心是随机数。以下将举例说明随机数是如何运作的: 假设我们的测试对象其中有一名是intj人格的【杨过】,杨过的intj人格中有这样一种性格倾向叫作【独立且蔑视权威】。本程序将这种倾向作了数值化处理如下: - 每天对自己 1. 生理满足:区间为[0,3]的随机减值,模拟杨过因不服从权威而导致的无法从社会主流环境提供的资源中摄取生理满足能力的降低; 2. 安全感:区间为[0,5]的随机减值,模拟杨过因背离权威而导致的极度不安全感; 3. 自尊:区间为[0,4]的随机减值,模拟杨过遭受社会主流舆论谴责的感受; 4. 自我实现:区间为[0,2]的随机减值,模拟杨过在社会中实现自我价值能力的削弱; 5. 超自我实现:区间为[0,2]的随机加值,模拟杨过因现实中的挫败,转而追求超然事物、自我内在价值等超自我价值的追求; - 每天对他人 1. 安全感:区间为[0,1]的随机减值,模拟他人与杨过这个社会异类共同生活所感受到的潜在不安全感; 2. 自尊:区间为[0,1]的随机减值,模拟他人在于杨过的相处过程中,因杨过的鹤立独行而感受不到来自他的尊重; 所以,由于intj人格的杨过的这一种性格倾向,导致每一天都对自己与他人产生两个方向的数值变化,其代码为: ```java public static void IntjSelf(){ int randomChanges1 = ThreadLocalRandom.current().nextInt(-3,1); int randomChanges2 = ThreadLocalRandom.current().nextInt(-5,1); int randomChanges3 = ThreadLocalRandom.current().nextInt(-4,1); int randomChanges4 = ThreadLocalRandom.current().nextInt(-2,1); int randomChanges5 = ThreadLocalRandom.current().nextInt(0,1+1); setPhysical(randomChanges1); setSecurity(randomChanges2); SetEsteem(randomChanges3); setSelfFulfillment(randomChanges4); setIntrisicValue(randomChanges5); } public static void IntjOpposite(){ int randomChanges1 = ThreadLocalRandom.current().nextInt(-1,1); setSecurity(randomChanges1); setEsteem(randomChanges1); } ``` 用户指定两人交互每n天,上述两个方法就执行n次(当然这只是其中一人的一个性格倾向,实际上两个人的多种性格都会相互影响)。然后将带来的数值变化传递给代表两人的类中,其中包含代表两人的各项指标。最后通过条件判断这些数值来模拟两人各项指标以及关系的变化。 --- ### 结果判断: 本程序的运行结果如下例所示,它显示了两名分别为entj/esfj人格类型的人在365天的互动之后,可能产生的结果: > Please tell us the personal types of Adam: entj > Please tell us the personal types of Eve: esfj > Please tell us how many days do you want these two people have interactions with each other? 365 >Adam: >Physical needs 'tremendously' enhanced (Eve brings tremendous changes to Adam's physical needs, now Adam can always feel his animal desire and have unstoppable impulsive to fulfill them.) >Sense of safety 'remarkably' enhanced (Eve's tenderness makes Adam reminding of his mother.) Social satisfaction 'tremendously' weakened (Adam feels meeting Eve is like walking in a silent cave: Maybe soliloquize at first, then completely mute at last because of the lack of response.) >Sense of esteem 'tremendously' weakened (Adam now has a desperate attitude towards life due to Eve's daily humiliation.) >Self-fulfillment 'slightly' enhanced (The tips from Eve is helpful on Adam's career.) >Intrinsic value 'slightly' weakened (Adam pay less attention to his soul than social identity, so does Eve.) >Affection 'tremendously' weakened (Adam is disgusting in others' eyes. They even give him a nickname called 'roach'.) >Bond between two people 'slightly' enhanced (The connection between these two grows steadily.) 从上述结果中可以看出,本程序模拟了一个自然人的如下方面: 1. 生理需求 2. 安全感 3. 社交满足感 4. 自尊 5. 自我实现 6. 超我实现 7. 对另一方的好感 8. 与另一方的感情 在对上述8个方面的数值进行条件判断以后,会有返回如下结果: 1. 增强 1. 显著地 2. 明显地 3. 稍许地 2. 减弱 1. 显著地 2. 明显地 3. 稍许地 通过上述条件判断来告诉用户,双方之间究竟带给了对方什么样的影响。由于本程序的运作是根据随机数来完成的,所以每一次同样人格类型经过同样的时间得出来的结果可能有所不同,这也与现实情况相符。
Markdown
UTF-8
2,847
3.015625
3
[]
no_license
## Box Api v2.0 SDK under development. So far this SDK has only machine to machine authentication mechanism and the following functionality #### Folders 1. Get folder info 2. Get folder items 3. Create folder 4. Delete folder 5. Get trashed items 6. Destroy trashed folder 7. Restore the trashed folder #### Files 1. Upload file 2. Upload Pre flight - This API is used to check if the metadata supplied is valid or not. 3. Get embed URL 4. Delete a file (soft delete - Moves to trash) 5. Destroy trashed file 6. Restore the trashed file ### Usage ```php use Linkstreet\Box\Box; use Linkstreet\Box\Enums\SubscriptionType; $box_sdk = new Box(['client_id' => "", "client_secret" => ""]); $app_auth_info = [ "key_id" => "key id from box app", "private_key" => "path to private key", "pass_phrase" => "passphrase", // Can be empty "subscription_type" => SubscriptionType::ENTERPRISE or SubscriptionType::USER, "id" => "enterprise id or user id" ]; // Authenticates with box server and returns app_auth instance. // Throws `GuzzleHttp\Exception\ClientException` on failure $app_auth_instance = $box_sdk->getAppAuthClient($app_auth_info); ``` #### Folder Service 1. To get the service ```php $folder_service = $app_auth_instance->getFolderService(); ``` 2. Methods available in `$folder_service` ``` 1. getFolderInfo($folder_id); // Defaults to root folder (id = 0) 2. getFolderItems($folder_id = 0, $fields = [], $limit = 100, $offset = 0); // Defaults to root folder (id = 0) 3. create($folder_name, $parent_folder_id = 0) 4. delete($folder_id, $recursive = false, $e_tag = null) 5. getTrashedItems() 6. destroyTrashedFolder($folder_id) 7. restore($trashed_folder_id, $new_name = null, $parent_folder_id = null) ``` #### File Service 1. To get the service ```php $file_service = $app_auth_instance->getFileService(); ``` 2. Methods available in `$file_service` ``` 1. uploadPreFlight($file_path = "", $folder_id = 0, $filename = null); // If filename is null, file name will be derived from actual file name. 2. upload($file_path = "", $folder_id = 0, $filename = null); // If filename is null, file name will be derived from actual file name. 3. getEmbedUrl($file_id) 4. delete($file_id) 5. destroyTrashedFile($file_id) 6. restore($trashed_file_id, $new_name = null, $parent_folder_id = null) ``` ##### NOTE: 1. All APIs return `\GuzzleHttp\Psr7\Response` (to get the body use `$response->getBody()->getContents()`. Refer [Guzzle HTTP Messages](http://docs.guzzlephp.org/en/latest/psr7.html#responses)) except `getEmbedUrl($file_id)` which returns string. 2. Guzzle related exceptions and its documentation can be found in [Guzzle Docs](http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions)
Python
UTF-8
7,141
3.109375
3
[]
no_license
################################################################################ ### Date: 2019.10.28 ### Author: Martin C Lim ### Version: 0.1 ### Description: Show drawing of Lissajous Plots ### ### Links: ### ################################################################################ ### User Inputs ################################################################################ Radius = 50 # lissajous Radius dotRad = 5 # Axis Dot Radius Gap = 10 # Gap Between plots LJx = [1,1.5,2,2.5,3,3.5] # Freq for each X/Col LJy = [1,2,4] # Freq for each Y/Row TimeFactor = 0.5 # Slow down factor ################################################################################ ### Code Begin ################################################################################ numCol = len(LJx) numRow = len(LJy) ScrWid = (numCol + 1) * (Radius+Gap) * 2 ScrHeight = (numRow + 1) * (Radius+Gap) * 2 import pygame import random import math import time from colors import * ################################################################################ ### Define colors ################################################################################ Colors = [RED,ORANGE,YELLOW,GREEN,BLUE,PURPLE] from pygame.locals import DOUBLEBUF, FULLSCREEN # flags = FULLSCREEN | DOUBLEBUF flags = DOUBLEBUF #screen = pygame.display.set_mode(resolution, flags, bpp) ################################################################################ ### Definitions ################################################################################ class lissajous: ###Class to keep track of a each lissajous plot def __init__(self,col,row): self.color = random.choice(Colors) self.centerX = (col + 1) * (Radius + Gap) * 2 + Radius self.centerY = (row + 1) * (Radius + Gap) * 2 + Radius # self.ljlines = [(self.centerX,self.centerY)] self.ljlines = [] def addsegment(self,x,y): self.ljlines.append((x,y)) if len(self.ljlines) == 1: self.ljlines.append((x,y)) if len(self.ljlines) > 1500: self.ljlines = self.ljlines[-1490:-1] # self.ljlines = [(x,y),(x,y)] def draw(self, screen): pygame.draw.lines(screen, self.color, False, self.ljlines, 2) tuppy = self.ljlines[-1] pygame.draw.circle(screen, GREEN,(int(tuppy[0]),int(tuppy[1])),dotRad,1) class circleX: def __init__(self,col): self.ljlines = [] self.color = WHITE #Lissajous self.a = 1 #Frequency multiplier self.centerX = (col + 1) * (Radius + Gap) * 2 + Radius self.centerY = Radius self.endX = 0 self.endY = 0 def newRadius(self,t): # t = pygame.time.get_ticks()/1000 self.endX = Radius * math.sin(self.a*t)+ self.centerX self.endY = Radius * math.cos(self.a*t)+ self.centerY def draw(self, screen): #(surface, color, closed, points, blend) pygame.draw.circle(screen, WHITE,(self.centerX,self.centerY),Radius,1) pygame.draw.circle(screen, BLUE, (int(self.endX),int(self.endY)),dotRad,1) pygame.draw.aalines(screen, GREY, False, [(self.centerX,self.centerY),(self.endX,self.endY),(self.endX,ScrHeight-2*Gap)], 1) class circleY: def __init__(self,row): self.ljlines = [] self.color = WHITE self.b = 1 self.centerX = Radius self.centerY = (row + 1) * (Radius + Gap) * 2 + Radius self.endX = 0 self.endY = 0 def newRadius(self,t): # t = pygame.time.get_ticks()/1000 self.endX = Radius * math.sin(self.b*t)+ self.centerX self.endY = Radius * math.cos(self.b*t)+ self.centerY # self.ljlines.append((x,y) def draw(self, screen): #(surface, color, closed, points, blend) pygame.draw.circle(screen, WHITE,(self.centerX,self.centerY),Radius,1) pygame.draw.circle(screen, BLUE, (int(self.endX),int(self.endY)),dotRad,1) pygame.draw.aalines(screen, GREY, False, [(self.centerX,self.centerY),(self.endX,self.endY),(ScrWid-2*Gap,self.endY)], 2) ################################################################################ ### Main Code ################################################################################ def main(): pygame.init() pygame.mouse.set_visible(False) size = [ScrWid, ScrHeight] screen = pygame.display.set_mode(size,flags) screen.set_alpha(None) pygame.display.set_caption("Lissajous Plot") done = False selected_lissajous = None clock = pygame.time.Clock() # Manage screen updates ############################################################################# ### Font ############################################################################# pygame.font.init() # you have to call this at the start, myfont = pygame.font.SysFont('Courier', 20, bold=True) ########################################################################### ### Main Code ########################################################################### CircX = [] for i,freq in enumerate(LJx): CircX.append(circleX(i)) CircX[-1].a = freq CircY = [] for i,freq in enumerate(LJy): CircY.append(circleY(i)) CircY[-1].b = freq LJPlots = [[lissajous(1,1)] * numRow for i in range(numCol)] for i,col in enumerate(CircX): for j,row in enumerate(CircY): temp = lissajous(i,j) LJPlots[i][j] = temp while not done: ####################################################################### ### Event Processing ####################################################################### pygame.mouse.set_visible(True) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True ####################################################################### ### Drawing Code ####################################################################### screen.fill(BLACK) # Set the screen background t = pygame.time.get_ticks()/1000 * TimeFactor for circXObj in CircX: circXObj.newRadius(t) circXObj.draw(screen) for circYObj in CircY: circYObj.newRadius(t) circYObj.draw(screen) for i in range(numCol): for j in range(numRow): LJPlots[i][j].addsegment(CircX[i].endX,CircY[j].endY) LJPlots[i][j].draw(screen) outText = f"FPS:{clock.get_fps():.2f}" textsurface = myfont.render(outText, True, WHITE) #render clock.tick(60) # Limit to 60 frames per second screen.blit(textsurface,(0,0)) # Draw text pygame.display.update() # update the screen with what we've drawn. #End While pygame.quit() if __name__ == "__main__": main()
Python
UTF-8
111
3.671875
4
[]
no_license
def square_it_func(a): return a * a x = map(square_it_func, [1, 4, 7]) print(x) # prints '[1, 16, 49]'
Python
UTF-8
965
3.390625
3
[]
no_license
# Practice Python, Exercise 17 - from 20140606 done (from solution but differently) in 20190729 # - ref: https://www.practicepython.org/exercise/2014/06/06/17-decode-a-web-page.html # Exercise: Use BeautifulSoup and requests Python packages to print out a # list of all article titles on the New York Times homepage. import requests from bs4 import BeautifulSoup base_url = 'http://www.nytimes.com' r = requests.get(base_url) soup = BeautifulSoup(r.text) for story_heading in soup.find_all("h2"): # for story_heading in soup.find_all("h2", "</h2>"): ## MarcMir70 - The code below has errors (today for the 4th line) ## if story_heading.a: ## print('1. '+story_heading.a.text.replace("\n", " ").strip()) ## else: ## print('2. '+story_heading.contents[0]) ### MarcMir70 - The code below shows the entire HTML clauses for each article text! if story_heading.a: print(story_heading.a) else: print(story_heading)
C
UTF-8
8,099
3.4375
3
[]
no_license
// // DoublyLinkedList.c // DoublyLinkedList // // Created by JianZhang on 2017/3/7. // Copyright © 2017年 NUT. All rights reserved. // #include <stdlib.h> #include <assert.h> #include "DoublyLinkedList.h" struct Node { int Element; Position Prior; Position Next; }; DoublyLinkedList DoublyLinkedListCreate(const int Source[], unsigned int count) { DoublyLinkedList List; Position P, TempCell; unsigned int index; List = calloc(1, sizeof(struct Node)); assert(List != NULL); P = List; for (index = 0; index < count; index++) { TempCell = calloc(1, sizeof(struct Node)); assert(TempCell != NULL); TempCell->Element = Source[index]; P->Next = TempCell; TempCell->Prior = P; P = TempCell; } return List; } int DoublyLinkedListIsLegal(DoublyLinkedList L) { Position P, TempCell; P = L; TempCell = L->Next; while (TempCell != NULL && TempCell->Prior == P) { P = TempCell; TempCell = TempCell->Next; } return TempCell == NULL; } int DoublyLinkedListIsEmpty(DoublyLinkedList L) { return L->Next == NULL; } int DoublyLinkedListIsFirstNode(DoublyLinkedList L, Position P) { assert(P != NULL); return P == L->Next; } int DoublyLinkedListIsLastNode(DoublyLinkedList L, Position P) { assert(P != NULL); return P->Next == NULL; } int DoublyLinkedListLength(DoublyLinkedList L) { unsigned int length; Position P; length = 0; P = L->Next; while (P != NULL) { length++; P = P->Next; } return length; } int DoublyLinkedListIsBadLoop(DoublyLinkedList L) { Position Slow, Fast; Slow = L; Fast = L; while (Fast->Next != NULL && Fast->Next->Next != NULL) { Slow = Slow->Next; Fast = Fast->Next->Next; if (Slow == Fast) return 1; } while (Fast->Next != NULL) Fast = Fast->Next; Slow = Fast; while (Fast->Prior != NULL && Fast->Prior->Prior != NULL) { Slow = Slow->Prior; Fast = Fast->Prior->Prior; if (Slow == Fast) return -1; } return 0; } int DoublyLinkedListBadLoopLength(DoublyLinkedList L, int *Flag) { int length; Position Slow, Fast; Slow = L; Fast = L; *Flag = 0; while (Fast->Next != NULL && Fast->Next->Next != NULL) { Slow = Slow->Next; Fast = Fast->Next->Next; if (Slow == Fast) { *Flag = 1; break; } } if (*Flag > 0) { length = 1; Fast = Fast->Next; while (Slow != Fast) { length++; Fast = Fast->Next; } return length; } while (Fast->Next != NULL) Fast = Fast->Next; Slow = Fast; while (Fast->Prior != NULL && Fast->Prior->Prior != NULL) { Slow = Slow->Prior; Fast = Fast->Prior->Prior; if (Slow == Fast) { *Flag = -1; break; } } if (*Flag < 0) { length = 1; Fast = Fast->Prior; while (Slow != Fast) { length++; Fast = Fast->Prior; } return length; } return 0; } int DoublyLinkedListRetrieve(Position P) { return P->Element; } Position DoublyLinkedListFirstNode(DoublyLinkedList L) { return L->Next; } Position DoublyLinkedListLastNode(DoublyLinkedList L) { Position P; P = L; while (P->Next) P = P->Next; return P; } Position DoublyLinkedListMiddleNode(DoublyLinkedList L) { Position Slow, Fast; Slow = L; Fast = L; while (Fast->Next != NULL && Fast->Next->Next != NULL) { Slow = Slow->Next; Fast = Fast->Next->Next; } return Fast->Next == NULL ? Slow : Slow ->Next; } Position DoublyLinkedListFindNode(DoublyLinkedList L, int Element) { Position P; P = L->Next; while (P != NULL && P->Element != Element) P = P->Next; return P; } Position DoublyLinkedListFindPreviousNode(DoublyLinkedList L, int Element) { Position P; P = L; while (P->Next != NULL && P->Next->Element != Element) P = P->Next; return P->Next == NULL ? NULL : P; } Position DoublyLinkedListFindPriorNode(DoublyLinkedList L, Position P) { Position TempCell; assert(P != NULL); TempCell = L; while (TempCell->Next != NULL && TempCell->Next != P) TempCell = TempCell->Next; return TempCell; } Position DoublyLinkedListFindNodeFromTail(DoublyLinkedList L, unsigned int Distance) { unsigned int index; Position P, TempCell; index = 0; TempCell = L; while (TempCell->Next != NULL && index < Distance) { TempCell = TempCell->Next; index++; } if (index < Distance) return NULL; P = L; while (TempCell->Next != NULL) { P = P->Next; TempCell = TempCell->Next; } return P; } Position DoublyLinkedListFindBadLoopEntrance(DoublyLinkedList L, int *Flag) { Position Slow, Fast, Tail; Slow = L; Fast = L; *Flag = 0; while (Fast->Next != NULL && Fast->Next->Next != NULL) { Slow = Slow->Next; Fast = Fast->Next->Next; if (Slow == Fast) { *Flag = 1; break; } } if (*Flag == 1) { Slow = L; while (Slow != Fast) { Slow = Slow->Next; Fast = Fast->Next; } return Slow; } while (Fast->Next != NULL) Fast = Fast->Next; Tail = Fast; Slow = Fast; while (Fast->Prior != NULL && Fast->Prior->Prior) { Slow = Slow->Prior; Fast = Fast->Prior->Prior; if (Slow == Fast) { *Flag = -1; break; } } if (*Flag == -1) { Slow = Tail; while (Slow != Fast) { Slow = Slow->Prior; Fast = Fast->Prior; } return Slow; } return NULL; } Position DoublyLinkedListAdvance(Position P) { return P->Next; } void DoublyLinkedListAppendList(DoublyLinkedList L, DoublyLinkedList A) { Position LTail; if (DoublyLinkedListIsEmpty(A)) return; LTail = DoublyLinkedListLastNode(L); LTail->Next = A->Next; A->Next->Prior = LTail; } void DoublyLinkedListInsertElement(DoublyLinkedList L, Position P, int Element) { Position TempCell; TempCell = calloc(1, sizeof(struct Node)); assert(TempCell != NULL); TempCell->Element = Element; TempCell->Prior = P; TempCell->Next = P->Next; P->Next = TempCell; if (TempCell->Next != NULL) TempCell->Next->Prior = TempCell; } void DoublyLinkedListDeleteElement(DoublyLinkedList L, int Element) { Position P, TempCell; P = DoublyLinkedListFindPreviousNode(L, Element); if (P == NULL) return; TempCell = P->Next; P->Next = TempCell->Next; if (TempCell->Next != NULL) TempCell->Next->Prior = P; free(TempCell); } void DoublyLinkedListDeleteNode(DoublyLinkedList L, Position P) { assert(L != P); P->Prior->Next = P->Next; if (P->Next != NULL) P->Next->Prior = P->Prior; free(P); } void DoublyLinkedListDeleteList(DoublyLinkedList L) { Position P, TempCell; P = L->Next; L->Next = NULL; while (P != NULL) { TempCell = P->Next; free(P); P = TempCell; } } void DoublyLinkedListReverse(DoublyLinkedList L) { Position P, R, TempCell; P = L->Next; TempCell = NULL; while (P != NULL) { R = P->Next; P->Next = TempCell; if (TempCell != NULL) TempCell->Prior = P; TempCell = P; P = R; } L->Next = TempCell; TempCell->Prior = L; } void DoublyLinkedListPrint(DoublyLinkedList L) { Position P; P = L->Next; while (P != NULL) { printf("%d, ", P->Element); P = P->Next; } }
Rust
UTF-8
1,971
3.125
3
[ "MIT" ]
permissive
use derive_new::new; /// TODO: Documentation #[derive(Clone, Debug)] pub enum WindowMode { /// Free floating window Borderless, /// Complete fullscreen window Fullscreen, /// Fake fullscreen (Plays better with alt tabbing/Multiple monitors) window Windowed, } impl Default for WindowMode { fn default() -> WindowMode { WindowMode::Windowed } } /// TODO: Documentation #[derive(Clone, Debug)] pub struct Resolution { /// TODO: Documentation pub width: f64, /// TODO: Documentation pub height: f64, } impl Default for Resolution { fn default() -> Resolution { Resolution { width: 1024f64, height: 768f64, } } } /// TODO: Documentation #[derive(Clone, Debug, new)] pub struct Config { /// If the window resizable #[new(default)] pub resizable: bool, /// Window resolution (Width x Height) #[new(default)] pub resolution: Resolution, /// Window title #[new(default)] pub title: String, /// Whether to enable v-sync or not #[new(default)] pub vsync: bool, /// Window mode #[new(default)] pub window_mode: WindowMode, } impl Default for Config { fn default() -> Config { Config { resizable: false, resolution: Resolution::default(), title: "Atlas".to_owned(), vsync: true, window_mode: WindowMode::Windowed, } } } impl Config { /// Set whether the window is resizable pub fn resizable(mut self, resizable: bool) -> Self { self.resizable = resizable; self } /// Set the window resolution (width/height) pub fn resolution(mut self, width: f64, height: f64) -> Self { self.resolution = Resolution { width, height, }; self } /// Set the window title pub fn title(mut self, title: String) -> Self { self.title = title; self } /// Set whether to use V-sync or not pub fn vsync(mut self, vsync: bool) -> Self { self.vsync = vsync; self } /// Set the window mode pub fn window_mode(mut self, window_mode: WindowMode) -> Self { self.window_mode = window_mode; self } }
Python
UTF-8
1,193
3
3
[ "MIT" ]
permissive
"""Class wrapper for Keras Reshape layers usable as meta-layers.""" from typing import Dict, List, Union, Tuple from tensorflow.keras.layers import Reshape, Layer from .meta_layer import MetaLayer class ReshapeMetaLayer(MetaLayer): """Class implementing Concatenation Meta Layer. The pourpose of a concatenation meta layer is to Reshape the output of the multiple meta-layers (tipically from different meta-models). """ def __init__(self, target_shape: Union[int, Tuple[int]], **kwargs): """Create new ReshapeMetaLayer object. Parameters ------------------------ target_shape: Union[int, Tuple[int]] = None, Shape to modify input into. **kwargs: Dict, Dictionary of keyword arguments to pass to parent class. """ super().__init__(**kwargs) self._target_shape = target_shape def _space(self) -> Dict: """Return space of hyper-parameters of the layer.""" return {} def _build(self, input_layers: List[Layer], **kwargs) -> Layer: """Build input layer.""" return Reshape( target_shape=self._target_shape )(input_layers)
Ruby
UTF-8
652
2.828125
3
[]
no_license
class List < ApplicationRecord has_many :tasks def complete_all_tasks! # tasks.each do |task| # task.update(complete: true) # end tasks.update_all(complete:true) end def snooze_all_tasks! # tasks.each do |task| # task.snooze_hour! # end tasks.each{|task| task.snooze_hour!} end def total_duration # total = 0 # tasks.each do |task| # total += task.duration # end # return total tasks.inject(0) { |sum,task| sum + task.duration } end def incomplete_tasks tasks.reject {|task| task.complete} end def favorite_tasks tasks.select {|task| task.favorite} end end
C#
UTF-8
1,709
2.671875
3
[]
no_license
//***************************************************************************** // Programmer: Ye Liu // Date: 22 October 2021 // Software: Microsoft Visual Studio 2019 Community Edition // Platform: Microsoft Windows 10 Professional 64­bit // Purpose: Drag and drop image to the picturebox // Adapted from https://1bestcsharp.blogspot.com/2015/03/c-how-to-drag-and-drop-image-from.html //**************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Assessment_2 { public partial class frmDragdrop : Form { public frmDragdrop() { InitializeComponent(); pictureBox1.AllowDrop = true; } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private void frmDragdrop_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; } private void frmDragdrop_DragDrop(object sender, DragEventArgs e) { foreach (string pic in ((string[])e.Data.GetData(DataFormats.FileDrop))) { Image img = Image.FromFile(pic); pictureBox1.Image = img; // var dragImage = new Bitmap((Bitmap)pictureBox1.Image, pictureBox1.Size); } } } }
Markdown
UTF-8
2,758
2.546875
3
[ "BSD-3-Clause" ]
permissive
CheddarGetter Yii Demo =========== A demo of the CheddarGetter API and PHP library as a simple service using the [Yii framework](http://www.yiiframework.com/) and [Vagrant](http://www.vagrantup.com/) with [VirtualBox](https://www.virtualbox.org/) ## Setup ### Get Vagrant and VirtualBox If you don't already use them, download [Vagrant](http://www.vagrantup.com/downloads.html) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads) for your OS. ### Get the Code Clone the repo and `vagrant up`. Better yet, fork and clone if you're planning to contribute or if there's even the most remote possibility that you will contribute improvements to the project. **Pull requests welcome!** In a terminal: ```bash $ cd cheddargetter-yii-demo $ vagrant up ``` That'll take a few minutes. Once complete, you'll have a virtualized dev environment running. For the curious, here's a general overview of what vagrant is doing (FYI): * Creates a virtual machine via VirtualBox: an Ubuntu 14.04 basic install. * Creates a forwarded port from your host machine to the guest vm (8023 to 80). So, once provisioned, you can go to http://localhost:8023 to see the demo. * Automatically install (via [Puppet](http://puppetlabs.com/)) all of the software required to run the demo: * PHP * Composer * Yii Framework * CheddarGetter Client Library * Apache * MySQL ### Signup for a Free CheddarGetter Account If you haven't done so already, [signup for CheddarGetter](https://cheddargetter.com/signup). Create your product account and complete the quick-start wizard. It only takes a few minutes. If you have questions about how it works, [CheddarGetter support](http://support.cheddargetter.com/disucussion/new) is usually quick to respond. Now have a coffee and relax. Then, edit the main config file located in protected/config to pass your CheddarGetter API information to the CG component. You should have an array that looks something like: ```php 'cheddar'=>array( 'class'=>'CheddarGetterClient', 'cgurl'=>'www.cheddargetter.com', 'cgemail'=>'you@youremail.com', 'cgpass'=>'hunter2', 'cgapp'=>'APP_NAME', ), ``` so we can make API calls to the proper account. You should also edit the db credentials to properly point to your preferred database. Finally, run the SQL in protected/modules/user/data/schema.*.sql through your favorite SQL program so we can properly create and track users. ## Contributing 1. [Fork it](https://help.github.com/articles/fork-a-repo) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new [Pull Request](https://help.github.com/articles/using-pull-requests)
Java
UTF-8
744
2.03125
2
[]
no_license
import com.rsbuddy.script.util.Filter; import com.rsbuddy.script.wrappers.GameObject; interface Filters { Filter<GameObject> RUNITE = new Filter<GameObject>() { public boolean accept(GameObject gameObject) { return gameObject.getId() == 45069 || gameObject.getId() == 45070; } }; Filter<GameObject> ADAMANTITE = new Filter<GameObject>() { public boolean accept(GameObject gameObject) { return gameObject.getId() == 29233 || gameObject.getId() == 29235; } }; Filter<GameObject> GOLD = new Filter<GameObject>() { public boolean accept(GameObject gameObject) { return gameObject.getId() == 45067 || gameObject.getId() == 45068; } }; }
Swift
UTF-8
3,178
2.625
3
[]
no_license
// // Made with ❤ and ☕ // import UIKit class LibraryAlbumsVC: UIViewController { var albums = [Album]() private let noAlbumsView = NoUserAlbumsView() private let albumLibraryTableView: UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.register(SearchResultsMultilineTableViewCell.self, forCellReuseIdentifier: SearchResultsMultilineTableViewCell.identifier) tableView.isHidden = true return tableView }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground view.addSubview(albumLibraryTableView) albumLibraryTableView.delegate = self albumLibraryTableView.dataSource = self fetchData() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() albumLibraryTableView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height) } @objc func didTapClose() { dismiss(animated: true, completion: nil) } private func fetchData() { albums.removeAll() APIManager.shared.getUserAlbums { [weak self] result in DispatchQueue.main.async { switch result { case .success(let albums): self?.albums = albums self?.updateUI() case .failure(let error): print(error.localizedDescription) } } } } private func updateUI() { if albums.isEmpty { noAlbumsView.isHidden = false albumLibraryTableView.isHidden = true } else { albumLibraryTableView.reloadData() noAlbumsView.isHidden = true albumLibraryTableView.isHidden = false } } } extension LibraryAlbumsVC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let libraryAlbumsCell = tableView.dequeueReusableCell(withIdentifier: SearchResultsMultilineTableViewCell.identifier, for: indexPath) as? SearchResultsMultilineTableViewCell else { return UITableViewCell() } let album = albums[indexPath.row] libraryAlbumsCell.configure( with: SearchResultsMultilineViewModel(title: album.name, subTitle: album.artists.first?.name ?? "-", imageURL: URL(string: album.images.first?.url ?? ""))) return libraryAlbumsCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let album = albums[indexPath.row] let vc = AlbumVC(album: album) vc.navigationItem.largeTitleDisplayMode = .never navigationController?.pushViewController(vc, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } }
Java
UTF-8
1,048
2.078125
2
[]
no_license
package com.lauvan.init; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import com.jfinal.plugin.activerecord.Record; import com.lauvan.apps.communication.ccms.model.T_Ccms_Setting; import com.lauvan.apps.communication.ccms.util.CcmsUtil; import com.lauvan.base.basemodel.model.T_Sys_Module; public class initModuleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void init(ServletConfig config) throws ServletException { super.init(config); List<Record> moduleList = T_Sys_Module.dao.getListByUsable(true); for(Record module : moduleList) { config.getServletContext().setAttribute(module.getStr("mark"), module.get("id")); } T_Ccms_Setting setting = T_Ccms_Setting.dao.findFirst("SELECT * FROM T_CCMS_SETTING"); getServletContext().setAttribute("CCMSET", setting); CcmsUtil.init(setting); System.out.println("权限初始化加载完成!"); } }
C#
UTF-8
2,484
2.828125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace System { public static class TypeShim { public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsSubclassOf(this Type type, Type parent) { return type.GetTypeInfo().IsSubclassOf(parent); } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool ImplementsInterface(this Type type, Type interfaceType) { if (interfaceType.IsGenericType()) { interfaceType = interfaceType.GetGenericTypeDefinition(); } return type.GetTypeInfo().ImplementedInterfaces.Any(i => { Type checkType = i; if (i.IsGenericType()) { checkType = i.GetGenericTypeDefinition(); } return interfaceType == checkType; }); } public static IEnumerable<Attribute> GetCustomAttributes(this Type type, Type attrType, bool inherit) { return type.GetTypeInfo().GetCustomAttributes(attrType, inherit).Cast<Attribute>(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { return type.GetTypeInfo().GetFields(flags); } public static Type GetInterface(this Type type, String name) { return type.GetTypeInfo().GetInterface(name); } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GetGenericArguments(); } public static PropertyInfo[] GetProperties(this Type type, BindingFlags flags) { return type.GetTypeInfo().GetProperties(flags); } } }
Go
UTF-8
428
2.515625
3
[ "BSD-2-Clause" ]
permissive
package vals import ( "testing" "github.com/elves/elvish/tt" ) type dissocer struct{} func (dissocer) Dissoc(interface{}) interface{} { return "custom ret" } var dissocTests = tt.Table{ Args(MakeMap("k1", "v1", "k2", "v2"), "k1").Rets( eq(MakeMap("k2", "v2"))), Args(dissocer{}, "x").Rets("custom ret"), Args("", "x").Rets(nil), } func TestDissoc(t *testing.T) { tt.Test(t, tt.Fn("Dissoc", Dissoc), dissocTests) }
Java
UTF-8
21,163
1.742188
2
[]
no_license
/************************************************************************** * $RCSfile: QuickQueryPanel.java,v $ $Revision: 1.13.2.15 $ $Date: 2009/12/02 05:36:02 $ **************************************************************************/ package smartx.publics.styletemplet.ui; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import smartx.framework.common.ui.*; import smartx.framework.common.utils.StringUtil; import smartx.framework.common.utils.Sys; import smartx.framework.common.vo.FrameWorkTBUtil; import smartx.framework.common.vo.ModifySqlUtil; import smartx.framework.metadata.ui.*; import smartx.framework.metadata.ui.componentscard.*; import smartx.framework.metadata.vo.*; import smartx.framework.metadata.vo.jepfunctions.JepFormulaParse; import smartx.framework.metadata.vo.jepfunctions.JepFormulaUtil; /** * * 模板快速查询组件 * * @author Sun xuefeng */ public class QuickQueryPanel extends JPanel { private static final long serialVersionUID = 4130562298534355459L; protected Pub_Templet_1VO templetVO = null; protected JPanel showpanel=null; protected JPanel querybtnpanel=null; private Vector v_compents = new Vector(); private Vector v_showcompents = null; private HashMap maplist = new HashMap(); private HashMap map = new HashMap(); private StringBuffer sbcard = null; private boolean isFirst2 = true; private boolean bo_iscardquery = true; protected BillListPanel billlist = null; private String condition = null; //元原模板的条件 private String ordersetting = null; //元原模板的排序 QueryKeyListener querylistener = new QueryKeyListener(); String realqueySQL = null; public QuickQueryPanel(String code) { this(code, null); } public QuickQueryPanel(String code, String condition) { try { templetVO = UIUtil.getPub_Templet_1VO(code); } catch (Exception e) { e.printStackTrace(); } this.condition = condition; init(); } public QuickQueryPanel(BillListPanel _panel) { this(_panel, null); } public QuickQueryPanel(BillListPanel _panel, String condition) { this.billlist = _panel; this.templetVO = billlist.getTempletVO(); this.condition = condition; init(); } public QuickQueryPanel(Pub_Templet_1VO templetVO) { this.templetVO = templetVO; init(); } public void init() { //获得元原模板的排序 this.ordersetting= templetVO.getOrdersetting(); if (NovaClientEnvironment.getInstance().isAdmin()) { this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { showPopupMenu(e); } } }); } showpanel = new JPanel(); showpanel.setName("quickquerypanel"); this.setBorder(BorderFactory.createMatteBorder(0,0,1,0,Color.LIGHT_GRAY )); FlowLayout flayout = new FlowLayout(FlowLayout.LEFT); flayout.setHgap(0); flayout.setVgap(2); showpanel.setLayout(flayout); if (getTempletViewItemVOs() != null) { Pub_Templet_1_ItemVO[] vos=getTempletViewItemVOs(); for (int i = 0; i < vos.length; i++) { //首先查看有没有设置条件类型,如果没有设置,则取默认字段类型。后面的参照和下拉都要有相应的处理 String str_type = vos[i].getConditionItemType(); str_type = (str_type==null)?vos[i].getItemtype():str_type; //如果设置为直接查询【值为1】,才允许展现 if ("1".equals(vos[i].getDelfaultquerylevel())) { if (str_type.equals("文本框")) { TextFieldPanel panel = new TextFieldPanel(vos[i]); showpanel.add(panel); panel.getTextField().addKeyListener(querylistener);//增回车触发查询监听 panel.setValue(execFormula(vos[i].getDefaultCondition())); v_compents.add(panel); } else if (str_type.equals("数字框")) { QueryNumericPanel panel=new QueryNumericPanel(vos[i],QueryNumericPanel.TYPE_FLOAT); panel.setValue(execFormula(vos[i].getDefaultCondition())); showpanel.add(panel); v_compents.add(panel); } else if (str_type.equals("下拉框")) { AbstractNovaComponent panel=null; if(vos[i].getConditionComBoxItemVos()!=null){ panel = new QueryComboxPanel(vos[i]); }else{ panel = new ComBoxPanel(vos[i]); } showpanel.add(panel); //TODO 这里的setValue应该和setObject统一起来 ((ComBoxPanel)panel).setValue(execFormula(vos[i].getDefaultCondition())); v_compents.add(panel); } else if (str_type.equals("参照")) { AbstractNovaComponent panel=null; if(vos[i].getConditionRefDesc()!=null){ panel = new QueryUIRefPanel(vos[i]); }else{ panel = new UIRefPanel(vos[i]); } showpanel.add(panel); //TODO 这里的setValue应该和setObject统一起来 ((UIRefPanel)panel).setValue(execFormula(vos[i].getDefaultCondition())); v_compents.add(panel); } else if (str_type.equals("日历")) { QueryCalendarPanel Panel = new QueryCalendarPanel(vos[i],QueryCalendarPanel.TYPE_DATE); showpanel.add(Panel); Panel.setValue(execFormula(vos[i].getDefaultCondition())); v_compents.add(Panel); } else if (str_type.equals("时间")) { QueryCalendarPanel Panel = new QueryCalendarPanel(vos[i],QueryCalendarPanel.TYPE_TIME); showpanel.add(Panel); Panel.setValue(execFormula(vos[i].getDefaultCondition())); v_compents.add(Panel); } else if (str_type.equals("勾选框")) { UICheckBoxPanel panel = new UICheckBoxPanel(vos[i]); showpanel.add(panel); panel.setValue(execFormula(vos[i].getDefaultCondition())); v_compents.add(panel); } } } } showpanel.addComponentListener(new ComponentAdapter(){ public void componentResized(ComponentEvent e) { //Object o=e.getSource(); Object o=e.getComponent(); if(o instanceof JPanel){ if(((JPanel)o).getName().equalsIgnoreCase("quickquerypanel")){ //System.out.println(e.paramString()); int width=((JPanel)o).getWidth(); int height=(int)((JPanel)o).getSize().getHeight(); //System.out.println("新高度"+height); int newheight=NovaPanelUtil.getPanelHeight(width,(JPanel[])v_compents.toArray(new JPanel[0]),StringUtil.parseInt(Sys.getInfo("UI_FIELD_VGAP"),1)); newheight=newheight+querybtnpanel.getHeight(); if(height!=newheight){ //((JPanel)o).setPreferredSize(null); JInternalFrame frame =getJInternalFrame((JPanel)o); if(frame==null)return ; //((JPanel)o).setPreferredSize(new Dimension(((JPanel)o).getWidth(),getPanelHeight(((JPanel)o),v_compents,5))); //((JPanel)o).setMinimumSize(new Dimension(width,newheight)); ((JPanel)o).setPreferredSize(new Dimension(width,newheight)); //((JPanel)o).updateUI(); ((JPanel)o).invalidate(); //frame.getRootPane().invalidate(); frame.getRootPane().revalidate(); } //JOptionPane.showMessageDialog(null,"大小事件,宽:"+((JPanel)o).getWidth()); //JOptionPane.showMessageDialog(null,"大小事件,高:"+((JPanel)o).getHeight()); } } } //找出最高一级的JInternalFrame、JFrame、Window private JInternalFrame getJInternalFrame(JComponent obj){ Container parent=obj; while(!((parent=parent.getParent()) instanceof JInternalFrame)){ if(obj==null) return null; } return (JInternalFrame)parent; } }); this.setLayout(new BorderLayout()); this.add(showpanel, BorderLayout.CENTER); //快速检索命令按钮 if (this.billlist != null) { querybtnpanel = new JPanel(); FlowLayout f = new FlowLayout(FlowLayout.RIGHT); flayout.setHgap(0); flayout.setVgap(3); querybtnpanel.setLayout(f); //JButton btn = new JButton("检索"); JButton btn = new JButton("检索", UIUtil.getImage("images/office/(03,31).png","快速检索")); btn.setPreferredSize(new Dimension(80, 20)); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try{ onQuery(); }catch(Exception ee){ NovaMessage.show(billlist, "操作错误:"+ee.getMessage(), NovaConstants.MESSAGE_ERROR); } } }); querybtnpanel.add(btn); this.add(querybtnpanel, BorderLayout.SOUTH); } if (NovaClientEnvironment.getInstance().isAdmin()) { this.setToolTipText("点击右键可以查看详细查询SQL!"); } } /** * 执行默认值方式 * */ private String execFormula(String formula) { if (formula != null && !formula.trim().equals("")) { String modify_formula = null; try { modify_formula = new FrameWorkTBUtil().convertFormulaMacPars(formula.trim(),NovaClientEnvironment.getInstance(), null); } catch (Exception e) { System.out.println("执行公式:[" + formula + "]失败!!!!"); //e.printStackTrace(); // } if (modify_formula != null) { String str_value = JepFormulaUtil.getJepFormulaValue(modify_formula,JepFormulaParse.li_ui); // 真正执行转换后的公式!!// //System.out.println("执行默认值公式:[" + formula + "],转换后[" + modify_formula + "],执行结果[" + str_value + "]"); // this.setCompentObjectValue(tempitem.getItemkey(), // str_value); //设置控件值,这里应该是送Object!!有待进一步改进!! return str_value; } return modify_formula; } return formula; } private class QueryKeyListener extends KeyAdapter { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { try{ onQuery(); }catch(Exception ee){ NovaMessage.show(billlist, "操作错误:"+ee.getMessage(), NovaConstants.MESSAGE_ERROR); } } } } private void showPopupMenu(MouseEvent e) { JPopupMenu menu = new JPopupMenu("查看SQL"); JMenuItem item = new JMenuItem("查看SQL"); menu.add(item); menu.show(this, e.getX(), e.getY()); item.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { showSQLDialog(); } } }); } private void showSQLDialog() { NovaMessage.show(this, this.realqueySQL, NovaConstants.MESSAGE_INFO); } /** * 执行检索 */ public void onQuery()throws Exception { /** * 1、创建sql * 2、判断附加条件 * 3、判断是否具有排序处理 * 4、组合sql */ if (billlist == null) { return; } String querysql = this.getQuerySQL(); if (querysql == null || querysql.equals("")) { querysql = "1=1"; } if (condition != null && !condition.equals("")) { querysql = querysql + " and " + condition; } //通过BillListPanel对sql进行组合完整 this.realqueySQL = billlist.getSQL(querysql); //3、判断是否具有排序处理 this.realqueySQL+=(this.ordersetting!=null&&!this.ordersetting.trim().equals(""))?(" order by "+this.ordersetting):""; //执行查询 billlist.QueryData(this.realqueySQL); Component frame = billlist.getLoadedFrame(); //如果是模板9,还要清除所有子表数据!! if (frame != null && frame instanceof smartx.publics.styletemplet.ui.templet09.AbstractTempletFrame09) { smartx.publics.styletemplet.ui.templet09.AbstractTempletFrame09 new_name = (smartx.publics.styletemplet.ui.templet09.AbstractTempletFrame09) frame; BillListPanel[] billListPanels = new_name.getChild_BillListPanels(); for (int i = 0; i < billListPanels.length; i++) { billListPanels[i].clearTable(); // } } } public void setQueryCondition(String condition){ this.condition=condition; } public INovaCompent getCompentByKey(String _key) { INovaCompent[] compents = (INovaCompent[]) v_compents.toArray(new INovaCompent[0]); for (int i = 0; i < compents.length; i++) { if (compents[i].getKey().equalsIgnoreCase(_key)) { return compents[i]; } } return null; } /** * 获得检索Sql * @return sql */ public String getQuerySQL() throws Exception { //initcard(); sbcard = new StringBuffer("1=1 "); //应该使用v_compents来判断所有条件,没有必要重新读取vo for (int i = 0; i < v_compents.size(); i++) { INovaCompent icomp=(INovaCompent)v_compents.get(i); Pub_Templet_1_ItemVO vo=icomp.getTempletItemVO(); String votype=vo.getConditionItemType(); votype=(votype==null)?vo.getItemtype():votype; //判断是否必要条件 if(vo.isMustCondition()&&isEmptyCompentByKey(icomp)){ String n=vo.getItemname(); throw new Exception("必选条件【"+n+"】没有填写。"); } //判断是否条件为空 if(isEmptyCompentByKey(icomp)){ continue; } if (votype.equals("时间")) { sbcard.append("and "+icomp.getObject()); } else if (votype.equals("日历")) { sbcard.append("and "+icomp.getObject()); } else if (votype.equals("数字框")) { sbcard.append("and "+icomp.getValue()); } else if (votype.equals("下拉框") || votype.equals("参照") || votype.equals("勾选框")) { String v=icomp.getValue(); if(v!=null){ sbcard.append(" and " + vo.getItemkey() + " = '" + v + "' "); } }else{ sbcard.append(" and upper(" + vo.getItemkey() + ") LIKE upper('%" + icomp.getObject() + "%') "); } } return sbcard.toString(); } //界面字段是否为空 private boolean isEmptyCompentByKey(String _key) { INovaCompent[] compents = (INovaCompent[]) v_compents.toArray(new INovaCompent[0]); for (int i = 0; i < compents.length; i++) { if (compents[i].getKey().equalsIgnoreCase(_key)) { Object v=compents[i].getObject(); return v==null||v.toString().equals(""); } } return false; } //界面字段是否为空 private boolean isEmptyCompentByKey(INovaCompent com) { Object v=com.getObject(); return v==null||v.toString().equals(""); } public ArrayList findIndexMap(Object _ob) { ArrayList index = new ArrayList(); if (map.get(_ob) instanceof ArrayList) { index.add( ( (ArrayList) (map.get(_ob))).get(0).toString()); index.add( ( (ArrayList) (map.get(_ob))).get(1).toString()); } return index; } /** * 当前类用到了好多个"getTempletViewItemVOs()", 其返回的是当前表(视图)中查询的列 * 在查询统计时,会要求快速查询界面不光显示表(视图)中查询的列,有可能显示一些用于过滤数据的列, * 计划通过之类重写该方法,对于表(视图)中没有查询的列,同样可以作为查询条件来显示 * @return Pub_Templet_1_ItemVO[] */ public Pub_Templet_1_ItemVO[] getTempletViewItemVOs(){ return templetVO.getRealViewItemVOs(); } } /************************************************************************** * $RCSfile: QuickQueryPanel.java,v $ $Revision: 1.13.2.15 $ $Date: 2009/12/02 05:36:02 $ * * $Log: QuickQueryPanel.java,v $ * Revision 1.13.2.15 2009/12/02 05:36:02 wangqi * *** empty log message *** * * Revision 1.13.2.14 2009/07/30 07:19:59 wangqi * *** empty log message *** * * Revision 1.13.2.13 2009/07/28 08:36:42 wangqi * *** empty log message *** * * Revision 1.13.2.12 2009/07/23 09:34:13 wangqi * *** empty log message *** * * Revision 1.13.2.11 2009/07/22 08:23:44 wangqi * *** empty log message *** * * Revision 1.13.2.10 2009/07/21 08:41:30 wangqi * *** empty log message *** * * Revision 1.13.2.9 2009/06/24 08:36:12 wangqi * *** empty log message *** * * Revision 1.13.2.8 2009/06/12 05:25:22 wangqi * *** empty log message *** * * Revision 1.13.2.7 2009/05/20 10:25:08 wangqi * *** empty log message *** * * Revision 1.13.2.6 2009/02/05 12:02:53 wangqi * *** empty log message *** * * Revision 1.13.2.5 2008/11/20 05:32:02 wangqi * *** empty log message *** * * Revision 1.13.2.4 2008/11/17 06:48:13 wangqi * *** empty log message *** * * Revision 1.13.2.3 2008/11/05 05:21:14 wangqi * *** empty log message *** * * Revision 1.13.2.2 2008/10/20 14:39:56 wangqi * *** empty log message *** * * Revision 1.13.2.1 2008/09/16 06:13:41 wangqi * patch : 20080916 * file : nova_20080128_20080916.jar * content : 处理 MR nova20-87,nova20-30; * 另外,改写了快速查询面板的处理。 * * Revision 1.15 2008/05/26 07:48:44 wangqi * *** empty log message *** * * Revision 1.14 2008/02/27 09:07:59 wangqi * *** empty log message *** * * Revision 1.13 2008/01/15 04:36:23 wangqi * *** empty log message *** * * Revision 1.12 2007/12/04 07:14:39 wangqi * *** empty log message *** * * Revision 1.11 2007/08/27 09:01:37 yanghuan * 修改bug,该bug描述:计算的高度不正确导致快速查询面板不能显示完整的查询条件 * * Revision 1.10 2007/08/24 07:06:53 yanghuan * 解决计算高度错误的bug * * Revision 1.9 2007/08/07 08:18:14 sunxf * 修改bug * * Revision 1.8 2007/07/31 04:50:06 sunxf * MR#:Nova 20-16 更改高度及滚动条显示时机 * * Revision 1.7 2007/07/24 05:47:53 lst * no message * * Revision 1.6 2007/07/18 11:08:42 sunxf * 日期时间查询控件 * * Revision 1.5 2007/07/17 06:14:47 sunxf * 修改多行显示不下的问题 * * Revision 1.4 2007/06/07 00:56:38 sunxb * *** empty log message *** * * Revision 1.3 2007/05/31 07:39:01 qilin * code format * * Revision 1.2 2007/05/31 06:47:51 qilin * 界面重构,所有的JFrame改为JInternalFrame样式 * * Revision 1.1 2007/05/17 06:14:29 qilin * no message * * Revision 1.13 2007/05/15 08:29:33 qilin * no message * * Revision 1.12 2007/03/29 05:29:58 shxch * *** empty log message *** * * Revision 1.11 2007/03/21 03:09:42 qilin * no message * * Revision 1.10 2007/03/15 05:27:05 shxch * *** empty log message *** * * Revision 1.9 2007/03/15 05:10:11 shxch * *** empty log message *** * * Revision 1.8 2007/03/15 04:59:43 shxch * *** empty log message *** * * Revision 1.7 2007/03/14 02:11:15 sunxf * *** empty log message *** * * Revision 1.6 2007/03/14 01:51:12 sunxf * *** empty log message *** * * Revision 1.5 2007/03/14 01:31:03 sunxf * *** empty log message *** * * Revision 1.4 2007/03/05 09:59:15 shxch * *** empty log message *** * * Revision 1.3 2007/03/02 05:28:06 shxch * *** empty log message *** * * Revision 1.2 2007/01/30 04:23:45 lujian * *** empty log message *** * * **************************************************************************/
Java
UTF-8
336
1.5
2
[]
no_license
package com.jk.pai.service; import java.util.List; import org.springframework.stereotype.Service; import com.jk.pai.model.Item; @Service public interface ISelectedProductsService { public boolean ImportProduct2DataBase(List<Item> itemList); public List<Item> AnalysisExcle(String FilePath, byte[] buf); }
Markdown
UTF-8
3,115
3.3125
3
[ "MIT" ]
permissive
--- title: 函数节流 date: 2018-03-01T08:44:29Z lastmod: 2018-03-01T08:44:35Z summary: tags: ["原生JS", "节流"] draft: false layout: PostLayout bibliography: references-data.bib --- 关于节流的实现,有两种主流的实现方式,一种是使用时间戳,一种是设置定时器,第一种事件会立刻执行,第二种事件会在 n 秒后第一次执行,第一种事件停止触发后没有办法再执行事件,第二种事件停止触发后依然会再执行一次事件 ``` <div class="box"></div> var box = document.getElementsByClassName("box")[0]; var WAIT_TIME = 500; var throttle1 = function (func, time){ var previous = 0, _this, args; return function (){ var now = +new Date(); //使用时间搓 _this = this; args = arguments; if(now - previous > time){ func.apply(_this, args); previous = now; } } } var throttle2 = function (func, time){ var _this, timeout, args; return function (){ _this = this; args = arguments; if(!timeout){ timeout = setTimeout(function (){ func.apply(_this, args); timeout = null; }, time); } } } var throttle3 = function (func, time){//时间戳与定时器的结合 var previous = 0, _this, timeout, args; var later = function (){ previous = +new Date(); timeout = null; func.apply(_this, args); } return function (){ var now = +new Date(); var remaining = time - (now - previous); //下次执行func剩余的时间 _this = this; args = arguments; if(remaining < 0 || remaining > time){ if(timeout){ clearTimeout(timeout); timeout = null; } previous = now; func.apply(_this, args); }else if(!timeout) { timeout = setTimeout(later, remaining); } } } var throttle4 = function (func, time, options){//时间戳与定时器的结合 var previous = 0, _this, timeout, args; if (!options) options = {}; var later = function (){ previous = options.leading === false ? 0 : new Date().getTime(); timeout = null; func.apply(_this, args); if (!timeout) _this = args = null; } return function (){ var now = +new Date(); if(!previous && options.leading === false) previous = now; var remaining = time - (now - previous); //下次执行func剩余的时间 _this = this; args = arguments; if(remaining < 0 || remaining > time){ if(timeout){ clearTimeout(timeout); timeout = null; } previous = now; func.apply(_this, args); if (!timeout) _this = args = null; }else if(!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } } } var getUserAction = function (){ console.log(this); console.log(arguments); } // box.onmousemove = throttle1(getUserAction, 1000); // box.onmousemove = throttle2(getUserAction, 1000); // box.onmousemove = throttle3(getUserAction, 1000); // box.onmousemove = throttle4(getUserAction, 1000,{ // leading:false 表示禁用第一次执行 trailing: false 表示禁用停止触发的回调 // }); box.onmousemove = throttle4(getUserAction, 1000,{ trailing: false }); ```
C#
UTF-8
845
3.65625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lottery { static class Seller { const int Size = 6; public static int [] GuessTicket() { int [] digits = new int[Size]; for (int i = 0; i < Size; i++) { bool res = false; do { Console.Write(String.Format("Digit {0} = ", i + 1)); res = Int32.TryParse(Console.ReadLine(), out digits[i]); if (!res || digits[i] < 1 || digits[i] > 9) { Console.WriteLine("Incorrect format!"); } } while(!res); } return digits; } } }
Java
UTF-8
11,285
1.929688
2
[]
no_license
package solrapi; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Function; import java.util.stream.Collectors; import common.Tools; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.util.Strings; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.SortClause; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.StreamingResponseCallback; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.MoreLikeThisParams; import org.apache.solr.common.util.SimpleOrderedMap; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.common.io.Files; public class SolrClient { private final static String COLLECTION = "dependencies"; final static Logger logger = LogManager.getLogger(SolrClient.class); private HttpSolrClient client; private static ObjectMapper mapper = new ObjectMapper(); public SolrClient(String solrHostURL) { client = new HttpSolrClient.Builder(solrHostURL).build(); } public static void main(String[] args) { SolrClient client = new SolrClient("http://localhost:8983/solr"); //client.writeTrainingDataToFile(Tools.getProperty("nlp.waterNerTrainingFile"), client::getWaterDataQuery, client::formatForNERModelTraining); //retrieveAnnotatedData(client, "0bb9ead9-c71a-43fa-8e80-35e5d566c15e"); updateAnnotatedData(client, "0bb9ead9-c71a-43fa-8e80-35e5d566c15e"); } private static void retrieveAnnotatedData(SolrClient client, String id) { try { SolrDocumentList docs = client.QuerySolrDocuments("id:" + id, 1, 0, null); SolrDocument doc = docs.get(0); String annotated = (String)doc.get("annotated"); FileUtils.writeStringToFile(new File("data/annotated.txt"), annotated, Charset.forName("Cp1252").displayName()); } catch (SolrServerException | IOException e) { e.printStackTrace(); } } private static void updateAnnotatedData(SolrClient client, String id) { String annotated = Tools.GetFileString("data/annotated.txt"); try { SolrDocumentList docs = client.QuerySolrDocuments("id:" + id, 1, 0, null); SolrDocument doc = docs.get(0); if (doc.containsKey("annotated")) { doc.replace("annotated", annotated); } else { doc.addField("annotated", annotated); } client.indexDocument(doc); } catch (SolrServerException e) { e.printStackTrace(); } } public void indexDocuments(Collection<SolrDocument> docs) throws SolrServerException { try { if (!docs.isEmpty()) { List<SolrInputDocument> inputDocuments = new ArrayList<>(); for (SolrDocument doc : docs) { SolrInputDocument solrInputDocument = convertSolrDocument(doc); inputDocuments.add(solrInputDocument); } client.add(COLLECTION, inputDocuments); UpdateResponse updateResponse = client.commit(COLLECTION); if (updateResponse.getStatus() != 0) { //TODO What should happen if the update fails? } } } catch (IOException e) { logger.error(e.getMessage(), e); } } private SolrInputDocument convertSolrDocument(SolrDocument doc) { SolrInputDocument solrInputDocument = new SolrInputDocument(); for (String name : doc.getFieldNames()) { solrInputDocument.addField(name, doc.getFieldValue(name)); } List<SolrDocument> children = doc.getChildDocuments(); if (children != null) { for (SolrDocument child : children) { solrInputDocument.addChildDocument(convertSolrDocument(child)); } } return solrInputDocument; } public void indexDocument(SolrDocument doc) throws SolrServerException { List<SolrDocument> docs = new ArrayList<>(); docs.add(doc); indexDocuments(docs); } public void deleteDocuments(String query) throws SolrServerException { try { client.deleteByQuery(COLLECTION, query); UpdateResponse updateResponse = client.commit(COLLECTION); if (updateResponse.getStatus() != 0) { //TODO What should happen if the update fails? } } catch (IOException e) { logger.error(e.getMessage(), e); } } public Boolean DocumentExists(String queryStr) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setRows(0); query.setQuery(queryStr); try { QueryResponse response = client.query(COLLECTION, query); return response.getResults().getNumFound() > 0; } catch (IOException e) { logger.error(e.getMessage(), e); return false; } } public SimpleOrderedMap<?> QueryFacets(String queryStr, String facetQuery) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setRows(0); query.setQuery(queryStr); query.add("json.facet", facetQuery); try { QueryResponse response = client.query(COLLECTION, query); SimpleOrderedMap<?> facets = (SimpleOrderedMap<?>) response.getResponse().get("facets"); return facets; } catch (IOException e) { logger.error(e.getMessage(), e); return null; } } public SolrDocumentList FindSimilarDocuments(String searchText) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setRequestHandler("/" + MoreLikeThisParams.MLT); query.setParam(CommonParams.STREAM_BODY, searchText); query.setRows(20); try { SolrDocumentList response = client.query(COLLECTION, query).getResults(); return response; } catch (IOException e) { logger.error(e.getMessage(), e); return null; } } public SolrDocumentList QuerySolrDocuments(String queryStr, int rows, int start, SortClause sort, String... filterQueries) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery(queryStr); if (filterQueries != null) { query.setFilterQueries(filterQueries); } query.setRows(rows); query.setStart(start); if (sort != null) { query.setSort(sort); } else { } try { SolrDocumentList response = client.query(COLLECTION, query).getResults(); return response; } catch (IOException e) { logger.error(e.getMessage(), e); return null; } } public <T> List<T> QueryIndexedDocuments(Class<T> clazz, String queryStr, int rows, int start, SortClause sort, String... filterQueries) throws SolrServerException { SolrQuery query = new SolrQuery(); query.setQuery(queryStr); if (filterQueries != null) { query.setFilterQueries(filterQueries); } query.setRows(rows); query.setStart(start); if (sort != null) { query.setSort(sort); } else { } try { Constructor<?> cons; try { cons = clazz.getConstructor(SolrDocument.class); } catch (NoSuchMethodException | SecurityException e1) { return null; } SolrDocumentList response = client.query(COLLECTION, query).getResults(); List<T> typedDocs = convertSolrDocsToTypedDocs(cons, response); return typedDocs; } catch (IOException e) { logger.error(e.getMessage(), e); return null; } } private <T> List<T> convertSolrDocsToTypedDocs(Constructor<?> cons, SolrDocumentList docs) { List<T> typedDocs = (List<T>) docs.stream().map(p -> { try { return cons.newInstance(p); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error(e.getMessage(), e); return null; } }).collect(Collectors.toList()); return typedDocs; } public static SolrQuery getAnnotatedDataQuery(SolrQuery query) { query.setQuery("annotated:*"); return query; } public static SolrQuery getWaterDataQuery(SolrQuery query) { query.setQuery("annotated:* AND category:Water"); return query; } public static SolrQuery getWastewaterDataQuery(SolrQuery query) { query.setQuery("annotated:* AND category:Wastewater"); return query; } public static SolrQuery getElectricityDataQuery(SolrQuery query) { query.setQuery("annotated:* AND category:Electricity"); return query; } public void formatForNERModelTraining(SolrDocument doc, FileOutputStream fos) throws IOException { String[] lines = ((String)doc.get("annotated")).split("\r\n"); List<String> annotatedLines = Arrays.stream(lines).filter(p -> p.contains("<START:")).collect(Collectors.toList()); String onlyAnnotated = String.join("\r\n", annotatedLines); fos.write(onlyAnnotated.getBytes(Charset.forName("Cp1252"))); } public void WriteDataToFile(String filePath, String queryStr, int rows, String... filterQueries) throws SolrServerException { ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter(); SolrDocumentList docs = QuerySolrDocuments(queryStr, rows, 0, null, filterQueries); try { String output = writer.writeValueAsString(docs); File file = new File(filePath); file.getParentFile().mkdirs(); Files.write(output, file, Charset.forName("Cp1252")); } catch (IOException e) { logger.error(e.getMessage(), e); } } public void writeTrainingDataToFile(String trainingFilePath, Function<SolrQuery, SolrQuery> queryGetter, Tools.CheckedBiConsumer<SolrDocument, FileOutputStream> consumer) { SolrQuery query = queryGetter.apply(new SolrQuery()); query.setRows(1000000); try { File file = new File(trainingFilePath); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); final BlockingQueue<SolrDocument> tmpQueue = new LinkedBlockingQueue<SolrDocument>(); client.queryAndStreamResponse(COLLECTION, query, new CallbackHandler(tmpQueue)); SolrDocument tmpDoc; do { tmpDoc = tmpQueue.take(); if (!(tmpDoc instanceof StopDoc)) { consumer.apply(tmpDoc, fos); fos.write(System.lineSeparator().getBytes()); } } while (!(tmpDoc instanceof StopDoc)); fos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } private class StopDoc extends SolrDocument { // marker to finish queuing } private class CallbackHandler extends StreamingResponseCallback { private BlockingQueue<SolrDocument> queue; private long currentPosition; private long numFound; public CallbackHandler(BlockingQueue<SolrDocument> aQueue) { queue = aQueue; } @Override public void streamDocListInfo(long aNumFound, long aStart, Float aMaxScore) { // called before start of streaming // probably use for some statistics currentPosition = aStart; numFound = aNumFound; if (numFound == 0) { queue.add(new StopDoc()); } } @Override public void streamSolrDocument(SolrDocument doc) { currentPosition++; queue.add(doc); if (currentPosition == numFound) { queue.add(new StopDoc()); } } } }
Java
UTF-8
21,178
1.921875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 MiLaboratory.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.milaboratory.core.alignment; import com.milaboratory.core.Range; import com.milaboratory.core.mutations.MutationType; import com.milaboratory.core.mutations.Mutations; import com.milaboratory.core.sequence.Alphabet; import com.milaboratory.core.sequence.Sequence; import com.milaboratory.core.sequence.SequenceQuality; import com.milaboratory.util.BitArray; import com.milaboratory.util.IntArrayList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.milaboratory.core.mutations.Mutation.RAW_MUTATION_TYPE_DELETION; import static com.milaboratory.core.mutations.Mutation.RAW_MUTATION_TYPE_SUBSTITUTION; public class MultiAlignmentHelper { // subject / queries nomenclature seems to be swapped here... // subject here corresponds to sequence2 from alignments (so, the query sequence) // queries here corresponds to sequence1 from alignments (so, the reference sequence) int minimalPositionWidth = 0; final String subject; final String[] queries; final int[] subjectPositions; final int[][] queryPositions; final BitArray[] match; final List<String> annotationStrings = new ArrayList<>(); final List<String> annotationStringTitles = new ArrayList<>(); String subjectLeftTitle; final String[] queryLeftTitles; String subjectRightTitle; final String[] queryRightTitles; private MultiAlignmentHelper(String subject, String[] queries, int[] subjectPositions, int[][] queryPositions, BitArray[] match, String subjectLeftTitle, String[] queryLeftTitles, String subjectRightTitle, String[] queryRightTitles) { this.subject = subject; this.queries = queries; this.subjectPositions = subjectPositions; this.queryPositions = queryPositions; this.match = match; this.subjectLeftTitle = subjectLeftTitle; this.queryLeftTitles = queryLeftTitles; this.subjectRightTitle = subjectRightTitle; this.queryRightTitles = queryRightTitles; } private MultiAlignmentHelper(String subject, String[] queries, int[] subjectPositions, int[][] queryPositions, BitArray[] match) { this(subject, queries, subjectPositions, queryPositions, match, "", new String[queries.length], "", new String[queries.length]); } public String getSubject() { return subject; } public String getQuery(int idx) { return queries[idx]; } public int[] getSubjectPositions() { return subjectPositions; } public int[][] getQueryPositions() { return queryPositions; } public BitArray[] getMatch() { return match; } public String getSubjectLeftTitle() { return subjectLeftTitle; } public String getSubjectRightTitle() { return subjectRightTitle; } public String getQueryLeftTitle(int i) { return queryLeftTitles[i]; } public String getQueryRightTitle(int i) { return queryRightTitles[i]; } public int getActualPositionWidth() { int ret = ("" + getSubjectFrom()).length(); for (int i = 0; i < queries.length; i++) ret = Math.max(ret, ("" + getQueryFrom(i)).length()); return ret; } public void setMinimalPositionWidth(int minimalPositionWidth) { this.minimalPositionWidth = minimalPositionWidth; } public MultiAlignmentHelper setSubjectLeftTitle(String subjectLeftTitle) { this.subjectLeftTitle = subjectLeftTitle; return this; } public MultiAlignmentHelper addSubjectQuality(String title, SequenceQuality quality) { char[] chars = new char[size()]; for (int i = 0; i < size(); ++i) chars[i] = subjectPositions[i] < 0 ? ' ' : simplifiedQuality(quality.value(subjectPositions[i])); addAnnotationString(title, new String(chars)); return this; } private static char simplifiedQuality(int value) { value /= 5; if (value > 9) value = 9; return Integer.toString(value).charAt(0); } public MultiAlignmentHelper setSubjectRightTitle(String subjectRightTitle) { this.subjectRightTitle = subjectRightTitle; return this; } public MultiAlignmentHelper addAnnotationString(String title, String string) { if (string.length() != size()) throw new IllegalArgumentException(); annotationStrings.add(string); annotationStringTitles.add(title); return this; } public MultiAlignmentHelper setQueryLeftTitle(int id, String queryLeftTitle) { this.queryLeftTitles[id] = queryLeftTitle; return this; } public MultiAlignmentHelper setQueryRightTitle(int id, String queryRightTitle) { this.queryRightTitles[id] = queryRightTitle; return this; } public int getSubjectPositionAt(int position) { return subjectPositions[position]; } public int subjectToAlignmentPosition(int subjectPosition) { for (int i = 0; i < subjectPositions.length; i++) if (subjectPositions[i] == subjectPosition) return i; return -1; } public int getQueryPositionAt(int index, int position) { return queryPositions[index][position]; } public int getAbsSubjectPositionAt(int position) { return aabs(subjectPositions[position]); } public int getAbsQueryPositionAt(int index, int position) { return aabs(queryPositions[index][position]); } private static int aabs(int pos) { if (pos >= 0) return pos; if (pos == -1) return -1; return -2 - pos; } public int getSubjectFrom() { return getFirstPosition(subjectPositions); } public int getSubjectTo() { return getLastPosition(subjectPositions); } public int getSubjectLength() { return 1 + getSubjectTo() - getSubjectFrom(); } public int getQueryFrom(int index) { return getFirstPosition(queryPositions[index]); } public int getQueryTo(int index) { return getLastPosition(queryPositions[index]); } public String getAnnotationString(int i) { return annotationStrings.get(i); } public int size() { return subject.length(); } public MultiAlignmentHelper getRange(int from, int to) { boolean[] queriesToExclude = new boolean[queries.length]; int queriesCount = 0; for (int i = 0; i < queries.length; i++) { boolean exclude = true; for (int j = from; j < to; j++) if (queryPositions[i][j] != -1) { exclude = false; break; } queriesToExclude[i] = exclude; if (!exclude) queriesCount++; } String[] cQueries = new String[queriesCount]; int[][] cQueryPositions = new int[queriesCount][]; BitArray[] cMatch = new BitArray[queriesCount]; String[] cQueryLeftTitles = new String[queriesCount]; String[] cQueryRightTitles = new String[queriesCount]; int j = 0; for (int i = 0; i < queries.length; i++) { if (queriesToExclude[i]) continue; cQueries[j] = queries[i].substring(from, to); cQueryPositions[j] = Arrays.copyOfRange(queryPositions[i], from, to); cMatch[j] = match[i].getRange(from, to); cQueryLeftTitles[j] = queryLeftTitles[i]; cQueryRightTitles[j] = queryRightTitles[i]; j++; } MultiAlignmentHelper result = new MultiAlignmentHelper(subject.substring(from, to), cQueries, Arrays.copyOfRange(subjectPositions, from, to), cQueryPositions, cMatch, subjectLeftTitle, cQueryLeftTitles, subjectRightTitle, cQueryRightTitles); for (int i = 0; i < annotationStrings.size(); i++) result.addAnnotationString(annotationStringTitles.get(i), annotationStrings.get(i).substring(from, to)); return result; } public MultiAlignmentHelper[] split(int length) { return split(length, false); } public MultiAlignmentHelper[] split(int length, boolean eqPositionWidth) { MultiAlignmentHelper[] ret = new MultiAlignmentHelper[(size() + length - 1) / length]; for (int i = 0; i < ret.length; ++i) { int pointer = i * length; int l = Math.min(length, size() - pointer); ret[i] = getRange(pointer, pointer + l); } if (eqPositionWidth) alignPositions(ret); return ret; } private static int getFirstPosition(int[] array) { for (int pos : array) if (pos >= 0) return pos; for (int pos : array) if (pos < -1) return -2 - pos; return -1; } private static int getLastPosition(int[] array) { for (int i = array.length - 1; i >= 0; i--) if (array[i] >= 0) return array[i]; for (int i = array.length - 1; i >= 0; i--) if (array[i] < -1) return -2 - array[i]; return -1; } private static int fixedWidthL(String[] strings) { return fixedWidthL(strings, 0); } private static int fixedWidthL(String[] strings, int minWidth) { int length = 0; for (String string : strings) length = Math.max(length, string.length()); length = Math.max(length, minWidth); for (int i = 0; i < strings.length; i++) strings[i] = spaces(length - strings[i].length()) + strings[i]; return length; } private static int fixedWidthR(String[] strings) { return fixedWidthR(strings, 0); } private static int fixedWidthR(String[] strings, int minWidth) { int length = 0; for (String string : strings) length = Math.max(length, string.length()); length = Math.max(length, minWidth); for (int i = 0; i < strings.length; i++) strings[i] = strings[i] + spaces(length - strings[i].length()); return length; } public static class Settings { public final boolean markMatchWithSpecialLetter; public final boolean lowerCaseMatch; public final boolean lowerCaseMismatch; public final char specialMatchChar; public final char outOfRangeChar; public Settings(boolean markMatchWithSpecialLetter, boolean lowerCaseMatch, boolean lowerCaseMismatch, char specialMatchChar, char outOfRangeChar) { this.markMatchWithSpecialLetter = markMatchWithSpecialLetter; this.lowerCaseMatch = lowerCaseMatch; this.lowerCaseMismatch = lowerCaseMismatch; this.specialMatchChar = specialMatchChar; this.outOfRangeChar = outOfRangeChar; } } @Override public String toString() { int aCount = queries.length; int asSize = annotationStringTitles.size(); String[] lines = new String[aCount + 1 + asSize]; for (int i = 0; i < asSize; i++) lines[i] = ""; lines[asSize] = "" + getSubjectFrom(); for (int i = 0; i < aCount; i++) lines[i + 1 + asSize] = "" + getQueryFrom(i); int width = fixedWidthL(lines, minimalPositionWidth); for (int i = 0; i < asSize; i++) lines[i] = annotationStringTitles.get(i) + spaces(width + 1); lines[asSize] = (subjectLeftTitle == null ? "" : subjectLeftTitle) + " " + lines[asSize]; for (int i = 0; i < aCount; i++) lines[i + 1 + asSize] = (queryLeftTitles[i] == null ? "" : queryLeftTitles[i]) + " " + lines[i + 1 + asSize]; width = fixedWidthL(lines); for (int i = 0; i < asSize; i++) lines[i] += " " + annotationStrings.get(i); lines[asSize] += " " + subject + " " + getSubjectTo(); for (int i = 0; i < aCount; i++) lines[i + 1 + asSize] += " " + queries[i] + " " + getQueryTo(i); width = fixedWidthR(lines); lines[asSize] += " " + subjectRightTitle; for (int i = 0; i < aCount; i++) if (queryRightTitles[i] != null) lines[i + 1 + asSize] += " " + queryRightTitles[i]; StringBuilder result = new StringBuilder(); for (int i = 0; i < lines.length; i++) { if (i != 0) result.append("\n"); result.append(lines[i]); } return result.toString(); } public static final Settings DEFAULT_SETTINGS = new Settings(false, true, false, ' ', ' '); public static final Settings DOT_MATCH_SETTINGS = new Settings(true, true, false, '.', ' '); public static <S extends Sequence<S>> MultiAlignmentHelper build(Settings settings, Range subjectRange, Alignment<S>... alignments) { S subject = alignments[0].getSequence1(); return build(settings, subjectRange, subject, alignments); } public static <S extends Sequence<S>> MultiAlignmentHelper build(Settings settings, Range subjectRange, S subject, Alignment<S>... alignments) { for (Alignment<S> alignment : alignments) if (!alignment.getSequence1().equals(subject)) throw new IllegalArgumentException(); int subjectPointer = subjectRange.getFrom(); int subjectPointerTo = subjectRange.getTo(); int aCount = alignments.length; int[] queryPointers = new int[aCount]; int[] mutationPointers = new int[aCount]; Mutations<S>[] mutations = new Mutations[aCount]; List<Boolean>[] matches = new List[aCount]; IntArrayList subjectPositions = new IntArrayList(); IntArrayList[] queryPositions = new IntArrayList[aCount]; StringBuilder subjectString = new StringBuilder(); StringBuilder[] queryStrings = new StringBuilder[aCount]; for (int i = 0; i < aCount; i++) { queryPointers[i] = alignments[i].getSequence2Range().getFrom(); matches[i] = new ArrayList<>(); mutations[i] = alignments[i].getAbsoluteMutations(); queryPositions[i] = new IntArrayList(); queryStrings[i] = new StringBuilder(); } final Alphabet<S> alphabet = subject.getAlphabet(); BitArray processed = new BitArray(aCount); while (true) { // Checking continue condition boolean doContinue = subjectPointer < subjectPointerTo; for (int i = 0; i < aCount; i++) doContinue |= mutationPointers[i] < mutations[i].size(); if (!doContinue) break; processed.clearAll(); // Processing out of range sequences for (int i = 0; i < aCount; i++) if (!alignments[i].getSequence1Range().contains(subjectPointer) && !(alignments[i].getSequence1Range().containsBoundary(subjectPointer) && mutationPointers[i] != mutations[i].size())) { queryStrings[i].append(settings.outOfRangeChar); queryPositions[i].add(-1); matches[i].add(false); processed.set(i); } // Checking for insertions boolean insertion = false; for (int i = 0; i < aCount; i++) if (mutationPointers[i] < mutations[i].size() && mutations[i].getTypeByIndex(mutationPointers[i]) == MutationType.Insertion && mutations[i].getPositionByIndex(mutationPointers[i]) == subjectPointer) { insertion = true; queryStrings[i].append(mutations[i].getToAsSymbolByIndex(mutationPointers[i])); queryPositions[i].add(queryPointers[i]++); matches[i].add(false); mutationPointers[i]++; assert !processed.get(i); processed.set(i); } if (insertion) { // In case on insertion in query sequence subjectString.append('-'); subjectPositions.add(-2 - subjectPointer); for (int i = 0; i < aCount; i++) { if (!processed.get(i)) { queryStrings[i].append('-'); queryPositions[i].add(-2 - queryPointers[i]); matches[i].add(false); } } } else { // In other cases char subjectSymbol = subject.symbolAt(subjectPointer); subjectString.append(subjectSymbol); subjectPositions.add(subjectPointer); for (int i = 0; i < aCount; i++) { if (processed.get(i)) continue; Mutations<S> cMutations = mutations[i]; int cMutationPointer = mutationPointers[i]; boolean mutated = false; if (cMutationPointer < cMutations.size()) { int mutPosition = cMutations.getPositionByIndex(cMutationPointer); assert mutPosition >= subjectPointer; mutated = mutPosition == subjectPointer; } if (mutated) { switch (cMutations.getRawTypeByIndex(cMutationPointer)) { case RAW_MUTATION_TYPE_SUBSTITUTION: char symbol = cMutations.getToAsSymbolByIndex(cMutationPointer); queryStrings[i].append(settings.lowerCaseMismatch ? Character.toLowerCase(symbol) : symbol); queryPositions[i].add(queryPointers[i]++); matches[i].add(false); break; case RAW_MUTATION_TYPE_DELETION: queryStrings[i].append('-'); queryPositions[i].add(-2 - queryPointers[i]); matches[i].add(false); break; default: assert false; } mutationPointers[i]++; } else { if (settings.markMatchWithSpecialLetter) queryStrings[i].append(settings.specialMatchChar); else queryStrings[i].append(settings.lowerCaseMatch ? Character.toLowerCase(subjectSymbol) : subjectSymbol); queryPositions[i].add(queryPointers[i]++); matches[i].add(true); } } subjectPointer++; } } int[][] queryPositionsArrays = new int[aCount][]; BitArray[] matchesBAs = new BitArray[aCount]; String[] queryStringsArray = new String[aCount]; for (int i = 0; i < aCount; i++) { queryPositionsArrays[i] = queryPositions[i].toArray(); matchesBAs[i] = new BitArray(matches[i]); queryStringsArray[i] = queryStrings[i].toString(); } return new MultiAlignmentHelper(subjectString.toString(), queryStringsArray, subjectPositions.toArray(), queryPositionsArrays, matchesBAs); } public static void alignPositions(MultiAlignmentHelper[] helpers) { int maxPositionWidth = 0; for (MultiAlignmentHelper helper : helpers) maxPositionWidth = Math.max(maxPositionWidth, helper.getActualPositionWidth()); for (MultiAlignmentHelper helper : helpers) helper.setMinimalPositionWidth(maxPositionWidth); } private static String spaces(int n) { char[] c = new char[n]; Arrays.fill(c, ' '); return String.valueOf(c); } }
C
UTF-8
2,792
2.5625
3
[ "Zlib" ]
permissive
/* Copyright (c) 2013 Alex Diener This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Alex Diener adiener@sacredsoftware.net */ #include "utilities/FixedIntervalRunLoop.h" #include "utilities/AutoFreePool.h" #include <stdlib.h> #define SUPERCLASS StemObject FixedIntervalRunLoop * FixedIntervalRunLoop_create(double (* timeFunction)(), double stepInterval, FixedIntervalRunLoopCallback stepCallback, void * stepContext) { stemobject_create_implementation(FixedIntervalRunLoop, init, timeFunction, stepInterval, stepCallback, stepContext) } bool FixedIntervalRunLoop_init(FixedIntervalRunLoop * self, double (* timeFunction)(), double stepInterval, FixedIntervalRunLoopCallback stepCallback, void * stepContext) { call_super(init, self); self->timeFunction = timeFunction; self->stepInterval = stepInterval; self->stepCallback = stepCallback; self->stepContext = stepContext; self->lastTime = self->timeFunction(); self->slop = 0.0; self->paused = false; self->dispose = FixedIntervalRunLoop_dispose; self->run = FixedIntervalRunLoop_run; self->pause = FixedIntervalRunLoop_pause; self->resume = FixedIntervalRunLoop_resume; return true; } void FixedIntervalRunLoop_dispose(FixedIntervalRunLoop * self) { call_super(dispose, self); } void FixedIntervalRunLoop_run(FixedIntervalRunLoop * self) { double currentTime, interval; if (self->paused) { return; } currentTime = self->timeFunction(); interval = (currentTime - self->lastTime) + self->slop; while (interval >= self->stepInterval) { self->stepCallback(self->stepContext); interval -= self->stepInterval; } self->slop = interval; self->lastTime = currentTime; AutoFreePool_empty(); } void FixedIntervalRunLoop_pause(FixedIntervalRunLoop * self) { if (!self->paused) { self->paused = true; self->pauseTime = self->timeFunction(); } } void FixedIntervalRunLoop_resume(FixedIntervalRunLoop * self) { if (self->paused) { self->paused = false; self->lastTime += self->timeFunction() - self->pauseTime; } }
C++
UTF-8
877
2.640625
3
[]
no_license
#ifndef BASICSTATISTICPLOT_H #define BASICSTATISTICPLOT_H #include <qwt_plot.h> #include <qwt_plot_grid.h> class BasicStatistic; class Histogram; class LineChart; /** * Class to draw a plot of basic statistic. */ class BasicStatisticPlot : public QwtPlot { Q_OBJECT public: /** * Constructor. */ BasicStatisticPlot(BasicStatistic statistic); /** * Destructor. */ ~BasicStatisticPlot(); /** * Set the statistic. */ void setStatistic(BasicStatistic statistic); private: /** * 3 line charts for RGB. */ LineChart *lineCharts[3]; /** * 1 histogram for gray. */ Histogram *grayHistogram; /** * The grid. */ QwtPlotGrid *grid; /** * Init the plot. */ void init(); private slots: /** * Show or hide an item. */ void showItem(QwtPlotItem *item, bool on); }; #endif // BASICSTATISTICPLOT_H
Java
UTF-8
856
2.25
2
[]
no_license
package br.org.pti.prjfinancasweb.application.converters; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javax.faces.convert.FacesConverter; /** * * @author sara.so */ public class LocalDateSerializer extends StdSerializer<LocalDate> { public LocalDateSerializer() { super(LocalDate.class); } @Override public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { generator.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); } }
Java
UTF-8
259
2.828125
3
[]
no_license
package com.home.designpattern.designpatterns.Factory; public class Warrior implements Adventurer { @Override public String getType() { System.out.println("我是鬥士!捨我其誰!"); return this.getClass().getSimpleName(); } }
Python
UTF-8
193
3.25
3
[ "MIT" ]
permissive
L = int(input("Digite a largura: ")) A = int(input("Digite a altura: ")) c =1 d = 1 while d <= A: while c <= L: c += 1 print("#", end="") d += 1 print() c = 1
Python
UTF-8
1,365
2.53125
3
[]
no_license
import requests from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from bs4 import BeautifulSoup import time import csv iso_url = "https://sosv.com" link = "/portfolio/notifai" driver_path = "/Users/tyarpornsuksant/Downloads/chromedriver" driver = webdriver.Chrome(driver_path) names = [] founders = [] linkedins = [] websites = [] descriptions = [] locations = [] hrefs = [] company_hrefs = [] iso_com_url = iso_url + link driver.get(iso_com_url) iso_src = driver.page_source iso_soup = BeautifulSoup(iso_src, 'html.parser') try: websites_links_raw = iso_soup.find_all('a',class_="sosv-link-dark mb-3") weblinks = [] for w in websites_links_raw: if w['href'][0] == "h": websites.append(w['href']) except: print("website for " + link + " not found") company_ppl = iso_soup.find('div', class_="company-people col") try: founder = company_ppl.find('p', class_="sosv-text mb-1") striped = founder.text.strip() n = striped.find("\n") striped_striped = striped[0:n] founders.append(striped_striped) except: print("founder for " + link + " not found") try: linkedin = company_ppl.find('a', {'title' : 'LinkedIn'})['href'] linkedins.append(linkedin) except: print("linkedin for " + link + " not found") print(websites) print(founders) print(linkedins)
Python
UTF-8
3,265
2.546875
3
[ "MIT" ]
permissive
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class DataportenAccount(ProviderAccount): def get_avatar_url(self): """ Returns a valid URL to an 128x128 .png photo of the user """ # Documentation for user profile photos can be found here: # https://docs.dataporten.no/docs/oauth-authentication/ base_url = "https://api.dataporten.no/userinfo/v1/user/media/" return base_url + self.account.extra_data["profilephoto"] def to_str(self): """ Returns string representation of a social account. Includes the name of the user. """ dflt = super(DataportenAccount, self).to_str() return "%s (%s)" % ( self.account.extra_data.get("name", ""), dflt, ) class DataportenProvider(OAuth2Provider): id = "dataporten" name = "Dataporten" account_class = DataportenAccount def extract_uid(self, data): """ Returns the primary user identifier, an UUID string See: https://docs.dataporten.no/docs/userid/ """ return data["userid"] def extract_extra_data(self, data): """ Extracts fields from `data` that will be stored in `SocialAccount`'s `extra_data` JSONField. All the necessary data extraction has already been done in the complete_login()-view, so we can just return the data. PS: This is default behaviour, so we did not really need to define this function, but it is included for documentation purposes. Typical return dict: { "userid": "76a7a061-3c55-430d-8ee0-6f82ec42501f", "userid_sec": ["feide:andreas@uninett.no"], "name": "Andreas \u00c5kre Solberg", "email": "andreas.solberg@uninett.no", "profilephoto": "p:a3019954-902f-45a3-b4ee-bca7b48ab507", } """ return data def extract_common_fields(self, data): """ This function extracts information from the /userinfo endpoint which will be consumed by allauth.socialaccount.adapter.populate_user(). Look there to find which key-value pairs that should be saved in the returned dict. Typical return dict: { "userid": "76a7a061-3c55-430d-8ee0-6f82ec42501f", "userid_sec": ["feide:andreas@uninett.no"], "name": "Andreas \u00c5kre Solberg", "email": "andreas.solberg@uninett.no", "profilephoto": "p:a3019954-902f-45a3-b4ee-bca7b48ab507", "username": "andreas", } """ # Make shallow copy to prevent possible mutability issues data = dict(data) # If a Feide username is available, use it. If not, use the "username" # of the email-address for userid in data.get("userid_sec"): usertype, username = userid.split(":") if usertype == "feide": data["username"] = username.split("@")[0] break else: # Only entered if break is not executed above data["username"] = data.get("email").split("@")[0] return data provider_classes = [DataportenProvider]
C++
UTF-8
1,030
2.90625
3
[ "MIT" ]
permissive
#include "lesh.hpp" static Frame make_frame( const Vlist& syms, const Vlist& vals ){ Frame fr; assert( syms.size() == vals.size() ); for ( auto si=syms.begin(), vi=vals.begin(); si!=syms.end(); si++,vi++ ){ fr.insert( make_pair(si->sym,*vi) ); } return fr; } Value Env::lookup_variable_value(const Symbol& sym){ for( auto itr=frames.begin(); itr!=frames.end(); itr++ ){ // list Frame f = *itr; auto found = f.find(sym);//map if( found != f.end() ){ return found->second; } } cout << "UNBIND ERROR" << endl; return Value("ooERRORoo"); } Value Env::define_variable(const Symbol& sym, const Value& val){ for ( auto itr=frames.begin(); itr!=frames.end(); itr++ ){ // list auto found = itr->find(sym);//map if ( found != itr->end() ){ // found !! itr->erase( found ); // unbind if found break; } } frames.begin()->insert( make_pair(sym,val)); return Value("ok"); } void Env::extend_environment( const Vlist& syms, const Vlist& vals){ frames.push_front( make_frame( syms, vals ) ); }
Java
UTF-8
2,133
2.265625
2
[]
no_license
package com.example.contactsreader; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.app.Activity; import android.database.Cursor; import android.view.Menu; import android.widget.Button; import android.widget.LinearLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout layout = (LinearLayout)findViewById(R.id.ll); // Uri mContactUri = ContactsContract.Contacts.CONTENT_URI; // String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.RawContacts.Data.DATA1 }; Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.Contacts.DISPLAY_NAME); while (phones.moveToNext()) { String Name=phones.getString(phones.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); Name += "\n" + phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Button myButton = new Button(this); myButton.setText(Name); layout.addView(myButton); } } public void getNames(){ LinearLayout layout = (LinearLayout)findViewById(R.id.ll); Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.Contacts.DISPLAY_NAME); while (phones.moveToNext()) { String Name=phones.getString(phones.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); Name += "\n" + phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Button myButton = new Button(this); myButton.setText(Name); layout.addView(myButton); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
Java
UTF-8
552
1.796875
2
[]
no_license
package com.senorics.senodata.devicemanagement.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.web.bind.annotation.CrossOrigin; import com.senorics.senodata.devicemanagement.domain.DeviceConfiguration; import io.swagger.annotations.Api; @Api @RepositoryRestResource @CrossOrigin(origins = "http://localhost:3000") public interface DeviceConfigurationRepository extends JpaRepository<DeviceConfiguration, Integer> { }
JavaScript
UTF-8
722
3.640625
4
[]
no_license
// Lancio Dado var nomeUtente = prompt("Ciao! Digita il tuo nome!"); alert("Bene" + nomeUtente + "! Ora Lancia il dado!"); document.getElementById("nome_utente").innerHTML = nomeUtente; // /Lancio Dado // Numero Random Utente var utente = Math.floor((Math.random() * 6) + 1 ); document.getElementById("utente_dado").innerHTML = utente; // /Numero Random Utente // Numero Random Avversario var avversario = Math.floor((Math.random() * 6) + 1 ); document.getElementById("avversario_dado").innerHTML = avversario; // /Numero Random Avversario // Confronto Risultati if (utente <= avversario){ var reDo = "<h1>Riprova!</h1>"; document.getElementById("risulato").innerHTML = reDo; } // /Confronto Risultati
JavaScript
UTF-8
1,333
2.5625
3
[]
no_license
import { login, signup, fetchCurrentUser } from "../services"; export function loginUser(formData, history) { return dispatch => { login(formData).then(res => { if (res.error) { alert( res.error + "\n\n Please check that your username and password are correct!" ); } else { localStorage.setItem("token", res.token); dispatch({ type: "LOGIN_USER", res }); history.push("/dashboard"); } }); }; } export function logoutUser(history) { return dispatch => { localStorage.removeItem("token"); dispatch({ type: "LOGOUT_USER" }); history.push("/"); }; } export function getCurrentUser() { return dispatch => { fetchCurrentUser().then(res => { if (res.errors) { localStorage.removeItem("token"); } else { dispatch({ type: "SET_USER", res }); } }); }; } export function createUser(formData, history) { return dispatch => { signup(formData).then(res => { if (res.errors) { alert(res.errors); } else { if (res.token) { localStorage.setItem("token", res.token); dispatch({ type: "SET_USER", res }); history.push("/dashboard"); } else { dispatch({ type: "SET_USER", res }); } } }); }; }
Java
UTF-8
653
3.078125
3
[]
no_license
package src; /** * Created by dewet on 7/25/17. * A String representation of the motif's pattren . Used in internal comparison only. */ public class pattern { private String patternStr; private int count; public pattern(){ this.count=0; } public String getPattern() { return patternStr; } public void setPattern(String pattern) { this.patternStr = pattern; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String toString(){ return "["+patternStr + " - " +count+"]"; } }
Ruby
UTF-8
876
3.796875
4
[]
no_license
# Bucket Sort works by distributing the elements of an array into a number of # buckets. Each bucket is then sorted individually, either using a different # sorting algorithm, or by recursively applying the bucket sorting algorithm. # Worst Case: O(n^2) # Average Case: Θ(n+k) require_relative './quick_sort' require 'benchmark' def bucket_sort(array) bucket_size = 5 min = array.min max = array.max bucket_count = ((max - min) / bucket_size).floor + 1 buckets = Array.new(bucket_count) {Array.new} array.each do |element| buckets[((element - min) / bucket_size)].push(element) end array.clear (0..buckets.length - 1).each do |x| quick_sort(buckets[x], 0, buckets[x].length - 1) buckets[x].each do |y| array.push(y) end end return array end array = [248, 185, 22, 288, 128, 234, 24, 206, 220] puts bucket_sort(array).inspect
Java
UTF-8
1,436
3.46875
3
[]
no_license
package com.algorithms.ik.dynamicprogramming; public class LongestCommonSubsequence { public static String lcs(String a, String b) { if(a == null || a.trim().length() == 0 || b == null || b.trim().length() == 0) return "-1"; String[][] dp = new String[a.length()+1][b.length()+1]; dp[0][0] = ""; for(int column = 1; column <= b.length(); column++){ dp[0][column] = ""; } for(int row = 1; row <= a.length(); row++){ dp[row][0] = ""; } for(int row=1; row<=a.length(); row++){ for(int column=1; column<=b.length(); column++){ if (a.charAt(row-1) == b.charAt(column-1)) { dp[row][column] = dp[row-1][column-1] + a.charAt(row-1); }else{ if(dp[row-1][column].length() > dp[row][column-1].length()){ dp[row][column] = dp[row-1][column]; }else{ dp[row][column] = dp[row][column-1]; } } } } if(dp[a.length()][b.length()].length() == 0) return "-1"; return dp[a.length()][b.length()]; } public static void main(String[] args){ String text1 = "ABC"; String text2 = "DEF"; LongestCommonSubsequence lcs = new LongestCommonSubsequence(); System.out.println(lcs.lcs(text1, text2)); } }
JavaScript
UTF-8
81,946
2.515625
3
[ "Apache-2.0" ]
permissive
/* Module: DiscordChannels -- Advanced behavior for Discord channels. */ const Module = require('../Module.js'); const moment = require('moment'); const { ChannelType, OverwriteType } = require('discord.js'); const PERM_ADMIN = "administrator"; class ModDiscordChannels extends Module { get optionalParams() { return [ 'datafile', 'tempchannels', //Enable/disable temporary channels 'publictempchannels', //Enable/disable public temporary channels (still requires tempchannels to enable) 'textcategory', //Parent category ID for temporary text channels 'voicecategory', //Parent category ID for temporary voice channels 'opscolor', //Color for the operators roles in temporary channels [R, G, B] 'autodeltext', //Seconds of inactivity until automatic deletion of temporary text channels (null disables) 'autodelvoice', //Seconds of inactivity until automatic deletion of temporary voice channels (null disables) 'defaulttopublic' //Newly created channels default to public instead of private ]; } get requiredEnvironments() { return [ 'Discord' ]; } get requiredModules() { return [ 'Users', 'Commands' ]; } constructor(name) { super('DiscordChannels', name); this._params['tempchannels'] = false; this._params['publictempchannels'] = false; this._params['datafile'] = null; this._params['textcategory'] = null; this._params['voicecategory'] = null; this._params['opscolor'] = [0, 0, 0]; this._params['autodeltext'] = null; this._params['autodelvoice'] = 900; this._params['defaulttopublic'] = false; //{ENV: {CHANNELID: {env, channelid, type, creatorid, accessroleid, opsroleid, key, temp, closed, public, lastused}, ...}, ...} this._data = {}; //IDs of objects being deliberately deleted. this._deleting = {}; //Automatically delete unused temporary channels this._autodeltimer = null; } initialize(opt) { if (!super.initialize(opt)) return false; this._data = this.loadData(null, {}, {quiet: true}); if (this._data === false) return false; let testIsModerator = (envname, userid, channelid) => this.mod('Users').testPermissions(envname, userid, channelid, [PERM_ADMIN]); this._autodeltimer = setInterval(() => { for (let name in opt.envs) { let env = opt.envs[name]; if (env.envName != "Discord") continue; for (let item of this.listAttachedChannels(env)) { if (!this.isChannelTemporary(env, item.channelid)) continue; let data = this.getChannelData(env, item.channelid); if (data.type == "text" && this.param("autodeltext") && this.checkSecsSinceLastUsed(env, item.channelid) > this.param("autodeltext") || data.type == "voice" && this.param("autodelvoice") && this.checkSecsSinceLastUsed(env, item.channelid) > this.param("autodelvoice")) { if (data.type == "voice") { let channel = env.server.channels.cache.get(item.channelid); if (channel && channel.members.size) continue; } this.destroyTempChannel(env, item.channelid) .then(() => { this.log("{" + env.name + "} [" + item.channelid + " " + data.name + "] Temporary channel destroyed for inactivity."); }) .catch((problem) => { this.log("error", "{" + env.name + "} [" + item.channelid + " " + data.name + "] Temporary channel could not be destroyed for inactivity: " + problem); }); } } } }, 60000); //Register callbacks let findEnvFromServer = (guild) => { for (let name in opt.envs) { if (opt.envs[name].server.id == guild.id) { return opt.envs[name]; } } return null; }; let guildMemberRemoveHandler = (member) => { //A server member is gone: If he owned any channels, hand them over to someone else or destroy them let env = findEnvFromServer(member.guild); if (!env) return; for (let item of this.listAttachedChannels(env)) { if (!this.isUserChannelOwner(env, item.channelid, member.id)) continue; let candidates = this.listChannelOps(env, item.channelid).filter((checkuserid) => checkuserid != member.id); if (!candidates.length) { if (this.isChannelTemporary(env, item.channelid)) { this.destroyTempChannel(env, channelid) .then(() => { this.log("{" + env.name + "} [" + item.channelid + "] Temporary channel destroyed when owner departed server without successors."); }) .catch((problem) => { this.log('error', "{" + env.name + "} [" + item.channelid + "] Failed to handle temporary channel destruction when owner departed server without successors (module state may have become corrupted!) Reason: " + problem); }); } else { this.channelDetach(env, item.channelid) .then(() => { this.log("{" + env.name + "} [" + item.channelid + "] Channel detached when owner departed server without successors."); }) .catch((problem) => { this.log('error', "{" + env.name + "} [" + item.channelid + "] Failed to handle permanent channel detachment when owner departed server without successors (module state may have become corrupted!) Reason: " + problem); }); } } else { this._data[env.name][item.channelid].creatorid = candidates[0]; this._data.save(); } } }; let guildMemberUpdateHandler = (oldmember, newmember) => { //A server member's roles may have changed: Prevent channel owners from losing ops let env = findEnvFromServer(oldmember.guild); if (!env) return; let promises = []; for (let item of this.listAttachedChannels(env)) { if (!this.isUserChannelOwner(env, item.channelid, oldmember.id)) continue; let data = this.getChannelData(env, item.channelid); if (oldmember.roles.cache.get(data.opsroleid) && !newmember.roles.cache.get(data.opsroleid)) { let role = env.server.roles.cache.get(data.opsroleid); if (!role) continue; promises.push(newmember.roles.add(role, "Restoring opsrole to attached channel owner")); } } Promise.all(promises) .then(() => { this.log("{" + env.name + "} Restored " + promises.length + " externally removed ops role(s)."); }) .catch((problem) => { this.log('error', "{" + env.name + "} Failed to restore " + promises.length + " externally removed ops role(s) (module state may have become corrupted!) Reason: " + problem); }); }; let roleDeleteHandler = (role) => { //A role was deleted: If it was the ops role of an attached channel, create a new ops role. If it was an access role, clear it. let env = findEnvFromServer(role.guild); if (!env) return; let promises = [], changes = false; for (let item of this.listAttachedChannels(env)) { if (this._deleting[item.channelid]) continue; let data = this._data[env.name][item.channelid]; if (data.accessroleid == role.id) { data.accessroleid = null; this.log("{" + env.name + "} [" + item.channelid + " " + data.name + "] Access role destroyed."); changes = true; } if (data.opsroleid == role.id) { let channel = env.server.channels.cache.get(item.channelid); if (channel) { promises.push( this.doCreateOpsRole(env, item.name) .then((opsrole) => { data.opsroleid = opsrole.id; return this.doAssignRoleToUser(env, opsrole.id, data.creatorid, "Promoting channel owner to operator"); }) .then(() => { this.log("{" + env.name + "} [" + channel.id + "] Handled associated role removal.") }) .catch((problem) => { this.log('error', "{" + env.name + "} [" + channel.id + "] Failed to handle role removal (module state may have become corrupted!) Reason: " + problem); }) ); } else { promises.push(this.doDetachChannel(env, item.channelid)); } } } if (promises.length) { Promise.all(promises) .then(() => { this._data.save(); }) .catch((problem) => { this.log('error', "{" + env.name + "} Failed to handle role removal (module state may have become corrupted!) Reason: " + problem); }); } else if (changes) { this._data.save(); } }; let channelDeleteHandler = (channel) => { //A channel was deleted: If it was attached, clear associated data. let env = findEnvFromServer(channel.guild); if (!env || !this.isChannelAttached(env, channel.id) || this._deleting[channel.id]) return; this._deleting[channelid] = true; this.doDestroyOpsRole(env, this._data[env.name][channel.id].opsroleid) .then(() => this.doDetachChannel(env, channel.id)) .then(() => { this.log("{" + env.name + "} [" + channel.id + "] Cleanup after channel destruction."); delete this._deleting[channelid]; }) .catch((problem) => { this.log('error', "{" + env.name + "} [" + channel.id + "] Failed cleanup after channel destruction (module state may have become corrupted!) Reason: " + problem); delete this._deleting[channelid]; }); }; let voiceStateUpdateHandler = (oldstate, newstate) => { if (!newstate.channelId) return; let env = findEnvFromServer(oldstate.guild); if (!env || newstate.deaf) return; if (!this.isChannelAttached(env, newstate.channelId)) return; this.doTouchChannel(env, newstate.channelId); }; let messageHandler = (env, type, message, authorid, channelid, messageObject) => { if (type != "regular") return; if (!this.isChannelAttached(env, channelid)) return; this.doTouchChannel(env, channelid); } for (let name in opt.envs) { let env = opt.envs[name]; if (env.envName != "Discord") continue; env.on("connected", () => { env.client.on("guildMemberRemove", guildMemberRemoveHandler); env.client.on("guildMemberUpdate", guildMemberUpdateHandler); env.client.on("roleDelete", roleDeleteHandler); env.client.on("channelDelete", channelDeleteHandler); env.client.on("voiceStateUpdate", voiceStateUpdateHandler); env.on("message", messageHandler); }); } //Register commands this.mod('Commands').registerRootDetails(this, 'chan', {description: 'Control channels with advanced behavior.'}); this.mod('Commands').registerCommand(this, 'chan attach', { description: "Attach an existing (non-temporary) channel.", details: ["You can provide the ID of an existing role to be used to regulate access. The role won't be modified."], args: ["channelid", "roleid"], minArgs: 0, environments: ["Discord"], permissions: [PERM_ADMIN] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid = args.channelid; if (!targetchannelid || targetchannelid == "-") { targetchannelid = channelid; } if (!this.checkEnvUsable(env)) { ep.reply("I can't manage channels or roles in this environment."); return true; } if (this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is already attached."); return true; } if (!env.server.channels.cache.get(targetchannelid)) { ep.reply("A channel with this ID could not be found."); return true; } if (args.roleid && !env.server.roles.cache.get(args.roleid)) { ep.reply("A role with this ID could not be found."); return true; } this.channelAttach(env, targetchannelid, args.roleid, userid) .then((channeldata) => { if (!channeldata.public) { return this.userJoinChannel(env, targetchannelid, userid); } }) .then(() => this.channelOp(env, targetchannelid, userid)) .then(() => { ep.reply("Channel attached."); this.log("{" + env.name + "} [" + targetchannelid + "] Attached by " + userid); }) .catch((problem) => { ep.reply("Unable to attach channel."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] Error attaching channel: " + problem); }) return true; }); this.mod('Commands').registerCommand(this, 'chan detach', { description: "Detach any attached channel.", details: ["Once you detach a channel, advanced behavior commands will no longer work with it until it's reattached."], args: ["channelid"], minArgs: 0, environments: ["Discord"], permissions: [PERM_ADMIN] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid = args.channelid; if (!targetchannelid || targetchannelid == "-") { targetchannelid = channelid; } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } this.channelDetach(env, targetchannelid) .then(() => { ep.reply("Channel detached."); this.log("{" + env.name + "} [" + targetchannelid + "] Detached by " + userid); }) .catch((problem) => { ep.reply("Unable to detach channel."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] Error detatching channel: " + problem); }) return true; }); this.mod('Commands').registerCommand(this, 'chan op', { description: "Turn a user into a channel operator.", details: ["Operators can create new operators, invite or kick users and change the channel key."], args: ["channel", "user"], environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } let targetuserid = env.displayNameToId(args.user) || args.user; if (!env.server.members.cache.get(targetuserid)) { ep.reply("User not found."); return true; } this.channelOp(env, targetchannelid, targetuserid) .then(() => { ep.reply("User successfully promoted."); this.log("{" + env.name + "} [" + targetchannelid + "] User " + targetuserid + " opped by " + userid); }) .catch((problem) => { ep.reply("Unable to promote user."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] User " + targetuserid + " could not be opped by " + userid + ": " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'chan deop', { description: "Revoke operator permissions from a user.", args: ["channel", "user"], environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } let ammoderator = testIsModerator(env.name, userid, targetchannelid); if (!this.isUserChannelOp(env, targetchannelid, userid) && !ammoderator) { ep.reply("You are not an operator."); return true; } let targetuserid = env.displayNameToId(args.user) || args.user; if (!env.server.members.cache.get(targetuserid)) { ep.reply("User not found."); return true; } let replacementid = null; if (this.isUserChannelOwner(env, targetchannelid, targetuserid)) { if (ammoderator || userid == targetuserid) { //Creator replacement let candidates = this.listChannelOps(env, targetchannelid).filter((checkuserid) => checkuserid != targetuserid); if (!candidates.length) { ep.reply("You can't demote the channel owner because there is no replacement candidate. Promote someone else first."); return true; } else { replacementid = candidates[0]; } } else { ep.reply("You can't demote the channel owner."); return true; } } this.channelDeop(env, targetchannelid, targetuserid) .then(() => { ep.reply("User successfully demoted."); this.log("{" + env.name + "} [" + targetchannelid + "] User " + targetuserid + " deopped by " + userid); if (replacementid) { this._data[env.name][targetchannelid].creatorid = replacementid; this._data.save(); ep.reply(env.idToDisplayName(replacementid) + " is now the channel owner."); this.log("{" + env.name + "} [" + targetchannelid + "] User " + replacementid + " is now the channel owner."); } }) .catch((problem) => { ep.reply("Unable to demote user."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] User " + targetuserid + " could not be deopped by " + userid + ": " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'chan set key', { description: "Set or clear the channel key.", details: [ "The channel key, if set, is required for joining the channel.", "This command, as well as join CHANNEL KEY, can only be used via private message." ], args: ["channel", "key"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelPublic(env, targetchannelid) && args.key) { ep.reply("This channel is public - users can't be excluded! Try setting it to private."); return true; } if (type != "private" && targetchannelid != channelid && args.key) { if (this.isChannelOpen(env, targetchannelid)) { ep.reply("You can't set the channel key in public! Channel automatically closed. Set the key privately and reopen it using chan open."); this.channelClose(env, targetchannelid); this.log("{" + env.name + "} [" + targetchannelid + "] Channel closed due to public key set attempt."); } else { ep.reply("You can't set the channel key in public! Try again in private, with a different key."); } return true; } this.channelSetKey(env, targetchannelid, args.key); if (args.key) { ep.reply("Channel key successfully set."); this.log("{" + env.name + "} [" + targetchannelid + "] Key successfully set."); } else { ep.reply("Channel key successfully cleared."); this.log("{" + env.name + "} [" + targetchannelid + "] Key successfully cleared."); } return true; }); this.mod('Commands').registerCommand(this, 'chan set public', { description: "Change a channel from private to public.", details: [ "Public channels are always visible to everyone.", "The commands (v)join, part, kick, invite and chan clear users will no longer work on them." ], args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelPublic(env, targetchannelid)) { ep.reply("The channel was already public."); return true; } this.channelSetPublic(env, targetchannelid) .then(() => { ep.reply("The channel is now public."); this.log("{" + env.name + "} [" + targetchannelid + "] Channel set to public."); }) .catch((problem) => { ep.reply("Unable to change channel from private to public."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] Unable to change channel from private to public: " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'chan set private', { description: "Change a channel from public to private.", details: [ "Private channels are subject to access control.", "When they are open, they can be joined with v(join), otherwise the require an invite." ], args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (!this.isChannelPublic(env, targetchannelid)) { ep.reply("The channel was already private."); return true; } this.channelSetPrivate(env, targetchannelid) .then(() => { ep.reply("The channel is now private."); this.log("{" + env.name + "} [" + targetchannelid + "] Channel set to private."); }) .catch((problem) => { ep.reply("Unable to change channel from public to private."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] Unable to change channel from public to private: " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'chan set accessrole', { description: "Set or clear the channel access role.", details: [ "When the channel has an access role, joining the channel adds users to the role.", "Otherwise, users receive independent permission to view the channel.", "If you clear an existing access role, the users currently in it will receive independent permission to view the channel.", "Note: The role itself will never be created or deleted automatically." ], args: ["channel", "role"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelPublic(env, targetchannelid) && args.role) { ep.reply("This channel is public - users can't be excluded! Try setting it to private."); return true; } let roleid = null; if (args.role && args.role != "-") { let role = env.server.roles.cache.find(r => r.name == args.role); if (role) { roleid = role.id; } else if (env.server.roles.cache.get(args.role)) { roleid = args.role; } else { ep.reply("Role not found."); return true; } } let prevaccessroleid = this.getChannelData(env, targetchannelid).accessroleid; this.channelSetAccessRole(env, targetchannelid, roleid); let promise; if (prevaccessroleid && !roleid) { //Unsetting access role: Give individual access permission to role users let changeusers = []; let channel = env.server.channels.cache.get(targetchannelid); let accessrole = env.server.roles.cache.get(prevaccessroleid); if (channel && accessrole) { for (let rolemember of accessrole.members.values()) { changeusers.push(channel.permissionOverwrites.create(rolemember, {ViewChannel: true}, {reason: "Propagating permission to access role members on removal"})); } } promise = Promise.all(changeusers); } else { promise = Promise.resolve(); } promise .then(() => { if (roleid) { ep.reply("Access role successfully set."); this.log("{" + env.name + "} [" + targetchannelid + "] User " + userid + (roleid ? "set access role to " + roleid : "cleared access role") + "."); } else { ep.reply("Access role successfully cleared."); } }) .catch((problem) => { ep.reply("Problem setting access role."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] Problem when user " + userid + " tried to " + (roleid ? "set access role to " + roleid : "clear access role") + ": " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'chan set owner', { description: "Transfer channel ownership to a specific user.", details: [ "The channel owner (initially the channel creator) is responsible for the channel and can use clear commands.", "The owner must always be a channel operator.", ], args: ["channel", "newowner"], environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOwner(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("This command can only be used by the channel owner."); return true; } let targetuserid = env.displayNameToId(args.newowner) || args.newowner; if (!env.server.members.cache.get(targetuserid)) { ep.reply("User not found."); return true; } if (!this.isUserChannelOp(env, targetchannelid, targetuserid)) { ep.reply("This user is not a channel operator.") return true; } this.channelSetOwner(env, targetchannelid, targetuserid); ep.reply("Owner successfully set."); this.log("{" + env.name + "} [" + targetchannelid + "] Owner set to: " + targetuserid + " (by " + userid + ")."); return true; }); this.mod('Commands').registerCommand(this, 'chan open', { description: "Open a previously closed channel.", details: ["Open channels can be joined using the join/vjoin command."], args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelOpen(env, targetchannelid)) { ep.reply("The channel was already open."); return true; } this.channelOpen(env, targetchannelid); ep.reply("The channel is now open."); this.log("{" + env.name + "} [" + targetchannelid + "] Channel opened."); return true; }); this.mod('Commands').registerCommand(this, 'chan close', { description: "Close a channel.", details: ["Closed channels can only be joined through an operator's use of the invite command."], args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelPublic(env, targetchannelid)) { ep.reply("This channel is public - users can't be excluded! Try setting it to private."); return true; } if (!this.isChannelOpen(env, targetchannelid)) { ep.reply("The channel was already closed."); return true; } this.channelClose(env, targetchannelid); ep.reply("The channel is now closed."); this.log("{" + env.name + "} [" + targetchannelid + "] Channel closed."); return true; }); this.mod('Commands').registerCommand(this, 'chan info', { description: "Show information about an attached channel.", args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } let data = this.getChannelData(env, targetchannelid); let infoblock = "```\n"; infoblock += `Environment: ${data.env}\n`; infoblock += `Channel: ${env.channelIdToDisplayName(data.channelid)}\n`; infoblock += `Owner: ${env.idToDisplayName(data.creatorid)}\n`; infoblock += `Operators: @${env.roleIdToDisplayName(data.opsroleid)} (${this.listChannelOps(env, data.channelid).length})\n`; if (!data.public) { infoblock += `Access: ${data.accessroleid ? "@" + env.roleIdToDisplayName(data.accessroleid) : "Individual"}\n`; } infoblock += `Last used: ${moment.unix(data.lastused).fromNow()}\n`; infoblock += `\n`; if (data.temp) infoblock += "This is a temporary channel.\n"; if (data.key) infoblock += "This channel has a key.\n"; if (data.public) { infoblock += "This channel is public (anyone can use it).\n"; } else if (data.closed) { infoblock += "This channel is closed (invite only).\n"; } infoblock += "```"; ep.reply(infoblock); return true; }); this.mod('Commands').registerCommand(this, 'chan clear users', { description: "Remove all channel users, excluding ops.", args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOwner(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("This command can only be used by the channel owner."); return true; } if (this.isChannelPublic(env, targetchannelid)) { ep.reply("This channel is public - users can't be excluded! Try setting it to private."); return true; } let data = this.getChannelData(env, targetchannelid); let kicks = []; for (let channeluserid of this.listChannelUsers(env, targetchannelid)) { if (this.isUserChannelOp(env, targetchannelid, channeluserid)) continue; kicks.push(this.userPartChannel(env, targetchannelid, channeluserid)); } if (!kicks.length) { ep.reply("There is no one to kick!"); return true; } Promise.all(kicks) .then(() => { ep.reply("Kicked " + kicks.length + " user" + (kicks.length != 1 ? "s" : "")); this.log("{" + env.name + "} [" + targetchannelid + " " + data.name + "] Clear users issued by owner " + userid + " affecting " + kicks.length + " user(s)."); }) .catch((problem) => { ep.reply("Problem clearing users."); this.log("warn", "{" + env.name + "} [" + targetchannelid + " " + data.name + "] Clear users issued by owner " + userid + " failed due to: " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'chan clear ops', { description: "Demote all channel ops, except for the owner.", args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOwner(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("This command can only be used by the channel owner."); return true; } let deops = []; for (let opuserid of this.listChannelOps(env, targetchannelid)) { if (this.isUserChannelOwner(env, targetchannelid, opuserid)) continue; deops.push(this.channelDeop(env, targetchannelid, opuserid)); } if (!deops.length) { ep.reply("There is no one to demote!"); return true; } Promise.all(deops) .then(() => { ep.reply("Demoted " + deops.length + " operator" + (deops.length != 1 ? "s" : "")); this.log("{" + env.name + "} [" + targetchannelid + "] Clear ops issued by owner " + userid + " affecting " + deops.length + " user(s)."); }) .catch((problem) => { ep.reply("Problem demoting ops."); this.log("warn", "{" + env.name + "} [" + targetchannelid + "] Clear ops issued by owner " + userid + " failed due to: " + problem); }); return true; }); let joinChannelHandler = (createTempChannelCallback, reqtype, createpublic) => (env, type, userid, channelid, command, args, handle, ep) => { if (!this.checkEnvUsable(env)) { ep.reply("I can't manage channels or roles in this environment."); return true; } let targetchannelid, channel = env.server.channels.cache.filter(channel => channel.type == reqtype).find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } let getchannel = null; if (targetchannelid) { if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } else if (this.isChannelPublic(env, targetchannelid)) { ep.reply("This channel is public - you always have access to it!"); return true; } else if (!this.isChannelOpen(env, targetchannelid)) { ep.reply("This channel is not open for joining."); return true; } else if (type != "private" && args.key && targetchannelid != channelid) { ep.reply("You can't use the channel key in public! Channel automatically closed. An operator must change the key privately and reopen it using chan open."); this.channelClose(env, targetchannelid); this.log("{" + env.name + "} [" + targetchannelid + "] Channel closed due to public key usage attempt in " + channelid + " by " + userid + "."); return true; } else { let data = this.getChannelData(env, targetchannelid); if (data.key && !this.isUserChannelOwner(userid) && data.key != args.key) { ep.reply("Incorrect key."); this.log("{" + env.name + "} [" + targetchannelid + "] Channel join attempt with incorrect key in " + channelid + " by " + userid + "."); return true; } getchannel = Promise.resolve(data); } } else if (!this.param("tempchannels")) { ep.reply("Channel not found."); return true; } else if (createpublic && !this.param('publictempchannels')) { ep.reply("The creation of public temporary channels is disabled. Try a private channel."); return true; } else if (type != "private" && args.key) { ep.reply("You can't set the channel key in public! Try again in private, with a different key."); return true; } else { getchannel = createTempChannelCallback(env, args.channel, userid, createpublic); if (args.key && !createpublic) { getchannel.then((data) => { this.channelSetKey(env, data.channelid, args.key); }); } } getchannel .then((data) => this.userJoinChannel(env, data.channelid, userid)) .then((result) => { this.log("{" + env.name + "} [" + result.channeldata.channelid + "] join: " + result.userid); }) .catch((problem) => { ep.reply("Failed to join channel."); this.log("warn", "{" + env.name + "} User " + userid + " could not join channel " + args.channel + " (" + targetchannelid + "): " + problem); }); return true; }; this.mod('Commands').registerCommand(this, 'join', { description: "Join an attached, open text channel or create a new temporary text channel.", details: ["This will give you permission to use the requested channel."], args: ["channel", "key"], minArgs: 1, environments: ["Discord"] }, joinChannelHandler(this.createTempTextChannel.bind(this), ChannelType.GuildText, this.param('defaulttopublic'))); this.mod('Commands').registerCommand(this, 'vjoin', { description: "Join an attached, open voice channel or create a new temporary voice channel.", details: ["This will give you permission to use the requested channel."], args: ["channel", "key"], minArgs: 1, environments: ["Discord"] }, joinChannelHandler(this.createTempVoiceChannel.bind(this), ChannelType.GuildVoice, this.param('defaulttopublic'))); this.mod('Commands').registerCommand(this, 'join public', { description: "Join an attached, open text channel or create a new temporary text channel.", details: [ "This will give you permission to use the requested channel.", "If the channel doesn't exist, it will be created as a public channel (visible to everyone)." ], args: ["channel"], minArgs: 1, environments: ["Discord"] }, joinChannelHandler(this.createTempTextChannel.bind(this), ChannelType.GuildText, true)); this.mod('Commands').registerCommand(this, 'vjoin public', { description: "Join an attached, open voice channel or create a new temporary voice channel.", details: [ "This will give you permission to use the requested channel.", "If the channel doesn't exist, it will be created as a public channel (visible to everyone)." ], args: ["channel"], minArgs: 1, environments: ["Discord"] }, joinChannelHandler(this.createTempVoiceChannel.bind(this), ChannelType.GuildVoice, true)); this.mod('Commands').registerCommand(this, 'join private', { description: "Join an attached, open text channel or create a new temporary text channel.", details: [ "This will give you permission to use the requested channel.", "If the channel doesn't exist, it will be created as a private channel (with access control)." ], args: ["channel", "key"], minArgs: 1, environments: ["Discord"] }, joinChannelHandler(this.createTempTextChannel.bind(this), ChannelType.GuildText, false)); this.mod('Commands').registerCommand(this, 'vjoin private', { description: "Join an attached, open voice channel or create a new temporary voice channel.", details: [ "This will give you permission to use the requested channel.", "If the channel doesn't exist, it will be created as a private channel (with access control)." ], args: ["channel", "key"], minArgs: 1, environments: ["Discord"] }, joinChannelHandler(this.createTempVoiceChannel.bind(this), ChannelType.GuildVoice, false)); this.mod('Commands').registerCommand(this, 'part', { description: "Leave an attached text channel.", details: [ "This will remove your permission to use the channel.", "If the channel is temporary, it will be destroyed when its last member leaves." ], args: ["channel"], minArgs: 0, environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (this.isChannelPublic(env, targetchannelid)) { ep.reply("This channel is public - it's always visible to everyone."); return true; } let replacementid = null; let channelusers = this.listChannelUsers(env, targetchannelid).filter((checkuserid) => checkuserid != userid); if (!channelusers.length) { //The last user leaves the channel if (this.isChannelTemporary(env, targetchannelid)) { this.destroyTempChannel(env, targetchannelid) .then(() => { this.log("{" + env.name + "} [" + targetchannelid + "] part: " + userid + " (temporary channel destroyed)"); }) .catch((problem) => { ep.reply("Could not destroy temporary channel."); this.log("warn", "{" + env.name + "} User " + userid + " could not destroy temporary channel " + args.channel + " (" + targetchannelid + "): " + problem); }); return true; } } else if (this.isUserChannelOwner(env, targetchannelid, userid)) { //Creator replacement let candidates = this.listChannelOps(env, targetchannelid).filter((checkuserid) => checkuserid != userid); if (candidates.length) { replacementid = candidates[0]; } else { replacementid = channelusers[0]; } } this.userPartChannel(env, targetchannelid, userid) .then((result) => { this.log("{" + env.name + "} [" + result.channeldata.channelid + "] part: " + result.userid); if (replacementid) { this._data[env.name][targetchannelid].creatorid = replacementid; this._data.save(); ep.reply(env.idToDisplayName(replacementid) + " is now the channel owner."); this.log("{" + env.name + "} [" + result.channeldata.channelid + "] user " + replacementid + " is now the channel owner."); } }) .catch((problem) => { ep.reply("Failed to part channel."); this.log("warn", "{" + env.name + "} User " + userid + " could not part channel " + args.channel + " (" + targetchannelid + "): " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'invite', { description: "Invite a user to an attached channel.", args: ["channel", "user"], environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelPublic(env, targetchannelid)) { ep.reply("This channel is public - users always have access to it!"); return true; } let targetuserid = env.displayNameToId(args.user) || args.user; if (!env.server.members.cache.get(targetuserid)) { ep.reply("User not found."); return true; } if (this.isUserChannelMember(env, targetchannelid, targetuserid)) { ep.reply("The user is already in the channel."); return true; } this.userJoinChannel(env, targetchannelid, targetuserid) .then((result) => { ep.reply("User " + env.idToDisplayName(targetuserid) + " has joined the channel."); this.log("{" + env.name + "} [" + result.channeldata.channelid + "] Join: " + result.userid + " (invite by " + userid + ")"); }) .catch((problem) => { ep.reply("Failed to invite to the channel."); this.log("warn", "{" + env.name + "} User " + userid + " could not join channel " + args.channel + " (" + targetchannelid + "): " + problem); }); return true; }); this.mod('Commands').registerCommand(this, 'kick', { description: "Remove a user from an attached channel.", details: [ "This will remove the user's permission to use the channel. If the user has a custom role that grants channel access, that role will not be removed.", "Operators can't be kicked." ], args: ["channel", "user"], environments: ["Discord"] }, (env, type, userid, channelid, command, args, handle, ep) => { let targetchannelid; if (!args.channel || args.channel == "-") { targetchannelid = channelid; } else { let channel = env.server.channels.cache.find(c => c.name == args.channel); if (channel) { targetchannelid = channel.id; } else if (env.server.channels.cache.get(args.channel)) { targetchannelid = args.channel; } else { ep.reply("Channel not found."); return true; } } if (!this.isChannelAttached(env, targetchannelid)) { ep.reply("This channel is not attached."); return true; } if (!this.isUserChannelOp(env, targetchannelid, userid) && !testIsModerator(env.name, userid, targetchannelid)) { ep.reply("You are not an operator."); return true; } if (this.isChannelPublic(env, targetchannelid)) { ep.reply("This channel is public - users can't be excluded! Try setting it to private."); return true; } let targetuserid = env.displayNameToId(args.user) || args.user; if (!env.server.members.cache.get(targetuserid)) { ep.reply("User not found."); return true; } if (this.isUserChannelOp(env, targetchannelid, targetuserid)) { ep.reply("This user is an operator."); return true; } this.userPartChannel(env, targetchannelid, targetuserid) .then((result) => { ep.reply("User " + env.idToDisplayName(targetuserid) + " was kicked from the channel."); this.log("{" + env.name + "} [" + result.channeldata.channelid + "] Part: " + result.userid + "(kick by " + userid + ")"); }) .catch((problem) => { ep.reply("Failed to kick from the channel."); this.log("warn", "{" + env.name + "} User " + userid + " could not part channel " + args.channel + " (" + targetchannelid + "): " + problem); }); return true; }); return true; } // # Module code below this line # //API methods: These methods can be used from extension modules. //Many of these methods return promises; don't forget to catch rejections. isChannelAttached(env, channelid) { return this._data[env.name] && this._data[env.name][channelid]; } isChannelOpen(env, channelid) { return this.isChannelAttached(env, channelid) && !this._data[env.name][channelid].closed; } isChannelTemporary(env, channelid) { return this.isChannelAttached(env, channelid) && this._data[env.name][channelid].temp; } isChannelPublic(env, channelid) { return this.isChannelAttached(env, channelid) && this._data[env.name][channelid].public; } isUserChannelOwner(env, channelid, userid) { if (!this.isChannelAttached(env, channelid)) return false; return userid == this._data[env.name][channelid].creatorid; } isUserChannelOp(env, channelid, userid) { if (!this.isChannelAttached(env, channelid)) return false; let member = env.server.members.cache.get(userid); if (!member) return false; return !!member.roles.cache.get(this._data[env.name][channelid].opsroleid); } isUserChannelMember(env, channelid, userid) { if (!this.isChannelAttached(env, channelid)) return false; let data = this._data[env.name][channelid]; if (data.accessroleid) { let role = env.server.roles.cache.get(data.accessroleid); if (!role) return false; return !!role.members.get(userid); } else { let channel = env.server.channels.cache.get(channelid); let member = env.server.members.cache.get(userid); return !!channel.permissionOverwrites.cache.filter((po) => po.id == member.id && po.type == OverwriteType.Member && po.allow.has("ViewChannel")).size; } } listAttachedChannels(env) { if (env.envName != "Discord") return []; if (!this._data[env.name]) return []; let result = []; for (let channelid in this._data[env.name]) { let channel = env.server.channels.cache.get(channelid); result.push({channelid: channelid, name: (channel ? channel.name : channelid)}); } result.sort((a, b) => a.name.localeCompare(b.name)); return result; } getChannelData(env, channelid) { if (!this.isChannelAttached(env, channelid)) return false; let data = Object.assign({}, this._data[env.name][channelid]); let channel = env.server.channels.cache.get(channelid); if (channel) data.name = channel.name; return data; } listChannelOps(env, channelid) { let data = this.getChannelData(env, channelid); if (!data) return false; let role = env.server.roles.cache.get(data.opsroleid); if (!role) return false; let results = []; for (let member of role.members.values()) { results.push(member.id); } return results; } listChannelUsers(env, channelid) { let data = this.getChannelData(env, channelid); if (!data) return false; let results = []; if (data.accessroleid) { let role = env.server.roles.cache.get(data.accessroleid); if (!role) return false; for (let member of role.members.values()) { if (member.id == env.server.members.me.id) continue; results.push(member.id); } } else { let channel = env.server.channels.cache.get(channelid); for (let member of env.server.members.cache.values()) { if (member.id == env.server.members.me.id) continue; if (!channel.permissionOverwrites.cache.filter((po) => po.id == member.id && po.type == OverwriteType.Member && po.allow.has("ViewChannel")).size) continue; results.push(member.id); } } return results; } async channelAttach(env, channelid, roleid, creatorid) { if (this.isChannelAttached(env, channelid)) { this._data[env.name][channelid].accessroleid = (roleid ? roleid : null); this._data.save(); return this._data[env.name][channelid]; } let channel = env.server.channels.cache.get(channelid); if (!channel) throw "Channel not found."; let opsrole = await this.doCreateOpsRole(env, channel.name); await this.doAssignRoleToUser(env, opsrole.id, creatorid, "Promoting channel owner to operator"); await channel.permissionOverwrites.create(env.server.members.me.id, {ViewChannel: true}, {reason: "Attaching channel"}); if (channel.type == ChannelType.GuildText) { await channel.permissionOverwrites.create(opsrole, {ViewChannel: true, ManageChannels: true, ManageMessages: true}, {reason: "Attaching channel (opsrole perms)"}); } if (channel.type == ChannelType.GuildVoice) { await channel.permissionOverwrites.create(opsrole, {ViewChannel: true, ManageChannels: true, MuteMembers: true, DeafenMembers: true}, {reason: "Attaching channel (opsrole perms)"}); } let ispublic = !channel.permissionOverwrites.cache.filter((po) => po.id == env.server.id && po.type == OverwriteType.Role && po.deny.has("ViewChannel")).size; return this.doAttachChannel(env, channelid, channel.type, false, opsrole, roleid, creatorid, ispublic); } async channelDetach(env, channelid) { if (!this.isChannelAttached(env, channelid)) return false; this._deleting[channelid] = true; await this.doDestroyOpsRole(env, this._data[env.name][channelid].opsroleid); this.doDetachChannel(env, channelid); delete this._deleting[channelid]; return true; } channelOp(env, channelid, userid) { if (!env.server.members.cache.get(userid)) return Promise.reject("User not found."); if (!this.isChannelAttached(env, channelid)) return Promise.reject("Channel not attached."); let roleid = this._data[env.name][channelid].opsroleid; if (env.server.members.cache.get(userid).roles.cache.get(roleid)) return Promise.resolve(); let role = env.server.roles.cache.get(roleid); if (!role) return Promise.reject("Role not found."); return env.server.members.cache.get(userid).roles.add(role, "Turning user into channel op"); } channelDeop(env, channelid, userid) { if (!env.server.members.cache.get(userid)) return Promise.reject("User not found."); if (!this.isChannelAttached(env, channelid)) return Promise.reject("Channel not attached."); let roleid = this._data[env.name][channelid].opsroleid; if (!env.server.members.cache.get(userid).roles.cache.get(roleid)) return Promise.resolve(); let role = env.server.roles.cache.get(roleid); if (!role) return Promise.reject("Role not found."); return env.server.members.cache.get(userid).roles.remove(role, "Demoting user from channel op"); } channelSetKey(env, channelid, key) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; this._data[env.name][channelid].key = (key ? key : null); this._data.save(); return true; } channelOpen(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; this._data[env.name][channelid].closed = false; this._data.save(); return true; } channelClose(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; this._data[env.name][channelid].closed = true; this._data.save(); return true; } async channelSetPublic(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) throw "Channel not attached."; let channel = env.server.channels.cache.get(channelid); if (!channel) throw "Channel not found."; await channel.permissionOverwrites.create(env.server.id, {ViewChannel: true}, {reason: "Changing channel to public"}); this._data[env.name][channelid].public = true; this._data.save(); return true; } async channelSetPrivate(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) throw "Channel not attached."; let channel = env.server.channels.cache.get(channelid); if (!channel) throw "Channel not found."; await channel.permissionOverwrites.create(env.server.id, {ViewChannel: false}, {reason: "Changing channel to private"}); this._data[env.name][channelid].public = false; this._data.save(); return true; } channelSetAccessRole(env, channelid, roleid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; if (roleid && !env.server.roles.cache.get(roleid)) return false; this._data[env.name][channelid].accessroleid = (roleid ? roleid : null); this._data.save(); return true; } channelSetOwner(env, channelid, userid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; if (!env.server.members.cache.get(userid)) return false; this._data[env.name][channelid].creatorid = userid; this._data.save(); return true; } userJoinChannel(env, channelid, userid) { if (!env.server.members.cache.get(userid)) return Promise.reject("User not found."); if (!this.isChannelAttached(env, channelid)) return Promise.reject("Channel not attached."); let channeldata = this._data[env.name][channelid]; if (channeldata.accessroleid) { if (env.server.members.cache.get(userid).roles.cache.get(channeldata.accessroleid)) return Promise.resolve({channeldata: channeldata, userid: userid}); return env.server.members.cache.get(userid).roles.add(channeldata.accessroleid, "Granting channel access to user") .then(() => ({channeldata: channeldata, userid: userid})); } else { let channel = env.server.channels.cache.get(channelid); if (!channel) return Promise.reject("Channel not found."); if (channel.permissionOverwrites.cache.filter((po) => po.id == userid && po.type == OverwriteType.Member && po.allow.has("ViewChannel")).get(userid)) { return Promise.resolve({channeldata: channeldata, userid: userid}); } return channel.permissionOverwrites.create(env.server.members.cache.get(userid), {ViewChannel: true}, {reason: "Granting channel access to user"}) .then(() => ({channeldata: channeldata, userid: userid})); } } async userPartChannel(env, channelid, userid) { if (!env.server.members.cache.get(userid)) throw "User not found."; if (!this.isChannelAttached(env, channelid)) throw "Channel not attached."; let channeldata = this._data[env.name][channelid]; if (this.isUserChannelOp(env, channelid, userid)) { await this.channelDeop(env, channelid, userid); } if (channeldata.accessroleid) { if (!env.server.members.cache.get(userid).roles.cache.get(channeldata.accessroleid)) return {channeldata: channeldata, userid: userid}; return env.server.members.cache.get(userid).roles.remove(channeldata.accessroleid, "Revoking channel access from user") .then(() => ({channeldata: channeldata, userid: userid})); } else { let channel = env.server.channels.cache.get(channelid); if (!channel) throw "Channel not found."; let joinpermission = channel.permissionOverwrites.cache.filter((po) => po.id == userid && po.type == OverwriteType.Member && po.allow.has("ViewChannel")).get(userid); if (joinpermission) return joinpermission.delete("Revoking channel access from user").then(() => ({channeldata: channeldata, userid: userid})); return {channeldata: channeldata, userid: userid}; } } async createTempTextChannel(env, name, creatorid, ispublic) { if (env.envName != "Discord") throw "Invalid environment type."; let role = await this.doCreateOpsRole(env, name); await this.doAssignRoleToUser(env, role.id, creatorid, "Promoting channel owner to operator"); let perms = [{id: env.server.members.me.id, allow: ['ViewChannel']}]; if (ispublic) { perms.push({id: env.server.id, allow: ['ViewChannel']}); } else { perms.push({id: env.server.id, deny: ['ViewChannel']}); } perms.push({id: role.id, allow: ['ViewChannel', 'ManageChannels', 'ManageMessages']}); let channel = await env.server.channels.create({name: name, type: ChannelType.GuildText, permissionOverwrites: perms, reason: "Temporary text channel"}); if (this.param("textcategory")) { let category = env.server.channels.cache.get(this.param("textcategory")); if (category) { await channel.setParent(category, "Setting category of temporary text channel"); } } return this.doAttachChannel(env, channel.id, channel.type, true, role, null, creatorid, ispublic); } async createTempVoiceChannel(env, name, creatorid, ispublic) { if (env.envName != "Discord") throw "Invalid environment type."; let role = await this.doCreateOpsRole(env, name); await this.doAssignRoleToUser(env, role.id, creatorid, "Promoting channel owner to operator"); let perms = [{id: env.server.members.me.id, allow: ['ViewChannel']}]; if (ispublic) { perms.push({id: env.server.id, allow: ['ViewChannel']}); } else { perms.push({id: env.server.id, deny: ['ViewChannel']}); } perms.push({id: role.id, allow: ['ViewChannel', 'ManageChannels', 'MuteMembers', 'DeafenMembers']}); let channel = await env.server.channels.create({name: name, type: ChannelType.GuildVoice, permissionOverwrites: perms, reason: "Temporary voice channel"}); if (this.param("voicecategory")) { let category = env.server.channels.cache.get(this.param("voicecategory")); if (category) { await channel.setParent(category, "Setting category of temporary voice channel"); } } return this.doAttachChannel(env, channel.id, channel.type, true, role, null, creatorid, ispublic); } async destroyTempChannel(env, channelid) { if (env.envName != "Discord") throw "Invalid environment type."; if (!this.isChannelAttached(env, channelid)) throw "Channel not attached."; let data = this.getChannelData(env, channelid); if (!data.temp) throw "Channel not temporary."; this._deleting[channelid] = true; let channel = env.server.channels.cache.get(channelid); if (channel) await channel.delete("Deleting temporary channel"); await this.doDestroyOpsRole(env, data.opsroleid); this.doDetachChannel(env, channelid); delete this._deleting[channelid]; return true; } //Auxiliary methods: Signature might change, don't call from other modules. doAttachChannel(env, channelid, type, temp, opsrole, accessroleid, creatorid, ispublic) { if (!this._data[env.name]) this._data[env.name] = {}; if (this._data[env.name][channelid]) return false; let datatype = "text"; if (type == ChannelType.GuildVoice || type == ChannelType.GuildStageVoice) { datatype = "voice"; } this._data[env.name][channelid] = { env: env.name, channelid: channelid, type: datatype, creatorid: creatorid, accessroleid: (accessroleid ? accessroleid : null), opsroleid: opsrole.id, key: null, temp: !!temp, closed: false, public: !!ispublic, lastused: moment().unix() }; this._data.save(); return this._data[env.name][channelid]; } doDetachChannel(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; delete this._data[env.name][channelid]; this._data.save(); return true; } doCreateOpsRole(env, name) { return env.server.createRole({name: name + ":ops", color: this.param("opscolor"), permissions: [], mentionable: false}, "Ops role for temporary voice channel '" + name + "'"); } doDestroyOpsRole(env, roleid) { let role = env.server.roles.cache.get(roleid); if (!role || !role.name.match(/:ops$/)) return Promise.reject("Role not found or not ops role."); return role.delete("Deleting ops role"); } doAssignRoleToUser(env, roleid, userid, reason) { if (!env.server.members.cache.get(userid)) return Promise.reject("User not found."); if (env.server.members.cache.get(userid).roles.cache.get(roleid)) return Promise.resolve(); return env.server.members.cache.get(userid).roles.add(roleid, reason); } doTouchChannel(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; this._data[env.name][channelid].lastused = moment().unix(); this._data.save(); return true; } checkEnvUsable(env) { return env.server.members.me.permissions.has("MANAGE_CHANNELS") && env.server.members.me.permissions.has("MANAGE_ROLES"); } checkSecsSinceLastUsed(env, channelid) { if (!this._data[env.name] || !this._data[env.name][channelid]) return false; return moment().unix() - this._data[env.name][channelid].lastused; } } module.exports = ModDiscordChannels;
Python
UTF-8
1,615
2.890625
3
[]
no_license
## late_fusion2_model Demo with Streamlit App ### requirements: ## pip install streamlit ### run command: ## streamlit run demo.py import streamlit as st import pandas as pd import numpy as np from PIL import Image,ImageOps import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.applications.mobilenet import preprocess_input ## Surpress warning st.set_option('deprecation.showfileUploaderEncoding', False) ## Upload image interface st.title("Image Emotion Model") uploaded_file = st.file_uploader("Choose an image...", type=["jpg"]) ## Load pretrained model emotion_model = tf.keras.models.load_model('./pretrained_models/late_fusion2_model.h5') ## After image uploaded if uploaded_file is not None: ## Image preprocessing image = Image.open(uploaded_file) size = (224,224) im = ImageOps.fit(image, size, Image.ANTIALIAS) im = img_to_array(im) im = im.reshape((1, im.shape[0], im.shape[1], im.shape[2])) im = preprocess_input(im) ## Predictions preds = emotion_model.predict([im,im]) predicted_index=np.argmax(preds,axis=1)[0] labels = ['amusement', 'anger', 'awe', 'contentment', 'disgust','excitement', 'fear', 'sadness'] predicted_classes=str(labels[predicted_index]) ## Display st.image(image,width=400,height=400) st.subheader('Predicted Emotion: '+predicted_classes) st.subheader('Emotion Distribution:') st.write(pd.DataFrame({'emotion_classes':labels\ ,'predicted_probability':preds[0]}))
Java
UTF-8
1,343
2.1875
2
[]
no_license
package pl.coderslab.charity.web.users.donations.details; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import pl.coderslab.charity.services.DonationService; import java.time.format.DateTimeFormatter; @Controller @RequestMapping("/users/donations/details") public class DonationDetailsController { private DonationService donationService; public DonationDetailsController(DonationService donationService) { this.donationService = donationService; } @GetMapping public String userDonationsPage(@RequestParam Long donationId, Model model) { model.addAttribute("donation", donationService.getDonationById(donationId)); model.addAttribute("formater", DateTimeFormatter.ofPattern("yyyy-MM-dd")); return "donation"; } @PostMapping public String donationChangeStatus(@RequestParam Long elementId, Model model) { System.out.println(elementId); donationService.changeStatusToReceived(elementId); return "redirect:/users/donations/details?donationId=" + elementId; } }
C
UTF-8
14,440
2.71875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: fast_march.h * Author: User * * Created on November 25, 2016, 6:53 PM */ #ifndef FAST_MARCH_H #define FAST_MARCH_H #include "heap_functions.h" void interface_nodes(double ***phi, double **int_cells) { for(int i=1; i<xelem-1; i++) { for(int j=1; j<yelem-1; j++) { if(phi[i][j][0]* phi[i+1][j][0] < 0.0) { /*Check if the cell i,j is already in list*/ if(int_cells.size() > 1) { bool inlist = false; for(int k=int_cells.size()-1; k > 0; k--) { if(i == int_cells[k][0] && j == int_cells[k][1]) { inlist = true; } } if(inlist == false) { int_cells.resize(int_cells.size() + 1); int_cells[int_cells.size()-1].resize(2); int_cells[int_cells.size()-1][0] = i; int_cells[int_cells.size()-1][1] = j; } } else //If list is empty just add the cell to list { int_cells.resize(int_cells.size() + 1); int_cells[int_cells.size()-1].resize(2); int_cells[int_cells.size()-1][0] = i; int_cells[int_cells.size()-1][1] = j; } /*Check if the cell i+1,j is already in list*/ bool inlist = false; for(int k=int_cells.size()-1; k > 0; k--) { if(i+1 == int_cells[k][0] && j == int_cells[k][1]) { inlist = true; } } if(inlist == false) { int_cells.resize(int_cells.size() + 1); int_cells[int_cells.size()-1].resize(2); int_cells[int_cells.size()-1][0] = i+1; int_cells[int_cells.size()-1][1] = j; } } /*Now for the j direction*/ if(phi[i][j][0]* phi[i][j+1][0] < 0.0) { /*Check if the cell i,j is already in list*/ if(int_cells.size() > 1) { bool inlist = false; for(int k=int_cells.size()-1; k > 0; k--) { if(i == int_cells[k][0] && j == int_cells[k][1]) { inlist = true; } } if(inlist == false) { int_cells.resize(int_cells.size() + 1); int_cells[int_cells.size()-1].resize(2); int_cells[int_cells.size()-1][0] = i; int_cells[int_cells.size()-1][1] = j; } } else //If list is empty just add the cell to list { int_cells.resize(int_cells.size() + 1); int_cells[int_cells.size()-1].resize(2); int_cells[int_cells.size()-1][0] = i; int_cells[int_cells.size()-1][1] = j; } /*Check if the cell i+1,j is already in list*/ bool inlist = false; for(int k=int_cells.size()-1; k > 0; k--) { if(i == int_cells[k][0] && j+1 == int_cells[k][1]) { inlist = true; } } if(inlist == false) { int_cells.resize(int_cells.size() + 1); int_cells[int_cells.size()-1].resize(2); int_cells[int_cells.size()-1][0] = i; int_cells[int_cells.size()-1][1] = j+1; } } } } } void find_ne(vector<int> &ne_i, vector <int> &ne_j, int i, int j) { /*Left and right neighbours*/ if(i == xelem-2 && x_bound == 3) { ne_i[0] = 1; ne_j[0] = j; ne_i[2] = i-1; ne_j[2] = j; } else if(i == 1 && x_bound == 3) { ne_i[0] = i+1; ne_j[0] = j; ne_i[2] = xelem-2; ne_j[2] = j; } else if(i == xelem-2 && x_bound !=3) { ne_i[0] = 10000; ne_j[0] = 10000; ne_i[2] = i-1; ne_j[2] = j; } else if(i == 1 && x_bound != 3) { ne_i[0] = i+1; ne_j[0] = j; ne_i[2] = 10000; ne_j[2] = 10000; } else { ne_i[0] = i+1; ne_j[0] = j; ne_i[2] = i-1; ne_j[2] = j; } /*Up and down neighbours*/ if(j == yelem-2 && y_bound == 3) { ne_i[1] = i; ne_j[1] = 1; ne_i[3] = i; ne_j[3] = j-1; } else if(j == 1 && y_bound == 3) { ne_i[1] = i; ne_j[1] = j+1; ne_i[3] = i; ne_j[3] = yelem-2; } else if(j == yelem-2 && y_bound !=3) { ne_i[1] = 10000; ne_j[1] = 10000; ne_i[3] = i; ne_j[3] = j-1; } else if(j == 1 && y_bound != 3) { ne_i[1] = i; ne_j[1] = j+1; ne_i[3] = 10000; ne_j[3] = 10000; } else { ne_i[1] = i; ne_j[1] = j+1; ne_i[3] = i; ne_j[3] = j-1; } } void compute_phi(int i, int j, double **phi2, int **tag, int solve_flag) { int ne_i[4]; int ne_j[4]; find_ne(ne_i, ne_j, i, j); double xphi, yphi; double xdsq, ydsq; double xflag=1.0; double yflag=1.0; double ne_phi[4]; for(int n=0; n<4; n++) { if(ne_i[n] != 10000) { if(tag[ne_i[n]][ne_j[n]] == solve_flag) { ne_phi[n] = phi2[ne_i[n]][ne_j[n]]; } else { ne_phi[n] = 10000.0; } } else { ne_phi[n] = 10000.0; } } double multiplier; if(solve_flag == 1) { multiplier = 1.0; } else if(solve_flag == -1) { multiplier = -1.0; } if(ne_phi[0] > 9999 && ne_phi[2] > 9999) { xphi = 0.0; xdsq = 1.0; xflag = 0.0; } else { xphi = multiplier * min(fabs(ne_phi[0]), fabs(ne_phi[2])); xdsq = pow(area[1][1][1][1], 2.0); } if(ne_phi[1] > 9999 && ne_phi[3] > 9999) { yphi = 0.0; ydsq = 1.0; yflag = 0.0; } else { yphi = multiplier * min(fabs(ne_phi[1]), fabs(ne_phi[3])); ydsq = pow(area[1][1][0][0], 2.0); } double anew = ydsq*xflag + xdsq*yflag; double bnew = -2.0*(xphi*ydsq + yphi*xdsq); double cnew = xphi*xphi*ydsq + yphi*yphi*xdsq - xdsq*ydsq; double disc = bnew*bnew - 4.0*anew*cnew; if(disc < 0.0) { printf("Solution to neighbour not found\n"); // <<i<<" "<<j<<" "<<xelem<<" "<<yelem<<endl; // <<xphi<<" "<<xdsq<<" "<<xflag<<endl; //<<yphi<<" "<<ydsq<<" "<<yflag<<endl; exit(0); } else if(disc >= 0.0 && solve_flag == 1) { phi2[i][j] = (-bnew + sqrt(disc))/(2.0*anew); } else if(disc >=0.0 && solve_flag == -1) { phi2[i][j] = (-bnew - sqrt(disc))/(2.0*anew); } } void fast_march(elemsclr &sclr) { double **phi2; allocator(phi2, xelem, yelem); int **tag; int **int_cells; iallocator(tag, xelem, yelem); /****Calculate interface nodes*****/ interface_nodes(sclr.phi, int_cells); //<<"No of cells on interface; "<<int_cells.size()<<endl; /*for(int i=0; i<int_cells.size(); i++) { <<int_cells[i][0]<<" "<<int_cells[i][1]<<endl; }*/ /*Tag interface nodes as 1*/ for(int i=1; i<xelem-1; i++) { for(int j=1; j<yelem-1; j++) { for(int k=0; k < int_cells.size(); k++) { if(i == int_cells[k][0] && j == int_cells[k][1] && sclr.phi[i][j][0] > 0.0) { tag[i][j] = 1; } else if(i == int_cells[k][0] && j == int_cells[k][1] && sclr.phi[i][j][0] < 0.0) { tag[i][j] = -1; } } } } /*Copy the phi values to phi2*/ for(int i=0; i<xelem; i++) { for(int j=0; j<yelem; j++) { phi2[i][j] = sclr.phi[i][j][0]; } } int solve_flag = 1; again: if(solve_flag == 1) { printf("Solving +ve nodes\n"); } else if(solve_flag == -1) { printf("Solving -ve nodes\n"); } /*Tag rest of the nodes as far nodes*/ int count=0; for(int i=1; i<xelem-1; i++) { for(int j=1; j<yelem-1; j++) { if(tag[i][j] !=1 && solve_flag == 1 && sclr.phi[i][j][0] > 0.0 || tag[i][j] !=-1 && solve_flag == -1 && sclr.phi[i][j][0] < 0.0) { tag[i][j] = 3; count++; } } } //<<"total far nodes "<<count<<endl; /*Now compute the phi values of interface nodes*/ for(int k=0; k < int_cells.size(); k++) { vector<int> ne_i(4,0); vector<int> ne_j(4,0); find_ne(ne_i, ne_j, int_cells[k][0], int_cells[k][1]); for(int n=0; n<4; n++) { if(ne_i[n] != 10000 && ne_j[n] != 10000) { if(solve_flag == 1 && sclr.phi[ne_i[n]][ne_j[n]][0] > 0.0 || solve_flag == -1 && sclr.phi[ne_i[n]][ne_j[n]][0] < 0.0) { if(tag[ne_i[n]][ne_j[n]] != 1 && tag[ne_i[n]][ne_j[n]] != -1 && tag[ne_i[n]][ne_j[n]] != 2) { compute_phi(ne_i[n], ne_j[n], phi2, tag, solve_flag); tag[ne_i[n]][ne_j[n]] = 2; } } } } } double *heap; int **index; int tot_tag=0; for(int i=1; i < xelem-1; i++) { for(int j=1; j<yelem-1; j++) { if(tag[i][j] == 2) { tot_tag++; } } } heap1.resize(tot_tag); index.resize(tot_tag); for(int i=0; i < tot_tag; i++) { index[i].resize(2); } int heap_index=0; for(int i=1; i < xelem-1; i++) { for(int j=1; j<yelem-1; j++) { if(tag[i][j] == 2) { heap1[heap_index] = abs(phi2[i][j]); index[heap_index][0] = i; index[heap_index][1] = j; heap_index++; } } } initialize_heap1(heap1, index); int band = 1; int ncount = 0; while(heap1.size() > 0) { ncount++; //Tag top of heap as 1 and delete tag[index[0][0]][index[0][1]] = solve_flag; int new_node[2]; new_node[0] = index[0][0]; new_node[1] = index[0][1]; delete_from_heap(heap1,index); //Find neighbours of new node, tag as band and find new phi values vector<int> ne_i(4); vector<int> ne_j(4); find_ne(ne_i, ne_j, new_node[0], new_node[1]); for(int n=0; n<4; n++) { if(ne_i[n] != 10000) { if(tag[ne_i[n]][ne_j[n]] != 1 && tag[ne_i[n]][ne_j[n]] != -1) { compute_phi(ne_i[n], ne_j[n], phi2, tag, solve_flag); if(tag[ne_i[n]][ne_j[n]] == 2) { for(int k=0; k < heap1.size(); k++) { if(index[k][0] == ne_i[n] && index[k][1] == ne_j[n]) { heap1[k] = fabs(phi2[ne_i[n]][ne_j[n]]); min_heapify(0, heap1, index); break; } } } else { tag[ne_i[n]][ne_j[n]] = 2; int nodex = ne_i[n]; int nodey = ne_j[n]; double phivalue = fabs(phi2[ne_i[n]][ne_j[n]]); add_to_heap(phivalue, nodex, nodey, heap1, index); } } } } //<<heap1.size()<<endl; //<<index.size()<<endl; } //<<"Total nodes processed "<<ncount<<endl; heap1.resize(0); index.resize(0); if(solve_flag == 1) { solve_flag = -1; goto again; } //<<heap1.size()<<endl; //<<index.size()<<endl; for(int i=1; i<xelem-1; i++) { for(int j=1; j<yelem-1; j++) { sclr.phi[i][j][0] = phi2[i][j]; } } level_setBC(sclr.phi); //<<"here"<<endl; //exit(0); } #endif /* FAST_MARCH_H */
Java
UTF-8
10,382
1.835938
2
[]
no_license
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2014 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2014 Sun Microsystems, Inc. */ package org.netbeans.api.io; import java.io.PrintWriter; import java.io.Reader; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.annotations.common.NullAllowed; import org.netbeans.spi.io.InputOutputProvider; import org.openide.util.Lookup; /** * An I/O connection to one tab on the Output Window. To acquire an instance to * write to, call, e.g., * <code>IOProvider.getDefault().getInputOutput("someName", false)</code>. To * get actual streams to write to, call <code>getOut()</code> or <code> * getErr()</code> on the returned instance. * <p> * Generally it is preferable not to hold a reference to an instance of * {@link org.netbeans.api.io.InputOutput}, but rather to fetch it by name from * {@link org.netbeans.api.io.IOProvider} as needed. * </p> * * <p> * Methods of this class can be called in any thread. * </p> * * @see OutputWriter * @author Ian Formanek, Jaroslav Tulach, Petr Hamernik, Ales Novak, Jan * Jancura, Jaroslav Havlin */ public abstract class InputOutput implements Lookup.Provider { private static final Set<ShowOperation> DEFAULT_SHOW_OPERATIONS = EnumSet.of(ShowOperation.OPEN, ShowOperation.MAKE_VISIBLE); private InputOutput() { } /** * Get a named instance of InputOutput from the default {@link IOProvider}, * which represents an output tab in the output window. Streams for * reading/writing can be accessed via getters on the returned instance. * * <p> * This is a shorthand for {@code IOProvider.getDefault().getIO(...)}. * </p> * * @param name A localised display name for the tab. * @param newIO If <tt>true</tt>, a new <code>InputOutput</code> is * returned, else an existing <code>InputOutput</code> of the same name may * be returned. * @return An <code>InputOutput</code> instance for accessing the new tab. * @see IOProvider */ @NonNull public static InputOutput get(@NonNull String name, boolean newIO) { return IOProvider.getDefault().getIO(name, newIO); } /** * Get a named instance of InputOutput from the default {@link IOProvider}, * which represents an output tab in the output window. Streams for * reading/writing can be accessed via getters on the returned instance. * * <p> * This is a shorthand for {@code IOProvider.getDefault().getIO(...)}. * </p> * * @param name A localised display name for the tab. * @param newIO If <tt>true</tt>, a new <code>InputOutput</code> is * returned, else an existing <code>InputOutput</code> of the same name may * be returned. * @param lookup Lookup which may contain additional information for various * implementations of output window. * @return An <code>InputOutput</code> instance for accessing the new tab. * @see IOProvider */ @NonNull public static InputOutput get(@NonNull String name, boolean newIO, @NonNull Lookup lookup) { return IOProvider.getDefault().getIO(name, newIO, lookup); } /** * Get a reader to read from the tab. * * @return The reader. */ @NonNull public abstract Reader getIn(); /** * Acquire an output writer to write to the tab. * * @return The writer. */ @NonNull public abstract OutputWriter getOut(); /** * Get an output writer to write to the tab in error mode. This might show * up in a different color than the regular output, e.g., or appear in a * separate pane. * * @return The writer. */ @NonNull public abstract OutputWriter getErr(); /** * Clear the output pane. */ public abstract void reset(); /** * Get lookup which may contain extensions provided by implementation of * output window. * * @return The lookup. */ @NonNull @Override public abstract Lookup getLookup(); /** * Closes this tab. The effect of calling any method on an instance of * InputOutput after calling <code>close()</code> on it is * undefined. */ public abstract void close(); /** * Test whether this tab has been closed, either by a call to * {@link #close()} or by the user closing the tab in the UI. * * @return Value <code>true</code> if it is closed. */ public abstract boolean isClosed(); /** * Get description of this I/O instance. * * @return The description, or null if not set. */ @CheckForNull public abstract String getDescription(); /** * Set description of this I/O instance. It can be used e.g. as tooltip for * output tab in the GUI. * * @param description The description, can be null. */ public abstract void setDescription(@NullAllowed String description); static <IO, OW extends PrintWriter, P, F> InputOutput create( InputOutputProvider<IO, OW, P, F> provider, IO io) { return new Impl<IO, OW, P, F>(provider, io); } /** * Show this I/O if possible (e.g. in tabbed pane). * <p> * Calling this method is the same as calling: * </p> * <pre> * show(EnumSet.of(ShowOperation.OPEN, ShowOperation.MAKE_VISIBLE)); * </pre> * * @see #show(java.util.Set) */ public final void show() { show(DEFAULT_SHOW_OPERATIONS); } /** * Show this I/O if possible (e.g. in tabbed pane). * * @param operations Set of operations that should be invoked to show the * output. If the set is empty or null, pane for this I/O will be only * selected, but its component will not be opened or made visible. So it * will stay closed or hidden if it is not opened or not visible. * * @see ShowOperation */ public abstract void show(@NullAllowed Set<ShowOperation> operations); private static class Impl<IO, OW extends PrintWriter, P, F> extends InputOutput { private final Map<OW, OutputWriter> cache = Collections.synchronizedMap( new WeakHashMap<OW, OutputWriter>()); private final InputOutputProvider<IO, OW, P, F> provider; private final IO ioObject; public Impl(InputOutputProvider<IO, OW, P, F> provider, IO ioObject) { this.provider = provider; this.ioObject = ioObject; } @Override public Reader getIn() { return provider.getIn(ioObject); } @Override public OutputWriter getOut() { return createOrGetCachedWrapper(provider.getOut(ioObject)); } @Override public OutputWriter getErr() { return createOrGetCachedWrapper(provider.getErr(ioObject)); } @Override @NonNull public Lookup getLookup() { return provider.getIOLookup(ioObject); } @Override public void reset() { provider.resetIO(ioObject); } private OutputWriter createOrGetCachedWrapper(OW pw) { OutputWriter ow = cache.get(pw); if (ow == null) { ow = OutputWriter.create(provider, ioObject, pw); cache.put(pw, ow); } return ow; } @Override public void close() { provider.closeIO(ioObject); } @Override public boolean isClosed() { return provider.isIOClosed(ioObject); } @Override public String getDescription() { return provider.getIODescription(ioObject); } @Override public void setDescription(String description) { provider.setIODescription(ioObject, description); } @Override public void show(Set<ShowOperation> operations) { provider.showIO(ioObject, operations != null ? operations : Collections.<ShowOperation>emptySet()); } } }
C#
UTF-8
790
3.171875
3
[]
no_license
using System; using System.Text; namespace Library { public class DateAndPlace { public string date {get; set;} public string appointmentPlace {get; set;} public DateAndPlace (DateTime date, String appointmentPlace) { this.appointmentPlace = appointmentPlace; } public static bool DateAndPlaceValidation (string date, string appointmentPlace) { StringBuilder stringBuilder = new StringBuilder(""); Boolean isValid = true; if (string.IsNullOrEmpty(appoinmentPlace)) { stringBuilder.Append("Unable to schedule appointment, Appoinment place is required\n"); isValid = false; } return isValid; } }
Java
UTF-8
189
2
2
[]
no_license
package battleship; /* This was in the design, but we didn't end up using it */ public class Point { int x; int y; boolean hit; public Point() { } }
Java
UTF-8
2,952
2.546875
3
[ "MIT" ]
permissive
package com.scr.journal.util; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.PrettyPrinter; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.time.LocalDate; import java.util.concurrent.Callable; public final class JsonConverter { private static final ObjectMapper OBJECT_MAPPER; static { OBJECT_MAPPER = new ObjectMapper(); ParameterNamesModule module = new ParameterNamesModule(); module.addDeserializer(LocalDate.class, new JsonDeserializer<LocalDate>() { @Override public LocalDate deserialize(JsonParser p, DeserializationContext context) throws IOException, JsonProcessingException { String dateStr = context.readValue(p, String.class); return ConversionUtils.convert(dateStr, LocalDate.class); } }); module.addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() { @Override public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException { if (value != null) { String dateStr = ConversionUtils.convert(value); gen.writeString(dateStr); } else { gen.writeNull(); } } }); OBJECT_MAPPER.registerModule(module); OBJECT_MAPPER.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); OBJECT_MAPPER.setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.PUBLIC_ONLY); OBJECT_MAPPER.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); PrettyPrinter prettyPrinter = new CustomMinimalPrettyPrinter(); OBJECT_MAPPER.setDefaultPrettyPrinter(prettyPrinter); } public static <T> void writeValue(OutputStream outputStream, T object) { processAndWrapCheckedException(() -> { OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, object); return null; }); } public static <T> T readValue(InputStream inputStream, Class<T> valueType) { return processAndWrapCheckedException(() -> OBJECT_MAPPER.readValue(inputStream, valueType)); } private static <T> T processAndWrapCheckedException(Callable<T> callable) { try { return callable.call(); } catch (Exception e) { throw new RuntimeException(e); } } private JsonConverter() { throw new UnsupportedOperationException(); } }
C
UTF-8
700
2.890625
3
[]
no_license
#ifndef RUNNER_H_ #define RUNNER_H_ #include <stdio.h> #include "publications.h" #include "parson.h" /** * Reads each command (query or new publication) from an input file and makes the * required call to the API. * After the call returns its result, the function compares this result with the * one found in the ref file. * * @param input_file the file where commands will be read from * @param ref_file the file containing the results that the tested * functions will be compared against * @return a code symbolising the correctness of the execution: * * 0: success * * -1: failure */ int parse_commands(FILE* input_file, FILE* ref_file); #endif /* RUNNER_H_ */
Markdown
UTF-8
3,011
2.765625
3
[]
no_license
--- layout: post title: 'Document Tools' description: '' date: 'April 05, 2022' --- Generally well-known document editing tools: - [Microsoft Word](https://www.microsoft.com/en-us/microsoft-365/word) - [Apple Pages](https://www.apple.com/pages/) - [Google Docs](https://www.google.com/docs/about/) --- Lesser known document editing tools: - [Notion](https://www.notion.so/) - [Roam Research](https://roamresearch.com/) - [Coda](https://coda.io/) - [Almanac](https://almanac.io/) - [Craft](https://www.craft.do/) - [Skiff](https://skiff.org/) - [Quip](https://quip.com/) - [AnyType](https://anytype.io/en) - [Microsoft Fluid Framework](https://fluidframework.com/) --- Documents as files are dying. Files are being replaced by structured data—enabling an opportunity for a semantic web, if we can agree on a [standard](https://xkcd.com/927/). - [The Block Protocol](https://www.joelonsoftware.com/2022/01/27/making-the-web-better-with-blocks/) --- An alternative solution: enable parts of existing document types to be transformed to other data types. What [Pieces.app](https://code.pieces.app/about) calls the “file fragment era”. Documents suck. Why do documents suck so bad? Among other things, saving sucks, losing changes sucks, and interoperability sucks. What if documents didn’t suck? And what might that look like for your average computer user? --- [Reimagining the document authorizing experience](https://lukasmurdock.com/cms/) has taken up a lot of my mind space recently. We’re seeing a move away from [word processors](https://en.wikipedia.org/wiki/Word_processor)—editing, formatting, and output of primarily text. Word processors were already too complicated for most people. I’m often considered the “[technical person”](https://xkcd.com/627/) and when I tried Notion years ago I gave up because I didn’t care to learn its intricacies. Notion has most certainly improved over the years, but I continue to use local text files for all my documents. I consider the design and focus of [iA Writer](https://ia.net/writer) an ideal document editing experience—[not without its flaws](https://lukasmurdock.com/cms/). Continually, I appreciate the simplicity and constraints of iA Writer—its [calmness](https://calmtech.com/). --- Editing experiences should be purposeful. Who authors documents? Why doesn’t the experience change based on what I’m creating? When moving from document formats, e.g., text, video, images, and audio, the experience obviously changes. But the editing experience is (mostly) not transformed by intentions within a document format. - Notes - Blog post - Research paper Should enable different default editor settings and come with their own sets of constraints. --- What if we didn’t care about files—instead we care about *fragments* of those files. What if we didn’t care about databases—instead we care about being able to replicate anywhere, seamlessly sync changes, and see where those changes are synced.
Markdown
UTF-8
2,718
3.265625
3
[]
no_license
# Sam's Data Science Projects ## Introduction I created this page to showcase my data science skills to potential employers. Below you will find a short introduction about me and links to pages about my personal data science projects broken down by category. ## About Me ![profile picture](https://user-images.githubusercontent.com/18587666/134286830-0491280b-4e79-45ed-9340-942bf1308e40.jpg) My name is Sam Matthews, I am a 33 year old male currently living in Sydney, Australia. Having recently graduated from a Master's of Data Science with the University of New South Wales, I am looking to start my career as a Data Scientist. I am no stranger to the world of data, over the last four and a half years I have worked as a Data Analyst for a number of Australia's largest companies and government organisations. My experience gained has given me skills in a number of areas including: - SQL used for both simple and complex queries - Python used in the ETL process to extract data from other databases or excel spreadsheets, transform the data into new formats and schemas and load the transformed data into a database - Presenting insights into data using tools such as Tableau, Qlik Sense and Power BI - Liasing with both technical and non-technical stakeholders about project requirements as well as any outcomes and insights Throughout my recent Master's I have been learning further skils to make the transition into a data science career. I have also been practicing and improving upon those skills through the various projects shown below. These skills included: - Using python to preprocess and explore massive datasets - Using models from the SciKitLearn Python module to create models based on various modelling techniques - Creating Neural Networks with Tensorflow and Pytorch - Comparing the outputs of different models to find the most suitable in terms of accuracy and understandablity ## Projects ### [Basic SciKitLearn Projects](https://sammatt87.github.io/SciKitLearn-basics/) These are projects that I used to practice my skills in SciKitLearn models before I undertook my Masters degree. ### [Image Recognition Projects](https://sammatt87.github.io/Image-Recognition/) Image clssification tasks using various sklearn models and Neural Networks. ### [Natural Language Processing Projects](https://sammatt87.github.io/NLP/) Various Natural Language processing tasks using sklearn models and Neural Networks ### [Prediction Projects](https://sammatt87.github.io/Prediction) Projects used to predict outcomes such as customer churn or flight delays using various sklearn models ### [Fun Python Projects](https://sammatt87.github.io/Fun) Just some fun projects showing off skills like web scraping
Python
UTF-8
2,457
2.9375
3
[]
no_license
"""Config file for the client's UI. Has variables describing text, and functions to style text correctly. Also handles the styling options from the ui_config.json file.""" TEXT_BROWSER_START = \ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" \ "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" \ "p, li { white-space: pre-wrap; }\n" \ "</style></head><body style=\" font-size:16pt; font-weight:400; " \ "font-style:normal;\">\n" TEXT_BROWSER_ITEM_START = "<p style=\" margin: 0; -qt-block-indent:0; text-indent:0px;\">" TEXT_BROWSER_ITEM_END = "</p><\n>" TEXT_BROWSER_END = "</body></html>" ui_config_filepath = "ui_config.json" def style_text_browser(messages: list, style_start=TEXT_BROWSER_START, style_end=TEXT_BROWSER_END, style_item_start=TEXT_BROWSER_ITEM_START, style_item_end=TEXT_BROWSER_ITEM_END): """Returns the desired text browser (HTML) for the list of messages. Messages should be in the form of [User] Message [Another User] Message [Server] Server Message""" msg_text = "" for msg in [n.strip() for n in messages]: # For every message in (stripped) messages name_text_segments = msg.split("]") # Split by ] (this is to signal the end of the name section) if len(name_text_segments) != 1: # If there is less than 2 entries in the list (meaning there was no ]) msg_text += f"{style_item_start}<b>{name_text_segments[0]}]</b> {name_text_segments[1].strip()}" \ f"{style_item_end}\n" else: msg_text += f"{style_item_start}<b>{msg.strip()}" return f"{style_start}{msg_text}{style_end}" def load_ui_config(): import json with open(ui_config_filepath, "r") as file: return json.load(file) def get_style_sheets(config: dict) -> dict: style_sheets = {'primary_col': f"background-color: {config['primary_col']['bg']};" f"color: {config['primary_col']['text']};" f"border: none; outline: none;", 'secondary_col': f"background-color: {config['secondary_col']['bg']};" f"color: {config['secondary_col']['text']};" f"border: hidden; outline: none;"} return style_sheets if __name__ == '__main__': load_ui_config()
Python
UTF-8
2,967
2.78125
3
[]
no_license
''' Python script to analyse communities of a kinetic transition network: clustering entropy, quality functions, community sizes, scaled link density of communities ''' from math import log from math import sqrt ### SET PARAMS ### n_nodes=48800 n_edges=62414 n_its=100 # CLUSTERING ENTROPY ic_node_probs = [0.]*n_nodes # probability of a node being inter-community ic_edge_probs = [0.]*n_edges # probability of an edge being inter-community for i in range(n_its): with open("sce_node."+str(i)+".dat","r") as sce_node_f: for j, line in enumerate(sce_node_f.readlines()): ic_node_probs[j] += float(line.split()[0]) with open("sce_edge."+str(i)+".dat","r") as sce_edge_f: for j, line in enumerate(sce_edge_f.readlines()): if int(line.split()[0])==-1: continue # dead TS flag ic_edge_probs[j] += float(line.split()[0]) for i in range(n_nodes): ic_node_probs[i] *= 1./float(n_its) for i in range(n_edges): ic_edge_probs[i] *= 1./float(n_its) s_ce = 0. # clustering entropy for j in range(n_edges): p_ij = ic_edge_probs[j] if p_ij==0. or p_ij==1.: continue else: s_ce += (p_ij*log(p_ij,2.)) + ((1.-p_ij)*log(1.-p_ij,2.)) s_ce *= -1./float(n_edges) print "clustering entropy is: %1.6f" % s_ce with open("ic_node_probs.dat","w") as icnp_f: for j in range(n_nodes): icnp_f.write("%1.6f\n" % ic_node_probs[j]) with open("ic_edge_probs.dat","w") as icep_f: for j in range(n_edges): icep_f.write("%1.6f\n" % ic_edge_probs[j]) bin_vals = [0.+(float(i)*0.05) for i in range(20+1)] ic_node_probs_bins, ic_edge_probs_bins = [0]*20, [0]*20 curr_bin_idx = 0 for p_i in sorted(ic_node_probs): while p_i > bin_vals[curr_bin_idx+1]: curr_bin_idx += 1 ic_node_probs_bins[curr_bin_idx] += 1 curr_bin_idx = 0 for p_ij in sorted(ic_edge_probs): while p_ij > bin_vals[curr_bin_idx+1]: curr_bin_idx += 1 ic_edge_probs_bins[curr_bin_idx] += 1 hist_files = ["ic_node_probs_distrib", "ic_edge_probs_distrib"] bin_arrs = [ic_node_probs_bins,ic_edge_probs_bins] for i in range(2): hist_file = hist_files[i] bin_arr = bin_arrs[i] with open(hist_file+".dat","w") as hist_f: for bin_idx, bin_popn in enumerate(bin_arr): hist_f.write("%1.2f %5i\n" % (bin_vals[bin_idx],bin_popn)) quit() # AVG & STD DEV OF QUALITY FUNCTIONS quality_files = ["modularity","avgncut","conductance"] for quality_f in quality_files: qf_vals = [0.]*n_its; qf_avg, qf_sd = 0., 0. with open(quality_f+".dat","r") as qual_f: for i in enumerate(qual_f.readlines()): qf_vals[i] = float(line.split()[0]) qf_avg += qf_vals[i] qf_avg *= 1./float(n_its) for i in range(n_its): qf_sd += (qf_vals[i]-qf_avg)**2 qf_sd = sqrt((1./float(n_its-1))*qf_sd) print "%s: avg: %1.8f sd: %1.8f" % (quality_f,qf_avg,qf_sd) # COMMUNITY SIZES DISTRIBUTION # SCALED LINK DENSITY OF COMMUNITIES DISTRIBUTION
Python
UTF-8
1,140
3.921875
4
[]
no_license
""" 解题思路: 要求解最小船数,就得使每艘船尽量满载 由于一艘船可坐两人,在不超重的情况下那最重的人和最轻的人在一起是最好的 如果超重,则最重的人单独坐一艘,然后再让剩下最重的和最轻的,依次类推。 所以首先应该对people列表倒序排序,然后一个left指针指向最重和一个right指针指向最轻 当left=right时,这个人单独坐一艘,当left>right时,代表所有人已经被分配,结束循环 """ class Solution: def numRescueBoats(self, people, limit): lens = len(people) if lens < 2: return lens people = sorted(people, reverse=True) left = 0 right = lens - 1 sum = 0 while left <= right: if left == right: sum += 1 break if people[left] + people[right] <= limit: left += 1 right -= 1 else: left += 1 sum += 1 return sum if __name__ == '__main__': sl = Solution() print(sl.numRescueBoats([3, 1, 7], 7))
SQL
UTF-8
810
3.328125
3
[ "Apache-2.0" ]
permissive
#standardSQL # HaveIBeenPwned breaches by type of data breached, e.g., email addresses # https://docs.google.com/spreadsheets/d/148SxZICZ24O44roIuEkRgbpIobWXpqLxegCDhIiX8XA/edit#gid=1158689200 SELECT data_class, breach_date, total_number_of_affected_accounts, SUM(total_number_of_affected_accounts) OVER ( PARTITION BY data_class ORDER BY data_class, breach_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cumulative_number_of_affected_accounts FROM ( SELECT data_class, BreachDate AS breach_date, SUM(PwnCount) AS total_number_of_affected_accounts FROM `httparchive.almanac.breaches`, UNNEST(JSON_VALUE_ARRAY(DataClasses)) AS data_class WHERE date = '2021-07-01' GROUP BY data_class, breach_date ) ORDER BY data_class, breach_date
JavaScript
UTF-8
245
3.875
4
[]
no_license
// 09.01 JavasScript code //Writing a loop that write the array into separate line var array = ["Pekka", "Minna", "Heikki", "Anna", "Jukka", "Iida"]; arrayLength = array.length; for (i = 0; i < arrayLength; i++) { console.log(array[i]); }
Markdown
UTF-8
2,147
2.5625
3
[ "Apache-2.0" ]
permissive
--- title: 为没有 sidecar 的应用程序提供证书和密钥 description: 通过挂载的文件获取和共享应用程序证书和密钥的机制。 publishdate: 2020-03-25 attribution: Lei Tang (Google) keywords: [certificate,sidecar] target_release: 1.5 --- {{< boilerplate experimental-feature-warning >}} Istio sidecars 获取使用 secret 发现服务的证书。服务网格中的服务可能不需要(或不想要) Envoy sidecar 来处理其流量。在这种情况下,如果服务想要连接到其他 TLS 或共同 TLS 安全的服务,它将需要自己获得证书。 对于不需要 sidecar 来管理其流量的服务,sidecar 仍然可以被部署只为了通过来自 CA 的 CSR 流量提供私钥和证书,然后通过一个挂载到 `tmpfs` 中的文件来共享服务证书。我们使用 Prometheus 作为示例应用程序来配置使用此机制的证书。 在示例应用程序(即 Prometheus)中,通过设置标识 `.Values.prometheus.provisionPrometheusCert` 为 `true`(该标识在 Istio 安装中默认设置为 true)将 sidecar 添加到 Prometheus 部署。然后,这个部署的 sidecar 将请求与 Prometheus 共享一个证书。 为示例应用程序提供的密钥和证书都挂载在 `/etc/istio-certs/` 目录中。运行以下命令,我们可以列出为应用程序提供的密钥和证书: {{< text bash >}} $ kubectl exec -it `kubectl get pod -l app=prometheus -n istio-system -o jsonpath='{.items[0].metadata.name}'` -c prometheus -n istio-system -- ls -la /etc/istio-certs/ {{< /text >}} 上面命令的输出应该包含非空的密钥和证书文件,如下所示: {{< text plain >}} -rwxr-xr-x 1 root root 2209 Feb 25 13:06 cert-chain.pem -rwxr-xr-x 1 root root 1679 Feb 25 13:06 key.pem -rwxr-xr-x 1 root root 1054 Feb 25 13:06 root-cert.pem {{< /text >}} 如果您想使用此机制来为您自己的应用程序提供证书,请查看我们的 [Prometheus 示例应用程序]({{< github_blob >}}/manifests/charts/istio-telemetry/prometheus/templates/deployment.yaml),并简单地遵循相同的模式。
Java
UTF-8
7,588
1.929688
2
[]
no_license
package com.cocoker.controller; import com.cocoker.VO.ResultVO; import com.cocoker.beans.*; import com.cocoker.dto.UserDetailDTO; import com.cocoker.enums.UserStatusEnum; import com.cocoker.service.*; import com.cocoker.utils.MD5; import com.cocoker.utils.RandomUtil; import com.fasterxml.jackson.annotation.JsonProperty; import net.bytebuddy.TypeCache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpSession; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.*; /** * @Description: * @Author: y * @CreateDate: 2019/1/6 11:09 AM * @Version: 1.0 */ @Controller @RequestMapping("/admin") public class AdminController { @Autowired private UserInfoService userInfoService; @Autowired private ComplaintService complaintService; @Autowired private OrderService orderService; @Autowired private EchartsService echartsService; @Autowired private RechargeService rechargeService; @Autowired private ExchangeService exchangeService; private static final DecimalFormat df = new DecimalFormat("#.00"); public static Integer EchartsConst = 0; @GetMapping("/login") public ModelAndView login() { return new ModelAndView("login/index"); } /** * 登录 * * @param username * @param pwd * @return */ @PostMapping("/toLogin") public ModelAndView toLogin(@RequestParam("username") String username, @RequestParam("pwd") String pwd, HttpSession session) { UserInfo userInfo = userInfoService.login(username, MD5.md5(pwd, "")); if (userInfo == null) { return new ModelAndView("login/index"); } session.setAttribute("admin", userInfo); return new ModelAndView("redirect:index"); } @GetMapping("/index") public ModelAndView index(@PageableDefault(sort = {"yUid"}, direction = Sort.Direction.DESC) Pageable pageable, Map<String, Object> map) { Page<UserInfo> list = userInfoService.findList(pageable); String allMoney = userInfoService.findAllMoney(); String dayAllIncMoney = userInfoService.findDayAllMoney(); String allUserCount = userInfoService.allUserCount(); String dayAllDecMoney = exchangeService.findDayExchangeAllMoney(); map.put("users", list.getContent()); //总余额 map.put("allMoney", allMoney); //今日充值 if (dayAllIncMoney != null) { map.put("dayAllMoney", df.format(Double.valueOf(dayAllIncMoney))); // map.put("dayAllMoney", df.format(Double.valueOf(Double.valueOf(dayAllIncMoney) * 6.79))); } else { map.put("dayAllMoney", "0"); } //所有用户数量 map.put("allUserCount", allUserCount); //今日提现 if (dayAllDecMoney != null) { map.put("dayAllDecMoney", df.format(Double.valueOf(dayAllDecMoney))); } else { map.put("dayAllDecMoney", "0"); } return new ModelAndView("admin/index", map); } @GetMapping("/ui-elements") public ModelAndView index(Map<String, Object> map, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) { if (page < 0) { return new ModelAndView("admin/ui-elements", map); } PageRequest pageRequest = PageRequest.of(page, size, Sort.Direction.DESC, "oid"); Page<Order> pages = orderService.findListPage(pageRequest); map.put("pages", pages); return new ModelAndView("admin/ui-elements", map); } @GetMapping("/complaint") public ModelAndView complaint(Map<String, Object> map) { List<Complaint> allComplaint = complaintService.findAllComplaint(); map.put("allComplaint", allComplaint); return new ModelAndView("admin/complaint", map); } @GetMapping("/clearComplaint") public ModelAndView clearComplaint() { complaintService.deleteAllComplaint(); return new ModelAndView("admin/complaint"); } @GetMapping("/tab-panel") public ModelAndView editAdmin() { return new ModelAndView("admin/tab-panel"); } @GetMapping("/table") public ModelAndView table() { return new ModelAndView("admin/table"); } @GetMapping("/form") public ModelAndView form() { return new ModelAndView("admin/form"); } @GetMapping("/search") public ModelAndView search() { return new ModelAndView("admin/search"); } @GetMapping("/editMoney") public ModelAndView editMoney() { return new ModelAndView("admin/empty"); } /** * 查询所有充值成功的 * * @param map * @param page * @param size * @return */ @GetMapping("/recharge") public ModelAndView rechargeList(Map<String, Object> map, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) { if (page < 0) { return new ModelAndView("admin/recharge"); } PageRequest request = PageRequest.of(page, size, Sort.Direction.DESC, "tid"); //1代表值查询充值成功的 Page<Recharge> rechargeList = rechargeService.findByTstatus(1, request); map.put("rechargeList", rechargeList); return new ModelAndView("admin/recharge"); } /** * 查询所有提现成功的 * * @param map * @param page * @param size * @return */ @GetMapping("/exchange") public ModelAndView exchangeList(Map<String, Object> map, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) { if (page < 0) { return new ModelAndView("admin/recharge"); } PageRequest request = PageRequest.of(page, size, Sort.Direction.DESC, "tId"); //1代表值查询提现成功的 Page<Exchange> exchangeList = exchangeService.findByTStatus(1, request); map.put("exchangeList", exchangeList); return new ModelAndView("admin/exchange"); } @GetMapping("/waitexchange") public ModelAndView waitexchange(Map<String, Object> map, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) { if (page < 0) { return new ModelAndView("admin/waitrecharge"); } PageRequest request = PageRequest.of(page, size, Sort.Direction.DESC, "tId"); //0代表值查询提现未成功的 Page<Exchange> exchangeList = exchangeService.findByTStatus(0, request); map.put("exchangeList", exchangeList); return new ModelAndView("admin/waitexchange"); } }
Java
UTF-8
6,631
2.4375
2
[ "Apache-2.0" ]
permissive
package main.java.controller; import com.jfoenix.controls.*; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import main.java.dao.User; import main.java.db.UserManager; import main.java.utils.JDBCUtils; import main.java.utils.TextUtils; import main.java.utils.Toast; import java.net.URL; import java.sql.SQLException; import java.util.Arrays; import java.util.Map; import java.util.ResourceBundle; import java.util.Stack; /** * Created by Inno Fang on 2018/1/17. */ public class UserInfoController implements Initializable { @FXML AnchorPane pane; @FXML Label userNo; @FXML JFXRadioButton male, female; @FXML JFXTextField nameInput, telInput; @FXML JFXPasswordField oldPasswordInput, newPasswordInput, repeatPasswordInput; @FXML JFXButton infoUpdateButton, passwordModifyButton; private ToggleGroup group; private String userType; @Override public void initialize(URL location, ResourceBundle resources) { group = new ToggleGroup(); male.setToggleGroup(group); female.setToggleGroup(group); userType = (String) UserManager.CURRENT_USR.get("type"); if (userType.equals(User.ADMIN)) { initInfo("Ano", "Atel", "Aname", "Asex"); } else { initInfo("Tno", "Ttel", "Tname", "Tsex"); } } private void initInfo(String no, String tel, String name, String sex) { Map<String, Object> map = UserManager.CURRENT_USR; userNo.setText((String) map.get(no)); telInput.setText((String) map.get(tel)); String s = (String) map.get(sex); if (s.equals("男")) { male.setSelected(true); } else { female.setSelected(true); } String n = (String) map.get(name); if (null != n) nameInput.setText(n); } public void onHandleUpdateInfo() { String name = nameInput.getText(); String sex = male.isSelected() ? "男" : "女"; String tel = telInput.getText(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(sex) || TextUtils.isEmpty(tel)) { Toast.show(pane, "更新信息不能为空"); } else { try { if (userType.equals(User.ADMIN)) { JDBCUtils.get() .update("UPDATE admin SET Aname=?, Atel=?, Asex=? WHERE Ano=?", Arrays.asList(name, tel, sex, userNo.getText())); UserManager.CURRENT_USR.put("Ano", userNo.getText()); UserManager.CURRENT_USR.put("Aname", name); UserManager.CURRENT_USR.put("Asex", sex); UserManager.CURRENT_USR.put("Atel", tel); } else { JDBCUtils.get() .update("UPDATE teacher SET Tname=?, Ttel=?, Tsex=? WHERE Tno=?", Arrays.asList(name, tel, sex, userNo.getText())); UserManager.CURRENT_USR.put("Tno", userNo.getText()); UserManager.CURRENT_USR.put("Tname", name); UserManager.CURRENT_USR.put("Tsex", sex); UserManager.CURRENT_USR.put("Ttel", tel); } Toast.show(pane, "更新成功"); } catch (SQLException e) { e.printStackTrace(); } } } public void onHandleModifyPassword() { String old = oldPasswordInput.getText(); String newP = newPasswordInput.getText(); String repeat = repeatPasswordInput.getText(); if (TextUtils.isEmpty(old) || TextUtils.isEmpty(newP) || TextUtils.isEmpty(repeat)) { Toast.show(pane, "信息不能为空"); return; } if (repeat.length() < 6) { Toast.show(pane, "密码长度不足 6 位,请修改"); return; } if (TextUtils.isDigitsOnly(repeat)) { Toast.show(pane, "密码强度太弱,不能只包含数字,请修改"); return; } try { String truePassword; if (userType.equals(User.ADMIN)) { truePassword = (String) JDBCUtils.get().getQueryResult("SELECT Apassword FROM admin WHERE Ano=?", Arrays.asList(userNo.getText())).get("Apassword"); } else { truePassword = (String) JDBCUtils.get().getQueryResult("SELECT Tpassword FROM teacher WHERE Ano=?", Arrays.asList(userNo.getText())).get("Tpassword"); } if (null != truePassword && old.equals(truePassword)) { if (newP.equals(repeat)) { boolean modify; if (userType.equals(User.ADMIN)) { modify = JDBCUtils.get().update("UPDATE admin SET Apassword=? WHERE Ano=?", Arrays.asList(repeat, userNo.getText())); } else { modify = JDBCUtils.get().update("UPDATE admin SET Apassword=? WHERE Ano=?", Arrays.asList(repeat, userNo.getText())); } if (modify) Toast.show(pane, "密码更改成功"); else Toast.show(pane, "密码更新失败"); } else { Toast.show(pane, "两次密码输入错误,请重新输入"); } } else { Toast.show(pane, "原始密码错误,请重新输入"); } oldPasswordInput.setText(""); newPasswordInput.setText(""); repeatPasswordInput.setText(""); } catch (SQLException e) { e.printStackTrace(); } } } /* // deprecation JFXDialogLayout content = new JFXDialogLayout(); content.setHeading(new Text("注意")); content.setBody(new Text("更新信息不能为空")); StackPane stackPane = new StackPane(); stackPane.setAlignment(Pos.CENTER); stackPane.setMaxSize(100, 100); JFXDialog dialog = new JFXDialog(stackPane, content, JFXDialog.DialogTransition.CENTER); JFXButton button = new JFXButton("知道了"); button.setOnAction(event -> dialog.close()); content.setActions(button); dialog.show(); */
Python
UTF-8
307
2.703125
3
[]
no_license
from django.http import HttpResponse from django.shortcuts import render_to_response def here(request): return HttpResponse("Mom, I'm here!") def math(request, a,b): a = int(a) b = int(b) s = a + b d = a - b p = a * b q = a / b return render_to_response('math.html', {'s':s, 'd':d, 'p':p, 'q':q})
Java
UTF-8
751
3.34375
3
[]
no_license
package Programers.Level2; public class Question12899 { public static void main(String[] args){ Question12899 question = new Question12899(); for(int i = 1; i<=100; i++){ System.out.println("================="+i+"================"); System.out.println(question.solution(i)); } } public String solution(int n){ String answer = ""; String prefix = ""; while(n > 0){ if(n%3 == 0){ prefix = "4"; n = n/3-1; }else{ prefix = String.valueOf(n%3); n = n/3; } String temp = answer; answer = prefix + temp; } return answer; } }
JavaScript
UTF-8
113
3.078125
3
[]
no_license
let stars = ("*"); for (i=1; i <= 6; i++) { console.log(stars); stars = stars + stars; }
C++
UTF-8
315
3.078125
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { unsigned int sum = 0, sqrsum = 0; for(int x = 1; x < 101; x++) { sum+=x; sqrsum += x * x; } cout << sum * sum << " " << sqrsum << endl; sum = sum * sum; cout << sum - sqrsum << endl; return 0; }
Python
UTF-8
6,202
2.5625
3
[]
no_license
# Utility to generate a stylesheet with all the combinations for alarms import os.path import argparse import json import itertools # Stylesheet for widgets which don't react to alarm status NO_ALARM = 0x0 # Stylesheet for the 'content' of widgets (text, usually) ALARM_CONTENT = 0x1 # Stylesheet for the border of widgets. ALARM_BORDER = 0x2 # Stylesheet for 'indicator' ornaments, where you want the "OK" status to actually have a color ALARM_INDICATOR = 0x4 # Alarm Serverities. Default set to widgets is ALARM_DISCONNECTED ALARM_NONE = 0 ALARM_MINOR = 1 ALARM_MAJOR = 2 ALARM_INVALID = 3 ALARM_DISCONNECTED = 4 # Alarm Color Definitions GREEN_ALARM = "#00EB00" YELLOW_ALARM = "#EBEB00" RED_ALARM = "#EB0000" MAGENTA_ALARM = "#EB00EB" WHITE_ALARM = "#EBEBEB" # We put all this in a big dictionary to try to avoid constantly # allocating and deallocating new stylesheet strings. alarm_style_sheet_map = { NO_ALARM: { ALARM_NONE: {}, ALARM_MINOR: {}, ALARM_MAJOR: {}, ALARM_INVALID: {}, ALARM_DISCONNECTED: {} }, ALARM_INDICATOR: { # Not being used at this time ALARM_NONE: {"color": GREEN_ALARM}, ALARM_MINOR: {"color": YELLOW_ALARM}, ALARM_MAJOR: {"color": RED_ALARM}, ALARM_INVALID: {"color": MAGENTA_ALARM}, ALARM_DISCONNECTED: {"color": WHITE_ALARM} }, ALARM_CONTENT: { ALARM_NONE: {"color": "black"}, ALARM_MINOR: {"color": YELLOW_ALARM}, ALARM_MAJOR: {"color": RED_ALARM}, ALARM_INVALID: {"color": MAGENTA_ALARM}, ALARM_DISCONNECTED: {"color": WHITE_ALARM} }, ALARM_BORDER: { ALARM_NONE: {"border": "2px solid transparent"}, ALARM_MINOR: {"border": "2px solid " + YELLOW_ALARM}, ALARM_MAJOR: {"border": "2px solid " + RED_ALARM}, ALARM_INVALID: {"border": "2px solid " + MAGENTA_ALARM}, ALARM_DISCONNECTED: {"border": "2px solid " + WHITE_ALARM} }, ALARM_CONTENT | ALARM_BORDER: { ALARM_NONE: {"color": "black", "border": "2px solid transparent"}, ALARM_MINOR: {"color": YELLOW_ALARM, "border": "2px solid " + YELLOW_ALARM}, ALARM_MAJOR: {"color": RED_ALARM, "border": "2px solid " + RED_ALARM}, ALARM_INVALID: {"color": MAGENTA_ALARM, "border": "2px solid " + MAGENTA_ALARM}, ALARM_DISCONNECTED: {"color": WHITE_ALARM, "border": "2px solid " + WHITE_ALARM} } } def produce_alarm_stylesheet(stylesheet_name, widget_type_names): """ Write the alarm styles into a file. Parameters ---------- stylesheet_name : str The absolute path where to save the output alarm stylesheet. widget_type_names : list A list of strings that are the widget names to write the alarm styles for """ with open(stylesheet_name, 'w') as alarm_stylesheet: alarm_severity = ALARM_NONE while alarm_severity <= ALARM_DISCONNECTED: table = list(itertools.product([False, True], repeat=2)) for row in table: is_border_alarm_sensitive = row[0] is_content_alarm_sensitive = row[1] _write_alarm_style(alarm_stylesheet, widget_type_names, is_border_alarm_sensitive, is_content_alarm_sensitive, alarm_severity) alarm_severity += 1 alarm_stylesheet.close() def _write_alarm_style(stylesheet_file, widget_type_names, is_border_alarm_sensitive, is_content_alarm_sensitive, alarm_severity): """ Write to the output stylesheet the styles for an alarm type, with alternating border, content, and border and content alarm sensitivities. Parameters ---------- stylesheet_file : file descriptor The file descriptor to the output stylesheet file widget_type_name : str The widget name to write the styles for is_border_alarm_sensitive : bool True if the widget's border style can change according to the alarm severity; False if not is_content_alarm_sensitive : bool True if the widget's border content can change according to the alarm severity; False if not alarm_severity : int The severity of the alarm, i.e. ALARM_NONE, ALARM_MINOR, ALARM_MAJOR, ALARM_INVALID, and ALARM_DISCONNECTED """ style = alarm_style_sheet_map[NO_ALARM][alarm_severity] selectors = ', '.join(widget_type_names) style_contents = ''.join([selectors, '[alarmSeverity="', str(alarm_severity), '"]']) if is_border_alarm_sensitive and is_content_alarm_sensitive: style_contents = ''.join([style_contents, '[alarmSensitiveBorder="true"]', '[alarmSensitiveContent="true"]']) style = alarm_style_sheet_map[ALARM_CONTENT | ALARM_BORDER][alarm_severity] elif is_border_alarm_sensitive: style_contents = ''.join([style_contents, '[alarmSensitiveBorder="true"]']) style = alarm_style_sheet_map[ALARM_BORDER][alarm_severity] elif is_content_alarm_sensitive: style_contents = ''.join([style_contents, '[alarmSensitiveContent="true"]']) style = alarm_style_sheet_map[ALARM_CONTENT][alarm_severity] style = json.dumps(style) # For a stylesheet, we want to separate settings by semicolons, not commas (as in JSON) style = style.replace(',', ';') style = style.replace('"', '') if style: style_contents = ''.join([style_contents, style.strip(), "\n"]) else: style_contents = ''.join([style_contents, " {}\n"]) stylesheet_file.write(style_contents) def main(): parser = argparse.ArgumentParser(description="Python Display Manager (PyDM) Stylesheet Generator") parser.add_argument( 'stylesheet_output_location', help='The location to save the output stylesheet' ) pydm_args = parser.parse_args() stylesheet_location = os.path.abspath(pydm_args.stylesheet_output_location) produce_alarm_stylesheet(os.path.abspath(stylesheet_location), ["PyDMWidget", "PyDMWritableWidget","PyDMLabel", "PyDMLineEdit", "PyDMSlider", "PyDMCheckbox"]) if __name__ == "__main__": main()
JavaScript
UTF-8
695
4.0625
4
[]
no_license
function getText(text) { return new Promise((res, rej) => { setTimeout(() => { res(text) }, 1000) }) } function log(text) { console.log(`текст: ${text}`) } async function test1() { let text = await getText('hello2'); log(text) } async function test2() { let text = await getText('hello3'); return text; } //пример с промисом getText('hello1').then(log); //вызов асинхронной функции test1(); //return из асинхронной функции let t = test2(); log(t); /* << ---- текст: [object Promise], выполняется не должыдаясь async function return text; */
Python
UTF-8
678
3.171875
3
[]
no_license
l=list() x=raw_input() i=1 while i<x: try: input=raw_input() except EOFError: break if input.startswith("insert"): items=input.split(" ") l.insert(int(items[1]),int(items[2])) elif input.startswith("print"): print str(l) elif input.startswith("remove"): items=input.split(" ") l.remove(int(items[1])) elif input.startswith("append"): items=input.split(" ") l.append(int(items[1])) elif input.startswith("reverse"): l.reverse() elif input.startswith("pop"): l.pop() elif input.startswith("sort"): l.sort() i=i+1
JavaScript
UTF-8
3,822
2.578125
3
[]
no_license
import Seperator from '../Seperator' const Ryouga = () => { return ( <div> <Seperator quote="Where the heck am I now?" /> <section> <h2 className="subhead">Ryouga Hibiki</h2> <article> <div className="col"> <img src="https://douglasave-static.sfo3.digitaloceanspaces.com/funkdafied-static/img/ryouga.jpg" alt="Ryouga and all his little ticks" title="Ryouga and all his little ticks" className="left mob-sizing" /> </div> <div className="col"> <p>Holy Hannah. I hate Ryouga. Well, I guess hate is kind of a strong word. I guess it would be more like I REALLY, REALLY, don't like Ryouga.</p> <p>I think I do not like him because of the way he acts. He does not seem to want to take responsibility for his own actions. A little background here.</p> <p>Before Genma drug Ranma off to China, Ryouga challenged him. (Ranma, not Genma.) Well, Ryouga, who has NO sense of direction got lost trying to find the vacant lot they were supposed to meet. This vacant lot was right BEHIND Ryouga's house. Ranma waited for Ryouga for 3 days. Ryouga arrived on the fourth day, after Ranma had left. So Ryouga in his infinite wisdom chases after Ranma to China. He ends up at a cliff overlooking Jusyenko. Ranma, in female form, sprints by knocking him into Spring of Drowned Piglet. You may think that this is Ranma's fault, but if that moron had stayed in Japan, well.</p> <p>Now, Ryouga is hell bent on revenge. But to make things more interesting Ryouga's cursed form is Akane's pet. To top things off Ryouga is in love with Akane! Sounds like a funked-up version of The 5th Wheel, eh? (The 5th Wheel was a stupid reality show that was airing when I first wrote this…)</p> </div> </article> <hr className="sep-hr" /> <div className="col"> <h3 className="article-head">Ryouga's Corner</h3> <p>I'm Ryouga Hibiki. Age 16.</p> <p>I have been cursed to spend the rest of my life as a pig thanks to that damned Ranma! <em>(Oh God, here we go.)</em> SHUT UP ERIN. Because of him I have been to hell and back! When I first became cursed his father tried to cook me! Then, the girl he is cheating on Akane with, Shampoo tried to cook me! Why can't they just become vegetarians?</p> <p>Yes, it's true I love Akane. Can you think of a reason why I shouldn't? <em>(I can think of about fifty reasons.)</em> Didn't I tell you to shut up? <em>(Sorry.)</em> Okay then. Yes, it's true that I spend my nights as Akane's pet, but I don't like it! *Erin's laughing cause him to have to leave the room* What's his problem? Anyway, I don't! I want to be able to love her as a man. I just - just haven't gotten around to telling her. Why would she want someone like me? And I can just imagine what would happen if she found out about my secret! She would hate me even more!</p> <p>I do have a slight problem with getting lost, but it is good for me. It helps in my training so that I can beat Ranma, avenge my curse, and give Akane a fiancée who will love her and treat her right. <em>(And I suppose that's your story and you’re sticking with it?)</em> Yep.</p> </div> </section> </div> ) } export default Ryouga
Python
UTF-8
1,293
3.265625
3
[]
no_license
class Solution: def myAtoi(self, str): """ :type str: str :rtype: int """ i = 0 sign = 1 currentValue = 0 max_int = 2**31 - 1 max_int_10 = int(max_int/10) min_int = 2**31 min_int_10 = int(min_int/10) str_length = len(str) max_int_last = max_int%10 min_int_last = min_int%10 if str_length == 0: return 0 for c in str: if c == ' ': i += 1 else: break if str_length - i <= 0: return 0 if str[i] == '-': sign = -1 i += 1 elif str[i] == '+': i += 1 while i < str_length and str[i] >= '0' and str[i] <= '9': int_i = int(str[i]) if sign == 1: if currentValue > max_int_10 or ( currentValue == max_int_10 and int_i > max_int_last): return max_int else: if currentValue > min_int_10 or ( currentValue == min_int_10 and int_i > min_int_last): return sign*min_int currentValue *= 10 currentValue += int_i i += 1 return sign*currentValue
Java
UTF-8
956
2.0625
2
[ "MIT" ]
permissive
package com.chulung.website.controller; import com.chulung.website.session.WebSessionSupport; import org.apache.commons.collections.MapUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import com.chulung.website.model.BaseComponent; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; /** * Controller基类 * * @author chulung */ public abstract class BaseController extends BaseComponent { @Resource protected WebSessionSupport webSessionSupport; protected ResponseEntity success() { return success(MapUtils.EMPTY_MAP, HttpStatus.OK); } protected ResponseEntity success(Object key, Object value) { Map map = new HashMap(); map.put(key, value); return new ResponseEntity(map, HttpStatus.OK); } protected ResponseEntity success(Map body) { return new ResponseEntity(body, HttpStatus.OK); } }
JavaScript
UTF-8
4,755
2.78125
3
[ "BSD-3-Clause" ]
permissive
function check_login() { var rule1 = /^\d+$/; if(reg.email.value == "") { alert("You forget to fill account!"); } else if(reg.password.value == "") { alert("You forget to fill password!"); } else if(reg.input_v_num.value == "") { alert("You forget to fill verification code!"); } else if( !rule1.test(reg.input_v_num.value) ) { alert("You are not filling in arabic numbers for verification code!"); } else if (reg.input_v_num.value.length != 4) { alert("The verification code is four digits!"); } else reg.submit(); } function check_update_pro_info() { var rule1 = /^\d+$/; if (reg.ticket.value == "") { alert("You forget to type Ticket number!!"); } else if( !rule1.test(reg.ticket.value) ) { alert("The format of Ticket number is incorrect!"); } else if (reg.ticket.value == 0) { alert("The Ticket number that you typed is 0, please confirm it again!"); } else reg.submit(); } function check_update_pro_info_action() { var rule = /^\w+$/; var rule2 = /^\w+(\d)+$/; var rule3 = /^[A-Za-z]+[0-9]+((\d+)|(\w+))+$/; var rule1 = /^\d+$/; if (reg.P_name.value == "") { alert("You forget to type product name!"); } else if(reg.P_name.value.length > 127) { alert("The product name is too long to submit!"); } else if(reg.P_description.value == "") { alert("You forget to type product description!"); } else if(reg.P_description.value.length > 1249) { alert("The product description is too long to submit!"); } else if(reg.P_amount.value == "") { alert("You forget to type the quantity of product!"); } else if( !rule1.test(reg.P_amount.value) ) { alert("The quantity of product that you typed is not arabic numbers!"); } else if(reg.P_amount.value <= 0) { alert("The quantity of product cannot be filled as 0 or less than 0!"); } else if(reg.P_in_price.value == "") { alert("You forget to type the cost of product!"); } else if( !rule1.test(reg.P_in_price.value) ) { alert("The cost of product that you typed is incorrect!"); } else if(reg.P_in_price.value <= 0 ) { alert("The cost of product cannot be filled as 0 or less than 0!"); } else if(reg.P_out_price.value == "") { alert("You forget to type the price of product!"); } else if( !rule1.test(reg.P_out_price.value) ) { alert("The format of price is incorrect!"); } else if(reg.P_out_price.value <= 0) { alert("The price of product cannot be filled as 0 or less than 0!"); } // reg.P_out_price.value is string, you have to convert it as number. else if( Number(reg.P_out_price.value) < Number(reg.P_in_price.value) ) { alert("The price is less than cost!"); } else if(reg.P_comment.value.length > 1249) { alert("The comment is too long to submit!"); } else reg.submit(); } function check_handle_order() { var rule1 = /^\d+$/; if (reg.P_amount.value == "") { alert("You forget to type quantity that expect to order!"); } else if( !rule1.test(reg.P_amount.value) ) { alert("The format of quantity of product is incorrect!"); } else if(reg.P_amount.value <= 0) { alert("The quantity of product cannot be filled as 0 or less than 0!"); } else if (reg.P_total_price.value == "") { alert("You forget to type the expectation total price!"); } else if( !rule1.test(reg.P_total_price.value) ) { alert("The format of expectation total price is incorrect!"); } else if (reg.P_total_price.value <= 0) { alert("The expectation total price cannot be filled as 0 or less than 0!"); } else if(reg.P_comment.value.length > 1249) { alert("The comment is too long to submit!"); } else if(reg.status.value == "") { alert("You forget to select the status of your order!"); } else reg.submit(); } function check_product_order() { var rule1 = /^\d+$/; if (reg.P_amount.value == "") { alert("You forget to type the quantity of product!!"); } else if( !rule1.test(reg.P_amount.value) ) { alert("The format of quantity of product is incorrect!"); } else if(reg.P_amount.value <= 0) { alert("The quantity of product cannot be filled as 0 or less than 0!"); } else if(reg.P_comment.value.length > 1249) { alert("The comment is too long to submit!"); } else reg.submit(); }
Java
UTF-8
427
3.109375
3
[]
no_license
package com.tim; public class Rectangle extends Shape{ private int width; private int height; //1st constructor public Rectangle(int x, int y){ this(x,y,0,0);//calls the second constructor } //2nd constructor public Rectangle(int x, int y, int width, int height){ super(x, y);//calls the constructor from parent Shape this.width=width; this.height=height; } }
Python
UTF-8
3,801
2.9375
3
[]
no_license
#!/usr/bin/python # -*- coding: UTF-8 -*- # Author : Enming Huang # Date : 1/7/2021 import csv import sys import os.path ## 字符串处理函数 M k m u n p f def handlerstring(str): chengshu = "" if(str[-1]=='M'): chengshu="e6" elif(str[-1]=='k'): chengshu="e3" elif(str[-1]=='m'): chengshu="e-3" elif(str[-1]=='u'): chengshu="e-6" elif(str[-1]=='n'): chengshu="e-9" elif(str[-1]=='p'): chengshu="e-12" elif(str[-1]=='f'): chengshu="e-15" else: return abs(float(str)) #print(str[0:-1]) #print(chengshu) val = abs(float(str[0:-1]+chengshu)) return val def checkdir(pathname,sign): if(sign == 0): #输入路径 if os.path.exists(pathname) is True: return True else: return False else: #输出路径判断 partpath = pathname.split('\\') if(len(partpath)==1): return True else: newpath = "" for i in range(len(partpath)-1): newpath = newpath+partpath[i]+'\\' #print(newpath) if os.path.exists(newpath) is True: return True else: return False def getres(indir,outdir): #提出文件名字 dicname = indir.split('\\') filename=dicname[-1].split('.')[0] #print(filename) ## f=open(indir,mode='r',encoding='utf-8') content=f.readlines() #print(type(content)) x = 0 y = 0 for i in range(len(content)): if content[i] == "x\n": x=i if content[i] == "y\n": y=i break #print(x) #print(y) if abs(y-x)<5: print("input file went wrong!") return ## 下面处理数据 output= [] ## 寻找有多少变量 #row_value = x + 2 valuenames = content[x+2].split(' ')[0:-1] #print(valuenames) new_valuenames = [] for valuename in valuenames: if(valuename != ''): new_valuenames.append(valuename) #print(new_valuenames) if(len(new_valuenames)==0): print("input file went wrong!") return ## j=x+4 while(j!=y): tmp=content[j][2:-1].split(' ') res=[] #j=j+1 for val in tmp: if val !='': res.append(val) #print(val) #print("//////////////") #print(res) #处理字符串 M k m u n p f hang=[] for i in range(len(new_valuenames)): hang.append(handlerstring(res[i])) output.append(hang) #print(hang) j=j+1 #print(len(output)) #print(output) if outdir !="": csvout = open(outdir,'w',newline='') else: newfilename=".\\"+filename+".csv" csvout = open(newfilename,'w',newline='') writer=csv.writer(csvout) writer.writerow(new_valuenames) writer.writerows(output) csvout.close() f.close() if __name__ == "__main__": argint = len(sys.argv) #print(argint) Flag = False if(argint >3): print("input arguments are illegal!") Flag = True if(checkdir(sys.argv[1],0) == False): print("input Hspice file does not exist!") Flag = True ## 用户定义了输出路劲 if(argint == 3) and checkdir(sys.argv[2],1) == False: print("output directory does not exist!") Flag = True if Flag == True: print("something went wrong!") else : if argint == 3: getres(sys.argv[1],sys.argv[2]) else: getres(sys.argv[1],"")
C++
UTF-8
1,996
3.359375
3
[]
no_license
// OOP244 Workshop 8: Virtual Functions and Abstract Base Classes // File: ChequingAccount.cpp // Version: 2.0 // Date: 2017/12/11 // Author: Chris Szalwinski, based on previous work by Heidar Davoudi // Description: // This file implements the ChequingAccount class /////////////////////////////////////////////////// #include <iostream> #include "ChequingAccount.h" #include "SavingsAccount.h" using namespace std; namespace sict { // constructor initializes balance and transaction fee // ChequingAccount::ChequingAccount(double init_balance, double trans_fee, double month_fee) :Account(init_balance) { if (trans_fee > 0) { this->m_transactionFee = trans_fee; } else { this->m_transactionFee = 0.0; } if (month_fee > 0) { this->m_monthlyFee = month_fee; } else { this->m_monthlyFee = 0; } } // credit (add) an amount to the account balance and charge fee // returns bool indicating whether money was credited // bool ChequingAccount::credit(double amount) { if (amount > 0) { Account::credit(amount); Account::debit(this->m_transactionFee); return true; } else { return false; } } // debit (subtract) an amount from the account balance and charge fee // returns bool indicating whether money was debited // bool ChequingAccount::debit(double amount) { if (amount > 0) { Account::debit(amount); Account::debit(this->m_transactionFee); return true; } else { return false; } } // monthEnd debits month end fee // void ChequingAccount::monthEnd() { this->debit(this->m_monthlyFee); } // display inserts account information into ostream os // void ChequingAccount::display(std::ostream& os) const { os.setf(std::ios::fixed); os.precision(2); os << "Account type: Chequing" << std::endl; os << "Balance: $" << this->balance() << std::endl; os << "Per Transaction Fee: " << this->m_transactionFee << std::endl; os << "Monthly Fee: " << this->m_monthlyFee << std::endl; } }
C#
UTF-8
3,734
3.28125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace ADSopdr3 { class Program { static void Main(string[] args) { Console.Out.WriteLine("Welcome to ADS opdr3"); CreateSom(); while (true) // Loop indefinitely { Console.WriteLine("Waiting for user input..."); // Prompt Console.Write(": "); // Prompt string input = Console.ReadLine().Trim(); // Get string from user if (input == "exit" || input == "e") // Check string { break; } else if (input == "skip" || input == "s") { Console.Out.WriteLine("Skip question"); CreateSom(); continue; } else if (input == "eyeofra") { debugmode = !debugmode;//toggle debug mode Console.Out.WriteLine("????????????????????????"); CreateSom(); continue; } if (input.Length == (numbers.Length + operators.Length)) { Infix infix = new Infix(input); String output = infix.toPostfix(); // do the translation if (infix.calculate() == answer) { Console.Out.WriteLine("Given answer is CORRECT"); CreateSom(); } else { Console.Out.WriteLine("Given answer is INCORRECT"); } } } } static bool debugmode = false; static int[] numbers; static char[] operators; static double answer=0; static void CreateSom() { Console.WriteLine("-------------------- (options: skip, exit)"); numbers = new int[] { RandomNumber(1, 9), RandomNumber(1, 9), RandomNumber(1, 9), RandomNumber(1, 9) }; operators = new char[] { '*', '+', '-' }; operators = Shuffle(operators); // Randomize the order string mathexp = numbers[0] + "" + operators[0] + "" + numbers[1] + "" + operators[1] + "" + numbers[2] + operators[2] + "" + numbers[3]; Infix infix = new Infix(mathexp); String postfix = infix.toPostfix(); // do the translation answer = infix.calculate(); // calculate the answer if (debugmode) { Console.WriteLine("Som: " + mathexp + " = " + answer + " postfix(" + postfix + ")"); } //sort the arrays Array.Sort(numbers); Array.Sort(operators); Console.WriteLine("Numbers: " + numbers[0] + " " + numbers[1] + " " + numbers[2] + " " + numbers[3]+"\r\n"+ "Operators: " + operators[0] + " " + operators[1] + " " + operators[2] + "\r\n"+ "Answer: " + answer); } private static Random random = new Random(); public static int RandomNumber(int min, int max) { return random.Next(min, max); } public static char[] Shuffle(char[] input) { List<char> inputList = new List<char>(input); char[] output = new char[input.Length]; int i = 0; while (inputList.Count > 0) { int index = random.Next(inputList.Count); output[i++] = inputList[index]; inputList.RemoveAt(index); } return output; } } }
Java
UTF-8
1,336
2.3125
2
[]
no_license
package com.example.demo; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import sentimentalAnalysis.DriverClass; import tweets.GetTweets; import twitter4j.Status; @Service public class ServiceClass { @Autowired private Jpainterface jpainterface; @PostConstruct public void loadData() { GetTweets tweet = new GetTweets(); DriverClass driver = new DriverClass(); for(Status status :tweet.getTweetMention()) { Bean bean = new Bean(); bean.setUser_name(status.getUser().getScreenName()); bean.setTweet(status.getText()); bean.setResult(driver.sentiment(status.getText())); bean.setTweet_id(Long.toString(status.getId())); jpainterface.save(bean); } // if(.equals("Negative")) // { // tweet.postTweet(status.getId(), status.getUser().getScreenName(),"Negative"); // } // else if(.equals("Positive")) // { // tweet.postTweet(status.getId(), status.getUser().getScreenName(),"Negative"); // } // else // { // tweet.postTweet(status.getId(), status.getUser().getScreenName(),"Negative"); // } // } } }
Markdown
UTF-8
1,056
3.03125
3
[]
no_license
``` cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int arr[100][100]; int check[100][100]; void dfs(int i, int j){ if(i < 0 || j < 0) return; if(check[i][j] || !arr[i][j]) return; check[i][j] = true; for(int x = -1; x <= 1; x++){ for(int y = -1; y <= 1; y++){ dfs(i+x, j+y); } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); while(1){ int w, h, count = 0; cin >> w >> h; if(w == 0 && h == 0) return 0; for(int i = 0; i < 100; i++){ for(int j = 0; j < 100; j++){ arr[i][j] = 0; check[i][j] = 0; } } for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ cin >> arr[i][j]; } } for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ if(!check[i][j] && arr[i][j]){ dfs(i, j); count++; } } } cout << count << '\n'; } return 0; } ``` ### 풀이 - dfs
JavaScript
UTF-8
567
3.3125
3
[]
no_license
'use strict'; module.exports = { lengthOfLastWord, lengthOfLastWord2 }; /** * @param {string} s * @return {number} */ function lengthOfLastWord(s) { const parts = s.split(' '); while (parts.length) { const s = parts.pop(); const l = s.length; if (l) { return l; } } return 0; } /** * @param {string} s * @return {number} */ function lengthOfLastWord2(s) { s = s.trimRight(); let l = s.length; let result = 0; while (l--) { const c = s[l]; if (c === ' ') { break; } result++; } return result; }
JavaScript
UTF-8
868
2.765625
3
[ "MIT" ]
permissive
const players = [ { id: 1, name: 'Colly', timePlayed: 200, points: 54, online: false }, { id: 2, name: 'Peter', timePlayed: 34, points: 34, online: true }, { id: 3, name: 'John', timePlayed: 87, points: 67, online: true }, { id: 4, name: 'Amber', timePlayed: 12, points: 21, online: false }, { id: 5, name: 'Rich', timePlayed: 90, points: 1221, online: false }, { id: 6, name: 'Keylis', timePlayed: 140, points: 22, online: true }, { id: 7, name: 'Mager', timePlayed: 354, points: 124, online: false }, { id: 8, name: 'Nidl', timePlayed: 11, points: 60, online: true }, { id: 9, name: 'Anchor', timePlayed: 78, points: 45, online: false }, ]; const jsonObj = JSON.stringify(players) console.log(jsonObj) console.log(typeof (jsonObj)); const parserJson = JSON.parse(jsonObj) console.log(parserJson) console.log(typeof parserJson)
Java
UHC
754
2.015625
2
[]
no_license
package model; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.GoogleMapDao; import dto.GoogleMapDto; // û public class MapCommand implements Command { @Override public void execute(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub HttpSession session = request.getSession(); String sessionBusinessNumber=(String)session.getAttribute("businessNumber"); String googledata = request.getParameter("googledata"); GoogleMapDao dao=GoogleMapDao.getInstance(); GoogleMapDto dto=new GoogleMapDto(sessionBusinessNumber,googledata); dao.insertMap(dto); } }
C++
UTF-8
1,875
4.0625
4
[]
no_license
#pragma once #include <iostream> using namespace std; struct NodeDoubly { int data; NodeDoubly* prev; NodeDoubly* next; }; class DoublyLinkedList { private: NodeDoubly* head = nullptr; public: void InsertAtIndex(int data, int index) { if (index <= 0) { return; } NodeDoubly* newNode = new NodeDoubly(); newNode->data = data; if (index == 1) { newNode->prev = nullptr; newNode->next = head; if (head != nullptr) { head->prev = newNode; } head = newNode; } else { NodeDoubly* prevPtr = head; // pointer to element after which new node to enter. while (index > 2) { prevPtr = prevPtr->next; index--; } NodeDoubly* nextPtr = prevPtr->next; prevPtr->next = newNode; newNode->prev = prevPtr; if (nextPtr != nullptr) { newNode->next = nextPtr; nextPtr->prev = newNode; } } } void deletAtIndex(int index) { if (index <= 0) { return; } else if (index == 1) { NodeDoubly* temp = head; head = head->next; temp->next = nullptr; if (head != nullptr) { head->prev = nullptr; } delete(temp); } else { NodeDoubly* deletePtr = head; // pointer to element to be deleted. while (index > 1) { deletePtr = deletePtr->next; index--; } NodeDoubly* prevPtr = deletePtr->prev; NodeDoubly* nextPtr = deletePtr->next; prevPtr->next = nextPtr; if (nextPtr != nullptr) { nextPtr->prev = prevPtr; } delete(deletePtr); } } void print() { NodeDoubly* temp = head; while (temp != nullptr) { cout << temp->data << " "; temp = temp->next; } } void printReverese() { if (head == nullptr) { return; } NodeDoubly* temp = head; while (temp->next != nullptr) { temp = temp->next;// reach the end node in linked list } while (temp != nullptr) { cout << temp->data << " "; temp = temp->prev; // print opposite - from end to start } } };
Python
UTF-8
15,107
2.609375
3
[]
no_license
#!/usr/bin/env python """Chapter model tests.""" from unittest import TestCase, main from models import Chapter, connect_db, db, RefImage, Story, User from dbcred import get_database_uri from datetime import date from app import app # == TEST CASE =================================================================================== # class ChapterModelTestCase(TestCase): """Test cases for Chapter ORM.""" @classmethod def setUpClass(cls) -> None: super().setUpClass() connect_db(app) db.drop_all() db.create_all() db.session.add_all(( RefImage(_url=User.DEFAULT_IMAGE_URI), RefImage(_url=Story.DEFAULT_THUMBNAIL_URI) )) db.session.commit() def setUp(self) -> None: super().setUp() for img in RefImage.query.filter(~RefImage.id.in_({1, 2})).all(): db.session.delete(img) Chapter.query.delete() Story.query.delete() User.query.delete() self.testuser = User.register( username = 'testuser', password = 'testuser', email = 'testuser@gmail.com', birthdate = date(1997, 3, 16) ) self.testuser.allow_risque = True self.testuser2 = User.register( username = 'testuser2', password = 'testuser2', email = 'testuser2@gmail.com', birthdate = date(1997, 3, 17) ) self.teststory = Story.new(self.testuser, "test") self.client = app.test_client() def tearDown(self) -> None: super().tearDown() db.session.rollback() def test_new(self) -> None: """Tests the Chapter.new class method.""" # name must be a string with at least one non-whitespace character or null self.assertRaises(ValueError, Chapter.new, self.teststory, 1.5) self.assertRaises(ValueError, Chapter.new, self.teststory, True) self.assertRaises(ValueError, Chapter.new, self.teststory, -5) self.assertRaises(ValueError, Chapter.new, self.teststory, []) self.assertRaises(ValueError, Chapter.new, self.teststory, {}) self.assertRaises(ValueError, Chapter.new, self.teststory, "") self.assertRaises(ValueError, Chapter.new, self.teststory, " ") # text must be a string self.assertRaises(ValueError, Chapter.new, self.teststory, text = None) self.assertRaises(ValueError, Chapter.new, self.teststory, text = 125) self.assertRaises(ValueError, Chapter.new, self.teststory, text = False) self.assertRaises(ValueError, Chapter.new, self.teststory, text = -6.28) self.assertRaises(ValueError, Chapter.new, self.teststory, text = []) self.assertRaises(ValueError, Chapter.new, self.teststory, text = {}) # author_notes must be a string or null self.assertRaises(ValueError, Chapter.new, self.teststory, author_notes = 3.6) self.assertRaises(ValueError, Chapter.new, self.teststory, author_notes = True) self.assertRaises(ValueError, Chapter.new, self.teststory, author_notes = 1) self.assertRaises(ValueError, Chapter.new, self.teststory, author_notes = []) self.assertRaises(ValueError, Chapter.new, self.teststory, author_notes = {}) chapter1 = Chapter.new(self.teststory) self.assertEqual(chapter1.story_id, self.teststory.id) self.assertEqual(chapter1.story, self.teststory) self.assertEqual(chapter1.flags, Chapter.Flags.DEFAULT) self.assertIsNone(chapter1.name) self.assertIsNone(chapter1.author_notes) self.assertEqual(chapter1.text, "") self.assertEqual(chapter1.index, 0) self.assertIsNone(chapter1.number) self.assertEqual(len(chapter1.comments), 0) self.assertEqual(len(chapter1.reports), 0) self.assertEqual(chapter1.posted, chapter1.modified) chapter2 = Chapter.new(self.teststory, " Test Chapter") self.assertEqual(chapter2.story_id, self.teststory.id) self.assertEqual(chapter2.story, self.teststory) self.assertEqual(chapter2.flags, Chapter.Flags.DEFAULT) self.assertEqual(chapter2.name, "Test Chapter") self.assertIsNone(chapter2.author_notes) self.assertEqual(chapter2.text, "") self.assertEqual(chapter2.index, 1) self.assertIsNone(chapter2.number) self.assertEqual(len(chapter2.comments), 0) self.assertEqual(len(chapter2.reports), 0) self.assertEqual(chapter2.posted, chapter2.modified) def test_flags(self) -> None: """Tests Chapter flag getters & setters.""" chapter = Chapter.new(self.teststory, "test") chapter.flags = 0 self.assertFalse(chapter.private) chapter.private = True self.assertTrue(chapter.private) self.assertEqual(chapter.flags, Story.Flags.PRIVATE) def test_visibility(self) -> None: """Tests chapter visibility based on privacy & NSFW flags.""" self.teststory.private = False chapter1 = Chapter.new(self.teststory, "private chapter", "Text") chapter2 = Chapter.new(self.teststory, "visible chapter", "Text") chapter2.private = False # private chapters are visible only to the author self.assertTrue(chapter1.visible(self.testuser)) self.assertFalse(chapter1.visible(self.testuser2)) # public chapters are visible to anyone self.assertTrue(chapter2.visible(self.testuser)) self.assertTrue(chapter2.visible(self.testuser2)) self.teststory.private = True # all chapters are visible only to the author for private stories self.assertTrue(chapter1.visible(self.testuser)) self.assertFalse(chapter1.visible(self.testuser2)) self.assertTrue(chapter2.visible(self.testuser)) self.assertFalse(chapter2.visible(self.testuser2)) def test_index_ordering(self) -> None: """Tests Chapter.index property and how that affects ordering in Story.chapters.""" chapter1 = Chapter.new(self.teststory) chapter2 = Chapter.new(self.teststory) self.assertEqual(self.teststory.chapters[0], chapter1) self.assertEqual(self.teststory.chapters[1], chapter2) chapter1.index = 1 chapter2.index = 0 db.session.commit() self.assertEqual(self.teststory.chapters[0], chapter2) self.assertEqual(self.teststory.chapters[1], chapter1) def test_order_properties(self) -> None: """Tests Chapter.number, Chapter.previous, and Chapter.next properties.""" chapter1 = Chapter.new(self.teststory) chapter2 = Chapter.new(self.teststory) chapter3 = Chapter.new(self.teststory) self.teststory.private = False chapter1.private = False chapter3.private = False self.assertIsNone(chapter1.previous) self.assertEqual(chapter1.next, chapter3) self.assertEqual(chapter1.number, 1) # private chapters aren't given an order, previous, or next; they're used solely # for public chapter navigation self.assertIsNone(chapter2.previous) self.assertIsNone(chapter2.next) self.assertIsNone(chapter2.number) self.assertEqual(chapter3.previous, chapter1) self.assertIsNone(chapter3.next) self.assertEqual(chapter3.number, 2) # private stories don't have a public ordering for chapters self.teststory.private = True self.assertIsNone(chapter1.previous) self.assertIsNone(chapter1.next) self.assertIsNone(chapter1.number) self.assertIsNone(chapter2.previous) self.assertIsNone(chapter2.next) self.assertIsNone(chapter2.number) self.assertIsNone(chapter3.previous) self.assertIsNone(chapter3.next) self.assertIsNone(chapter3.number) def test_update(self) -> None: """Tests the Chapter.update method.""" chapter = Chapter.new(self.teststory, None, "Text") chapter2 = Chapter.new(self.teststory, None, "Text") chapter3 = Chapter.new(self.teststory, None, "Text") chapter.private = False chapter2.private = False chapter3.private = False self.assertEqual(len(chapter.update()), 0) self.assertIsNone(chapter.name) self.assertEqual(chapter.text, "Text") self.assertEqual(chapter.index, 0) self.assertFalse(chapter.private) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(name=True)), 1) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(name=-5)), 1) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(name=123.456)), 1) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(name=[])), 1) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(name={ 'a': True, 'b': True })), 1) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(name="abc")), 0) self.assertEqual(chapter.name, "abc") self.assertEqual(len(chapter.update(name=" abc")), 0) self.assertEqual(chapter.name, "abc") self.assertEqual(len(chapter.update(name="")), 0) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(name=" ")), 0) self.assertIsNone(chapter.name) self.assertEqual(len(chapter.update(author_notes=False)), 1) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(author_notes=2)), 1) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(author_notes=3.6)), 1) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(author_notes=[])), 1) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(author_notes={})), 1) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(author_notes="test notes")), 0) self.assertEqual(chapter.author_notes, "test notes") self.assertEqual(len(chapter.update(author_notes="more test notes ")), 0) self.assertEqual(chapter.author_notes, "more test notes") self.assertEqual(len(chapter.update(author_notes="")), 0) self.assertIsNone(chapter.author_notes) self.assertEqual(len(chapter.update(text=True)), 1) self.assertEqual(chapter.text, "Text") self.assertEqual(len(chapter.update(text=17)), 1) self.assertEqual(chapter.text, "Text") self.assertEqual(len(chapter.update(text=-5.5)), 1) self.assertEqual(chapter.text, "Text") self.assertEqual(len(chapter.update(text=["hi", 'there'])), 1) self.assertEqual(chapter.text, "Text") self.assertEqual(len(chapter.update(text={"go": 'away'})), 1) self.assertEqual(chapter.text, "Text") self.assertEqual(len(chapter.update(text="# hello\nlolololo")), 0) self.assertEqual(chapter.text, "# hello\nlolololo") self.assertEqual(len(chapter.update(text="abc abc")), 0) self.assertEqual(chapter.text, "abc abc") self.assertEqual(len(chapter.update(text="\n\nabc\n\nabc\n\n")), 0) self.assertEqual(chapter.text, "abc\n\nabc") # chapter with no visible text must be private self.assertEqual(len(chapter.update(text="")), 0) self.assertEqual(chapter.text, "") self.assertTrue(chapter.private) self.assertEqual(len(chapter.update(text=" # \n> > - []() ")), 0) self.assertEqual(chapter.text, "# \n> > - []()") chapter.update(private = False) self.assertTrue(chapter.private) self.assertEqual(len(chapter.update(text="Text")), 0) self.assertEqual(chapter.text, "Text") self.assertTrue(chapter.private) chapter.update(private = False) self.assertFalse(chapter.private) self.assertEqual(len(chapter.update(index=False)), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index=1.5)), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index="hello world")), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index=[0, 1, 2, 'test'])), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index={})), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index=-1)), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index=3)), 1) self.assertEqual(chapter.index, 0) self.assertEqual(len(chapter.update(index=1)), 0) self.assertEqual(chapter.index, 1) self.assertEqual(chapter2.index, 0) self.assertEqual(chapter3.index, 2) self.assertEqual(len(chapter.update(index=2)), 0) self.assertEqual(chapter.index, 2) self.assertEqual(chapter2.index, 0) self.assertEqual(chapter3.index, 1) self.assertEqual(len(chapter.update(index=0)), 0) self.assertEqual(chapter.index, 0) self.assertEqual(chapter2.index, 1) self.assertEqual(chapter3.index, 2) self.assertEqual(len(chapter.update(private=0)), 1) self.assertFalse(chapter.private) self.assertEqual(len(chapter.update(private=1.5)), 1) self.assertFalse(chapter.private) self.assertEqual(len(chapter.update(private="")), 1) self.assertFalse(chapter.private) self.assertEqual(len(chapter.update(private=[55])), 1) self.assertFalse(chapter.private) self.assertEqual(len(chapter.update(private={'str': 'abc'})), 1) self.assertFalse(chapter.private) self.assertEqual(len(chapter.update(private=True)), 0) self.assertTrue(chapter.private) self.assertEqual(len(chapter.update(private=False)), 0) self.assertFalse(chapter.private) # chapter with no text must be private chapter.update(text="") self.assertEqual(len(chapter.update(private=False)), 0) self.assertTrue(chapter.private) self.assertEqual(len(chapter.update(private=True)), 0) self.assertTrue(chapter.private) if __name__ == "__main__": from sys import argv app.config['SQLALCHEMY_DATABASE_URI'] = get_database_uri( "fictionsource-test", cred_file = ".dbtestcred", save = False ) if app.config['SQLALCHEMY_DATABASE_URI'] is None: app.config['SQLALCHEMY_DATABASE_URI'] = get_database_uri( "fictionsource-test", cred_file = None, save = False ) app.config['SQLALCHEMY_ECHO'] = False if len(argv) > 1: app.config['SQLALCHEMY_DATABASE_URI'] = get_database_uri( "fictionsource-test", argv[1], argv[2] if len(argv) > 2 else None, cred_file = ".dbtestcred" ) main()
Python
UTF-8
1,230
4.3125
4
[]
no_license
print('Задача 7. Великий и могучий') # Паоло изучает русский язык: занимается по учебникам, читает книги, слушает музыку. # Особенно Паоло понравилась книга “Преступление и наказание”. # И ему стало интересно, # какое можно найти самое длинное слово в этой книге, чтобы потом сравнить его с аналогом на своём языке. # # Напишите программу, # которая получает на вход текст и находит длину самого длинного слова в нём. # Слова в тексте разделяются одним пробелом. # # Пример: # Введите текст: Меня зовут Петр # Длина самого длинного слова: 5 print('Введите текст: ', end='') text = input() symbol = 0 word_max = 0 for i in text: if i != ' ': symbol += 1 else: symbol = 0 if symbol > word_max: word_max = symbol print('\nДлина самого длинного слова: ', word_max)
Java
UTF-8
1,797
1.96875
2
[]
no_license
package com.resolve.qa.framework.numa.testsuite.impl; public class CheckType extends JsonAbstract{ public static enum SOURCE_TYPE { PLAIN, REFERENCE, JSON } public static enum COMPARE_METHOD { EQUAL, LESS, LESSOREQUAL, GREATER, GREATEROREQUAL, CONTAIN, NOCONTAIN, INCREASEEQUAL, NOTEMPTY, ISEMPLTY, SIZEEQUAL } public static enum TARGET_TYPE { PLAIN, REFERENCE, JSON } private SOURCE_TYPE sourceType; private String sourceKey; private COMPARE_METHOD compareMethod; private TARGET_TYPE targetType; private String targetKey; public CheckType() { super(); } public CheckType(SOURCE_TYPE sourceType, String sourceKey, COMPARE_METHOD compareMethod, TARGET_TYPE targetType, String targetKey) { super(); this.sourceType = sourceType; this.sourceKey = sourceKey; this.compareMethod = compareMethod; this.targetType = targetType; this.targetKey = targetKey; } public SOURCE_TYPE getSourceType() { return sourceType; } public void setSourceType(SOURCE_TYPE sourceType) { this.sourceType = sourceType; } public String getSourceKey() { return sourceKey; } public void setSourceKey(String sourceKey) { this.sourceKey = sourceKey; } public COMPARE_METHOD getCompareMethod() { return compareMethod; } public void setCompareMethod(COMPARE_METHOD compareMethod) { this.compareMethod = compareMethod; } public TARGET_TYPE getTargetType() { return targetType; } public void setTargetType(TARGET_TYPE targetType) { this.targetType = targetType; } public String getTargetKey() { return targetKey; } public void setTargetKey(String targetKey) { this.targetKey = targetKey; } }
Java
UTF-8
3,200
4.15625
4
[]
no_license
package com.atguigu.thread.communicate; /* * 线程通信问题: * 生产者与消费者问题: * 当一个或一些线程负责“生产”数据,另一个或一些线程负责“消耗、消费”数据,这样的情况,就称为生产者与消费者问题。 * 生产者与消费者要使用同一个“数据缓冲区”,并且这个数据缓冲区有“固定大小”,当数据缓冲区“空”的时候,消费者线程 * 应该停下来,当生产者线程生产了数据之后,通知/唤醒消费者线程;当数据缓冲区“满”的时候,生产者线程应该停下来, * 当消费者线程消耗了数据之后,通知/唤醒生产者线程继续生产。 * * 问题:(1) 同一个“数据缓冲区”-->线程安全问题 * (2)多个线程协作/通信,需要用到wait(),notify()/notifyAll() * * 例子: * 厨师(生产者)和服务员(消费者),之间一个工作台(数据缓冲区),当厨师做完菜,放到台上,服务员可以从台上取走给客户。 * * 1、wait()和notify()方法由谁来调用? * 你的锁对象 * * 如果你用了非锁对象调用wait和notify,那么会报java.lang.IllegalMonitorStateException * * 2、 wait()和notify()方法在哪里声明的呢? * java.lang.Object * * 因为它必须有锁对象调用,而锁对象的类型是任意的引用数据类型。 * * */ public class TestCommunicate { public static void main(String[] args) { Workbench w = new Workbench();//工作台 Cook cook = new Cook(w); Waiter waiter = new Waiter(w); cook.start(); waiter.start(); } } class Workbench{ private static final int MAX_VALUE = 10;//最多能放10盘菜 private int num ;//台上菜的数量 //由厨师调用 //锁对象:this,因为非静态同步方法的锁对象一定是this public synchronized void put() { if(num >= MAX_VALUE){//工作台满的时候,厨师线程停下来等待 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } num++; System.out.println("厨师做了一份菜,现在工作台上有:" + num); //通知服务员线程,可以取菜了 this.notify(); } //由服务员调用 public synchronized void take(){ if(num <= 0){//当工作台空的时候,服务员线程停下来 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } num--; System.out.println("服务员取走了一份菜,现在工作台上有:" + num); //通知厨师可以继续做菜了 this.notify(); } } class Cook extends Thread{ private Workbench work; public Cook(Workbench work) { super(); this.work = work; } public void run(){ while(true){ work.put(); } } } class Waiter extends Thread{ private Workbench work; public Waiter(Workbench work) { super(); this.work = work; } public void run(){ while(true){ work.take(); } } }
C++
UTF-8
626
2.765625
3
[]
no_license
#include "main.ih" namespace { size_t g_lo; size_t g_hi; ostream null(0); } ostream &msg(size_t level) { return g_lo <= level && level <= g_hi ? cerr : null; } int main(int argc, char **argv) try { if (argc > 1) { g_lo = A2x(argv[1]); g_hi = g_lo; } if (argc > 2) g_hi = A2x(argv[2]); cout << "usage: read stdin. use numeric argument: higher = more info\n" " two numeric args: all msg in 1st-2nd levels are shown\n" "\n"; Scanner scanner; while (scanner.lex() != -1) ; } catch (...) { return 1; }
Python
UTF-8
898
3.296875
3
[ "MIT", "Apache-2.0" ]
permissive
import api class InvalidPreferenceItem(api.APIError): """Raised if an invalid preference item is used.""" def __init__(self, item): """Constructor""" super(InvalidPreferenceItem, self).__init__( "Invalid preference item: %r" % item) class Preference(object): def __init__(self, item, value, user, repository): self.__item = item self.__value = value self.__user = user self.__repository = repository def __bool__(self): return bool(self.__value) def __int__(self): return self.__value def __str__(self): return self.__value @property def item(self): return self.__item @property def value(self): return self.__value @property def user(self): return self.__user @property def repository(self): return self.__repository
JavaScript
UTF-8
2,721
2.78125
3
[]
no_license
import React, { useState } from 'react' import { AppHeader } from '../AppHeader' import { SearchPanel } from '../SearchPanel' import { TodoList } from '../TodoList' import { ItemStatusFilter } from '../ItemStatusFilter' import { ItemAddForm } from '../ItemAddForm' import './app.css' function App() { const initialState = [ createTodoItem('Drink Coffee'), createTodoItem('Make Awesome App'), createTodoItem('Have a lunch'), ] const [todoData, setTodoData] = useState(initialState) const [term, setTerm] = useState('') const [filterState, setFilterState] = useState('all') function createTodoItem(label) { return { label, important: false, done: false, id: label + Math.random(), } } const deleteItem = id => { const idx = todoData.findIndex(el => el.id === id) const newArray = [...todoData.slice(0, idx), ...todoData.slice(idx + 1)] setTodoData(newArray) } const addItem = text => { if (!text) return const newItem = createTodoItem(text) const newArr = [...todoData, newItem] setTodoData(newArr) } function toggleProperty(arr, id, propName) { const idx = arr.findIndex(el => el.id === id) const oldItem = arr[idx] const newItem = { ...oldItem, [propName]: !oldItem[propName] } return [...arr.slice(0, idx), newItem, ...arr.slice(idx + 1)] } const onToggleDone = id => { setTodoData(toggleProperty(todoData, id, 'done')) } const onToggleImportant = id => { setTodoData(toggleProperty(todoData, id, 'important')) } function search(items, word) { if (!word) return items return items.filter( item => item.label.toLowerCase().indexOf(word.toLowerCase()) > -1, ) } function filter(items) { switch (filterState) { case 'all': return items case 'active': return items.filter(item => !item.done) case 'done': return items.filter(item => item.done) default: return items } } const doneCount = todoData.filter(el => el.done).length const todoCount = todoData.length - doneCount const visibleItems = filter(search(todoData, term)) return ( <div className="todo-app"> <AppHeader toDo={todoCount} done={doneCount} /> <div className="top-panel d-flex"> <SearchPanel onSearchChange={setTerm} /> <ItemStatusFilter filterState={filterState} onFilterChange={setFilterState} /> </div> <TodoList todos={visibleItems} onDeleted={deleteItem} onToggleImportant={onToggleImportant} onToggleDone={onToggleDone} /> <ItemAddForm onItemAdd={addItem} /> </div> ) } export { App }
Markdown
UTF-8
439
2.625
3
[]
no_license
# median-age Countries by Median Age :older_man: :woman: :boy: :baby: - extracted from https://en.wikipedia.org/wiki/List_of_countries_by_median_age ## Installation `npm i median-age` ## Usage ### Module ```js import { data } from "median-age"; console.log(data); ``` ### CLI ```shell npx median-age ``` ## CDN `median-age` can also be accessed using CDN `curl https://cdn.jsdelivr.net/gh/maddhruv/median-age@latest/data.json`
Java
UTF-8
2,963
2.984375
3
[]
no_license
package com.barrios_irabedra.obligatorio.dominio; // @author Juan Barrios, Juan Irabedra import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import javafx.beans.property.SimpleIntegerProperty; public abstract class Pregunta { private String pregunta; private int tiempo; private HashMap<String, Boolean> respuestas; private SimpleIntegerProperty segundosRestantes; private TimerPregunta timerPregunta; //Acceso y modificacion public String getPregunta() { return pregunta; } public void setPregunta(String pregunta) { this.pregunta = pregunta; } public int getTiempo() { return tiempo; } public void setTiempo(int tiempo) { this.tiempo = tiempo; } public SimpleIntegerProperty getSegundosRestantes() { return segundosRestantes; } public void setSegundosRestantes(SimpleIntegerProperty segundosRestantes) { this.segundosRestantes = segundosRestantes; } public void disminuirTiempoRestante() { Platform.runLater(() -> { this.getSegundosRestantes().set( getSegundosRestantes().subtract(1).get()); }); } public void agregarRespuesta(String respuesta, Boolean valorVerdad) { this.respuestas.put(respuesta, valorVerdad); } public String getRespuestas() { return this.respuestas.toString(); } public HashMap<String, Boolean> getMapaRespuestas() { return this.respuestas; } //Constructor con params public Pregunta(String nombre, int tiempo, HashMap<String, Boolean> respuestas) { this.pregunta = nombre; this.tiempo = tiempo; this.respuestas = respuestas; this.segundosRestantes = new SimpleIntegerProperty(tiempo); this.timerPregunta = new TimerPregunta(); } //Constructor sin params. public Pregunta() { this.tiempo = 30; this.respuestas = new HashMap<>(); this.segundosRestantes = new SimpleIntegerProperty(this.tiempo); this.timerPregunta = new TimerPregunta(); } @Override public String toString() { return this.getPregunta() + ". \n" + "Tienes " + this.getTiempo() + " segundos para responder. \n" + "Y sus respuestas eran " + this.getRespuestas(); } private class TimerPregunta extends TimerTask { @Override public void run() { if (getSegundosRestantes().get() > 0) { disminuirTiempoRestante(); } else { stop(); } } } public void stop() { this.timerPregunta.cancel(); } public void start() { Timer timer = new Timer(); timer.scheduleAtFixedRate(timerPregunta, 0, 1000); } }
JavaScript
UTF-8
1,974
3.0625
3
[]
no_license
var clock=null; var speed=4; $(document).ready(function() { init(); }); function init() { for (var i = 0; i < 4; i++) { createRow(); } $('#main').click(function(event){ judge(event); }); clock=setInterval(move,30); } function createCell(){//创建随机className数组 var temp=['cell','cell','cell','cell']; var i=Math.floor(Math.random()*4); temp[i]='cell black'; return temp; } function createRow(){ var row=createDiv('row'); var arr=createCell(); for (var i = 0; i < 4; i++) {//创建cell,并加入到行里 row.append(createDiv(arr[i])); } //行加入到con中 if ($('#con').children()==null) { $('#con').append(row); }else{ $('#con').prepend(row); } } function createDiv(className){ return $('<div></div>').addClass(className) } function deleteRow(){ if ($('#con').children().length==6) { $('#con').children().last().remove();//删除最后一个子元素 } } function move(){ var top=parseInt($('#con').css('top'));//top要变为数值才能进行加减运算 if (top+speed>0) { top=0; }else{ top+=speed; } $('#con').css('top',top+'px'); if (top==0) { createRow(); $('#con').css('top','-100px'); deleteRow(); }else if(top==(-100+speed)){ var rows=$('#con').children(); if((rows.length>=5)&&(rows[rows.length-1].pass!==1)){ fail(); } } } function judge(ev){//判断是否点击黑色 if (ev.target.className.indexOf('black')==-1) { fail(); }else{//是黑色则变白 并且增加score,标记点击改行 ev.target.className='cell'; ev.target.parentNode.pass=1; score(); } } function fail(){ clearInterval(clock); confirm('Your score is:'+parseInt($('#score').text())); clear(); } function clear(){ speed=4; $('#con').empty(); $('#score').empty(); } function score(){ var newScore=parseInt($('#score').text())+1;//text()获取内部文本内容 console.log(newScore); $('#score').text(newScore); if(newScore%10==0){ speed+=2; if (speed==20) { alert('niubility!'); } } }
Java
UTF-8
6,002
2.734375
3
[]
no_license
package kr.ac.hanyang.tosca2camp.definitiontypes; import java.util.*; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import kr.ac.hanyang.tosca2camp.definitiontypes.PropertyDef.Builder; public class CapabilityDef implements Cloneable{ private String name; // for normative this should be the short name private String type; private String derived_from; private DataTypeDef version; private String description; // description are treated as their own type but for now they will be string private Map<String, PropertyDef> properties; private Map<String, AttributeDef> attributes; private List<String> valid_source_types; public static class Builder { private String name; private String type; private String derived_from; private DataTypeDef version; private String description; // description are treated as their own type but for now they will be string private Map<String, PropertyDef> properties = new LinkedHashMap<String, PropertyDef>(); private Map<String, AttributeDef> attributes = new LinkedHashMap<String, AttributeDef>(); private List<String> valid_source_types = new ArrayList<String>(); public Builder(){ } public Builder(String name, String type){ this.name = name; this.type = type; } public Builder(String type){ this.name = ""; this.type = type; } public Builder name(String name){ this.name = name; return this; } public Builder type(String type){ this.type = type; return this; } public Builder derived_from(String derived_from){ this.derived_from = derived_from; return this; } public Builder version(DataTypeDef version){ this.version = version; return this; } public Builder description(String description){ this.description = description; return this; } public Builder addProperty(PropertyDef property){ this.properties.put(property.getName(),property); return this; } public Builder addAttribute(AttributeDef attribute){ this.attributes.put(attribute.getName(),attribute); return this; } public Builder addValid_source_types(String valid_source_type){ this.valid_source_types.add(valid_source_type); return this; } public CapabilityDef build(){ return new CapabilityDef(this); } } public Object clone(){ try{ CapabilityDef.Builder toReturn = ((CapabilityDef) super.clone()).getBuilder(); if (derived_from != null) toReturn.derived_from = new String(derived_from); toReturn.properties = new LinkedHashMap<String, PropertyDef>(); if (version != null)toReturn.version = (DataTypeDef) version.clone(); for(String pDefName:properties.keySet()){ PropertyDef pDef = properties.get(pDefName); toReturn.properties.put(pDefName, (PropertyDef)pDef.clone()); //make sure pDef can create a copy } toReturn.attributes = new LinkedHashMap<String, AttributeDef>(); for(String aDefName:attributes.keySet()){ AttributeDef aDef = attributes.get(aDefName); toReturn.attributes.put(aDefName, (AttributeDef)aDef.clone()); //make sure aDef can create a copy } toReturn.valid_source_types = new ArrayList<String>(); for(String vSource: valid_source_types) toReturn.valid_source_types.add(vSource); return toReturn.build(); }catch(CloneNotSupportedException e){ return null; } } private CapabilityDef(Builder builder){ this.name = builder.name; this.type = builder.type; this.derived_from = builder.derived_from; this.version = builder.version; this.description = builder.description; this.properties = builder.properties; this.attributes = builder.attributes; this.valid_source_types = builder.valid_source_types; } public Builder getBuilder(){ Builder builder = new Builder(); builder.type = this.type; builder.name = this.name; builder.derived_from = this.derived_from; builder.version = this.version; builder.description = this.description; builder.properties = this.properties; builder.attributes = this.attributes; builder.valid_source_types = this.valid_source_types; return builder; } public String getName() {return name;} public String getType() {return type;} public String getDerived_from() {return derived_from;} public String getDescription() {return description;} public List<PropertyDef> getProperties() { List toReturn = new ArrayList<PropertyDef>(); for(PropertyDef property: properties.values()){ toReturn.add(property); } return toReturn; } public List<AttributeDef> getAttributes() { List toReturn = new ArrayList<AttributeDef>(); for(AttributeDef attribute: attributes.values()){ toReturn.add(attribute); } return toReturn; } public List<String> getValid_source_types() {return valid_source_types;} public PropertyDef getProperty(String propName){ return properties.get(propName); } public void setPropertyValue(String name, DataTypeDef value){ PropertyDef toSet = properties.get(name); toSet.setPropertyValue(value); } public void setAttributeValue(String name, DataTypeDef value){ AttributeDef toSet = attributes.get(name); toSet.setAttributeValue(value); } public AttributeDef getAttribute(String attributeName){ return attributes.get(attributeName); } private int tabNum; public void setTabNum(int tabs){ tabNum = tabs;} public String toString(){ String padding = new String(new char[tabNum]).replace("\0", "\t"); ToStringBuilder builder = new ToStringBuilder(this,ToStringStyle.SIMPLE_STYLE) .appendToString("\n"+padding+"name: "+name) .appendToString("\n"+padding+"type: "+type) .appendToString("\n"+padding+"derived_from: "+derived_from) .append("\n"+padding+"properties: "); for(PropertyDef property: properties.values()){ property.setTabNum(tabNum+1); builder.appendToString(property.toString()); } return builder.toString(); } }
Java
UTF-8
587
1.890625
2
[]
no_license
package com.boot.aoplistener; import com.boot.module.form.service.IAm01FormMetaService; import com.boot.module.sys.SpringBeanTools; /** * @author h3dwy * @Description * @CreateDate 创建时间:2018-10-18 11:28 * @ModifiedBy * @ModifiedDate */ public class TestEventListener implements IEventListener { @Override public boolean eventExecute() { IAm01FormMetaService service = (IAm01FormMetaService) SpringBeanTools.getBean("am01FormMetaService"); System.out.println("--------------================" + (null == service)); return false; } }
TypeScript
UTF-8
4,432
2.921875
3
[ "MIT" ]
permissive
declare module socket.io.client { /** * Options: * - reconnection whether to reconnect automatically (true) * - reconnectionDelay how long to wait before attempting a new reconnection (1000) * - reconnectionDelayMax maximum amount of time to wait between reconnections (5000). * Each attempt increases the reconnection by the amount specified by reconnectionDelay. * - timeout connection timeout before a connect_error and connect_timeout events are emitted (20000) */ interface Options { reconnection?: boolean; reconnectionDelay?:number; reconnectionDelayMax?:number; timeout?:number; } interface SocketStatic { (): Socket; (url?:string, opts?:Options): Socket; Socket(): Socket; Manager: Manager; /** * Protocol version. * */ protocol:string; } interface Socket { /** * `Socket` constructor. * */ (io:any, nsp:number):Socket; /** * Sends a `message` event. * * @return {Socket} self */ send():Socket; /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @param {String} event name * @return {Socket} self */ emit(event:string):Socket; /** * Disconnects the socket manually. * * @return {Socket} self */ close():Socket; disconnect():Socket; } interface Manager { /** * `Manager` constructor. * * @param {String} engine instance or engine uri/opts * @param {Object} options */ (uri?:string, opts?:Options):Manager; /** * Sets the `reconnection` config. * * @param {Boolean} true/false if it should automatically reconnect * @return {Manager} self */ reconnection(value:Boolean):Manager; /** * Gets the `reconnection` config. * * @return {Boolean} value */ reconnection():boolean; /** * Sets the reconnection attempts config. * * @param {Number} max reconnection attempts before giving up * @return {Manager} self */ reconnectionAttempts(value:number):Manager; /** * Gets the reconnection attempts config. * * @param {Number} max reconnection attempts before giving up * @return {Number} value */ reconnectionAttempts():number; /** * Sets the delay between reconnections. * * @param {Number} delay * @return {Manager} self */ reconnectionDelay(value:number):Manager; /** * Gets the delay between reconnections. * * @return {Number} value */ reconnectionDelay():number; /** * Sets the maximum delay between reconnections. * * @param {Number} delay * @return {Manager} self */ reconnectionDelayMax(value:number):Manager; /** * Gets the maximum delay between reconnections. * * @return {Number} value */ reconnectionDelayMax():number; /** * Sets the connection timeout. `false` to disable * * @param {Number | Boolean} delay * @return {Manager} self */ timeout(value:number): Manager; timeout(value:boolean): Manager; /** * Gets the connection timeout. * * @return {Number | Boolean} value `false` for disabled */ timeout<T extends number>(): T; timeout<T extends boolean>(): T; /** * Sets the current transport `socket`. * * @param {Function} optional, callback * @return {Manager} self */ connect(callback?:Function):Manager; open(callback?:Function):Manager; /** * Creates a new socket for the given `nsp`. * * @return {Socket} */ socket(nsp:number):Socket; } } declare module "socket.io-client" { var io:socket.io.client.SocketStatic; export = io; } declare var io:socket.io.client.SocketStatic;
Java
UTF-8
1,927
3.5
4
[]
no_license
/* * Copyright (c) 2020 NeuLion, Inc. All Rights Reserved. */ package k.th.smallest.bst; import binary.TreeNode; import java.util.Deque; import java.util.LinkedList; /** * Solution. * * @author <A HREF="mailto:eric.ding@neulion.com.cn">Eric.Ding</A> * @version 1.0, $Revision: 0$, $Date: 2020/10/29$ * @since 1.0 */ public class Solution { public int kthSmallest(TreeNode root, int k) { Deque<TreeNode> stack = new LinkedList<>(); while (true) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if (--k == 0) break; root = root.right; } return root.val; } public static TreeNode buildBst(int[] values) { TreeNode root = new TreeNode(values[0]); for (int i = 1; i < values.length; i++) { TreeNode newNode = new TreeNode(values[i]); TreeNode cur = root; while (cur != newNode) { if (newNode.val < cur.val) { if (cur.left == null) { cur.left = newNode; } cur = cur.left; } else { if (cur.right == null) { cur.right = newNode; } cur = cur.right; } } } return root; } public static void main(String[] args) { int[] input1 = new int[] { 3, 1, 4, 2 }; int[] input2 = new int[] { 5, 3, 6, 2, 4, 1 }; Solution solution = new Solution(); System.out.println(solution.kthSmallest(buildBst(input1), 1)); System.out.println(solution.kthSmallest(buildBst(input2), 3)); } }
Java
UTF-8
1,153
2.296875
2
[]
no_license
package ua.itea.model.message; import java.io.Serializable; import java.util.List; import ua.itea.model.DataFileAnswer; import ua.itea.model.Downloader; import ua.itea.model.Channel; public class DataAnswerMessage extends DataMessage implements Serializable { private static final long serialVersionUID = -6359875826557787382L; private List<DataFileAnswer> answers; public DataAnswerMessage() { /* empty */ } public DataAnswerMessage(List<DataFileAnswer> answers) { this.answers = answers; } public List<DataFileAnswer> getList() { return answers; } public void setList(List<DataFileAnswer> answers) { this.answers = answers; } public boolean isEmpty() { return answers == null || answers.isEmpty(); } public int size() { return isEmpty() ? 0 : answers.size(); } @Override public void execute(Channel loader) { Downloader downloader = loader.getDownloader(); DataRequestMessage dataRequest = new DataRequestMessage(); /* TODO: parallelize A */ dataRequest.setList(downloader.createRequest(answers)); getMessenger().send(dataRequest); /* TODO: parallelize B */ downloader.save(answers); } }
PHP
UTF-8
2,673
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Middleware; use Closure; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; use Response; use \Illuminate\Http\Response as Res; use Illuminate\Support\Facades\Auth; class SpatieJwtAuthentication extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next, $role, $permission) { if (!$token = $this->auth->setRequest($request)->getToken()) { return Response::json([ 'status' => 'error', 'status_code' => Res::HTTP_BAD_REQUEST, 'message' => 'Token Not Provided!', ]); } try { $user = $this->auth->authenticate($token); } catch (TokenExpiredException $e) { return Response::json([ 'status' => 'error', 'status_code' => Res::HTTP_BAD_REQUEST, 'message' => 'Token Expired!', ]); } catch (JWTException $e) { return Response::json([ 'status' => 'error', 'status_code' => Res::HTTP_BAD_REQUEST, 'message' => 'Token Expired!', ]); } if (!$user) { return Response::json([ 'status' => 'error', 'status_code' => Res::HTTP_NOT_FOUND, 'message' => 'User Not Gound!', ]); } $permissions = is_array($permission) ? $permission : explode('|', $permission); $roles = is_array($role) ? $role : explode('|', $role); if (!Auth::user()->hasPermissionTo($permission)) { return Response::json([ 'status' => 'error', 'status_code' => Res::HTTP_UNAUTHORIZED, 'message' => 'Unauthorized Access!', ]); } //$role = auth()->user()->getRoleNames(); //\Log::info(app('auth')->user()->can($permission)); //\Log::info(Auth::user()->hasPermissionTo($permission)); //\Log::info(Auth::user()->hasPermissionTo($permission)); //return $role->hasPermissionTo($permission); //\Log::info($roles); //\Log::info($permissions); //\Log::info(app('auth')->user()); //\Log::info(auth()->user()->getRoleNames()); return $next($request); } }
Java
UTF-8
1,389
2.328125
2
[]
no_license
package com.sychev.user.entity; import com.sychev.user.model.TokenType; import javax.persistence.*; import java.io.Serializable; import java.util.UUID; @Entity @Table(name = "tokens") public class Token implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private UUID serviceUuid; @Column private String value; @Column private Long dttmCreate; @Enumerated(EnumType.STRING) @Column private TokenType tokenType; @ManyToOne @JoinColumn(name = "uuid", nullable = false) private User user; public Token() { } public UUID getServiceUuid() { return serviceUuid; } public void setServiceUuid(UUID serviceUuid) { this.serviceUuid = serviceUuid; } public Enum getTokenType() { return tokenType; } public void setTokenType(TokenType tokenType) { this.tokenType = tokenType; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Long getDttmCreate() { return dttmCreate; } public void setDttmCreate(Long dttmCreate) { this.dttmCreate = dttmCreate; } }